text
string
size
int64
token_count
int64
from utilities.getStore import getStore filePath = "./entities/bill/store.json" productFilePath = "./entities/product/store.json" def getProduct(name): for product in getStore(productFilePath): if product["name"] == name: return product def getProductBillsAverage(name): productPriceSummat...
1,974
596
#discord.pyのインポート from asyncio import sleep import discord client = discord.Client() #BOTログイン処理 @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') await client.change_presence(game=discord.Game(name='!delchat *')) # BOT動作プログラム @cli...
1,826
650
# Generated by Django 3.2.11 on 2022-01-08 03:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='Element', fi...
1,191
348
#!/usr/bin/python ########################################################################### # # Copyright 2019 Dell, 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....
5,468
1,792
import os import time exec_count = 100 cmds = [] cmds.append("tar -cPzf /opt/web.tar.gz /opt/web/ /opt/soft") cmds.append("rm -f /opt/web.tar.gz") for i in range(exec_count): for cmd in cmds: if os.system(cmd) != 0: break time.sleep(1)
268
111
from .help import help_handler from .pre import pre_handler from .now import now_handler from .filter import filter_handler
123
32
import utils.fileutils as futils inp = futils.read_list("../data/day6.txt") nums_dict = dict() group_size, res_count = 0, 0 for line in inp: if line == "": # res_count += len(nums_set) for k, v in nums_dict.items(): if v == group_size: res_count += 1 nums_dict = ...
581
220
from . import types from . import dep from . import RuntimeModel from . import Metadata class Property(object): def __init__(self, name, description, namespace='', visible=False, readonly=False, define_name=None, long_description=None): ''' :param name: Name of the property (string) :param...
45,165
12,260
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tests/schematics_proto3_tests.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descri...
48,837
19,293
from rest_framework.serializers import ModelSerializer from accounts.models import Account class AccountSerializer(ModelSerializer): class Meta: model = Account fields = [ 'account_id', 'limit', ]
241
59
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import logging import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from config impor...
6,320
2,546
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-09-21 17:17 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('dashboard', '0011_auto_...
1,376
432
from .private.HMC804x import _RohdeSchwarzHMC804x from qcodes.utils.deprecate import deprecate_moved_to_qcd @deprecate_moved_to_qcd(alternative="qcodes_contrib_drivers.drivers.RohdeSchwarz.HMC8042.RohdeSchwarzHMC8042") class RohdeSchwarzHMC8042(_RohdeSchwarzHMC804x): """ This is the qcodes driver for the Rohd...
476
199
# Multiples -- Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise for i in range(1, 1000, 2): print(i) # Multiples -- Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000 for m in range(5, 1000000, 5): ...
682
306
#!/usr/bin/env python3 """ Demo example to test CFG-VALSET ublox message - generation 9 @author: mgesteiro """ import sys import time from serial import Serial, SerialException, SerialTimeoutException from pyubx2 import ( UBXMessage, GET, SET, VALSET_RAM, UBXMessageError, UBXTypeError, UBXP...
2,817
1,104
import pygame import time import sys, random pygame.init() yellow = (255, 255, 102) green = (0, 255, 0) black = (0,0,0) width = 1280 height = 720 gameDisplay = pygame.display.set_mode((width, height)) pygame.display.set_caption('Snake Game By Saswat Samal') clock = pygame.time.Clock() snake_block = 10 snak...
3,996
1,401
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matm...
918
395
# Generated by Django 2.2.20 on 2021-05-27 14:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analyzer', '0005_auto_20210526_1755'), ] operations = [ migrations.AddField( model_name='graphitevariable', name='f...
465
171
# -*- coding: utf-8 -*- """ Solution to Project Euler problem X Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ import math def isTri(n): return ((math.sqrt(1+8*n)-1)/2).is_integer() def isSqr(n): return (math.sqrt(n)).is_integer() def isPent(n): return ((1+math.sqrt(1+24*n)...
2,865
1,048
from shop.models import Product from django.shortcuts import render_to_response from django.template import RequestContext def index_view(request): products = Product.objects.all() return render_to_response("cuescience_shop/index.html", RequestContext(request, {"products": products}))
302
84
import numpy as np from qrogue.game.logic.actors import StateVector stv = StateVector([1 / np.sqrt(2), 0 + 0j, 0 + 0j, 1 / np.sqrt(2)]) #stv.extend(1) print(stv)
163
76
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Image, Comment, Like from .serializers import ImageSerializer, CommentSerializer, LikeSerializer class Feed(APIView): def get(self, request, format=None): user ...
3,190
934
#!/usr/bin/env python """ Compute the comparison of the analytic and experimental PSD matrices. This will generate Figure 1. This is probably the only example that will run in a reasonable time without a GPU. For more details on the method see https://arxiv.org/abs/2106.13785. """ import numpy as np import matplotli...
4,195
1,479
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql class WebSpiderPipeline(object): def init_insert_db(self,key,table_name): pass def proc...
5,581
1,393
"""mixin to add destinations to config attributes""" class AddDestinationMixin(object): """stuff""" def add_destination_chooser(self, destination_chooser_mappings): """adds destination_choosers to config""" pass
239
72
#!/usr/bin/env python3 """ Description: ------------ This Python script (assumes Python3) downloads boundary conditions files from AWS S3 to a target directory for the requested date range. Remarks: -------- (1) Jiawei Zhuang found that it is much faster to issue aws s3 cp commands from a bash script than...
6,298
1,813
from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. # import pymysql # # pymysql.install_as_MySQLdb()
216
66
____notmain: BeginFunc 0 ; EndFunc ;
39
19
""" Ejercicio para operación entre currencies """ """ Representación del currency""" class Curency: def __init__(self, name, symbol, factor): self.name = name self.symbol = symbol self.factor = factor # No me queda muy claro el uso de esta función, sirve para mostrar puntualmente qué?...
483
161
import os from IPython import get_ipython # need this fix first os.environ["LD_PRELOAD"] = "" os.system("apt remove libtcmalloc-minimal4") os.system("apt install libtcmalloc-minimal4") os.environ["LD_PRELOAD"] = "/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4.3.0" os.system("dpkg -L libtcmalloc-minimal4") # then ...
587
242
from django.db import models from django_countries.fields import CountryField from localflavor.us.models import USStateField from base.models import EONBaseModel class Amenity(EONBaseModel): """Common amenities, i.e. Pool, Lake, Hiking Trail, Primitive Camping, etc.""" name = models.CharField(max_length=50)...
2,352
808
#!/usr/bin/env python2.7 import sys reload(sys) sys.setdefaultencoding("utf-8") from flask import Flask, render_template, request, jsonify import argparse import datetime import os, sys import requests from socket import error as SocketError import errno import json import pika import uuid app = Flask(__name__) @a...
3,891
1,246
import numpy as np from ComponentStructural import ComponentStructural from ..subsystems import SubsystemStructural class Component3D(ComponentStructural): pass
167
42
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler import logging from utils import TELEGRAM_TOKEN from handlers import start, ask_new_url, get_url, get_description, cancel from handlers import URL_URL, URL_DESCRIPTION logging.basicConfig(format='%(levelname)s - %(message)s...
1,063
341
#!/usr/bin/env python """ Simple surface plot example """ from gr import * from math import * x = [-2 + i * 0.5 for i in range(0, 29)] y = [-7 + i * 0.5 for i in range(0, 29)] z = list(range(0, 841)) for i in range(0, 29): for j in range(0, 29): r1 = sqrt((x[j] - 5)**2 + y[i]**2) r2 = sqrt((x[j] + 5)**2 +...
841
493
# function that will be distributed def inc(x): return x + 2 # wrapper function, uses the dask client object def main(context, x=1, y=2): context.logger.info(f"params: x={x},y={y}") print(f"params: x={x},y={y}") x = context.dask_client.submit(inc, x) print(x) print(x.result()) context.log_...
344
129
"""Main functionalities.""" from .image.image import (Image, RawDataContainer) from .image.color_format import AVAILABLE_FORMATS from .parser.factory import ParserFactory import cv2 as cv import os def load_image(file_path, color_format, width): try: image = Image.from_file(file_path) parser = Pa...
1,495
464
"""demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
1,423
460
from django.urls import path from .views import teacherregister,studentregister,login_view,logout from . import views from .views import ( ClassroomCreateView,ClassroomListView,ClassroomDetailView,ClassroomUpdateView,ClassroomDeleteView, SubjectCreateView,SubjectListView,SubjectDetailView,SubjectUpdateView,SubjectDelet...
3,478
955
#!/usr/bin/env python """ CLI tool to runs various tasks related to QA. """ import os import time from pathlib import Path import sys import traceback import json import yaml import uuid import datetime import click from .run import RunContext from .runners import runners, Job, JobGroup from .runners.lsf import LsfPr...
44,634
14,258
# -*- coding: utf-8 -*- import threading import time import global_def as gd from db_reader import DbReaderDef, DbReaer from queue import Queue, Empty class DataHandlerThd(threading.Thread): def __init__(self, req_queue: Queue, rcv_queue: Queue, db_host: str, db_port: int, db_user: str, db_pw: str, db_name: str, ...
5,838
1,964
import logging from rest_framework import mixins, generics, permissions, exceptions from django.conf import settings from django.utils import timezone from .serializers import CategorySerializer, TagSerializer, TodoSerializer from .models import Category, Tag, Todo logger = logging.getLogger(__name__) class MyGen...
7,865
2,237
# coding=utf-8 # # This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis) # # Most of this work is copyright (C) 2013-2015 David R. MacIver # (david@drmaciver.com), but it contains contributions by others. See # https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a # full list of...
16,294
4,363
""" Script to generate a security pipeline for PDF files. It does the following: - Adds specified meta-data - Encrypts file Run: python3 pipeline.py """ from PyPDF2 import PdfFileWriter, PdfFileReader from PyPDF2.generic import NameObject, createStringObject def encrypt(input_pdf, output_pdf, password): pdf...
2,014
689
import glob from numpy.linalg import norm import numpy as np from copy import deepcopy as copy from MergeTrack.merge_functions import read_ann,read_props from MergeTrack.ReID_net_functions import ReID_net_init, add_ReID input_images = "DAVIS/val17/" input_proposals = "DAVIS/ReID_props/" first_frame_anns = "DAVIS/val1...
1,989
754
import unittest import string_matching class StringMatchingTest(unittest.TestCase): def test_string_matching_naive(self): t = 'ababbababa' s = 'aba' self.assertEquals(string_matching.string_matching_naive(t, s), [0, 5, 7]) t = 'ababbababa' s = 'abbb' self.assertEq...
1,377
534
import numpy as np import pytest import molecool_test @pytest.fixture def methane_molecule(): symbols = np.array(['C', 'H', 'H', 'H', 'H']) coordinates = np.array([ [1, 1, 1], [2.4, 1, 1], [-0.4, 1, 1], [1, 1, 2.4], [1, 1, -0.4], ]) return symbols, coordinates...
1,411
558
from unittest import TestCase from unittest.mock import patch, MagicMock, PropertyMock from basketball_reference_web_scraper.html import SearchPage, PlayerSearchResult class TestSearchPage(TestCase): def test_nba_aba_baa_players_content_query(self): self.assertEqual( SearchPage(html=MagicMock...
5,004
1,622
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
19,891
5,288
from abc import ABC from typing import List from zeep import CachingClient, Client, Settings from .exceptions import APIError class _BaseClient(ABC): """API клиент сервиса отслеживания посылок. https://tracking.pochta.ru/specification """ WSDL = '' def __init__(self, login: str, password: str...
6,705
2,032
# @Time: 2022/4/12 20:50 # @Author: chang liu # @Email: chang_liu_tamu@gmail.com # @File:4.4.Implementing_the_iterator_protocol.py ################ clean version ######################### # class Node: # def __init__(self, val): # self._value = val # self._children = [] # # def __repr__(self): ...
2,291
731
import tensorflow as tf import tensorflow_probability as tfp import numpy as np import pickle import random from utils import gauss_cross_entropy tfk = tfp.math.psd_kernels def _add_diagonal_jitter(matrix, jitter=1e-6): return tf.linalg.set_diag(matrix, tf.linalg.diag_part(matrix) + jitter) cla...
29,762
11,403
from abc import ABC, abstractmethod from argparse import Namespace, ArgumentParser from spotty.commands.writers.abstract_output_writrer import AbstractOutputWriter class AbstractCommand(ABC): """Abstract class for a Spotty sub-command.""" @property @abstractmethod def name(self) -> str: """Th...
1,069
283
# -*- 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 ...
9,495
2,772
import os.path import os from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from datetime import datetime # If modifying these scopes, delete the file token.json. SCOPES ...
6,981
2,191
from .QArithmetic import * from .qft import *
46
16
"""Calculate conditional probability of a short interevent time being followed by another short interevent time, compared with the unconditional probability. This is used to test whether fault records have memory """ import os, sys from glob import glob import numpy as np import matplotlib.pyplot as plt from QuakeRat...
2,631
900
import time #Controls functions for the delta sleep_time = 0.5 def turn_on_vacuum(): print("Turning on vacuum pump") def pickup(): print("Picking up sample...") time.sleep(sleep_time) def drop(): print("Dropping sample...") time.sleep(sleep_time) def move_to_start(): ...
643
221
# From The School of AI's Move 37 Course https://www.theschool.ai/courses/move-37-course/ # Coding demo by Colin Skow # Forked from https://github.com/lazyprogrammer/machine_learning_examples/tree/master/rl # Credit goes to LazyProgrammer from __future__ import print_function, division from builtins import range # Note...
3,120
1,055
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GTKcsvimport.py # # Copyright 2010-2015 Jose Riguera Lopez <jriguera@gmail.com> # # 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...
19,238
6,283
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
9,024
2,993
from tensorflow.contrib.slim.python.slim.data import data_provider from tensorflow.contrib.slim.python.slim.data import parallel_reader
137
40
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want wit...
1,205
341
# import colorgram # # colors = colorgram.extract('image.jpg', 30) # rgb_colors = [] # for color in colors: # rgb_colors.append((color.rgb.r, color.rgb.g, color.rgb.b)) # # print(rgb_colors) from turtle import Turtle, Screen import random color_list = [(238, 251, 245), (250, 228, 15), (213, 12, 8), (199, 11, 36),...
1,048
613
from django import forms from .models import UserAccount, JobPost, JobPostActivity, UserProfile class FormUserCreation(forms.ModelForm): UserTypes = ((1, 'Applicants'), (2, 'Organisations')) user_type = forms.ChoiceField(choices=UserTypes, widget=forms.Select(attrs={'class': ...
8,723
2,077
#!/usr/bin/env python #_MIT License #_ #_Copyright (c) 2017 Dan Persons (dpersonsdev@gmail.com) #_ #_Permission is hereby granted, free of charge, to any person obtaining a copy #_of this software and associated documentation files (the "Software"), to deal #_in the Software without restriction, including without limi...
5,538
1,768
# Generated by Django 3.2.7 on 2021-09-12 01:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AddField( model_name='userprofile', name='mail', ...
687
223
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
3,040
1,010
from pathlib import Path from unittest import mock import pytest from fab.build_config import AddFlags from fab.dep_tree import AnalysedFile from fab.steps.compile_fortran import CompileFortran # todo: we might have liked to reuse this from test_dep_tree from fab.util import CompiledFile @pytest.fixture def src_tre...
2,025
736
""" 5. Faça um programa que receba do usuário um arquivo texto e um caracter. Mostre na tela quantas vezes aquele caractere ocorre dentro do arquivo. """ arquivo=open('CursoUdemyPython/exercicios/Lista6/arq.txt') texto=arquivo.read() carac=input('Informe um caractere: ') ca=0 for c in texto: if(c == carac): ...
393
152
#--------------------------------------------------------- # Superset specific config #--------------------------------------------------------- ROW_LIMIT = 5000 SUPERSET_WEBSERVER_PORT = 8088 #--------------------------------------------------------- #--------------------------------------------------------- # Flask...
3,704
1,191
import argparse import cv2 import re import numpy as np import string import PIL import os,glob import ntpath import time import matplotlib.pyplot as plt from PIL import Image from yad2k.models.keras_yolo import (preprocess_true_boxes, yolo_body, yolo_eval, yolo_head, yolo_loss) fr...
5,038
1,781
""" =================================================================== Plot time-frequency representations on topographies for MEG sensors =================================================================== Both induced power and phase locking values are displayed. """ print(__doc__) # Authors: Alexandre Gramfort <g...
2,881
929
import bluetooth import sys, os import subprocess as sp import datetime from pushBulletForBluetooth import pushNotification from makeReminderforBluetooth import Reminder import csv class blueDev: def findmyDevice(self): sendPushBullet = pushNotification() timestamp = datetime.datetime.now()...
2,201
597
appendMe = '\nNew bit of information' appendFile = open('example.txt','a') appendFile.write(appendMe) appendFile.close()
127
43
from kafka import KafkaProducer TOPIC_NAME = 'items' KAFKA_SERVER = 'localhost:9092' producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER) producer.send(TOPIC_NAME, b'Test Message!!!') producer.flush()
209
85
from datetime import datetime import myfitnesspal import sqlite_utils import click from . import utils @click.group() @click.version_option() def cli(): "Save data from MyFitnessPal to a SQLite database" @cli.command() @click.argument( "db_path", type=click.Path(file_okay=True, dir_okay=False, allow_das...
954
329
import numpy as np class T1Hist: def __init__( self, max_t1: float = 3000, min_t1: float = 200 ): self.max_t1 = max_t1 self.min_t1 = min_t1 def get_t1_histogram(self, t1_matrix: np.ndarray, norm_m0_matrix: np.ndarray): t1_histogram = t1_matrix.astype(float).ravel() ...
849
352
import pluginpackageRENAME import preload import os if __name__ == "__main__": preload.preload() app = pluginpackageRENAME.app app.static_folder = os.path.join(os.getcwd(), "html") app.run()
209
76
import matplotlib.pyplot as plt import numpy as np import math import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit import json from scipy.interpolate import interp1d from data_utils import * def integral(y, x): area = 0 for xi, xj, yi, yj in zip(x[:-1], x[1:], y[:-1], y[1:]): ar...
6,948
3,598
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AoiInfoDTO import AoiInfoDTO from alipay.aop.api.domain.ItemStoreDTO import ItemStoreDTO class CircleRecommendItemDTO(object): def __init__(self): self._aoi_info = No...
8,392
2,737
import subprocess import time import logging import os import signal log = logging.getLogger(__name__) def runpreloadcommand(cmd,timeout,preload): newenv = dict(os.environ) newenv["LD_PRELOAD"] = preload process = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,env=new...
3,599
1,149
# drones/serializers.py file from rest_framework import serializers from drones.models import DroneCategory, Drone, Pilot, Competition from django.contrib.auth.models import User import drones.views class UserDroneSerializer(serializers.HyperlinkedModelSerializer): """serialize the drones related to a User""" ...
3,923
1,071
import learnables.py # création d'un objet Calamous class Calamous: #définition de son type et de si c'est un pokémon pokemon = True type_ = "Water" # définition de ses talents et de son genre (qui seront random) abilities = "Multicule" or "Glissade" or "Protéen" gender = "M" or "F" ...
1,471
552
import random import matplotlib.pyplot as plt import numpy as np from scipy import stats ############################ STATS input data ################################################ def return_nan_percentage(input_data): """ prints percentage of nan values in max. 3D sized array Parameters -----...
5,186
1,734
def load(): with open("input") as f: for x in f: a, b, = x.strip().split("|") yield {frozenset(x) for x in a.strip().split()}, [frozenset(x) for x in b.strip().split()] def decode_signal(signal): num = {} while len(num) < 10: for x in signal.difference(num.values()...
1,382
494
#!/usr/bin/env python # # This is the library for Grove Base Hat. # # Button Base Class # ''' ## License The MIT License (MIT) Grove Base Hat for the Raspberry Pi, used to connect grove sensors. Copyright (C) 2018 Seeed Technology Co.,Ltd. Permission is hereby granted, free of charge, to any person...
2,469
863
# Reverse a linked list # Developer: Murillo Grubler # https://www.hackerrank.com/challenges/reverse-a-linked-list/problem # Time complexity of reverse function: O(n) class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def _...
1,402
452
import os from PIL import Image import random from functools import wraps from flask import jsonify from flask_jwt_extended import get_current_user from .artpiece import Artpiece from .exceptions import InvalidUsage from web.extensions import cache #decorator to require admin_acccess for a route def access_level_requ...
1,737
496
import spconv import torch from torch import nn def residualBlock(channels, kernel_size=3): return spconv.SparseSequential( spconv.ConcatTable() .add(spconv.Identity()) .add(spconv.SparseSequential( nn.BatchNorm1d(channels), spconv.SubMConv3d(channels...
2,528
944
#!/usr/bin/env python # # Copyright (c) 2013 In-Q-Tel, Inc/Lab41, 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...
3,794
1,177
import copy import logging import math import torch from torch import nn logger = logging.getLogger('global') def init_weights_normal(module, std=0.01): for m in module.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear) or isinstance( m, nn.ConvTranspose2d): n...
2,659
945
# This Python file uses the following encoding: utf-8 import os; import sys; import urllib.request; from bs4 import BeautifulSoup; import wikipedia from PyQt5.QtWebEngineWidgets import *; from PyQt5.QtGui import QIcon; from PyQt5.QtWidgets import *; from PyQt5.QtNetwork import QNetworkProxy class AudioFile(QMainWindo...
3,000
972
__author__ = 'petriau' import requests # for HTTP requests from bs4 import BeautifulSoup # for HTML parsing url_SBM_FinanceProgress = 'http://sbm.gov.in/sbmreport/Report/Financial/SBM_StateReleaseAllocationincludingUnapproved.aspx' # Function to return HTML parsed with BeautifulSoup from a POST request URL and param...
16,649
11,608
def listprime(max): prime=[True]*max prime[0]=False prime[1]=False for x in range(max/2): if prime[x]: bei=x+x while bei<max: prime[bei]=False bei+=x return prime def listprimenumber(lpn): listprimelpn=listprime(lpn) ...
677
279
__author__ = 'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import scipy as sp import random import time # --------------------------------------------------------------- # Class - Graph # -----------------------...
4,189
1,166
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/login', methods=['POST']) def login(): return f'<h2>Name: {request.form["name"]}</h2><br><h2>Password: {request.form["password"]}' if __name__ == '__main__...
337
122
""" Django settings for spartify project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os ...
6,094
2,201
#!/usr/bin/env python # # tdwggeo2csv.py # # Description: convert TDWG plant distribution files out of the box to a single # CSV file # # TODO: should create new id's for each entry and have a tdwg_code for # each so we can maintain as much data as possbible # TODO: we should probably include the original text files ...
7,018
2,346
#!/usr/bin/python """ Program to read and parse haproxylogs to put them in shape to upload to DataLogger The input date schould be sorted by date, and finished the uploaded data will immediately split into TimeseriesArray, so no further data of this day could be appended """ import os import sys import gzip import logg...
7,386
2,317