text string | size int64 | token_count int64 |
|---|---|---|
from enum import Enum
from fastapi import status, HTTPException
from order.adapters.orm_adapter import ordermodel
class Order:
async def create(self, data):
return await ordermodel.create(obj_in=data)
async def update(self, id, data):
_order = await ordermodel.get(id)
if not hasattr(... | 2,356 | 698 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
from base import BaseObject
def to_list(results):
"""
Purpose:
Simplify the ComputeSkipGrams result set
:param results:
a ComputeSkipsGrams result set
looks like this
[(u'Problems', u'installing'), (u'Proble... | 2,924 | 859 |
import r2pipe, sys
r2=r2pipe.open("iof.elf")
s=r2.cmd("p8 4 @ "+sys.argv[1])
s=s[6:8]+s[4:6]+s[2:4]+s[0:2]
print s
print r2.cmd("xr 4 @ "+sys.argv[1]+"")
r=open("esp32.rom").readlines()
for l in r:
if s in l:
print l
| 230 | 126 |
"""
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais;
- Variáveis globais são reconhecidas, ou seja, seu escopo compreende, todo o o programa.
2 - Variáveis locais;
- Variáveis locais são reconhecidas apenas no bloco onde foram declaradas, ou seja, seu escopo
está limitado ao bloco onde fo... | 1,021 | 387 |
import unittest
import six
from pynetbox.core.endpoint import Endpoint
if six.PY3:
from unittest.mock import patch, Mock, call
else:
from mock import patch, Mock, call
class EndPointTestCase(unittest.TestCase):
def test_filter(self):
with patch(
"pynetbox.core.query.Request.get", r... | 2,117 | 644 |
# secondcounter
from tkinter import *
import threading
import time
r=Tk()
r.geometry("400x400")
r.minsize(200,200)
r.maxsize(500,500)
speed=0
count=0
counting=None
counting=IntVar()
def counter():
global speed,count
print(count)
while True:
time.sleep(1)
count+=speed
counting.set(cou... | 1,030 | 431 |
from typing import List, Optional
from app.schemas.base import APIBaseCreateSchema, APIBaseSchema, PyObjectId
class AppSchema(APIBaseSchema):
name: str
creator: PyObjectId
description: Optional[str] = ""
class AppCreateSchema(APIBaseCreateSchema):
name: str = ""
description: Optional[str] = ""
... | 655 | 179 |
from django.conf.urls import url
from student_app import views
from django.contrib.auth.views import password_reset,password_reset_done,password_reset_confirm,password_reset_complete
# SET THE NAMESPACE!
app_name = 'student_app'
# Be careful setting the name to just /login use userlogin instead!
urlpatterns=[
ur... | 1,365 | 469 |
import pandas as pd
trust = pd.read_csv('WVS_TimeSeries_1981_2020_ascii_v2_0.csv')
trust = trust[['COUNTRY_ALPHA', 'S020', 'A165', 'A170', 'A169']]
trust = trust.rename(columns={'COUNTRY_ALPHA': 'ISO', 'S020': 'year'})
trust.to_csv('trust.csv', index=None) | 260 | 137 |
import os
import pickle
def save_as_pickle(variable_name, save_name):
"""Saves variable as pickle file.
# Arguments
save_name: Name of file.
# Example
dataPath = "C:/Users/nicol/Desktop/Master/Data/"
save_name = dataPath + 'predictionsResNet50ADAM_lr0001_decay0005'
file_uti... | 1,164 | 422 |
from nose.tools import ok_
import oemof
import oemof.db as oemofdb
def test_that_oemof_is_importable():
ok_(oemof.__version__)
def test_oemofdb_imports():
ok_(oemofdb.connection)
ok_(oemofdb.engine)
ok_(oemofdb.url)
| 237 | 96 |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmedit.models.common import SpatialTemporalEnsemble
def test_ensemble_cpu():
model = nn.Identity()
# spatial ensemble of an image
ensemble = SpatialTemporalEnsemble(is_temporal_ensemb... | 2,440 | 811 |
import sys
from .utils import ext
if sys.version_info >= (3,):
import xmlrpc.client as xmlrpclib
import urllib.request as urllib2
else:
import xmlrpclib
import urllib2
try:
import simplejson as json
except ImportError:
import json
def pypi_client(index_url='http://pypi.python.org/pypi', *arg... | 10,299 | 3,310 |
import re
from . import Mod
REPLACE_TEXT = "REPLACEME"
def prepend_content_into_body(content, output):
p = re.compile(r'(?i)(<[^/>]*body[^>]*>)([\s\S]*)(<\s*\/s*body[^>]*>)')
sub = r'\1' + REPLACE_TEXT + r'\2' + r'\3'
output = re.sub(p, sub, output)
output = output.replace(REPLACE_TEXT, content)
... | 399 | 164 |
"""
日志类。通过读取配置文件,定义日志级别、日志文件名、日志格式等。
日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
一般直接把logger import进去
from utils.log import logger
logger.info('test log')
"""
import logging
from logging.handlers import TimedRotatingFileHandler
from com.web.utils.Config import LOG_PATH, Config
import os
class Logger(objec... | 2,466 | 858 |
from .show_port_channel_database import ShowPortChannelDatabase
from .show_port_channel_database_detail import ShowPortChannelDatabaseDetail
| 141 | 34 |
# Copyright 2016 Red Hat, 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 in writing... | 8,385 | 2,512 |
# Copyright 2021, Yahoo
# Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms
import re
from enum import Enum
from types import DynamicClassAttribute, SimpleNamespace
from typing import Any, Iterable, List, Optional, Type, TypeVar
T = TypeVar("T")
class BuiltinUt... | 2,435 | 781 |
import sys
import os
import socket
import json
import time
import subprocess
from influxdb import InfluxDBClient
import Adafruit_DHT
def getConfig():
# Pull the configuratin from env vars or the config file
if os.environ.get('AM_I_IN_A_DOCKER_CONTAINER', False):
c = {
"debug": os.environ.... | 5,091 | 1,599 |
# Generated by Django 3.0.4 on 2020-06-20 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('artistArt', '0004_auto_20200617_1706'),
]
operations = [
migrations.AddField(
model_name='artistart',
name='tags',
... | 561 | 193 |
import random
no_switch = 0
switch= 0
'''
for i in range(10000):
car_loc = random.randint(1,3) #obviously random
my_choice = random.randint(1,3) #obviously random
host = [1,2,3]
host.remove(car_loc)
if my_choice in host:
host.remove(my_choice)
host = random.choice(host)
options = [1... | 930 | 332 |
# answer 1632
import csv
import sys
filename = sys.argv[1]
layers = dict()
with open(filename, 'r') as f:
reader = csv.reader(f, delimiter=':')
for row in reader:
layer = map((lambda x : int(x)), row)
layers[layer[0]] = layer[1]
def getLayerAtTime(depth, time):
# find the remainder of de... | 813 | 269 |
# Copyright (c) OpenMMLab. All rights reserved.
import cv2
import numpy as np
import torch
from mmcv.ops import contour_expand
from mmocr.core import points2boundary
from mmocr.models.builder import POSTPROCESSOR
from .base_postprocessor import BasePostprocessor
@POSTPROCESSOR.register_module()
class PSEPostprocess... | 3,190 | 944 |
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://127.0.0.1:8080/#")
b = driver.find_elements_by_id("view-fullscreen")[0]
b.click() | 163 | 67 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
default_args = {
'owner': 'afroot03'
}
dag = DAG(
'research_report_parser',
default_args=default_args,
description='beta_info_update',
schedu... | 878 | 315 |
import tweepy
import os
import pandas as pd
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.plotly as py
from plotly import tools
from dotenv import load_dotenv
import plotly
import datetime
import time # {Added}
load_dotenv()
plotly.tools.set_credentials_file(
username=os.enviro... | 2,983 | 951 |
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import state_union
from nltk import RegexpParser
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSen... | 1,007 | 345 |
from utils import plot_confusion_matrix, load_map, plot_SHAP, create_map
import hydralit as hy
import streamlit as st
import streamlit.components.v1 as components
st.set_option("deprecation.showPyplotGlobalUse", False)
app = hy.HydraApp(
title="Explainer Dashboard", # nav_container=st.header,
nav_horizontal=... | 3,446 | 1,116 |
from ermaket.api.scripts import ReturnContext, UserScript
__all__ = ['script']
script = UserScript(id=1)
@script.register
def step_1(context):
ctx = ReturnContext(abort=418)
ctx.add_message("Sorry, this won't work", variant="danger")
return ctx
| 261 | 91 |
from hardhat.recipes.base import GnuRecipe
class XInitRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(XInitRecipe, self).__init__(*args, **kwargs)
self.sha256 = '75d88d7397a07e01db253163b7c7a00b' \
'249b3d30e99489f2734cac9a0c7902b3'
self.name = 'xinit'
... | 578 | 253 |
from game.hangman import Hangman
def main():
w = Hangman(7)
while True:
w.draw_word_scheme()
w.check_char(input("Enter a char -> "))
w.check_win()
if __name__ == "__main__":
main()
| 221 | 84 |
from aws_cdk import (
aws_ec2 as ec2,
aws_elasticloadbalancingv2 as elbv2,
core as cdk
)
from . import VPCStack
class MoodleLoadBalancerStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, construct_id: str, vpc: VPCStack.MoodleVPCStack, **kwargs):
super().__init__(scope, const... | 1,057 | 368 |
from django.db import models
# Create your models here.
class Result(models.Model):
resultId = models.IntegerField(primary_key=True)
raceId = models.ForeignKey('races.Race', on_delete=models.CASCADE)
driverId = models.ForeignKey('drivers.Driver', on_delete=models.CASCADE)
constructorId= models.ForeignK... | 948 | 281 |
import argparse
import cv2
from models import * # set ONNX_EXPORT in models.py
from utils.datasets import *
from utils.utils import *
###############################################################
class_index = { '0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9,\
'A':10, 'B':11,... | 21,312 | 7,038 |
import subprocess as sub
sub.call('f2py -c ftarcoder42.pyf constantf.f90 mathf.f90 physicf.f90 -m'
' ftarcoder42', shell=True)
| 137 | 61 |
#!/usr/bin/python3
# Written By: Sahar Hathiramani
# Date: 01/11/2021
import pexpect
import os
os.system("clear")
print("🄱🄰🄳 🄱🄾🅈 🄱🅄🅃 🄰 🅂🄰🄳 🄱🄾🅈")
PROMPT = ['# ', '>>> ', '> ', '\$ ', '$ ']
def send_command(connection, command):
connection.sendline(command)
connection.expect(PROMPT)
print(co... | 1,257 | 491 |
#!/usr/bin/env python
# pylint: disable=missing-docstring
from patr import ctxt
import pytest
def test_gen_host_entry():
data = dict(
name="lala",
variables=dict(
kuku="kaka",
susu="sasa",
)
)
# order of dict generated iteration (non orderdict) is unreliabl... | 972 | 326 |
import logging
import os
import boto3
import psycopg2
from psycopg2.extensions import AsIs
from botocore.exceptions import ClientError
from urllib.parse import urlparse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
secretsmanager = boto3.client("secretsmanager")
s3 = boto3.client("s3")
def handler(event... | 2,613 | 889 |
# EGEN 310R D.3 Runner Script
# Written by Jared Weiss at Montana State University
# RESOURCES:
### [Pygame Docs:] https://www.pygame.org/docs/
# - I used the joystick docs (https://www.pygame.org/docs/ref/joystick.html) the most
### [Servo control article:] https://www.learnrobotics.org/blog/raspberry-pi-servo-motor/
... | 7,607 | 2,553 |
from collections import defaultdict
from send_email import send_email
class MailingList:
def __init__(self, data_file):
self.data_file = data_file
self.email_map = defaultdict(set)
def add_to_group(self, email, group):
self.email_map[email].add(group)
def emails_in_group(self, *g... | 1,438 | 425 |
# coding: utf8
from __future__ import unicode_literals
# import the symbols for the attrs you want to overwrite
from ...attrs import LIKE_NUM
# Overwriting functions for lexical attributes
# Documentation: https://localhost:1234/docs/usage/adding-languages#lex-attrs
# Most of these functions, like is_lower or like_u... | 1,465 | 463 |
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from pirates.battle import EnemyGlobals
from pirates.npc.BossBase import BossBase
from pirates.pirate import AvatarTypes
from pirates.effects.BossEffect import BossEffect
from pirates.effects.BossAura import BossAura
from direct.showbase.Dir... | 6,277 | 2,187 |
import turtle
nombre = turtle.Turtle()
colors=['red', 'purple', 'blue', 'green', 'yellow', 'orange', 'pink','light blue']
#Nombre:Willington
nombre.color("blue")
nombre.pu()
nombre.setposition(-500,300)
nombre.speed(10)
nombre.pensize(5)
nombre.pd()
nombre.left(270)
nombre.forward(350)
nombre.left(135)
n... | 5,751 | 2,755 |
#!/usr/bin/env python
import os
import subprocess
import logging
import smtplib
import socket
import ssl
import email
class App:
__logger: logging.Logger = logging.getLogger("ip-notifier")
__wanip_file: str = os.environ.get(
"WANIP_FILE", '/tmp/ip-notifier/current.ip')
__smtp_server: str = os.env... | 2,905 | 1,010 |
"""
Authors: Wouter Van Gansbeke, Simon Vandenhende
Licensed under the CC BY-NC 4.0 license (https://creativecommons.org/licenses/by-nc/4.0/)
"""
import os
import yaml
from easydict import EasyDict
from utils.utils import mkdir_if_missing
def create_config(config_file_env, config_file_exp, batch_size, epochs):
# C... | 1,292 | 495 |
"""
Plot comparisons between SIT and SIC modeling experiments using
WACCM4. Subplot includes FIT, HIT, FICT. Composites are
organized by QBO-E - QBO-W
Notes
-----
Author : Zachary Labe
Date : 31 January 2018
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basema... | 12,319 | 4,980 |
# -*- coding: utf-8 -*-
import csv
class Lectorcsv:
"""
Clase para importar y exportar diccionarios de personajes
Args:
m: instancia de la clase modelo
"""
def __init__(self,m):
self.__modelo = m
def importDict(self, fichero):
"""
Metod... | 1,836 | 559 |
import collections
import datetime
import difflib
import hashlib
import itertools
import json
import os
import pathlib
import string
import sys
import time
import uuid
import boto3
import botocore
import click
import halo
import yaml
from .. import gitlib
from ..exceptions import StackNotFound
from .connection_manage... | 24,465 | 6,998 |
import os
import fnmatch
import shutil
import re
import datetime
import time
#import StringIO
import pickle
import sys
import MetadataDateModules
from MetadataDateModules import metadataDateUpdater
from MetadataDateModules import TodaysDate
from FirstAlternativeTitle import FirstAlternativeTitle
from Res... | 35,129 | 10,601 |
import psycopg2
import yaml
from pathlib import Path
class DB():
"""
A simple wrapper class for connecting to the PostgreSQL database.
Takes no arguments. Relies on having connection information in
`~/dbconn.yaml`.
"""
def __init__(self):
"Reads the connection parameters, makes the c... | 1,511 | 442 |
import odoo.tests
@odoo.tests.tagged("at_install", "post_install")
class TestUi(odoo.tests.HttpCase):
def test_open_url(self):
# wait till page loaded
code = """
setTimeout(function () {
if ($('body').css('background-image').startsWith('url')) {
cons... | 537 | 153 |
# Copyright 2017 The Bazel 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 applicable la... | 8,094 | 2,277 |
from integration.api_setu import (
get_applicable_slots,
get_district_id_from_file,
get_state_id_by_state_name,
get_instant_applicable_slots,
)
from utils.load_config import load_configuration
from utils.external_caller import APIInterface
import time
from VacciDate_bot.send_message import send_personal... | 2,896 | 917 |
from . import dtree_util
import sys
sys.modules['dtree_util'] = dtree_util | 74 | 26 |
import gspread
import time
from oauth2client.service_account import ServiceAccountCredentials
#TODO
class Database:
INITIAL_FUND = "initial_fund"
INITIAL_DATE = "initial_date"
INTEREST_RATE = "interest_rate"
INTEREST_TYPE = "interest_type"
DEPOSIT_INTERVAL = "deposit_interval"
DEPOSIT_ACCOUNT ... | 889 | 296 |
import re
from collections import defaultdict
from copy import deepcopy
import numpy as np
import tensorflow as tf
from utils.model_utils import get_shape_list
def build_optimizer_from_config(loss, optimizer_config, device_config=None):
"""
This is a utility to build an optimizer from optimizer_config.
... | 18,833 | 5,958 |
palavra_secreta = input('Digite a palavra secreta: ')
print('Ok, agora peça pro seu amigo advinhar!')
letras_digitadas = []
contador = len(palavra_secreta) * 2
while True:
if contador <= 0:
print('Acabou as chances')
break
letra_usuario = input('Difite uma letra: ')
if len(letra_usuario)... | 1,001 | 378 |
'''
Transfer an object to its gear, as an interface.
'''
import asyncio
import datetime
from .AsyncPeriod import AsyncPeriod
from .method_run_when import call_backs
from ensureTaskCanceled import ensureTaskCanceled
gears = {}
class _Gear:
# last_set_period = {}
def __init__(self, obj):
self.obj = ... | 9,157 | 2,731 |
import functools
from .path import Path
class AbstractPolicy(object):
"""
A policy implements all routing decisions by
providing comparison methods for interfaces
and paths
"""
name = NotImplemented
def __init__(self):
if self.name == NotImplemented:
raise NotImplemen... | 1,851 | 539 |
#This is the class for construcing State Machines. The individual CAs
#(both inputs and states) run at 5 ms. See the notes for running faster or
#slower.
#There are test functions at the end.
#Note that to externally activate a CA State, you should only send
#excitatory connections to the first 8 neurons.
#Using ... | 21,905 | 7,506 |
import json
import sys
import requests
from bs4 import BeautifulSoup
# Scrape the ISO Country Codes @ https://en.wikipedia.org/wiki/ISO_3166-1
# USAGE: venv/bin/python scrape_iso_country_codes.py
def main():
iso_data = []
try:
website = requests.get('https://en.wikipedia.org/wiki/ISO_3166-1')
... | 1,318 | 422 |
from setuptools import find_packages, setup
setup(
name='q_gym',
packages=find_packages(),
version='0.1.0',
description='Reinforcement Learning models to run on the environments of the OpenAI Gym.',
author='Alexandre A. A. Almeida',
license='MIT',
)
| 275 | 89 |
import os
import inspect
import urllib.request
import shutil
import time
import socket
from colors import Colors
from tasks import gen_runner
from tasks import Task
from tasks import Edge
from passes import Pass
from passes import PassResult
from utils import get_file_extention
from utils import get_file_name
from uti... | 3,769 | 943 |
"""
calc_power_equivalents.py
"""
import numpy as np
from types import SimpleNamespace
def calc_power_equivalent(rf_pulse: SimpleNamespace,
tp: float,
td: float,
gamma_hz: float = 42.5764)\
-> np.ndarray:
"""
Calculates... | 1,431 | 492 |
my_int = 22
my_float = 64.21
my_str_num = "38.24"
print("Int my Float! "+str(int(my_float)))
print("Float my int! "+str(float(my_int)))
print("Num my string! "+str(float(my_str_num)))
#add
foo = float(my_str_num)
foo = foo+my_float
print(foo)
| 243 | 111 |
# -*- coding: utf 8 -*-
"""
Advent of Code 2018
Day X
"""
def argmax2d(list2d):
maxi = (0, 0)
for i, r in enumerate(list2d):
for j, e in enumerate(r):
maxi = (i, j) if e > list2d[maxi[0]][maxi[1]] else maxi
return maxi
def max2d(list2d):
r, c = argmax2d(list2d)
return list2d[r]... | 2,682 | 1,029 |
# log4jLogger = sc._jvm.org.apache.log4j
# LOGGER = log4jLogger.LogManager.getLogger(__name__)
# LOGGER.info("pyspark script logger initialized")
class Log4j(object):
"""Wrapper class for Log4j JVM object.
:param spark: SparkSession object.
"""
def __init__(self, spark):
# get spark app deta... | 1,262 | 390 |
import os
from pathlib import Path
from typing import Dict, List, Tuple, Union
import csv
from torch import Tensor
from torch.utils.data import Dataset
import torchaudio
def load_audio(line: List[str],
header: List[str],
path: str) -> Tuple[Tensor, int, Dict[str, str]]:
# Each line ... | 1,537 | 512 |
import json
import logging
from typing import Dict, List, Union
from .claim import Claim
from .wikidatasession import WikidataSession
class Entity(dict):
"""
Base class for all types of entities – currently: Lexeme, Form, Sense.
Not yet implemented: Item, Property.
"""
def __init__(self, repo: W... | 3,875 | 1,139 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import batch_norm
from tensorflow.contrib.layers.python.layers import l2_regularizer
import functools
def log_sum_exp(x, axis=1):... | 9,715 | 3,662 |
import pickle
import pandas as pd
from flask import Flask, render_template, request
# Pastas de template e assets
application = Flask(__name__, template_folder='template', static_folder='template/assets')
# Modelo Treinado
modelo = pickle.load(open('./models/modelo.pkl', 'rb'))
@application.route('/')
def home():
... | 2,091 | 742 |
# pylint: disable=C0111,R0902,R0913
# Smartsheet Python SDK.
#
# Copyright 2016 Smartsheet.com, 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/LICE... | 9,732 | 2,740 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import ciso8601
from datetime import datetime
import dtparse
def test_ciso8601(benchmark):
assert benchmark.pedantic(
ciso8601.parse_datetime, args=('2018-12-31T23:59:58', ),
rounds=10 ** 6, iterations=100
) == datetime(2018, 12,... | 770 | 371 |
from Cube import *
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
pygame.init()
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height), DOUBLEBUF | OPENGL)
pygame.display.set_caption('Lights in OpenGL')
done = False
white = pygame.... | 1,201 | 557 |
expected_output = {
'mac_table': {
'vlans': {
'100': {
'vlan': '100',
'mac_addresses': {
'0000.0000.1111': {
'mac_address': '0000.0000.1111',
'entry': '+',
'interfaces': {
... | 6,480 | 1,686 |
"""
my pretty printer module
"""
def printit(text):
# use ANSI escape sequeences top print inverted, bold ,red text
# https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit
print("\033[;7m\033[1;31m{}\033[0;0m".format(str(text) ) )
| 238 | 106 |
import copy
import random
import os
import pysam
import itertools
import numpy as np
from numpy.random import choice
VALID_CHROMS = set(['{}'.format(c) for c in range(1,23)]+['X']+['contig1','contig2','contig3'])
# estimate prior probability of genotypes using strategy described here:
# http://www.ncbi.nlm.nih.gov/pm... | 5,504 | 1,971 |
# -*- coding: utf-8 -*-
"""
@author: Li-Cheng Xu
"""
import numpy as np
from rdkit import Chem
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_error,r2_score
from sklearn.model_selection import train_test_split
from openbabel.pybel import readfile,Outputfile
def molformatconversion... | 26,604 | 10,488 |
import matplotlib.pyplot as plt
import os
import numpy as np
import json
plt.rcParams["font.family"] = 'Arial Unicode MS' #显示中文标签
plt.rcParams['axes.unicode_minus'] = False #这两行需要手动设置
data_source = '../data/'
def his_1():
data_path = os.path.join(data_source, 'single.txt')
f = open(data_path, 'r')
y1 = ... | 4,736 | 2,113 |
import os
from dotenv import load_dotenv
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import FormRecognizerClient
from azure.ai.formrecognizer import FormTrainingClient
from azure.core.credentials import AzureKeyCredential
def main():
try:
# Get con... | 1,591 | 438 |
from .other import yaml_to_json
from .selectors import convert_html_to_selector | 79 | 24 |
# Copyright (c) 2020 Open Collector, 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 to use, copy, modify, merge, publish... | 7,830 | 2,348 |
"""This module implements the pipeline steps needed to classify partner choices
in the OpenML Speed Dating challenge."""
from functools import lru_cache
import operator
from joblib import Parallel, delayed
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.imput... | 10,671 | 3,016 |
# Question 02, Lab 09
# AB Satyaprkash, 180123062
# imports
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# functions
def plotGraphs(fileName):
df = pd.read_csv(fileName)
# extract and rename columns
df = df[['Expiry', 'Strike Price', 'Clo... | 2,061 | 791 |
import subprocess
import tempfile
def do_screenshot(url):
"""
Screenshot an `url` (fullscreen) and return a path to an image.
:param url: A previously validated URL of a webpage to capture.
:return: A Path-like object representing a screenshot.
"""
_, path = tempfile.mkstemp(suffix='.png')
... | 486 | 161 |
from __future__ import print_function
import socket
from fdp.lib import datasources
# some valid shots for testing
shotlist = [204620, 204551, 142301, 204670, 204956, 204990]
def server_connection():
machine = datasources.canonicalMachineName('nstx')
servers = [datasources.MDS_SERVERS[machine],
... | 714 | 231 |
import numpy as np
import matplotlib.pyplot as plt
r = {
# Normal experiments
'Independent': np.genfromtxt('IndependentModel__WithValSigmoid/results.txt'),
'Sequential': np.genfromtxt('SequentialModel__WithVal/results.txt'),
'Sequential_ConceptsBreakdown': np.genfromtxt('SequentialModel__WithVal/conce... | 15,731 | 6,985 |
# Copyright 2017 The TensorFlow 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 applica... | 2,104 | 588 |
from argparse import Namespace
from itertools import product
from joblib import Parallel, delayed
import prediction
def run(args):
tasks = [
'TB/death_pvals',
'TB/platelet_pvals',
'TB/hemo',
'TB/hemo_pvals',
'TB/acid',
'TB/septic_pvals',
'UKBB/breast_25',
... | 1,099 | 404 |
a = 50
print('\033[32m_\033[m' * a)
print(f'\033[1;32m{"SISTEMA QUE SORTEIA E SOMA PARES":=^{a}}\033[m')
print('\033[32m-\033[m' * a)
from random import randint
from time import sleep
def sorteia(lista):
print('\033[1;34msorteando 5 valores da lista: ', end='')
for cont in range(0,5):
lista.append(ran... | 649 | 298 |
# -*- encoding: utf-8 -*-
BINARY_CLASSIFICATION = 1
MULTICLASS_CLASSIFICATION = 2
MULTILABEL_CLASSIFICATION = 3
REGRESSION = 4
REGRESSION_TASKS = [REGRESSION]
CLASSIFICATION_TASKS = [BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION,
MULTILABEL_CLASSIFICATION]
TASK_TYPES = REGRESSION_TASKS + C... | 1,915 | 899 |
# coding=utf-8
"""The root of pyzxing namespace."""
from .reader import BarCodeReader #noqa | 92 | 32 |
class SubmissionModule(object):
pass
| 41 | 12 |
# MINLP written by GAMS Convert at 08/13/20 17:37:47
#
# Equation counts
# Total E G L N X C B
# 1 0 0 1 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | 314,305 | 247,703 |
import networkx as nx
import random
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
class Passenger:
def __init__(self):
self.fees = 0
self.transit_time = 0
def initialize(n_passengers, node_capacity, itinerary=None, intermediate_stops=0):
g = nx.read_gml('cta.gm... | 4,374 | 1,348 |
from unittest.mock import patch
import pytest
from werkzeug.exceptions import InternalServerError, BadRequest
from signal_interpreter_server.routes import interpret_signal
from signal_interpreter_server.routes import signal_interpreter_app, parser_factory
from signal_interpreter_server.exceptions import SignalError
... | 3,362 | 915 |
"""Iterators utils."""
def iterate_in_slices(iterable, batch_size):
"""Yield lists of size batch_size from an iterable."""
it = iter(iterable)
try:
while True:
chunk = [] # The buffer to hold the next n items.
for _ in range(batch_size):
chunk.append(next(i... | 425 | 125 |
# oops in python
class sample:
data1= 10
data2= 'abc'
def show(self):
print(self.data1, self.data2)
def putdata1(self, data1):
self.data1 = data1
def putdata2(self.data2):
self.data2 = data2
s1 = sample()
s1.show()
s1.putdata1(25)
s1.show()
print(s1.data1)
# in this as we can see that th... | 3,526 | 1,136 |
# type: ignore
import nox
@nox.session
def python(session):
session.install("pytest", "maturin", "sphinx")
session.install(".", "--no-build-isolation")
session.run("make", "test", external=True)
| 209 | 74 |
import urllib.request
import zipfile
import os
url = 'https://syncandshare.lrz.de/dl/fiVRr3EeLiGxcoHXmW5yoWHq/models.zip'
print('Dlownloaing models (This might take time)')
urllib.request.urlretrieve(url, 'models.zip')
with zipfile.ZipFile('models.zip', 'r') as zip_ref:
print("extracting models")
zip_ref.extra... | 845 | 306 |