text stringlengths 8 6.05M |
|---|
'''
Created on Jan 24, 2016
@author: Andrei Padnevici
@note: This is an exercise: 11.1
'''
import re
try:
fName = input("Enter file name: ")
if fName == "": fName = "mbox-short.txt"
file = open(fName)
except:
print("Invalid file")
exit()
txt = file.read()
revisons = re.findall("New Revision: ([\d... |
#! /usr/bin/python
import sys
import time
def test01 ():
k = 0
try:
buff = ''
while True:
buff += sys.stdin.read(1)
if buff.endswith('\n'):
print "XXXX: " + buff[:-1]
buff = ''
k = k + 1
except KeyboardInterrupt:
... |
# 文件复制
'''with open('test.txt','r') as read_f,open('test1.txt','w+') as write_f:
data=read_f.read()
data=write_f.write(data)'''
# 图片复制
with open('176817195_49.jpg','rb') as img_f,open('123.jpg','wb') as write_img:
data=img_f.read()
data=write_img.write(data)
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
url(r'^messages/', include('privatemessages.urls')),
url(r'^admin/', include(admin.sit... |
#! python3
import pymysql
import csv
db = pymysql.connect(host='localhost', user='mat', password='1980mk**', port=3306, db='spiders')
db.set_charset('utf8mb4')
cursor = db.cursor()
#sql = 'CREATE TABLE IF NOT EXISTS
# maoyan (排名 INT(4), 片名 VARCHAR(100), 演员 VARCHAR(255), 上映时间 VARCHAR(100), 评分 FLOAT(1,1))'
#cursor.exe... |
from flask import Flask
from flask.ext.babel import Babel, get_translations
from flask.ext.openid import OpenID
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.redis import Redis
from flask.ext.compass import Compass
from . import filters, context_processors, utils, ext
import __builtin__
import pytz
import ... |
import numpy as np
import pandas as pd
from math import exp
import copy
from sklearn import preprocessing
# Feed Forward helper methods
def sigmoid(value):
if value < 0:
return 1 - 1 / (1 + exp(value))
else:
return 1.0/(1+exp(value * (-1)))
def sigma(matrix_weight, matrix_input, bias=0):
#... |
#!/usr/bin/python
# dedup.py - Sat, 23 Apr 2011 00:03:30 -0400
# As command line arguments are files of md5sum's. The md5sums are read one
# by one in their order and all duplicated files are removed, only the
# files of their first appearance are kept in their old path.
import sys;
import os.path;
f = {} # File hash... |
import sys
import os
project = u'Ceph'
copyright = u'2018, SUSE, and contributors. Licensed under Creative Commons BY-SA'
version = 'dev'
release = 'dev'
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
exclude_patterns = ['**/.#*', '**/*~', 'start/quick-common.rst']
if tags.has('man'):
... |
import sqlite3
conn = sqlite3.connect("factbook.db")
query = "SELECT * FROM facts;"
facts = read_sql_ |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
from django.urls import reverse, reverse_... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import Any
from pants.bsp.spec.base import BSPData, BuildTarget, BuildTargetIdent... |
import unittest
from katas.beta.print_that_calendar import show_calendar
class ShowCalendarTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(
show_calendar(2001, 10),
' October 2001\n'
'Mo Tu We Th Fr Sa Su\n'
' 1 2 3 4 5 6 7\n'... |
# Generated by Django 1.10.7 on 2017-11-23 15:53
from django.db import migrations
def move_relaydomain_to_transport(apps, schema_editor):
"""Transform relaydomains to transports."""
RelayDomain = apps.get_model("relaydomains", "RelayDomain")
RecipientAccess = apps.get_model("relaydomains", "RecipientAcces... |
import tkinter as tk
from tkinter import messagebox
from tkinter.constants import LEFT
import tkinter.font as tkFont
import GetImage as GM
from tkinter.messagebox import askokcancel, showinfo, WARNING
def main(root,user,token,id,Room_ID):
root.title("Room Preview")
width=750
height=600
screenwidth... |
"""index file manager."""
import hashlib
import os
import json
from cryptarchive import constants
from cryptarchive.errors import FileNotFound
# ============ INDEX FORMAT =================
# as json:
# {
# "dirs": {
# name: {
# name: {
# "name": childname,
# ... |
"""
Placeholder plugin to test the plugin system.
"""
__help__ = 'Hello world. A throwaway module.'
def seed_parser(parser):
"""
Seed the parser.
"""
parser.add_argument('--awesome',dest='awesome',default='completely')
def seed_commands(commands):
"""
Seeds the commands.
"""
def aw... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
# CSS/Tag
html = urlopen("https://morvanzhou.github.io/static/scraping/list.html").read().decode("UTF-8")
print('here is the html structure: \n')
print(html)
soup = BeautifulSoup(html, features='lxml')
#month = soup.find_all('li', {'class': 'month'})
... |
import functools
import numpy as np
import pandas as pd
def handle_na(func):
"""Decorator for scalar function so it returns nan when nan is input"""
@functools.wraps(func)
def func_wrapper(arg, *args, **kwargs):
if pd.isna(arg):
return arg
return func(arg, *args, **kwargs)
... |
import logging
import networkx as nx
import os
import time
class mp_network:
id = None
logger = None
cfg = {}
node_types = []
edge_types = []
graph = None
def __init__(self, config = None):
# initialize id
self.id = int(time.time() * 10... |
# works in Python 2 & 3
class _Singleton(type):
_instances = {}
def __call__(self, *args, **kwargs):
if self not in self._instances:
self._instances[self] = \
super(_Singleton, self).__call__(*args, **kwargs)
return self._instances[self]
class Singleton(_Singleton(... |
def testit(s):
return ' '.join(a.lower()[:-1] + a[-1].upper() for a in s.split())
|
class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
if len(digits) == 0:
return [1]
digits[len(digits)-1] += 1
carry = 0
for x in xrange(len(digits)-1,-1,-1):
if digits[x] == 10:
digits[x] = 0
... |
import os
import platform
if platform.system() == 'Windows':
texconv_path = f'{os.path.dirname(__file__)}/../resources/texconv.exe'
else:
raise Exception('Unknown Architecture')
def convert_texture(arg: str):
os.system(f'{texconv_path} {arg}')
|
import csv
import re
import sys
import pandas as pd
import numpy as np
import collections
"""
family id
"""
if __name__ == '__main__':
data = pd.read_csv('data/all_data_1.csv')
data['Family'] = pd.Series(str(np.nan), index=data.index)
for index,row in data.iterrows():
sirname = row['Name'].split(",")
fam... |
"""
2021年5月24日
矫正踢腿磁铁设计
现在的情况是这样的:
前偏转段优化后,不同动量分散下的相椭圆形状、Δx、Δy、Δxp都可以,唯独 Δxp 会变动,大约是 4mr/%
现在打算加入矫正踢腿磁铁
先看看没有动量分散下,全段情况
"""
# 因为要使用父目录的 cctpy 所以加入
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
from work.A01run import *
from cctpy import *
def beamline_ph... |
from common.run_method import RunMethod
import allure
@allure.step("极运营/前台业务/批量转班/查询转班学生")
def classChange_student_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认json格... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 13:24:09 2018
@author: Markus Meister
@instute: University Oldenburg (Olb)
@devision: Machine Learning
@faculty:FVI Math.&Nat.Sci.
"""
#%% imports
import torch
from torch.autograd import Variable
import torch.nn as nn
import tor... |
def binarySearch(arr, l, r, x):
#base case
if r >= l:
mid = int(l + (r-l)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
'''
if element is smaller than element at mid
it can only be present in the left subarray
'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from main_widget import *
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
# self.form_widget = FormWidget(self)
# self.setCentralWi... |
def read_access_point(interface):
'''Read the MAC address of the access point associated
with the network that @interface is on.
ARGS:
@interface -- The interface inquired about.
RETURNS:
@ap -- The MAC address of the interface's
network access point.
'''
from parse_iwconfig import parse_iwconfig... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ed Mountjoy
#
import sys
import os
import argparse
import pandas as pd
from pprint import pprint
from collections import OrderedDict
from parquet_writer import write_parquet
def main():
# Parse args
args = parse_args()
# Load
df = pd.read_csv(args.in... |
import os
from flask import (Flask, flash, render_template, redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
if os.path.exists("env.py"):
import env
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] =... |
from typing import Optional, Sequence
from waitlist.storage.database import Waitlist, Character, Shipfit, WaitlistGroup, SolarSystem, Constellation, Station,\
Account
Optionalcharids = Optional[Sequence[int]]
def make_json_wl_entry(entry, exclude_fits: bool = False, include_fits_from: Optionalcharids = None,
... |
import pyaudio
import threading
import wave
from interface.lights import Lights
Thread = threading.Thread
FORMAT = pyaudio.paInt16
# CHANNELS = 2
CHANNELS = 1
# RATE = 44100
RATE = 16000
CHUNK = 1024
class Record(Thread):
def __init__(self, audio_interface):
Thread.__init__(self)
... |
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foodev'.upper(), 'FOODEV') |
# -*- coding: utf-8 -*-
from collections import defaultdict
from typing import List
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
occurrences, result = defaultdict(list), 0
for i, num in enumerate(nums):
if num in occurrences:
result += sum(i * ... |
'''
41. First Missing Positive
Given an unsorted integer array nums, find the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Example 3:
Input: nums = ... |
import os
file_path = os.path.dirname(__file__)
# model_dir = os.path.join(file_path, 'chinese_L-12_H-768_A-12/')
model_dir = os.path.join('../chinese_L-12_H-768_A-12/')
config_name = os.path.join(model_dir, 'bert_config.json')
ckpt_name = os.path.join(model_dir, 'bert_model.ckpt')
output_dir = os.path.join(file_path... |
import z
import datetime
import collections
tmonth = datetime.date.today().month
tday = datetime.date.today().day
dates = z.getp("dates")
spy = z.getCsv("SPY")
dlist = (spy["Date"].tolist())
avgdict = collections.defaultdict(list)
for ayear in range(2, 18):
year = "200{}".format(ayear)
if ayear >= 10:
... |
# Generated by Django 3.0.8 on 2020-08-03 11:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prezola', '0006_orderlineitem_status'),
]
operations = [
migrations.AddField(
model_name='orderlineitem',
name='quan... |
# functions which simplify the choosing of stimulation frequencies
# this is based on an a set of valid frequencies determined externally to this
# code and is based on the experimental data
# format [[UpTime, DownTime, SendFreq, closet = 128, closest = 256, closest = 384, closest = 512, closest =640, closest = 768... |
import mysql.connector
import random
import datetime
from flask import Flask, render_template, request, flash, redirect, url_for, make_response
def ValidateNewUserLogIn(PossibleUser,PasswordProvided):
if PossibleUser == "admin" and PasswordProvided == "password":
return PossibleUser
Results ... |
dict1= {
"<action>":[],
"<attr_name>":[],
"<table_name>":[],
"<condition_name>":[],
"<condition>":[],
"<value>":[],
"<logic>":[]
}
dictionary11= {
"ssc": ["10th"],
"hsc": ["12th"],
"OR": ["or","OR"],
"DESC": ["descending","decreasing"],
"ASC": ["ascen... |
# 导入sqlite驱动
import sqlite3
def createConn(dbName):
# 连接到sqlite数据库
# 数据库文件是test.db
# 如果文件不存在, 会自动在当前目录创建
conn = sqlite3.connect(dbName)
return conn
def createCursor(conn):
# 创建一个Cursor
cursor = conn.cursor()
return cursor
def close(cursor, conn):
# 关闭cursor
cursor.close()
... |
--- setup.py.orig 2021-01-14 10:34:05 UTC
+++ setup.py
@@ -39,7 +39,7 @@ setup(
'isodate>=0.5.0',
'lxml>=3.3.5',
'xmlsec>=1.0.5',
- 'defusedxml==0.6.0'
+ 'defusedxml>=0.6.0'
],
dependency_links=['http://github.com/mehcode/python-xmlsec/tarball/master'],
extras_req... |
#!/usr/bin/env python
"""Load COMTRADE data, aggregate and calculate steel contents.
Usage:
aggregate_trade_flows.py --allocation ALLOCATION-FILE --steel-contents CONTENTS-FILE COMTRADE-FILE...
Options:
--allocation ALLOCATION-FILE CSV file with mappings from SITC v2 codes to product categories
--steel-co... |
import click
import random
def beta_convert(b, n):
"""Returns given n in b number system"""
if b is 2:
return bin(n)
elif b is 8:
return oct(n)
elif b is 16:
return hex(n)
return n
@click.command()
def from_to():
"""Generates a random number in two different
number... |
import maya.cmds as cmds
import os
calabash_menu = None
def calabash_menu():
global calabash_menu
if cmds.menu('calabash_m', exists=True):
cmds.deleteUI('calabash_m')
###############################################################################
calabash_menu = cmds.menu('calabash_m', p=... |
# list 模拟栈
class Solution:
def maxDepth(self, s: str) -> int:
maxn = 0
l = []
for t in s:
if t == '(':
l.append(1)
maxn = max(maxn, len(l))
elif t == ')':
l.pop()
return maxn |
import tensorflow as tf
import numpy as np
from dps.register import RegisterBank
from dps.env import TensorFlowEnv
from dps.utils import Param, Config
def build_env():
return GridBandit()
config = Config(
build_env=build_env,
curriculum=[dict()],
env_name='grid_bandit',
threshold=-5,
T=5,
... |
import pandas as pd # 导入pandas库
data = pd.read_csv("F:\\数据采集\\数据采集课设\\淘宝空调数据.csv",encoding='utf-8-sig')
print(data.describe())
# 将工资低于1000或者高于10万的异常值清空
data[u'views_price'][(data[u'views_price'] < 900) | (data[u'views_price']> 30000)] = None
data.dropna()#删除空缺值
print(data.describe())
print(data.shape)
data.to_... |
import time
import threading
inicio = time.perf_counter()
def aDormir():
print("Iniciando función, voy a dormir 1 s")
time.sleep(1)
print("Paso un segundo, he despertado")
#Vamos a comparar ahora creando dos hilos
#Para luego poder iterar sobre todos los hilos crearemos una lista vacia llamada hilos
hilos=[]
#En ... |
import numpy as np
import os, sys
import argparse
import csv
parser = argparse.ArgumentParser('Character-based Model for LAS')
parser.add_argument('--data-path', default='all', type=str, help='Path to data')
parser.add_argument('--write-file', default='', type=str, help='csv file to write vocabulary')
parser.add_argum... |
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
temp = [0]*20001
for num in nums:
temp[num+10000] += 1
for i in range(len(temp)-1, 0, -1):
k -= temp[i]
if k <= 0:
return i-10000
return 0 |
import json
data = {'a': 'A', 'c': 3.0, 'b': (2, 4), 'd': [1, 2.0, "3", True]}
with open("data.json", mode="w") as f:
json.dump(data, f)
with open("data.json") as f:
data = json.load(f)
print data['b']
print data['d']
"""
[2, 4]
[1, 2.0, u'3', True]
"""
|
from nab import config
from nab import register
from nab import log
_log = log.log.getChild("database")
class Database(register.Entry):
_register = register.Register()
_type = "database"
def get_show_titles(self, show):
return []
def get_show_absolute_numbering(self, show):
return F... |
str1='Hello'
str2='there'
bob=str1+str2
print(bob)
str3='123'
x=int(str3)+1 # convert into integer number
print(x)
|
from __future__ import division
import argparse
import torch
import os
import cv2
import numpy as np
from models import *
parser = argparse.ArgumentParser(description='PyTorch face landmark')
# Datasets
parser.add_argument('-img', '--image', default='spine', type=str)
parser.add_argument('-j', '--workers', default=4, ... |
import sys
import os
import xml.dom.ext
from xml.dom import XML_NAMESPACE, XMLNS_NAMESPACE, DOMException
from xml.dom.ext import Printer
from xml.dom.minidom import parseString, parse, Node
uiSetStub="""
<set
description='Automaticaly generated structure. Please do not change it !! All changes will be overwritt... |
from itertools import izip_longest
class Vector(object):
def __init__(self, nums):
self.nums = nums
def __str__(self):
return '({})'.format(','.join(str(a) for a in self.nums))
def add(self, v2):
return Vector([b + c for b, c in izip_longest(self.nums, v2.nums)])
def dot(sel... |
Nentr = int(input())
for i in range(0, Nentr):
N = int(input())
if 2015 - N < 0:
print('%d A.C.'%(N-2014))
elif 2015 - N == 0:
print('1 A.C.')
else:
print('%d D.C.'%(2015-N))
|
import hashlib
from urllib.parse import urlencode
from django import template
from django.conf import settings
register = template.Library()
@register.filter
def gravatar(user):
email = user.email.lower().encode('utf-8')
default = 'mm'
size = 256
url = 'https://lh3.googleusercontent.co... |
from typing import List
from Position import Position
def read_city_positions(file_path: str, skip_lines: int) -> List[Position]:
city_positions: List[Position] = []
with open(file_path, 'r') as reader:
lines_list: List[str] = reader.readlines()
for idx in range(skip_lines, len(lines_list)):
coords: List[st... |
from leetcode import test, TreeNode, new_tree
def rob(root: TreeNode) -> int:
def helper(node: TreeNode) -> (int, int):
if not node:
return 0, 0
left_max, left_no_rob = helper(node.left)
right_max, right_no_rob = helper(node.right)
return (
max(left_no_rob +... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 16:19:14 2020
@author: Anuj
"""
# making the imports
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input,Conv2D,MaxPooling2D,Dropout,Flatten,Dense,Activation,BatchNormalization,add
from tensorflow.keras.models import Model,Sequ... |
from flask import Blueprint
from flask import jsonify
from shutil import copyfile, move
from google.cloud import storage
from google.cloud import bigquery
import pandas as pd
from pandas import DataFrame
import dataflow_pipeline.sensus.sensus_seguimiento_beam as sensus_seguimiento_beam
import dataflow_pipeline.sensus.s... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" KafkaKeySerializer
Serialize string key to bytes & deserialize key in string
"""
from tonga.services.serializer.base import BaseSerializer
from tonga.services.serializer.errors import KeySerializerDecodeError, KeySerializerEncodeError
class Kafk... |
from leetcode.tree import printtree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Queue(object):
def __init__(self):
self.stacka = []
self.stackb = []
self.queue = []
def inqueue(self, node):
... |
from django.test import TestCase
from portfolio.models import Project
class ProjectModelTest(TestCase):
def test_creating_and_retrieving_projects(self):
first_project = Project()
first_project.title = '1st project'
first_project.description = '1st desc'
first_project.save()
... |
from logging import info, warning
from api import gitlab
from utilities import validate, types
gitlab = gitlab.GitLab(types.Arguments().url)
def get_all_project_members(project):
members = {}
info("[*] Fetching all members for project %s", project)
details = gitlab.get_project_members(project)
if va... |
import re
email_file = "C:\\Users\\gk\\Documents\\myPython\\Day4\\contacts_regex.txt"
pattern = re.compile(r'@\w[\w\.\-]+\w')
with open(email_file,"r",encoding='utf8') as file :
dict_domain = dict()
for line in file.readlines() :
for domain in re.findall(pattern,line) :
if domain in dict_... |
from random import randint
from card import Card
from deck import Deck
from noble import Noble
from token import Token
from player import Player
from prettytable import PrettyTable
class Environment:
def __init__(self, playerCount):
self.__players = Player.initialize(playerCount)
self.__nobles = ... |
#! /usr/bin/env python
import sys
import os
from numpy import *
from scipy import *
import scikits.audiolab as audiolab
import matplotlib.pylab as plt
project_path = sys.argv[1] # where the audio files are
recording_number = int(sys.argv[2]) # e.g. 9, for #09
pixclock_prefix = "PixClock "
velocity_threshold = 0.025... |
def calcWei(Ns,Nf,Dur):
# calculate the weight matrix of the nodes in the directed graph using the
# information extracted from the file
n = 28
# define the number of nodes in the graph
wei = np.zeros((n,n),dtype=float)
# initialise the weight matrix
for i in range(len(Dur... |
import torch
import csv
from Data_Loader import *
from model import ModelManager
if __name__ == '__main__':
model = ModelManager()
model.load_state_dict(torch.load("model_param/parameter_1.pkl",map_location='cpu'))
test_loader = DataProcess()
model.eval()
f = open('predict_1.csv', 'w', encoding=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
STEL Sistemas de Telecomunicações 2016/17 2S
Simulation of a Poisson call arrival process
Grupo:
'''
import csv
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import itertools
# Data
time_scale = []
value = []
poissonX = []
poiss... |
import datetime
from region import Region
from track import Track
from log import log
class ObjectTracker:
ttl = datetime.timedelta(seconds=2)
def __init__(self):
self.tracks = []
def process(self, region_proposals):
birthed, promoted, reaped = [], [], []
region_proposals = Reg... |
from flask import request
from flask_restplus import Namespace, Resource, fields
api_operator = Namespace('operator', description='Requests to operator model.')
operator_fields = api_operator.model('CReate operator payload.', {
"username": fields.String,
"email": fields.String,
"password": fields.String,... |
import glob
sensor_list = []
excluded_files = [
"__init__",
"example",
"cansat_sensor"
]
# Get all sensors in the Sensors directory and import them
for sensorFile in glob.glob("*.py"):
# Remove the .py from the sensorFile
sensorFile = sensorFile[:sensorFile.find(".py")]
# Check if it is in the list of excluded... |
import chainer
import onnx
import pytest
import onnx_chainer
def pytest_addoption(parser):
parser.addoption(
'--value-check-runtime',
dest='value-check-runtime', default='onnxruntime',
choices=['skip', 'onnxruntime', 'mxnet'], help='select test runtime')
parser.addoption(
'--o... |
month = int(input())
if month == 12 or month < 3:
print('winter')
elif month < 6:
print('spring')
elif month < 9:
print('summer')
else:
print('fall') |
import torch
import os
import json
import random
import numpy as np
import argparse
from datetime import datetime
from tqdm import tqdm
from torch.nn import DataParallel
from itertools import islice, takewhile, repeat
from transformers import EncoderDecoderModel, BertTokenizerFast, BertModel
from dataset import TextD... |
# -*- coding: utf-8 -*-
'''
Obtener justificaciones de un usuario
@author Ivan
@example python3 getJustificationsStockByUser.py userId justificationId date
@example python3 getJustificationsStockByUser.py e43e5ded-e271-4422-8e85-9f1bc0a61235 fa64fdbd-31b0-42ab-af83-818b3cbecf46 01/05/2015
'''
import sys
sys.path.inser... |
# Author: ambiguoustexture
# Date: 2020-03-11
import pickle
import numpy as np
from scipy import io
from similarity_cosine import sim_cos
file_context_matrix_X_PC = './context_matrix_X_PC'
file_t_index_dict = './t_index_dict'
with open(file_t_index_dict, 'rb') as t_index_dict:
t_index_dict = pickle.load... |
import requests
import logging
import binascii
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36',
}
def download(url, binary=False):
logging.debug('download: %s', url)
response = requests.get(url, headers=h... |
num_of_list = int(input("Enter the length of list-:"))
number_perm = []
for num in range(num_of_list):
list_num = int(input("Enter the number in the list-:"))
number_perm.append(list_num)
def permutation(number_perm):
if len(number_perm) == 0:
return []
if len(number_perm) == 1:
return ... |
import os
import sys
import zipfile
def unzip(filename: str):
try:
file = zipfile.ZipFile(filename)
dirname = filename.replace('.zip', '')
# 如果存在与压缩包同名文件夹 提示信息并跳过
if os.path.exists(dirname):
print(f'{filename} dir has already existed')
return
else:
... |
# coding:utf-8
# From 180103
# add function check_lighten()
import sys
from datetime import datetime
import socket
import json
sys.path.append('Users/better/PycharmProjects/GUI_Qt5/Intersection_Ex_2')
import rec_funcs
import copy
import new_Rect
class IM():
def __init__(self):
# preparation as a server
... |
from collections import OrderedDict
from network.rnn_5 import CLSTM_cell
# build model
# in_channels=v[0], out_channels=v[1], kernel_size=v[2], stride=v[3], padding=v[4]
convlstm_encoder_params = [
[
OrderedDict({'conv1_leaky_1': [2, 16, 3, 1, 1]}),
OrderedDict({'conv2_leaky_1': [32, 32, 3, 2, 1]}... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import json
app = dash.Dash()
with open("contrCode.json") as f:
country_codes = json.load(f)
with open("dataToUse.json") as f:
data = json.load(f)
app.layout = html.Div([
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do
# Write by Eneldo Serrata (eneldo@marcos.do)
#
# This program is free software: you can redistribute it and/or modify
# it under... |
# Date: 10/09/2020
# Author: rohith mulumudy
# Description: contains configuration data.
# Check the keys which are tagged "Important" before execution. #Important
## Certificate Fetching Constants
### Contains domains list
cert_in_file = "sample.txt" #important
### File that stores domains which threw error whi... |
# Generated by Django 3.2.8 on 2021-10-28 21:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chatbot', '0006_auto_20211028_1611'),
]
operations = [
migrations.AddField(
model_name='trainingmodels',
name='acc_t... |
import numpy as np
from permaviss.gauss_mod_p.gauss_mod_p import gauss_col
def test_gauss_col():
A1 = np.array([[0, 1, 1], [1, 1, 0], [1, 1, 0]])
R1 = np.array([[0, 1, 0], [1, 0, 0], [1, 0, 0]])
T1 = np.array([[1, 1, 1], [0, 1, 1], [0, 0, 1]])
eq1 = np.array([R1, T1])
eq2 = np.array(gauss_col(A1... |
#!/usr/bin/env python
'''Helping functions'''
__author__ = 'Denys Tarnavskyi'
__copyright__ = 'Copyright 2018, RPD site project'
__license__ = 'MIT'
__version__ = '1.0'
__email__ = 'marzique@gmail.com'
__status__ = 'Development'
import re
import os
import secrets
from PIL import Image
from itsdangerous import URLSafeT... |
def es5(sequenza):
n = len(sequenza)
T = [0 for _ in range(n)]
T[0] = 1
max_index = 0
for i in range(1, n):
T[i] = max([T[j] for j in range(0, i) if sequenza[j] < sequenza[i]],
default = 0) + 1
max_index = max_index if T[max_index] >= T[i] else i
# Ricostruis... |
import random
import adecide
from adecide import adecide
class attack:
def start(self,na,nd):
self.x=0
self.l=adecide()
self.m=attack()
if adecide.decide(self.l,na,nd)==1:
self.x=adecide.war(self.m,na,nd)
else:
pass
return self.x
def war(self,na,nd):
self.a=0
self.m=0
while ((self.a==0)):
... |
from django.contrib import admin
from . models import joinus, researchpaper, alumini
# Register your models here.
admin.site.register(researchpaper)
admin.site.register(joinus)
admin.site.register(alumini) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.