text stringlengths 38 1.54M |
|---|
# Export useful functions and types from private modules.
from py_zipkin.encoding._types import Encoding # noqa
from py_zipkin.encoding._types import Kind # noqa
from py_zipkin.storage import get_default_tracer # noqa
from py_zipkin.storage import Tracer # noqa
|
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Home").master("local").getOrCreate()
spark.read.format("csv").load("employee.csv").show(2,False);
|
board = {'1': ' ', '2': ' ', '3': ' ',
'4': ' ', '5': ' ', '6': ' ',
'7': ' ', '8': ' ', '9': ' '}
keys = []
for key in board:
keys.append(key)
# function to print the board after every move
def boardAfterEveryMove(sampleBoard):
print(sampleBoard['1'] + '|' + sampleBoard['2'] + '|' + sampleBo... |
"""
1248.
Medium
Given an array of integers nums and an integer k.
A subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
... |
#!/usr/bin/env python3
N = int(input())
# print(N)
result = 0
for num in range(1, N+1):
if num % 2 == 1:
count = 0
for i in range(1, num+1):
if num % i == 0:
count += 1
if count == 8:
result += 1
print(result)
|
import requests
import time
import pytest
allowed_fpe = 1e-6
def is_close(a, b, err=allowed_fpe):
return abs(a-b) <= err
def reset_time(server):
"""Call at the BEGINNING of a test if you want it to use manual time. Time will be set to `time`."""
# set time to 0
resp = requests.post(server.url + 'sud... |
# Copyright (c) 2014--2019 Muhammad Yousefnezhad
#
# 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, modify, merge, ... |
from pythonzombie.proxy.client import ZombieProxyClient
from pythonzombie import Browser
from unittest import TestCase
import fudge
import os
class BrowserClientTest(TestCase):
"""
Sets up a pythonzombie.Browser() object to test with.
"""
def setUp(self):
sup... |
import sys
sys.path.append(sys.path[0] + '/../src/')
from Measurement import Measurement
from MeasurementStarter import MeasurementStarter
from top_block import top_block
def main():
starter = MeasurementStarter(Measurement(top_block))
starter.start()
if __name__ == '__main__':
main() |
# When stack address: 0xffffd554
# arg_4h = 0xffffd57c delta = 0x28
# shell: 0x080484eb
# Heap address: 0x0804b570
""" : > wv 0x080484eb @0x0804b578
: > wv 0x0804b57c @0x0804b590
: > wv 0xffffd564 @ 0x0804b594
here is stack address leak: 0xffffd554
here is heap address leak: 0x804b570
now that you have leaks, get she... |
from PIL import Image
import os
def main():
path = os.curdir+"//Pictures_of_ChineseCharacter"
files = os.listdir(path)
number = 0
for file in files:
picture = Image.open(path+"//"+file)
lists = file.split('.')
picture_1 = picture.convert("1")
picture_1.save(os.curdir+"//... |
import os
#os.system("date")
#os.mkdir ("C:/Users/Dell/Desktop/Module3/C-99/sourcefolder")
path="C:/Users/Dell/Desktop/Module3/C-99/sourcefolder"
isexist=os.path.exists(path)
print(isexist)
testpath="C:/Users/Dell/Desktop/Module3/C-99/OSModule.py"
splitpath=os.path.splitext(testpath)
print(splitpath[0])
p... |
from dataclasses import dataclass
from typing import Tuple, List, Union
from enum import Enum
Coords = List[str]
FpFigure = Union['FpArc', 'FpPoly', 'FpLine', 'FpCircle']
class TextType(Enum):
reference = 0
value = 1
user = 2
simple = 3
class PadType(Enum):
circle = 0
rect = 1
oval = 2... |
# -*- coding: utf-8 -*-
'''
title : get photo exif information
author : ysoftman
python version : 2.x
prerequisite:
sudo pip install exifread
doc:
https://pypi.python.org/pypi/ExifRead
'''
import glob
import exifread
def get_exif():
for fn in glob.glob("*.jpg"):
f = open(fn, 'rb')
tags = exifrea... |
from utils import Session, permission_test
def test_visuals_admin():
superuser = Session('superuser')
assignment_id = superuser.get('/admin/assignments/list')['assignments'][0]['id']
# student = Session('student')
# student.get(f'/admin/visuals/assignment/{assignment_id}', should_fail=True)
# pe... |
from __future__ import division, print_function
from .move import Move
from .mh import MHMove
from .gaussian import GaussianMove
from .red_blue import RedBlueMove
from .stretch import StretchMove
from .walk import WalkMove
from .kde import KDEMove
from .de import DEMove
from .de_snooker import DESnookerMove
__all__ = [... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Media(db.Model):
__tablename__ = 'media'
id = db.Column(db.Integer, primary_key=True)
expiration = db.Column(db.DateTime, nullable=False)
title = db.Column(db.String, nullable=False)
file_name = db.Column(db.String, nullable=False)
... |
import numpy as np
from scipy import optimize
from .c_circle_apx import circle_apx, circle_apx_nl
def apx_circle(points):
points = np.array(points)
x = points[:, 0]
y = points[:, 1]
x_m = x.mean()
y_m = y.mean()
def calc_R(xc, yc):
""" calculate the distance of each 2D points from th... |
import requests
from sc_settings import user, passw, ip
from pprint import pprint
import arrow
# Use this to debug
# import pdb; pdb.set_trace()
# Ignore the InsecureRequestWarning message:
requests.packages.urllib3.disable_warnings()
def one_week_ago():
return arrow.utcnow().shift(weeks=-1).format... |
import inspect
import re
from fedjaz_serializer.serializer.stuff import CODE_OBJECT_ARGS, FUNCTION_ATTRIBUTES
from pydoc import locate
from types import CodeType, FunctionType
class Serializer:
@staticmethod
def serialize(obj):
ans = {}
object_type = type(obj)
if object_type == list:
... |
# Generated by Django 2.0 on 2017-12-18 22:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('talks', '0004_auto_20171218_1752'),
]
operations = [
migrations.AlterField(
model_name='talk',
name='tags',
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Created on Mon Oct 30 19:00:00 2017
@author: gsutanto
"""
import numpy as np
from scipy import signal
import os
import sys
import copy
sys.path.append(os.path.join(os.path.dirname(__file__), '../dmp_param/'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..... |
# -*- coding: utf-8 *-*
class Listas:
#getters de las listas
def getTareasAlta(self):
for tar in self.proAlta:
print tar
return self.proAlta
def getTareaByIdAlta(self, fId):
for tar in self.proAlta:
if(tar.getID()>=fId):
return tar
def getTareasMedi(self):
for tar in self.proMedi... |
#Python06_22_DataTypeEx07_신동혁
#다른 주소를 가리키도록 만들 수는 없을까?
a = [1,2,3]
b = a[:]
a[1] = 4
print(a, "\t", b)
from copy import copy # import는 내부에 빌트되어 있지 않은 함수 or 명령어를 가져온다
a = [1,2,3]
b = copy(a)
print(b)
print(id(a)) # 3036778696264
print(id(b)) # 3036776444104 |
i = vin = vgr = em = tipo = 0
while tipo != 2:
ine, gr = [int(i) for i in input().split()]
i += 1
if ine == gr:
em += 1
elif ine > gr:
vin += 1
elif ine < gr:
vgr += 1
while True:
print("Novo grenal (1-sim 2-nao)")
tipo = int(input())
if tipo == 1 ... |
#!/usr/bin/env python3
# Steve Callaghan <scalla[at]amazon.com>
# 2018/03/16
import sys
import auth
import json
import export
import config
def print_json (jsonMsg):
print json.dumps(jsonMsg, indent=4, sort_keys=False)
def fail_with_error (msg):
print('Fatal Error: ' + msg)
sys.exit()
def print_help (f... |
class SerializeToTransaction(object):
def serialize(self, sender, instance, **kwargs):
return None
|
$NetBSD$
--- media/media.gyp.orig 2011-05-24 08:01:03.000000000 +0000
+++ media/media.gyp
@@ -173,14 +173,14 @@
'video/mft_h264_decode_engine.h',
],
}],
- ['OS=="linux" or OS=="freebsd"', {
+ ['OS=="linux" or OS=="freebsd" or OS=="dragonfly"', {
'link_settings'... |
import random
import matplotlib.pyplot as plt
_x = [i / 100 for i in range(100)]
_y = [3 * e + 4 + random.random() for e in _x]
w = random.random()
b = random.random()
for i in range(10):
for x, y in zip(_x, _y):
z = w * x + b
o = z - y
loss = o ** 2
dw = 2 * o * x
db = 2... |
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
bool_idx = ((a % 2)==0)
print(bool_idx)
print(a[bool_idx])
print(a[a > 10])
print(a[a%2==1]*10)
|
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def sum(self):
return self.num1 + self.num2
def sub(self):
return self.num1 - self.num2
def mul(self):
return self.num1 * self.num2
def div(self):
return self.n... |
from . import base
from . import fields
from . import mixins
class Voice(base.TelegramObject, mixins.Downloadable):
"""
This object represents a voice note.
https://core.telegram.org/bots/api#voice
"""
file_id: base.String = fields.Field()
file_unique_id: base.String = fields.Field()
dura... |
import share
import cv2
import numpy as np
import segmentation.predict
import time
from packet.PacketCreator import PacketCreator
from kickboard.Kickboard import Kickboard, kickboardDict
from user.UserData import UserData, userDict
def user_login(clientData, data):
id = data["id"]
pw = data["pw"]
def user_re... |
"""
Critic Network definition, the input is (o, a_{t-1}, a_t) since (o, a_{t-1}) is the state.
Basically, it evaluates the value of (current action, previous action and observation) pair
"""
import tensorflow as tf
import tflearn
class CriticNetwork(object):
"""
Input to the network is the state and action, ... |
from gravity import gravityOnEverything as gravity
from gravitySum_ContribRegress import gravitySumOnEverything as gravitySum
import sys
import parseData
import common
import numpy as np
def gravityBoth(popFile, distFile, roadFile, titleString = " ", filename="img"):
pop = parseData.parsePopulation(popFile)
ke... |
from fuzzy_set import FuzzySet
class FuzzyVariable():
def __init__(self, min, max, res, name=''):
self.sets = {}
self.res = res
self.min = min
self.max = max
self.name = name
def add_set(self, name, f_set):
self.sets[name] = f_set
def get_set(self, name):
... |
import sys
debug=1
class Message:
# For MsgID
nextMsgID = 0
# Update Message ID Function
# Description: Iterate message ID to provide unique ids for new messages
# Input: None
# Output: Message ID integer
def getNextMessageID(self):
msgID = Message.nextMsgID... |
from __future__ import division
from autograd.scipy.special import digamma, gammaln
def expectedstats(natparam):
alpha = natparam + 1
return digamma(alpha) - digamma(alpha.sum(-1, keepdims=True))
def logZ(natparam):
alpha = natparam + 1
return gammaln(alpha).sum() - gammaln(alpha.sum())
|
""""
Un hombre desea saber cuánto dinero se generará por concepto de intereses
sobre la cantidad que tiene en inversión en el banco. El decidirá reinvertir
los intereses siempre y cuando éstos excedan a $100.000 COP y en ese caso,
desea saber cuánto dinero tendrá finalmente en su cuenta.
"""
Cap=int(input("Ingrese Capi... |
#removes bar element elsets from a .INP file (useful when we need to edit an RVE in hypermesh)
global physical_groups
#physical_groups = raw_input("Number of physical groups: ")
physical_groups = 1
#need to figure out a way to print this
#$MeshFormat
#2.2 0 8
#$EndMeshFormat
#$PhysicalNames
#3
#1 1 "a"
#2 2 "b"
#3 3 ... |
# -*- coding: utf-8 -*-
"""
Created on 2017/3/24
@author: will4906
"""
from enums.Config import Config
from util.WaitEngine import WaitEngine
class Query:
search_button_xpath = "/html/body/div[3]/div[3]/div/div[2]/div[3]/a[3]"
inventor_input_id = "tableSearchItemIdIVDB021"
proposer_input_id ... |
# Generated by Django 2.2 on 2020-04-19 15:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('travel', '0008_booking'),
]
operations = [
migrations.AddField(
model_name='booking',
name='image_pay',
fi... |
class CompressedGene:
__encodings = {"A": 0b00, "C": 0b01, "G": 0b10, "T": 0b11}
__decodings = {value: key for key, value in __encodings.items()}
def __init__(self, gene: str) -> None:
self._compress(gene)
def __str__(self) -> str:
return self.decompress()
def _compress(self, gene... |
from dataclasses import dataclass
@dataclass
class Microsoftoffice365emailattachment:
attachment_id: str = None
attachment_name: str = None
attachment_url: str = None
message_id: str = None
content_type: str = None
size: str = None
|
# -*- coding: utf-8 -*-
"""
@Date: Created on 2019/7/4
@Author: Haojun Gao
@Description:
"""
import csv
paper_path = './raw_data/papers.txt'
domain = "information_retrieval"
domain_path = "./raw_data/" + domain + ".csv"
list = []
index = 0
with open(paper_path, 'r') as file:
for linea in file.readlines():
... |
import ListSplit
import Date_Time
def returnBook():
name=input("Enter name of borrower: ")
a="Borrow :- "+name+".txt"
try:
with open(a,"r") as f:
lines=f.readlines()
lines=[a.strip("$") for a in lines]
with open(a,"r") as f:
data=f.read()
... |
class Comment(object):
def __init__(self, comment_id, user_id, post_id, value):
self.comment_id = comment_id
self.user_id = user_id
self.post_id = post_id
self.value = value
|
from aiohttp import ClientResponse, hdrs
from app.core.api_connector import APIConnector
from app.core.config import settings
class WalletAPIClient(APIConnector):
base_url = settings.WALLET_SERVICE_BASE
async def notify_transaction(self, *, uuid: str) -> ClientResponse:
return await self.fetch(
... |
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
class Owner(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=CASCADE, null=True)
photo = models.ImageFi... |
#!/usr/bin/env python
import unittest
from csmon.utils.config import Config
class TestConfig(unittest.TestCase):
def test_set(self):
value = Config.set('CHECK_INTERVAL',50)
self.assertEqual(value, Config.get('CHECK_INTERVAL'))
with self.assertRaises(NameError):
Config.set('ABC... |
#!/usr/bin/python
import cgi
import base
from connect import connect
import settings
import os.path
import sys
if __name__ == "__main__":
form = cgi.FieldStorage()
attach_id = base.cleanCGInumber(form.getvalue('attach_id'))
db=connect(0)
cur=db.cursor()
if(attach_id != 0):
cur.execute("SELECT test_id, attac... |
#coding=utf-8
import re
import urllib2
import urllib
from bs4 import BeautifulSoup
import lxml.html as HTML
import MySQLdb
import os
import threading,time
def getHtml(url):
html=''
print " It is parsing webpage:%s" %url
try:
req = urllib2.Request(url)
response = urllib2.urlop... |
import os
import sys
import ROOT as r
import monkeyroot
# f1 = r.TFile("/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.09_fakesv2/output/year_2016/TTBAR_PH.root")
# f2 = r.TFile("/nfs-7/userdata/namin/tupler_babies/merged/FT/v3.09_fakesv2/output/year_2016/TTDLht500.root")
f1 = r.TFile("/nfs-7/userdata/namin/tupler_... |
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
import sklearn
'''
了解前向传播和反向传导
这个例子是用np来实现感知机 用于和后面keras作对比
1.生成100个点, 用一条随机生成的线划为两部分
2.用感知机来画一条线来预测
'''
plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示中文标签
plt.rcParams['axes.unicode_minus'... |
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
url_list = []... |
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import subprocess
def open_file(*_):
dialog = Gtk.FileChooserNative(title='Select a file',
transient_for=win,
action=Gtk.FileChooserAction.OPEN)
... |
#Python that uses fromkeys
# A list of keys.
keys = ["bird", "plant", "fish"]
# Create dictionary from keys.
d = dict.fromkeys(keys, 5)
# Display.
print(d)
"""
Output
{'plant': 5, 'bird': 5, 'fish': 5}
""" |
import mc
import urllib
import simplejson
from app import user, ui
def show_message():
mc.ShowDialogOk("MSG", 'Starting?')
tabs = [10, 11, 12, 13, 14]
def toggleTabs(tabIndex):
global tabs
for tab in tabs:
if tab != tabIndex:
toggle = mc.GetActiveWindow().GetToggleButton(tab)
... |
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
class Article(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
edited = models.DateTimeField(auto_now=True)
... |
# https://app.codility.com/demo/results/training4J6YHP-927/
# large_max : 0.244s
def solution(H):
n = len(H)
check = [False] * n
sorted_idx = sorted(range(n), key=lambda x: H[x])
cnt = 0
# 최악의 경우(피라미드) 처리: O(N**2) -> O(N)
# 단조 증감 구간을 찾는다
def find_monotonous():
n = len(H)
in... |
from flask import Flask, render_template,json, request, redirect, url_for, request, get_flashed_messages
from login_check import *
from flask.ext.login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required
from models import *
from flask import session
from nocache import *
#The web app... |
import nltk
nltk.download("stopwords")
nltk.download("wordnet")
from nltk.corpus import wordnet
from nltk.corpus import stopwords
import gensim.downloader as api
import time
import os
import string
os.environ["GENSIM_DATA_DIR"] = "/home/proj/VL-BERT15/language_augmentation/"
class LanguageAugmentation:
def _... |
from scipy.stats import t
from scipy.special import gamma
from scipy.stats import norm, multivariate_normal
import numpy as np
class student():
def __init__(self, corrMatrix, nu):
self.corrMatrix = np.asarray(corrMatrix)
self.nu = nu
self.n = len(corrMatrix)
"""
The m... |
(lambda a, b: a * b)(3, 4) # returns 12
addition = lambda a, b: a * b
print (addition(3, 4)) # returns 12 |
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if len(A) < 2:
return False
exist = set()
duplicate_char = False
different = {}
for i in range(len(A)):
if A[i] != B[i]:
... |
from django.contrib import admin
from apps.booking import models
from apps.booking.models import Flight
class FlightAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'user':
kwargs['queryset'] = get_user_model().objects.filter(usern... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-10-13 14:33:09
# @Author : Michael (mishchael@gmail.com)
import pandas as pd
pd.set_option('expand_frame_repr', False)
pd.set_option('display.max_rows', 1000)
# =====布林线策略=====
# 简单布林线策略
def signal_bolling(df, para = [100,2]):
"""
布林线中轨:n天收盘价的移动平均线
... |
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
from tensorflow.contrib import learn
import csv
# Parameters
# ==================================================
tf.flags.DEFINE_string("buckets", "D:/ai/cnn-text-classification-tf/", "input data path")
tf.flags.DEFINE_string("checkpoint_dir... |
#DATASET_DIR = 'audio/LibriSpeechSamples/train-clean-100-npy/'
#TEST_DIR = 'audio/LibriSpeechSamples/train-clean-100-npy/'
WAV_DIR = '/home/lei/d/LibriSpeech/train-clean-100/'
DATASET_DIR = '/home/lei/2019/dataset/LibriSpeech/train-clean-100-npy/'
#TEST_DIR = '/home/lei/2019/dataset/LibriSpeech/train-clean-100-npy/'
T... |
import requests
from pyquery import PyQuery as pq
from time import sleep
from lxml import html
BASE_URL = 'http://hotline.ua'
"""
class Proxy:
proxy_url = 'http://www.ip-adress.com/proxy_list/'
proxy_list = []
def __init__(self):
r = requests.get(self.proxy_url)
# str_ = pq(r.content)
... |
import pickle
from tqdm import tqdm
from db import DUMP_LANG, DUMP_DATE
RESULTS_DIR = 'results'
N = 20
with open(f"{RESULTS_DIR}/{DUMP_LANG}wiki-{DUMP_DATE}-links-adjlist.csv") as f:
nodes = set()
edges = {}
indegree = {}
for l in tqdm(f):
l = list(map(int, l.split(' ')))
s = l[... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from datetime import datetime
import mock
import textwrap
from common import rotations
from common.waterfall import failure_type
from infra_api_clients.code... |
# -*- coding: utf-8 -*-
"""
@author: Trajan
"""
# One of parameters high and low must be None and the other one must be a number.
import numpy as np
from classbuild import Contract
from vanilla import Tree_Dynamics
from classbuild import MC
class Lookback_Contract(Contract):
def __init__(self, Strick = 1.1, Time... |
'''
题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题解:将两个链表之中的数值转换到列表之中,并进行排序,将排序后的列表构造成链表。
'''
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def Merge(self,head1,head2):
if head1 == None and head2 == None:
return None
num1,n... |
from bs4 import BeautifulSoup
import responses
import urllib2
import sqlite3
import re
def returnsourcecode(url):
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, "html.parser")
return soup;
def getmenulinks():
returnsourcecode("http://www.ferraramalta.com/")
url = "http://www.ferraramalt... |
from __future__ import unicode_literals
import discord
from discord.ext import commands, tasks
import re
import time
import requests
import json
import sys
import youtube_dl
import os
import random
import asyncio
from pornhub_api import PornhubApi
from pornhub_api.backends.aiohttp import AioHttpBackend
from photoCog im... |
from django.db import models
# Create your models here.
class User(models.Model):
email=models.EmailField()
fullname = models.CharField(max_length = 100)
password = models.CharField(max_length = 100)
username = models.CharField(max_length=100)
profilePic = models.CharField(max_length=100, blank=Tru... |
from Bio import SeqIO
#--------------------------------------------------------------------------------------
# compute transition/transversion ratio
# transition: A <--> G or C <--> T
# transversion: A <--> C or T ... G <--> T or C ... C <--> G or A ... T <--> G or A
def compute_tt_ratio():
s1 = str(dna_strings[0... |
from flask import g
from werkzeug.local import LocalProxy
from flask_dance.consumer import OAuth2ConsumerBlueprint
__maintainer__ = "David Baumgold <david@davidbaumgold.com>"
def make_dropbox_blueprint(
app_key=None,
app_secret=None,
*,
scope=None,
offline=False,
force_reapprove=False,
d... |
from django.shortcuts import render, redirect
from Faculty.daofaculty import Student, Course, Faculty, Module
def facultydashboard(request):
return render(request, 'Faculty/faculty_dashboard.html')
def applyleave(request):
if "emailid" in request.session:
emailid = request.session['emailid']
dao = ... |
import gitlab
import cfg
import json
gl = gitlab.Gitlab('https://gitlab.gitlab.bcs.ru', cfg.token, api_version=4)
gl.auth()
def get_working_mode():
working_mode = input('Для выбора диалогового режима нажмите Enter или укажите "f" для загрузки конфигураци из файла :')
if working_mode.lower() == 'f':
us... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret,img = cap.read()
# Operations on the captured frame
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray image',gray)
cv2.imshow('Normal image',img)
if cv2.waitKey(0):
break
... |
import copy
from collections import defaultdict
from utils import points, is_word_possible
def get_extra_letters(x):
extra_letters = defaultdict(lambda: 0)
extra_letters[x[0]] += 1
extra_letters[x[4]] += 1
return extra_letters
def get_fifth_words_by_first_and_fifth(letters, words):
multiplier =... |
#!/usr/bin/env python3
from __future__ import annotations
import re
import string
from typing import Iterator, Optional
from itertools import product, combinations
from bs4 import BeautifulSoup
import httpx
import spacy
from pathlib import Path
from pydantic import BaseModel
from itertools import chain
import uvicorn... |
#deklarasi 5 variabel
# lakukan perhitungan rata-rata 5 nilai tsb
# tampilkan hasilnya
nilai_1 = int(input('nilai ke-1 : '))
nilai_2 = int(input('nilai ke-2 : '))
nilai_3 = int(input('nilai ke-3 : '))
nilai_4 = int(input('nilai ke-4 : '))
nilai_5 = int(input('nilai ke-5 : '))
rata2 = (nilai_1 + nilai_2 ... |
#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.rindex(str2,10))
|
'''
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COPYRIGHT NOTICE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Permission is granted for anyone to copy, use, modify, or distribute the
accompanying programs and documents for any purpose, provided this copyright
notice is retained and prominently displayed, along with a complete citation of
t... |
# coding=utf-8
import os
import re
import time
import logging
import subprocess
from logging.handlers import TimedRotatingFileHandler
class LoggerUtil(object):
@classmethod
def instance(self, file_name=__name__):
logger = logging.getLogger(file_name)
logger.setLevel(logging.INFO)
fh =... |
import numpy as np
import matplotlib.pyplot as plt
# The class for plotting
class plot_diagram():
#constructor
def __init__(self, X, Y, w, stop, go =False):
start = w.data
self.error = []
self.parameter = []
self.X = X.numpy()
self.Y = Y.numpy()
self.paramet... |
n = int(input("수 입력 : "))
sum = n*(n+1)//2
print(sum)
data = 5000000*1.05
for i in range(1,4,1) : # 1 ~ 4까지 1씩 증가
data *= 1.05
print(data)
|
c = int(raw_input())
order = [(0, 'Z', 'ZERO'),
(2, 'W', 'TWO'),
(6, 'X', 'SIX'),
(8, 'G', 'EIGHT'),
(4, 'U', 'FOUR'),
(5, 'F', 'FIVE'),
(7, 'V', 'SEVEN'),
(3, 'H', 'THREE'),
(9, 'I', 'NINE'),
(1, 'O', 'ONE')]
for idx in range(c):
st... |
"""
testing orbital elements in Kepler
"""
from amuse.units import units, constants, nbody_system
from amuse.community.kepler.interface import Kepler
from amuse.datamodel import Particles
import numpy
sun_and_stone = Particles(2)
sun_and_stone[0].position = [-5.40085336308e+13, -5.92288255636e+13, 0.] | units.m
sun_... |
fin = open("complete.in", "r")
fout = open("complete.out", "w")
vertex_count, edges_count = list(map(int,fin.readline().split()))
one_count = 0
matrix =[[0] * vertex_count for i in range(vertex_count)]
for i in range(edges_count):
x, y = [int(x) for x in fin.readline().split()]
matrix[x - 1][... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QImage
import numpy as np
import cv2
import argparse
from tkinter import filedialog
from tkinter import *
image_path=""
image=None
picture=None
class search():
ap_config="yolo-obj-medical.cfg"
ap_weight="yolo-obj-medical_nonContrast... |
#Logan Passi
#10/03/2016
#SalesCommission.py
#In class exercise to create the Python implementation of a program
#to calculate sales commissions with the inclusion of advanced pay
# getSales will get the sales amount from the user
def getSales():
monthlySales = float()
monthlySales = float(input("Ente... |
"""
CP1404/CP5632 Practical
Demos of various os module examples
"""
import os
def main():
"""Demo os module functions."""
print("Starting directory is: {}".format(os.getcwd()))
# Change to desired directory
os.chdir('Lyrics/Christmas')
# Print a list of all files in current directory
print("... |
import datetime
import json
import subprocess as sp
import time
from os.path import join as path_join
from ask import askInt
import config
import utils
from log import logger
from net import get_ssh, ssh_execute, ssh_execute_async
def _get_sh_envs(file_name):
source = 'source %s' % file_name
dump = '/usr/bi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
from livereload import Server, shell
subprocess.run(['ark', 'build'])
server = Server()
cmd = shell('ark build')
server.watch('./*.py', cmd)
server.watch('./ext/**/*.py', cmd)
server.watch('./src/**/*.md', cmd)
server.watch('./src/**/**/*.md', cmd)
ser... |
import dlib
import matplotlib.pyplot as plt
import numpy as np
import cv2
import math
import os
def distances(points):
dist = []
for i in range(points.shape[0]):
for j in range(points.shape[0]):
p1 = points[i,:]
p2 = points[j,:]
dist.append( math.sqrt((p1[0] - ... |
A_length = int(input())
A = set(map(int,input().split()))
otherSetsNum = int(input())
for i in range(otherSetsNum):
line1 = input()
command = line1.split()[0]
setLenght = int(line1.split()[1])
newSet = set(map(int,input().split()))
if command == "intersection_update":
A.intersection_update... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.