text stringlengths 38 1.54M |
|---|
import io
import pycurl
import stem.process
from stem.util import term
TOR_SOCKS_PORT = 9150
# Uses pycurl to fetch a site using the proxy on the SOCKS_PORT
def query(url):
output = io.BytesIO()
query = pycurl.Curl()
query.setopt(pycurl.URL, url)
query.setopt(pycurl.PROXY, 'localhost')
query.setopt(pycurl.PROXY... |
from pm25_beijing.items import Pm25BeijingItem
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from datetime import datetime
from os import path as p
from os import mkdir
class Pm25Spider(BaseSpider):
name = "pm25_beijing"
allowed_domains = ["zx.bjmemc.com.cn"]
start_urls... |
from abc import ABC, abstractmethod
import torch
from torch import nn, Tensor
from typing import Generic, Iterable, Optional, Sequence, Tuple, Union, TypeVar
from .init import lstm_bias, Initializer
from ..prelude import Self
from ..utils import Device
from block_wrapper import BlockWrapper
class RnnState(ABC):
@... |
import numpy as np
import pandas as pd
import random
from collections import deque
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import Earl... |
import traceback
from fbchat import models
from contextlib import redirect_stdout
import importlib
from io import StringIO
import textwrap
#==================================================================================================================================================
class Admin:
def __init__(s... |
from enum import Enum,auto
import math
class Quantity(Enum):
FEETTOINCH=12
INCHTOFEET=0.084
FEETTOYARD=0.334
YARDTOFEET=3
INCHTOYARD=0.028
YARDTOINCH=36
CENTIMETERTOINCH=0.40
INCHTOCENTIMETER=2.54
LITERTOMILILITER=1000
MILILITERTOLITER=0.001
GALLONTOLITER=3.78
LITERTOGAL... |
import pandas
import os
import os.path
import numpy as np
import pyreadstat
file = os.path.dirname(os.path.realpath(__file__)) + '/SPAQ.sav'
data = pandas.read_spss(file)
genes1way = ['PER2', 'PER3A', 'PER3B', 'PER3C', 'CLOCK', 'CRY1', 'CRY2', 'VNTR']
allGenes = ['PER2AA', 'PER2GG', 'PER2AG', 'PER3ACC', 'PER3AGG', ... |
import requests
import re
from bs4 import BeautifulSoup
import json
import time
suffix_dict = {}
with open("phone-url-list.txt", "r") as input_file:
brand = ""
for line in input_file:
if line[0] == ">":
brand = line[1:].strip()
suffix_dict[brand] = []
else:
... |
# Copyright (c) 2016, Intel Corporation.
# 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-2.0
#
# Unless r... |
from github import Github
import datetime
# todays_date = str(datetime.date.today())
# current_time = datetime.datetime.now().strftime('%Hh%Mm')
# time_with_date = current_time.strftime("%d%B_%Hh%Mm")
# access_token = "qfqegbwdsfvd"
# g = Github("access_token")
g = Github("<userName>", "<Password>")
repo = g.get_... |
import pandas as pd
import re
import csv
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('train.csv', nrows=10000)
colnames = ['sentiment', 'text', 'actual_sentiment']
testData = pd.read_csv('test.csv', names=colnames)
# trainData.sample(frac=1).head(5)
testData_list = testData.text.tolist()
actual... |
from __future__ import print_function
import torch
import numpy as np
import colorsys
from PIL import Image
import os
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def fruxel2im(image_tensor, imtype=np.uint8):
image_numpy = image_tensor.cpu().float().numpy()
... |
import unittest
import numpy as np
from numpy.testing import assert_array_equal
# 単位行列
class TestArrayEye(unittest.TestCase):
def test_eye_NxN(self):
metrix = np.eye(3)
assert_array_equal(metrix, np.array([[x, x, x],
[x, x, x],
... |
class BinaryTree:
class Position:
def __init__(self, container, node):
self._container = container
self._node = node
def data(self):
return self._node.data
def __eq__(self, other):
return type(other) is type(self) and other._node is self._n... |
import urllib
import requests
from bs4 import BeautifulSoup
import pandas as pd
import os
def find_jobs_from(website, job_title, location, specific_characs, filename="big_dataengineer_result.xlsx"):
"""
This function extracts all the specific characteristics of all new job postings
of the title ... |
"""
SQLAlchemy attribute annotations
--------------------------------
Annotations are strings attached to attributes that serve as a programmer
reference on how those attributes are meant to be used. They can be used to
indicate that a column's value should be :attr:`immutable` and should never
change, or that it's a ... |
from rest_framework import serializers
from .models import ModelTasks
class TasksSerializer(serializers.ModelSerializer):
class Meta:
model = ModelTasks
fields = ['id', 'label', 'completed'] |
from Geo.DBhelper import Helper
from Common.util import *
from Common.enum import *
from Geo import DBhelper as DBhelper
from Filter import controller as filter
from Redis import controller as redis
def get_search_zones(long,lati,distance,origin_zone):
'''
judge whether needs to search the drivers in the neig... |
import v4l2ForPython3 as v4l2
import fcntl
import numpy as np
import os
class V4L2Write:
def __init__(self, fileName, width, height, pixelFormat):
#print("width : " + str(width))
#print("height : " + str(height))
self.fileName = fileName
self.format = v4l2.v4l2_format()
self.format.type = v4l2.V4L2_BUF_... |
# -*- coding: latin-1 -*-
import random
from Player import *
from Constants import *
from AIPlayerUtils import *
from Construction import CONSTR_STATS
from Ant import UNIT_STATS
from Move import Move
from GameState import addCoords
#Constants used for the findTile helper method
LOOKING_FOR_CONSTR = 0
LOOKING_FOR_ANT =... |
peso = float(input('informe o peso da pessoa: '))
altura = float(input('informe a altura da pessoa: '))
imc = peso / (altura*altura)
if imc < 18.50:
print('{:.2f} IMC, Abaixo do peso.'.format(imc))
elif imc <= 25:
print('{:.2f} IMC, Peso ideal.'.format(imc))
elif imc < 30:
print('{:.2f} IMC, Sobre... |
import operator
def hamming_distance(p, q):
mismatches = 0
for i in range(len(p)):
if p[i] != q[i]:
mismatches += 1
return mismatches
def Neighbors(Pattern, d):
if d == 0:
return [Pattern]
if len(Pattern) == 1:
return ['A', 'C', 'G', 'T']
Neighborhood = [... |
class SalesSummary:
def __init__(self, seller_id, sales_year, sales_quarter, sales_expenses_amount, sales_revenue, sales_profit):
self.seller_id = seller_id
self.sales_year = sales_year
self.sales_quarter = sales_quarter
self.sales_expenses_amount = sales_expenses_amount
... |
from django.db import models
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class DummyModel1(models.Model):
title = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse("dummymodel1-detail", args=(self.pk,))
clas... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Secretaire)
admin.site.register(Eleve)
admin.site.register(Classe)
admin.site.register(CahierTexte)
admin.site.register(Prof)
admin.site.register(Cours)
admin.site.register(Notification)
admin.site.register(Enseigne... |
#!/usr/bin/env python3.6
from functions import *
import argparse
parserdescription = 'Arguments for k, training set, and test set'
parser = argparse.ArgumentParser(
description=parserdescription
)
parser.add_argument(
'train',
... |
from .split_train_val_params import SplitTrainValParams
from .feature_params import FeatureParams
from .model_params import ModelParams, SearchParams
from .predict_command_params import PredictCommandParams, read_predict_command_params
from .train_pipeline_params import TrainingPipelineParams, read_training_pipeline_pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# DCASE 2016::Sound Event Detection in Real-life Audio / CNN based system
# Arseniy Gorin, AC Technologies LLC
from src.ui import *
from src.general import *
from src.files import *
from src.features_cnn import *
from src.sound_event_detection_cnn import *
from src.dat... |
"""
sentry.tasks.deletion
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from celery.task import task
@task(name='sentry.tasks.deletion.delete_project', queue='cleanup')
def delete_project(object_id, **kwargs):
f... |
from fabric.api import run
from fabric.context_managers import settings
def _get_manage_dot_py(host):
return (
'~/sites/{host}/virtualenv/bin/python '
'~/sites/{host}/source/manage.py'.format(host=host)
)
def reset_database(host):
manage_dot_py = _get_manage_dot_py(host)
with setting... |
import csv
from collections import Counter
import os
import matplotlib.pyplot as plt
path = os.path.join('Data', 'arbolado-en-espacios-verdes.csv')
def leer_arboles(nombre_archivo,especie):
'''Lectura de archivo'''
lista = []
file = open(nombre_archivo,'rt')
rows = csv.reader(file)
headers = next(... |
PREGUNTA = '¿Cómo te llamas?'
RESPUESTA = input(PREGUNTA)
print('Hola', RESPUESTA,'¿Como estas?')
respuesta_formateada = 'Hola {}, ¿Como estas?'.format(RESPUESTA)
print(respuesta_formateada) |
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linkedlist:
def __init__(self):
self.head=None
def print_list(self):
cur_node=self.head
while cur_node:
print(cur_node.data)
cur_node=cur_node.next
def append(self,... |
from toxi.geom.mesh2d import Voronoi
from toxi.geom import SutherlandHodgemanClipper
from toxi.geom import Vec2D
from toxi.geom import Line2D
from toxi.geom import Polygon2D
from toxi.geom import Rect
from toxi.util.datatypes import BiasedFloatRange
W = H = 500
FPS = 20.0
BG_COLOR = color(53,44,73)
MAIN_COLOR = color... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from math import ceil, sqrt
from maths.math_lib import gcd
from maths.primes import inverse_primorial
from maths.tonelli_shanks import square_root_mod
from maths.quotients import representative_in_range, solve_congruences
from structures.fields.finite import FiniteField
from ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'BatteryInfo'
db.create_table(u'data_batteryinfo', (
... |
from numpy import*
from math import*
x= int(input("digite seu valor x:"))
k= int(input("digite seu valor k: "))
n=0
cos=1
print(cos)
|
from .custom_permissions import isOwnerOrReadOnly
from rest_framework import viewsets, permissions
from .models import Paper
from .serializers import PaperSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
from django.shortcuts import get_object_or_404
from rest_framew... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 16:55:01 2020
@author: kedongwang
"""
import time
import pandas as pd
from openpyxl.styles import Alignment
from openpyxl.styles import Font
from openpyxl import Workbook, load_workbook
from os import remove, path
print('开始处理')
start = time.time()
"""excel格式调整类"""
... |
# --------------------------------------------------------
# Write a program that given two numbers a, b print "divisible"
# if one of the two numbers divides the other
a, b = int( input( "a = ")), int( input( "b = "))
if a % b == 0 or b % a == 0:
print( "divisible" )
# ------------------------------------------... |
import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt
def revolve_integral(x, y, xmin, xmax):
""" Function to calculate surface area and volume of an arbitrary solid of rotation about the x axis.
Function utilized a 3D trapezoidal integration method - adds frustums of leng... |
# -*- coding: UTF-8-*-
"""
设计一个猜数字的游戏,系统随机生成一个1~100之间的整数,
玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,
如果猜中了,则告知玩家并提前结束游戏,
如果5次都没猜中,结束游戏并告知正确答案。
"""
import random
secret = random.randint(1,100)
count=1
while count<=5:
temp=int(input("不妨猜一下小甲鱼现在心里想的是哪个数字:"))
result=cmp(temp,secret)
if result==0:
print("恭喜你,猜对了")
... |
# clean the case directory for a restart
import os
nums = 5
base_dir = ['/BIGDATA1/iocas_mmu_3/cesm/1.2.2/ice/14/parallel/' + str(i) + '/mycase' for i in range(nums)]
run_dir = [route + '/run/' for route in base_dir]
fin_dir = [route + '/finished' for route in base_dir]
start_date = '0052-11-15-00000'
for index in... |
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import sys
def detect(target):
# blob object
blob = cv2.dnn.blobFromImage(target, scalefactor=1., size=(300, 300), mean=(104., 177., 123.))
face_detector.set... |
"""isabl_cli validators tests."""
from os.path import join
import click
import pytest
from isabl_cli import api
from isabl_cli import exceptions
from isabl_cli import factories
from isabl_cli import validators
def test_validate_patterns_are_files(tmpdir):
"""Create multiple files and test test_validate_pattern... |
from collections import OrderedDict
from umsgpack import packb
import base64
import datetime
import dateutil.parser
from Cryptodome.Hash import SHA256
from libs import Identity
from .exceptions import ValidationError
def verify_sha256(content, providen_hash: bytes):
"""verify_sha256
Helper function for SHA... |
import linked_lists.my_linked_list as ll
def get_middle(head):
"""
returns middle element of the linked list
:param head: ll.Node
:return: ll.Node
"""
if not head or not head.next:
return head
fast = head
slow = head
while fast.next:
fast = fast.next
if fast... |
# Generated by Django 2.2.2 on 2019-07-31 14:57
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AboutUs',
... |
def bfs(start, end, board, c):
M = len(board[0])
N = len(board)
visit = [[0] * M for _ in range(N)]
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
arr = []
arr.append(start)
visit[start[0]][start[1]] = 0
while arr:
cur = arr.pop(0)
x = cur[0]
y = cur[1]
n... |
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('Best-Loan-for-Students.jpg', 1)
faces = face_cascade.detectMultiScale(img, 1.1,1) #img 1.1,1 is used to detect the rectangle on face
for(x,y,w,h) in faces:
print(x,y,w,h)
img = cv2.rectangle(img, (x,y), (... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pytunegen.tunegen import TuneGen
from pytunegen.constants import full_notes
from midiutil import MIDIFile
import math
class MIDIgen():
"""MIDI Exporter"""
def __init__(self, seed = None, music_length = 50,
scale = None, bpm = None, time_sig ... |
#coding=utf-8
from __future__ import absolute_import
from unittest import TestCase
if __name__ == "__main__" and __package__ is None:
__package__ = "keyjson_test"
import keyjson
import keyjson_alt
IMPLS = [keyjson, keyjson_alt]
BYTESTRINGS = [
'', '1', '12', '123', '1234', '12345', '123456',
5 * ''.jo... |
# Project Euler: Problem 50
# Jonathan Kosasih
#The prime 41, can be written as the sum of six consecutive primes:
#
#41 = 2 + 3 + 5 + 7 + 11 + 13
#This is the longest sum of consecutive primes that adds to a prime below one-hundred.
#
#The longest sum of consecutive primes below one-thousand that adds to a prime, con... |
from db_connection import get_db_connection
from db_connection import get_testdb_connection
from initialize_db import initialize_db
class HighscoresRepository:
"""Luokka, jolla hallinoidaan uusien tulosten lisäämistä ja hakemista tietokannasta
"""
def __init__(self, testing=False):
"""Luokan konstr... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
# Create your views here.
@login_required
def profile(request, username=None):
if username:
u = User.objects.get(username=username)
user = u
else:
u... |
import requests
from requests.compat import quote_plus
from django.shortcuts import render
from bs4 import BeautifulSoup
from . import models
# Create your views here.
BASE_URL='https://ahmedabad.craigslist.org/search/?query={}'
BASE_URL_IMG='https://images.craigslist.org/{}_300x300.jpg'
def home(request):
retur... |
import pyautogui
import random
import scipy
import time
from scipy import interpolate
# Any duration less than this is rounded to 0.0 to instantly move the mouse.
pyautogui.MINIMUM_DURATION = 0 # Default: 0.1
# Minimal number of seconds to sleep between mouse moves.
pyautogui.MINIMUM_SLEEP = 0 # Default: 0.05
# The ... |
from elasticsearch_dsl import A
from app.models.movie import Movie
from pprint import pprint
search = Movie.search()
def get_all_genre():
genre_agg = A('terms', field = 'genre.raw')
search.aggs.bucket('genre_terms', genre_agg)
result = search.execute()
# pprint(result.aggregations['genre_terms']['buckets'])
... |
mysecretdictionary = {
"a": "z",
"b": "y",
"c": "x",
"d": "w",
"e": "v",
"f": "u",
"g": "t",
"h": "s",
"i": "r",
"j": "q",
"k": "p",
"l": "o",
"m": "n",
"n": "m",
"o": "l",
"p": "k",
"q": "j",
"r": "i",
"s": "h",
"t": "g",
"u": "f",
... |
from django.shortcuts import render
from orders.models import Food_item, Cart, Order, Regular_Pizza, Sicilian_Pizza, Topping, Sub, Salad, Pasta, Dinner_Platter
def index(request):
#if (session.get('channel')!=None and session.get('dp_name')!=""):
# return render_template("chats.html", channel=session['... |
from ecdsa import SigningKey, SECP256k1
import hashlib
from hashlib import sha256
from utilitybelt import change_charset
from binascii import hexlify, unhexlify
def get_pair():
sk = SigningKey.generate(curve=SECP256k1)
vk = sk.get_verifying_key() # curve.generator * sk.privkey.secret_multiplier
point = vk... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
# @Project :ShangKe
# @File :my_stydy
# @Date :2020/10/21 9:40 上午
# @Author :段益迈
# @Email :dym0822@163.com
# @Software :PyCharm
-------------------------------------------------
"""
class English:
def eng_know(self):
... |
from cfoundation import Service
from os import path
class Stow(Service):
def stow(self, packages):
s = self.app.services
home_path = path.expanduser("~")
dotfiles_path = path.join(home_path, '.dotfiles')
s.util.subproc('stow -t ' + home_path + ' -d ' + dotfiles_path + ' ' + ' '.join... |
from MainClasses import *
#from GroceryApp import shopping_objects
#from GroceryApp import *
shopping_objects = []
class MenuActions():
def __init__(self):
pass
def shopping_object_to_string(self, shopping_objects): #This method creates a list of shopping destinations, so when the user wants to ... |
import os,re,linecache,argparse
MSE, MSE_X, MSE_y = 0, 0, 0
FACE=0
eyes2eyes=0
def cal_iou(box1, box2):
"""
:param box1: = [xmin1, ymin1, xmax1, ymax1]
:param box2: = [xmin2, ymin2, xmax2, ymax2]
:return:
"""
xmin1, ymin1, xmax1, ymax1 = box1[0], box1[1], box1[2], box1[3]
xmin2, ymin2, xma... |
from django.conf.urls import url
from .views import *
from django.contrib import admin
urlpatterns = [
# url(r'^$', index, name='index'),
# url(r'^p/(?P<article_id>[0-9]+)/$', detail,name='detail'),
url(r'',admin.site.urls),
url(r'^register/$',register, name='register'),
url(r'^login/$',my_lo... |
# Find a Profile-most probable k-mer in a string.
# Input: A string Text, an integer k, and a k × 4 matrix Profile.
# Output: A Profile-most probable k-mer in Text.
import sys
from operator import mul
lines = open(sys.argv[1].strip(), 'r').readlines()
dna = lines[0].strip()
k = int(lines[1])
profile = [map(float, l.s... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2023 Amano LLC
from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.errors import BadRequest
from pyrogram.types import ChatPrivileges, InlineKeyboardMarkup, Message
from config import PREFIXES
from eduu.database.welcome import get... |
def cart_to_tab_add(tree, l):
if tree:
cart_to_tab_add(tree.left, l)
l.append(tree.val)
cart_to_tab_add(tree.right, l)
def cart_to_tab(tree):
l = []
cart_to_tab_add(tree, l)
return l
def cart_haut(tree):
return 1+max(cart_haut(tree.right), cart_haut(tree.left)) if tree else 0
def cart_to_str(tree):
if tr... |
import re
a = raw_input("Enter the file to split:")
lines = int(raw_input("Enter the number of lines with which the file to split:"))
s = re.search(r'\.\w+$', a)
s = s.group()
g = open(a,'r')
for row, con in enumerate(g):
row=row+1
g.close()
number=1
count=0
t=0
f = open(a,'r')
for line in f:
count += 1
... |
#!/usr/bin/env python3
import os
import qm3.utils
import qm3.engines.dynamo
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import qm3.maths.grids
m = qm3.engines.dynamo.coordinates_read( "crd.0.0" )
bnd = [ ( m.indx["A"][145]["SG"], m.indx["A"][613]["C36"] ),
( m... |
# -*- coding: utf-8 -*-
from wtforms import TextAreaField
from wtforms.widgets import TextArea
class CKEditor(TextArea):
def __call__(self, field, **kwargs):
c = kwargs.pop('class', '') or kwargs.pop('class_', '')
kwargs['class'] = u'%s %s' % ('ckeditor', c)
return super(CKEditor, self).__... |
#!/usr/bin/env python
"""A facade for the GRR-FS server-side connection."""
import logging
from typing import Optional
from grr_response_core import config
from fleetspeak.server_connector import connector as fs_client
# The singleton instance of the Fleetspeak connector.
CONN: Optional[fs_client.ServiceClient] = Non... |
#https://www.cs.ubc.ca/~murphyk/Teaching/CS340-Fall07/denoise.pdf
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame as df
from numpy.random import randint, randn, rand
Size = 50
J = 1
H = 0.0
Temp = 0
def spin_direction(field, x, y):
energy = H
for dx, dy in [(-1,0), (1,0), (0,... |
import numpy
##
# Closed-loop maintenance of a dark hole in a coronagraph (based on https://arxiv.org/abs/1902.01880) via a combination of wavefront control (Electric Field Conjugation - EFC) and estimation (Extended Kalman Filter - EKF).
# The example compares the contrast in the dark hole as the wavefront error accu... |
import pandas as pd
from datetime import date
import os
import glob
from sphdf import read_sp_hdf
import numpy as np
today = date.today()
f_name = 'results_' + str(today)
results_path = '/home/vojtech/Nextcloud/python/UHFO_Pavel/results_generic/' + f_name + '/'
if not os.path.exists(results_path):
os.mkdir(resul... |
'''
天赋特性 --1.0 initial
--1.1 生效时间 #战前类型 只有技能威力的提升 其他有buff 提供 或者后续版本
#战中类型 只有伤害增强类型
#战后类型 只有回复气血类型
#其他类型 后续nn个版本
--2.0 与技能的配合
'''
class Talent(object):
def __init__(self,name=None,talen... |
import json
import pickle
import sys
from loguru import logger
def load_json(fp):
with open(fp, "r", encoding="UTF-8") as f:
return json.load(f)
def load_token(token):
creds = bytearray.fromhex(token)
return pickle.loads(creds)
def set_logger(log_path="Logs/algs.log"):
log_format = (
... |
import numpy as np
import pyroomacoustics as pra
def compute_rir(order):
fromPos = np.zeros((3))
toPos = np.ones((3, 1))
roomSize = np.array([3, 3, 3])
e_abs = 1.0 - (1.0 - 0.95) ** 2
room = pra.ShoeBox(
roomSize, fs=1000, materials=pra.Material(e_abs), max_order=order
)
room.add_... |
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch
import pdb
# import your model class
# import ...
from Yandhi import Yandhi, Segmentation
# Put your transform function here, we will use it for our dataloader
# For bounding boxes task
def get_transform_task1():
return torchvis... |
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedir... |
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
denominator = 0
print("Cannot div... |
# Generated by Django 3.1.1 on 2020-12-18 12:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0010_orders_deductible'),
]
operations = [
migrations.CreateModel(
name='Enquiry',
fields=[
... |
metadata = """
summary @ GObject bindings for libudev
homepage @ https://wiki.gnome.org/Projects/libgudev
license @ LGPL2.1
src_url @ https://download.gnome.org/sources/libgudev/230/libgudev-230.tar.xz
arch @ ~x86_64
"""
srcdir ="libgudev-230"
depends = """
runtime @ sys-libs/glibc
"""
def install():
raw_install(... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtWidgets, QtGui
import sys
import subprocess
import os
import platform
from pnn import analysis
imp... |
#Function to calculate sentiment value of new words found in the tweet
def new_words_sentiment(new_words,tweet={}):
file=open("sentiment_new_words.txt","w");
res = 0.0
#Loop to calculate the new word from the tweet that are not present in dictionary
for words in new_words:
value = 0;
cou... |
# Use this to find the theoretically perfect level of TIR1 expressions
from matplotlib import pyplot as plt
import numpy as np
import math
from scipy.integrate import odeint
import random
def find_index_from_time(t_obs,time,start_index=0):
i=start_index
while i+1<len(t_obs):
if t_obs[i+1]>time:... |
# Copyright 2022 The nn_inconsistency Authors. 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-2.0
#
# Unless required by a... |
import random
list_a = [1,2,3,4,5]
# 리스트의 원소중에 2 와 3의 값을 변경
temp = list_a[1]
list_a[1] = list_a[2]
list_a[2] = temp
print( list_a)
# 1 ~ 45
rotto= list(range(1,46))
# random
print('섞기전 : ', rotto)
# 위치변경하기(두 변수의 값을 교환)
# 리스트의 첫번재 값과 임의의 위치에 해당하는 값을 교환
# for문이용하는 적당히 순환 대략 100번 rotto[0]
fo... |
import sys
import threading
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QGridLayout, QSizePolicy, QApplication
from src.models.dataframe_model import DataFrameModel
from src.views.dataframeview.datatable_view import DataTableView
from src.views.dataframeview.header... |
# -*- coding: utf-8 -*-
"""
This module provides the main command line interface to using VSG.
"""
import os
import sys
import argparse
def make_parser(**kwargs):
"""
Generates the application's :class:`~argparse.ArgumentParser` instance.
"""
from vsgenptvs.suite import PTVSSuite
return PTVSSuite... |
#!/usr/bin/env python3
"""
hist.py; plot fkpm
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
fpkms = []
for i, line in enumerate(open(sys.argv[1])):
if i == 0:
continue
col = line.rstrip("\n").split("\t")
if float(col[11]) > 0:
fpkms.append(f... |
"""[
Rytong.BuildApp
Created by xie.pignjia on 14-10-3.
]
"""
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import codecs
"""---------------------------------------------------"""
"""HG"""
username1 = "xie.pingjia"
password1 = "xpj123"
""""""
BundleIdentifier1 = "ssdsa... |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
import KratosMultiphysics.DEMApplication as DEM
import KratosMultiphysics.DEMApplication.main_script as MainDEM
import KratosMultiphysics.FemToDemApplication as FEMDEM
class DEM... |
import sys
def convert_to_intlist(line):
return [int(elem) for elem in line.split()]
def merge_sorted_arrays(first, second, length_1, length_2, inversions):
merged_list = []
ix = 0
jy = 0
while ix < length_1 or jy < length_2:
if ix == length_1 and jy < length_2:
merged_list.a... |
# Do not modify these lines
__winc_id__ = '71dd124b4a6e4d268f5973db521394ee'
__human_name__ = 'strings'
# Add your code after this line
first_scored_goal = 'Ruud Gullit'
second_scored_goal = 'Marco van Basten'
# tijdvandescores
goal_1 = str(32)
goal_2 = str(54)
scorers = (first_scored_goal + ' ' + goal_1 +... |
__version__ = '1.8.0.dev20201210'
debug = False
cuda = None
git_version = 'ff32f65844e3661ce43d5cea0eb83defea2c012f'
hip = None
|
def fac(n):
if n == 0:
return 1
return n*fac(n-1)
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def eta(n):
for i in range(2, n+1):
if isPrime(i):
x = 1
while x < n:
x *= i
if x == n:
return i
return 1
def delta(x):
product = 1
for n in range(x)... |
"""
Rutines for iterating lists
+------------------------------------------------+----------------------+
| Functions | Description |
+================================================+======================+
| :py:func:`~matlab2cpp.tree.iterate.comma_list` | Iterate over a... |
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn import tree
from sklearn.model_selection import cross_val_score, KFold
from sklearn.externals import joblib
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
def maxDepth(train_X, train_Y, testX, targetTest):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.