text stringlengths 38 1.54M |
|---|
import serial
import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped, Quaternion, Point
import math
class RallyCar:
def __init__(self, way_points):
rospy.Subscriber("cur_pos", Point, self.get_cur_pos)
self.cur_x = 0
self.cur_y = 0
self.thread_hold = 1
self.rate = rospy.Rate(150)
... |
from django.conf.urls import url
from .views import DailyCountExportCRUDL, IncomingPerDayChart, MostUsedLabelsChart, RepliesPerMonthChart
urlpatterns = DailyCountExportCRUDL().as_urlpatterns()
urlpatterns += [
url(r"^incoming_chart/$", IncomingPerDayChart.as_view(), name="statistics.incoming_chart"),
url(r"^... |
import segmentation_models_pytorch as smp
model = smp.Unet('resnet34', classes=3, activation='softmax') |
stuff = []
x = True
while x is True:
y = input("")
if y.lower() != 'done':
stuff.append(y)
else:
print(stuff)
print(len(stuff))
break
|
import torch
from base import utils as ut
from base.models import nns
from torch import nn
from torch.nn import functional as F
import numpy as np
class MultipleTimestepLSTM(nn.Module):
def __init__(self, in_num_ch=1, img_size=(64,64,64), z_dim=512,inter_num_ch=16, fc_num_ch=16, lstm_num_ch=16, kernel_si... |
import plotly as py # 导入plotly库并命名为py
import plotly.graph_objs as go
# -------------pre def
pyplt = py.offline.plot
import pandas as pd
df = pd.read_csv(r'dat/appl.csv', index_col=['date'], parse_dates=['date'])
trace = go.Ohlc(
x=df.index,
open=df.open,
high=df.high,
low=df.low,
close=df.clos... |
# -*- coding:utf-8 -*-
import errno
import os
from random import randint
from const import *
def make_static_dir(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def getSourceId(source)... |
1. Let _envRec_ be the function Environment Record for which the method was invoked.
1. If _envRec_.[[ThisBindingStatus]] is ~lexical~, return *false*.
1. If _envRec_.[[HomeObject]] has the value *undefined*, return *false*; otherwise, return *true*. |
import os
import datetime
import json
from markupsafe import Markup
import requests
from flask import render_template, redirect, request
from app import app
# The node with which our application interacts, there can be multiple
# such nodes as well.
CONNECTED_NODE_ADDRESS = "http://127.0.0.1:" + str(os.environ.get('... |
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
i... |
# Copyright (c) 2013 Michael Bitzi
# Licensed under the MIT license http://opensource.org/licenses/MIT
import string
import re
import time
import pwm.windows
from pwm.config import config
from pwm.ffi.xcb import xcb
from pwm.ffi.cairo import cairo
import pwm.color
import pwm.keybind
import pwm.xdg
import pwm.spawn
im... |
from pettingzoo.utils.deprecated_module import DeprecatedModule
prison_v0 = DeprecatedModule("prison", "v0", "v3")
prison_v1 = DeprecatedModule("prison", "v1", "v3")
prison_v2 = DeprecatedModule("prison", "v2", "v3")
prospector_v0 = DeprecatedModule("prospector", "v0", "v4")
prospector_v1 = DeprecatedModule("prospecto... |
country={}
for number in range(2):
key = input('Введите страну:\n')
value = input('Введите город этой страны\n')
country[key] = value
print(country)
for number in range(2):
key = input('Введите страну:\n')
value = input('Введите город этой страны\n')
country[key] = value
print(countr... |
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, CommandLineInputSpec, CommandLine, traits, File, TraitedSpec
from nipype.interfaces.matlab import MatlabCommand
#==================================================================================================
# Denoising with non-local me... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging, time
from rest_framework import serializers
from django.contrib.auth.models import User, Group
from django.db import transaction
from natrix.common.natrix_views.serializers import NatrixSerializer
from natrix.common import exception as na... |
__author__ = 'frankhe'
import time
import numpy as np
import data_sets
class QLearning(object):
def __init__(self, pid, network, flags, comm, share_comm):
self.pid = pid
self.network = network
self.flags = flags
self.comm = comm
self.share_comm = share_comm
self.tra... |
import requests
from bs4 import BeautifulSoup
URL_TOTAL_LIST = 'https://comic.naver.com/webtoon/weekday.nhn'
response = requests.get(URL_TOTAL_LIST)
soup = BeautifulSoup(response.text, 'html.parser')
class_title_a_list = soup.select('a.title')
title_list = []
for a in class_title_a_list:
a_href = a.get('href') ... |
# Copyright 2018 www.privaz.io Valletech AB
# Copyright 2002-2023, OpenNebula Project, OpenNebula Systems
#
# 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/LI... |
# -*- coding: utf-8 -*-
import Ouroboros
import math
import Math
import time
import random
from OURODebug import *
import GlobalDefine
import data_entities
class Motion:
"""
Movement related package
"""
def __init__(self):
self.nextMoveTime = int(time.time() + random.randint(5, 15))
# Default walk speed (dec... |
"""
Utility functions
=================
This module defines some utility functions that can be used in multiple
unrelated part of the code, such as error reporting.
"""
from __future__ import print_function
import sys
import functools
def terminate_program(err_msg, ret_code=1):
"""Terminates the current prog... |
import olca_schema as o
import unittest
class EnumConvTest(unittest.TestCase):
def test_flow_type(self):
val: str = o.FlowType.ELEMENTARY_FLOW.value
self.assertEqual('ELEMENTARY_FLOW', val)
self.assertEqual(o.FlowType.ELEMENTARY_FLOW, o.FlowType[val])
self.assertEqual(o.FlowType.... |
"""Module about the main application."""
import enum
import numpy as np
import vtk
from qtpy import QtCore
from qtpy.QtCore import QSize
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (QToolButton, QButtonGroup,
QFileDialog)
from .utils import DefaultFunction
from .element import... |
from rpgplayer import Player
import random
p = Player('Ricardo')
class item:
def __init__(self,name,cost,weight):
self.name = name
self.cost = cost
self.weight = weight
self.type = type
class weapon(item):
def __init__(self,name,cost,weight,attack,type):
self.name = na... |
from pyspark.sql import SparkSession
spark = SparkSession.builder.master('local').appName('DataFrames Sample').getOrCreate()
# READING THE CSV FILE TO DATAFRAME AND GIVING SCHEMA FOR THAT DATA
ordersCSV = spark.read.csv('E:\\Spark2usingPython3\\data-master\\retail_db\\orders')\
.toDF('order_id','order_date','orde... |
import object_storage
import timeit
def list_objects():
container_list = sl_storage.containers()
for container in container_list:
print(container.name)
print(sl_storage[container.name].objects())
def upload_objects():
for container_name in containers:
sl_storage[contai... |
import unittest
import namegenerator.markovchain
class TestMarkovChain(unittest.TestCase):
def setUp(self):
self.markov_chain = namegenerator.markovchain.MarkovStateMachine()
self.markov_chain.analyze_text(["mark", "mark", "mark"])
def test_get_name_with_single_name_input(self):
self... |
# -*- coding: utf-8 -*-
# Author: Tom Bresee <tbresee@umich.edu>
#
# License: BSD 3 clause
from ..datasets import public_dataset
from sklearn.naive_bayes import BernoulliNB, MultinomialNB, GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
... |
import pygame
from pygame.locals import *
import math
from py3de import *
# Setup pygame
pygame.init()
pygame.font.init()
width, height = 800, 800
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Nick\'s 3D Engine')
engine = Engine3D(width, height)
cube = Cube(engine, 0, 0, 2, 0, 0, 1)
... |
from sqlalchemy import BigInteger, Column, Integer, Numeric, String, Table
from src.models.base import Base
"""
Trending Params aggregate the paramters used to calculate trending track scores
"""
# Materialized view
t_trending_params = Table(
"trending_params",
Base.metadata,
Column("track_id", Integer, ... |
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QIcon, QFontMetricsF
from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QScrollArea, \
QGroupBox, QFormLayout
from src.widget.answer import Answer
from src.widget.header import Header
ENCODE_... |
from __future__ import absolute_import
from .base import BaseContent
from ..utils import resize_image
from ZODB.blob import Blob
class Image(BaseContent):
""" Image model """
def _store_resized_image(self, key, data):
""" store a blob image as attribute """
blob = Blob()
f = blob.ope... |
# Support and confidence are values to specify the sensitivity of the algorithm that you're running.
# Use it together with this URL to do calls to the public API.
# There is a pyspotlight wrapper, or you can do pure API calls (there is atleast on tutorial online)
AnnotationURL = "https://api.dbpedia-spotlight.org/en/a... |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="dtf",
version="0.1.4",
description="dtf is my personal dotfile manager.",
url="https://github.com/ericnchen/dtf",
author="Eric Chen",
author_email="eric@ericnchen.com",
license="MIT",
packages=["dtf", "dtf.dotfiles"],
... |
def main():
temperatures = open("temps_input.txt", 'r')
output = open("temps_output.txt", 'w')
lines = temperatures.readlines()
for line in lines:
line = float(line)
print(fahrenheit_to_celsius(line), file=output)
output.close()
temperatures.close()
def fahrenheit_to_celsius... |
from users.models import InvalidPassword
from users.models import User
from users.models import UserDoesNotExist
class ModelBackend(object):
def authenticate(self, username=None, password=None):
return User.authenticate(username=username, password=password) |
# Generated by Django 3.0.3 on 2020-02-10 16:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ghostPost', '0002_auto_20200210_1639'),
]
operations = [
migrations.AlterField(
model_name='boastroast',
name='boast... |
def enqueue(l1):
if(not isFull(l1)):
data=int(input("Enter the data :"))
l1.append(data)
else:
print("QUEUE IS FULL DEQUEUE FIRST...")
def dequeue(l1):
if(not isEmpty(l1)):
l1.pop(0)
else:
print("QUEUE IS EMPTY ENQUEUE FIRST...")
def isFull(l1):
return len(l1)==10
def isEmpty(l1):
return l1==[] or l1==... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/14 0014 上午 9:11
# @Author : Aries
# @Site :
# @File : 函数的应用.py
# @Software: PyCharm Community Edition
def func(fn):
fn()
def gn():
print('hello world')
func(gn)
|
import numpy
class layer():
def __init__(self, input_shape, trainable, name):
self.input_shape = input_shape
self.trainable = trainable
self.name = name
def forward(self, X):
raise NotImplementedError("Please Implement the Forward method")
def backward(self, dL_Z):
... |
import os
from selenium import webdriver
import json
from time import sleep
import chromedriver_autoinstaller
drVer = str(chromedriver_autoinstaller.get_chrome_version())
drVer = drVer[0:drVer.index(".")]
hutbeler = [[],[],[]]
def printHutbeler(hutbeler):
print(f"""
NO | TARIH | HUTBE ADI
-----... |
count = 0
sum = 0.0
while True:
value = input("Enter a number: ")
if value == 'done':
break
try:
extravalue = float(value)
except:
print("Invalid input")
continue
count = count + 1
sum = sum + extravalue
print("Sum: " + str(sum), "Count: " + str(count), "Average... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Vantiv eCommerce
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-12-08 13:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('message', '0002_auto_20181208_2107'),
]
operations = [
migrations.AlterModelOption... |
from itertools import groupby
from operator import itemgetter
import sys, os
import xlrd
from db import drugDB, reportElm
class ExcelParser:
def __init__(self, xl_path = None, file_content=None, sheet_index=0, **extra_fields):
wb = xlrd.open_workbook(xl_path) if xl_path else xlrd.open_workbook(file_contents=file... |
# #TaxCalculator
#
# gross_salary = 40000
# loan = 3000
# sacco = 2000
#
# age = (input("enter age: "))
# if age <=18:
# result = gross_salary * 3/100
# elif age > 18 and age <= 24:
# result = gross_salary * 6/100
# elif age > 24 and age <= 35:
# result = gross_salary * 8/100
# elif age > 35 and age <= 40:
... |
from setuptools import setup
setup(
name='clouds_are_fun',
version='0.0.1',
description="Clouds are (as stated) fun!",
author='Rachel Storer',
author_email='rls347@gmail.com',
license='',
packages=['clouds_are_fun'],
zip_safe=False)
|
# $example on$
from pyspark.ml.classification import LogisticRegression, LinearSVC
# $example off$
from pyspark.sql import SparkSession
from configs import d_path
"""
An example demonstrating Logistic Regression Summary.
Run with:
bin/spark-submit examples/src/main/python/ml/logistic_regression_summary_example.py
""... |
from db import create_app
from db.api.views import api_bp as api_module
from db.custom_api.views import custom_api_bp as custom_api_module
from flasgger import Swagger
if __name__ == '__main__':
app = create_app('config.DevelopmentConfig')
app.register_blueprint(api_module)
app.register_blueprint(custom_a... |
def reference_demo(x):
print("Before assigning: x=", x, " id=", id(x))
x = 8
print("After assigning: x=", x, " id=", id(x))
x = 1
print("Before the call: x=", x, " id=", id(x))
reference_demo(x)
print("After the call: x=", x, " id=", id(x))
|
import sqlite3
import hashlib
#execfile('databasecommands.py')
exec(open('databasecommands.py').read())
DB = DataBase('stuff.db')
#
#SET UP INITIAL TABLES
#
#check if user table is inputted
if not DB.tableExists('users'):
print('no table "users"... making one now...')
DB.createTable('users (username VARCHAR(25) U... |
#!/usr/bin/env python2.7
# coding: utf-8
import os
import re
import datetime
import traceback
from slog import SysLog
class Writer(object):
def __init__(self, lock, target, file_name, max_size, max_count):
self.target = target
self.file_path = os.path.join(target, file_name)
self.file_nam... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-30 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('horas', '0012_carrera_carrera_abreviada'),
]
operations = [
migrations.AddF... |
## Generate a contour plot
# Import some other libraries that we'll need
# matplotlib and numpy packages must also be installed
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
# define objective function
def f(x):
x1 = x[0]
x2 = x[1]
obj = x1**2 - 2.0 * x1 * x2 + 4 * x2**2
... |
import re
import sys
from contextlib import contextmanager
from pprint import pprint as p
from app import create_app
from app.jiraapi import get_marketplace_jira
from app.models import Application
app = create_app('development')
@contextmanager
def jira_with_app_context():
with app.app_context():
j = ge... |
import os
from unittest import TestCase
from xml.etree import ElementTree as ET
from xam import Addon
try:
from collections import OrderedDict
except ImportError:
from collective.ordereddict import OrderedDict
class TestAddon(TestCase):
def assert_attrs(self, obj, attrs):
for attr_name, expected_... |
#RUBEN CUADRA
#DAVID GAONA
#code to run a server that manages game boards of the Onitama game
class options():
PVE = b'0'
PVP = b'1'
DIFFICULTY_NORMAL = b'1'
DIFFICULTY_HARD = b'2'
class responses():
OK = '0'
WRONG_DIFFICULTY="26"
BLUE = 0
RED = 1 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... |
import tensorflow as tf
def PairwiseEuDist(
user_vec,
subgraph,
item_vec=None,
item_bias=None,
p_item_vec=None,
p_item_bias=None,
n_item_vec=None,
n_item_bias=None,
train=True,
weights=1.0,
margin=1.0,
scope="PointwiseMSE",
):
if train:
l2_user_pos = tf.red... |
import os
import linecache
import re
from glob import glob
from collections import defaultdict
from typing import List, Tuple
from pipeline.sanitizers.regex import HAS_TAG, HAS_BOTH, HAS_CLOSING_TAG, HAS_OPENING_TAG
def annotate(raw_tokens) -> List[Tuple]:
tokens = []
current_label = 'other'
for raw_toke... |
from django.contrib import admin
from RNG.models import UserProfile, Category, Game, Rating, Comment
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Category)
admin.site.register(Game)
admin.site.register(Rating)
admin.site.register(Comment)
|
from sys import exit
def i(): return input()
def ii(): return int(input())
def iis(): return map(int, input().split())
def liis(): return list(map(int, input().split()))
def print_array(a): print("".join(map(str, a)))
t = ii()
for _ in range(t):
m, n = iis()
ans = [['B' for j in range(n)] for i in range(m)]
ans[0... |
from math import sqrt
from numpy import dot, array
def euclid_dist(p1, p2):
euclid_sum = 0
for i,j in zip(p1, p2):
euclid_sum += math.sqrt((j - i) ** 2)
return euclid_sum
def np_euclid_dist(p1, p2):
np1, np2 = array(p1), array(p2)
return sqrt(dot(np2 - np1, np2 - np1))
def manhattan_dist(p1, p2):
ma... |
def count_substring(string, sub_string):
count_substring=0
for i in range(len(string)-len(sub_string)+1):
if string[i:i+len(sub_string)] == sub_string:
count_substring+=1
return count_substring
string = input().strip()
sub_string = input().strip()
count = count_substring(string, su... |
# -*- coding: utf-8 -*-
"""
Display current sound volume using amixer.
Expands on the standard i3status volume module by adding color
and percentage threshold settings.
Volume up/down and Toggle mute via mouse clicks can be easily added see
example.
Configuration parameters:
button_down: Button to click to decrea... |
class Patient:
"""
The Patient object. The initialization will not happen here. For this take a look at the
CSVDataReader class.
"""
def __init__(self,
id,
kuerzel,
alter,
geschlecht,
hauptdiagnose,
nebendiagnose,
vorherige_erkrankungen,
... |
favorite_numbers={"Max":3,
"Den":2,
"Dima":1
}
print("Max's favorite number is {}".format(favorite_numbers["Max"]))
print("Den's favorite number is {}".format(favorite_numbers["Den"]))
print("Dima's favorite number is {}".format(favorite_numbers["Dima"]))
print(sort... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist/", one_hot=True)
#定义输入
x=tf.placeholder("float",[None,784])
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,W)+b)
#定义输出
y_=tf.placeholder("float",[Non... |
import requests
from lxml import html
USERNAME = 'tnetwork'
PASSWORD = '1dehudaa'
LOGIN_URL = 'https://www.centraldispatch.com/'
URL = 'https://www.centraldispatch.com/protected/cargo/dispatched-to-me?folder=Dispatched'
def main():
session_requests = requests.session()
# Get login csrf token
result = se... |
# -*- coding: utf-8 -*-
from django import http
from django.conf import settings
from django.shortcuts import render
from django.template import Context, loader
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# root
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
def collatx(n):
if n==1: return 1
if n%2 == 0: return 1 + collatx(int(n/2))
return 1 + collatx(3*n + 1)
n = int(input())
mx = collatx(n)
nums = list(map(int, list(str(n))))
print(nums)
for i in range(len(nums)):
for j in range(1,10):
tmp = list(nums)
tmp[i] = j
val = int(""... |
import json
class Achievements_Categories:
def __init__(self, json):
self.id = json['id']
self.name = json['name']
self.description = json['description']
self.order = json['order']
self.icon = json['icon']
self.achievements = json['achievements']
... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/Users/adityabhat/Downloads/devel/include;/Users/adityabhat/Downloads/src/ros_comm/topic_tools/include".split(';') if "/Users/adityabhat/Downloads/devel/include;/Users/adityabhat/Downloads/src/ros_comm... |
# Copyright (C) 2005 Paul Harrison
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is... |
import numpy as np
import torch
from datasets import load_dataset
from torchtext.data.metrics import bleu_score
from transformers import AutoTokenizer, T5ForConditionalGeneration
from mmengine.evaluator import BaseMetric
from mmengine.model import BaseModel
from mmengine.runner import Runner
tokenizer = AutoTokenizer... |
from Db.DataClass import DataClass
from Db.CustomerType import CustomerType
class CustomerTypeSearch(DataClass):
def __init__(self, status):
DataClass.__init__(self)
self.status = status
def search(self):
params = "'" + self.status + "'"
self.rows = DataClass.sele... |
class Solution:
def balancedStringSplit(self, s: str) -> int:
l_num = 0
r_num = 0
res = 0
i = 0
while i < len(s):
if s[i] == 'L':
l_num += 1
i += 1
elif s[i] == 'R':
r_num += 1
i += 1
... |
# split a list into two parts
def split(n, l):
return [l[0:n], l[n:]]
def test_split():
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
expected = [['a', 'b', 'c'], ['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k']]
assert split(3, l) == expected
assert split(3, []) == [[], []]
assert s... |
import sys
sys.stdin = open('특이한자석.txt')
def rotation(num, dir, chain):
# 자기자신을 포함한 오른쪽 연결정보 확인
dr = dir
for i in range(num, 5):
target = mags[i]
if dr == 1: # 시계 방향
tmp = target.pop(7)
target.insert(0, tmp)
else: # 반시계 방향
tmp = target.pop(0)
... |
import pytest
import vcs, cdms2
from cdat.MarkEdit import MarkerEditor
@pytest.fixture
def editor():
editor = MarkerEditor.MarkerEditorWidget()
marker = vcs.createmarker()
editor.setMarkerObject(marker)
return editor
def test_type(qtbot, editor):
editor.updateType('triangle_up')
assert editor.... |
from flask import Flask, url_for,render_template,flash,redirect
import flask_login
from form import LoginForm
from flask_sqlalchemy import SQLAlchemy
from fileconfig import *
app = Flask(__name__)
#flask config
app.config.from_object('fileconfig')
#database setting
db = SQLAlchemy(app)
db.create_all()
#login manager
lo... |
import os
import uuid
import sys
sys.path.append("./src/main/python")
import main
try:
work_path = os.getcwd()
random_number = str(uuid.uuid1())
with open(os.path.join(work_path, '.hilens/rtmp.txt'), 'w') as f:
f.write(random_number)
os.environ['RTMP_PATH'] = "rtmp://127.0.0.1/live/" + random_... |
import numpy as np
import zhinst.utils
import time
import matplotlib.pyplot as plt
import pygame, sys
from pygame.locals import *
import math
from my_poll_v2 import R_measure as R_measure
import stlab
import os
#############################################################
''' Definitions'''
# definitions
device_id... |
def luasSegitiga2(a, t):
luas = a * t / 2
print('Luas segitiga dg alas ', a,
' dan tinggi ', t,
' adalah ', luas)
luasSegitiga2(10, 20)
#segitiga dengan alas=15, dan tinggi= 45
luasSegitiga2(15, 45)
|
def main():
power = 1000
number = 2**power
return sum(int(digit) for digit in str(number))
if __name__ == "__main__":
answer = main()
print(answer) |
#!/usr/bin/env python
import sys
print("#include <array>")
namespaces = 10
for i in range(0, namespaces):
print("namespace someothername" + str(i) + " {")
func_name = sys.argv[1] + "veryLongFunctionNameToMakeTheBenchmarkBigger"
func_list = []
for i in range(0, 10000):
func_list.append(func_name + str(i))
prin... |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
client = Table('client', post_meta,
Column('id', INTEGER, primary_key=True, nullable=False),
Column('first_name', VARCHAR(length=255)),
Column('last_name', VARCHAR(length=255)),... |
from log import Log
class ResultFormatterBase:
file_extension = None
def format_result(self, test_cases):
Log.err("BaseFormatter doesn't know what to do :(")
|
def selection_Sort():
n=raw_input("\nEnter the numbersize")
l=[]
for i in range(int(n)):
x=raw_input("Enter %d element" %i)
l.append(x)
for i in range(len(l)):
mini=l[i]
for j in range(i,len(l)):
if(l[j]<mini):
mini=... |
#! /usr/bin/python
import sys
import os
lib_path = os.path.abspath('/home/dept/ta/yuhan/mobility-detector/src/Mobility-Detector/activity-detection/src/lib')
sys.path.append(lib_path)
from sensors import *
from location import *
from math import *
from numpy.fft import *
import numpy
from normal import *
from distribut... |
# ,< ,> ,>= ,<= ,== ,!= ,is ,is not
# is not untuk membandingkan object dan is
a = "kamu"
b = "kamu"
hasil = a is not b
print(hasil) |
import urllib.parse
import settings
TORTOISE_ORM = {
"connections": {"default": f'mysql://{settings.DB_USER}:{urllib.parse.quote_plus(settings.DB_PASS)}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}'},
"apps": {
"models": {
"models": ["models", "aerich.models"],
"de... |
from django.contrib import admin
from .models import Application
# Register your models here.
@admin.register(Application)
class ApplicationAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj:
return self.readonly_fields + ('legal_agreement','signature','income_ph... |
# -*- coding: utf-8 -*-
#python 3.5
import pandas as pd
def print_frequency(data, col, format="count"):
norm=True if format=="percent" else False
print(format,'-')
print(data[col].value_counts(sort=False, normalize=norm))
if __name__=="__main__":
dataset="ADDHEALTH"
data=pd.read_csv("addhealth_pd... |
import time
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware
from stem import Signal
from stem.control import Controller
def new_tor_identity():
with Controller.from_port(port=9051) as controller:
controller.authenticate(password='articles')
controller.signal(Signal.NEWNYM)
... |
#!/usr/bin/python
import os
import re
import sys
import glob
from scipy import stats
from Bio import SeqIO
from collections import Counter, defaultdict
def isInt(astring):
""" Is the given string an integer? """
try: int(astring)
except ValueError: return 0
else: return 1
def ExtractEggPSGNumber(PSG):... |
import asyncio
async def func():
print("开始执行协程内部工作")
response = await asyncio.sleep(2)
print("执行完毕", response)
return "执行结果"
if __name__ == '__main__':
print("main开始")
# 创建task对象,将当前执行函数任务添加到事件循环内部
task_list = [
func(),
func(),
]
print("main结束... |
print "I will now count my chickens:"
print "Hens", 2.5 + 3.0 / 6.0 #make the operation
print "Roosters", 10.0 - 2.5 * 3.0 % 4.0 #make the operation
print "Now I will count the eggs:"
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0 #make the operation
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?... |
'''
Created on 8. 5. 2014
@author: casey
'''
import inspect
import sys
import pkgutil
def loadClasses(mod_path, base_class, class_name_filter, skip_private_mod = True):
result = []
if not mod_path in sys.path:
sys.path.append(mod_path)
modules = pkgutil.iter_modules(path=[mod_path])
for loader... |
'''
Daniel Loyd
'''
def run(train, labels, test):
'''
data -> numpy.array
labels -> numpy.array
'''
import numpy as np
length = max([len(data) for data in train])
data = []
for info in train:
new_info = info
diff = length - len(new_info)
if diff > 0:
... |
"""Script for choosing and entering board games."""
from json import load, dump
import sys
from pathlib import Path
from boardgamegeek import BGGClient, BGGItemNotFoundError
from terminalprompts import list_prompt, confirmation_prompt, input_prompt
FILE = "games.json"
FOLDER = "game_data"
PATH = Path().parent / F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.