text stringlengths 8 6.05M |
|---|
'''
Faire des tests sur les dimensions des fonctions, rapide juste un assert pour être sur
'''
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics as skt
from src.Activation.sigmoid import Sigmoid
from src.Activation.softmax import Softmax
from src.Loss.CESoftMax import CESoftMax
from src.Module... |
from discord.ext import commands
class SubcommandIsNone(commands.CommandError):
"""
Исключение, когда пользователь не указал подкоманду из группы команд
"""
def __init__(self, commands_group):
self.commands_group = commands_group
class CogImportError(commands.CommandError):
"""
Искл... |
# Generated by Django 2.2.4 on 2020-03-22 11:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("budget", "0009_quartertotal")]
operations = [
migrations.RemoveField(model_name="quartertotal", name="amount_pln"),
migrations.AlterField(
... |
import subprocess
import os
import tempfile
def importer(filename, type):
contents = ''
with tempfile.TemporaryDirectory() as tmpdir:
if type == 'png':
path = tmpdir + '/out'
redirected_output_file = open(os.devnull, "w")
subprocess.call(['tesseract', filename, path]... |
import unittest
from conans.test.utils.tools import TestClient
from conans.paths import CONANINFO
from conans.util.files import load
import os
class OptionTest(unittest.TestCase):
def parsing_test(self):
client = TestClient()
conanfile = '''
from conans import ConanFile
class EqualerrorConan(Cona... |
'''
Created on 2013-4-21
@author: Xsank
'''
import os
import re
import tokenize
from exception import TemplateError
from util import tou,abort,html_escape
from config import TEMPLATES,TEMPLATE_PATH,DEBUG
class BaseTemplate(object):
extentions = ['tpl','html']
settings = {}
defaults = {}
def __ini... |
#import sys
#input = sys.stdin.readline
def main():
N = int(input())
S = list(input())
ANS = []
t = 0
for s in S:
# print(t, ANS)
if t <= 1:
ANS.append(s)
t += 1
continue
if s != "x":
ANS.append(s)
t += 1
... |
list1 = list( range (1,31))
print(list1)
print('------------------------------\n')
print('\n'.join([' '.join('%d*%d=%d' % (x,y,x*y) for x in range(1,y+1)) for y in range(1,10)]))
print('-------------------------------\n')
list2 = [x*x for x in range(1,11)]
print(list2)
print('-------------------------------\n')
l... |
from django.http import request
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
#return HttpResponse("<em>My Second App</em>")
my_dict = {"insert_me" : "Hello, I am from views.py - I am the index page!",
"title" : "Index Pag... |
#!/usr/bin/env python
# encoding: utf-8
import unittest
import simulator.tests.mm1 as mm1
import simulator.tests.sim as sim
# Run tests
# 1. MM1EventHandler class
unittest.TextTestRunner(verbosity=2).run(
unittest.TestLoader().loadTestsFromTestCase(mm1.MM1EventHandlerTests))
# 2. SimulatorEngine class
unittest.T... |
#!/usr/bin/env python
iwconf_file = open('iwcfg.txt', 'r+')
iwconf = iwconf_file.readlines()
iwconf_file.close()
link_quality = ""
signal = ""
for line in iwconf:
if line.find("Link Quality") > -1:
link_quality = line[23:25]
signal = line[43:46]
link_quality = str(float(link_quality)/70)
... |
'''
Backup Manager for ComicRack
bmUtils.py - utility classes for the Backup Manager
Copyright 2013 docdoom
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/lic... |
import tensorflow as tf
import numpy as np
import os
from tensorflow import keras
from tensorflow.keras import layers
from PIL import Image
from matplotlib import pyplot as plt
tf.random.set_seed(22)
np.random.seed(22)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def save_image(imgs, name):
new_im = Image.new('L', (... |
""" Contains upgrade tasks that are executed when the application is being
upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`.
"""
from onegov.core.orm.types import HSTORE
from onegov.core.orm.types import JSON
from onegov.core.orm.types import UTCDateTime
from onegov.core.upgrade import upgrade_tas... |
# Generated by Django 3.1.5 on 2021-03-26 13:19
from django.db import migrations, models
import django_mysql.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AudioBook',
fields=[
... |
tab_cat = "\tI'm tabbed."
pers_cat = "I'm split\non a line"
back_cat = "I'm \\ a \\ cat"
fat_cat = """
I'll do a list:
\t*food
\t* fish
\t* nip\n\t*Grass
"""
print(tab_cat)
print(pers_cat)
print(back_cat)
print(fat_cat)
print("Lyla is a beautiful coder.") |
# -*- coding: utf-8 -*-
# flake8: noqa
"""Automatic and manual clustering facilities."""
from .algorithms import cluster
from .session import Session
from .view_models import (BaseClusterViewModel,
HTMLClusterViewModel,
StatsViewModel,
)
|
import itertools
import os
import cv2
from video_util.frame_drawer import FrameDrawer
get_your_config_from_env_var = os.environ.get('CONFIG_NAME', 'default_value_if_not_set')
# comma separated strings
video_feed_names = os.environ.get('VIDEO_FEED_NAMES',
'FILE1,RTSP2')
streams = os.... |
from pypomvisualiser.pom.PomTreeNode import PomTreeNode
from pypomvisualiser.exceptions.PyPomExceptions import PomParseError
from enum import Enum
import logging
class NodeEnum(Enum):
EXTDEP = "#C0C0C0"
USERPOM = "#99CCFF"
ROOTPOM = "#0099FF"
class TreeCreation(object):
def __init__... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
#! /usr/bin/env python
"""
Analysis of revision data with more depth in the immune compartment.
"""
import sys
import datetime
from argparse import ArgumentParser, Namespace
import json
from dataclasses import dataclass
from tqdm import tqdm
from joblib import parallel_backend # type: ignore[import]
import numpy as... |
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = "C:\\Users\\danilo\\AppData\\Local\\Programs\\Python\\Python36-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Users\\danilo\\AppData\\Local\\Programs\\Python\\Python36-32\\tcl\\tk8.6"
include_files=["C:\\Users\\danilo\\AppData\\Local\\Pro... |
import sqlite3
class DeliveryServiceAPI:
def __init__(self):
self.APIDB = sqlite3.connect('delivery_service.db')
self.APIDB.execute('''create table if not exists courier_images (
bill_number unique not null,
courier_image not null,
pri... |
import os
class segmentation(object):
def __init__(self):
self.__report = None
@property
def report(self):
print('print out the report')
class lungSeg(segmentation):
def __init__(self):
super(lungSeg, self).__init__()
self.__show = None
@property
def show(self... |
#!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
n,m=map(int,input().split())
a=set([input() for i in range(n)])
b=set([input() for i in range(m)])
chk=a&b
a-=chk
b-=chk
print('YES' if (len(a)>len(b)-len(chk)%2) else 'NO')
|
"""
This example is based on Determined's MNIST PyTorch example.
This file is a how-to example for multiple learning rate schedulers
in Determined.
"""
from typing import Any, Dict, Sequence, Tuple, Union, cast
import torch
from torch import nn
from torch.optim.lr_scheduler import _LRScheduler
from layers import... |
# MTH 437 HW 1
# 0.0 X0
# Author: Paul Glenn
from math import cos
x = 2.0 #Initial guess
eps = 1.1*10**-16 #Just allows it to terminate with near-perfect agreement
g = open('HW1.txt','w+')
while abs(cos(x)-x)>eps:
x = cos(x)
g.write('guess = {:<20} | cos(x) = {:^10}'.format(repr(x),rep... |
import re
from symphony.bdk.core.activity.command import CommandContext
from symphony.bdk.core.service.datafeed.real_time_event_listener import RealTimeEventListener
from symphony.bdk.gen.agent_model.v4_initiator import V4Initiator
from symphony.bdk.gen.agent_model.v4_message_sent import V4MessageSent
from symphony.bd... |
import copy
import cPickle as pickle
from multiprocessing import Process
from rwlock import RWLock
import socket
import sys
from threading import Thread
import urllib2
import urlparse
"""Lightning-Fast Deep Learning on Spark
"""
class DeepDist:
def __init__(self, model, batch=None, master='127.0.0.1:5000'):
... |
import idc
import idaapi
import idautils
PRE_ADDR = None
def clear():
heads = idautils.Heads(idc.SegStart(idc.ScreenEA()), idc.SegEnd(idc.ScreenEA()))
for i in heads:
idc.SetColor(i, idc.CIC_ITEM, 0xFFFFFF)
def get_new_color(current_color):
colors = [0xffe699, 0xffcc33, 0xe6ac00, ... |
class Solution1:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
i = 0
max_dis = 0
while i < len(seats):
if seats[i] == 1:
i += 1
continue
left = i
while left >= ... |
from datetime import datetime
from dateutil import relativedelta
class AgeBarrier:
""" Holds various age barrier approaches available to the period. """
registry: dict[str, type['AgeBarrier']] = {}
def __init_subclass__(cls, name, **kwargs):
assert name not in cls.registry
cls.registry[... |
from ConfigParser import *
import os
import glob
import re
import sys
path = '/run/media/mzanotto/dataFast/renvision/experiments/P38_06_03_14_ret1/t0_modSmall_single_pca_cond_'
f1 = 'input_configuration'
f2 = 'confNumAndMI'
expParams = []
print 'BatchSize | k | Hidden | Delay | LearningRate | Delta | MI | R | MI/R'
... |
from ED6ScenarioHelper import *
def main():
# 古罗尼山道
CreateScenaFile(
FileName = 'C1500 ._SN',
MapName = 'Bose',
Location = 'C1500.x',
MapIndex = 61,
MapDefaultBGM = "ed60022",
Flags = 0,
... |
# -*- coding: utf-8 -*-
'''
This is a series of custom functions for the inferring of GRN from single cell RNA-seq data.
Codes were written by Kenji Kamimoto.
'''
###########################
### 0. Import libralies ###
###########################
# 0.1. libraries for fundamental data science and data processing
... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from django.db import models
# Create your models here.
class ServiceInfo(models.Model):
service=models.CharField(max_length=200,verbose_name="产品线")
cluster_name=models.CharField(max_length=200,verbose_name="集群名")
install_path=models.CharField(max_length=200,b... |
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class PrepaidGamer :
def __init__(self):
webOptions = webdriver.ChromeOptions()
webOptions.add_a... |
a = 'This is test naive.py file...'
print (a) |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'aplicativo.views.home', name='home'),
url(r'^mostrarTab/(?P<namespace>\S+)/$', 'aplicativo.views.... |
"""
Azure provides a set of services for Microsoft Azure provider.
"""
from diagrams import Node
class _Azure(Node):
_provider = "azure"
_icon_dir = "resources/azure"
fontcolor = "#ffffff"
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mptt.fields
from django.conf import settings
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
mi... |
#!/usr/bin/env python
# Author: Ben Langmead <ben.langmead@gmail.com>
# License: MIT
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
|
from flask import Flask, render_template
app=Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html',title='home')
@app.route('/jelly')
def jelly():
return render_template('jelly.html')
@app.route('/fish')
def fish():
return render_template('fish.html')
@app.... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
#!/usr/bin/python
# fussel.py is a stupid fuzzer. using pcap, scapy and radamsa
import scapy.all as scapy
from subprocess import Popen, PIPE
import ssl
import socket
import random
import time
import argparse
import sys
import os.path
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[9... |
from .models import UserAccount, EventPlace, EventPlaceSeatType, Contract, Ticket
from django.contrib.auth.models import Group
from django.contrib import admin
from django import forms
class EventPlaceAdmin(admin.ModelAdmin):
list_display = ('name', 'adress', 'open_air')
list_filter = ('name',)
class Contra... |
#_*_ coding:utf-8 _*_
#怎么执行程序 :scray crawl pursuit(这是自己指定的爬虫名)
#scrapy crawl pursuit -o pursuit_teacher.json -t json
import scrapy
from mySpider.items import PursuitItem
class PursuitSpider(scrapy.spiders.Spider):
#这些名称都是内置的
name = "pursuit"
allowd_damains = ["http://itcast.cn"]
start_urls = ["http://www.itca... |
from django.contrib.gis import admin
from world.models import WorldBorder
admin.site.register(WorldBorder, admin.OSMGeoAdmin)
# admin.site.register(WorldBorder, admin.GeoModelAdmin)
|
import cloudscraper
import time, os, sys, re, json, html
mangas = []
def remove_special_char(str):
return ''.join(e for e in str if e.isalnum())
def pad_filename(str):
digits = re.compile('(\\d+)')
pos = digits.search(str)
if pos:
return str[1:pos.start()] + pos.group(1).zfill(3) + ... |
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from .models import Subscriber
def subscriber_profile(sender, instance, created, **kwargs):
if created:
Subscriber.objects.create(
user=instance,
)
post_save.connect(subscriber_profile, ... |
import csv
import urllib.request
import json
import requests
from flask import redirect, render_template, request, session
from functools import wraps
from cs50 import SQL
from passlib.apps import custom_app_context as pwd_context
import smtplib
import random
db = SQL("sqlite:///games.db")
def login_required(f):
... |
from utils.api import fetch_from_api
from datetime import datetime
from utils.api.scoring import score_videos
from utils.mysql.get import get_videos
from utils.mysql.connect import get_mysql
def get_published_datetime(published):
return datetime.strptime(published, "%Y-%m-%dT%H:%M:%SZ")
def search(qu... |
from django.contrib import admin
from .models import Wishlist
# Register your models here.
# admin.site.register(Wishlist)
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Reto:
"""
Reto #7 “Edad futura y pasada”
Instrucciones: pide al usuario que indique su nombre y su edad.
Como mensaje de salida le indicarás que edad tuvo el año pasado y cuantos años tendrá el siguiente año.
Ejemplo: [nombre] el año pasado tenías X años y el próximo añ... |
import pprint
import eng_to_ipa as ipa
from time import sleep
class WordPronunciationPairs :
def __init__(self,word:str):
self.word = word;
self.pronunciation = ipa.convert(word)
def __repr__(self):
return self
def cleanbaby():
inpFile = open("./wordlist/babynames.txt",'r')
li... |
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import logging
from collections import OrderedDict
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
fr... |
#!/usr/bin/python
#\file kuka_joint_states.py
#\brief Convert /iiwa/state/JointPosition topic to /joint_states.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Jun.08, 2017
import roslib; roslib.load_manifest('iiwa_ros')
import rospy
import sensor_msgs.msg
import iiwa_msgs.msg
import copy
d... |
import copy
class Solution(object):
def stoneGame(self, piles):
"""
:type piles: List[int]
:rtype: bool
"""
#should use backtrack
alex_sum = 0
total_sum = sum(piles)
return self._helper(piles, alex_sum, total_sum)
def _helper(self, remain_piles, ... |
# -*- coding: utf-8 -*-
#############
#
# Copyright - Nirlendu Saha
#
# author - nirlendu@gmail.com
#
#############
from __future__ import unicode_literals
import uuid
from datetime import datetime
from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model as ModelCassandra
class Channe... |
# go to
# and reset API key
# then CTRL+C CTRL+V it below
import cassiopeia as cass
from os.path import dirname, abspath
riot_api_key = "RGAPI-77619554-7949-4393-be68-5e643092e8b4"
config = cass.get_default_config()
# stores data to disk
# doesn't work with match history :(
config["pipeline"]["SimpleKVDiskStor... |
import numpy as np
import math
# 想清楚之后就是找最大连续子列的问题
# 洪水无法侵蚀已经画过的墙,所以找到子列以后一定可以全部画满
# 时间复杂度O(N)
output = open("./B-large-practice.out", 'w+')
with open('./B-large-practice.in') as fp:
T = int(fp.readline())
cur_rd = 1
while cur_rd <= T:
key = 'Case #'+str(int(cur_rd))+': '
cur_rd += 1
... |
# Generated by Django 3.0.5 on 2020-04-21 06:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('learning_logs', '0006_auto_20200421_0643'),
]
operations = [
migrations.AlterField(
model_name=... |
# ! /usr/bin/env python
import requests
from bs4 import BeautifulSoup as BS
import time
def download(url):
# url = 'https://xs.sogou.com/chapter/14734139_481036348916/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/53... |
import sys
from lxml import html
import requests
import urlparse
import os
import argparse
import re
def process_links(links, formats=["jpg", "png", "gif", "svg", "jpeg"]):
x = []
for l in links:
# TODO regular expressions
if os.path.splitext(l)[1][1:].strip().lower() in formats:
... |
# Level 13
# http://www.pythonchallenge.com/pc/return/disproportional.html
# C:\Users\pablo>curl -u huge:file http://www.pythonchallenge.com/pc/return/evil4.jpg
# Bert is evil! go back!
# Python Console
"""phonebook = xmlrpc.client.ServerProxy('http://www.pythonchallenge.com/pc/phonebook.php')
phonebook
phon... |
from pwn import *
import sys
#import kmpwn
sys.path.append('/home/vagrant/kmpwn')
from kmpwn import *
#fsb(width, offset, data, padding, roop)
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./babyheap"
#"""
HOST = "35.186.153.116"
PORT = 7001
"""
HOST = "localhost"
PORT = 7777
"""
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import tinify
import os
import os.path
tinify.key = "234-zhwWJVU50Y7X8b3FYEFtx8xWzVQv"
fromFilePath = ""
print "压缩图片脚本开始"
print "_____________________________________________\n"
index = 1;
sumOldfileByte = 0
sumnewfileByte = 0
for root, dirs, files in os.walk(fromFilePat... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Domain(models.Model):
domain = models.CharField(_('domain'), max_length=128, unique=True)
description = models.CharField(_('description'), max_length=128, blank=True, null=True)
active = models.BooleanField(_('is act... |
from django.contrib import admin
from main.models import Product, Clothing, UserPicture, Review
# Register your models here.
admin.site.register(Product)
admin.site.register(Clothing)
admin.site.register(UserPicture)
admin.site.register(Review) |
#!/usr/bin/env python2.7
# encoding: utf-8
"""
sim1.py
Created by Jakub Konka on 2011-04-20.
Copyright (c) 2011 University of Strathclyde. All rights reserved.
"""
import sys
import os
import SimPy.SimulationTrace as sim
class Car(sim.Process):
def __init__(self, name, cc):
sim.Process.__init__(self, name=name)
... |
import numpy as np
import tensorflow as tf
import autokeras as ak
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 28, 28, 1).astype('float32') / 256.
x_test = x_test.reshape(10000, 28, 28, 1).astype('float32') / 256.
from tensorfl... |
#!/usr/bin/env python
import path_util # noqa: F401
import argparse
import asyncio
import logging
from typing import (
Coroutine,
List,
)
import os
import subprocess
from hummingbot import (
check_dev_mode,
init_logging,
)
from hummingbot.client.hummingbot_application import HummingbotApplicati... |
import pdb
x = [1,2,3]
y = 5
z = 6
a = y + z
print(a)
pdb.set_trace()
b = x + y # bug
print(b) |
"""PubMed Crawler of CSBC/PS-ON Publications.
author: nasim.sanati
author: milen.nikolov
author: verena.chung
"""
import os
import re
import argparse
import getpass
import ssl
from datetime import datetime
import requests
from Bio import Entrez
from bs4 import BeautifulSoup
import synapseclient
import pandas as pd
fr... |
from copy import deepcopy
from datetime import date, timedelta
from docx.document import Document
from docx.oxml import CT_P, CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
from onegov.translator_directory.collections.certificate import \
LanguageCertificateCollection
from on... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import librosa
import librosa.display
import warnings
warnings.filterwarnings('ignore')
''' FMA '''
# MFCC
for dir in os.scandir('../data/project_data/mini/fma'):
print(str(dir)[-5:-2])
files = []
labels = []
zcrs = []... |
import json
import asyncio
import traceback
from typing import Sequence
from datetime import datetime, timedelta
import aiosqlite
from discord.ext import commands
from potato_bot.bot import Bot
from potato_bot.cog import Cog
from potato_bot.types import Job, UserID
from potato_bot.utils import minutes_to_human_read... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 17:59:18 2020
@author: TakahiroKurokawa
"""
import sys
def py2_or_py3():
major=sys.version_info.major
if major==2:
return "Python2"
elif major==3:
return "Python3"
else:
return "Neither"
print(py2_or_py3... |
from urllib import parse
import urllib.request
url = 'http://172.16.1.188:8888/budget/pages/main'
wd = {'wd': '传智播客'}
pw = parse.urlencode(wd)
print(pw)
wd1 = {'wd1': '传'}
pw1 = parse.urlencode(wd1)
print(pw1)
wd2 = {'wd2': '智'}
pw2 = parse.urlencode(wd2)
print(pw2)
wd3 = {'wd3': '播'}
pw3 = parse.urlencode(wd3)
pr... |
#实验室考核第一题
n=input("请输入一个正整数")
n=int(n)
steps=[]
cnt=0
while n!=1:
if n%2==0:
cnt+=1
n/=2
steps.append('^')
elif n==3:
cnt+=1
n-=1
steps.append('-')
else:
if (n+1)%4==0:
cnt+=1
n+=1
steps.append('+')
else:
... |
# -*- coding: utf-8 -*-
import csv
import random
import logging
import requests
import numpy as np
from tqdm import tqdm
from typing import Text, Dict, Any, List
import re
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.forms import FormAction
from rasa_sdk.events ... |
from django.db import models
from . import models as base
from . import society
class VehicleBrand(base.BaseModel):
name = models.CharField(max_length=40, null=True, blank=False)
is_active = models.BooleanField(default=0, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
db_table = 've... |
#for loop
p = [1,2,3,4,5]
for x in p:
print(x)
q = ['apple','banana','pine apple','orange']
for m in q:
print(m)
k = ['mehedi','012458654','225413','kamrul','noyon','<->',"@"]
print(k[3])
|
from pynput.keyboard import Key, Listener
import logging
from pyautogui import typewrite, hotkey
log_dir = r"C:/users/Cameron/Desktop/1P03/LawtoCorrect/backend/"
logging.basicConfig(filename=(log_dir + "keyLog.txt"), level=logging.DEBUG, format='%(message)s')
keys = []
shifted = False
corrected
def in_alphabet(key... |
#__author: "Jing Xu"
#date: 2018/1/18
# -------------------------------------------------------------------------
# def f(n):
# return n*n*n
#
# a = [ x*2 for x in range(10) ]
#
# s = ( x*2 for x in range(10) ) #generator is an iterable
# print(s) #<generator object <genexpr> at 0x000001C20702C308>
# print(next(s))... |
input_file = 'Day 20\\Input.csv'
text_file = open(input_file)
lines = text_file.read().split('\n')
ips = []
for line in lines:
ip = []
lower = int(line.split('-')[0])
upper = int(line.split('-')[1])
ip.append(lower)
ip.append(upper)
ips.append(ip)
ip_list = sorted(ips)
def min_... |
from flask import Flask,request
import pandas as pd
import numpy as np
import pickle
from flasgger import Swagger
app=Flask(__name__)
Swagger(app)
pkl_imprt = open('bank_note_base.pkl','rb')
classifier = pickle.load(pkl_imprt)
@app.route('/')
def base():
return "Base path or welcome page"
@app.route('/authentic... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 21:42:46 2020
@author: enix3
"""
import torch
import torch.nn as nn
# For DIV2K
class MeanShift(nn.Conv2d):
def __init__(
self, rgb_range,
rgb_mean=(0.4488, 0.4371, 0.4040), rgb_std=(1.0, 1.0, 1.0), sign=-1):
super(MeanShift... |
import json
def getJsonFromFile(filename):
with open('data/{}'.format(filename), 'r') as jsonFile:
return json.load(jsonFile)
def getJsonObjectById(obj, id):
for dict in obj:
if dict['id'] == id:
return dict
|
# -*- coding: utf-8 -*-
"""
@author: Duy Anh Philippe Pham
@date: 26/07/21
@version: 1.00
@Recommandation: Python 3.7
@But : Study of density
"""
import numpy as np
import sys
sys.path.insert(1,'../../libs')
import matplotlib.pylab as plt
import tools, display, barycenter, process
def triangle_sup(mask,n):
# tri... |
N, W = map( int, input().split())
WV = [ list( map( int, input().split())) for _ in range(N)]
dp = [0]*(W+1)
for i in range(N):
w, v = WV[i]
for i in range(W,-1,-1):
if i >= w:
dp[i] = max( dp[i], dp[i-w]+v)
else:
break
print( dp[-1])
|
#Function to check if two strings are rotations of one another
def isRotation(string1, string2):
double = string1 + string1
return bool(double.find(string2) != -1)
print("terwa is rotation of water? ")
print(isRotation("water", "terwa"))
print("terwas is rotation of water? ")
print(isRotation("water", "terwas"))... |
from lib import Math
m = Math()
n1 = 2
n2 = 3
result = m.sumIntegers(n1,n2)
print ("The result of " + str(n1) + " + " + str(n2) + " is: " + str(result)) |
#NOTE: this is in Python 2, not Python 3
import csv
test_list1 = []
class HeartRate:
def __init__(self, filename='filename.csv'):
### Sean:
### csv.reader() is a better solution, but I'll do this quickly
### Feel free to fix / improve.
dataFromFile = open(filename).readlines()
dat... |
import sys
import os
import xlrd
numlines = int(sys.argv[1])
loc = ("datadictionary.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
for index in range(2, sheet.nrows):
row = sheet.row_values(index)
if row[0] != '':
os.system("generate.py "+row[0]+" "+str(numlines)+" scripts/"+row[0]... |
from django.conf import settings
from portia_api.jsonapi import JSONResponse
def capabilities(request):
capabilities = {
'custom': settings.CUSTOM,
'username': request.user.username,
'capabilities': settings.CAPABILITIES,
}
return JSONResponse(capabilities)
|
class Solution:
def fourSum(self, nums, target):
resList = []
if len(nums)<4:
return resList
nums.sort()
length = len(nums)
# i j k h
for i in range(length-3):
if i>0 and nums[i]==nums[i-1]:
continue
# 找出最大最小值,若不可能满足... |
from scrapy.item import Item, Field
import scrapy
class Blog(Item):
text = Field()
time = Field()
image_urls = scrapy.Field()
images = scrapy.Field()
image_paths=Field()
|
#!/usr/bin/python
from flask import Flask
from flask_restplus import Api, Resource, reqparse
from werkzeug.datastructures import FileStorage
from cStringIO import StringIO
from utils.linda import *
from manager.upload import library, model
from manager.run import prepare_instance, execute_workflow
from manager.csar ... |
import numpy as np
def parse_file(filename):
""" Parse files structured in the same way as demos are """
with open(filename) as f:
points = []
for line in f.readlines():
points += [[int(_) for _ in point.strip('()').split(',')] for point in line.split()]
return np.array(points)
def rescale_ol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.