text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import re import time import MySQLdb s = requests.Session() login_url = "http://www.trueworldagency.com/member/login_ok.asp" login_data = {'upw': '07092519', 'uid': '07092519'} s.post(login_url, login_data) counter = 0 trip_bookingID = [] trip_perio...
5,730
2,622
# Code for extract the information from the web # with the <id> information into the bolivia_power_1.csv file # input: bolivia_power_1.id.csv # output 6x.npy array file: # <nodes_ids.lat,lon> <node.tags> # <way.ids> <way.ref> <way.tags> # ... # v. 1.1 #import pandas as pd import numpy as np...
6,718
2,379
from api.utils.config import settings def test_config_validation() -> None: assert type(settings.host) == str assert type(settings.port) == int assert type(settings.expire) == int
194
57
#!/bin/python3 import math import os import random import re import sys # Complete the maximizingXor function below. def maximizingXor(l, r): result = [] for num1 in range(l,r+1): for num2 in range(l,r+1): xor = num1^num2 result.append(xor) return max(result) i...
526
193
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License,...
2,216
619
# Copyright © 2020 by Spectrico # Licensed under the MIT License model_file = "model-weights-spectrico-car-colors-recognition-mobilenet_v3-224x224-180420.pb" # path to the car color classifier label_file = "labelsC.txt" # path to the text file, containing list with the supported makes and models input_layer = "inpu...
436
160
#! /usr/bin/env python """Exploring Genie's ability to gather details and write to CSV This script is meant to be run line by line interactively in a Python interpretor (such as iPython) to learn how the Genie and csv libraries work. This script assumes you have a virl simulation running and a testbed file created. ...
4,417
1,348
import os, sys import json as _json from flask import Flask, Response, request app = Flask(__name__) app.debug = True import lib @app.route("/", methods=["HEAD", "GET", "POST", "DELETE", "PUT"]) def adapter(): json = request.get_data() decoded = _json.loads(json) docker_json = _json.loads(decoded['Clien...
1,159
362
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with # the License. Y...
1,316
392
n = int(input()) for _ in range(n): line = input() prev = '' counter = 0 for char in line: if char != prev: if prev != '': print(counter, prev, end = ' ') prev = char counter = 1 else: counter += 1 print(counter, prev)
280
100
# built-in import os import logging # installed import pandas as pd import seaborn as sns from matplotlib import pylab # custom import src.settings from src.utils.log_utils import setup_logging, LogLevel from src.utils.config_loader import ConfigLoader, Config def setup_jupyter( root_dir: str, config_path: s...
1,514
520
from django.db import models from django.contrib.auth.models import User from core.models import Profile from array import * from datetime import datetime from django.utils import timezone class Contest(models.Model): """ Contests models are used to store save contests as object. Contests contain problems, use...
3,169
836
# -*- coding: utf-8 -*- """ Special compiler-recognized numba functions and attributes. """ from __future__ import print_function, division, absolute_import __all__ = ['NULL', 'typeof', 'python', 'nopython', 'addressof', 'prange'] import ctypes from numba import error #--------------------------------------------...
2,659
699
""" Base class for renderers. """ from itertools import chain import re import sys from typing import Optional from mistletoe import block_tokens, block_tokens_ext, span_tokens, span_tokens_ext from mistletoe.parse_context import ParseContext, set_parse_context class BaseRenderer: """ Base class for rendere...
7,602
2,136
if '__file__' in globals(): import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import math import numpy as np import matplotlib.pyplot as plt import dezero from dezero import optimizers import dezero.functions as F import dezero.datasets as datasets from dezero.models import MLP from ...
2,123
829
#!/usr/bin/env python ''' Plots velocity profiles for a diagnostic solve for a range of resolutions, with and without GLP. ''' import numpy as np import netCDF4 #import datetime # import math # from pylab import * from optparse import OptionParser import matplotlib.pyplot as plt from matplotlib import cm # from matplot...
2,807
1,040
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ """ from .exclude import ExcludeSchema, rating_indices from .spec import SpecSchema, loadspec, savespec from .tags import BoldTagsSchema, FuncTagsSchema, entities, entity_long...
2,713
880
#!/usr/bin/env python3 from game import World from game.creatures import Humanoid, Unit from game.creatures.adventurers import Adventurer, Party from game.objects.containers import Container from game.places.underground import Dungeon from game.dice import d4 from pathlib import Path import pickle import sys import u...
4,363
1,353
class HelloPy: def hello(self): print("Hello Python!") HelloPy().hello()
87
30
from cx_Freeze import setup, Executable import requests.certs # Dependencies are automatically detected, but it might need # fine tuning. buildOptions = dict(packages = [], excludes = [], include_msvcr=True, include_files=[(requests.certs.where(),'cacert.pem')]) import sys base = 'Win32GUI' if sys....
590
189
def greeting(name: str) -> str: return f"Hello, {name}" print(greeting("John")) # "Hello, John"
103
41
# Import elasticsearch module from elasticsearch import Elasticsearch,ImproperlyConfigured,TransportError import json class ElasticsearchConnector: def __init__(self,credobject=None): """ Description: Accepts elasticsearch connection parameters and connects to elasticsearch cloud """ #Parameter chec...
2,742
890
from numpy import * from scipy.signal import correlate2d from numpy.random import randint,choice,uniform from matplotlib.pyplot import * import matplotlib.pyplot as plt from os import system class KineticMonteCarlo(object) : def __init__( self, Model ) : # reference state ...
15,813
6,377
import time import cv2 import numpy as np from ..openvino_base.base_model import Base class GazeEstimation(Base): """Class for the Gaze Estimation Recognition Model.""" def __init__( self, model_name, source_width=None, source_height=None, device="CPU", thres...
4,434
1,468
import warnings import matplotlib.pyplot as plt import pandas as pd import pytask import seaborn as sns from src.config import BLD from src.config import PLOT_END_DATE from src.config import PLOT_SIZE from src.config import PLOT_START_DATE from src.config import SRC from src.plotting.plotting import style_plot from s...
1,982
705
from typing import Optional from pydantic import BaseModel, Field class BrandModel(BaseModel): brand: str = Field(...) auth_key: Optional[str] user_id: str = Field(...) class Config: allow_population_by_field_name = True schema_extra = { "example": { "brand...
734
250
# thanks to Francis Song for this function # source: http://www.nervouscomputer.com/hfs/cmdscale-in-python/ from __future__ import division import numpy as np def cmdscale(D): """ Classical multidimensional scaling (MDS) ...
2,917
551
from flask import Flask from flask import Flask, flash, redirect, render_template, request, session, abort import os import newtrain app = Flask(__name__) @app.route('/') def home(x): return x @app.route('/login', methods=['POST']) def do_admin_login(): url_new=request.form['username'] x=newtrai...
443
161
from os.path import abspath, dirname with open(dirname(abspath(__file__))+'/../VERSION', 'r') as version_file: __version__ = version_file.read().replace('\n', '').strip()
178
63
from __future__ import division import numpy as np import numpy.testing.decorators as dec import nose.tools as nt import statsmodels as sm import matplotlib.pyplot as plt from selection.algorithms.sqrt_lasso import (sqrt_lasso, choose_lambda, estimate_sigma, data_carving, split_model)...
9,150
3,308
""" Train a noised image classifier on ImageNet. """ import os import blobfile as bf import torch as th import torch.distributed as dist import torch.nn.functional as F from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.optim import AdamW import torch from pathlib import Path import s...
8,607
2,755
#!/usr/bin/python3 -u import threading import time import queue import socket import grpc import karmen.karmen_pb2 as pb import karmen.karmen_pb2_grpc as pb_grpc class Karmen: def __init__(self, name=socket.gethostname(), hostname="localhost", port=8080): super().__init__() self.name = name ...
3,015
913
def fun(name, age=20): print(name, age) fun('Emma')
54
27
import socket import threading import signal import sys import fnmatch import utils from time import gmtime, strftime, localtime import logging config = { "HOST_NAME" : "192.168.0.136", "BIND_PORT" : 12345, "MAX_REQUEST_LEN" : 1024, "CONNECTION_TIMEOUT" : 5, ...
6,680
1,918
''' xbox.py Responsible for getting information directly from controller Courtesy Aaron Schif, former member Don't touch this file, it's perfect. ''' from math import isclose from collections import namedtuple import sdl2 from sdl2 import ext ButtonEvent = namedtuple('ButtonEvent', ['time', 'state']) Ax...
9,336
3,055
from openrec.legacy.recommenders import VisualPMF from openrec.legacy.modules.interactions import PointwiseGeCE class VisualGMF(VisualPMF): def _build_default_interactions(self, train=True): self._add_module( "interaction", PointwiseGeCE( user=self._get_module("use...
765
226
from xml.etree import ElementTree as ET from explorecourses import * class TestTag(object): @classmethod def setup_class(cls): text_tag = ( '<tag>' '<organization>EARTHSYS</organization>' '<name>energy_foundation</name>' '</tag>' ) cls....
732
240
from flask import Flask import easyWik app = Flask(__name__) @app.route('/') def usage(): return "you shouldn't be here." @app.route('/<title>') def simplify(title): # do some magic return easyWik.run_main(title) # return title if __name__ == "__main__": context = ('yourserver.crt','yourserver.k...
385
141
def init_s(data): return ("init", [ [ # set configuration time "$getTime", "configuration_millis", # set state initially below lower threshold "$=(const)=", "state", "@<t", "$printInt_ln", data['sensorIdentifier'], # set requestString...
458
112
""" Link extraction for auto scraping """ from scrapy.link import Link from scrapy.selector import Selector from slybot.linkextractor.base import BaseLinkExtractor class XmlLinkExtractor(BaseLinkExtractor): """Link extractor for XML sources""" def __init__(self, xpath, **kwargs): self.remove_namespace...
1,521
472
TITLE = 'Knight of Valhalla' SCREEN_ROWS = 9 SCREEN_COLUMNS = 16 SIZE = screen_width, screen_height = 64 * 16, 64 * 9 FPS = 60 tile_size = 64 ## Speeds WORLD_SPEED = 1 DEFAULT_PLAYER_SPEED = 5 ASPHALT_SPEED = 1 * DEFAULT_PLAYER_SPEED GRASS_SPEED = 1 * DEFAULT_PLAYER_SPEED DIRT_SPEED = 0.6 * DEFAULT_PLAYER_SPEED WATER_...
643
357
""" A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: The area of the rectangular web page you designed must equal to the given target area...
1,319
429
from flask_restful import Resource, marshal from flask_pdv.ext.api import requests from flask_pdv.ext.db.models import TransacaoModel from flask_pdv.ext.db.schemas import transacao_field from flask_pdv.ext.db import db class Transacao(Resource): def get(self): transacao = TransacaoModel.query.all() ...
891
291
from functools import wraps from time import sleep from typing import List from .rate_limit import RateLimit from .exceptions import RateLimitHit class OnHitAction: raise_exception = 0 wait = 1 class RateLimiter: def __init__(self, storage=RateLimit, *, action=OnHitAction.raise_exception): self...
2,434
645
import json class AmsException(Exception): """Base exception class for all Argo Messaging service related errors""" def __init__(self, *args, **kwargs): super(AmsException, self).__init__(*args, **kwargs) class AmsServiceException(AmsException): """Exception for Argo Messaging Service API errors...
2,081
581
import pytz import datetime from fixture import DataSet, NamedDataStyle, SQLAlchemyFixture from pmg.models import ( db, House, Committee, CommitteeMeeting, Bill, BillType, Province, Party, CommitteeMeetingAttendance, Member, CallForComment, TabledCommitteeReport, Com...
18,871
6,264
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities driver = webdriver.Chrome("D:\chromedriver\chromedriver") driver.get("http://www.google.com") if not "Google" in driver.title: raise Exception("Unable to loa...
455
137
from PuppeteerLibrary.utils.coverter import str2bool, str2str import os import glob import shutil import time from PuppeteerLibrary.ikeywords.iformelement_async import iFormElementAsync class PuppeteerFormElement(iFormElementAsync): def __init__(self, library_ctx): super().__init__(library_ctx) asyn...
2,265
688
import shutil, os, csv, itertools, glob import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader import torch.optim as optim from sklearn.metrics import confusion_matrix import pandas as pd i...
7,187
2,585
# Copyright (c) 2003-2012 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: serviceinstall.py 1141 2014-02-12 16:39:51Z bethus@gmail.com $ # # Service Install Helper librar...
12,279
3,185
from direct.directnotify import DirectNotifyGlobal from pirates.reputation. DistributedReputationAvatarAI import DistributedReputationAvatarAI from Teamable import Teamable from direct.distributed.ClockDelta import globalClockDelta from pirates.piratesbase import EmoteGlobals class DistributedBattleAvatarAI(Distribut...
11,879
4,211
from __future__ import unicode_literals from django.db.migrations.executor import MigrationExecutor from django_migrate_project.loader import ProjectMigrationLoader class ProjectMigrationExecutor(MigrationExecutor): def __init__(self, connection, progress_callback=None): super(ProjectMigrationExecutor, ...
484
119
#!/usr/bin/env python """ Script pour déployer une VM TAT1 dont on a récupéré les informations Ecrit par Benoit BARTHELEMY benoit.barthelemy2@open-groupe.com """ import atexit import datetime import re import ssl from argparse import ArgumentParser from getpass import getpass from os import path from sys import exit ...
31,942
9,465
""" A form view can have a custom form_fields but reusing those fields that were deduced automatically, using grok.AutoFields: >>> grok.testing.grok(__name__) We only expect a single field to be present in the form, as we omitted 'size': >>> from zope import component >>> from zope.publisher.browser import Tes...
1,393
475
import os import sys import pandas as pd # USAGE: python cifar100_dirmap.py <path to cifar100 dataset directory> # Organized cifar100 directory can be created using cifar2png: https://github.com/knjcode/cifar2png if len(sys.argv) > 1: DATA_DIR = sys.argv[1] else: DATA_DIR = "./../data/cifar100" # Get class n...
1,398
524
""" Ensures there is no data past the deactivation date for deactivated participants. Original Issue: DC-686 The intent is to sandbox and drop records dated after the date of deactivation for participants who have deactivated from the Program This test will mock calling the PS API and provide a returned value. Every...
5,616
1,847
from django.shortcuts import render,redirect from django.contrib import messages, auth from django.contrib.auth.models import User from django.http.request import HttpRequest # Create your views here. def home(req): return redirect('login') def login(req): if req.method == 'POST': username = req.POST[...
2,499
654
from mpython import * import neopixel import time my_rgb = neopixel.NeoPixel(Pin(Pin.P13), n=24, bpp=3, timing=1) def flashlight(): for i in range(2): my_rgb.fill( (255, 0, 0) ) my_rgb.write() time.sleep_ms(50) my_rgb.fill( (0, 0, 0...
1,089
474
from checks import NaptanCheck # %% class StopsBearing(NaptanCheck): """[summary] top has a bearing that is different to the calculated bearing of the road link it is connected to. The test compensates for stops being snapped to the wrong side of the road. Therefore if the calculated bear...
1,449
371
"""Defines the trial class. """ from datetime import datetime from logging import getLogger logger = getLogger(__name__) class Trial(dict): def __init__(self, *args, **kwds) -> None: """Create a trial object. Trials objects are fancy dictionaries whose items are also attributes. They are ...
2,476
726
#!/usr/bin/env python import ast import sys import nltk import numpy as np from review_data import read_reviews ############################################################################### def main(): low = 3.0 high = 4.0 target_language = u"english" topics = [] with open(sys.argv[1]) as in...
1,839
585
import subprocess import sys import os # This code is meant to manage running multiple instances of my KMCLib codes at the same time, # in the name of time efficiency numLambda = 512 numStepsEquilib = 1600000 numStepsAnal = 16000 numStepsSnapshot = 1000 numStepsReq = 16000 sysWidth = 32 sysLength = 32 analInterval = 1...
1,068
408
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # fill initial set/dict s = {target-nums[0]} d = {nums[0]: 0} for i in range(1, len(nums)): if nums[i] in s: ...
1,063
354
from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def mainmenu(request): return render(request, 'main/mainmenu.html', {}) @login_required def user_admin(request): return render(request, 'main/user_admin.html', {}) @login_required def user_profile(...
589
182
""" Here we will show how to build a graph from a class inheritance structure. Since we will n change the class of classes (type), we will use a wrapper to do this. """ from anygraph import Many """ First we define the wrapper class; because we create instances of ClassWrapper on the flight; to detect if the class w...
2,124
639
import time import numpy as np from os import path def read_graph(filename): i = 0 with open(path.join('.', filename), 'r') as f: for row in f.readlines(): if i == 0: _list = row.strip("\n").split(' ') n_vertex, n_edge = int(_list[0]), int(_list[1]) ...
2,069
791
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import io import random import numpy as np def visualizationpreprocess(age,sex,cp,trestbps,restecg,chol,fbs,thalach,exang,oldpeak,slope,ca,thal,result): if sex=="male": sex=1 else: sex=0 ...
2,448
978
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/15 16:36 # @Author : bxf # @File : P_DB_OPT.py # @Software: PyCharm import pymysql import json from datetime import date, datetime from model.util import md_Config from model.util.PUB_LOG import * ''' 提供数据的增删改查功能: ''' clas...
6,006
2,465
import pybullet as p import pybullet_data cid = p.connect(p.SHARED_MEMORY) if (cid < 0): p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.loadURDF("plane.urdf") quadruped = p.loadURDF("quadruped/quadruped.urdf") logId = p.startStateLogging(p.STATE_LOGGING_MINITAUR, "LOG00048.TXT", [quadru...
448
191
#!/usr/bin/env python3 from setuptools import setup fuse_reqs = [ 'fuse-python >= 0.3.1; python_version < "3"', 'fuse-python >= 1.0.0; python_version > "3"', ] readme = open('README.md', 'r').read() readme = readme.replace( '(FUSE.md)', '(https://github.com/drougge/wellpapp-pyclient/blob/master/FUSE.md)' ) setu...
1,025
450
from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. # create a new attribute in your model class FormModel(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) blog_title = models.CharF...
506
148
import socket import threading conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM) conn.bind (('', 7070)) conn.listen() clients = [] print ('Start Server') def new_client(): while True: clientsocket, address = conn.accept() if clientsocket not in clients: clients.append(clientsocket) threading.Thread...
715
264
from qtpy.QtCore import Signal from qtpy.QtWidgets import QDialog, QDialogButtonBox, QListWidget, QVBoxLayout class PopInDialog(QDialog): pop_in_tabs = Signal(list) def __init__(self, parent, loggers): super().__init__(parent) self.loggers = loggers self.setupUi() def setupUi(se...
1,563
492
# Importing required libraries from tkinter import * from tkinter import messagebox as mb from tkinter import ttk import random # function to create screen for the game def board(): global value,w # initialising screen root=Tk() root.geometry("320x335") root.title("MineSweeper") root.resizable(...
6,730
2,901
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt4 (Qt v4.8.7) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x05\x96\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x18\x00...
125,439
116,828
# -*- coding: utf-8 -*- from .constants import * from . import io from . import ai from . import filters from ._version import __version__ __version_date__ = "Sun Feb 14 14:28:51 2016 +0100" __version_hash__ = "1d5f7f3"
225
100
# # PySNMP MIB module ONEFS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEFS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:34:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
2,309
850
# Generated by Django 3.1.3 on 2021-05-20 06:04 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), ('ChatAPI', '00...
926
302
""" Python unit tests """ import pytest, json from streetwise.models import Campaign from . import app, app_context, db @pytest.fixture(scope="module") def client(): app.config['TESTING'] = True return app.test_client() def test_campaign_all(client): with app_context: campaign1 = Campaign() ...
1,240
398
# Generated by Django 3.1.13 on 2021-10-02 23:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('plugins', '0002_auto_20211002_2236'), ] operations = [ migrations.DeleteModel( name='NewCoinConfig', ), ]
303
119
from nltk.corpus import movie_reviews import random import cython_module as cm import cytoolz def label_docs(): docs = [(list(movie_reviews.words(fid)), cat) for cat in movie_reviews.categories() for fid in movie_reviews.fileids(cat)] random.seed(42) random.shuffle(docs) return...
831
287
# encoding: utf-8 # pylint: disable=E1101 # 加權指數 # https://www.twse.com.tw/zh/page/trading/indices/MI_5MINS_HIST.html import scrapy from scrapy import signals, Spider from urllib.parse import urlencode import time from random import randint import datetime import logging from copy import copy from dateutil.relativedel...
4,900
1,539
from json import loads from time import time def main(self): def handler(message): if message["channel"] == "/service/player" and message.get("data") and message["data"].get("id") == 2: self.questionStartTime = int(time() * 1000) self._emit("QuestionStart",loads(message["data"]["con...
374
108
import torch.nn as nn import numpy class BinOp(): def __init__(self, model): count_conv2d = 0 for m in model.modules(): if isinstance(m, nn.Conv2d): count_conv2d += 1 start_range = 1 end_range = count_conv2d - 2 self.bin_range = numpy.linspace...
2,973
972
import numpy as np import os from os.path import dirname, join from modules.numpy import covmix, varroll from modules.pandas import DesignMatrix from modules.scipy.stats import gaussian_mixture def gaussian_mixture_generate(file, train=60000, test=60000, validate=10000): dim_x, dim_z = 784, 10 # distribution...
1,198
469
import pyttsx3 #pip install pyttsx3 import speech_recognition as sr #pip install speechRecognition import datetime import wikipedia #pip install wikipedia import webbrowser import os import smtplib import random engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') # print(voices[0].id) engine.setProper...
7,860
2,355
import json from pathlib import Path from PyQt5 import uic from PyQt5.QtCore import pyqtSignal from PyQt5.QtWidgets import QWidget from vk_api.vk_api import VkApi from utils import print_message, validate_QLineEdit class AuthForm(QWidget): authorized_successfull = pyqtSignal() def __init__(self): ...
1,620
498
"""Module responsible to parse Exif information from a image""" import math import datetime from enum import Enum from typing import Optional # third party import exifread import piexif MPH_TO_KMH_FACTOR = 1.60934 """miles per hour to kilometers per hour conversion factor""" KNOTS_TO_KMH_FACTOR = 1.852 """knots to kil...
11,467
4,072
# NPTEL EXERCISE 5 courses = {} students = [] grades = {} f = 0 while(True): S = input() if S=="EndOfInput": break if S=='Courses': f = 1 continue elif S=='Students': f = 2 continue elif S=='Grades': f = 3 continue i...
1,505
588
#!/usr/bin/python3 import abc import re import logger class Provider(metaclass=abc.ABCMeta): def __init__(self, access_key_id, bucket, cacert, endpoint, no_ssl_verify, region, secret_access_key, staging_directory): """Instantiate a new 'Provider' object. Should only be created by implementing super classe...
5,122
1,496
from django.contrib import admin from .models import User , Trip, Notification , Spending # Register your models here. admin.site.register(User) admin.site.register(Trip) admin.site.register(Notification) admin.site.register(Spending)
235
67
''' The follwing code runs a test lstm network on the CIFAR dataset I will explicitly write the networks here for ease of understanding with cnn_sropout = 0.4 and rnn dropout = 0.2and lr = 1e-3 and res = 8 ################# cnn_gru_True Validation Accuracy = [0.3408, 0.411, 0.44, 0.4448, 0.466, 0.4684, 0.4802, 0.4...
70,500
63,660
import os from domain.base import Domain, Yaml from properties import APPLICATION_PROPERTIES class Config(Domain): def __init__(self, file_name, *args, **kwargs): super(Config, self).__init__(*args, **kwargs) self.file_name = file_name @property def file_path(self): return os.pa...
549
179
from __future__ import annotations # SOURCE: https://blog.bartab.fr/fastapi-logging-on-the-fly/ import logging from fastapi import APIRouter, HTTPException from ultron8.api.models.loggers import LoggerModel, LoggerPatch LOG_LEVELS = { "critical": logging.CRITICAL, "error": logging.ERROR, "warning": logg...
2,719
892
# Python Program To Understand The Usage Of try With finally Blocks ''' Function Name : Usage Of try With finally Blocks Function Date : 23 Sep 2020 Function Author : Prasad Dangare Input : String Output : String ''' try: x = int(input('Enter A Number : ')) y = 1...
422
148
def fib1(n: int) -> int: return fib1(n-1) + fib1(n-2) print(fib1(5))
72
39
#!/usr/bin/env python """ Background: -------- GliderScienceSet_Plots.py Purpose: -------- History: -------- """ import argparse import os from io_utils import ConfigParserLocal import numpy as np import xarray as xa # Visual Stack import matplotlib as mpl import matplotlib.pyplot as plt def plot_ts(...
4,036
1,541
""" Define models used in this app. This module only serves to provide some consistency across the `users`, `accounts` , `projects` etc apps so that you can `from users.models import Users`, just like you can for `from projects.models import Projects` and instead of having to remember to do the following. """ from ty...
17,416
4,957
from trex.emu.api import * from trex.emu.emu_plugins.emu_plugin_base import * import trex.utils.parsing_opts as parsing_opts class DHCPSRVPlugin(EMUPluginBase): """ Defines DHCP Server plugin based on `DHCP <https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol>`_ Implemented based on `RFC 2...
6,075
1,811
# Copyright 2020 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...
2,683
921