text string | size int64 | token_count int64 |
|---|---|---|
# Goal:
#
# Find the sums of subsections of an array
# Change an element of the array and don't recalculate everything
if __name__ == '__main__':
arr = [1,2,3,4,5]
print('here') | 195 | 73 |
# encoding: utf-8
"""
Visualization functions for features and predictions.
Copyright 2016 Matthias Leimeister
"""
import numpy as np
from feature_extraction import load_raw_features
from evaluation import post_processing
import matplotlib.pyplot as plt
import pickle
def visualize_predictions():
"""
... | 2,658 | 943 |
from time import time
from datetime import datetime
from .digest_tokens import DigestTokens
class TokenBuilder:
application_id = None
secret = None
token = {}
def __init__(self):
"""Token builder helper class to create digest tokens that
can be used with the Phenix platform.
... | 7,468 | 1,965 |
# Generated by Django 3.2.5 on 2021-07-26 18:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myhood', '0009_business_created_on'),
]
operations = [
migrations.RemoveField(
model_name='neighborhood',
name='occupants_co... | 343 | 121 |
from flask import Blueprint, Response, abort, render_template
from utils import blog as blog_utils
from utils import tags as tag_utils
bp = Blueprint("blog", __name__)
@bp.route("/", methods=["GET"])
def blog():
return blog_utils.respond_blog_list()
@bp.route("/post_<post_name>", methods=["GET"])
def blog_pos... | 954 | 332 |
import collections
import subprocess
class Runner(object):
"""Base object to run linters."""
_runners = collections.defaultdict(lambda: ByFileRunner)
def __init__(self):
"""Runner constructor"""
pass
@classmethod
def new_runner(cls, name):
"""Return an instance of a Runn... | 3,208 | 826 |
from django.db import models
# Create your models here.
class TestModel(models.Model):
test_field = models.IntegerField(default=0)
| 138 | 42 |
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
dairy = {}
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
... | 590 | 185 |
import logging
from telegram.error import (
TelegramError,
Unauthorized,
BadRequest,
TimedOut,
ChatMigrated,
NetworkError,
)
from .badrequest import badrequest
from .chatmigrated import chatmigrated
from .networkerror import networkerror
from .telegramerror import telegramerror
from .timedout im... | 1,580 | 452 |
import functools
from typing import Callable, TypeVar
import jax
import jax.numpy as jnp
def scan(f, s, as_):
bs = []
for a in as_:
s, b = f(s, a)
bs.append(b)
return s, jnp.concatenate(bs)
KwArg = TypeVar('KwArg')
@functools.partial(jax.jit, static_argnums=(0, 1, 2, 3, 4, 5, 6, 7))
d... | 2,590 | 1,072 |
import cv2 as cv
from matplotlib import pyplot as plt
img=cv.imread('maliao.jpg', cv.IMREAD_COLOR)
plt.imshow(img)
plt.show() | 131 | 54 |
# -*- coding: utf-8 -*-
"""
Code to rank packages from a search in APT using Levenshtein
"""
from apt import Cache
from Levenshtein import ratio
from exact import Pack, _parser
from multiprocessing.pool import ThreadPool as Pool
_MAX_PEERS = 20
def Thread_Rank(k):
pack = _args[0]
item = Pack()
item.... | 1,713 | 544 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module defines an interface to run matlab codes from python.
"""
import os
import time
import sys
import logging
import pathlib
import numpy as np
import scipy.io as sio
_logger = logging.getLogger(__name__)
def matlab_interface(program, dataDico):
"""Int... | 4,991 | 1,526 |
#!/usr/bin/env python3
from __future__ import print_function
import sys
import errno
import statistics
import serial
from binho.utils import log_silent, log_verbose, binhoArgumentParser
from binho.errors import DeviceNotFoundError, CapabilityError
def main():
# Set up a simple argument parser.
parser = bi... | 4,719 | 1,341 |
# -*- coding: utf-8 -*-
from flask import url_for, current_app, g
from werkzeug import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from . import db
from app.exceptions import ValidationError
from datetim... | 6,349 | 2,044 |
import pandas as pd
import sys
import numpy as np
import matplotlib.pyplot as plt
T = pd.read_csv('GenTrends_cat.csv')
T.index = T.cat
T = T.drop('cat', axis=1)
tT = np.transpose(T)
tT.loc[:,'Cycle'] = [i.strip('_vars').strip('_mean') for i in list(tT.index)]
tT_mean = tT.ix[0::2,:]
tT_var = tT.ix[1::2,:]
cats = [i ... | 1,098 | 489 |
print("\033[92m")
import os
import urllib2
import sys
print("---------------------------------------------")
os.system("figlet web info")
print("----------------------------------------------")
print("\033[91m")
print("#############################################")
print(" Coded by B4t33n ... | 1,094 | 380 |
from viper import *
import inspect
def GetSource(func):
lines = inspect.getsource(func)
print(lines) | 109 | 34 |
""" django models utilities"""
from django.db import models
class CRideModel(models.Model):
""" Comparte Ride base model
CRideModel acts as an abstract base class from which every
other model in the project will inherit. This class provides
every table with the following attributes:
+ creat... | 925 | 240 |
import boto3
import json
import uuid
from datetime import datetime
import logging
# Update the root logger to get messages at DEBUG and above
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger("botocore").setLevel(logging.CRITICAL)
logging.getLogger("boto3").setLevel(logging.CRITICAL)
logging.getLogger("url... | 1,811 | 537 |
#!/usr/bin/env python3
from argparse import ArgumentParser, ArgumentError
import re, sys
# Define a custom argument type `interval_int` to properly parse arguments
# https://docs.python.org/3/library/argparse.html#type
def interval_int(arg):
"""
Validate given interval and return as list
"""
pattern ... | 2,735 | 794 |
from typing import Tuple
from abc import abstractmethod
from torch import Tensor
from torch.nn import Module
class BaseDiscriminator(Module):
@abstractmethod
def forward_(self, z: Tensor) -> Tuple[Tensor, Tensor]:
raise NotImplementedError
def forward(self, z: Tensor) -> Tuple[Tensor, Tensor]: #... | 388 | 121 |
inputFile = "day6/day6_1_input.txt"
# https://adventofcode.com/2021/day/6
if __name__ == '__main__':
print("Lanternfish")
with open(inputFile, "r") as f:
fishArray = [int(num) for num in f.read().strip().split(",")]
# for part2... not needed to read array again from file
origFishArray = fishA... | 1,484 | 498 |
# -*- coding: utf-8 -*-
# @Time : 2018/9/21 17:21
# @Author : HLin
# @Email : linhua2017@ia.ac.cn
# @File : Voc_Dataset.py
# @Software: PyCharm
import PIL
import random
import scipy.io
from PIL import Image, ImageOps, ImageFilter
import numpy as np
import cv2
import os
import torch
import torch.utils.data as ... | 7,915 | 2,654 |
#!/usr/local/bin/python3.4
#
# Avi Persin, Revision 2016-01-06
# grid.py
"""
grid YYYY-MM [v2-file]
Display gridded anomalies as SVG file.
"""
# Regular expression used to match/validate the "when" argument.
RE_WHEN = r'(\d{4})-(\d{2})'
def map(when, inp, out):
"""Take a cccgistemp subbox file in V2 mean form... | 2,341 | 905 |
from fastapi import FastAPI
from transformers import ElectraModel, ElectraTokenizer
from koelectra_fine_tuner import KoelectraQAFineTuner
from nlu_flow.preprocessor.text_preprocessor import normalize
import torch
import faiss
import dill
app = FastAPI()
is_ready = False
#load chitchat_retrieval_model
model = None... | 1,460 | 517 |
#!/usr/bin/env python
# coding: utf-8
# In[8]:
import requests
import re
import time
import json
def get_one_page(url):
# 根据源码分析,构造请求头
headers = {
# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) '
# 'Chrome/52.0.2743.116 S... | 930 | 411 |
#==============================================================================
# load a beam and write it
#==============================================================================
import pyansys
from pyansys import examples
# Sample *.cdb
filename = examples.hexarchivefile
# Read ansys archive file
archive = p... | 2,434 | 740 |
# included from libs/mincostflow.py
"""
Min Cost Flow
"""
# derived: https://atcoder.jp/contests/practice2/submissions/16726003
from heapq import heappush, heappop
class MinCostFlow():
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.pos = []
def add_edge(s... | 5,401 | 2,151 |
# Generated by Django 3.1.12 on 2021-07-13 00:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reo', '0111_auto_20210708_2144'),
]
operations = [
migrations.RenameField(
model_name='sitemodel',
old_name='year_one_emiss... | 1,512 | 518 |
INITIAL = 'INITIAL'
CONNECTING = 'CONNECTING'
ESTABLISHED = 'ESTABLISHED'
ACCEPTED = 'ACCEPTED'
DECLINED = 'DECLINED'
ENDED = 'ENDED'
ERROR = 'ERROR'
| 150 | 80 |
# Static data class for character stats
class Zhongli:
level = 90
talentLevel = 8
# Base stat values
baseHP = 14695
baseATK = 251
baseCritRATE = 0.05
baseCritDMG = 0.5
# Ability MVs and frame counts
class Normal: # Normal attack spear kick hop combo
frames = 140
#m... | 901 | 396 |
import os
import sys
from instance.config import DATABASE_URI
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlche... | 369 | 127 |
"""
accounts.profile.serializers
============================
Serializers file for a basic Accounts App
"""
from rest_framework import serializers
from .models import AccountsUser
class AccountsUserSerializer(serializers.ModelSerializer):
class Meta:
model = AccountsUser
| 302 | 78 |
import numpy as np
import sys
import tensorflow as tf
slim = tf.contrib.slim
def convertNHWC2NCHW(data, name):
out = tf.transpose(data, [0, 3, 1, 2], name=name)
return out
def convertNCHW2NHWC(data, name):
out = tf.transpose(data, [0, 2, 3, 1], name=name)
return out
def denormalize(batch_input, lo... | 20,551 | 7,272 |
import os
from musicscore.musictree.treescoretimewise import TreeScoreTimewise
from musurgia.unittest import TestCase
from musurgia.fractaltree.fractalmusic import FractalMusic
path = str(os.path.abspath(__file__).split('.')[0])
class Test(TestCase):
def setUp(self) -> None:
self.fm = FractalMusic(temp... | 829 | 294 |
from setuptools import setup
if __name__ == '__main__':
setup(name='foo', version='1.0.0')
| 96 | 36 |
# -*- coding: utf-8 -*-
"""
Description
-----------
This module defines the :obj:`ParaMol.Objective_function.Properties.regularization.Regularization` class, which is a ParaMol representation of the regularization property.
"""
import numpy as np
from .property import *
# ------------------------------------------... | 8,324 | 2,112 |
def octalToDecimal(octString: str)->str:
octString = str(octString).strip()
if not octString:
raise ValueError("empty string was passed to function")
isNegative = octString[0] == "-"
if isNegative:
octString = octString[1:]
if not all(0 <= int(char) <= 7 for char in octString):
... | 643 | 195 |
import os,json
import requests
BASE_URL = 'http://epfl.elasticsearch.spinn3r.com/content*/_search'
BULK_SIZE = 100
SPINN3R_SECRET = os.environ['SPINN3R_SECRET']
HEADERS = {
'X-vendor': 'epfl',
'X-vendor-auth': SPINN3R_SECRET
}
query = {
"size": BULK_SIZE,
"query":{
"bool":{
"must":{
... | 879 | 342 |
import time
import requests
from core.utils.parser import Parser
from core.utils.helpers import Helpers
from core.models.plugin import BasePlugin
class HIBP(BasePlugin):
def __init__(self, args):
self.args = args
self.base_url = "https://haveibeenpwned.com/api/v2/breachedaccount"
self.url... | 1,672 | 503 |
from re import S
from flask import render_template, redirect, url_for, flash, request
from flask_paginate import Pagination, get_page_parameter
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_babel import _, lazy_gettext as _l
from flask_login import curre... | 2,099 | 668 |
# Copyright 2018 Google 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 writing, ... | 835 | 247 |
# Copyright (c) 2019 Works Applications Co., Ltd.
#
# 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 a... | 8,072 | 2,375 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import base64
try:
import json
except ImportError:
import simplejson as json
from behave.formatter.base import Formatter
class JSONFormatter(Formatter):
name = 'json'
description = 'JSON dump of test run'
dumps_kwargs = {}
def _... | 4,487 | 1,271 |
"""
Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
from torch import nn
from torch.autograd import Variable
import torch
import torch.nn.functional as F
import utils
import functools
try:
from... | 54,368 | 18,450 |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 5 14:01:56 2019
@author: Angelo Antonio Manzatto
This implementation use ST-ResNet for inflow / outflow bike prediction on the city of NY
Article: https://arxiv.org/pdf/1610.00081.pdf
References and credits:
Junbo Zhang, Yu Zheng, Dekang Qi. Deep Spatio-Temporal Resid... | 24,084 | 8,231 |
import argparse
import csv
import json
import sklearn.manifold
import torch
def parse_arguments():
parser = argparse.ArgumentParser(description="MiniConf Portal Command Line")
parser.add_argument("papers", default=False, help="paper file")
parser.add_argument("embeddings", default=False, hel... | 802 | 280 |
class Environment(object):
def ask(self, prompt, default=None, starting=None):
pass
def ask_values(self, prompt, values, default=None, starting=None):
pass
def ask_directory(self, prompt, default=None, starting=None):
pass
def ask_completion(self, prompt, values, starting=Non... | 1,964 | 616 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
####################################<<<<Breast_cancer_prediction>>>>>>####################################
# In[ ]:
#part(1)--By:Manar Moeanse
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
DB = pd.read_csv('Breast_c... | 1,838 | 854 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 17:13:54 2017
Should have similar functions as galfit and allow a model object to use functions to
calculate chisq and optimse using standard optimisation.
@author: rs548
"""
import pyprofit
def optimise():
| 290 | 107 |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
import unittest
from branch_utility import BranchUtility
from fake_url_fetcher import FakeUrlFetcher
from obj... | 6,061 | 1,892 |
from flask import Flask
from flask_restful_swagger_2 import Api
from resources.userResource import UserListResource, UserResource, UserLoginResource
from resources.imageResource import ImageListResource, ImageResource
from resources.environmentResource import EnvironmentListResource, EnvironmentResource, UserEnvironmen... | 6,818 | 1,920 |
x = float(input("Enter Number: "))
if(x % 2) == 0 and x > 0:
print("The number you entered is positive and even.")
elif(x % 2) == 0 and x < 0:
print("The number you entered is negative and even.")
elif(x % 2) != 0 and x > 0:
print("The number you entered is positive and odd.")
elif(x % 2) != 0 and x < 0:
... | 427 | 148 |
"""
Created on Dec 16 2021
@author: Ilan Rosen
Poisson equation solver for the Hall effect.
Includes classes for Hall bars, Hall bars in a nonlocal geometry, and Corbino disks.
The Hall bar class has build in methods for longitudinal and Hall 4-probe resistance measurements.
Plotting functions assume coordinates are in... | 18,763 | 8,146 |
import os
import simplejson as json
from boutiques.logger import raise_error
# Parses absolute path into filename
def extractFileName(path):
# Helps OS path handle case where "/" is at the end of path
if path is None:
return None
elif path[:-1] == '/':
return os.path.basename(path[:-1]) + ... | 2,078 | 635 |
import re
def word_count(s):
d = {}
s = re.sub('[^0-9a-zA-Z]+', ' ', s.lower()).split()
for word in s:
if word in d:
d[word] += 1
else:
d[word] = 1
return d
| 214 | 85 |
from django import forms
from core.models import Profile
def get_sender_choices():
return list(Profile.objects.all().values_list('pk', 'inn'))
class TransactionForm(forms.Form):
sender = forms.ChoiceField(
label='Отправитель',
help_text='Выберите ИНН отправителя',
choices=get_sender... | 1,913 | 540 |
from fabric2 import Connection
from fabric2 import task
from fabric2 import config
import os
import time
from xml.etree import ElementTree as ET
import uuid
import glob
import json
import urllib.parse
import io
workflow_components = ['input.xml', 'binding.xml', 'flow.xml', 'result.xml', 'tool.xml']
@task
def release_... | 19,736 | 6,029 |
import unittest
from electropy.charge import Charge
import numpy as np
from electropy import volume
class VolumeTest(unittest.TestCase):
def setUp(self):
self.position_1 = [0, 0, 0]
self.position_2 = [-2, 4, 1]
self.charge = 7e-9
def tearDown(self):
pass
# Potential fun... | 5,529 | 1,970 |
"""
AiiDA Plugin Template
Adapt this template for your own needs.
"""
__version__ = '0.3.4'
| 94 | 38 |
import unittest
from concourse_common import testutil
import out
class TestOut(unittest.TestCase):
def test_invalid_json(self):
testutil.put_stdin(
"""
{
"source": {
"user": "user",
"password": "password",
"host": "hos... | 794 | 211 |
#-*- coding=utf-8 -*-
import urllib2, time, datetime
from lxml import etree
import sqlite3,time
class getProxy():
def __init__(self):
self.user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
self.header = {"User-Agent": self.user_agent}
self.dbname="proxy.db"
... | 2,877 | 1,165 |
import sys
def content(name):
try:
with open('../apama-mqtt-connect/monitors/' + str(name) + '.mon', 'r') as file:
data = file.read()
return data
except:
return []
| 214 | 68 |
#!/usr/bin/env python
import pytest
from .test_data import get_search_test_cases, search_catalog_get_stac_ids
from capella_console_client import client
from capella_console_client.validate import _validate_uuid
from capella_console_client.search import _paginated_search
@pytest.mark.parametrize("search_args,expecte... | 1,046 | 351 |
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME... | 6,514 | 2,266 |
from . import adskPrepareRender
import maya.cmds as cmd
import maya
| 69 | 25 |
#Ask user for name
name = input("What is your name?: ")
#Ask user for the age
age = input("How old are you? ")
#Ask user for city
city = input("What city do you live in? ")
#Ask user what they enjoy
hobbies = input("What are your hobbies?, What do you love doing? ")
#Create output text using placeholders to concat... | 503 | 158 |
"""These are utilities designed for carefully handling communication between
processes while multithreading.
The code for ``pool_imap_unordered`` is copied nearly wholesale from GrantJ's
`Stack Overflow answer here
<https://stackoverflow.com/questions/5318936/python-multiprocessing-pool-lazy-iteration?noredirect=1&lq... | 2,568 | 768 |
#!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_flcdrpf_ckl_mmp_cds
@file marine-integrations/mi/dataset/parser/test/test_flcdrpf_ckl_mmp_cds.py
@author Mark Worden
@brief Test code for a flcdrpf_ckl_mmp_cds data parser
"""
import os
from nose.plugins.attrib import attr
from mi.core.exce... | 4,786 | 1,631 |
"""Print the metadata for one or more Python package distributions.
Usage: %prog [options] path+
Each 'path' entry can be one of the following:
o a source distribution: in this case, 'path' should point to an existing
archive file (.tar.gz, .tar.bz2, or .zip) as generated by 'setup.py sdist'.
o a binary distrib... | 6,602 | 1,826 |
# Generated by Django 3.0.8 on 2020-08-16 18:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('app_jumanji', '0006_auto... | 2,109 | 662 |
import os
import pytest
import json
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.fixture()
def waited_failed_task_name(host):
all_variables = host.ansible.get_variables()
return all_v... | 1,135 | 386 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Visualization
==================
This is module contains a simple visualizer to show event lists along with the audio.
The visualizer can show multiple event lists for the same reference audio allowing the
comparison of the reference and estimated event lists.
.. imag... | 54,744 | 16,322 |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render,redirect, render_to_response
from .models import *
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse
from django.http import HttpRespo... | 498 | 134 |
class Info:
"""
Allows to print out information about the application.
"""
def commands():
print('''Main modules:
imu | Inertial Measurement Unit (GPS, gyro, accelerometer)
gps | GPS
gyro | Gyroscope
accel | Accelerometer
... | 1,131 | 350 |
# -*- encoding: utf-8 -*-
"""
search_indexex.py: Creacion de los indices de busqueda.
@author Camilo Ramírez
@contact camilolinchis@gmail.com
camilortte@hotmail.com
@camilortte on Twitter
@copyright Copyright 2014-2015, RecomendadorUD
@license GPL
... | 2,095 | 678 |
''' Handling the data io '''
from torchvision import transforms, datasets
import numpy as np
import zipfile
from io import open
import glob
from PIL import Image, ImageOps
import os
import string
# Read data
def extractZipFiles(zip_file, extract_to):
''' Extract from zip '''
with zipfile.ZipFile(zip_file, ... | 1,968 | 630 |
# -*- coding: utf-8 -*-
"""Tests for the metaregistry."""
import unittest
import bioregistry
from bioregistry.export.rdf_export import metaresource_to_rdf_str
from bioregistry.schema import Registry
class TestMetaregistry(unittest.TestCase):
"""Tests for the metaregistry."""
def test_minimum_metadata(self... | 4,072 | 1,243 |
print('Analisador de números')
print('=-=' * 15)
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
if n1 > n2:
print('O número {} é maior que o número {}'.format(n1, n2))
elif n2 > n1:
print('O número {} é maior que o número {}'.format(n2, n1))
else:
print('Os dois v... | 341 | 130 |
from setuptools import setup, find_packages
setup(
name="symbulate",
version="0.5.5",
description="A symbolic algebra for specifying simulations.",
url="https://github.com/dlsun/symbulate",
author="Dennis Sun",
author_email="dsun09@calpoly.edu",
license="GPLv3",
classifiers=[
... | 750 | 236 |
from __future__ import print_function
import gzip
import os
import sys
from decimal import Decimal
def calculate_gc(inpath):
inf = gzip.open(inpath) if inpath.endswith('.gz') else open(inpath)
ttl_bases = 0
gc_bases = 0
for i, l in enumerate(inf):
if i % 4 == 1:
s = l.strip().uppe... | 833 | 313 |
from typing import Optional, TypeVar
from .event import EventBlocker
T = TypeVar('T')
class Blocker(EventBlocker):
def __init__(self):
self.__block = False
self.__block_list: [T] = []
def block(self):
self.__block = True
def unblock(self):
self.__block = False
def ... | 725 | 231 |
import pulsar as psr
def load_ref_system():
""" Returns chlorophyll_c2 as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C -2.51105 2.48309 -0.00367
C -1.01315 4.06218 0.09798... | 4,239 | 2,164 |
import os
import time
import sys
import random
user_pass = ('''admin
admi
admin
universo
html
veggeta
Admin
bados
free-fire
royale
clang
free
fire
anonimo
anonimous
anoni
bills
anonymous
Aanonimous
pass
password
wordlist
kali
linux
kali-linux
start
Hacker
parrot
ubuntu
blacken
redhat
deepin
lubuntu
depin
gogeta
hacke... | 14,669 | 5,348 |
import itertools
import math
import pprint
import sys
import typing
import map_funcs
GOOGLE_EARTH_AIRPORT_IMAGES = {
'GoogleEarth_AirportCamera_C.jpg' : {
'path': 'video_images/GoogleEarth_AirportCamera_C.jpg',
'width': 4800,
'height': 3011,
# Originally measured on the 100m legend... | 5,637 | 2,261 |
import pymongo
from datetime import datetime, timedelta
from mongo_queue.job import Job
from uuid import uuid4
from pymongo import errors
DEFAULT_INSERT = {
"attempts": 0,
"locked_by": None,
"locked_at": None,
"last_error": None
}
class Queue:
def __init__(self, collection, consumer_id, timeout=3... | 4,527 | 1,334 |
print('''
Exercício 71 da aula 15 de Python
Curso do Guanabara
Day 24 Code Python - 23/05/2018
''')
print('{:^30}'.format('BANCO DO CIRINO'))
print('=' * 30)
n = int(input('Qual o valor para sacar? R$ '))
total = n
nota = 50 # começar de cima para baixo na estrutura
qtdNota = 0
while True:
if tota... | 776 | 328 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils.validation import check_random_state
from sklearn.datasets import fetch_olivetti_faces
from sklearn.externals import joblib
rng = check_random_state(21)
dataset = fetch_olivetti_faces()
X = dataset.images.reshape(dataset.images.shape[0], -1)
trai... | 1,823 | 712 |
TONES = list('CDEFGAB')
def build_offset_list(scale):
iter_scale = iter(scale)
first = next(iter_scale)
base = first.tonal_offset
last_diff = 0
tonal_offsets = []
for dt in iter_scale:
diff = dt.tonal_offset - base
if diff < 0:
diff += 12
# This is the diffe... | 1,815 | 595 |
from django.contrib.auth.models import User
from django.db.models import Sum
from rest_framework import serializers
from api.models.information_model import Information
from api.models.information_effect_model import InformationEffect
from api.models.information_vote_model import InformationVote
from api.serializers.u... | 3,447 | 935 |
import os
import cv2
import mxnet as mx
import numpy as np
from . import face_preprocess
from .mtcnn_detector import MtcnnDetector
def get_model(ctx, image_size, model_str, layer):
_vec = model_str.split(',')
assert len(_vec) == 2
prefix = _vec[0]
epoch = int(_vec[1])
print('loading', prefix, ep... | 3,493 | 1,266 |
import newspaper
from newspaper import Article
def getarticle(url):
articleurl = url
article = Article(articleurl)
try:
article.download()
article.parse()
alltext = article.text
return alltext
except:
return "this website is not available"
| 316 | 90 |
from .activity_logger import idea_activity_logger, todo_activity_logger | 71 | 18 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import h2o
import os
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from tests import pyunit_utils
def model_download_with_cv():
prostate = h2o.import_file(pyunit_utils.locate("smalldata/prostate/prostate.csv"))
prostate["CAPSULE"] = prostate["CAPSU... | 1,302 | 490 |
import tensorflow as tf
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras import models
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input
import numpy as np
import cv2
# prebuild model with pre-trained weights on imagene... | 890 | 314 |
"""
call in shell: python evaluate.py --dir <rootdir/experiment/> --epoch <epoch to>
e.g. in shell: python evaluate.py --dir Runs/se_resnet_trained_final/ --epoch 149
loops over all folds and calculates + stores the accuracies in a file in the root folder of the experiment
you might change the model in line 45 from r... | 3,262 | 1,127 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | 18,413 | 5,343 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 08:38:28 2020
pyqt realtime plot tutorial
source: https://www.learnpyqt.com/courses/graphics-plotting/plotting-pyqtgraph/
@author: nlourie
"""
from PyQt5 import QtWidgets, QtCore,uic
from pyqtgraph import PlotWidget, plot,QtGui
import pyqtgra... | 11,139 | 4,112 |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class QuotesItem(scrapy.Item):
# define the fields for your item here like:
author_name = scrapy.Field()
author_location = scrapy.Field()
author_date = scrapy.... | 380 | 125 |