text stringlengths 8 6.05M |
|---|
# -^- coding:utf-8 -^-
# --------------------------------------------------------------
# Author: TanChao
# Date : 2015.09.23
# Intro : 用装饰器实现参数类型判断
# --------------------------------------------------------------
import inspect
import re
class ValidateException(Exception):
pass
def validParam(*varargs, **keywo... |
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import json
import datetime
import Messenger as messenger
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
def serve_file(self)... |
import logging
import fmcapi
def test__monitoredinterfaces(fmc):
logging.info("Test MonitoredInterfaces. get, put MonitoredInterfaces Objects")
obj0 = fmcapi.DeviceHAMonitoredInterfaces(fmc=fmc, ha_name="HaName")
obj1 = fmcapi.MonitoredInterfaces(fmc=fmc, ha_name="HaName")
# Interface logical name (i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def copy_status_data(apps, schema_editor):
ModerationHistory = apps.get_model("elections", "ModerationHistory")
Election = apps.get_model("elections", "Election")
ModerationStatus = apps.get_model("elections"... |
from .models import Coupon
from rest_framework_mongoengine import serializers
class CouponSerializers(serializers.DocumentSerializer):
class Meta:
model = Coupon
fields = "__all__" |
#判断一个字符串是否为对称字符串(20分)用函数形式进行操作完成
def hanshu(str):
if str ==str[::-1]:
print("是对称字符串")
else:
print("不是对称字符串")
hanshu("abgba") |
dumpling = int(input("만두 개수 입력 : "))
price = 1000
if dumpling > 0 and dumpling < 10:
price *= dumpling #대입연산자 price = price * dumpling
elif dumpling >= 10 and dumpling < 100:
price *= 0.85 * dumpling
elif dumpling >= 100:
price *= 0.75 * dumpling
else: #0보다 작아
print("잘못된 개수입니다.")
print("가격 : %... |
'''
Created on Oct 12, 2017
@author: John Nguyen
Test 7
'''
import os
import PyPDF2
input_directory = "/Users/NguyenJ.MININT-3LV3JTL/InputTestCaseInPDFFormat"
output_text_file = "/Users/NguyenJ.MININT-3LV3JTL/TestCaseFromPDFToTextOutput/OutputTextFile"
os.chdir(input_directory)
set_of_all_PDF_input_files = os.listdir(... |
from impedence_functions import paper_results
def main():
paper_results()
if __name__ == "__main__":
main()
|
import argparse
import json
import os
from glob import glob
from tempfile import TemporaryDirectory
from time import time
from functools import partial, reduce
from collections import namedtuple
import h5py
import numpy as np
import pandas as pd
from joblib import Parallel, delayed, dump, load
from sklearn import metr... |
from main.activity.desktop_v3.activity_login import *
from main.activity.desktop_v3.activity_logout import *
from main.activity.desktop_v3.activity_myshop_editor import *
from utils.lib.user_data import *
from utils.function.setup import *
import unittest
class TestMyshopInfo_Validation(unittest.TestCase):
_site ... |
# -*- coding: utf-8 -*-
# Personal Assistant Reliable Intelligent System
# By Tanguy De Bels
import speech_recognition as sr
import Utilities
r = sr.Recognizer()
def listen():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print(u'Say something!')
audio = r.listen(sourc... |
import threading
from client import Client
from ftpcommands import *
from network import *
# Get settings from config.ini, read the config file comments for a detailed description on each value
config = configparser.ConfigParser()
config.read('config.ini')
host = config['IP']['Host']
port = int(config['IP']['Port'])
... |
from django.urls import path, include
from products import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', include('orders.urls')),
path('products/<str:slug>', views.list_product, name='list_product'),
path('', include('details.urls')),
path('', include('basket.urls'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 11:51:17 2020
@author: aureoleday
"""
#from gnuradio import gr
#from gnuradio import audio,analog
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from functools import reduce
b, a = signal.butter(3, [0.1], 'lowpass'... |
# Python 3
import os
import argparse
from stat import S_ISDIR, S_ISREG
def walktree(top):
'''parcourt récursivement le dossier et renvoit
une liste avec tous les fichiers normaux'''
liste = []
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname).st_mode #... |
"""
===========================================================================
Sampling techniques using KDD Cup 1999 IDS dataset
===========================================================================
The following examples demonstrate various sampling techniques for a dataset
in which classes are extremely imbal... |
from apscheduler.schedulers.blocking import BlockingScheduler
from bras import add_bingfa, add_itv_online
import switch
import olt
sched = BlockingScheduler(daemonic=False)
def bas_add_bingfa():
add_bingfa()
def olt_tuopu():
olt.del_old_data()
olt.add_infs()
olt.add_groups()
def sw_tuopu():
s... |
#!/usr/bin/python3
# -----------------------------------------------------------------------------
# Extractor.py
# Search for all ROP gadgets in a given binary using Ropper.
# The gadgets can be searched according to a label or an opcode.
#
# Author: Eval
# GitHub: https://github.com/jcouvy
# -------------------------... |
from chai.src.corpus.Corpus import Corpus
def main():
print("Hi, Welcome to Chai Interactive")
print("You are in the 'Corpus' Interactive Mode")
corpus_name = input("Please Enter the name of your Corpus")
corpus = Corpus(corpus_name)
print("Please Enter the 'Standard Terms' for the corpus")
... |
from unittest import TestCase
import six
import os
from datetime import datetime
import json
from approx_dates.models import ApproxDate
from popolo_data.importer import Popolo, NotAValidType
from popolo_data.models import (Person, Organization, Membership,
Area, Post, Event)
from popolo... |
# -*- coding: utf-8 -*-
"""
@File:api_request.py
@Author:cdf
@Version:3.0
@Description:request请求封装
"""
import datetime
import requests
from ApiAutoCore.base.read_yml import readYaml
from ApiAutoCore.base.log import Logger
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class apiRequ... |
# -*- coding: utf-8 -*-
import math
class Solution:
def countVowelStrings(self, n: int) -> int:
return math.comb(n + 4, n)
if __name__ == "__main__":
solution = Solution()
assert 5 == solution.countVowelStrings(1)
assert 15 == solution.countVowelStrings(2)
assert 66045 == solution.coun... |
scores={}
result_f=open("results.txt")
for each_line in result_f:#系统对for自动从上到下来排序。
#for 后面可以视为临时变量 所以each_line换成a,b等均可以
(name,score)=each_line.split()
scores[score]=name #[]内为key的部分,name为key对应的值
result_f.close
print("the top scores were:")
for each_score in sorted(scores.keys(),reverse=True):
... |
import torch
from openvaccine.losses.loss import Loss
@Loss.register("MCRMSE")
class MCRMSE(Loss):
def forward(self, logits: torch.Tensor, targets: torch.Tensor, weight: torch.Tensor = None) -> torch.Tensor:
logits = logits[:, :self._num_to_calc_on]
targets = targets[:, :self._num_to_calc_on]
... |
import os
import sys
import time
STANDARD_SIZES = set(((250, 250), (300, 1050), (160, 600), (728, 90),
(300, 600), (970, 90), (234, 60), (125, 125), (300, 250),
(120, 240), (120, 90), (180, 160), (300, 100), (970, 250),
(120, 60), (550, 480), (468, 60), (336, 280), (88, 31),
(240, 4... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import NoSuchElementException
from ... |
s = raw_input().strip()
pos, char = raw_input().strip().split()
l = list(s)
l[int(pos)] = char
print ''.join(l)
|
# 数学题
class Solution:
def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
n = len(queries)
d = intLength // 2 + intLength % 2
base = 10**(d-1) if d != 1 else 1
res = []
for item in queries:
pre = base + item - 1
if pre >= 10 ** d:... |
import tensorflow as tf
x = [1,2,3]
y = [1,2,3]
w = tf.Variable(5.0)
hypothesis = x * w
cost = tf.reduce_mean(tf.square(hypothesis - y))
train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(101)... |
import os
class ManifestMaker:
def __init__(self, config):
self.config = config
self.templates = os.path.join(os.path.dirname(__file__), 'resources/')
def master_deployment(self):
return self.__template_parse("locust-master.yaml")
def worker_deployment(self):
return self... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 20:09:12 2020
@author: adeela
"""
'''
https://www.thepythoncorner.com/2017/12/the-art-of-avoiding-nested-code/
https://nedbatchelder.com/text/iter.html
https://nedbatchelder.com/blog/201608/breaking_out_of_two_loops.html
https://book.pythontips... |
def insertion_sort(sortable):
for i in range(len(sortable)):
while i>0 and sortable[i] < sortable[i-1]:
temp = sortable[i-1]
sortable[i-1] = sortable[i]
sortable[i] = temp
i -= 1
return sortable
def insertion_sort_recursive(sortable, n=-1):
if n == -1... |
import numpy as np
import cv2
import pathlib
import imutils
address = pathlib.PureWindowsPath(r'C:\Users\Muhammad Reza\KTPDetect\Foto ktp\ktp0.jpg')
image = cv2.imread(address.as_posix())
image = imutils.resize(image,width=650)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL)
low_blue = np.array([80,30,155],np.uint1... |
"""
Antelope Interface Definitions
The abstract classes in this sub-package define what information is made available via a stateless query to an Antelope
resource of some kind. The interfaces must be instantiated in order to be used. In the core package
"""
from .interfaces.abstract_query import PrivateArchive, En... |
# encoding: utf-8
import matplotlib as mpl
import matplotlib.pyplot as plt
import os
from natsort import natsorted, ns
import numpy
import re
import xlsxwriter
def start():
directory = 'result_exe1/'
arq = os.listdir(directory)
arquivosDiretorio = natsorted(arq, alg=ns.IGNORECASE) #ordena arquivos para plot
size ... |
import smtplib
import requests
from BeautifulSoup import BeautifulSoup
import time
import random
def main():
nogood=1
x=0
while nogood==1:
bitly = "http://goo.gl/WNOecx"
time.sleep(random.randint(12, 15))
r = requests.get(bitly)
soup=BeautifulSoup(r.text)
y = soup.find(id='shelfDiv').find(id="border")
n... |
"""
created by Nasim Zolaktaf, 2019
This file estimates the reaction rate constant of a reactions and returns the squared error between the predicted log reaction rate cosntant and experimental log reaction rate constant
"""
from __future__ import division
import warnings
import gc
import numpy as np
import ConfigParse... |
print "A circle/sphere calculator for easy conversion:"
radius = raw_input("radius of a circle(cm) = ")
x = radius
circumference = float(x)*2*3.14159
area = float(x)*float(x)*3.14159
volume = (float(x)*float(x)*float(x)*4*3.14159)/3
print 'circumference of the circle =',circumference,'cm'
print 'area of the circle =',... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You pressed something!\n"
]
}
],
"source": [
"##simple GUI\n",
"\"\"\"\n",
"Very si... |
from os import linesep
from asyncio.subprocess import Process
from typing import Iterable, Tuple, Union
from logging import error, log, DEBUG
from tqdm import tqdm
import config
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def... |
# encoding: utf-8
from src.config import FaqConfig, TfidfTransformerConfig
import json
import pickle
from sklearn.exceptions import NotFittedError
from sklearn.feature_extraction.text import TfidfVectorizer
from src.utils import Cutter
from src.utils import singleton
import logging.config
import logging
import os
impo... |
class Node(object):
def __init__(self, data, pnext=None):
self.data = data
self._next = pnext
class ChainTable(object):
def __init__(self):
self.head = None
self.length = 0
def isEmpty(self):
return (self.length == 0)
def append(self, dataOrNode):
item ... |
from tabulate import tabulate
import GraphQL
import os
import decimal
import yaml
c = yaml.load(open('config.yml', encoding='utf8'), Loader=yaml.SafeLoader)
################################################################
# Define the payout calculation here
############################################################... |
a = 2
b=3
c=a+b
print (c)
a = 2
b=3
print (a+b)
print ('Привет мир!')
c=a-b
print (c)
c=a*b
print (c)
c=a**b
print (c)
c=a/b
print (c)
a = 2.1
b=3.3
c=a+b
print (c)
a = 3.1
b=0.1
c=a-b
print (c)
a = 3.1
b=0.1
c=a<b
print (c)
a = 3.1
b=0.1
c=a>b
print (c)
a = 3.1
b=0.1
c=a!=b
print (c)
a = 3.1
b=0.1
c=a==b
p... |
import requests
import re
data = requests.get(input())
result = []
for link in re.findall(r"<a(.*?)href(.*?)=(.*?)(\"|')(((.*?):\/\/)|(\.\.)|)(.*?)(\/|:|\"|')(.*)", data.text):
domain = link[8]
if domain not in result:
result.append(domain)
result.sort()
for domain in result:
print(domain)
|
def maxArea(height):
n=len(height)
maxindex=height.index(max(height))
#找出列表中第一个最大元素对应的下标
maxarea=0
i=0
while i<n-1 and i<maxindex+1:
j=i+1
while j<n:
maxarea=max(maxarea,(j-i)*min(height[j],height[i]))
j+=1
while height[i]>=height[i+1] and i<maxindex:... |
import click
import numpy as np
import logging
import pickle
from sklearn.preprocessing import RobustScaler
from sklearn.utils import check_random_state
from recnn.recnn import event_baseline_predict
logging.basicConfig(level=logging.INFO,
format="[%(asctime)s %(levelname)s] %(message)s")
@cli... |
new_price = [1, 2, 3]
map(str, new_price)
|
"""Created February 7, 2019 by Mimi Sun
Rose8bot.py - main file
cmd - drag file and press enter
terminal - python3 rose8bot.py
install discord.py rewrite - python3 -m pip install -U discord.py[voice]
pip install -U git+https://github.com/Rapptz/discord.py@rewrite#egg=discord.py[voice]
pip install psycopg2-binary
pip ... |
#!/usr/bin/env python
import rospy
from hektar.msg import wheelVelocity
from std_msgs.msg import Float64, Int8
from dynamic_reconfigure.server import Server
from hektar.cfg import WheelControlConfig
UPPER_LIMIT = 127
LOWER_LIMIT = -127
class Callback():
def __init__(self):
self.speed = 0
self.variation_f... |
yz=int(input())
mg=0
temp=yz
while(temp>0):
dig=temp%10
mg=mg+dig ** 3
temp=temp//10
if(mg==yz):
print("yes")
else:
print("no")
|
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import warnings
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Lambda
from tensorflow.keras.layers import Activation
fr... |
import collections
import logging
from concurrent.futures import ProcessPoolExecutor
from functools import partial
import nltk
import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.util import ngrams
from tqdm import tqdm
from nlp.chunker import Chunker
from nlp.pattern_grammer import PatternGrammar
f... |
import sys
import uuid
if sys.version_info[0] == 2: # noqa
from io import BytesIO as StringIO
else:
from io import StringIO
import warnings
from base64 import b64encode
import numpy as np
from matplotlib.pyplot import cm
from matplotlib.colors import Colormap
from astropy import units as u
from traitlets i... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.datasets import load_sample_image
from sklearn.datasets.samples_generator import make_blobs
sns.set()
'''
K-Means
'''
# 设置随机样例点
X, y = make_blobs(n_sam... |
import redis
import time
import threading
class Listener(threading.Thread):
def __init__(self, r, p):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.psubscribe(p)
def run(self):
for m in self.pubsub.listen():
if ... |
import sc2, sys
from __init__ import run_ladder_game
from sc2 import Race, Difficulty
from sc2.player import Bot, Computer, Human
import random
# Load bot
from Overmind import Overmind
bot = Bot(Race.Zerg, Overmind())
# Start game
if __name__ == '__main__':
if "--LadderServer" in sys.argv:
# Ladder game s... |
from SupportClasses.DatasetEmbedder import DatasetEmbedder
from SupportClasses.TrainTestSplitter import TrainTestSplitter
class PreProcessor:
# def __init__(self, classifyToParent=False, classifyToChild=False):
# if(classifyToParent or classifyToChild):
# self.datasetEmbedder = self.__createDa... |
"""add article
Revision ID: 36c61afe3519
Revises: 519e5b696ae4
Create Date: 2015-11-24 16:50:25.083234
"""
# revision identifiers, used by Alembic.
revision = '36c61afe3519'
down_revision = '519e5b696ae4'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... |
from django.contrib import admin
from django.db.models import Q
from django.utils.translation import gettext as _
from .models.post import Post
class InputFilter(admin.SimpleListFilter):
template = 'admin/input_filter.html'
def lookups(self, request, model_admin):
# Dummy, required to show the filte... |
import tempfile
import os
import subprocess
from django.conf import settings
from django.db import connection
class DbUtil(object):
"""
a set of utility method to access db
"""
def __init__(self):
raise Exception("Utility class can't be instantiated.")
_database = settings.DATABASES[... |
assists = crosses = 3
chancesCreated = goals = 4
shotsOnTarget = 5
successfulDribbles = 10
points = 89
# points = goals * 9 + assists * 6 + chancesCreated * 3 + \
# shotsOnTarget * 2 + crosses + successfulDribbles
|
#!/usr/bin/env python
import unittest
from asyncdnspy.dns_message_decoder import DNSMessageDecoder
from asyncdnspy.error.asyncdnspy_error import AsyncDNSPyError
from asyncdnspy.udp_client import UDPClient
from asyncdnspy.tcp_client import TCPClient
from asyncdnspy.dns_raw_message import DNSRawMessage
from asyncdnspy.... |
#coding : utf-8
#Ewan GRIGNOUX LEVERT
#Avril 2020
import sys
import csv
from tkinter import *
from PIL import Image, ImageTk # pour les images
from tkinter import ttk
from tkinter.messagebox import*
from datetime import *
from Champs import Champs
from Inventaire import Inventaire
from Magasin import Magasin
import Cha... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# User Datagram Protocol
# Analyser for UDP header
from .transport import Transport
from ..utilities import Info
class UDP(Transport):
"""This class implements Transmission Control Protocol.
Properties:
* name -- str, name of corresponding procotol
... |
#CalpiV2.py
from time import perf_counter
from random import random
DARTS=1000*1000
#DARTS=1000*1000*10
hits=0.0
start=perf_counter()
#for i in range(DARTS):
for i in range(1,1+DARTS):
x,y=random(),random()
dist=pow(x**2+y**2,0.5)#求点(x,y)到原点的距离
if dist<=1.0:
hits+=1
pi=4*(hits/DARTS)
print("圆周率为:{}"... |
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import current_thread
import time
import random
import os
# 这就是进程池和线程池的两个类
# threading 模块 没有提供池
# multiprocessing 模块是仿照 threading 写的,Pool
# py 3.x 推出了 concurrent.futures 模块,线程池和进程池都能够用相似的方式启动/使用
# pp = ProcessPoolExecutor(5) # 创建5个进程对... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* UMSE Antivirus Agent Example
* Author: David Alvarez Perez <dalvarezperez87[at]gmail[dot]com>
* Module: UMSE Decryption Tools
* Description: This module allows to decrypt UMSE file entries.
*
* Copyright (c) 2019-2020. The UMSE Authors. All Rights Reser... |
def rgb_range(n):
return min(255, max(n, 0))
def rgb(r, g, b):
return ('{:02X}' * 3).format(rgb_range(r), rgb_range(g), rgb_range(b))
|
from unittest.case import TestCase
from pythonbrasil.lista_2_estrutura_de_decisao.ex_07_mostrar_maior_e_menor_de_tres_numeros \
import obter_maior_numero, obter_menor_numero
class ObterMaiorNumeroTests(TestCase):
def test_todos_numeros_iguais(self):
self.assertEqual(1, obter_maior_numero(1, 1, 1))
... |
""" template
This code is written for COMP9021.
Author: Jack Jiang (z5129432)
Version: v01
Date: 2017
"""
import os
import sys
def template_function():
""" function
Arguements:
Returns:
"""
return
# Test Codes
if __name__ == "__main__":
pass
|
from PyQt5 import QtWidgets, QtCore, QtGui
class DrawWords(QtWidgets.QWidget):
def __init__(self, word_1, word_2, word_3):
super(DrawWords, self).__init__()
self.word_1 = word_1
self.word_2 = word_2
self.word_3 = word_3
self.move(150,50)
self.setFixedSize(900,500)
... |
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['MutateEventTestCase::test_create_event_with_calendar_authorized 1'] = {
'data': {
'createEvent': None
},
'errors': [
... |
# DET
from common import *
import tune
mbbOut('DET:GAIN', DESC = 'Detector gain', *dBrange(7, -12) + ['-120dB'])
boolOut('DET:MODE', 'All Bunches', 'Single Bunch',
FLNK = tune.setting_changed, DESC = 'Detector mode')
mbbOut('DET:INPUT', 'ADC', 'FIR',
DESC = 'Detector input selection')
boolOut('DET:AUTOGAIN'... |
class Solution:
# @param A : list of list of integers
# @return the same list modified
def setZeroes(self, A):
n = len(A)
n2 = len(A[0])
for i in range(n):
for j in range(n2):
if(A[i][j]==0):
for col in range(n2):
... |
"""Example_1"""
# try:
# number = int(input("enter a number: "))
# print(number)
# # most general type of exceptions
# except Exception as e:
# print("please enter a number!", e)
"""Example_2"""
# try:
# number = int(input("enter a number: "))
# res = 10 / number
# print(number)
# # most ge... |
def solution(numbers):
numbers.sort()
if numbers[0] < 0 and numbers[1] < 0:
if numbers[0] * numbers[1] >= numbers[-1] * numbers[-2]:
return numbers[0] * numbers[1]
else:
return numbers[-1] * numbers[-2]
else:
return numbers[-1] * numbers[-2] |
from unittest.mock import Mock
from game import Game
import math
from model.skills.whirlwind import Whirlwind
from model.systems.system import ComponentSystem
import pytest
def _mock_factory(*args, fighter=None, **kwargs):
fighter = fighter or Mock()
m = Mock(*args, **kwargs)
Game.instance.fighter_system... |
'''
Created on Mar 12, 2019
@author: akash18.TRN
'''
dbname="Hello"
tname="employee2"
author="Teja"
filename="d2.txt"
primarykey_col=-1
thisdict={
};
batch_size=20000
deli=','
col_name=['col1','col2','col3','col4','col5','col6','col7','col8']
datatype_dict={
1: "varchar(30)",
2: "varcha... |
# Libraries
import gym
import numpy as np
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import copy
import sys
# Install TF 2 and enable GPU
# if "2." not in tf.__version__ or not tf.test.is_gpu_available():
# !pip uninstall tensorflow
# !pip install tensorflow-gpu
# print(f"Tensorflow ve... |
"""
From causality-treated data; construct a graph of causality
Author : Diviyan Kalainathan
Date : 28/06/2016
"""
import csv
import cPickle as pkl
import numpy
import scipy.stats as stats
import sys
inputfolder = 'output/obj8/pca_var/cluster_5/'
causal_results = inputfolder + 'results_lp_CSP+Public_thres0.12.csv' #... |
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
import sys
from os import path
from io import BytesIO
from difflib import unified_diff
import json
from djang... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 21:59:46 2020
@author: thomas
"""
import numpy as np
import pandas as pd
import os, sys
import time as t
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.ticker import ... |
# from sololearn
# class methods, static methods, properties
# classmethods
# class methods are called by the class and then passed to cls
# Methods of objects we've looked at so far are called by an instance of a class, which is then passed to the self parameter of the method.
# Class methods are different - they are... |
#encoding: utf-8
#Patron 1, la n especifica la altura del triángulo. Debe ser mayor o igual a 7
import sys
if len(sys.argv) != 2 :
print 'Args: número'
sys.exit(2)
n = int(sys.argv[1])
if n < 7 :
print 'El primer argumento debe ser mayor o igual a 7'
sys.exit(1)
i = 0
j = n
c = 0
while i < n :
while c >= 0:
p... |
def find_default_player():
pass
__all__ = [
"find_default_player"
]
|
print ('Research on language popularity.')
#LANGUAGE SHARE OF WEBSITES IN THE TOP 10 MIL. NATIVE SPEAKERS, MIL. TOTAL SPEAKERS OF LANGUAGE, MIL.
#English 0.539 378.2 1121
#Russian 0.061 153.9 264.3
#German 0.06 76 132
#Spanish 0.049 442.3 512.9
#French 0.04 76.7 284.9
#Japanese 0.034 128.2 128.3
#Portuguese 0.029 222.7... |
"""
Generates a sequence of trials that satisfy
a mixed-block/event related design (Visscher et al 2003, NeuroImage).
Currently: no M-sequence. I'll look into this as the time for scanning
gets closer. For now, it's pseudo-random
"""
import random
# How long to wait before the first block of trials (seconds)
INITIAL_... |
import jpype
from jpype import *
import subprocess
class Farasa:
def __init__(self,path_to_jars):
jvmPath = jpype.getDefaultJVMPath()
jpype.startJVM(jvmPath,
"-Djava.class.path="+path_to_jars)
def segment(self,text):
Far = JPackage("com").qcri.farasa.segmenter.... |
#!/usr/bin/env python2
import sys
import struct
import time
# You can use this method to exit on failure conditions.
def bork(msg):
sys.exit(msg)
# Some constants. You shouldn't need to change these.
MAGIC = 0x8BADF00D
VERSION = 1
if len(sys.argv) < 2:
sys.exit("Usage: python stub.py input_file.fpff")
# ... |
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, BatchNormalization
a = np.array(range(1,101))
batch_size = 1
size = 5
def split_5(seq, size):
aaa = []
for i in range(len(a)-size+1):
subset = a[i:(i+size)]
aaa.append(subset)
... |
import filecmp
import os
import tempfile
import unittest
import sbol3
import tyto
import labop
import labop_time as labopt
import uml
# from labop_check.labop_check import check_doc, get_minimum_duration
class TestTime(unittest.TestCase):
def test_single_behavior(self):
################################... |
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
sys.exit()
# let's open a connection to google with socket
PORT = 80
try:
# first we need t... |
import boto3
import sys
import time
import json
import os
import sagemaker
from sagemaker.processing import ProcessingJob
from sagemaker.model_monitor import DefaultModelMonitor, BaseliningJob, CronExpressionGenerator
# Load arguments
bucket_name = sys.argv[1]
prefix = sys.argv[2]
execution_role = sys.argv[3]
process... |
#Bitácora de prácticas
#Edoardo Martín Ricalde Ché
#=============================
#Optimización Local
#=============================
#Ejercicio 1
#Original
Edo = 3
Victor = 5
Sobra = 2
total = a + b
diferencia = a - b
print(total)
#Optimizado
#Las variables y operaciones que no se necesitan o utilizan se eliminan
Edo... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.python import target_types_rules
from pants.backend.python.lint.flake8 import skip_field
... |
# Generated by Django 2.1.7 on 2019-02-27 11:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20190227_1102'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='birth_date',
... |
from wsgiref.simple_server import make_server # the wsgiref webserver (default with Python)
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.response import FileResponse
from pyramid.renderers import render_to_response
''' Basic Routes '''
def home_route(req):
re... |
print "Hello World"
x = 5
myInt = 7
myFloat = 7.0
myFloat2 = float(7)
hello = "hello"
world = "world"
lotsOfHellos = hello * 10
print "Lots of hellos using the * 10 operator gives " + lotsOfHellos
helloworld = hello + " xxx " + world
print helloworld
print "my int is %d" % myInt
#print "my int is also" + myInt # this d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.