text stringlengths 38 1.54M |
|---|
# coding=utf-8
import pyglet
import BasePiece
class Piece(BasePiece.BasePiece):
def __init__(self, name, x, y):
self.__name = name
self.current_position = [x, y]
self.__target_position = []
self.isKilled = False
self.__position_history = []
self.Prepar... |
import requests as req
import json
url='http://localhost:9515/session'
data=json.dumps({
"desiredCapabilities": {
"caps": {
"nativeEvents": "false",
"browserName": "chrome",
"version": "",
"platform": "ANY"
}
}
})
r=req.post(url,data)
# req.dele... |
# 讀取檔案,把內容存成清單
def read_file(filename):
data = []
with open(filename, 'r') as f:
for line in f:
data.append(line)
return data
# 印出長度小於某數的留言數量
def word_count_filter(data, amount):
new = []
for d in data:
if len(d) < amount:
new.append(d)
print(f'一共有{len(new)}筆留言長度小於{amount}')
# 印出有某個字... |
import pymysql
import aws_credentials as rds
import string
import random
import datetime
def id_generator(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def ticket_generator(size, chars=string.ascii_letters + string.digits):
return ''.join(ra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2018/10/17
@Author : AnNing
"""
import datetime
from dateutil.relativedelta import relativedelta
import numpy as np
def is_day_timestamp_and_lon(timestamp, lon):
"""
根据距离 1970-01-01 年的时间戳和经度计算是否为白天
:param timestamp: 距离 1970-01-01 年的时间戳
:par... |
import sys
import time
import threading
from itertools import count
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
import numpy as np
import time
import datetime as dt
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# length of window
n = 50
# Create figure... |
# Generated by Django 2.2.12 on 2020-09-03 19:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('homepage', '0011_session_table'),
]
operations = [
migrations.CreateModel(
name='current_session',
fields=[
... |
import hashlib
import shlex
import subprocess
from os import system
def Mash(input):
m = hashlib.md5()
m.update(input)
print(m.hexdigest())
def main():
curFiles = 2
subprocess.run(["./fastcoll", "-p", "prefix", "-o", "col0", "col1"])
while(curFiles<=32):
subprocess.run(["./fastcoll"... |
import numpy as np
import time
import scipy.spatial as sp
import scipy
import matplotlib.path as mpltpath
import matplotlib.pyplot as plt
from scipy import interpolate
rtimewprMFs=[]
rtimesum=[]
print("lsspy.optMF3D: This optimized library computes the 3-D Minkowski Functional based on a Voronoi Tessellation.\n")
C_... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 13:07:04 2019
@author: Sunny
"""
'''
import socket
#hostname = '127.0.0.1'
#port = 7777
#addr = (hostname,port)
#clientsock = socket.socket() ## 建立一個socket
#clientsock.connect(addr) # 建立連線
def main():
while True:
clientsock=socket.socket(sock... |
from django.conf import settings
from rest_framework import serializers, validators
from locations.serializers import LocationSerializer
from .models import PaymentMethod, Truck, TruckImage
class TruckImageSerializer(serializers.ModelSerializer):
class Meta:
model = TruckImage
fields = ("id", "i... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
__author__ = 'zachary'
"""
File Name: demo.py
Created Time: 2020-04-11 11:42:57
Last Modified:
"""
import re
from selenium import webdriver
from parsel import Selector
url = 'http://www.porters.vip/captcha/clicks.html'
browser = webdriver.Firefox(executable_path='../gec... |
import socket
import datetime
import sys
import os
HOSTNAME = "127.0.0.1"
PORT = 8000
PROTOCOL = 0
TIMEOUT = 15
MAX_SIZE = 1024
QUEUE_SIZE = 5
FILE_A = "GET /a.jpg HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\n\n"
FILE_B = "GET /b.mp3 HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\n\n"
FI... |
"""
@version 0
@author: Jetse
Quality control:
* Checked whether each column contains at least 8 columns
* Checked whether file contains at least a single SNP
"""
from qualityControl import QualityControlExceptions
class VcfFile:
def __init__(self, fileName, bcf=False):
self.fileName = fileName
... |
from DG_MMSFunctions import *
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
import sys
functions = []
for arg in sys.argv[1:-1]:
functions.append(arg)
n_rows = int(sys.argv[-1])
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'
plt.subplots_adjus... |
def facebook():
print("Hallo, wat is jou naam?")
naam = input()
print("Welkom", naam, "!")
print("Mogen wij jou wat vragen? Ja/Nee")
vraag = input().lower()
if vraag == "nee":
exit()
if vraag == "ja":
print("Top! Laten we beginnen.")
print(naam, "hoe oud ben jij?")
... |
known_users=['Alice', 'Bob', 'Claire', 'Dam','Emma']
while True:
print "Hi! My Name is Travis"
name=raw_input("What is your name?:").strip().capitalize()
if name in known_users:
print 'Hello {}!'.format(name)
else:
print 'i dont think i have met you'
|
import glob
import os
from PIL import Image
outdir = 'cropped'
scale = 1.3
BBOX = [600, 176, 1417, 795]
files = glob.glob('./*.png')
for file in files:
print('process %s' % file)
inimage = Image.open(file).crop(BBOX)
width, height = inimage.size
inimage.resize((int(width/scale), int(height/scale)), ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#上面的注释是用来支持中文,没有就会出错
# 注意 本文件是根据 index.py 复制修改的
# 基本上复用了 index.py 的逻辑,下面是修改的地方
# 1)原来的递归解构没了
# 2)没有数据库相关的操作(所以没有网页版本)
# 3) 命令行参数是需要查询的股票
from __future__ import division
#这个需要先 pip install requests
import requests
import json
import math
import time
import argparse #用来... |
class Solution(object):
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
def bits(n, base, bit_arr):
if n != 0 and bit_arr[n] == 0:
while base > n:
base >>= 1
bit_arr[n] = ... |
nome = str(input())
fixo = float(input())
venda = float(input())
print("TOTAL = R$ %.2f" % round((fixo+(0.15*venda)),4))
|
magician_names = ['David Blaine', 'Cris Angel', 'Houdini', 'Harry Potter', 'Wutan']
def great_magicians(magicians):
'''Function that modifies the string in a list'''
magicians[:] = ['The Great ' + magician for magician in magicians]
return magicians
def show_magicians(magicians):
'''Function t... |
#!/usr/bin/python
import zlib
msg = """
Society in every state is a blessing, but government even in its best state is but a necessary evil
in its worst state an intolerable one; for when we suffer, or are exposed to the same miseries by a
government, which we might expect in a country without ... |
def is_odd_num(n):
return n & 1
# 13 = 1101 so bits are 3,2,1,0 first bit starts from zero
def is_ith_bit_set(n, i):
return (n >> i) & 1 or n & (1 << i)
def set_ith_bit(n, i):
return n | (1 << i)
def unset_ith_bit(n, i):
return n ^ (1 << i)
def check_number_is_power_of_2(n):
return (n &
... |
#!/bin/env python
# Accounting file parser, to answer questions such as:
# - What is the breakdown of usage between faculties?
# - What is the breakdown of usage between users?
# - What is the breakdown of usage between users within a faculty?
# Try and be python2 compatible
from __future__ import print_function
imp... |
from aiogram import Bot
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from bot import TOKEN
bot = Bot(token=TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
dp.middleware.s... |
"""
#Author: Sean Sill
#email: sms3h2@gmail.com
#Date: 2/2/2013
#Notes:
Created this file to act as a remote control from my pc to my computer!
"""
try:
import serial
print 'Serial Imported'
except:
import testserial as serial
print 'Pyserial not found, using a dummy serial port'
pass
... |
import numpy as np
import pandas as pd
import gzip
import json
import preprocessing as pre
#Read json.gz (gzip)
#Chunk reading needed
def parse(path, lower, limit):
g = gzip.open(path, 'rb')
i=0
for l in g:
i = i+1
if i < lower:
continue
if i > limit:
break
yield json.loads(l)
de... |
#!/usr/bin/env python3
from string import Template
user_data = '''Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_log_error, mean_squared_error, make_scorer, r2_score
from sklearn.utils import resample
from sklearn.prepr... |
import setuptools
with open("README.rst", "r") as readMe:
long_description = readMe.read()
setuptools.setup(
name="billionfong",
version="1.2.6",
author="Billy Fong",
author_email="billionfong@billionfong.com",
description="Welcome to billionfong's playground",
long_description=long_descri... |
import pytest
import sys
import random
import string
import json
from app import create_app
def random_string_generator():
allowed_chars = string.ascii_letters + string.punctuation
size = 12
return ''.join(random.choice(allowed_chars) for x in range(size))
username = random_string_generator()
password = ... |
"""
(C) Casey Greene.
This python script generates a number of different files that serve as permuted
standards for NetWAS analysis from a GWAS. These files differ only in their
gene ordering to evaluate the effects of multiple cross validation intervals
on the results.
"""
import os
import pandas as pd
import numpy ... |
# -*- coding: utf-8 -*-
# Description:
# Created: liujiaye 2020/08/11
from app.utils.base_dao import BaseDao
class StockDao(BaseDao):
def select_stock_day_detail(self, day):
sql = """SELECT
id,
ORITEMNUM order_number,
NOTICENUM shipping,
WAINTFORDELNUMBER w... |
#! usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg
def calc_granularity(hist2d_output):
'''Calulates the granularity of a plt.hist2d object.
The granularity approaches 0 when the histogram approaches a single bin, and 1 when the
geometric area of the diagon... |
# coding:utf-8
'''
Created on 2013-6-11
@author: wolf_m
'''
class ViperClientGroup():
inst = None
def __init__(self):
self.clientMap = {}
def addClient(self, client):
if client.id in self.clientMap:
return None
else:
self.clientMap[client.id] = client
... |
in_queue = Queue()
def consumer():
print('Consumer waiting')
work = in_queue.get() # 두 번째로 완료함
print('Consumer working')
# 작업을 수행함
# ...
print('Consumer done')
in_queue.task_done() # 세 번째로 완료함
Thread(target=consumer).start()
in_queue.put(object()) # 첫 번째로 완료함
print('Pr... |
#Multiplies a factor times all of the elements in a list
number_list = [2, 4, -22, 10, -16, 20, 55]
my_number = 10
multiplied_list = []
for num in number_list:
new_number = num * my_number
multiplied_list.append(new_number)
print(multiplied_list) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 21:55:45 2019
@author: yoelr
"""
import numpy as np
from .array import array
__all__ = ('tuple_array',)
ndarray = np.ndarray
asarray = np.asarray
def invalid_method(self, *args, **kwargs):
raise TypeError(f"'{type(self).__name__}' objects are immutable.")
class... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 10:05:56 2018
@author: Jun Wang
"""
import xml.etree.cElementTree as ET
# import pprint
import re
import codecs
import json
from audit import update_name
lower = re.compile(r'^([a-z]|_)*$')
lower_colon = re.compile(r'^([a-z]|_)*:([a-z]|_)*$')
problemchars = re.compi... |
from django.urls import path
from django.urls import path,include
from . import views
urlpatterns = [
path('product-grid/',views.products_grid, name='products_grid'),
] |
#!/usr/bin/env python3
import asyncio
import json
import logging
import random
import string
import threading
import discord
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class TimerClass(threading.Thread):
def __init__(self, bot):
threading.Thread.__init__(self)
se... |
from django.db import models
from taggit.managers import TaggableManager
from nomadgram.users import models as user_models
#if we import many models we make nickname using 'as~'
# Create your models here.
class TimeStampedModel(models.Model):
created_at = models.DateField(auto_now_add=True)
updated_at = model... |
from lib.chatbot.reaction.reactionBase import ReactionBase
class ReactionDefault(ReactionBase):
def __init__(self, message, me):
super().__init__(message, me)
def response(self):
text = "Uff, I'm speechless..."
self._send_message(text)
def action(self):
pass
|
import mysql.connector
try:
host_name = "localhost"
user_name = "root"
pwd = "9866850403"
db_name = ""
con = mysql.connector.connect(host=host_name, user=user_name, password=pwd, database=db_name)
cur = con.cursor()
sql = "show databases"
cur.execute(sql)
existing_dbs = cur.fetcha... |
#/bin/python
from pyb import *
from time import sleep
x = 0
brightness = 100
led1 = LED(1)
led2 = LED(2)
brightness = 0
while True:
for count in range(50):
led1.intensity(brightness)
brightness += 1
sleep(0.05)
for count in range(50):
led1.intensity(brightness)
brightness += -1
sleep(0.... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.listar_publicaciones),
url(r'^post/(?P<pk>[0-9]+)/$', views.detalle_publicacion),
url(r'^post/new/$', views.nueva_publicacion, name='nueva_publicacion'),
url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_editar, na... |
import discord
from discord.ext import commands
import json
import os
from classes import Guild
import database as db
from env import TOKEN
from vars import bot, extensions, get_prefix
@bot.event
async def on_ready():
"""Initial function to run when the bot is ready to function"""
await bot.change_presence(
... |
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
PATH = "https://raw.githubusercontent.com/hyeonukbhin/homework3_NA/master/assets/data/"
FILENAME = "647_Global_Temperature_Data_File.txt"
TITLE = "Global Temperature"
X_LABEL = "YEAR"
Y_LABEL = "Temperature Anomaly (C)"
SAVE_FIL... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 6 15:27:04 2016
@author: alex
"""
from AlexRobotics.dynamic import Prototypes as Proto
from AlexRobotics.control import RolloutComputedTorque as RollCTC
import numpy as np
R_ctl = Proto.SingleRevoluteDSDM()
R = Proto.SingleRevoluteDSDM()
# Loa... |
import os
import random
import string
import wave
import logging
from handlers.base import BaseHandler
from recognizer import speech
logger = logging.getLogger(__name__)
def get_path(filename):
from settings import UPLOAD_ROOT
return os.path.join(UPLOAD_ROOT, filename)
class UploadHandler(BaseHandler):
... |
import os
from setuptools import setup, find_packages
version = '0.0.1'
README = os.path.join(os.path.dirname(__file__), 'README.rst')
long_description = open(README).read() + '\n\n'
if __name__ == '__main__':
setup(
name='todo',
version=version,
description=(''),
long_description=... |
# +------------------------------------------------+
# | Atack: Bof Win Function |
# +------------------------------------------------+
#
# For more info checkout: https://github.com/guyinatuxedo/nightmare/tree/master/modules/05-bof_callfunction
from pwn import *
import sf
target = process("./... |
"""
prometheus.py
A simple python script that pulls data from Prometheus's API, and
stores it in a Deephaven table.
This is expected to be run within Deephaven's application mode https://deephaven.io/core/docs/how-to-guides/app-mode/.
After launching, there will be 2 tables within the "Panels" section of the Deephav... |
from rest_framework import viewsets
from rest_framework.response import Response
from ..serializers import TrailSectionsSerializer
from trail_mapper.models import TrailSections, Trail
class TrailSectionsViewSet(viewsets.ModelViewSet):
"""This is the m2m join of trails and trail_sections."""
queryset = TrailS... |
from pathlib import Path
import os
import argparse
import pandas as pd
DST_DIR = os.environ.get('FREESURFER_DST')
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--dir')
return parser.parse_args()
def main():
args = parse()
P = Path(__file__).resolve().parent / args.d... |
import django_filters
from django_filters import CharFilter
from cashPayment.models import cashPayment
class CashFilter(django_filters.FilterSet):
Month = CharFilter(field_name='Month', lookup_expr='icontains')
class Meta:
model = cashPayment
fields = ['Year', 'Month'] |
import os
import hvac
from hvac.exceptions import InvalidPath
from requests.exceptions import ConnectionError
from django.conf import settings
from .models import Vault
class VaultClient():
def __init__(self, mount_point=os.environ.get('VAULT_MOUNT_POINT', 'pwdmng/')):
path_prefix = self._path_prefix ... |
print('yes')
print('whats')
print('eat gulabjamun')
print('switzerland trip to parents in 2023')
work = input()
if work==1:
print('earn now') |
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0",
"Upgrade-Insecure-Requests":"1",
}
allowed_domains = ["sogou.com", "tmal... |
"""Implementing Report screen page objects"""
from TestFramework.Libraries.Pages.base_page import BasePage
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
class ReportPage(BasePage):
"""
Contains Report UI page locators
Switch to report functio... |
import subprocess
import shlex
import os
import signal
from helper import path_dict, path_number_of_files, pdf_stats, pdf_date_format_to_datetime, dir_size, url_status
import json
from functools import wraps
from urllib.parse import urlparse
from flask import flash, redirect, url_for, Response, send_file, Markup, loggi... |
# while loop if the condition is true it will continuously executing the loop.
# it will continuously execute the loop until the condition becomes false.
s = 4
while s > 1:
print(s)
s = s - 1 # it is required to avoid the infinite loop
print("first while loop execution is done")
# if you don't want to print ... |
#!/usr/bin/env python
from anuga.culvert_flows.culvert_polygons import *
import unittest
import os.path
from anuga.geometry.polygon import inside_polygon, polygon_area
class Test_poly(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_1(self):
... |
#!/usr/bin/python3
"""Translate messages.json using Google Translate.
The `trans` tool can be found here:
https://www.soimort.org/translate-shell/
or on Debian systems:
$ sudo apt-get install translate-shell
"""
import collections
import json
import os
import shutil
import subprocess
import sys
LANG_MAP = {
... |
# ********************************************************************
# Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one,
# from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown... |
"""
abstraction of a lane line
"""
class LaneLine(object):
def __init__(self):
self.fit = None
self.x = None
self.yvals = None
self.curverad = None
def reset(self):
# if self.x is not None and len(self.x) > 0:
# del self.x[:]
# if self.yvals is not... |
import numpy as np
class Transformer:
def transform_X(self, X):
return X
def transform_y(self, y):
return y
def format_X(self, X):
num_samples = len(X)
num_features = len(X[0])
return np.reshape(X, [num_samples, num_features])
def format_y(self, y):
... |
# -*- coding: utf-8 -*-
"""
@author: Chris Lucas
"""
import os
from flask import json
from app import app, api
OUTPUT = 'static/swagger.json'
mode = os.environ['SESLR_APP_MODE']
mode = '/' + mode if mode != 'prod' else ''
base_path = '{}/api/'.format(mode)
os.makedirs(os.path.dirname(OUTPUT), exist_ok=True)
with ... |
#!/usr/bin/env python
#
# Generated Fri May 27 17:23:42 2011 by parse_xsd.py version 0.4.
#
import saml2
from saml2 import SamlBase
from saml2.schema import wsdl
NAMESPACE = "http://schemas.xmlsoap.org/wsdl/soap/"
class EncodingStyle_(SamlBase):
"""The http://schemas.xmlsoap.org/wsdl/soap/:encodingStyle eleme... |
import numpy as np
def _unit_vector(data, axis=None, out=None):
""" Return ndarray normalized by length, i.e. Euclidean norm, along axis.
>>> v0 = np.random.random(3)
>>> v1 = _unit_vector(v0)
>>> np.allclose(v1, v0 / np.linalg.norm(v0))
True
>>> v0 = np.random.rand(5, 4, 3)
>>> v1 = _uni... |
MAX_64_INT = 9223372036854775807
MAX_32_INT = 2**32-1
GROUND_FILE_NAME = "ground_truth.txt"
UNIVERSE_FILE_NAME = "universe.txt"
WHITES_FILE_NAME = "whites_example.txt"
|
# Generated by Django 3.1.1 on 2020-09-08 20:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('soldiers_viewer', '0006_auto_20200907_2012'),
]
operations = [
migrations.AddField(
model_name='soldier',
name='addr... |
import discord
import random
import json
from discord.ext import commands
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
self.limited = []
self.count = 0
@commands.command()
async def random(self,ctx):
with open('./model/utils/elements.json... |
"""
*What is this pattern about?
In Java and other languages, the Abstract Factory Pattern serves to provide an interface for
creating related/dependent objects without need to specify their
actual class.
The idea is to abstract the creation of objects depending on business
logic, platform choice, etc.
In Python, th... |
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
iris_dataset = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_st... |
import glob,os
import numpy as np
import matplotlib.pyplot as plt
from plotmaker import trav_wave
def simple_PDE(T,Nx,Nt,X,lam,beta,S_1,I_1,R_1,f,g,h):
S = np.zeros(Nx+3) #list of Susceptible
#S_1 = np.ones(Nx+1)#list of Susceptible in previous time step
I = np.zeros(Nx+3) #list of Susceptible
#I_... |
from jinja2 import Environment, FileSystemLoader
ENV = Environment(loader=FileSystemLoader('.'))
template = ENV.get_template("template.j2")
#class method works to a similar output to the Dictionary method
class NetworkInterface(object):
def __init__(self, name, description, vlan, uplink=False):
self.name... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as plt
tf.set_random_seed(1)
np.random.seed(1)
BATCH_SIZE = 50
LR = 0.001 # learning rate
mnist = input_data.read_data_sets('./mnist', one_hot=True) # they has been normalized... |
from mcrcon import MCRcon
class Connection:
def __init__(self, address, port, secret):
self.mcr = MCRcon(address, secret)
self.mcr.connect()
def send(self, msg):
resp = self.mcr.command(msg)
return resp
|
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
combined = []
combined.extend(nums1)
combined.extend(nums2)
combined = sorted(combined)
length = len(combined)
if length % 2 != 0:
return combined[length // 2]
else:
return... |
from numpy import array
from numpy import mean
import numpy as np
M = array([[1,2,3,4,5,6],[1,2,3,4,5,6]])
#print(M)
col_mean = mean(M, axis=0)
print(col_mean)
row_mean = mean(M, axis=1)
print(row_mean)
all_mean = mean(M)
print(all_mean)
l = [1, 2, 3]
p = [.2, .3, .5]
e = 0
for count, i in enumerate(l):
e += i * p... |
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
from _sadm import libdir
from _sadm.service import Service
from _sadm.utils import path
__all__ = ['configure']
def configure(env, cfg):
env.settings.merge(cfg, 'service', (
'config.dir',
'enable',
))
_loadEnabled(env)
def _loadEnab... |
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 5
img = cv.imread('C:/Users/Windows/Desktop/Trabalhos/Verso.png',1) # trainImage
marca1 = img[0:57, 0:57]
marca2 = img[0:57, 540:590]
marca3 = img[790:840, 0:57]
marca4 = img[790:840, 540:590]
gray1 = cv.cvtColor(marca1,cv.COL... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Ana")
process.load("FWCore.MessageService.MessageLogger_cfi")
############# Set the number of events #############
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1000)
)
############# Define the source file ###############
pro... |
# Path to access data
DATA_PATH = './Data/planilha_de_repasse.xlsx'
# Value of used column keys
DATA_KEY_CONCILIATION = 'Conciliação'
DATA_KEY_PAYMENT_WAY = 'Método de pagamento'
DATA_KEY_ML_COMMISSION = 'Comissão ML por parcela'
DATA_KEY_GROSS_AMOUNT = 'Valor bruto da parcela'
DATA_KEY_TRANSACTION_DATE = 'Data da tra... |
import cPickle
import gzip
import os
import sys
import time
import numpy
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
from logistic_sgd import LogisticRegression, load_data
from mlp import HiddenLayer
from convolutional_mlp import LeNetConvPo... |
import itertools
from typing import Iterable
from fireant.utils import (
flatten,
format_dimension_key,
format_metric_key,
)
from pypika import (
Table,
functions as fn,
)
from .finders import (
find_and_group_references_for_dimensions,
find_joins_for_tables,
find_required_tables_to_jo... |
from .utils import clever_format
from .profile import profile, profile_origin
import torch
default_dtype = torch.float64 |
#
# Created on Thu Aug 24 2020
# Author: Vijendra Singh
# Licence: MIT
# Brief:
#
import os
import cv2
import parameters as params
def read_images(dir_name=params.DATA_DIR):
'''
@brief: read images and store it along with unique ID representing its position
@args[in]: directory containing images
@ar... |
from django.shortcuts import render
from .forms import StudentRegistration
# Create your views here.
def showformdata(request):
fm=StudentRegistration(auto_id='some_%s', label_suffix=' ?', initial={'name':'rishabh'})
return render(request,"enroll/userregistration.html",{'stud':fm})
|
class Task:
title = "Task"
done = False
def __init__(self, title):
self.title = title
def check(self):
self.done = not self.done |
# cff for L1GtAnalyzer module
#
# V.M. Ghete 2012-05-22
from L1Trigger.GlobalTriggerAnalyzer.l1GtAnalyzer_cfi import *
|
import os
obj_dir = "/home/pirate03/hobotrl_data/playground/initialD/exp/record_rule_scenes_rnd_obj_v3_fenkai_rm_stp/val"
eps_names = sorted(os.listdir(obj_dir))
for eps_name in eps_names:
eps_dir = obj_dir + "/" + eps_name
lines = open(eps_dir+"/0000.txt", "r").readlines()
new_txt = open(eps_dir+"/0001.tx... |
1
import rospy
import Talker
from std_msgs.msg import String
def speak_text_callback(data):
pass
def socialist():
rospy.init_node("socialist")
rospy.Subscriber("speak_text", String, speak_text_callback)
rospy.spin()
if __name__ == '__main__':
socialist()
|
_base_ = '../res2net/cascade_rcnn_r2_101_fpn_20e_coco.py'
model = dict(
backbone=dict(
type='CBRes2Net',
cb_del_stages=1,
cb_inplanes=[64, 256, 512, 1024, 2048],
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True)),
... |
import io, re, sys
import string
import pandas as pd
from toolz.functoolz import compose_left
from ast import literal_eval
from pathlib import Path
from types import SimpleNamespace
from typing import Dict, List, Tuple
from pdb import set_trace as st
from prettyprinter import pprint
from prettyprinter import cpprint
fr... |
import sys
def error(msg):
"""Prints error message, sends it to stderr, and quites the program."""
sys.exit(msg)
args = sys.argv[1:] # sys.argv[0] is the name of the python script itself
try:
arg1 = int(args[0])
arg2 = args[1]
arg3 = args[2]
print("Everything okay!")
except ValueError:
... |
from flask import Flask,jsonify,request,render_template
from flask_cors import CORS
app = Flask(__name__, static_url_path='/assets')
CORS(app)
listBerat = [
{'tanggal':'2018-08-22', 'max':50, 'min':49},
{'tanggal':'2018-08-21', 'max':49, 'min':49},
{'tanggal':'2018-08-20', 'max':52, 'min':50},
... |
import io
from keras.models import Model
from keras.layers import Dense, Input
from matplotlib import pyplot
import numpy as np
import tensorflow as tf
import time
def discriminator():
# Entrée à 2 valeurs
inp = Input(shape=(2,), name='input_sample')
x = inp
# Unique couche cachée Dense de 25 noeuds avec une f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.