text
string
size
int64
token_count
int64
#!/usr/bin/env python # -*- coding: UTF-8 -*- import sys import rospy import re import time import numpy import argparse import math import underworlds import tf2_ros from underworlds.helpers.geometry import get_world_transform from underworlds.tools.loader import ModelLoader from underworlds.helpers.transformations i...
9,855
3,121
import code.PdfReader as PdfReaderModule import code.ExcelReader as ExcelReader import code.TemplateParser as TemplateParser import code.PdfAnalyzer as PdfAnalyzer import code.EmailSender as EmailSender def getFileContent(fileName): read_data = "" with open(fileName, encoding="utf-8") as f: read_data =...
3,171
908
from importlib.util import spec_from_file_location, module_from_spec from os import listdir from os.path import join def load_cls(file_path: str, class_name: str): s = spec_from_file_location(class_name, file_path) m = module_from_spec(s) s.loader.exec_module(m) return m.__dict__[class_name] def loa...
1,146
404
from django import template from django.conf import settings from leaflets.models import Leaflet from constituencies.models import Constituency register = template.Library() @register.inclusion_tag('constituencies/ordered_list.html') def constituency_list_by_count(): constituencies = Constituency.objects.all().or...
681
210
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import textwrap import time import bs4 from django.core.urlresolvers import get_resolver from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http i...
8,439
2,551
# -*- coding: utf-8 -*- """ Created on Wed Nov 22 21:44:55 2017 @author: Mike """ import numpy as np import cv2 import glob import pickle import matplotlib.pyplot as plt from matplotlib.pyplot import * import os from scipy import stats from moviepy.editor import VideoFileClip from IPython.display im...
20,404
7,793
""" homeassistant.components.light.insteon ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support for Insteon Hub lights. """ from homeassistant.components.insteon_hub import INSTEON, InsteonToggleDevice def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the Insteon Hub light platform. """ ...
624
188
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian import numpy as np import plotly.graph_objects as go import plotly.io as pio pio.templates.default = "simple_white" SAMPLES_NUM = 1000 LEFT_CIRCLE = '(' RIGHT_CIRCLE = ')' COMMA = ', ' GRAPH_SIZE = 500 HEATMAP_SIZE = 700 def test_univariate_gaussi...
3,481
1,194
def digitsProduct(product): """ Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. Time Complexity: O(inf) Space Complexity: O(1) """ number = 1 ...
562
170
results = open('test-results-gpu.out', 'a') results.write('** Starting serial GPU tests **\n') try: # Fresnel #import fresnel #results.write('Fresnel version : {}\n'.format(fresnel.__version__)) #dev = fresnel.Device(mode='gpu', n=1) #results.write('Fresnel device : {}\n'.format(dev)) # H...
715
262
numero = input('\nInsira um numero de 0 a 9999: \n') if not numero.isnumeric(): print('Condição inválida, insira apenas números\n') elif len(numero) == 1: print('\nA unidade do número {} é {}\n'.format(numero, numero[-1])) elif len(numero) == 2: print('\nA unidade do número {} é {}'.format(numero, n...
1,027
383
from django.utils.translation import ugettext_lazy as _ from mayan.apps.authentication.link_conditions import condition_user_is_authenticated from mayan.apps.navigation.classes import Link, Separator, Text from mayan.apps.navigation.utils import factory_condition_queryset_access from .icons import ( icon_current_...
4,785
1,499
import os import urllib.parse basedir = os.path.abspath(os.path.dirname(__file__)) if "DB_CONNECTIONSTRING" in os.environ: params = urllib.parse.quote_plus(os.environ.get("DB_CONNECTIONSTRING")) class Config(object): SECRET_KEY = os.environ.get("SECRET_KEY") or "iR33OXoRSUj5" SQLALCHEMY_DATABASE_URI = ...
626
266
from django.utils.translation import gettext_lazy as _, gettext from .utils import get_main_menu_item, APPS ENTITIES = { 'apart': ('apart', 'apartment'), 'meter': ('meters data', 'execute'), 'bill': ('bill', 'cost'), 'service': ('service', 'key'), 'price': ('tari...
3,254
1,029
#!/usr/bin/python3 # -*- coding: utf-8 -*- import time from PySide2.QtWidgets import QWidget, QMainWindow, QGridLayout, QFileDialog, QToolBar,\ QAction, QDialog, QStyle, QSlider, QLabel, QPushButton, QStackedWidget, QHBoxLayout,\ QLineEdit, QTableWidget, QAbstractItemView, QTableWidgetItem, QGrap...
6,288
1,951
# -*- mode: python; coding: utf-8 -*- # Copyright (c) 2018 Radio Astronomy Software Group # Licensed under the 2-clause BSD License """Primary container for radio interferometer datasets.""" import os import copy from collections.abc import Iterable import warnings import threading import numpy as np from scipy impor...
554,022
151,452
# 15. replace() -> Altera determinado valor de uma string por outro. Troca uma string por outra. texto = 'vou Treinar todo Dia Python' print(texto.replace('vou','Vamos')) print(texto.replace('Python','Algoritmos'))
215
72
'''Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.''' #RESOLUÇÃO ALAN '''mult = int(input(' Digite um número para ver sua tabuada: ')) for num in range(1, 11): rest = num * mult print('{} X {} = {} '. format(num, mult, rest))''' #RESOLUÇÃO PROF...
573
229
from django.utils.formats import localize from rest_framework.serializers import ( ModelSerializer, HyperlinkedIdentityField, SerializerMethodField, ValidationError, ) from rest_framework import serializers from django.contrib.auth import ...
4,710
1,268
from django import template register = template.Library() @register.filter def fast_floatformat(number, places=-1, use_thousand_separator=False): """simple_floatformat(number:object, places:int) -> str Like django.template.defaultfilters.floatformat but not locale aware and between 40 and 200 times f...
2,377
824
import vdf implemented_bots = set([ 'npc_dota_hero_axe', 'npc_dota_hero_bane', 'npc_dota_hero_bounty_hunter', 'npc_dota_hero_bloodseeker', 'npc_dota_hero_bristleback', 'npc_dota_hero_chaos_knight', 'npc_dota_hero_crystal_maiden', 'npc_dota_hero_dazzle', 'npc_dota_hero_death...
3,877
1,571
#! /usr/bin/env python3 """ Maigret entrypoint """ import asyncio from .maigret import main if __name__ == "__main__": asyncio.run(main())
147
62
"""Allow users to access the function directly.""" from egcd.egcd import egcd
80
24
TokIdentifier = "Identifier" TokOpenStruct = "OpenStruct" TokCloseStruct = "CloseStruct" TokAssign = "Assign" TokEndStatement = "EndStatement" TokString = "String" TokEOF = "EOF" TokComment = "Comment" TokInteger = "Integer" class Token(object): def __init__ (self, type, val): self.type = type self...
18,872
5,821
import inspect try: from unittest import mock except ImportError: import mock import pytest from selenium.webdriver.common.by import By from selenium.webdriver.remote.webdriver import WebDriver, WebElement from selenium.common.exceptions import NoSuchElementException from page_objects import PageObject, Pag...
6,286
1,914
from flask import Blueprint, jsonify, request from flask_jwt_extended import jwt_required, get_jwt_identity from marshmallow import ValidationError from flaskr import db from flaskr.helpers import error_bad_request, error_validation from flaskr.models import User from flaskr.schemas import UserProfileSchema bp = Blue...
1,355
444
import copy import struct class PointerTable: END_OF_DATA = (0xff, ) """ Class to manage a list of pointers to data objects Can rewrite the rom to modify the data objects and still keep the pointers intact. """ def __init__(self, rom, info): assert "count" in info ...
6,394
1,943
#Telegram @javes05 import spamwatch, os, asyncio from telethon import events from userbot import client as javes, JAVES_NAME, JAVES_MSG JAVES_NNAME = str(JAVES_NAME) if JAVES_NAME else str(JAVES_MSG) swapi = os.environ.get("SPAMWATCH_API_KEY", None) SPAM_PROTECT = os.environ.get("SPAM_PROTECT", None) SPAMWATCH_SHOUT...
2,092
702
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from setup_app_db import Title, User, Base engine = create_engine('sqlite:///book_catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Create dummy title user1 = User(u_name="...
2,483
945
import logging import termcolor class Formatter(logging.Formatter): _LEVELS_COLORS = { '[INFO]': 'green', '[WARNING]': 'yellow', '[ERROR]': 'red', } def format(self, record): message = super().format(record) for level, color in self._LEVELS_COLORS.items(): ...
755
241
import json from urllib import parse, request from telegram.ext import CallbackContext, CommandHandler from telegram.update import Update from autonomia.core import bot_handler BASE_URL = "https://query.yahooapis.com/v1/public/yql?" def _get_weather_info(location): query = ( "select * from weather.fore...
1,373
433
import numpy as np import utils from utils import NUMBER_OF_ENCODED_BITS, VECTORLENGTH, Z, TransmissionPackage class Decoder: def __init__(self): self._inputData = [] # [(informationID, [[(a, y)]] )] <-- Format, place in second Array is chunkID self._decodedData = [] # [(informationID, [decoded...
5,733
1,695
"""Mock hardware implementation""" import logging from stage import exceptions from unittest.mock import Mock LOGGER = logging.getLogger("mock") class MockStage: """A mock implemenation of a stepper motor driven linear stage""" MAX_POS = 100 MIN_POS = 0 def __init__(self): self._position = _...
2,006
560
""" Singly linked lists ------------------- - is a list with only 1 pointer between 2 successive nodes - It can only be traversed in a single direction: from the 1st node in the list to the last node Several problems ---------------- It requires too much manual work by the programmer It is too error-prone (this is a ...
6,861
1,825
for _ in range(int(input())): n = input() print(int(n[0])+int(n[-1]))
78
35
from .utils import get_train_transforms, get_val_transforms, \ get_preprocessing, seed_everything from .train_2d import TrainSegExperiment from .infer import GeneralInferExperiment
200
56
from src.answerkey import AnswerKey from src.model import Model, unmasker import streamlit as st PAGE_CONFIG = {"page_title":"MCQ-App by Glad Nayak","page_icon":":white_check_mark:"} st.set_page_config(**PAGE_CONFIG) def render_input(): """ Renders text area for input, and button """ # source of defa...
7,513
1,950
from compmech.stiffpanelbay import StiffPanelBay spb = StiffPanelBay() spb.a = 2. spb.b = 1. spb.r = 2. spb.stack = [0, 90, 90, 0, -45, +45] spb.plyt = 1e-3*0.125 spb.laminaprop = (142.5e9, 8.7e9, 0.28, 5.1e9, 5.1e9, 5.1e9) spb.model = 'cpanel_clt_donnell_bardell' spb.m = 15 spb.n = 16 spb.u1tx = 0. spb.u1rx = 1. spb...
687
496
from banana.analysis.mri.base import MriAnalysis from banana.utils.testing import AnalysisTester, PipelineTester, TEST_CACHE_DIR from banana import FilesetFilter from arcana.repository.xnat import XnatRepo class TestMriBaseDefault(AnalysisTester): analysis_class = MriAnalysis parameters = {'mni_tmpl_resoluti...
2,203
734
class Email: def __init__(self): self.from_email = '' self.to_email = '' self.subject = '' self.contents = '' def send_mail(self): print('From: '+ self.from_email) print('To: '+ self.to_email) print('Subject: '+ self.subject) print('Contents: '+ s...
333
106
#!/usr/bin/env python3 __author__ = "JR. Lambea" __copyright__ = "Copyright 2015" __credits__ = ["JR. Lambea"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "JR. Lambea" __email__ = "jr.lambea@yahoo.com" __status__ = "" import sys import argparse def main(): parser = argparse.ArgumentParser() parser....
1,290
528
""" <Program Name> common.py <Author> Lukas Puehringer <lukas.puehringer@nyu.edu> Santiago Torres <santiago@nyu.edu> <Started> Sep 23, 2016 <Copyright> See LICENSE for licensing information. <Purpose> Provides base classes for various classes in the model. <Classes> Metablock: pretty printed ca...
3,465
1,108
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class Application: def __init__(self): self.wd = webdriver.Chrome(executable_path='/Users/atvelova/Documents/python_training/chromedriver') self.wd.implicitly_wait(60) d...
1,034
361
from .model_nefnet import Model_nefnet from torch.nn import MSELoss, L1Loss, CrossEntropyLoss from .loss import losswrapper, MSELead def build_model(cfg): model_name = cfg.MODEL.model if model_name == 'model_nefnet': return Model_nefnet(theta_encoder_len=cfg.MODEL.theta_L, lead_num=cfg.DATA....
704
261
# Copyright 2017-2020 TensorHub, 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 writ...
8,942
2,751
r"""Provides functions used by strategies that use a tree to select the permutation. To compute optimal permutations, we use the belief states .. math:: b(y^{k-1}) := \mathbb{P}(s_0, s_k|y^{k-1}), where the :math:`s_k` are the states of the HMM at step :math:`k`, and the superscript :math:`y^{k-1}` is the sequen...
12,770
3,844
# All .ui files and .so files are added through keyword: package_data, because setuptools doesn't include them automatically. import sys import os from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name = "xfntr", version = "0.3.0", autho...
1,424
476
import xarray as xr import argparse from glob import glob def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="Input File Directory") parser.add_argument("-o", "--output", help="Output file directory") parser.add_argument("-x", "--xsub", type=int, default=2, help="X...
720
244
from torchvision import transforms, datasets from torch.utils.data import DataLoader import config from dataset import custom_dataset import pretrainedmodels as models import torch from tqdm import tqdm from torch.nn import functional as F import types from utils import AverageMeter, get_shuffle_idx import os from util...
7,099
2,410
""" module contains a function that polls the ukcovid api in order to find up to date information about coronavirus in the UK """ import json import logging from uk_covid19 import Cov19API from requests import get logging.basicConfig(level=logging.DEBUG, filename='sys.log') def get_covid() -> str: """...
1,957
639
# coding: utf-8 from django.db import models from django.contrib.auth.models import User from RoomManage.models import Room, Customs # Create your models here. class Task(models.Model): context = models.TextField() date = models.DateTimeField() task_status = models.CharField(max_length=20, default='und...
1,187
389
import pathlib import pytest from pypendency.parser.yaml import Parser from pypendency.lexer import LarkRelationLexer def test_read_yaml_node_length(): file = pathlib.Path(__file__).parent / "example.yml" lexer = LarkRelationLexer() p = Parser(lexer=lexer, folder=pathlib.Path(__file__).parent) g = p...
400
146
import re import string import random import mylib # Python ZIP version def count_doubles(val): total = 0 # there is an improved version later on this post for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total # Python REGEXP version double_re = re.compile(r'(?=(....
842
306
__all__ = [ "GuestUserPool", "GuestUser", "NormalUserPool", "NormalUser", "GoldUserPool", "GoldUser", "GoldUserStatus", ] from .gold_user_pool import GoldUserPool, GoldUser, GoldUserStatus from .guest_user_pool import GuestUserPool, GuestUser from .normal_user_pool import NormalUserPool, No...
329
114
# Copyright Contributors to the Rez project # # 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 ...
5,954
1,812
from .cs_loader import CSPointDataset from .cs_class_loader import CSClassDataset from .cs_seed_loader import CSSeedDataset
124
38
# Copyright 2015 Google 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, ...
1,235
370
# linuxjournalarchiver - Some hacky code I wrote to archive the Linux Journal. # Licensed under the BSD-3-Clause license. from bs4 import BeautifulSoup import requests import re import pathlib # Download the download page. print("Downloading magazine list...") session = requests.session() # Update the User Agent to c...
2,432
754
import os.path filepathlist=[] filenamelist=[] def processDirectory ( args, dirname, filenames ): for filename in filenames: file_path=os.path.join(dirname,filename) if os.path.isfile(file_path): filepathlist.append(file_path) filenamelist.append(filename) def ...
548
200
#! /usr/bin/env python3 """ Pulls artifacts from external repo using branches defined in branchConfig.yaml file. Run the script with -h flag to learn about script's running options. """ __author__ = "Michal Cwiertnia" __copyright__ = "Copyright (C) 2018 ACK CYFRONET AGH" __license__ = "This software is released under ...
4,858
1,294
import os import shutil from distutils.dir_util import copy_tree from setuptools import find_packages, setup # global variables nb_dir = os.environ['PYNQ_JUPYTER_NOTEBOOKS'] package_name = 'pystrath_rfsoc' pip_name = 'pystrath-rfsoc' data_files = [] # copy common notebooks to jupyter home def copy_common_notebooks()...
845
321
"""Tests of querying tools.""" import contextlib import importlib import io import logging import os import pathlib import sys import tempfile import unittest from version_query.version import VersionComponent, Version from version_query.git_query import query_git_repo, predict_git_repo from version_query.py_query im...
7,682
2,447
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SelectField ,SubmitField from wtforms.validators import input_required class EditProfile(FlaskForm): about = TextAreaField('Tell us about yourself.',validators = [input_required()]) submit = SubmitField('Update') class UpdatePos...
728
213
import gdb def print_field(f): print("========") print("name: %s" % f.name) print("type: %s" % f.type) if hasattr(f, "bitpos"): print("bitpos: %d" % f.bitpos) else: print("No bitpos attribute.") print("bitsize: %d" % f.bitsize) print("parent_type: %s" % f.parent_type) print("is_base_class: %s" ...
647
269
import argparse import getpass import glob import hashlib import itertools import json import logging import os import sys import threading import time import traceback import subprocess import urllib import urllib.request import urllib.parse import urwid import pybtex import pybtex.database class BibEntry: cla...
42,581
12,348
# ----------------------- # # -------- SETUP -------- # # ----------------------- # # Import PySpark, Parameters, File Paths, Functions & Packages import pyspark from CCSLink import Parameters from CCSLink.Parameters import FILE_PATH from CCSLink import Person_Functions as PF from CCSLink import Household_Functions as...
11,144
4,285
n, x = map(int, input().split()) ll = list(map(int, input().split())) ans = 1 d_p = 0 d_c = 0 for i in range(n): d_c = d_p + ll[i] if d_c <= x: ans += 1 d_p = d_c print(ans)
199
102
from django.contrib import admin from ballon.models import Pkg, Resume, Main, Education, Project, Work, Skill, Testimonial, Social, Address #admin.site.register(Category) admin.site.register(Resume) admin.site.register(Main) admin.site.register(Education) admin.site.register(Work) admin.site.register(Project) admin.si...
453
146
#!/usr/bin/env python3 # Add unversioned labels to a page, before each versioned label ## Overview # This script adds unversioned labels (i.e. Sphinx labels without the _N suffix, # where N is the name of the protocol) to one doc page before every versioned # label, unless an unversioned label already exists. # If i...
1,316
442
# Get arxiv data import json import logging import os import pickle from collections import Counter from datetime import datetime from io import BytesIO from zipfile import ZipFile import numpy as np import pandas as pd import requests from kaggle.api.kaggle_api_extended import KaggleApi from eurito_indicators impor...
10,435
3,622
#### #Made reduntant in Alpha 0.4 # # As this provided no extra functionality from the Channel, and is, in essance, # simply a speciall channel, various additions were made to Channel.py # To perform the same function. This has meant less duplication of code. #### import sys, sip from PyQt5 import QtCore, QtGui #fro...
6,617
2,550
from collections import namedtuple Config = namedtuple('Config', [ 'env_id', 'env_seed', 'population_size', 'timesteps_per_gen', 'num_workers', 'learning_rate', 'noise_stdev', 'snapshot_freq', 'return_proc_mode', 'calc_obstat_prob', 'l2coeff', 'eval_prob' ]) Optimizati...
697
264
import sys import logging import functools import asyncio import cocrawler.burner as burner import cocrawler.parse as parse import cocrawler.stats as stats test_threadcount = 2 loop = asyncio.get_event_loop() b = burner.Burner(test_threadcount, loop, 'parser') queue = asyncio.Queue() def parse_all(name, string): ...
1,833
631
#!/usr/bin/env python """ Generates a list of OS X system events into a plist for crankd. This is designed to create a large (but probably not comprehensive) sample of the events generated by Mac OS X that crankd can tap into. The generated file will call the 'tunnel.sh' as the command for each event; said fail can ...
3,362
957
import csv import random from functools import partial from typing import Callable, Optional from pdb import set_trace as st import os import random import pandas as pd from typing import Any, Callable, Dict, Iterable, List, Tuple, Union import numpy as np import tensorflow as tf from foolbox.attacks import ( FGSM...
15,742
4,987
# Copyright 2016 Google Inc. 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 law or a...
2,459
835
def fill_the_box(*args): height = args[0] length = args[1] width = args[2] cube_size = height * length * width for i in range(3, len(args)): if args[i] == "Finish": return f"There is free space in the box. You could put {cube_size} more cubes." if cube_size < args[i]: ...
794
322
# -*- coding: utf-8 -*- import pandas as pd from ..signal import signal_rate, signal_sanitize from .ecg_clean import ecg_clean from .ecg_delineate import ecg_delineate from .ecg_peaks import ecg_peaks from .ecg_phase import ecg_phase from .ecg_quality import ecg_quality def ecg_process(ecg_signal, sampling_rate=1000...
4,759
1,642
#!/usr/bin/env python3 #Antonio Karlo Mijares # return_text_value function def return_text_value(): name = 'Terry' greeting = 'Good Morning ' + name return greeting # return_number_value function def return_number_value(): num1 = 10 num2 = 5 num3 = num1 + num2 return num3 # Main program if __name__ == '__ma...
457
169
import numpy as np from ..utils.constants import * from ..utils.vector3 import vec3 from ..geometry import Primitive, Collider class Sphere(Primitive): def __init__(self,center, material, radius, max_ray_depth = 5, shadow = True): super().__init__(center, material, max_ray_depth, shadow = shadow)...
1,958
752
from logs import logDecorator as lD import json, psycopg2 from lib.celery.App import app config = json.load(open('../config/config.json')) logBase = config['logging']['logBase'] + 'lib.worker.worker_1' @app.task @lD.log(logBase + '.add') def add(logger, a, b): try: result = a+b return result ...
430
149
from metaflow import FlowSpec, step class ForeachFlow(FlowSpec): @step def start(self): self.creatures = ['bird', 'mouse', 'dog'] self.next(self.analyze_creatures, foreach='creatures') @step def analyze_creatures(self): print("Analyzing", self.input) self.creature ...
647
218
# Imports from our app from wotd import db, app # Flask-Login works via the LoginManager class: Thus, we need # to start things off by telling LoginManager about our Flask app from flask_login import LoginManager login_manager = LoginManager(app) login_manager.init_app(app) # Password hashing from werkzeug.security im...
2,150
664
""" for x in range(10): print(x) for x in range(20, 30): print(x) for x in range(10,100,5): print(x) for x in range(10,1,-1): print(x) print(range(10)) """ frutas = ["maçã", "laranja", "banana", "morango"] for x in range(len(frutas)): print(frutas[x]) for fruta in frutas: print(fruta)
316
154
import twitter import util from config import * BOSTON_WOEID = 2367105 api = twitter.Api(consumer_key=key,consumer_secret=secret,access_token_key=access_key,access_token_secret=access_secret) def search(searchTerm): """ Print recent tweets containing `searchTerm`. To test this function, at the command li...
2,092
681
"""Tests various methods of the Download class. All the methods that start with test are used to test a certain function. The test method will have the name of the method being tested seperated by an underscore. If the method to be tested is extract_content, the test method name will be test_extract_content """ from...
2,830
997
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException...
9,932
3,455
from dataclasses import dataclass, field from itertools import chain from typing import Optional from talon import Context, Module, actions, app, cron, ui # XXX(nriley) actions are being returned out of order; that's a problem if we want to pop up a menu mod = Module() mod.list("notification_actions", desc="Notific...
10,830
2,903
"""System-wide constants.""" from __future__ import annotations import os # Mode Names PRODUCTION_MODE_NAME = "prod" DEVELOPMENT_MODE_NAME = "dev" # Latest Git Commit LATEST_KEYWORD = "latest" # Root of repo ROOT_DIR = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..") ) DE...
529
197
{ "variables": { "HEROKU%": '<!(echo $HEROKU)' }, "targets": [ { "target_name": "gif2webp", "defines": [ ], "sources": [ "src/gif2webp.cpp", "src/webp/example_util.cpp", "src/web...
1,367
336
import numpy as np from multiagent.core import World, Agent, Landmark from multiagent.scenario import BaseScenario class Scenario(BaseScenario): def make_world(self): world = World() # set any world properties first world.dim_c = 2 num_agents = 2 num_adversaries = 1 ...
4,881
1,516
from dataclasses import dataclass from typing import Optional import jax.numpy as jnp from pyshocks import Grid, ConservationLawScheme from pyshocks import flux, numerical_flux, predict_timestep from pyshocks.weno import WENOJSMixin, WENOJS32Mixin, WENOJS53Mixin # {{{ base @dataclass(frozen=True) class Scheme(Con...
2,931
1,217
from finitewave.core.command.command import Command from finitewave.core.command.command_sequence import CommandSequence
121
28
from django.apps import AppConfig class SmartMeterConfig(AppConfig): name = 'smart_meter'
96
32
import secrets channel_name = "nopogo_tv" server_ip = "0.0.0.0" server_port = 8000 channel_id = 28092036 ws_host = "wss://pubsub-edge.twitch.tv" ws_local = secrets.local_ip topics = [ "channel-bits-events-v2.{}".format(channel_id), "channel-points-channel-v1.{}".format(channel_id), "channel-subscribe-events-v1.{}...
344
156
# Imports import numpy as np # Single to double frame # Combines images by 2, returning an array with two frames (one for each image). # # Input: 5 images with step 1. # Output: 4 double-framed images. # FrameA: 1 2 3 4 # FrameB: 2 3 4 5 # # Input: 8 images with step 3. # Output: 5 doubled...
1,510
578
import os import time from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from transformers import PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer from transformers.data.datasets import GlueDa...
4,656
1,298
#! /usr/bin/env python """ This script parses and cleans up a provided Flow Cytometry Standard (fcs) file and saves it as a Comma Separated Value (csv). """ import os import re import numpy as np import pandas as pd import optparse import fcsparser # ####################################################################...
4,071
1,156
from enum import Enum class Semester(Enum): FALL = 9 WINTER = 1 SUMMER = 5
89
38
with open("day6_input.txt") as f: initial_fish = list(map(int, f.readline().strip().split(","))) fish = [0] * 9 for initial_f in initial_fish: fish[initial_f] += 1 for day in range(80): new_fish = [0] * 9 for state in range(9): if state == 0: new_fish[...
485
169