content stringlengths 5 1.05M |
|---|
# usr/bin/env/python
# For some damn reason, plain old "import obj" breaks things
from robot import BuildStandard
robot = BuildStandard(DEBUG=False)
topic = robot.say_hello()
theysay = raw_input("> ")
while(True):
topix = robot.topics_triggered(theysay) # tuple of all new topics opened
agree = robot.agrees(theys... |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
n, *r = map(int, read().split())
if n < 3:
print(0)
exit()
ans = 1
high = None
for x, y in zip(r, r[1:]):
if x < y:
if not high or high is None:
... |
"""
Tests the functionality in the simtk.unit package.
"""
from __future__ import division
from simtk import unit as u
import copy
import math
import unittest
try:
import numpy as np
except ImportError:
np = None
try:
from itertools import izip as zip
except ImportError:
pass # Python 3... zip _is_ izi... |
# A function that returns names of the jobs on the queue
def jobs_on_queue():
onq = []
import os
import subprocess
pwd = os.getcwd().split('/')
if len(pwd)>1 and pwd[1]=='home':
username = pwd[2]
elif len(pwd)>3 and pwd[1]=='stash':
username = pwd[3]
else:
username = ''
if os.path.exists('... |
#! /usr/bin/env python3
import os
import shutil
from tinytag import TinyTag, TinyTagException
from pydub import AudioSegment
source_folder = ''
destination_folder = ''
def normalize_audio(audio_file):
audio_file = audio_file.split('.')
sound = AudioSegment.from_file(audio_file[0], audio_file[1])
normal... |
import pandas as pd
import pytest
from pandas.testing import assert_series_equal
from prereise.gather.demanddata.eia.map_ba import (
aggregate_ba_demand,
get_demand_in_loadzone,
map_buses_to_ba,
map_buses_to_county,
)
def test_get_demand_in_loadzone_case():
bus_map, agg_demand = create_loadzone_d... |
import dolfin as df
import numpy as np
import os
from . import *
from common.io import mpi_is_root, mpi_comm
from common.bcs import Fixed, Charged
import random
__author__ = "Gaute Linga"
class PeriodicBoundary(df.SubDomain):
# Left boundary is target domain
def __init__(self, Lx):
self.Lx = Lx
... |
from warnings import warn
from os.path import join
from cobra.core import Model
from cobra.flux_analysis.gapfilling import GapFiller
from .likelihood import LikelihoodAnnotation
from .templates.util import read_json_file, create_boundary
from .templates.universal import create_universal_metabolite, metabolite_json_sc... |
import json
import os
import re
from django.conf import settings
from django.contrib.auth.models import Permission
from django.test import TransactionTestCase
from django_digest.test import Client as DigestClient
from tempfile import NamedTemporaryFile
from django.contrib.auth.models import User
from django_digest.tes... |
__author__ = 'Peter'
f = open ('codon.txt','r') #Megnyitja a filet
#Variablek
x = f.read()
d = {}
y = len (x)
s = "AUGGCUCGUAAUCUCUUCCUGCGCUAUGCCUCGAUAGCCCACAGGCUUAAUGUUUGGCUCAGCGAGAUCAUGAAAAAGGCUUCAUCACUGUUUUGUUUCAGGUGGGUCGUAGGCUUCCUCGCUCCCAUCUCGAAGACCUGCGUUGUAUCCGUUUGGCGCAAGCUGGACAUGAGUGUCUCAGUCCAGAUUGUCUCUCAACACCG... |
#!/usr/bin/env python
import sys
import os
import re
from lm import *
turn = 0
operator_sys = ''
if __name__ == "__main__":
assert len(sys.argv) == 5, "Usage: %s <lm data> <nbr class> <wrd2cls file> <cls2wrd file>" % sys.argv[0]
construct_word_class(sys.argv[1], int(sys.argv[2]), sys.argv[3], sy... |
"""Init file for Supervisor Security RESTful API."""
import logging
from typing import Any, Dict
from aiohttp import web
import voluptuous as vol
from ..const import ATTR_CONTENT_TRUST, ATTR_FORCE_SECURITY, ATTR_PWNED
from ..coresys import CoreSysAttributes
from .utils import api_process, api_validate
_LOGGER: loggi... |
#!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
class BTree:
nodes=[]
def __init__(self,value):
self.data=value
self.left=None
self.right=None
def insert(self,value):
if self.data:
if self.data>value:
if self.left==None:
self.left=BTree(value)
else:
self.left.insert(value)
elif self.data<value:
if self.right==None:
self.... |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from website.lib.base import BaseController, render
from sqlalchemy import func, and_
from website.model.user import User
import database as db
import json
log = logging.getLogger(... |
"""
This module provides the implementation for the intellimouse-ctl CLI.
"""
from __future__ import annotations
import argparse
from collections import namedtuple
import json
import traceback
import sys
from intellimouse import IntelliMouse
from intellimouse import ProIntelliMouse
from intellimouse import ClassicInte... |
"""
Java processes
"""
# On l implemente en Java appele par du Python car de toute facon Java est necessaire.
#
# (1) http://stackoverflow.com/questions/376201/debug-a-java-application-without-starting-the-jvm-with-debug-arguments
# http://docs.oracle.com/cd/E19205-01/819-5257/blabw/index.html
#
# Debugging a Program ... |
#!/usr/bin/python
class Note:
loc: str
date: str
text: str
def __init__(self, loc: str, date: str, text: str):
self.loc = loc
self.date = date
self.text = text
class Book:
title: str
author_first: str
author_last: str
year_published: str
notes: list[Note]
... |
import typer
from analysis.analysis_cache import AnalysisCache
from typing import *
from pathlib import Path
import numpy as np
import torch
from analysis import LMAnalysisOutputH5, AnalysisCache, model_path2name, model_name2path
from analysis.helpers import topk_token_diff
from tqdm import tqdm
import pandas as pd
imp... |
import os
import sys
from shapeworks import *
success = True
def addTest1():
img = Image(os.environ["DATA"] + "/la-bin.nrrd")
img += img
compareImg = Image(os.environ["DATA"] + "/la-bin-doubled.nrrd")
return img.compare(compareImg)
success &= utils.test(addTest1)
def addTest2():
img = Image(os.environ["... |
import re
numero_tarjeta = list(input("Ingresar el número de tarjeta: "))
digito_control = numero_tarjeta.pop()
numero_tarjeta.reverse()
procesar_digitos = []
for index, digito in enumerate (numero_tarjeta):
if index % 2 == 0:
doble_digito = int(digito)*2
if doble_digito > 9:
... |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.models.rgb.transfer_functions.red_log`
module.
"""
from __future__ import division, unicode_literals
import numpy as np
import unittest
from colour.models.rgb.transfer_functions import (
log_encoding_REDLog, log_decoding_REDLog, log_encoding_REDLogF... |
import zipfile
def sanitize(time):
return time.replace("-", ".").replace(":", ".")
try:
with zipfile.ZipFile("data/hfpy_ch5_data.zip") as zipFile:
print(zipFile.namelist())
players = []
for name in zipFile.namelist():
fileContent = zipFile.read(name).decode('utf-8')
... |
#!/usr/bin/env python
#
# Copyright (C) 2019
# Christian Limberg
# Centre of Excellence Cognitive Interaction Technology (CITEC)
# Bielefeld University
#
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistribu... |
from random import choices
nome =[]
cont = 0
for c in range(4):
cont += 1
nome.append(str(input(f'Digite {cont}º nome: ')))
escolha = choices(nome)
print(f'O nome escolhido foi: {escolha}')
|
import matplotlib as plt
def normal_pdf(x, mu=0, sigma=1):
sqrt_two_pi = math.sqrt(2 * math.pi)
return (math.exp(-(x-mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma))
xs = [x / 10.0 for x in range(-50, 50)]
plt.plot(xs,[normal_pdf(x,sigma=1) for x
plt.plot(xs,[normal_pdf(x,sigma=2) for x
plt.plot(xs,[normal_pdf(x,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
############################
# File Name: employee.py
# Author: One Zero
# Mail: zeroonegit@gmail.com
# Created Time: 2015-12-28 20:18:40
############################
class Employee:
"""所有员工的基类"""
empCount = 0
def __init__(self, name, salary):
self.n... |
#!/usr/bin/env python
data = { "key1" : "value1", "key2" : "value2" }
for k in data:
print "%s=%s" % (k,data[k])
|
from .client import PicnicAPI
__all__ = ["PicnicAPI"]
__title__ = "python-picnic-api"
__version__ = "1.0.0"
__author__ = "Mike Brink"
|
import sys
sys.path.append('../')
from pynyzo.clienthelpers import NyzoClient
def test_client_frozen(verbose=False):
client = NyzoClient()
res = client.get_frozen()
if verbose:
print("res", res)
assert "height" in res
assert "hash" in res
assert "timestamp" in res
def test_client_sen... |
from tornado.util import import_object
import tornado.ioloop
from monstro.conf import settings
from monstro.core.exceptions import ImproperlyConfigured
from monstro.db.migrations.models import Migration
from monstro.management import Command
class ApplyMigrations(Command):
def execute(self, arguments):
... |
import iocsv
import csv
import requests
repos = iocsv.read_csv_repos("projects.csv")
out = open('checked_projects.csv', 'w')
w_out = csv.writer(out)
def get(url):
try:
response = requests.get(url)
if response.status_code is 200:
return True
return False
except:
ret... |
import os
from typing import Any, Dict
import wandb
from common.types import Verbosity
from common.utils import save_compressed_pickle
from experiments.config import Config
class Logger:
"""
A basic logger that acts as the interface to log results
"""
def __init__(self, config: Config, verbose: V... |
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from .views import (
KeyQueryView, KeyQueryResultView, PrivateKeyListView, PublicKeyListView
)
urlpatterns = patterns(
'django_gpg.views',
url(
r'^delete/(?P<fingerprint>.+)/(?P<key_type>\w+)/$', 'key_delete',
... |
#
# Copyright (c) 2016 Shane Ambler
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disc... |
class DRChannel():
def __init__ ( self ):
self.instrmentID = ["I1"]
self.gain = []
def add_attenuator( self, temperature, attenuation ):
info={
"T":temperature,
"A":-attenuation,
}
self.gain.append(info)
... |
import argparse
from lazylawyer.database import table_docs, table_doc_contents, table_cases
from flask import Flask, render_template, request
from lazylawyer import helpers
from lazylawyer.nlp.curia_preprocessor import preprocess
from lazylawyer.nlp.curia_preprocessor import tokenize_and_process_metadata
from laz... |
import mysql.connector
def Admin(sid,name,add,gender,dob,age,email,con_1,con_2) :
mydb = mysql.connector.connect(host="localhost",user="root",passwd="v@run",database="Exam")
mycursor = mydb.cursor()
mycursor = mydb.cursor()
sql = "INSERT INTO students (Sid, Name, Address , Gender, DOB , Age, Email, Contact... |
import os
def get_base_url():
return os.environ.get(
'APCA_API_BASE_URL', 'https://api.alpaca.markets').rstrip('/')
def get_data_url():
return os.environ.get(
'APCA_API_DATA_URL', 'https://data.alpaca.markets').rstrip('/')
def get_credentials(key_id=None, secret_key=None, oauth=None):
... |
import cdislogging
from . import config
logger = cdislogging.get_logger(__name__, log_level="debug" if config.DEBUG else "info")
|
import os
import pydicom
from pydicom._dicom_dict import DicomDictionary
class DicomExplorer:
def __init__(self):
super(DicomExplorer, self).__init__()
self.files = []
@staticmethod
def is_dicom(file_path):
if not os.path.isfile(file_path):
return False
try:
... |
from Core.IFactory import IFactory
from Regs.Block_C import RC320
class RC320Factory(IFactory):
def create_block_object(self, line):
self.rc320 = _rc320 = RC320()
_rc320.reg_list = line
return _rc320
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2018-05-03 12:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import processlib.models
import uuid
class Migration(migrations.Migration):
initial = True
... |
LOOP_NUM = 100
i = 0
j = 0
for num in range(1, LOOP_NUM + 1, 1):
i += num * num
j += num
j = j * j
k = abs(i - j)
print(f"1 ~ {LOOP_NUM}: {i} - {j} = {k}")
if __name__ == "__main__":
pass
|
#!/usr/bin/env python
# coding: utf-8
# # 4. Causal Models
# ## 4.1 The do-operator and Interventional Distributions
#
# **potential outcome $Y(t)$的分布**
#
# $$P(Y(t)=y)\triangleq P(Y=y|do(T=t)) \triangleq P(y|do(t))$$
#
# **ATE(average treatment effect)**
#
# $$\mathbb{E}\left[Y|do(T=1)\right]-\mathbb{E}\left[Y|d... |
import bmesh
from ..generic import clamp_count
from ..frame import add_frame_depth
from ..fill import fill_panel, fill_glass_panes, fill_louver, FillUser
from ..arch import (
fill_arch,
create_arch,
add_arch_depth,
)
from ...utils import (
clamp,
FaceMap,
validate,
local_xyz,
valid_ngon... |
def merge(list1, list2):
i = 0
j = 0
out = []
for k in range(len(list1 + list2)):
if list1[i] < list2[j]:
out.append(list1[i])
i += 1
if i == len(list1):
out.extend(list2[j:])
return out
else:
out.append(list... |
"""Functions to ask the user questions.
These functions can be used to query the user for information.
"""
from .ansi import format_ansi
from . import cli
def yesno(prompt, *args, default=None, **kwargs):
"""Displays `prompt` to the user and gets a yes or no response.
Returns `True` for a yes and `False` f... |
from django.test import TestCase
from casexml.apps.case.mock import CaseFactory, CaseStructure
from casexml.apps.case.tests.util import delete_all_cases, delete_all_xforms
from casexml.apps.case.util import get_case_history
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from corehq.form_process... |
N, K = map(int, input().split())
ab = [tuple(map(int, input().split())) for _ in range(N)]
ab.sort()
t = 0
for a, b in ab:
t += b
if t >= K:
print(a)
break
|
"""
The class in this file is supported by the mmaction/tools/data/build_file_list
"""
import os
import glob
import json
from mmaction.tools.data.anno_txt2json import lines2dictlist
from mmaction.tools.data.parse_file_list import parse_directory
from plato.datasources.datalib.parse_datasets import build_list, obta... |
# -*- coding: utf-8 -*-
import unittest
from tir import Webapp
class BIXPROFILE(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGACFG','11/12/2018','T1','D MG 01 ')
inst.oHelper.SetLateralMenu('Ambiente > Extrator Bi > Perfil de Extração')
def test_BIX... |
from math import floor
num = int(input('Digite um número: '))
milhar = floor(num / 1000)
centena = floor((num - milhar*1000) / 100)
dezena = floor((num - milhar*1000 - centena*100) / 10)
unidade = floor((num - milhar*1000 - centena*100 - dezena*10) / 1)
print('''Milhares: {}
Centenas: {}
Dezenas: {}
Unidades: {}'''.... |
import torch
from data_loader import *
from loss import *
from model import *
import torch.utils.data as DATA
import os
BATCH_SIZE = 1
BASE_LR = 1e-3
G_LR = 1e-5
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device_ids = [0,2,3,4]
normalization_mean = torch.tensor([0.485, 0.456, 0.406])
norma... |
from requests import get
from requests_oauthlib import OAuth1
from configparser import ConfigParser
from codecs import open
from os.path import dirname
from uitdatabank.searchresults import SearchResults
class UiTdatabank:
"""
.. autosummary::
:nosignatures:
find
construct_parameters_... |
from sp_api.base.credential_provider import CredentialProvider
class BaseClient:
scheme = 'https://'
method = 'GET'
content_type = 'application/x-www-form-urlencoded;charset=UTF-8'
user_agent = 'python-sp-api'
def __init__(self, account='default', credentials=None):
self.user_agent += '0.... |
#!/usr/bin/env python3
import csv
import ast
import os
import matplotlib.pyplot as plt
from collections import defaultdict, namedtuple
parameter_tuples = {
"Flat": namedtuple("FlatParameters", []),
"IVF": namedtuple("IVFParameters", ["nprobe", "size"]),
"KMeans": namedtuple("KMeansParameters", ["U", "bnb"... |
from server import app
from flask import render_template, Flask, jsonify, redirect, url_for, request, sessions
from http.cookies import SimpleCookie
import bcrypt
import ibm_db
import json
import secrets
from flask_cors import CORS
import datetime
import os
CORS(app)
conn = ibm_db.connect(
'DATABASE=BLUDB;'
... |
import os
import numpy as np
from PIL import Image
import foolbox
import inspect
from mlsploit import Job
from mlsploit.dataset.datasets import ImageClassificationDatasetWithPrediction
from data import get_or_create_dataset, recreate_image
from models import CUSTOM_MODEL, load_foolbox_zoo_model, load_pretrained_mode... |
import numpy as np
from collections import defaultdict
class Data:
def __init__(self, data_dir='./data/JF17K/'):
print('Loading the string facts from raw data...')
train_strfacts, valid_strfacts, test_strfacts, rel_list, ent_list, self.max_ary = self.load_strfacts(data_dir=data_dir)
self.re... |
from copy import deepcopy
import os
from tempfile import SpooledTemporaryFile
from requests import Session
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from ocd_backend.settings import TEMP_DIR_PATH, USER_AGENT
from ocd_backend.enrichers import BaseEnricher
from ocd... |
from django.db.models import Q
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from shop.api.pagination import ArticlePageNumberPagination
from shop.api.serializers import ArticleListSerializer
from ... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
from azure_devtools.scenario_tests import GeneralNameReplacer, patch_time_sleep_api, RequestUrlNormalizer
from devtools_testutils.azure_testcase import AzureT... |
'''
https://leetcode.com/problems/string-to-integer-atoi/
8. String to Integer (atoi)
Medium
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character, takes... |
#!/usr/bin/env python3
#
# https://publicwiki.deltares.nl/display/~baart_f/2011/10/23/Calling+fortran+from+python
#
import numpy as np
from ctypes import (
CDLL,
POINTER,
ARRAY,
c_void_p,
c_int,
byref,
c_double,
c_char,
c_char_p,
create_string_buffer,
)
from numpy.ctypeslib impo... |
from kaira.app import App
from kaira.response import response
from kaira.log import log
app = App()
def handler1_on_request(request):
"""After request"""
log.info("Handler 1: On request. Request path: %s" % request.path)
def handler2_on_request(request):
"""After request"""
log.info("Handler 2:... |
import torch.utils.data as data
import torch
class DataIterator(object):
def __init__(self, dataloader):
self.dataloader = dataloader
self.iterator = enumerate(self.dataloader)
def __next__(self):
try:
_, data = next(self.iterator)
except Exception:
sel... |
# Copyright (C) 2019 Intel Corporation
#
# 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 wri... |
"""empty message
Revision ID: 1ba6bf86c89f
Revises: 4dcd1257e2a0
Create Date: 2020-05-26 22:31:41.675455
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1ba6bf86c89f'
down_revision = '4dcd1257e2a0'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from tensorflow import keras
from nn_meter.builder.backend_meta.fusion_rule_tester import BaseTestCase
class MyTestCase(BaseTestCase):
name = 'MyTestCase'
cases = {
'case1': ['dwconv_add', 'dwconv', 'dwconv', 'add', 'relu'],
'case2': ['dwconv_add_add', 'dwconv', 'dwconv', 'relu'],
}
tru... |
from datetime import datetime
from utc import utc
import sys
def get_timestamp():
timestamp = datetime.now(utc).strftime("[%d/%b/%Y:%H:%M:%S %z]")
return timestamp
def log_stdout(msg):
sys.stdout.write(get_timestamp() + " [info] " + msg + "\n")
sys.stdout.flush()
def log_stderror(msg):
sys.stderr... |
m = int(input())
d = int(input())
if m < 2:
print('Before')
elif m > 2:
print('After')
elif d < 18:
print('Before')
elif d > 18:
print('After')
else:
print('Special')
|
from .serializers import RoomSerializer, CreateRoomSerializer, UpdateRoomSerializer
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
from .models import Room
from spotify.utils import skip_song
bad_he... |
"""
Common utilities for testing.
Copyright 2020. Siwei Wang.
"""
from typing import Iterable, Tuple, List
from math import comb
from itertools import product
from graph import Graph
def len_iter(iterable: Iterable) -> int:
"""Count number of entries in iterable."""
return sum(1 for _ in iterable)
def chec... |
from __future__ import absolute_import
from django.test import TestCase
class EmptyTests(TestCase):
def test_this_test_is_run(self):
u"""Test that the test suite is running this tests."""
self.assertTrue(True)
def test_GDPR_app_is_reachable(self):
u"""Test that GDPR app is reachable."... |
# Generated by Django 3.0.5 on 2020-05-10 15:40
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinics', '0015_clinic_time_slots'),
]
operations = [
migrations.AlterField(
model_name='clinic',
na... |
"""IPython extension that activates special IPython notebook features of Nengo.
At the moment this only activates the improved progress bar.
Use ``%load_ext nengo.ipynb`` in an IPython notebook to load the extension.
Note
----
This IPython extension cannot be unloaded.
"""
from nengo.rc import rc
from nengo.utils.... |
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.template import context, loader, TemplateDoesNotExist
from django.template.context import RequestContext
from .models import RadioStation, Office
#from .form import MyForm
# Create your views here.
def in... |
from .params_init import dict_portfolio, time_params, Mu, Rfree, Std, det_income, norm_factor, age_plot_params
import numpy as np
from HARK.utilities import approxNormal
time_params['Age_born'] = 27
dict_portfolio['T_age'] = time_params['Age_death'] - time_params['Age_born'] + 1
dict_portfolio['T_cycle'] = time_params[... |
{
'targets': [
{
'target_name': 'FFmpegLibNode',
'sources':[
'FFmpegLibNode/FFmpegLibNode.cc',
'FFmpegLibNode/FFmpegEngine.cc'
],
'include_dirs':[
'<(module_root_dir)/include/',
'<(module_root_dir)/FFmpegLibNode/',
"<!(node -e \"require('nan')\")"
... |
import logging
import lldb
from . import handles
log = logging.getLogger('disassembly')
MAX_INSTR_BYTES = 8 # Max number of instruction bytes to show.
NO_SYMBOL_INSTRUCTIONS = 32 # How many instructions to show when there isn't a symbol associated
# with the PC location.
# bisect_left wit... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.encoding import python_2_un... |
import matplotlib.pyplot as plt
from __init__ import ROOT_DIR
from pathlib import Path
import pandas as pd
import os
def export(dataset_dirname, scores):
"""
export pd.Dataframe or plt.Figure to csv or png files respectively
:param dataset_dirname: the directory name containing the dataset. e.g.: dirname ... |
from transformers import TFGPT2Model, GPT2Config
import tensorflow as tf
from transformers import modeling_tf_utils
import numpy as np
import utils
import sys
import os
from collections import defaultdict
EPS = 1e-6
NUM_CLASSES = 58
NUM_IDX = NUM_CLASSES + 2
NUM_SUBTYPE = 35
NUM_SIZE = 3
NUM_FLIP = 2
MAX_NUM_TOKE... |
config = {
'url': 'http://olymp.sumdu.edu.ua:8080/tren.php', # sample page
'db': 'acmrating.db'
}
|
import json
from colorama import Fore, Back, Style
import sys
# take index and file name
idx, fn = sys.argv[1:]
with open(fn) as f:
d = json.load(f)
p = d["docs"][int(idx)]
print(Style.BRIGHT + Fore.BLUE + "TITLE: " + Fore.WHITE + p["title"][0])
print(Style.BRIGHT + Fore.BLUE + "AUTHOR: " + Fore.WHITE + p["firs... |
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
unique_set = set()
for num in nums:
if len(unique_set & set([num])):
unique_set.remove(num)
else:
unique_set.add(num)
return list(unique_set) |
from itertools import combinations
from sys import maxsize
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
A = [2, 2, -1, -5, 12, 1]
max = - maxsize
sum_ = list()
sum_.append(A[0])
obj_tree = Node(... |
"""Implements a login manager and an user loader to control a session."""
from flask_login import LoginManager
from user.models import User
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id):
"""Load a user from its id"""
return User.query.get(user_id)
|
from aiohttp import web
from aiohttp_security import check_authorized, forget
from models import User
async def set_email(request: web.Request):
user: User = await check_authorized(request)
data = await request.json()
user.email = data["email"]
user.save()
return web.HTTPOk()
async def set_pass... |
from dash import html
from dash import dcc
dashboard_modal = html.Div([
html.I(className="far fa-times-circle", id="btn-fechar-modal"),
html.H2("Envio de relatório por e-mail", className="modal__header"),
html.Hr(className="modal__line"),
html.Div([
html.Div([
html.H3("E-mai... |
import os
from Bio import Entrez
#Poskytnúť email
Entrez.email = "brunix@upcmail.sk"
with Entrez.einfo(db="nucleotide") as handle:
record = Entrez.read(handle)
for field in record["DbInfo"]["FieldList"]:
print("%(Name)s, %(FullName)s, %(Description)s" % field)
with Entrez.esearch(db="nucleotide", term="SARS-C... |
# Author: Simulan
from direct.showbase.ShowBase import ShowBase
from direct.stdpy import threading2
from direct.filter.CommonFilters import CommonFilters
from panda3d.core import load_prc_file_data
from panda3d.core import BitMask32
from panda3d.core import Shader, ShaderAttrib
from panda3d.core import Transfo... |
# leia o sexo, aceitando apenas M ou F,
#em caso de erro solicitar a digitação novamente até o valor correto
sexo = str(input("Digite o seu sexo [F/M]: ")).strip().upper()[0]
while sexo not in "FfMm":
sexo = str(input("Dado inválido.\nDigite o seu sexo [F/M]: ")).strip().upper()[0]
print("Agradecemos a partici... |
"""
Central component of this autoscaling system.
@author: fernandez
"""
import math
from time import time, sleep
from conpaas.services.webservers.manager.autoscaling import log
from conpaas.services.webservers.manager.autoscaling.performance import StatUtils
from conpaas.services.webservers.manager.autoscaling.cos... |
# coding=utf-8
import library
import re
import yaml
import netaddr
import os
import sys
import csv
from collections import defaultdict
import time
print("Post Deployment - Hayward")
SITE = raw_input("School Code: ").upper()
# Checks for site yaml file
if not os.path.isfile(os.path.sep.join(['yamls', SITE + '.yml'])):... |
import glob
import logging
from optparse import OptionParser
import os
import sys
import json
from lxml import etree
from collections import Counter
# ------------------ setting up logger ------------------------------
# create logger with 'python_sample_analysis_tool'
logger = logging.getLogger('python_sam... |
__author__ = 'Izzat'
import wx
import wx.lib.agw.floatspin as FS
import OpenGL.GL as gl
import OpenGL.GLU as glu
from objects import Frame, RevoluteJoint, FixedJoint, PrismaticJoint
from wx.glcanvas import GLCanvas
from numpy import sin, cos, radians, pi, inf, nan
from math import atan2
from sympy import Expr
from core... |
import fractions
def funkcija33():
produkt = 1
for i in range(10,100):
for j in range(i+1, 100):
skupne_stevke = list(set(str(i))&set(str(j)))
if len(skupne_stevke) != 0:
if skupne_stevke[0] != '0':
stevec = list(str(i))
im... |
"""
composite pattern in python
"""
class Component:
"""Abstract class"""
# pylint: disable=unused-argument
def __init__(self, *args, **kwargs):
print("initializing")
class Child(Component): # Inherits from the abstract class, Component
"""Concrete class"""
def __init__(self, *args, *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.