text stringlengths 38 1.54M |
|---|
lista = []
class Individual (object):
def __init__(self, genotype, accuracy):
self.genotype = genotype
self.accuracy = accuracy
def __repr__(self):
return str(self.genotype) + ":" + str(self.accuracy) + "\n"
ind = Individual([1,23,4],0.3)
lista.append(ind)
ind = Individual([1,... |
###############################################################################
# $Id$
#
# Project: Sub1 project of IRRI
# Purpose: Quality Assessment extraction from MODIS
# Author: Yann Chemin, <yann.chemin@gmail.com>
#
###############################################################################
# Copyright (c... |
### Rocket Dashboard version 0.1 -- Andrew R Gross -- 2020-10-29
from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
ap... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C11_cff import Phase2C11
from Configuration.ProcessModifiers.dd4hep_cff import dd4hep
Phase2C11_dd4hep = cms.ModifierChain(Phase2C11, dd4hep)
|
from bs4 import BeautifulSoup
import requests
import re
from get_contaminent_details1 import get_contaminent_details
from pprint import pprint
def assign_data(contam_name, contam_data):
"""given the name of a contamination and the data for it, assign by dict values
contam_name: str
contam_data: list
"... |
import numpy as np
import json
import Plots
import SpiralMapping
def analog_generator(filename, CSNR, symbols, alpha, sigma):
rxSignal_aux = np.zeros((len(CSNR), symbols))
rxSignal_ML_aux = np.zeros((len(CSNR), symbols))
gamma = np.zeros(len(CSNR))
delta = np.zeros(len(CSNR))
txSignal = np.zeros(... |
import tkinter as tool
from tkinter import filedialog
import pyautogui
root=tool.Tk()
canvas1=tool.Canvas(root,width=300,height=300)
canvas1.pack()
def takeScreenshot ():
screenshot = pyautogui.screenshot()
file_path=filedialog.asksaveasfilename(defaultextension='.png')
# file_path=filedialog.asksaveasfi... |
import requests, time
import sikhgenerator
request = {'token' : '[redacted]'}
while True:
response = requests.get('https://api.groupme.com/v3/groups/27409006/messages', params=request)
if(response.status_code == 200):
messages = response.json()['response']['messages']
for m in messages:
if(m['text'] ... |
from injector import Module, Injector, inject, singleton
from flask import Flask, Request, jsonify
from flask_injector import FlaskInjector
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import Column, String
... |
# Generated by Django 3.1.5 on 2021-02-01 06:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0057_auto_20210201_0655'),
]
operations = [
migrations.AlterModelOptions(
name='application',
options={'o... |
#!/usr/bin/env python3
from sys import argv, stdin
if __name__ == '__main__':
if len(argv) == 2:
iterator = stdin
squareSize = int(argv[1])
else:
filename = argv[1]
squareSize = int(argv[2])
if filename == "-" :
iterator = stdin
else:
iter... |
from django.contrib import admin
from .models import (
User, AuctionListing, Bid, Comment, Category, Watchlist, WinnerList
)
# Register your models here.
admin.site.site_header = "CS50 Project2 Dashboard"
admin.site.site_title = "CS50 Project2 Dashboard"
admin.site.index_title = "Auctions Dashboard"
class UserAd... |
import random
import requests
import json
class MyRequests:
get_time_url = "http://s-kv-center-v20:44330/api/FreeTime?FilialId=1998&TicketToken=ODNjMjVhYTgyMmRlN2NmYjNjNDViNjIxNWZlYjMzYWE6eyJpZCI6MzV9"
get_lagers_url = "http://s-kv-center-v20:44330/api/Lager?filialId=2382&ticketToken=56"
create_lagers_in... |
# -*- coding: utf-8 -*-
"""
validator handlers boolean module.
"""
from pyrin.core.globals import _
from pyrin.validator.handlers.base import ValidatorBase
from pyrin.validator.handlers.exceptions import ValueIsNotBooleanError
class BooleanValidator(ValidatorBase):
"""
boolean validator class.
"""
i... |
# ************************************* BANK_APPLICATION **********************************
import ast
class Bank:
def __init__(self):
pass
# User login Function/method
def signin(self):
account_id = input(" Enter Your ID/Name ")
account_pwd = str(input(" Enter Your passwor... |
#!/usr/bin/python
#-*-coding:utf-8-*-
#(40)(39)で構築したデータベースを読み込み,標準入力から読み込んだ文の生起確率を計算せよ.
#入力された文が単語列(w1, w2, ..., wN)で構成されるとき,生起確率はP(w2|w1)P(w3|w2)...P(wN|wN-1)と求めればよい.
#試しに,"this paper is organized as follows"と"is this paper organized as follows"の生起確率を計算せよ.
import kyotocabinet as kc
import sys
from test39 import Kyoto... |
# Import the pyautogui library; will need to install it with pip (python package manager)
import pyautogui
# Get position of the chrome icon on the launcher
chromeX = 690
chromeY = 873
# Move the mouse to the position of the chrome icon and click it; make it take 2 seconds
pyautogui.moveTo(chromeX, chromeY, 2)
pyauto... |
## Taken from yt/fields/xray_emission_fields.py
## https://yt-project.org/doc/analyzing/analysis_modules/xray_emission_fields.html#
from yt.utilities.on_demand_imports import _h5py as h5py
import numpy as np
import os
from yt.config import ytcfg
from yt.fields.derived_field import DerivedField
from yt.funcs import \
... |
import random
class Node(object):
def __init__(self, key, level):
self.key = key
self.forward = [None]*(level+1)
class SkipList(object):
def __init__(self, max_lvl, P):
self.MAXLVL = max_lvl
self.P = P
self.header = self.createNode(self.MAXLVL, -1)
s... |
from rest_framework import generics
from . import serializers
from Drives import models
class ListDrivers(generics.ListAPIView):
queryset = models.Driver.objects.all()
serializer_class = serializers.DriverSerializer
class ListVehicle(generics.ListAPIView):
queryset = models.Vehicle.objects.all()
ser... |
# -*- coding: utf-8 -*-
import scrapy
from foodmate.items import FoodmateItem
import re
from lxml import html
import time
import copy
class YingyangSpider(scrapy.Spider):
name = 'yingyang'
allowed_domains = ['foodmate.net']
start_urls = ["http://db.foodmate.net/yingyang"]
def parse(self, response):
... |
from imagepy.core.engine import Free
from imagepy import IPy
import platform
import subprocess
import json
import wx
from imagepy.ui.panelconfig import ParaDialog
from imagepy.core.util import fileio
import os
class Plugin(Free):
title = 'DeepClas4BioPy'
model = ''
framework = ''
python... |
from typing import Any, Dict, Iterable, Optional
import numpy as np
import torch
from torch import nn
from autoPyTorch.constants import CLASSIFICATION_TASKS, STRING_TO_TASK_TYPES
from autoPyTorch.pipeline.components.setup.forecasting_target_scaling.base_target_scaler import BaseTargetScaler
from autoPyTorch.pipeline... |
# The MIT License
#
# Copyright (c) 2009 John Schember <john@nachtimwald.com>
#
# 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
# ... |
#!/usr/bin/env python2
"""
Thin layer chromatography spot segmentation & quantification.
"""
# Need matplotlib for saving image
import matplotlib
import matplotlib.pyplot as plt
# Import other Python libraries we use
import argparse
from collections import defaultdict
from sys import stdout
from glob import glob
... |
import math as m
D=100
LB=-1
UB=1
def FitnessFunction(x):
s=0
p=0
q=0
for i in range(1,D-1):
a=x[i-1]*m.sin(x[i])+m.sin(x[i+1])
b=((x[i-1]**2)-2*x[i]+3*x[i+1]-m.cos(x[i])+1)
p = p + (20 * i * (m.sin(a) ** 2))
q = q + (i * m.log10(1 + i * (b ** 2)))
for i in range(0,D)... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('crimeapp', '0004_rides'),
]
operations = [
migrations.CreateModel(
name='Crimes',
fields=[
... |
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import numpy as np
import pandas as pd
import config
def sendEmail(df, email, passwordy, errors_and_warnings, program_emails):
emails_not_found = []
# Create a list of all of the program names from df
p... |
# Copyright 2021 Hathor Labs
#
# 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 agreed to in writing, s... |
chords_to_notes_mappings = {
"A": ['A', 'B', 'C#', 'D', 'E', 'F#', 'G#', 'A'],
"A#": ['A#', 'C', 'D', 'D#', 'F', 'G', 'A', 'A#'],
"B": ['B', 'C#', 'D#', 'E', 'F#', 'G#', 'A#', 'B'],
"C": ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
"C#": ['C#', 'D#', 'F', 'F#', 'G#', 'A#', 'C', 'C#'],
"D": ['D', 'E', 'F... |
import sys
import string
import re
import math
if len(sys.argv) == 1:
print " #Successes, #Trials, #Probability of Success"
print " #Successes - an integer or the letter X"
#print sys.argv[1]
#print sys.argv[2]
#print sys.argv[3]
if sys.argv[1].isdigit():
r = int(sys.argv[1])
elif sys.argv[1].upp... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User_SW(db.Model):
__tablename__ = 'user_sw'
id_user = db.Column(db.Integer, primary_key=True)
name_user = db.Column(db.String(250), nullable=False)
password = db.Column(db.String(250), nullable=False)
email_user = db.Column(db.Strin... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-08-06 13:15
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re
class Migration(migration... |
import numpy as np
import datarobot as dr
from AE_ts_model import open_data
import pandas as pd
"""Load the data"""
X_train, X_val, y_train, y_val = open_data('./UCR_TS_Archive_2015')
X_train, X_train_out = X_train[:, :-1], X_train[:, -1]
X_val, X_val_out = X_val[:, :-1], X_val[:, -1]
N = X_train.shape[0]
Nval = X_va... |
import numpy as np
import scipy as sp
from quaternion import from_rotation_matrix, quaternion
from rlbench.environment import Environment
from rlbench.action_modes import ArmActionMode, ActionMode
from rlbench.observation_config import ObservationConfig
from rlbench.tasks import *
from pyrep.const import ConfigurationP... |
'''
查詢歷史資料 範例
https://rate.bot.com.tw/xrt/all/2023-03-20
'''
import requests
from bs4 import BeautifulSoup
def get_html_data1(url):
print('取得網頁資料: ', url)
resp = requests.get(url)
# 檢查 HTTP 回應碼是否為 requests.codes.ok(200)
if resp.status_code != requests.codes.ok:
print('讀取網頁資料錯誤, url: ', resp.u... |
import pygame
import colors
class button(pygame.sprite.Sprite):
def __init__(self, game, pos,**kwargs):
self.game = game
self.onClick = False
self.groups = []
self.rect = (0, 0, 200, 60)
# Normal Selected
self.colors = ((50, 255, 255), (25... |
#!/usr/bin/env python
import rospy
import numpy as np
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
def callback(msg):
marker.pose.position.x = msg.z
marker.pose.position.y = -msg.x
marker.pose.position.z = -msg.y
mypub.publish(marker)
rospy.init_node("pong_pong_marke... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
local_min = float('inf')
answer = 0
for price in prices:
if local_min > price:
local_min = price
answer = max(answer, price - local_min)
return answer |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import OccupancyGrid
from std_msgs.msg import Int16
from geometry_msgs.msg import Twist
from compressed_image_transport import *
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
from tf2_msgs.msg import TFMessage
import tf
import math
import c... |
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib import animation
def make_animation1d(x, y, y_, E, optimizer, xlim, ylim, answer, print_error=True, epoch_per_frame=1, **kwargs):
train_x = np.squeeze(x.get_result())
train_y = np.squeeze(y.get_result... |
import logging
import click
from pypgatk.cgenomes.cosmic_downloader import CosmicDownloadService
from pypgatk.toolbox.general import read_yaml_from_file
log = logging.getLogger(__name__)
@click.command('cosmic-downloader', short_help='Command to download the cosmic mutation database')
@click.option('-c', '--confi... |
from porc import Client
client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')
# make sure our API key works
client.ping().raise_for_status()
zipcode = client.get('income', 97229)
print(zipcode['median']) |
import random
import uuid
# Zadanie 1
laws_of_robotics = [
'A robot may not injure a human being or, through inaction, allow a human being to come to harm.',
'A robot must obey the orders given it by human beings except where such orders would conflict with the First Law.',
'A robot must protect its... |
from envparse import Env
from jinja2 import Environment, FileSystemLoader
template_env = Environment(loader=FileSystemLoader('/usr/local/docker'))
template = template_env.get_template('default.conf.j2')
env = Env()
context = {
'NGINX_DEV': env.bool('NGINX_DEV', default=False),
'NGINX_ENABLE_PROXY_HEADERS': ... |
import logging
import os
import time
from urllib.parse import urljoin
from django.conf import settings
from django.core.cache import cache
from django.http import JsonResponse
from common import utils, errors, config
from libs.http import render_json
from user import logic
from user.forms import ProfileForm
from user... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import os
import xml.etree.ElementTree as xml
import cv2
from . import common as com
from .wbia_object import IBEIS_Object
class IBEIS_Image(object): # NOQA
def __init__(ibsi, filename_xml, absolute_dataset_path, **kwargs):
with open(filename_x... |
from io import open
import re
from setuptools import setup, find_packages
def find_version(pth):
with open(pth, encoding='utf8') as f:
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
f.read(), re.M
)
if version_match:
return version_match.group... |
nota=float(input("digite a nota"))
mensagem=input("mensagem")
acrescimo=10/100*nota
if (mensagem.upper()=="S"):
resposta=nota+acrescimo
else:
resposta=nota
print(resposta) |
import requests
data = {
'data1': 'XXXXX',
'data2': 'XXXXX'
}
url = 'xxx'
# Requests:data为dict,json
response = requests.post(url=url, data=data) |
from pyshorteners import Shortener
import webbrowser
import clipboard
import time
import tinyurl
import urllib2
#------------------------HELPER UTILITIES--------------------
def getOnlyQRCode(shortened_url):
url = "http://chart.apis.google.com/chart?cht=qr&chl={}&chs=120x120".format(shortened_url)
print "\n\tQRCode... |
#!/usr/bin/env python
import argparse
import messagebird
from messagebird.conversation_message import MESSAGE_TYPE_TEXT
parser = argparse.ArgumentParser()
parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True)
parser.add_argument('--channelId', help='channel that you want to... |
from __future__ import annotations
from sympy.core import Basic
from sympy import Matrix, Symbol, sympify, ones
from typing import Tuple, Union
from copy import deepcopy
from functools import cmp_to_key
import re
from ._methods import (
_cartan_matrix,
_cocartan_matrix,
_quadratic_form,
_reflection_ma... |
"""
Author: Tyson Bradford
Assignment: Checkpoint 1
"""
"""
When you physically exercise to strengthen your heart, you
should maintain your heart rate within a range for at least 20
minutes. To find that range, subtract your age from 220. This
difference is your maximum heart rate per minute. Your heart
simply will no... |
# basicAnimationDemo2.py
# version 0.5
# Barebones timer, mouse, and keyboard events
# without (much) event-based programming or (much) object-oriented programming
# To run this, you need to download basicAnimation.py
# and save that file in the same folder as this one.
from Tkinter import *
from basicAnimation impo... |
import argparse
import h5py
import numpy as np
from geodesic import GeodesicDistanceComputation
def main(input_animation_file, output_sploc_file):
with h5py.File(input_animation_file, 'r') as f:
verts = f['verts'].value.astype(np.float)
tris = f['tris'].value
N, _ = verts.shape
compute_dis... |
# -*- encoding: utf-8 -*-
import urllib.request
from urllib.parse import urlencode
import json
import sys
import importlib
importlib.reload(sys)
appid = 'wxb596c90e795d46b3'
secret = 'f6bc8c361cb46bd8b4dc227ad01e3201'
gettoken = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid +... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure(figsize=(15,5))
ax = plt.subplot2grid((1,4),(0, 0))
ax.set_xlim(-0.5,0.5)
ax.set_ylim(-2,2)
spine, = ax.plot([], [], lw=2)
left_arm, = ax.plot([], [], lw=2)
right_arm, = ax.plot([], [], lw=2)
... |
# -*- coding: utf-8 -*-
import psycopg2, psycopg2.extras
import urllib2
import ConfigParser
from string import join
import os
from time import sleep
class loadtables():
def conect(self):
thisfolder = os.path.dirname(os.path.abspath(__file__))
initfile = os.path.join(thisfolder, 'config.ini')
... |
import configparser
import glob
import inspect
import logging
import os
import pprint
import sys
import unittest
from itertools import takewhile, dropwhile
from pathlib import Path
from securify.solidity import compile_cfg
from securify.staticanalysis import static_analysis
from securify.__main__ import fix_pragma
US... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 7 13:03:11 2017
@author: bgris
"""
import numpy as np
import structured_vector_fields as struct
import cmath
import group
class function_2D_scalingdisplacement():
def __init__(self, space, kernel):
self.space = space
self.uns... |
#August Challenge 2020
import math
try:
def getScore(finalPower):
if finalPower%9==0:
return finalPower/9
else:
return math.floor(finalPower/9)+1
def declareWinner(ChefScore,RickScore):
if RickScore>ChefScore:
print("0",int(ChefScore))
else:
print("1",int(RickScore))
Test... |
查找和替换模式
class Solution:
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
a = []
len1 = len(set(pattern))
for i in words:
dic = {}
flag = True
... |
'''
Simple python cache system.
Example usage:
import json
from chainedcache import DictCache, FileCache, S3Cache, ChainedCache
json2bytes = lambda d: json.dumps(d).encode('UTF-8')
bytes2json = lambda d: json.loads(d.decode('UTF-8'))
stream2json = lambda d: json.load(d)
dict_cache = DictCach... |
from import_export import resources
from .models import Visitor,Visit
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
class VisitorResource(resources.ModelResource):
class Meta:
model = Visitor
class VisitResource(resources.ModelResource):
cellphone = Field(
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
File: level14.py
Author: rshen <anticlockwise5@gmail.com>
Description: The Python Challenge Level 14 (Walk Around): http://www.pythonchallenge.com/pc/return/italy.html
'''
import urllib
import Image
img_url = "http://huge:file@www.pythonchallenge.com/pc/return/wire.png"
... |
with open(r'd:\Projects\ExperisAcademy\Exercises\IO\redwood-data.txt', 'r') as input_file:
next(input_file)
next(input_file)
tree_data = []
current_ind = highest_ind = highest_height = biggest_ind = biggest_diameter = 0
for line in input_file:
cols = [col.strip() for col in line.split(... |
# -*- coding: utf-8 -*-
#
# Test all end points are working as expected
#
# :copyright: 2023 Sonu Kumar
# :license: BSD-3-Clause
#
import unittest
import pyquery
from django.test import TestCase
from util import TestBase
from django.conf import settings
from error_tracker.django.models import ErrorModel
cl... |
travel = ['Jerusalem', 'Hong Kong', 'Singapore', 'Disney World', 'Silicon Valley']
print(travel)
print(sorted(travel))
print(travel)
print(sorted(travel, reverse=True))
print(travel)
travel.reverse()
print(travel)
travel.reverse()
print(travel)
travel.sort()
print(travel)
travel.sort(reverse=True) |
#!/usr/bin/python
#########################
# python script 21
########################
from os import system
#defining a class
class Class_name():
def function1(self):
system("ls -ltr & df -h & ./dict_to_json.py")
#creating a object
class_object = Class_name()
#calling a def in class
class_object.function1... |
class Car:
def __init__(self, streets):
self.streets = streets
self.num_streets = len(streets)
self.next_street = 0
self.time_to_intersection = 0
self.finish_time = None
# add to first intersection
self.streets[self.next_street].queue.append(self)
def __str__(self):
return(f"""
... |
#you will need the following library
#First we import SpeechToTextV1 from ibm_watson.For more information on the API,
from ibm_watson import SpeechToTextV1
import json
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import wget as wg
#The service endpoint is based on the location of the service instance... |
from django.db import models
class AuditFieldBasic(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
|
# ~ STATES
# ----------------------------------
START = "start"
INFO = "info"
CANCEL = "cancel"
# > CONSTANTES PARA CATEGORIA DE MOTOS
NAKED = "naked"
SCOOTER = "scooter"
CRUCERO = "crucero"
CHOOPER = "chooper"
CUSTOM = "custom"
SIDECAR = "sidecar"
TOURING = "touring"
RACER = "racer"
TRIAL = "trial"
SHOW_MOTO_NAKE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
f = open('hotel_daily.csv')
f2 = open('hotel_predict','w')
st = f.readline()
f2.write('id,hotel_id,the_date,dayofweek,total_need_money\n')
while st:
st = f.readline()
if st:
st = st.strip('\n').split(',')
the_date = '2016-7-1'
dayofweek = '星期五'
s = [st[0],st[1],t... |
# -*- coding: utf-8 -*-
"""
Created on Wens Jul 4 20:16:28 2018
@author: boston
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import MagDipole as md
import MagLoops as ml
import Moment as mm
'''
图形界面输入自定义数据:
define
线圈:电流:20 半径:0.25 位置:(0,0,1) 频率:1000
物体:形状:s... |
import datetime
import json
from json import JSONDecodeError
from django.conf import settings
from django.contrib.postgres.search import TrigramSimilarity
from django.db import models
from django.db.models import Case, When
from django.db.models.query_utils import Q
from django_filters import rest_framework as filters... |
from .db import db
import datetime
class Pad(db.Model):
__tablename__ = 'pads'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
color = db.Column(db.String(64), default='#AFB1D4')
multiplier = db.Column(db.Integer, default=1)
block_seq = db.Colum... |
#!/usr/bin/env python
# coding=utf-8
import codecs
import sys
#only for query
#the node class
class edge():
def __init__(self):
self.words = 0
self.prefix = 0
self.sons = {} #use dictionary, hash map faster
def addWord(self,word):
if word == '':
self.words = self.words+1
else:
self.prefix = self... |
import argparse
def get_argument():
parser = argparse.ArgumentParser()
# Directory option
parser.add_argument("--checkpoints", type=str, default="../../checkpoints/")
parser.add_argument("--data_root", type=str, default="../../data/")
parser.add_argument("--device", type=str, default="cuda")
... |
import json
import time
import requests
import datetime
import numpy as np
from PIL import Image
from io import BytesIO
import tensorflow as tf
from azureml.core.model import Model
def init():
global model
try:
model_path = Model.get_model_path('tacosandburritos')
except:
model_path = '/m... |
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
zigzag font means there are
always a column full of chars,
then numRows-2 diagonal chars
then again a column full of chars
then again numRo... |
"""
Tests for some application-specific db invariants
"""
import itertools
from sqlalchemy import func, or_, and_, literal, union_all, select, true
from sqlalchemy import orm
from clld.db.meta import DBSession
from clld.db.models import Config, Language, LanguageIdentifier, Identifier, ValueSet
from glottolog3.model... |
# coding: utf-8
# In[11]:
import cv2
import numpy as np
vc = cv2.VideoCapture(0)
pic_no = 0
total_pic = 1200
flag_capturing = False
path = './dataset/Y'
while(vc.isOpened()):
# read image
rval, frame = vc.read()
frame = cv2.flip(frame, 1)
# get hand data from the rectangle sub window on the sc... |
import FWCore.ParameterSet.Config as cms
# Geometry for simulation
from Geometry.ForwardCommonData.totemTest2021XML_cfi import *
from Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cff import *
from Geometry.EcalCommonData.ecalSimulationParameters_cff import *
from Geometry.HcalCommonData.hcalDDConstants_cf... |
import struct
import string
from .utils import chunkify, rchunkify, int_to_byte, byte_to_int
# chr(x) - int to single char
# bin(x) - int to bin repr
# ba = bytearray()
# ba.append(num) (num <= 255)
# ba.extend(b'\x01\x02\x03')
_static_table = (
(':authority', ''),
(':method', 'GET'),
(':method', 'POST'... |
# Generated by Django 2.1.4 on 2019-01-14 15:04
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quote', '0004_auto_20190114_1242'),
]
operations = [
migrations.AlterField(
model_na... |
import config
class Wall:
def __init__(self, grid):
self.rows = grid.rows
self.cols = grid.cols
for i in range(self.rows):
for j in range(self.cols):
if i in [0, self.rows-1] or j in [0, self.cols-1]:
grid.matrix[i][j] = 'wall'
for i ... |
from subprocess import Popen, PIPE
from crm import app
@app.cli.command()
def generate_graphql_docs():
"""
Generates schema.graphql IDL file and the GraphQL API documentation for queries and mutations.
requires graphdoc to be installed.
"""
from crm import app
sc = app.graphql_schema
w... |
from bs4 import BeautifulSoup
from email.mime.text import MIMEText
from email.header import Header
import urllib.request
import json
import smtplib
import datetime
import locale
locale.setlocale(locale.LC_ALL)
today = datetime.date.today()
tarih1=""
tarih2=""
tarih3=""
eskitarih1=""
eskitarih2=""
eskitarih3=""
mail_1... |
class Authentication(object):
def __init__(self, request, response):
self.request = request
self.response = response
#
#
def login(self):
return 'Authentication.Login'
#
#
def logout(self):
return 'Authentication.Logout'
#
#
def callback(se... |
from django.conf import settings
from django.db import models
class Follower(models.Model):
"""Модель подписчиков"""
user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='owner')
subscriber=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='su... |
import math
shape = input()
area = 0.0
if shape == "square":
a = float(input())
area = a * a
elif shape == "rectangle":
a = float(input())
b = float(input())
area = a * b
elif shape == "circle":
r = float(input())
area = r * r * math.pi
elif shape == "triangle":
a = float(input())
... |
from __future__ import division
pazartesi = "(1) pazartesi"
sali = "(2) sali"
carsamba = "(3) carsamba"
persembe = "(4) persembe"
cuma = "(5) cuma"
cumartesi = "(6) cumartesi"
pazar = "(7) pazar"
isim = raw_input("isiminiz")
print pazartesi, sali, carsamba, persembe, cuma, cumartesi, pazar
soru = raw_input("hangi gu... |
from BrythonAnimation import BrythonAnimation
import browser
def rgbString(r, g, b):
if not(0 <= r < 256 and 0 <= g < 256 and 0 <= b < 256):
return "#000000"
r = "{0:x}".format(r)
if (len(r) == 1): r = "0" + r
g = "{0:x}".format(g)
if (len(g) == 1): g = "0" + g
b = "{0:x}".format(b)
... |
"""0MQ Frame pure Python methods."""
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
import zmq
from zmq.backend import Frame as FrameBase
from .attrsettr import AttributeSetter
def _draft(v, feature):
zmq.error._check_version(v, feature)
if not zmq.DRAFT_API:
... |
import json
import cherrypy
class notesController:
def __init__(self, notesdb):
self.notesdb = notesdb
# create a new note
def POST_NOTE(self):
msg = json.loads(cherrypy.request.body.read())
self.notesdb.add_note(msg)
return json.dumps({"result": "success"})
# get existing notes
def GET_NOTES(self):
n... |
#!/usr/bin/python
'''
filter MulTiXcan and PrediXcan WB rm bad map results Mappability>0.8 and no cross-mappability between pairs
to also rm likely false positives based on NCBI gene summaries
grep retro, pseudogene, or paralog
needed for Table 1 tested count and Fig 2 QQ plot
'''
import gzip
import sys
import argpars... |
# A child is playing a cloud hopping game. In this game, there are sequentially numbered clouds that can be thunderheads or cumulus clouds. The character must jump from cloud to cloud until it reaches the start again.
# There is an array of clouds, c and an energy level e = 100 . The character starts from c[0] and us... |
import torch
import torch.nn as nn
import numpy as np
import time
from torch.autograd import Variable
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from models import resnet18
import torchvision.models as models
import torchvision.transforms as transforms
imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.