text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
"""
* Get fortran code running for comparisons with R's party:cforest
** install cforest
** have script which runs forest and cforest on some dataset
** also run parf rf classifier on dataset
*** betsy: ~/scratch/rf_parf/parf
** compare results (will need to do crossvalidation)
** First try out ... |
#config.py
# Config file for PyGlass Client
from configobj import ConfigObj
#This imported by PyGlass via import config
#
#CONSTANTS
TEST = 1 #run test routine (will not recieve any data from Flight Sim program)
FSXSP0 = 2 #Recieve data from test routine
FSXSP1 = 3
FSXSP2 = 4
ESP = 5
CLIENT = 6
modes = {'Test':1,'FSX... |
"""
BasicWriter Class
"""
from logging import Logger
import os
from ..common import get_default_logger, WriteFileAlreadyExists
from ..format.ynf import cYnf
class BasicWriter(object):
"""
BasicWriterクラス。
Ynf形式から何かのフォーマットへ変換する処理の基底クラス。
"""
def __init__(self, file_path:str, overwrite:bool=False, log... |
#!/bin/python3
"""
bumper
======
Version bumping interface.
Allows bumping by specified version and SemVer semantics.
"""
from abc import ABCMeta, abstractmethod
from garden.log import logger
import argparse
import enum
import re
_logger = logger
#: Regex for matching version numbers
RE_VERSION = '(?P<version>(?:... |
import math
print(math.pow(6,1000)) |
import json
global profile_list
profile_list = []
with open("profiles.txt","r") as file:
for profile in file:
profile_list.append(profile[:-1])
global logins_undftd
logins_undftd = []
with open("logins_undftd.txt","r") as file:
for line in file:
login = {}
login.update({"username":line.... |
from django.db import models
class Transactions(models.Model):
amount = models.BigIntegerField(),
user_ID_from = models.PositiveIntegerField(),
user_ID_to = models.PositiveIntegerField(),
date = models.parse_datetime(),
#TODO @classmethod
#TODO def create_transaction(cls, amount,user_ID_from, user_ID... |
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
#import GCForest
import pandas as pd
import time
import numpy as np
from sklearn.model_selection import train_test_split
#from GCForest import gcForest
from sklearn.metrics import accuracy_score
from gcforest.gcforest import G... |
# Generated by Django 3.0.3 on 2020-03-16 18:43
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ClienteModel',
fields=[
('id', models.AutoF... |
import os
from ase.io import vasp
from ase.io import lammpsdata
import configparser
import sys
binVasp = 'vasp_std'
elements = []
def readVASP(inputFile):
global binVasp
global elements
# Read input data for the interface
config = configparser.ConfigParser()
config.read(inputFile)
vars = config... |
from tf2_models.attention.transformer import point_wise_feed_forward
from tf2_models.attention.transformer import transformer
from tf2_models.attention import masks
import tensorflow as tf
import tensorflow_datasets as tfds
import time
import numpy as np
import matplotlib.pyplot as plt
import logging
logger = tf.get_lo... |
from hashlib import *
from pwn import p64
# Currently works only for md5 hashes
"""
Step 1: Get the values of data, append, length of the string from the user
Step 2: (i) Pad the secret+data with '1' and '0's such that the resultant length
becomes congruent to 56 modulus 64
(ii) Convert length of s... |
import GlobalSettings
import os
from PyQt5 import QtWidgets, Qt, uic
import traceback
import math
#global logger
logger = GlobalSettings.logger
###########################################################
# closingWindow: this class is a little window where the user can select which files they want to delete
# Once th... |
# Copyright 2017 The Forseti Security 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 ap... |
########################################
# This script is a helpful tool for locating the position of context corresponding to the quesition.
# Calculating N-gram language model probabilites of context sentence.
import math
import sys
import operator
########################################
# Language model function... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
from web_backend.nvlserver.module import nvl_meta
from sqlalchemy import (
BigInteger, String, Column, Boolean, DateTime, Table, ForeignKey, func, LargeBinary, PrimaryKeyConstraint,
Numeric
)
from sqlalchemy.dialects.postgresql import JSONB
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 12:30:10 2021
@author: Victor
"""
import requests
import base64
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
def auth():
return auth_manager
Client_ID = 'c6d7404e014a4395b773c3b3f4c50d95'
Client_Secret = '8004465dd19444eab52... |
questions = ["What is the capital of telangana?","Which is the smallest state in India?","Which is the most populated country in the world?","What is the capital of Himachal Pradesh?","Raipur is the capital of which state of India?"]
first_options = ["Jaipur","Maharastra", "USA","Chandigarh","Chhattisgarh"]
second_opt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Andre Fellipe'
SITEURL = 'https://andrefellipe.com'
SITENAME = u"Andre Fellipe"
SITETITLE = u'Andre Fellipe'
SITESUBTITLE = u'made on the internet'
SITEDESCRIPTION = "Andre's personal site"
SITELOGO = SITEURL + '/images/... |
import sys, os
import numpy as np
sys.path.append(os.pardir)
from common.util import im2col
a1 = np.random.rand(5, 9, 11, 11)
col1 = im2col(a1, 10, 10, stride=2, pad=1)
print(col1.shape) # (20, 900)
a2 = np.random.rand(30, 7, 9, 9)
col2 = im2col(a2, 10, 10, stride=2, pad=1)
print(col2.shape) # (30, 700)
|
a=input("Write a: ")
b=input("Write b: ")
S=float(a)*float(b)
print(S)
P=2*(float(a)+float(b))
print(P) |
# -*- coding: utf-8 -*-
import pytest
from django.core.management import call_command
from chloroform.mails import ChloroformMailBuilder
from chloroform.models import Contact, Configuration
@pytest.fixture
@pytest.mark.django_db
def cf(settings):
settings.CHLOROFORM_DOMAIN = 'https://chloroform.emencia.net'
... |
"""
The disappearing cross task reimplemented from Blascovich & Katkin 1993.
mattcieslak@gmail.com
"""
from fmri_trigger import TRIGGER_EVENT, RIGHT_BUTTON_EVENT, LEFT_BUTTON_EVENT
import viz, vizact, viztask, vizinfo
# Images
cue = viz.addTexture("images/cue.png")
hbar = viz.addTexture("images/hbar.png")
vbar = viz.a... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import re
from textwrap import dedent
from typing import Iterable
import pytest
from internal_plugins.test_lockfile_fixtures.lockfile_fixture import (... |
#################################################################################
# Name : Matthew Nummy
# Date : 11/25/2020
# Assignment : Quiz 2 - Part 2
# Pledge : I pledge my Honor that I have abided by the Stevens Honor System
# I understand that I may access the course textbook and co... |
# -*- coding: utf-8 -*-
#
# This file is part of Flask-AppExts
# Copyright (C) 2015 CERN.
#
# Flask-AppExts is free software; you can redistribute it and/or
# modify it under the terms of the Revised BSD License; see LICENSE
# file for more details.
"""Flask-Collect extension."""
from __future__ import absolute_impor... |
from collections import defaultdict
from devpi_server.log import threadlog as log
from devpi_server.readonly import get_mutable_deepcopy
from devpi_web.whoosh_index import project_name
from elasticsearch import Elasticsearch
from elasticsearch.helpers import streaming_bulk
class Index:
def __init__(self):
... |
../../process/base/common_base.py |
#!\usr\bin\env python
import os
import sys
import subprocess as sp
dimensions = \
{"merged":63, \
"colorNormalHist":45, \
"colorHSV":3, \
"colorRGB":3, \
"colorH":5, \
"colorS":5, \
"colorV":5, \
"colorHist":30, \
"normal":3, \
"normalX":5, \
"normalY":5, \
"normalZ":5, \
"normalHist":15, \
"normalHistLarge":27, \
"f... |
class CoreException(Exception):
"""Exists for the benefit of making the cli easier to catch exceptions."""
class SubmoduleFindingError(CoreException):
"""when struggling to find the submodule."""
class DirtyRepoError(CoreException):
"""dirty repo, d'uh"""
class MasterBranchError(CoreException):
""... |
# At start-up, a Thread does some basic initialization and then calls its run()
# methond, which calls the target function passed to the constructor. To create
# a subclass of Thread, override run() to do whatever is necessary.
import threading
import logging
logging.basicConfig(level=logging.DEBUG,
format='(... |
# paramiko模块支持以加密和认证的方式连接远程服务器。可以实现远程文件的上传,下载或通过**==ssh==**远程执行命令。
# 安装: pip3.6 install paramiko
# paramiko模块远程上传下载文件
import paramiko # 导入import模块
# trans = paramiko.Transport(("10.1.1.12",22)) # 产生连接10.1.1.12的22的传输,赋值给trans
#
# trans.connect(username="root",password="123456") # 指定连接用户名与密码
#
# sftp = paramik... |
#coding=utf8
from django.db import models
# Create your models here.
class Accounts(models.Model):
usr_name = models.CharField(max_length = 64)
passwd = models.CharField(max_length = 256)
email = models.EmailField()
phone = models.CharField(max_length = 32)
qq = models.CharField(max_length = 64)
|
# -*- coding: utf-8 -*-
#
# Copyright 2016 Ramil Nugmanov <stsouko@live.ru>
# This file is part of MODtools.
#
# MODtools is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License,... |
# http://www.practicepython.org/exercise/2014/07/14/19-decode-a-web-page-two.html
from bs4 import BeautifulSoup
import requests
url = requests.get("http://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture")
sopa = BeautifulSoup(url.text, "lxml")
titulo = sopa.find("h1")
subtitulo = titulo.... |
from ._uirevision import UirevisionValidator
from ._sector import SectorValidator
from ._radialaxis import RadialAxisValidator
from ._hole import HoleValidator
from ._gridshape import GridshapeValidator
from ._domain import DomainValidator
from ._bgcolor import BgcolorValidator
from ._barmode import BarmodeValidator
fr... |
import io
with io.open('1000english.txt', 'r', encoding='utf8') as f:
english_words = set(word.strip().lower() for word in f)
with io.open('1000welsh.txt', 'r', encoding='utf8') as g:
welsh_words = set(word.strip().lower() for word in g)
def is_english_word(word):
return word.lower() in english_words
de... |
"""
7. Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
"""
lado_quadrado = float(input("Digite o comprimento de um lado do quadrado: "))
area_quadrado = lado_quadrado * 2
dobro_area = 2 * area_quadrado
print(f"A área do quadrado é igual a {area_quadrado}m2 e o d... |
import FunctionsForModuleCreations2
number = int(input("enter a number = "))
(FunctionsForModuleCreations2.num(number)) |
dictionary = {
'1' : 'One',
'2' : 'Two',
'4' : 'Four',
'5' : 'Five',
'6' : 'Six',
'7' : 'Seven',
'8' : 'Eight',
}
dictionary[9] = ['soda', 'loli']
# print(dictionary)
zx = {
1 : {'we', 'are', 'great'},
2 : {'we', 'are', 'great'}
}
# print(zx)
# print(type(zx))
# TABLE for a sing... |
# libraries
import pickle
import numpy as np
import pandas as pd
import fbprophet as prop
from keras.models import load_model
def predict_arima(trained_model, predict_type, n_periods, df_train=None, df_test=None):
assert predict_type in ('once', 'sequential')
# load the trained model
with o... |
class Movie(object):
"""
A movie object stores a movie's title, genres, and description.
"""
def __init__(self, title, genres, description):
"""
Initializes a Movie object.
title: string, movie's title
genres: list of strings, movie's genres
description: string, m... |
# Copyright 2021-2022 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
#importamos todas las clases y funciones de las otras carpetas
from db.user_db import UserInDB
from db.user_db import update_user, get_user
from db.transaction_db import TransactionInDB
from db.transaction_db import save_transaction
from models.user_models import UserIn, UserOut
from models.transaction_mode... |
from utils.function.setup import *
from utils.lib.user_data import *
from main.activity.desktop_v3.activity_login import *
from main.activity.desktop_v3.activity_logout import *
from main.activity.desktop_v3.activity_user_settings import *
import unittest
class TestProfile(unittest.TestCase):
#Instance
_site =... |
from urllib import request
import tarfile
import argparse
import json
from pathlib import Path
JOPLIN_PORT_RANGE = (41184, 41194)
JOPLIN_PING_RESPONSE = "JoplinClipperServer"
JOPLIN_RESOURCES_PATH = "resources/"
JOPLIN_RESOURCE_ID_LEN = 32
def get_joplin_port():
for port in range(*JOPLIN_PORT_RANGE):
prin... |
#!/usr/bin/env python3
"""Fit the Lotka-Volterra with prey density dependence rR(1 - R/K), plot and save population dynamics between consumer and resource with input from command line"""
__appname__ = '[LV3.py]'
__author__ = 'Zongyi Hu (zh2720@ic.ac.uk)'
__version__ = '0.0.1'
# import packages
import scipy as sc
imp... |
import requests
from os import system,chdir,mkdir
from time import sleep
import concurrent.futures
system('clear')
la7mar = '\033[91m'
la5dhar = '\033[92m'
labyadh = '\033[00m'
green = "\033[0;32m"
red = '\033[31m'
g = '\033[32m'
y = '\033[33m'
b = '\033[34m'
m = '\033[35m'
c = '\033[36m'
w = '\033[37m'
auth = """{} M... |
from fractions import Fraction
a = Fraction(5, 4)
b = Fraction(7, 16)
print a + b
print a * b
c = a * b
print c.numerator
print c.denominator
print float(c)
print c.limit_denominator(8)
x = 3.75
y = Fraction(*x.as_integer_ratio())
print y |
from clientpy3 import *
import time
import random
import math
def status_parser(status):
try:
tokens = status[0]
except (IndexError):
return
tokens = status.split(' ')
# print(tokens)
data = {}
data['position'] = (tokens[1],tokens[2])
data['velocity'] = (tokens[3],tokens[4])
num_mines = int(... |
#!/usr/bin/python
import sys
from PyQt5 import QtCore, QtGui, QtWidgets,uic
from sympy import mod_inverse #for optimized mod_inverse
import sys
#Import code generated by pyqt5 designer
#pyuic5 *.ui -o *.py
from Ciphers import Ui_MainWindow
class Ui(QtWidgets.QMainWindow):
global firstRun # Described where I use i... |
def joke():
return (u'''I'm fed up with kleptomaniacs... '''
u'They take everything literally')
|
#REPASO DE CONCEPTOS BÁSICOS
'''
numeros = [1, 2, 3, 4, 5]
print(numeros)
primera_posicion = numeros[0]
longitud = len(numeros)
print(f"El primer valor es: {primera_posicion}\nLa longitud de la lista es: {longitud}")
#ITERAR SOBRE UNA LISTA
for num in numeros:
print(num)
'''
'''
#INDEXADO Y SUBLISTAS
lista = ["E... |
'''
输出九九乘法表
'''
def lower_triangle(): #下三角输出
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%d"%(i,j,i*j),end="\t")
print()
def upper_triangle(): #上三角输出
for i in range(1,10):
for t in range(2,i+1):
print("\t",end="")
for j i... |
import pandas as pd
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
import sys
sys.path.insert(1, '/home/marcon/Documents/exchange/')
import config
# Authenticate
client = Client(config.API_KEY, config.API_SECRET)
# Get Tickers
tickers = client.get_all_tickers()
ticker_df = pd.DataFram... |
from flask import Flask, request, make_response
import logging
from logging.handlers import RotatingFileHandler
import paramiko
from config import Config
import requests
import os
BASEPATH = os.path.abspath(os.path.dirname(__file__))
print('BASE', BASEPATH)
def check_dir(dir):
print('check_dir:', dir)
if not ... |
import socket
import subprocess
import time
import os
host = '127.0.0.1'
port = 52918
password = '' #soon askfor password
#issue : security
#-solution : add password with hashing base64/md5 to matching server password if timeout 3/5 second without password then DIE
#-solution : send header to matching the rat client ... |
#!/usr/bin/python
'''
plot_log in DeepGeom
author : cfeng
created : 1/31/18 7:49 AM
'''
import os
import sys
import glob
import time
import argparse
import numpy as np
from matplotlib import pyplot as plt
from utils import TrainTestMonitor as TTMon
#from Tkinter import Tk
#import tkFileDialog
... |
import Tkinter, tkFileDialog
import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot as plt
filepath = 'G:\My Drive\Lab\UIUC EPR Data\Day 2\T1\data_fit_stretchedInvRec2\\temp_dep_stretched.txt'
if filepath == '':
root = Tkinter.Tk()
root.withdraw()
... |
#!/usr/bin/env python
"""
Package specific script that 'builds' the package content as part of the
publish process.
Usage: build <pkgroot>
Returns: If the build is succesful, then the script returns '0'; else
a non-zero value is returned.
"""
#------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
import numpy as np
import sys
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
# 接收外部传入的参数
filename = sys.argv[1]
# filename = "admin2.csv"
# 获... |
# this is a simple attempt to make a *navigable* documentation within |Vim|
from sage.rings.integer import Integer
from riordan_utils import *
from riordan_group import *
from riordan_visiting import *
class AbstractTriangleShape:
def format_tikz_node_template_string(self, **kwds):
return self.build_ti... |
def test_challenge1():
from challenge1 import ENTRIES, get_entries_summing_to
assert get_entries_summing_to(ENTRIES, 2020) == (438, 1582)
assert get_entries_summing_to(ENTRIES, 2020, 3) == (688, 514, 818)
def test_challenge2():
from challenge2 import PASSWORDS, get_number_of_valid_passwords, get_numbe... |
list = ['1', '2','3']
list1 = list.copy()
print(list)
print(list1) |
import requests
import re
from bs4 import BeautifulSoup
from lxml import etree
import time
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0',
'Host': 'movie.douban.com',
'Cookie': 'll="118208"; bid=7oCzYf0fk0w; _pk_ref.100001.4cf6=%5B%22%22%... |
import requests
import json
import pandas as pd
#
# Get all weather stations available at Climate Data Online Web Services
# found on the map within USA coordinates +/- Bermuda, Bahamas etc. having name ending in US
# having data available starting start_date
# Service Doc: https://www.ncdc.noaa.gov/cdo-web/webservice... |
#!/Users/apple/silver/projects/PERSONAL/STEGANOGRAPHY/stenoENV/bin/python3.8
import sys
from lib2to3.main import main
sys.exit(main("lib2to3.fixes"))
|
# Usage: $ python3 get_sac_files_lines.py /home/kevin/Desktop/sac-data/stats output.csv
# python3 get_sac_files_lines.py <merged_files> <merged_files> <output_path>
#
# Merges all the extracted contribution per tag data into one single file.
__author__ = 'kevin'
import sys
import csv
import os
# RQ 1: Gener... |
import sys
import os
f = open("C:/Users/user/Documents/atCoderProblem/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n = int(input())
s = list(input())
def list_intersection(a,b):
c = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
... |
# Generated by Django 3.0.3 on 2020-05-11 18:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dimensoes', '0009_auto_20200504_1529'),
]
operations = [
migrations.AlterField(
model_name='dimensaomodel',
name='co... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
#生成Java和CSharp所需要的MessageID文件
import os
import sys
#设置初始ID值,这里必须从20002开始,server端定义login方法如果不是20002就返回错误,fuck!!!
start_index = 20002
java_class_name = "HOpCodeEx.java"
cs_class_name = "MessageID.cs"
proto_file = open("PBMessage.proto","r")
lines = proto_file.rea... |
import boto3
import json
def get_system_manager_info():
"""
A fucntion that gives the associations and documents details
"""
conn = boto3.client('ec2')
regions = [region['RegionName'] for region in conn.describe_regions()['Regions']]
association_details = []
document_details = []
comma... |
# Generated by Django 2.2.1 on 2019-07-28 13:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('notice', '0013_comment_comment_writer'),
]
operations = [
migrations.AlterModelOptions(
name='notice',
options={'ordering': ... |
a = 'mini'
b = 'ari'
print "%r/n loves %r !" %( a , b )
|
import base64
import eventlet
import os
import subprocess
import sys
import yaml
from forge.tasks import sh, TaskError
def key_check():
if not os.getenv('SOPS_KMS_ARN'):
raise TaskError("You must obtain the master key and export it in the 'SOPS_KMS_ARN' environment variable")
def decrypt(secret_file_dir... |
"""
Train Script of Auto Encoder Model
"""
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model import AutoEncoder, CAE
from load_data import ImbalancedCIFAR10
device... |
s1={"a","e","i","o","u"}
s2={"k","l",'m',"n","o"}
s3=s1-s2
print(s3)
s4=s2-s1
print(s4)
print(s4-s3)
|
STM_message1 = "Welcome to Spin That Mission!"
print(STM_message1)
STM_message2 = "Click Ok to Start"
print(STM_message2) |
import tkinter as tk
def recalc():
cel_temp = entry_cel.get() # get temp from text entry
try: # calculate converted temp and place it in label
far_temp = float(cel_temp) * 9/5 + 32
far_temp = round(far_temp, 2) # round to 2 decimal places
result_far.config(text=far_temp)
except Valu... |
# -*- coding: utf-8 -*-
from collective.cover.tiles.base import IPersistentCoverTile
from collective.cover.tiles.base import PersistentCoverTile
from plone.app.uuid.utils import uuidToObject
from plone.memoize import view
from plone.tiles.interfaces import ITileDataManager
from plone.uuid.interfaces import IUUID
from P... |
from django.shortcuts import render,redirect
from .models import *
from aristo.models import *
from payment.models import *
from instagram import functions
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate, logout
from instagram import private_api
import time
from . impor... |
import gevent.monkey
gevent.monkey.patch_all()
from flask import Flask, render_template, request, redirect
from flask_socketio import SocketIO
import sqlite3
from chatterbot import ChatBot
#
bot = ChatBot(
'Terminal',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
logic_adapters=[
{
... |
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from polls.views import PollViewSet
router = DefaultRouter()
router.register('polls', PollViewSet, basename='polls')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(rou... |
import math
limit = 50*10**6
primes = []
not_primes = set([0, 1])
# Crible d'Erathostene : on remplit primes (en utilisant not_primes)
print "Loading of the primes until", limit
for head in range(2, int(math.sqrt(limit)) + 1):
if head not in not_primes:
primes.append(head)
i = 2
next_not_p... |
# Generated by Django 3.0.3 on 2020-02-08 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facts', '0003_auto_20200208_1221'),
]
operations = [
migrations.AlterField(
model_name='artist',
name='artist',
... |
# -*- coding: utf-8 -*-
"""
Deep Q-network implementation with chainer and rlglue
Copyright (c) 2015 Naoto Yoshida All Right Reserved.
"""
import copy
import pickle
import numpy as np
import cv2
import scipy.misc as spm
import sys
import matplotlib
import matplotlib.pyplot as plt
from chainer import cuda, FunctionSe... |
from pywss import Pyws, route
@route('/test/example/1')
def example_1(request, data):
return data + ' - data from pywss'
if __name__ == '__main__':
ws = Pyws(__name__, address='127.0.0.1', port=7006)
#from ipdb import set_trace; set_trace()
ws.serve_forever() |
import cv2
import TD
img = cv2.imread('test.jpg')
rect = TD.text_detect(img)
for i in rect:
cv2.rectangle(img,i[:2],i[2:],(0,255,0))
cv2.imwrite('img-out.png', img) |
from typing import List
import random
def countingsort(nums: List[int], place: int) -> List[int]:
count_list = [0] * 10
for num in nums:
index = int(num / place) % 10
count_list[index] += 1
for i in range(1, 10):
count_list[i] += count_list[i-1]
results = [0] * len(nums)
... |
import optproblems.cec2005
import numpy as np
import time
from IA import *
import os
def IAalgorithm(n_parties, politicians, R, function, function_index, max_evaluations, desertion_threshold):
IA = IdeologyAlgorithm(n_parties=n_parties, politicians=politicians, R=R, function=function,
function_inde... |
#!/usr/bin/env python
import json
import sys
import urllib2
twitter_url = 'http://search.twitter.com/search.json?q=from:{username}'
def main():
print 'What username would you like to display?'
username = raw_input('> ')
message = '\nMost recent tweets from @{0}'.format(username)
print message
pr... |
# -*- coding: utf-8 -*-
from collections import deque
class Color:
BLACK = 0
WHITE = 1
class Solution:
def possibleBipartition(self, N, dislikes):
return self.isBipartite(self.toGraph(range(N), dislikes))
def toGraph(self, vertices, edges):
result = [[] for vertex in vertices]
... |
from torch.nn import (
AvgPool2d,
Conv2d,
CrossEntropyLoss,
Dropout,
Flatten,
Linear,
MaxPool2d,
MSELoss,
ReLU,
Sigmoid,
Tanh,
ZeroPad2d,
)
from backpack.extensions.backprop_extension import BackpropExtension
from backpack.extensions.curvature import Curvature
from backp... |
import Choice
def ora_datafile(curs, conn):
tbsnm = input("请输入表空间名:")
df = "select rownum,file_name,bytes/1024/1024,AUTOEXTENSIBLE,maxbytes/1024/1024 from dba_data_files \
where tablespace_name='{}' order by 1".format(tbsnm.upper())
# print(df)
rr = curs.execute(df)
for result in rr:
r... |
from Camel import config
from flask import request, make_response
import sys
import MySQLdb
def db_connect(config):
db_conf = config['database']
try:
db = MySQLdb.connect(host=db_conf['HOST'],
user=db_conf['USER'],
passwd=db_conf['PASSWORD'],
... |
"""This is a module"""
import os
from app.views import create_app
from database import database
config_name = os.getenv('APP_SETTINGS') # config_name = "development"
app = create_app(config_name)
database(app)
if __name__ == '__main__':
app.run(debug=True)
|
import itertools
class RM:
def __init__(self, r = 0, m = 1):
if r > m or r < 0 or m < 1:
raise Exception("r > m")
self.r = r
self.m = m
self.n = 2 ** m
self.generating_matrix = self.__create_generating_matrix__()
self.k = len(self.generating_matrix)
... |
"""
This type stub file was generated by pyright.
"""
from distutils import version
"""Various utilities for parsing OpenAPI operations from docstrings and validating against
the OpenAPI spec.
"""
COMPONENT_SUBSECTIONS = { 2: { "schema": "definitions","response": "responses","parameter": "parameters","security_scheme... |
from Dota2AbilitiesForAlexa import JsonParser
from Dota2AbilitiesForAlexa import Dota2SkillBuilder
myParser = JsonParser()
Dota2SkillBuilder(myParser.get_hero_abilities(), myParser.get_ability_details())
|
import pkg_resources
from datetime import datetime
from unittest.mock import sentinel
import pandas as pd
from . import process_temperature_log as module
temperature_log_path = pkg_resources.resource_filename(
"osmo_camera", "test_fixtures/temperature.csv"
)
class TestProcessTemperatureLog:
def test_parse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.