id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6521189 | <reponame>him4318/Transformer-ocr
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 16:15:54 2020
@author: himanshu.chaudhary
"""
from torch import nn
import torch
from torch.autograd import Variable
import numpy as np
import time
class LabelSmoothing(nn.Module):
"Implement label smoothing."
def __init_... | StarcoderdataPython |
6464178 | # AUTOGENERATED! DO NOT EDIT! File to edit: 00_person.ipynb (unless otherwise specified).
__all__ = ['Person']
# Cell
class Person:
def __init__(self, name:str = 'Tyler'):
self.name = name
def __str__(self):
"""String representation of the person"""
return f"This person's name is: {s... | StarcoderdataPython |
8160859 | <filename>src/sprite/sprite_cat.py
from enum import Enum
from PyQt6 import QtGui
from sprite.sprite import Sprite
from sprite.sprite import SpritePos as Pos
import os
import random
class Cat(Sprite):
ANIMATION_FRAME_PATH = 'assets\\cat\\animation_frames\\'
SPRITE_SIZE = Pos(100, 100)
class States(Enum... | StarcoderdataPython |
5019620 | #!/usr/bin/env python
# coding: utf-8
import os
import csv
import re
def get_reason_content_simple(verdict, date, file_num):
try:
start_index = verdict.index('理由') + 5
end_index = re.search("^\S、\S*(?:上訴|原告).{0,15}(?:主張|意旨)\S*(?:︰|:)", verdict, re.M).start() - 3
content = verdic... | StarcoderdataPython |
11316049 | import pathlib
import panflute
import pandocacro
def test_pandocacro() -> None:
"""Check the prepare and finalize properly add and remove the acronyms
"""
root = pathlib.Path(__file__).parent
text = "\n".join(
[(root / f).open().read() for f in ("metadata.yaml", "example.md")]
)
doc ... | StarcoderdataPython |
264947 | def check_user(user, session_type=False):
frontend.page(
"dashboard",
expect={
"script_user": testing.expect.script_user(user)
})
if session_type is False:
if user.id is None:
# Anonymous user.
session_type = None
else:
ses... | StarcoderdataPython |
4841710 | <gh_stars>1-10
from collections import Counter
import logging
import numpy
import os
from multiprocessing import Process, Manager, Value, Semaphore
from random import random
from keras.models import Sequential, load_model
import pysam
from Bio import pairwise2
from Bio.Seq import Seq
from Bio import SeqIO
from advntr... | StarcoderdataPython |
11241916 | #encoding=utf-8
from __future__ import unicode_literals
import sys
sys.path.append("../")
import codecs
import jieba
import jieba.posseg
import jieba.analyse
import pickle
# extract keys dict
def create_keys_dict():
all_keys = {'女装'}
with codecs.open(r'C:\Users\jmlu\Desktop\Kobe\KOBE\data\origin_data\alldata.... | StarcoderdataPython |
1692210 | """
See https://en.wikipedia.org/wiki/Travelling_salesman_problem
Examples of Execution:
python3 TravelingSalesman.py -data=TravelingSalesman_10-20-0.json
python3 TravelingSalesman.py -data=TravelingSalesman_10-20-0.json -variant=table
"""
from pycsp3 import *
distances = data
nCities = len(distances)
# c[i] is... | StarcoderdataPython |
3311198 | import pandas as pd
class H3Index:
def __init__(self, h3_to_chains_path):
self.h3_to_chains = pd.read_pickle(h3_to_chains_path)
self.valid = set([x for x in self.h3_to_chains.keys()])
self.h3_to_index = {h3: i for i, h3 in enumerate(self.h3_to_chains.keys())}
self.r_h3_to_index = {i... | StarcoderdataPython |
94961 | # The experiment logic and analysis
import copy
import gym
import json
import matplotlib
import multiprocessing as mp
import warnings
import numpy as np
import platform
import pandas as pd
import traceback
from keras import backend as K
from os import path, environ
from rl.util import *
from rl.agent import *
from rl.m... | StarcoderdataPython |
1679797 | <reponame>yycho0108/DRLND_Core
#!/usr/bin/env python3
from abc import ABC, abstractmethod
import os
import numpy as np
from enum import Enum
from collections import defaultdict
import pickle
from drlnd.core.agents.base_agent import AgentBase
from drlnd.core.common.epsilon import EpsilonBase, IncrementalEpsilon
from ... | StarcoderdataPython |
4914098 | # SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
# @author <NAME>
import numpy as np
def hex_to_rgb(hex_color):
rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]]
return np.array([int(hex_value, 16) for hex_value in rgb_hex])
def rgb_to_hex(rgb):
... | StarcoderdataPython |
3237974 | <reponame>freeclouds/OpenHDMap<filename>map_label_tool/py_proto/modules/perception/onboard/proto/fusion_component_config_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: modules/perception/onboard/proto/fusion_component_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (la... | StarcoderdataPython |
12844798 | #!/usr/bin/env python
"""Test add_metadata_route function with legal parameters.
"""
import apikit
from flask import Flask
def test_set_flask_metadata():
"""Test metadata creation with legal parameters.
"""
app = Flask("bob")
apikit.set_flask_metadata(app, "2.0", "http://example.repo", "BobApp")
a... | StarcoderdataPython |
6608959 | <reponame>siavash-khodadadeh/MetaLearning-TF2.0
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Input, BatchNormalization
from decorators import name_repr
class SimpleModel(tf.keras.Model):
name = 'SimpleModel'
def __init__(self, num_classes):
super(SimpleModel, s... | StarcoderdataPython |
6457157 | <filename>src/app/voltdb/voltdb_src/lib/python/voltcli/voltdb.d/start.py
# This file is part of VoltDB.
# Copyright (C) 2008-2021 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundat... | StarcoderdataPython |
8093444 | import pandas as pd
import time
import os
#os.environ['TZ'] = 'America/Los_Angeles' # set new timezone
#time.tzset()
url="https://healthdata.gov/api/views/g62h-syeh/rows.csv?accessType=DOWNLOAD"
#Read current data into dataframe
data = pd.read_csv(url)
#Save as CSV
#data.to_csv(f'./hhs/scrapes/{time.strftime("%Y-%m-%... | StarcoderdataPython |
3548559 | #!/usr/bin/env python
"""
Point Grey camera used in the context of a focus lock.
Hazen 09/19
Evan 06/21
"""
import numpy
import time
from PyQt5 import QtCore
import storm_control.sc_hardware.utility.af_lock_c as afLC
import storm_control.sc_hardware.pointGrey.spinnaker as spinnaker
import tifffile
# ===== Import fit... | StarcoderdataPython |
12184 | from __future__ import print_function
import argparse, sys
from .utils import is_textfile
def contains_crlf(filename):
with open(filename, mode='rb') as file_checked:
for line in file_checked.readlines():
if line.endswith(b'\r\n'):
return True
return False
def main(argv=Non... | StarcoderdataPython |
6485850 | from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 6
_version_micro = "" # use "" for first of series, number for 1 and above
_version_extra = "" # use "dev0" for developemnt, "" for full release
# Construct full version... | StarcoderdataPython |
9687019 | <gh_stars>0
#!/usr/bin/env python3
import sys
import os
import logging
import argparse
from wordpal import puzzicon
from pb5.balloons import WordSearcher
def main():
parser = argparse.ArgumentParser()
parser.add_argument("balloons", nargs='+')
parser.add_argument("-l", "--log-level", choices=('DEBUG', 'IN... | StarcoderdataPython |
5199931 | <gh_stars>1-10
import os
from pddlstream.algorithms.reorder import get_partial_orders
from pddlstream.language.constants import EQ, get_prefix, get_args, NOT, MINIMIZE
from pddlstream.language.conversion import str_from_fact, evaluation_from_fact
from pddlstream.language.function import FunctionResult
from pddlstream.... | StarcoderdataPython |
6599933 | <reponame>cpearce/scikit-ika<filename>skika/hyper_parameter_tuning/trees_arf/evaluate_prequential_and_adapt.py<gh_stars>1-10
import os
import warnings
import re
from timeit import default_timer as timer
from numpy import unique
# Include the 2 following from the third_party skmultiflow
from skmultiflow.evaluation.ba... | StarcoderdataPython |
109184 | <reponame>uaca/deepy<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from wrapper import deepy_tensor
from functions import concat, concatenate, reverse, ifelse, apply, repeat, var, vars, activate, is_neural_var, is_theano_var
from onehot import onehot_tensor, onehot
import theano_nnet_imports as nnet
... | StarcoderdataPython |
8146088 | <filename>all_utils.py
from keras.layers import CuDNNLSTM
from keras.layers import Lambda
from keras.layers.merge import add
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
import numpy as np
from numpy import dstack
from pandas import read_csv
from keras.utils import to_categorica... | StarcoderdataPython |
1671645 | <filename>glslc/test/option_dash_S.py
# Copyright 2015 The Shaderc 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... | StarcoderdataPython |
1728710 | <reponame>alfredots/image-processing
import numpy as np
import math
class Aritmetics:
@staticmethod
def add(img1, img2):
newImage = np.zeros((img1.shape[0],img1.shape[1],img1.shape[2]), np.uint8)
rows, columns, pixel = img1.shape
for i in range(rows):
for j in range(colum... | StarcoderdataPython |
1755123 | # -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Also if needed: retab
'''
TEST equimap
'''
from __future__ import (unicode_literals, absolute_import, \
print_function, division)
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import ti... | StarcoderdataPython |
5105717 | <reponame>idvxlab/vega-lite-linter<filename>vega_lite_linter/fixer/action.py
class Actions:
ADD_MARK = "ADD_MARK"
CHANGE_MARK = "CHANGE_MARK"
BIN = "BIN"
BIN_X = "BIN('X')"
BIN_Y = "BIN('Y')"
BIN_COLOR = "BIN('COLOR')"
BIN_SIZE = "BIN('SIZE')"
REMOVE_BIN = "REMOVE_BIN"
REMOVE_BIN_X... | StarcoderdataPython |
4819211 | # https://docs.gunicorn.org/en/latest/settings.html#accesslog
accesslog = "-"
# https://docs.gunicorn.org/en/latest/settings.html#accesslog
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(M)s'
# https://docs.gunicorn.org/en/latest/settings.html#errorlog
errorlog = "-"
# https://doc... | StarcoderdataPython |
123871 | <reponame>zopefoundation/zc.resourcelibrary<gh_stars>0
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of... | StarcoderdataPython |
9712394 | <filename>django_candy/middleware.py
from django.http import HttpResponse, JsonResponse
from django.conf import settings
CORS_ALLOW_ORIGIN = getattr(settings, 'CORS_ALLOW_ORIGIN', 'http://localhost:3000')
CORS_ALLOW_METHODS = getattr(settings, 'CORS_ALLOW_METHODS', ['POST', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']... | StarcoderdataPython |
5093236 | from colorama import Fore, Back, Style
from pyfiglet import Figlet
from PyInquirer import prompt, Separator
from examples import custom_style_2
import time
import src.migrations.YoutubeToSpotify as YoutubeToSpotify
import src.migrations.SpotifyToYoutube as SpotifyToYoutube
def main():
# print banner
f = Figle... | StarcoderdataPython |
4809821 | /home/runner/.cache/pip/pool/3b/e4/ff/dbcd7adea90479a5fc6cb82a24bb8e2d8babd79702dbfc6903444435f3 | StarcoderdataPython |
8087403 | <filename>NBApredict/scrapers/scraper.py<gh_stars>1-10
"""
This module wraps the team stats, schedule, and betting line scrapers together and stores their data in the database.
If the script is called, it instantiates a DBInterface object for database interactions and creates a SQLalchemy session
object from the DBInt... | StarcoderdataPython |
1726777 | import pandas as pd
import numpy as np
import os
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant
import cubetools.config as cfg
class Model():
'''Creates data for the UI and export'''
def __init__(self):
super().__init__()
self.valid_cncfilelist = self.check_cnc_filepaths()
de... | StarcoderdataPython |
3360739 | #!/usr/bin/env python
import pytest
from click.testing import CliRunner
from enshrine import to_json, to_yaml, main
VARS_YAML = """---
var1: value1
var2: value2
"""
INI_TEMPLATE = """[section]
value1: {{ var1 }}
value2: {{ var2 }}
"""
def _write_files():
with open('vars.yaml', 'w') as f:
f.write(VARS... | StarcoderdataPython |
1929440 | <filename>setup.py<gh_stars>1-10
import sys
if sys.version_info.major != 3: raise Exception('ktrain requires Python 3')
from distutils.core import setup
import setuptools
with open('README.md', encoding='utf-8') as readme_file:
readme_file.readline()
readme = readme_file.read()
exec(open('ktrain/version.py')... | StarcoderdataPython |
396638 | import math
import logging
import torch
import torch.nn as nn
from prettytable import PrettyTable
from ..mask import Mask_s, Mask_c
__all__ = ['resdg20_cifar10', 'resdg32_cifar10', 'resdg56_cifar10',
'resdg110_cifar10']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convol... | StarcoderdataPython |
8016381 | import time
from tqdm import tqdm
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.utils import Progbar
from nlpgnn.datas.checkpoint import LoadCheckpoint
from nlpgnn.datas.dataloader import TFWriter, TFLoader
from nlpgnn.metrics import Metric
from nlpgnn.models import bert
from nlp... | StarcoderdataPython |
8069182 | from collections import Counter
from aoc.util import load_input, load_example
def column_counts(lines, pos):
result = ""
for i in range(len(lines[0].strip())):
result += Counter(line[i] for line in lines).most_common()[pos][0]
return result
def part1(lines):
"""
>>> part1(load_example(_... | StarcoderdataPython |
9752756 | ##通过字典文件矫正box
# 原文件重命名为 old_[name].box,新建原名文件用于保存矫正后box
# 实现思路详见 check_box()
##使用说明:
# 修改 boxName
# 修改 mode和 mImgNum
# 如有需要可以修改 imgNum
import cv2
import os
import numpy as np
import random
import pickle
def check_box( boxName, mImgNum, mode, numNum=10):
'''
------------------------------------------... | StarcoderdataPython |
6462214 | """config.py: a place to hold config/globals"""
from os import path
from enum import Enum
import logging
import prosper.common.prosper_logging as p_logging
import prosper.common.prosper_config as p_config
HERE = path.abspath(path.dirname(__file__))
LOGGER =logging.getLogger('publicAPI')
CONFIG = None #TODO
USER_AGE... | StarcoderdataPython |
6645244 | <reponame>albseb511/execode<gh_stars>0
from flask import request
from flask_restful import Resource, reqparse
from ..services.contest_detail import get_contests_challenges, get_contests, add_contest, update_contest, caesar_encrypt_raw, caesar_decrypt_raw
from app.main.services.decode_auth_token import decode_auth_token... | StarcoderdataPython |
3297956 | <reponame>shigeyukioba/matchernet
from matchernet.ekf import *
from matchernet.fn import *
from matchernet.matchernet import *
from matchernet.matchernet_null import *
from matchernet.observer import *
from matchernet.state import *
from matchernet.state_space_model_2d import *
from matchernet.utils import *
from match... | StarcoderdataPython |
9609618 | <filename>test/test_player.py
import pytest
from PyBall import PyBall
from PyBall.models import Person
from PyBall.exceptions import InvalidIdError, BadRequestError
@pytest.fixture(scope='module')
def test_player():
pyball = PyBall()
return pyball.get_player(446372)
def test_get_player_endpoint_returns_pla... | StarcoderdataPython |
8099804 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
CODE_TYPE_CHOICES = (
('code', _('Inline code')),
('pre', _('Code block')),
('var', _('Variables')),
('kbd', _('User input')),
('samp', _('Sample output')),
)
| StarcoderdataPython |
321541 | <reponame>greysondn/gamesolutions<gh_stars>0
from tqdm import tqdm
def main():
# some very basic config
minSeatCount = 0
maxSeatCount = 9
for i in range(minSeatCount, maxSeatCount + 1):
# build table
table = []
for j in range(i):
table.append(j)
#actu... | StarcoderdataPython |
6639141 | <filename>python/pandaset/meta.py
#!/usr/bin/env python3
import json
import os.path
from abc import ABCMeta, abstractmethod
from typing import TypeVar, List, overload, Dict
T = TypeVar('T')
class Meta:
"""Meta class inherited by subclasses for more specific meta data types.
``Meta`` provides gen... | StarcoderdataPython |
3206486 | <gh_stars>1-10
#!/usr/bin/env python
import unittest
from six.moves import xrange
from netutils_linux_monitoring.softirqs import Softirqs
class SoftirqsTest(unittest.TestCase):
def test_file2data(self):
for cpu in ('dualcore', 'i7'):
for i in xrange(1, 6):
top = Softirqs()
... | StarcoderdataPython |
8176783 | <gh_stars>1-10
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ---------------------------------... | StarcoderdataPython |
6539893 | # ---------------------------------------------------------------------------------------------------------------------
# API Wars
# controller: server logic control
# ... | StarcoderdataPython |
191641 | <filename>knxpy/dpts/dpt1.py
#!/usr/bin/env python3
"""
Boolean data
1 bit
0,1
"""
def encode(value):
return [int(value) & 0x01]
def decode(data):
return (data & 0x01)
| StarcoderdataPython |
8006032 | """
Test Results for the VAR model. Obtained from Stata using
datasets/macrodata/var.do
"""
import numpy as np
class MacrodataResults(object):
params = [-0.2794863875, 0.0082427826, 0.6750534746,
0.2904420695, 0.0332267098, -0.0073250059,
0.0015269951, -0.1004938623, -0.1231841792,
... | StarcoderdataPython |
7343 | import csv
import os
from collections import deque
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_PATH = os.path.join(BASE_DIR, 'goods_source.csv')
OUTPUT_PATH = os.path.join(BASE_DIR, 'result.csv')
FILE_ENCODE = 'shift_jis'
INPUT_COLS = ('id', 'goods_name', 'price')
def import_csv():
"""入力データの読み込... | StarcoderdataPython |
1964486 | <reponame>agonzale34/sdc-advanced-lane-detection
import matplotlib.pyplot as plt
import numpy as np
import cv2
# helper to show 2 images next to each other
def visualize_result(original, result, gray=False, show=True):
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
ax1.imshow(original)
ax1.set_title... | StarcoderdataPython |
3207702 | <filename>ex020.py
#O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.
from random import shuffle
n1 = input('Digite o nome do primeiro aluno: ')
n2 = input('Digite o nome do segundo aluno: ')
n3... | StarcoderdataPython |
1785146 | <reponame>damm89/django-camunda<gh_stars>1-10
"""
Public Python API to interact with Activiti.
"""
from typing import Any, Dict, Iterable, List, Optional
import requests
from .camunda_models import ProcessDefinition, Task, factory
from .client import get_client
from .types import CamundaId, ProcessVariables
from .uti... | StarcoderdataPython |
8128579 | <reponame>papperlapapp/PyScep
from enum import Enum, IntEnum
class MessageType(Enum):
"""The SCEP Message Type.
This is encoded as PrintableString so this enum also uses strings.
See Also:
- `SCEP RFC <https://datatracker.ietf.org/doc/draft-gutmann-scep/?include_text=1>`_ Section 3.2.1.2.
"""... | StarcoderdataPython |
1805475 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | StarcoderdataPython |
6645690 | <filename>src/day6.py<gh_stars>0
import numpy as np
def find_closest(loc, coords): #-1 for ties
#make sure they're in the same coordinate system
closest_dist = np.inf
closest_pair_index = 0
hits = 0
dist = np.abs(loc[:,None] - coords).sum(-1)
# np.abs(coords-loc)
import pdb
pdb.set_trace()
for i, pair in enum... | StarcoderdataPython |
11305181 | <reponame>Truelite/modian<filename>modian-live-wrapper/lwr/utils.py
# live-wrapper - Wrapper for vmdebootstrap for creating live images
# (C) 2016 <NAME> <<EMAIL>>
# See COPYING for terms of usage, modification and redistribution.
#
# lwr/utils.py - data utilities for suites and url information
"""
General utility fun... | StarcoderdataPython |
1920372 | import os
import sys
import traceback
def executeNode(node):
"""
TODO: Imprement https://github.com/pyqtgraph/pyqtgraph/blob/229f650adfd04053213fe6567d6308a4751a349b/pyqtgraph/flowchart/Flowchart.py#L248
Args:
Node (Node):
"""
print ("Executing...")
try :
_root = []
_ex... | StarcoderdataPython |
3468675 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 09:29:20 2018
@author: Tilly
"""
import time
import requests
request_id = 677078
def check_status(request_id):
"""
uses the request ID to return the state of the request
Example
input:
request_id = 677078
output:
'COMPLETE', 'PE... | StarcoderdataPython |
4851930 | from panini import app as panini_app
from panini.middleware.prometheus_monitoring import PrometheusMonitoringMiddleware
from app.utils import Environment
Environment.load("test")
BROKER_HOST, BROKER_PORT = Environment.get_broker()
CONFIG_PATH = Environment.get_config_path()
some_config = Environment.get_config("some-... | StarcoderdataPython |
71787 | <reponame>zaltoprofen/chainer<gh_stars>1000+
import unittest
import numpy
import six
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testi... | StarcoderdataPython |
3391048 | <reponame>jackyin68/jobsearch<gh_stars>1-10
from django.db import models
# Create your models here.
from datetime import datetime
from elasticsearch_dsl import DocType, Date, Nested, Boolean, \
analyzer, Completion, Keyword, Text
from elasticsearch_dsl.analysis import CustomAnalyzer as _CustomAnalyzer
from elast... | StarcoderdataPython |
1945856 | # uvozimo ustrezne podatke za povezavo
import auth as auth
# uvozimo psycopg2
import psycopg2, psycopg2.extensions, psycopg2.extras
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki
import csv
def ustvari_tabelo():
cur.execute("""
CREATE TABLE obisk (
... | StarcoderdataPython |
11353156 | <filename>pi/emo_reco/helpers/nn/mxconv/mxgooglenet.py
# import the necessary packages
import mxnet as mx
class MxGoogLeNet:
@staticmethod
def conv_module(data, K, kX, kY, pad=(0, 0), stride=(1, 1)):
# define the CONV => BN => RELU pattern
conv = mx.sym.Convolution(data=data, kernel=(kX, kY),
num_filter=K, pa... | StarcoderdataPython |
4935977 | # -*- coding: utf-8 -*-
"""Module scanning for compression support
"""
# import basic stuff
# import own stuff
import tlsmate.msg as msg
import tlsmate.plugin as plg
import tlsmate.tls as tls
# import other stuff
class ScanCompression(plg.Worker):
name = "compression"
descr = "scan for compression support"
... | StarcoderdataPython |
1842395 | from database import SQL
import conll
def reorder(trees, outfile): # 重新排序conll树,可重命名所有sent_id
"""
Reorders the trees based on the nr sentencefeature, adds updated text and sentence_id.
Once this is done, the trees are written to a new file.
input: List(Tree), Str
does: Writes <outfile>
output: None
"""
prefi... | StarcoderdataPython |
1767992 | <gh_stars>0
import numpy as np
from scipy.integrate import solve_bvp
class boundary_layer():
def __init__(self, stream, plate, Pr):
self.T_w = 0
self.T_e = 0
self.deltaT = self.T_w - self.T_e
# Prandtl
self.Pr = Pr
# Nusselt
self.Nusselt = []
self.stream = stream
self.plate = ... | StarcoderdataPython |
35962 | a = input()
b= input()
print(ord(a) + ord(b))
| StarcoderdataPython |
235410 | <gh_stars>1-10
import datetime
import time
import numpy as np
import random
import ray
import os
from filelock import FileLock
####################################################################################################
##########################################################################################... | StarcoderdataPython |
4863869 | from Configurables import DaVinci
DaVinci().DataType = '2012'
DaVinci().Simulation = True
DaVinci().TupleFile = 'mc.root'
# DaVinci().HistogramFile = 'mc-histo.root'
from Configurables import LHCbApp
LHCbApp().CondDBtag = "sim-20130503-1-vc-md100"
LHCbApp().DDDBtag = "dddb-20130503-1"
from GaudiConf import IOHel... | StarcoderdataPython |
1602074 | import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config['DEBUG'] = True
fruits = [
{
'name' : 'watermelon',
'price' : 12
},
{
'name' : 'banana',
'price' : 20
},
{
'name' : 'orange',
'price' : 100
}
]
@app.route("/"... | StarcoderdataPython |
1684546 | <filename>tests/test_5_adding_functions_to_the_mix.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
from nose.tools import assert_equals, assert_raises_regexp, \
assert_raises, assert_true, assert_is_instance
from diylang.ast import is_list
from diylang.evaluator import evaluate
from diylang.parser import parse
from ... | StarcoderdataPython |
1751376 | <reponame>JFF-Bohdan/tamaku<filename>tests/test_solver_implementation.py
from solver.solver_impl import find_best_step, game_result_to_string, play_game_bool
def test_solver_implementation_by_fixture():
with open("./tests/valid_output_fixture.txt", "rt") as file:
for line in file:
if line is N... | StarcoderdataPython |
3491986 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os
import re
import codecs
from collections import namedtuple
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import unchanged_required
from docutils import nodes
... | StarcoderdataPython |
6469467 | #! /usr/bin/python
import json
import altair
import pandas
import datetime
import bs4
import os
import csv
import statistics
import locale
#define constants
#TODO Clean up to removal duplicate calls for yesterday
workingDir = os.getcwd()
yesterdayDate = datetime.date.today() - datetime.timedelta(1)
yesterday = yesterd... | StarcoderdataPython |
1835948 | <reponame>k-for-code/serverless-transformers-on-aws-lambda
import warnings
from functools import lru_cache
warnings.filterwarnings("ignore")
from tqdm import tqdm
from transformers import (AutoConfig, AutoModelForSequenceClassification,
AutoTokenizer, pipeline)
from src import config, utils... | StarcoderdataPython |
9709917 | <gh_stars>1-10
import supervisor
supervisor.set_next_stack_limit(4096 + 4096)
#### My boot.py : disable midi, repl and mass storage unless button pressed
from usb_midi import disable as mididisable
from usb_cdc import disable as consoledisable
from digitalio import DigitalInOut, Direction, Pull
from storage import... | StarcoderdataPython |
3464836 | <gh_stars>1-10
# @author <NAME>
# This code is licensed under the MIT license (see LICENSE.txt for details).
"""
Utility classes to provide a graphical interface to paperfetcher handsearch and snowballsearch classes.
"""
import ipywidgets
from IPython.display import display
import os
from paperfetcher import handsearc... | StarcoderdataPython |
11341476 | # https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
carry = 0
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[Li... | StarcoderdataPython |
4925643 | <filename>lisa/tools/lsblk.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import re
from dataclasses import dataclass
from typing import List
from lisa.executable import Tool
from lisa.util import find_patterns_groups_in_lines
@dataclass
class PartitionInfo(object):
name: str = ""
... | StarcoderdataPython |
6553552 | from cx_Freeze import setup, Executable
setup(
name = "AdcpTerminal",
version = "1.0.0",
description = "Setup the Terminal and connection to crossbar.io",
executables = [Executable("../frontend/qt/mainwindow.py")],
)
| StarcoderdataPython |
146537 | # Copyright 2019 TerraPower, LLC
#
# 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 writi... | StarcoderdataPython |
85506 | import os
from testglobals import config
import subprocess
import re
# Feature names generally follow the naming used by Linux's /proc/cpuinfo.
SUPPORTED_CPU_FEATURES = {
# These aren't comprehensive; they are only CPU features that we care about
# x86:
'sse', 'sse2', 'sse3', 'ssse3', 'sse4_1', 'sse4_2',
... | StarcoderdataPython |
89549 | <filename>tests/monitoring/fixtures/server.py
# pylint: disable=redefined-outer-name
import logging
from typing import List
from unittest.mock import patch
import pytest
from eth_utils import to_canonical_address
from web3 import Web3
from monitoring_service.database import Database
from monitoring_service.service im... | StarcoderdataPython |
6643645 | <reponame>mudkipmaster/MLB-Crawler
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
class Visualizer:
def set_up_sz_plot(self, title):
f = plt.figure()
ax = f.gca()
ax.axis('equal')
self.plot... | StarcoderdataPython |
9753925 | <filename>noise_characterization/tomography/DDTMarginalsAnalyzer.py
"""
@authors: <NAME>, <NAME>, <NAME>
@contact: <EMAIL>
REFERENCES:
[0] <NAME>, <NAME>, <NAME>,
"Mitigation of readout noise in near-term quantum devices
by classical post-processing based on detector tomography",
Quantum 4, 257 (2020)
[0.5] <NAME>, <... | StarcoderdataPython |
9669839 | #Declare a list x
x=[1,2,13,4,15]
print('printing the list declared:', x)
#Iterate the list forward and print the value
for i in x:
print(i)
#Length of the list
print('length of the list is:', len(x))
#Print the new line
print("")
#Decrement the value held in i until it become zero
while(i):
i = i-1
pr... | StarcoderdataPython |
1957516 | <filename>rl/data/interactions_producer.py
import abc
import numpy as np
import tensorflow as tf
from rl.utils.env_batch import EnvBatch, SingleEnvBatch
class BaseInteractionsProducer(abc.ABC):
def __init__(self, env, policy, batch_size, env_step=None):
self._env = env
self._policy = policy
self._batc... | StarcoderdataPython |
1699314 | <gh_stars>0
from fetch_data import fetch_poem
from markov_python.cc_markov import MarkovChain
def intialize_model():
'''Feed the data to a markov chain and return the object of it'''
poems = fetch_poem()
mc = MarkovChain()
for poem in poems:
mc.add_string(poems[poem])
return mc
def generate_poem(mc, para = ... | StarcoderdataPython |
5128647 | <filename>compoundInvestment.py
# Calculate the total savings you can get from a starting annualSalary
def f():
annualSalary = 80000
global timeWorking
timeWorking= 20
annualSalaryIncrease = 5000
super = 0.1 # Superannuation
annualSavingPercent = 0.1
tax = 0.04
totalSaving = annualSal... | StarcoderdataPython |
8000465 | from .utils import RequestHandler, HTTPException, role_admitted, scanAllLinks, export
from .controllers import Roles, add_event_to_user, verify_token, remove_event_from_user
from .controllers import get_event, get_all_events, update_event, get_user_events, get_user_tags
import json
class Events(RequestHandler):
... | StarcoderdataPython |
1602940 | <gh_stars>10-100
import mymodule
a = mymodule.A()
a.spam()
b = mymodule.B()
b.bar()
| StarcoderdataPython |
11366482 | import numpy as np
from astropy.coordinates import ICRS, SkyCoord
from astropy.wcs.utils import skycoord_to_pixel
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import cdshealpix
from ... import mocpy
def border(moc, ax, wcs, **kw_mpl_pathpatch):
from .utils import build_plotting_mo... | StarcoderdataPython |
95136 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.