text stringlengths 8 6.05M |
|---|
from equadratures import *
import numpy as np
import matplotlib.pyplot as plt
def function(x):
return 1.0/(2.0 + 16*(x[0] - 0.1)**2 + 25*(x[1] + 0.1)**2 )
def tensor():
order = 100
x1 = Parameter(lower=-1, upper=1, order=order, distribution='Uniform')
x2 = Parameter(lower=-1, upper=1, order=order, d... |
from MarkovBuilder import *
from restore import *
from itertools import *
import numpy as np
from eval import *
class MusicMatrix:
def __init__(self, order):
self.previous_state = [None for i in range(order)]
self.order = order
self.current_note_num = 0 # 记录当前输入了几个note
# 这里应该传入所有需要考... |
#!/usr/bin/env python
"""
Calculate the consecutive sum of
each digit passed in as parameter.
"""
def consecutive_sum(number):
if number // 10 < 1:
return number
return number % 10 + consecutive_sum(number // 10)
def main():
assert consecutive_sum(123456789) == 45
assert consecutive_sum(12)... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
import tweepy
from tweepy.auth import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
import socket
import json
# Set up your credentials from http://apps.twitter.com
consumer_key = '********************'
consumer_secret = '**************************************************'
acce... |
#!/usr/bin/env python
import sys
sys.path.insert(0,'../redis_')
from confluent_kafka import Consumer, KafkaError
import json
import time
from pprint import pprint
from redis_ import redisDriver
topics = ['add_build', 'delete_build', 'add_user', 'delete_user', 'add_build_component', 'remove_build_component', 'add_de... |
import time
list_1=[]
i=0
n=int(input("Enter the no of items you want to insert in the list : "))
while i <n:
element=input("Enter the element of the list :")
list_1.append(element)
i+=1
time.sleep(1)
print("Appending items in the list ...")
time.sleep(1)
print("List : ",list_1)
string_1="Appending lists"... |
from .models import OnlineCourse
from workprogramsapp.models import WorkProgram, Topic, DisciplineSection
import pandas as pd
import numpy as np
import re
import nltk; nltk.download('stopwords')
from nltk.corpus import stopwords
from pymorphy2 import MorphAnalyzer
from sklearn.feature_extraction.text import TfidfVector... |
#!/usr/bin/env python
import sys
import os
import math
import argparse
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('directory', help='path of directory to create')
parser.add_argument('dirsize', help='how many files', type=int, default=1, nargs='?')
parser.add_argument('filesize', help='fi... |
# -*- coding: utf-8 -*-
import os
import re
import cv2
import glob
import pickle
import keras
import time
import csv
import sys
import openpyxl
import numpy as np
from mlc.function import check_existfile,show,Roi_Reduction,draw_contours,load_image_from_txt,Read_Parameter
from PIL import Image,ImageDraw
... |
# Задача для самопроверки (то есть за неё не даются баллы).
# Реализуйте метод update_mini_batch класса Neuron. Когда вы решите сдать задачу, вам нужно будет просто скопировать соответствующие функции (которые вы написали в ноутбуке ) сюда. Копируем без учёта отступов; шаблон в поле ввода ответа уже будет, ориентируйт... |
import torch
import numpy as np
import os
import os.path as osp
import cv2
import pandas as pd
import time
from .base_dataset import BaseDataset
from .base_dataset import pil_loader
class Dataset(BaseDataset):
def __init__(self, args, split='train', **kwargs):
super().__init__(args)
self.data_dir... |
import pygame
from network import Network
pygame.font.init()
# Window width and height
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
class Button:
"""
To create and interface a button in pygame
"""
def __init__(self, text, x, y, color)... |
import copy
import keras as K
import numpy as np
from keras.datasets import mnist
from keras import layers
from matplotlib import pyplot
def select_real_samples(data, n):
x = data[np.random.randint(0, data.shape[0], n)]
y = np.ones((n, 1))
return x, y
def create_null_samples(n):
x = np.random.rand(28... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" CRC computation gateware for USB3. """
import unittest
import operator
import functools
from amaranth import *
from ....test import LunaSSGatewareTestCase, ss_domain_tes... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
import json
import os
import tarfile
import shutil
import subprocess
def main():
latest = latest_version()
download(latest['name'], latest['browser_download_url'])
docker_build(latest['name'])
def docker_build(file_name):
tar = tarfile.o... |
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import status, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
# import jwt
# from rest_framework_jwt.utils import jw... |
#!/usr/bin/env python
def many(name, *values):
print name, values
args = input('Gimme some juice!: ')
many(args[0], [arg for arg in args[1:]])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from models import *
@admin.register(Facility)
class FacilityAdmin(admin.ModelAdmin):
list_display = ['scraped_name', 'name','street_address', 'city', 'state', 'zip_code', 'created_by', 'mailing_address']
|
import os
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import json
from PIL import Image
def normalize(I):
I = np.copy(I)
mean = np.mean(I)
std = np.std(I)
if std:
I = (I-mean)/std
else:
I = np.ones(I.shape)
return I
def non_maximu... |
import os
from flask import Flask, render_template, jsonify, request
import json
import requests
import time
import ConfigParser
import IncidentCache
config = ConfigParser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + '/../../server.cfg')
cps_address = config.get('CPS', 'address')
subscrib... |
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]},
def put(self, todo_id):
todos[todo_id] = request.form['data']
retu... |
import json
import os
import sys
import warnings
import deepsecurity as api
from deepsecurity.rest import ApiException
def format_for_csv(line_item):
"""Converts a list into a string of comma-separated values, ending with a newline character.
:param line_item: The list of lists to convert to a string of comma... |
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from direct.directnotify import DirectNotifyGlobal
class DistributedPiratesTutorialAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPiratesTutorialAI')
def __init__(self, air):
DistributedOb... |
#this file is just a modification of an example script to interact with APIC-EM available in the cisco dev-net zone,
#adapted to be used as a function and with some slight modifications
import requests
import json
import sys
requests.packages.urllib3.disable_warnings() # Disable warnings for not verifying the SSL c... |
# Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'refs_to_shard_external_lib',
'type': 'static_library',
'dependencies': [
# Make sure references in othe... |
def main():
try:
lue = input("Syötä luettavan tiedoston nimi: ")
kirjoita = input("Syötä kirjoitettavan tiedoston nimi: ")
lukutiedosto = open(lue, "r")
kirjoitustiedosto = open(kirjoita, "w")
rivimäärä = sum(1 for line in open(lue))
rivi = lukutiedosto.readlin... |
#BAREBONE APP
from flask import flask
app = flask(__name__)
@app.route('/hello/<stringname>')
def hello(name):
return ("hello, world", 200)
#ROUTING
@app.route('/test') #default, only allow get method
@app.route('/test', method=['GET', 'POST']) #default, only allow get method
@app.route('/test', method=['PUT'])... |
import os
from django.conf import settings
DEBUG = False
TEMPLATE_DEBUG = False
DATABASES = settings.DATABASES
import dj_database_url
# Parse database configuration from $DATABASE_URL
DATABASES['default'] = dj_database_url.config()
# Allow all host headers
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
... |
# Copyright 2018 Cable Television Laboratories, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from ckeditor_uploader.fields import RichTextUploadingField
from datetime import date
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
from django.db import models
from django.utils.functional import cached_property
from django.utils.text import slugify
def user_ph... |
import os
import socket
import sys
import SocketServer
from lib.constants import *
from threading import Thread
class ThreadedSocketServerClient(Thread):
def __init__(self, server: SocketServer, conn: socket):
Thread.__init__(self)
self.daemon = True
self.server: SocketServer = server
... |
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for v in phone_numbers.values():
print(v.replace("+", "00")) |
import time
import zmq
def producer:
streamer_pull_port = 5559
context = zmq.Context()
socket = context.socket(zmq.PUSH)
#connectC to streamer PULL socket
socket.connect("tcp://127.0.0.1:%s" % streamer_pull_port)
publisher_id = random.randrange(0,9999)
#create some work
for num in range(20000):
work_message ... |
#Program on performing Addition Operation
m1 = 60
m2 = 70
m3 = 80
totmarks= m1 + m2 + m3
print("total marks are:",totmarks) |
import warnings
from torchvision.transforms._functional_pil import * # noqa
warnings.warn(
"The torchvision.transforms.functional_pil module is deprecated "
"in 0.15 and will be **removed in 0.17**. Please don't rely on it. "
"You probably just need to use APIs in "
"torchvision.transforms.functional... |
import torch, sys
import torch.nn as nn
import baseline_model_layers as bml
from transformers import BertForSequenceClassification
class BiCondLSTMModel(torch.nn.Module):
'''
Bidirectional Coniditional Encoding LSTM (Augenstein et al, 2016, EMNLP)
Single layer bidirectional LSTM where initial states are ... |
import json
from engines.ios import EngineIOS
from engines.android import EngineAndroid
from engines.ionic import EngineIonic
from managers.translator import TranslateManager
from managers.cache import CacheItem
from tabulate import tabulate
class CoreManager(object):
def __init__(self,params):
self.sav... |
from abc import ABCMeta, abstractmethod
class SignalObserver(metaclass=ABCMeta):
"""
Абстрактный суперкласс для всех наблюдателей.
"""
def __init__(self, model, plot_canvas):
self.model = model
self.model.AddObserver(self)
self.plot_canvas = plot_canvas
def UpdateModel(self... |
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
from cvpm.solver import Solver
from api_example.bundle import ApiExampleBundle as Bundle
class ImageRecognitionSolver(Solver):
def __init__(self, toml_file=None):
super().__init__(toml_file)
self.app = ClarifaiApp(api_... |
from geocode import getGeocodeLocation
import json
import httplib2
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
foursquare_client_id = "F1OAP3TOGKR1HGKPVHV44NOZXRY0XSIA45MCUEWRZ13EJW43"
foursquare_client_secret = "MQFJB1QUTLDXAW3PSYUCSEUA... |
# -*- coding: utf-8 -*-
__all__ = ['Point']
class Point(object):
def __init__(self, x, y):
super(Point, self).__init__()
self.x = x
self.y = y
def draw(self):
print 'point x:%s, y:%s' % (self.x, self.y)
|
# Parametric tapered sandwich with cohesive zone and XFEM with curvature
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from job import *
from sketch import *
from visualization import *
from conne... |
# Template Class
# as a template for file halding and such
#
from dateutil import parser
from decimal import Decimal
import pandas as pd
import time
import datetime
import csv
import os, sys
import re
class Template(object):
def __init__(self, log, **kwargs):
'''
kwargs:
... |
#!/usr/bin/env python\n
# -*- coding: utf-8 -*-
import sys
import os
import re
import sublime
import sublime_plugin
from . import sqlodbccon
from .te_sql_alias import SQLAlias
sys.path.append(os.path.join(os.path.dirname(__file__), "../libs"))
from ..libs.terminaltables.other_tables import WindowsTable as SingleTable
... |
#!/usr/bin/env python
#! -*- coding:utf-8 -*-
#!@Author: faple
#!@Time: 2019/4/1 10:59
from arcsoft_all.lib import face_dll, face_detect_sdk, face_property_sdk
from arcsoft_all.util import faceUtil
APP_ID = b'4fEUb81MxFozpgncw2k8a7ZAEArfvNGZjvvo8jZDLgkn'
SDK_KEY = b'7ewepBAnhYgQdsGyJ9aqDchQ9aZGy8U8sYdHMHehx9ps'
# App... |
import numpy as np
from sklearn.linear_model import ElasticNet
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
boston = load_boston()
X,y = mglearn.datasets.load_extended_boston()
#데이터 나누기 TRAIN, TEST
X_train , X_test , y_train , y_test = train_test_split(X,y,r... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
from pathlib import Path
OFFSET = (10, 10, 10)
SHAPE = (20, 20, 20)
PADDED_SHAPE = tuple(s + o * 2 for s, o in zip(SHAPE, OFFSET))
PAD_VALUE = 1
INTERNAL_PATH = "volume"
TEST_DIR = Path(__file__).resolve().parent
PROJECT_DIR = TEST_DIR / "tests"
|
from datetime import datetime, time, timedelta
from flask.blueprints import Blueprint
import logging
from flask.templating import render_template
from flask_login import login_required, current_user
from flask.globals import request
import flask
from werkzeug.utils import redirect
from flask.helpers import url_for
from... |
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.resource import ResourceManagementClient
resource_client = get_client_from_cli_profile(ResourceManagementClient)
resource_client.resource_groups.delete("PythonAzureExample-Storage-rg")
|
import pygame, pygame.font
from menu import *
class Score():
def __init__(self):
self.current_player_score = 0
self.current_enemy_score = 0
self.games_player_score = 0
self.games_enemy_score = 0
self.sets_player_score = 0
self.sets_enemy_score = 0
self.advan... |
#encoding:utf-8
### Calculate category probs from fasttext model and store them into dictionary
dct={}
with open('model_fasttext.txt') as file:
lines=file.readlines()
for line in lines:
lst=line.strip('\n').split('\t')
if not dct.has_key(lst[1]):
dct.setdefault(lst[1],[0,0])
... |
from django.shortcuts import render, get_object_or_404, get_list_or_404
from .models import Article, Media
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
#Displays the 10 latest article titles.
class HomeView(generic.ListView):
context_object_name = 'rec... |
# this is a psuedo code for the coloring project
import tensorflow as tf
import numpy as np
from glob import glob
import math
import sys
import random
#import the necessary packages above I think should be useful
'''
To present the nueral network, I want to create an object with methods and attributes.
... |
#! /usr/bin/env python
#coding: utf-8
import timeit
def break_rings(connections):
from collections import Counter
import itertools
remain_rings = lambda L: set(itertools.chain(*L))
remain_links = lambda r, L: [x for x in L if r not in x]
rings = remain_rings(connections)
count = 0
while Tr... |
import shutil
from datetime import datetime
import pytest
import importlib.resources
import sys
try:
import matplotlib # noqa: F401
except ImportError as e:
pytest.skip(f"Matplotlib missing {e}", allow_module_level=True)
import gemini3d.web
import gemini3d.plot
@pytest.mark.skipif(sys.version_info < (3, 8)... |
def div(a = 0, b = 0):
try:
a = int(input("Write first number: "))
b = int(input("Write second number: "))
except ValueError as val:
print("Values you've wrote are not numbers!", val)
return None
try:
result = a / b
print(round(result, 2))
return resul... |
#------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at... |
from lib.classifier import Classifier
import os
import pickle
import shutil
from sklearn.ensemble import RandomForestClassifier
class RandomForest(Classifier):
"""
A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the
data set and use averaging t... |
from typing import Any, Mapping, Optional
from .base import api_function, BaseFunction
from ..exceptions import BackendAPIError
from ..request import Request
from ..session import api_session
__all__ = (
'Admin',
)
class Admin(BaseFunction):
"""
Provides the function interface for making admin GrapQL qu... |
#!/usr/bin/env python
# pip install gitpython
# pip install pygerrit2
from git import Repo
from pygerrit2 import GerritRestAPI, HTTPBasicAuth
import os
import pprint
import re
# Configuration variables.
repo = "fuchsia"
owner = "smklein"
def minify_subject(subject):
simple_subject = subject.replace('[','_') \
... |
from __future__ import division
def defineNodes(nodes):
n = input('How many nodes? ')
for i in range(0,n):
nodes[input("Enter unique name for node " + str(i+1) + ": ")] = {}
for k in nodes.keys():
nodes[k]['LinkedTo'] = [] # establishes node as a hub point
nodes[k]['HubScor... |
import math
segundos = int(input("Digite o tempo em segundos: "))
horas = math.floor(segundos/3600)
segundos = segundos%3600
minutos = math.floor(segundos/60)
segundos = segundos % 60
print(str(horas)+":"+str(minutos)+":"+str(segundos))
|
# Copyright (c) 2016-2017 Adobe Systems Incorporated. All rights reserved.
#
# 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... |
#! usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from xml.etree import ElementTree as ET
from flask import render_template
from urllib import urlopen
from json import loads
app = Flask(__name__)
@app.route('/weixin', methods=['GET', 'POST'])
def wechat():
# 接收和返回G... |
with open ('dataset_3363_4.txt') as file:
m = []
f = []
r = []
for line in file:
s1 = line.strip().split(';')
m.append(int(s1[1]))
f.append(int(s1[2]))
r.append(int(s1[3]))
print((int(s1[1]) + int(s1[2]) + int(s1[3]))/3)
print(sum(m) / len(m), sum(f) / len(f),... |
import hello
if __name__ == '__main__':
a = hello.A()
a.f2() |
def train (bayes, item, cat):
wordlist = bayes.get_features(item)
if cat not in bayes.class_count:
bayes.class_count[cat] = 0
bayes.class_count[cat] += 1
for word in wordlist:
if (word,cat) not in bayes.feature_count:
bayes.feature_count [(word, cat)] = 0
bayes.featur... |
#!/usr/bin/env python
# coding: utf-8
### Author: zss
### Date: 2018.7.16
## For: 16S Analysis ###
import ConfigParser
import sys
import os
import commands
if len(sys.argv) != 2:
print "\n\t\tUsage: python %s 16S_Analysis.conf\n" % sys.argv[0]
sys.exit(1)
ConfgFile = sys.argv[1]
Config = ConfigParser.Config... |
class Demo:
def __init__(self, v1=11, v2=22):
self.__a = v1
self.__b = v2
def do_something(self):
return self.__a + self.__b
if __name__ == "__main__":
d = Demo(12, 34)
print(d.do_something())
# 檔名: class_demo9.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
from django.urls import path
from .views import (
home,
delete,
update,
cross,
uncross
)
app_name = 'core'
urlpatterns = [
path('', home.as_view(), name='home'),
path('delete/<str:pk>/', delete, name='delete'),
path('update/<str:pk>/', update, name='update'),
path('cross/<str:pk>/',... |
from django.urls import path, re_path
from api.views.v1 import views
from api.controllers.v1.addressbook import add_person, address_book, search_person, delete, edit, add_mobile, add_email, \
add_address
urlpatterns = [
path('health/', views.health, name='health'),
path('health-secure/', views.health_secur... |
# Generated by Django 2.2.3 on 2020-09-13 11:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('reviewapp', '0011_delete_ratingevaluationstring'),
]
operations = [
migrations.CreateModel(
nam... |
################################################################################
# #
# MHD MODES CONVERGENCE PLOTS #
# ... |
import requests
import datetime
from collections import *
get_price_btc_ts = 0
get_price_btc_price = 0
def get_price_btc():
#增加缓存,同一秒钟内只获取一次价格
global get_price_btc_ts, get_price_btc_price
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if timestamp == get_price_btc_ts:
... |
# Author: Yinsen Miao
import pandas as pd
import numpy as np
import os
import random
import matplotlib.pyplot as plt
import lightgbm
from sklearn.metrics import mean_squared_error
from scipy.stats import pearsonr
from math import sqrt
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import s... |
name = input("What is your name : ")
print("Wellcome "+name+" in the python course") |
# Author: Jyotika Bahuguna: -j.bahuguna@fz-juelich.de
from NeuroTools.parameters import ParameterSet
from NeuroTools.parameters import ParameterRange
from NeuroTools.parameters import ParameterTable
from NeuroTools.parameters import ParameterSpace
import NeuroTools.signals as signal
import numpy,shelve,pylab,os
def... |
def TwoSum(my_list,target):
output=[]
for i in range(0,len(my_list)):
for j in range(1+i,len(my_list)):
tot=my_list[i]+my_list[j]
if tot==target:
output.append(i)
output.append(j)
return output
if len(output)==0:
output... |
import numpy as np
import cv2
IMAGE_HEIGHT=66
IMAGE_WIDTH=200
def clahe_image(image):
yuv_img = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
clahe = cv2.createCLAHE(clipLimit=5.0, tileGridSize=(4,4))
yuv_img[:,:,2]= clahe.apply(yuv_img[:,:,2])
n_img = cv2.cvtColor(yuv_img,cv2.COLOR_HSV2RGB)
return n_img... |
# Exercício 2.1 - Livro
print(10 + 20 * 30)
print(4 ** (1/2) / 30)
print((9 ** (1/4)) * 6 - 1)
|
import base64
import json
import logging
import requests
import jwt
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
from jwt.exceptions import InvalidTokenError
_default_options = {
"verify_signature": True,
"verify_exp": True,
"verify_nbf":... |
def CtoF(input_celsius):
return input_celsius * 1.8 + 32
def FtoC(input_fahrenheit):
return (input_fahrenheit - 32) / 1.8
c_or_f = input("What type of number do you want to convert? (Type C or F)")
if c_or_f.lower() == 'c':
print(int(CtoF(float(input("Enter a temperature in celsius: ")))))
elif c_or_f.lower() ... |
#!/usr/bin/env python3
import os
from ..lib import utils, doc_utils
'''
desc: infomation of linux
per-function infomation in Linux Core API page
- basic description, Parameters, Description, Note, Context, Return
concern: may have some absent situations
'''
def preprocess_linux_apidoc(info, preprocess... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis"
# Import libraries
import os
import numpy as np
from gaussian_color import *
from train_color import *
from util import *
from sklearn import metrics
# Highway sequences configuration, range 1050 - 1350
highway_pat... |
from django.contrib import admin
from .models import *
# Register your models here.
# Register your models here.
class Analyse_FFAdmin(admin.ModelAdmin):
list_display = ("ig_user","instagram_account","follower_update_time","following_update_time")
admin.site.register(Analyse_FF,Analyse_FFAdmin)
class Instagram... |
print(1, 2,3,4)
print("a" + "b" + "c"+ "d")
# '%' Formating
print("%d %d %d" %(1, 2, 3))
print("%s %s" % ("1","2"))
# str.format
age = 36;
print("I'm {0} years old." .format(age))
#padding 여유공간을 지정하여 배열 + 소수점 자리수 맞추기
print("Priduct: %5s, Price per unit: %.5f." %("apple", 5.243))
#naming
print("Product: %(name)... |
#!/usr/bin/python3
"""
Copyright (c) 2015, Joshua Saxe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of con... |
import os
import random
import logging
import torch
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel
import numpy as np
from apex import amp
from typing import Dict
# pylint:disable=no-member
logger = logging.getLogger(__name__)
def set_seed(config):
random.seed(config.seed)
np.ra... |
from Jumpscale import j
import netaddr
def chat(bot):
"""
"""
user_info = bot.user_info()
name = user_info["username"]
email = user_info["email"]
ips = ["IPv6", "IPv4"]
env = dict()
expiration = j.data.time.epoch + (60 * 60 * 24) # for one day
explorer = j.clients.explorer.explor... |
# Generated by Django 2.2.11 on 2021-07-17 15:11
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('facility', '0265_auto_20210712_1133'),
]
operations = [
migrations.AlterField(
model_name='dailyr... |
# Manually start the process of making markdown gallery.
import datetime, glob, os, sys
import gallery_to_markdown as output_format
THUMBNAIL_PREFIX = 't_'
THUMBNAILS_DIR = 't'
EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif']
IMAGE_TYPE = {
'.jpg': 'JPEG',
'.jpeg': 'JPEG',
'.gif': 'GIF',
'.png': 'PNG'
... |
# Dummy GUI just printing date + current temp to the stdout
from mqtt_client import MQTT_Client
from hbmqtt.mqtt.constants import QOS_1
import asyncio
import tkinter as Tk
# Configuration of TOPICS and addresses
from config import *
# For exception handeling
import sys
# Just a variable used for conditional debuggi... |
# -*- coding: utf-8 -*-
import scrapy
import labsql
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
from threading import Thread
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCP... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
"""
クローリングを説明するための最小限のコードを書く
"""
import re
import requests
import time
import random
# クローリングを開始するURL
start_url = "https://goworkship.com/magazine/"
# サイト管理者に分かるよう自身の連絡先などをUser-Agentに記載する
headers = {
'User-Agent': 'sig-Bot/1.0 (@sig_Left: https://twitter.com/sig_Left)'
}
# アクセスするURL(初期値はクローリングを開始するURL)
url ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 03/02/2018 3:09 PM
# @Author : Lee
# @File : quick_sort_3_ways.py
# @Software: PyCharm
import random
from utils.common import swap
from utils.sort_test_helper import SortTestHelper
class QuickSort3Ways(object):
@classmethod
def sort(cls, lists,... |
# Problems : Candy
# Description : There are N children standing in a line. Each child is assigned a rating value.
# You are giving candies to these children subjected to the following requirements:
# Each child must have at least one candy.
# Children with a higher rating get more candies than their n... |
from torchvision import datasets, transforms
from torchtext import datasets as textdata
from torchtext import data
from torchtext.vocab import GloVe
from PIL import Image
from .usps import USPS
from . import caltech_ucsd_birds
from . import pascal_voc
import os
import contextlib
import numpy as np
import torch
from col... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.