text
string
size
int64
token_count
int64
from flask_wtf import Form from wtforms import StringField from wtforms.validators import DataRequired class BranchSlugField(StringField): def process_formdata(self, valuelist): if valuelist: if valuelist[0]: self.data = valuelist[0].strip() else: s...
434
129
import requests import re import os from flask import Response, request, abort, render_template, url_for, Blueprint from igvjs._config import basedir seen_tokens = set() igvjs_blueprint = Blueprint('igvjs', __name__) # give blueprint access to app config @igvjs_blueprint.record def record_igvjs(setup_state): igv...
2,458
807
# -*- coding: utf-8 -*- # Copyright (c) 2019, Totall and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class Representacion(Document): pass # # def validate(self): # self.db_set('mes_entrega', self....
335
117
numero = int(input('Tabuada do ')) print(f'{numero} X 0 = {numero*0}') print(f'{numero} X 1 = {numero*1}') print(f'{numero} X 2 = {numero*2}') print(f'{numero} X 3 = {numero*3}') print(f'{numero} X 4 = {numero*4}') print(f'{numero} X 5 = {numero*5}') print(f'{numero} X 6 = {numero*6}') print(f'{numero} X ...
458
248
#!/usr/bin/env python import sys import yaml import logging import time from multiprocessing.pool import ThreadPool import kraken.cerberus.setup as cerberus import kraken.kubernetes.client as kubecli import kraken.post_actions.actions as post_actions from kraken.node_actions.aws_node_scenarios import AWS from kraken.n...
5,068
1,511
import h5py import collections import numpy as np import os import ipdb import math import time import datetime import random import torch from torch.utils.data.dataset import Dataset def hdf5_load_dataset(hdf5_file_path, all_indices, step_size, large_batch=1024, is_decode_utf8=False): random.shuffle(all_indice...
16,539
5,128
# # Matching Word & Non-Word Character # # https://www.hackerrank.com/challenges/matching-word-non-word/problem # Regex_Pattern = r"\w{3}\W\w{10}\W\w{3}" # Do not delete 'r'. import re print(str(bool(re.search(Regex_Pattern, input()))).lower())
248
103
""" https://leetcode.com/problems/same-tree/ https://leetcode.com/submissions/detail/109733704/ """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from common.tree_node import TreeNode class So...
980
328
# -*- coding: utf-8 -*- """ (c) 2014-2016 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <pingou@pingoured.fr> """ # pylint: disable=too-few-public-methods # pylint: disable=no-init # pylint: disable=super-on-old-class from __future__ import unicode_literals, absolute_import import datetime import re i...
30,220
9,235
"""Service sub commands.""" from docknv.shell.common import exec_handler, load_project def _init(subparsers): cmd = subparsers.add_parser( "service", help="manage one service at a time (service mode)" ) cmd.add_argument( "-c", "--config", help="configuration name (swap)", default=None ...
5,285
1,717
#!/usr/bin/env python # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # Consorzio COMETA (COMETA), Italy # # See http://www.infn.it and and http://www.consorzio-cometa.it for details on # the copyright holders. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
7,254
2,315
import pandas as pd import numpy as np def main(): print("a bombae bros production\n") if __name__ == "__main__": main()
130
45
from canvasaio.canvas_object import CanvasObject from canvasaio.util import combine_kwargs class Bookmark(CanvasObject): def __str__(self): return "{} ({})".format(self.name, self.id) async def delete(self, **kwargs): """ Delete this bookmark. :calls: `DELETE /api/v1/users/se...
1,466
450
#!/usr/bin/env python # vim: fdm=marker ''' author: Fabio Zanini date: 17/05/14 content: Split the reads for mapping into small aliquots, to exploit the short queue on the cluster. ''' # Modules import os import sys import time import argparse import pysam import numpy as np import subprocess a...
5,295
1,658
from spikeforest import SFMdaSortingExtractor from copy import deepcopy from mountaintools import client as mt from .recordingcontext import RecordingContext import mtlogging class SortingResultContext(): def __init__(self, *, sorting_result_object, recording_context): self._signal_handlers = dict() ...
3,843
1,109
import bh_plugin class SelectAttr(bh_plugin.BracketPluginCommand): def run(self, edit, name, direction='right'): """ Select next attribute in the given direction. Wrap when the end is hit. """ if self.left.size() <= 1: return tag_name = r'[\w\:\.\-]+' ...
2,712
689
"""" using python version 3.7+ python-gitlab version 1.8.0 python-jenkins version 1.7.0 """ import gitlab import jenkins import smtplib import ssl import markdown from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class JenkinsAuto: __host = '' __user_name = '' __passwo...
8,304
2,434
import json import pickle from typing import Dict import cx_Oracle from interpro7dw import pfam from interpro7dw.utils import logger from interpro7dw.utils.oracle import lob_as_str from interpro7dw.utils.store import BasicStore def get_clans(cur: cx_Oracle.Cursor) -> Dict[str, dict]: cur.execute( """ ...
5,189
1,631
import unittest from annotypes import add_call_types, Anno from malcolm.core import Controller, Part, PartRegistrar, StringMeta, \ Process, Queue, Get, Return, Put, Error, Post, Subscribe, Update, \ Unsubscribe with Anno("The return value"): AWorld = str class MyPart(Part): my_attribute = None ...
4,054
1,242
# _*_coding:utf8- import ftplib from Violent_Python import _Config ''' This code, we need learning how to upload file or download file with target FTP. Note:Make sure your "write enable equal YES" in your /etc/vsftpd.conf Document: --------- 1. we logon target FTP, and use ftp.retrlines(cmd,callback) function down...
2,364
734
from random import randint from time import sleep continuar = 'Ss' while continuar in 'Ss': print('\033[1;32mVamos jogar. Exemplo: 1d20 ou 5d10\033[m') opc = input() qntDados = int(opc[:1]) valorDado = int(opc[2:]) if qntDados > 10 or valorDado not in [4,6,8,10,12,20,100]: print('\033[1;31m...
684
303
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 MarkLogic 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# # # U...
3,155
1,029
import unittest from os import sys, path from crypto.signature import Signature sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class TestSignatureFunctions(unittest.TestCase): def test_sign_ed25519(self): private_key = bytes.fromhex('3b24b5f9e6b1371c3b5de2e402a96930eeafe52111bb4a1b00...
1,094
482
# -*- coding: utf8 from __future__ import unicode_literals from flask_admin.contrib.sqla import ModelView from instashare.database import db from instashare.extensions import admin from .models import UserPointInfo, UserDailyPointInfo, \ UserPointHistory admin.add_view(ModelView(UserPointInfo, db.session)) admin...
429
132
#input print("This program find the volume of a cylinder") PI= 3.14159265359 diameter= float(input("Enter diameter: ")) height= float(input("Enter height: ")) #processing volume= PI * diameter *height #output (print("The volume of a cyclinder with a diameter of",diameter, "and a height of", height, "is",volume))
318
111
class CP_HTTP_RESULT(object): CP_HTTP_OK = 200 CP_HTTP_CREATED = 201 CP_HTTP_MULTI_STATUS = 207 CP_HTTP_BAD_REQUEST = 400 CP_HTTP_UNAUTHORIZED = 401 CP_HTTP_PAYMENT_REQUIRED = 402 CP_HTTP_FORBIDDEN = 403 CP_HTTP_NOT_FOUND = 404 CP_HTTP_NOT_ALLOWED = 405 CP_HTTP_NOT_ACCEPTABLE =...
946
458
import praw # Visit the PRAW website for instructions on installation and configuration. # https://praw.readthedocs.io/en/latest/getting_started/authentication.html#script-application username="" #Your username. reddit = praw.Reddit( client_id = "", #14 character code. client_secret = "", #27 character code....
600
183
# -*- coding: utf-8 -*- """ Test Settings """ import django APP_NAME = 'ebay_accounts' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'ebay_accounts', ) MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.Cs...
2,219
815
from PyQt5 import QtCore, QtWidgets, QtGui, uic import os class IndicatorParametersUI(QtWidgets.QDialog): def __init__(self, parent = None): super(IndicatorParametersUI, self).__init__() #self.setParent(parent) # It does not finish by a "/" self.current_dir_path = os.path.dirna...
2,736
754
try: from django.conf.urls import url, patterns, include except ImportError: from django.conf.urls.defaults import url, patterns, include urlpatterns = patterns('', url(r'test/$', 'captcha.tests.views.test', name='captcha-test'), url(r'test-modelform/$', 'captcha.tests.views.test_model_form', name='cap...
699
242
from django.shortcuts import render from django.template.loader import render_to_string from django.http import HttpResponse from django.conf import settings from persons.models import Role, Right, Department, Person from math import floor import os from subprocess import Popen, PIPE import tempfile # Create your...
5,475
1,777
# coding:utf-8 #!/usr/bin/python # # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # # lut_helper.py import sys import os import argparse import math import s...
7,118
2,406
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'standardLayout.ui' # # Created by: PyQt4 UI code generator 4.12 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(...
2,922
942
#!/usr/bin/env python3 from distutils.core import setup setup( name='RoSys', version='0.1', description='Zauberzeug Robot System', author='Zauberzeug', author_email='info@zauberzeug.com', url='https://github.com/zauberzeug/rosys/', packages=['rosys'], )
283
101
import pickle import logging import subprocess import concurrent.futures from pathlib import Path import luigi from luigi.util import inherits from recon.config import defaults from recon.masscan import ParseMasscanOutput @inherits(ParseMasscanOutput) class ThreadedNmapScan(luigi.Task): """ Run nmap against spe...
7,560
2,209
# Copyright (c) 2021-2022, InterDigital Communications, Inc # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted (subject to the limitations in the disclaimer # below) provided that the following conditions are met: # * Redistributions of source cod...
3,041
1,064
"""Data I/O: Import and export data to other useable formats.""" import csv from pathlib import Path from model import Job def import_csv(filename, base_dir=Path("data/")): """Converts CSV files with the relevant data (see columns below) to a list of Jobs. """ datafile = base_dir / filename with ...
2,219
588
# Copyright 2021 Huawei Technologies 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 agreed to...
16,694
7,492
from .eventemitter import * from .misc import * from .process import * from .string import *
93
28
# Generated by Django 3.0.4 on 2020-04-14 07:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0002_chapter_add_time'), ] operations = [ migrations.AlterField( model_name='courses', name='title_pic', ...
406
140
import tkinter from tkinter import messagebox import random WINDOW_HEIGHT=1200 WINDOW_WIDTH=600 BUTTON_HEIGHT=2 BUTTON_WIDTH=10 class Item: def __init__(self, id, content): self.index=id if len(content.split(" ")) == 1: self.text=content.split(" ")[0] elif not c...
9,162
3,255
# This file is part of the NESi software. # # Copyright (c) 2020 # Original Software Design by Ilya Etingof <https://github.com/etingof>. # # Software adapted by inexio <https://github.com/inexio>. # - Janis Groß <https://github.com/unkn0wn-user> # - Philip Konrath <https://github.com/Connyko65> # - Alexander Dincher <...
1,728
560
import os, re from django.contrib.messages import constants as messages BASE_DIR = os.path.dirname(os.path.dirname(__file__)) makepath = lambda *f: os.path.join(BASE_DIR, *f) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')2x-r4x+4oxdmvvxenj*dhq##uxrgl%f3=#+l*1s32y=f^51hz' ALLOWED_H...
2,665
966
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
4,147
1,247
# -*- coding: utf-8 -*- """ * @file KeystrokeDynamics.py * @brief Keystroke generator capture for L. Antichi Thesis * * @author Leonardo Antichi (<leo.antichi@sutd.uniroma3.it>) * @version 1.7 * @since 1.0 * * @copyright Copyright (c) 2017-2018 Roma Tre, Italy * @copyright Apache License, Version 2.0 """ import win32a...
2,703
1,297
from django.contrib import admin from .models import Portfolio @admin.register(Portfolio) class PortfolioAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'slug', 'category', 'published_at', 'image') list_display_links = ('id',) list_editable = ('title', 'category') list_filter = ('published_at...
423
132
# type: ignore """Provide a CLI.""" import logging import click from cpias import __version__ from cpias.cli.client import run_client from cpias.cli.server import start_server SETTINGS = dict(help_option_names=["-h", "--help"]) @click.group( options_metavar="", subcommand_metavar="<command>", context_settings=...
737
254
import os from typing import Literal, get_args, Final, Set, Dict AUTH_API_URL = os.getenv('AUTH_API_URL') AUTH_API_FIELD_USERNAME = os.getenv('AUTH_API_FIELD_USERNAME', 'username') AUTH_API_FIELD_PASSWORD = os.getenv('AUTH_API_FIELD_PASSWORD', 'password') if not AUTH_API_URL: raise Exception('please provide AUTH_A...
1,368
448
#! /usr/bin/env python import sys import copy import rospy import moveit_commander import moveit_msgs.msg import geometry_msgs.msg from math import pi from std_msgs.msg import String from moveit_commander.conversions import pose_to_list from geometry_msgs.msg import Pose, PoseStamped # Initializing the node represent...
4,347
1,934
# Generated by Django 2.0.8 on 2018-09-08 09:03 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0003_auto_20180908_1750'), ] operations = [ migrations.AddField( model_name='p...
502
176
""" @author: magician @date: 2019/12/10 @file: str_demo.py """ import os def to_str(bytes_or_str): """ to_str(python2, python3) :param bytes_or_str: :return: """ if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str ...
959
374
from random import * import tkinter from pokeapi import * smallFont = ["Ariel" , 10] mediumFont = ["Ariel" , 14] bigFont = ["Ariel" , 24] #function to display data for a pokemon number def showPokemonData(): #get the number typed into the entry box pokemonNumber = randint(1,178) #use the function above t...
2,452
921
from datetime import date info = dict() info['nome'] = str(input('Nome: ')) ano = int(input('Ano de Nascimento: ')) info['idade'] = date.today().year - ano info['ctps'] = int(input('Carteira de Trabalho (0 não tem): ')) if info['ctps'] > 0: info['contratação'] = int(input('Ano de contratação: ')) info['Salário'...
551
212
from pathlib import Path from typing import Callable, Dict, List, Type, Iterator from words.lexer.lex import Lexer from words.parser.parse import Parser from words.parser.parse_util import Program from words.token_types.lexer_token import LexerToken from words.token_types.parser_token import ParserToken, VariableParse...
2,547
764
import os, logging, toml _cfgFile_RAW = os.path.abspath(os.path.join("conf.toml")) _cfg = toml.load(_cfgFile_RAW) ''' log setting ''' if _cfg['Servers']['server']['CONSOLE'] == 'DEBUG': logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.DEBUG, ) e...
666
307
from django.db import models from django.utils.translation import ugettext_lazy as _ class ContactMessage(models.Model): name = models.CharField(max_length=500, verbose_name=_("Name")) email = models.EmailField(max_length=500, verbose_name=_("Email")) subject = models.CharField(max_length=1000, verbose_nam...
793
250
import os import subprocess import tempfile import urllib.request def _get_ceph_deploy(location, silent=False, retries=5): url = 'https://github.com/ceph/ceph-deploy/archive/refs/heads/master.zip' with tempfile.TemporaryDirectory() as tmpdir: # We use a tempfile to store the downloaded archive. archiv...
11,982
3,505
from pysubparser import parser from pysubparser.util import time_to_millis from pydub import AudioSegment # find segments of conversation import sys FIVE_SECONDS = 5000 def get_segments(subtitles): segments = [] prev_end = -1000000 curr_segment = None for subtitle in subtitles: this_start ...
1,539
551
try: import feedparser, html2text, asyncio, json, datetime, telepot from loguru import logger from telepot.aio.loop import MessageLoop from telepot.aio.delegate import per_chat_id, create_open, pave_event_space except ImportError: print("Failed to import required modules.") class RSS(telepot.aio.h...
4,766
1,367
""" nimsdata.medimg.dcm =================== TODO: docs? here? yes. Currently supported dicoms include the following Manufacturers and SOPs SUPPORTED_MFR - 'GE MEDICAL SYSTEMS' - 'SIEMENS' SUPPORTED_SOP - '1.2.840.10008.5.1.4.1.1.4' MR Image - '1.2.840.10008.5.1.4.1.1.7' Secondary Capture...
617
351
import pathlib import unittest from unittest.case import skip from pyais.stream import FileReaderStream, should_parse from pyais.messages import NMEAMessage class TestFileReaderStream(unittest.TestCase): FILENAME = "tests/ais_test_messages" def test_reader(self): with FileReaderStream(self.FILENAME) ...
3,475
1,263
# Driver for MAX 6639 fan controller # In normal operation: # reset() possibly with options # set_fan_ config() for each fan # set_pwm_mode() or set_rpm_mode() for each fan. from __future__ import print_function try: from i2c import i2c except: from .i2c import i2c class max6639: # registers, some may ac...
6,354
2,550
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Effet de déphasage à la Barberpole. Cet exemple utilise deux déphaseurs (basés sur une modulation complexe) décalant linéairement le contenu fréquentiel d'un son. Le décalage de fréquence est similaire à la modulation en anneaux, sauf que les bandes latérales supérie...
1,423
526
# Copyright 2018 Jérôme Dumonteil # Copyright (c) 2009-2013 Ars Aperta, Itaapy, Pierlis, Talend. # # 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...
8,885
2,435
import os DRIVER_DB = 'db_to_case' DRIVER_EXCEL = 'excel_to_case' DRIVER_TXT = 'txt_to_case' db_case_config = { 'host': '127.0.0.1', 'username': 'root', 'password': 'root', 'port': 3306, 'db': 'test', } excel_case_config = { 'path': os.path.dirname(__file__) + str('/excel_case/'), 'defaul...
659
274
# Copyright 2016 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...
3,634
1,039
# syracuseSequence.py # A program that prints a Syracuse sequence. """The Syracuse (also called "Collatz" or "Hailstone") sequence is generated by starting with a natural number and repeatedly applying the following function until reaching 1: syr(x) = x/2 (if x is even), 3x + 1 (if x is odd) For example, the Syracu...
1,253
360
from setuptools import setup setup( name = "todo-flask", version = "0.0.1", author = "Wayne Werner", author_email = "waynejwerner@gmail.com", description = "A sample todo app written with Flask, unittest, and sqlite", license = "BSD", keywords = "example flask unittest", url = "https://...
731
237
import os import logging import avalon.maya import avalon.io from collections import defaultdict from avalon.maya.pipeline import ( AVALON_CONTAINER_ID, AVALON_CONTAINERS, containerise, ) from maya import cmds from . import lib from .vendor import sticker from .capsule import namespaced, nodes_locker from...
17,834
5,289
from flask import Flask, render_template, request, session, redirect, url_for import pyrebase app = Flask(__name__) app.config['SECRET_KEY'] = 'covid_19' config = { "apiKey": "AIzaSyB6L9PLOIa-y8spupA2UFiegQGN7gmp12E", "authDomain": "vefferk5.firebaseapp.com", "databaseURL": "https://vefferk5.firebaseio.c...
2,697
1,005
"""Helper routines needed in pax Please only put stuff here that you *really* can't find any other place for! e.g. a list clustering routine that isn't in some standard, library but several plugins depend on it """ import re import sys import inspect import random import string import logging import time import os im...
2,511
788
from flask_babel import _, lazy_gettext as _l from flask_wtf import FlaskForm from wtforms import PasswordField, StringField, SubmitField from wtforms.validators import DataRequired, Email, EqualTo, Length from app.user.models import User class RegisterForm(FlaskForm): """Register form.""" username = String...
3,251
872
# -*- coding: utf-8 -*- from typing import List from tock.session.storage import Storage from tock.session.session import Session from tock.models import UserId class MemoryStorage(Storage): def __init__(self): self.__sessions: List[Session] = [] def get_session(self, user_id: UserId) -> Session: ...
674
195
import numpy as np import unittest import os import tempfile # import matplotlib.pyplot as plt from pystripe import core class TestWavedec(unittest.TestCase): def test(self): img = np.eye(5) coeffs = core.wavedec(img, wavelet='db1', level=None) approx = coeffs[0] self.assertEqual(l...
2,607
1,100
from ._callback_ptl import ReleaseAfterCallback
47
12
from distutils.core import setup from setuptools import find_packages setup( name='mean_average_precision', version='0.1', packages=find_packages(), url='', license='MIT', author='Mathieu Garon', author_email='mathieugaron91@gmail.com', description='' )
288
95
from menus import * from urls import *
38
11
from __future__ import absolute_import from __future__ import print_function import copy from collections import defaultdict import numpy as np import tensorflow as tf from tqdm import tqdm from six.moves import xrange import sys sys.path.append('../../.') from cleverhans.utils import other_classes from cl...
8,854
3,183
# -*- coding: utf-8 -*- """ Pretty print pykit IR. """ from __future__ import print_function, division, absolute_import from pykit.utils import hashable prefix = lambda s: '%' + s indent = lambda s: '\n'.join(' ' + s for s in s.splitlines()) ejoin = "".join sjoin = " ".join ajoin = ", ".join njoin = "\n".join...
2,009
753
from expr import Expr from stmt import Stmt class Parser: class ParserError(Exception): pass def __init__(self, tokens): self.tokens = tokens self.c_tok = 0 def match(self, *kinds): if self.c_tok == len(self.tokens): return False for kind in kinds: if kind == self.tokens[self....
9,059
3,108
from .multibox_tf_loss import MultiBoxLoss_tf_source from .knowledge_distillation_loss import KD_loss from .imprinted_object import search_imprinted_weights from .multibox_tf_loss_target import MultiBoxLoss_tf_target __all__ = ['MultiBoxLoss_tf_source', 'KD_loss', 'search_imprinted_weights', 'MultiBoxLoss_...
332
119
''' lab4 ''' #3.1 my_dict= { 'name':'Tom', 'id':123 } print(my_dict) #3.2 print(my_dict.values()) print(my_dict.keys()) #3.3 my_id='321' print(my_id) #3.4 my_dict.pop('name') print(my_dict) #3.5 my_tweet= { "tweet_id":1138, "coordinates": (-75, 40), "visited_countries": ["GR", "HK", "MY"] } print(my_twee...
549
294
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static import profiles.urls import accounts.urls import courses.urls import uploader.urls from . import views # Links URLs to views urlpatterns = patterns( '', ...
945
302
from datetime import datetime from . import db, login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(225)...
2,546
848
'''Test output of {tip}.''' from nose import * from util import * def _tip_rev(): opts = { 'template': '{rev}', } _ui = get_sandbox_ui() _ui.pushbuffer() commands.tip(_ui, get_sandbox_repo(), **opts) return _ui.popbuffer() def _tip_node(): opts = { 'template': '{node}', } ...
1,741
643
class EndState(metaclass=ABCMeta): pass
44
16
""" Open Orchestrator Cloud Radio Access Network 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...
3,542
1,010
import markdown from django.http import Http404 from django.shortcuts import render from pages.models import get_top_pages from userprofiles.models import Volunteer from .models import Article def index(request): try: article_list = Article.objects.values( 'id', 'title', 'created_date').order...
2,066
597
"""Test cases for recording functions with gradients.""" import pytest import numpy as np from .example_functions import function_1, Function2, Function5 from .recorder import recorder from ..interfaces.functions import CallableWithGradient @pytest.mark.parametrize( "function,params", [ (function_1, n...
727
237
""" __author__: HashTagML license: MIT Created: Sunday, 28th March 2021 """ import json import io import os import shutil import warnings from pathlib import Path, PosixPath from typing import Any, Callable, Dict, Optional, Union import pandas as pd from lxml import etree as xml from PIL import Image import xml.etree...
15,085
4,964
import socket import ssl from bad_requests.response import Response HTTP_STANDARD_PORTS = [80] HTTPS_STANDARD_PORTS = [443, 8080] BUFFERSIZE = 1024 class Request: def __init__(self, host, message, get_body=True): self.host = host self.message = message self.get_body = get_body def s...
2,960
918
import mock import unittest from StringIO import StringIO from supervisor_newrelic.status import Status def mock_request(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(sel...
2,055
723
import numpy as np from tqdm import tqdm import elo import utils import random import plotly.graph_objects as go from sklearn.metrics import r2_score from scipy.stats import linregress import pandas as pd from predictions import predict_tournament, ROUNDS ERRORS_START = 4 #after 4 seasons (starts counting errors 20141...
11,100
4,535
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 19 13:21:45 2017 @author: davidpvilaca """ import matplotlib.pyplot as plt import numpy as np import cv2 def getHist(arr_img): hists = [] sm = [] for img in arr_img: hist = cv2.calcHist([img], [0, 1, 2], None, [8, 8, 8], [0, 2...
3,075
1,155
import copy import json import logging import os import shutil from distutils.version import LooseVersion from threading import Lock from typing import List, Dict, Optional from zipfile import ZipFile import aiofiles from tornado.ioloop import IOLoop from package_management.constants import zpspec_filename, package_n...
8,005
2,319
""" encode the word on a pure state. """ import pennylane as qml def put_word_on_qubits(word_rep, qubits, base="X"): """ :param word_rep: "00..10..0" :param qubits: :param base: """ word_rep = str(word_rep) if base == "X": for i in range(len(word_rep)): if word_rep[i]...
631
242
from datetime import date from functools import partial import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import pyro import torch from pyro import poutine from pyro.infer.autoguide import AutoNormal, init_to_mean from scipy.sparse import issparse from scvi import _CONSTANTS from...
17,667
5,132
import os from django.conf import settings DEFAULT_BINARY_SCANIMAGE_PATH = '/usr/bin/scanimage' DEFAULT_SOURCES_BACKEND_ARGUMENTS = { 'mayan.apps.sources.source_backends.SourceBackendSANEScanner': { 'scanimage_path': DEFAULT_BINARY_SCANIMAGE_PATH } } DEFAULT_SOURCES_CACHE_STORAGE_BACKEND = 'django.cor...
570
227
import warnings import time import random import util from test_base import TestCase class Test_AdvancedSearch(TestCase): def get_radio(self, name): return self.q('#search-option .content form input[type="radio"][name="%s"]:checked' % name) def set_size(self, wlt, hlt, wgt, hgt): for name in 'wlt', 'hlt...
3,050
1,172
import discord from discord.ext import commands from service.utils import TemplateColours class Help_command(commands.MinimalHelpCommand): async def send_pages(self): ctx = self.get_destination() self.paginator.suffix = "\nif something is wrong, he is to blame\n ---> <@202011264589758464>" ...
511
162