text stringlengths 8 6.05M |
|---|
from onegov.feriennet.models.activity import VacationActivity
from onegov.feriennet.models.calendar import Calendar, AttendeeCalendar
from onegov.feriennet.models.group_invite import GroupInvite
from onegov.feriennet.models.invoice_action import InvoiceAction
from onegov.feriennet.models.message import ActivityMessage
... |
# -*- coding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 9
_modified_time = 1389308004.184105
_enable_loop = True
_template_filename = 'C:\\myStuff\\calculator\\styles/calc.cssm'
_template_uri = 'calc.cssm'
_source_... |
import os
import socket
from bottle import route, run, static_file, template, TEMPLATE_PATH
"""
This is the simplest, dumbest content engine ever
Love, Devin
"""
LATEST = 1
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
STATIC_PATH = os.path.join(PROJECT_PATH, 'static')
TEMPLATE_PATH.append(os.path.join(P... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Nombre: interruptorPalanca.py
# Autores: Miguel Andres Garcia Niño - Ángel Iván Hernández
# Creado: 29 de Junio 2018
# Modificado: 29 de Junio 2018
# Copyright: (c) 2018 by Miguel Andres Garcia... |
#!/usr/bin/python3
#\file cuda_avail.py
#\brief Check if CUDA is available.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Aug.16, 2021
import torch
if __name__=='__main__':
print('CUDA available?', torch.cuda.is_available())
|
#Code by Donnacha Kirk
#Edited by Simon Samuroff 09/2015
import numpy as np
from cosmosis.datablock import names as section_names
from cosmosis.datablock import option_section
def setup(options):
dz = options.get_double(option_section, "dz", default=0.01)
survey = options.get_string(option_section, "survey")
retu... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import powerlaw
#Dataset 1
dct1 = np.zeros([1000,100])
n1 = 100
count1 = 0
data1 = pd.read_csv('dist1.txt', sep = ' ')
data1 = data1.dropna(axis = 'index')
data1_list = data1.values.tolist()
dataset1 = pd.DataFrame(... |
from datetime import date
from onegov.user import User
from onegov.user import UserCollection
from onegov.wtfs.collections import MunicipalityCollection
from onegov.wtfs.collections import NotificationCollection
from onegov.wtfs.collections import PaymentTypeCollection
from onegov.wtfs.collections import ScanJobCollect... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler
from torch.utils.data import Dataset
class BalancedBatchSampler(BatchSampler):
"""
BatchSampler - from a MNIST-like dataset, samples n_classes and within... |
import numpy as np
import copy
import pdb
import random as rdm
import time
import scipy.special as scp
import scipy.stats as scs
import scipy.optimize as scopt
import matplotlib.pyplot as plt
import os
import datetime
from scipy import optimize as scipyopt
import utilities as utils
from loggedopt import Log
from algi... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 20:10:40 2019
@author: gustavo.fonseca
"""
'''Esse script será usado para a resolução da tarefa 8. Cada exercício possuirá
comentários explicando como cada parte do script funciona. Algumas soluções
serão plotadas em gráficos, que serão nomeados para a fácil... |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
This file will analyse the wing geometry from cpacs file.
| Works with Python 2.7
| Author : Stefano Piccini
| Date of creation: 2018-09-27
| Last modifiction: 2019-08-29 (AJ)
"""
#=========================... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 14:41:16 2018
@author: JHodges
"""
import matplotlib.pyplot as plt
import osgeo.gdal
import numpy as np
import struct
import matplotlib.path as mpltPath
from collections import defaultdict
import os
def getHistogram(file):
img = osgeo.gdal.Open(file)
band = n... |
"""
back.app.config
This module contains the constants to config the app.
"""
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
"""
Config module for the application.
I'm taking the database URL from the DATABASE_URL environment variable, and if
that isn't de... |
import numpy as np
from numpy.random import default_rng
import pandas as pd
import argparse
from modules.data_structure import ConfigType
from modules.utils import create_config, states_per_magnet, cycle_length, rules_per_factor
from modules.Evolve import evolve, setup
from modules.metric import Metric
dpn = 'Samples... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app
import bts.index
from bts.models import *
from indexed_models import *
logging.getLogger().setLevel(logging.INFO)
class IndexModel(webapp.RequestHandler):
... |
# get a ball bouncing aroung the screen
# get lots of balls bouncing around the screen
# get people moving aroung infecting each other
# https://www.youtube.com/watch?v=T3TD_fD3AFk
w = 800
h = 800
number_of_people = 30
class Ball(object):
global w,h
def __init__(self,x_,y_,vx_,vy_):
self.x=x_
... |
# keras21_cancer1.py 를 다중분류로 코딩하시오.
import numpy as np
from sklearn.datasets import load_breast_cancer
# 1. 데이터
datasets = load_breast_cancer()
print(datasets.DESCR)
print(datasets.feature_names)
x = datasets.data
y = datasets.target
print(x.shape) # (569, 30)
print(y.shape) # (569,)
from tensorflow.kera... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 16:08:07 2016
@author: pavel
"""
import tkinter
import random
import time
import datetime
from sys import argv
SOUND_FILE = "95078__sandyrb__the-crash.wav" #"http://www.freesound.org/people/sandyrb/sounds/95078/"
DEFAULT_SIZE = 10
DEFAULT_BOMBS =... |
from typing import Union
import sys
from src.data.json import Json
from commons.ini import Config
import commons.errors as errors
json = Json()
config = Config()
class GuildData:
def __init__(self):
pass
def create_guild_data(self, guild_id: str) -> bool:
prefix = config.get... |
import time
from pteromyini.lib.design_pattern.ref import Ref
from pteromyini.core.com.exceptions import ButtonNotFound
from pteromyini.core.com.find_element import find_buttons
from pteromyini.interpreter.interpreter_facade import code_to_str, is_code
from pteromyini.lib.web.wait import retry_get_result
de... |
# Generated by Django 4.0.5 on 2022-07-06 21:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_level_remove_team_goalsgame_remove_team_goalsperiod_and_more'),
]
operations = [
migrations.DeleteModel(
name='Line',
... |
import logging
def preprocessing(**kwargs):
ti = kwargs['ti']
loaded = ti.xcom_pull(task_ids='load_data')
logging.info('variables successfully fetched from previous task')
new_samples = loaded[0]
test_set = loaded[1]
# Once we have loaded the new data we could do some preprocessing and pass on the preprocess... |
CENTRALIZED = False
EXAMPLE_PAIR = "ZRX-WETH"
USE_ETHEREUM_WALLET = True
FEE_TYPE = "FlatFee"
FEE_TOKEN = "ETH"
DEFAULT_FEES = [0, 0.00001]
|
from django.db import models
from django.template.defaultfilters import escape
from django.core.urlresolvers import reverse
from smart_selects.db_fields import ChainedForeignKey
from simple_history.models import HistoricalRecords
from core.models import TimeStampedModel
from practices.models import Practice
from contac... |
X = 0
Y = 1
BLUE = ( 0, 100, 200)
RED = (255, 0, 0)
GREEN = (0, 200, 0)
BLACK = (0, 0, 0) # DUH!
class InvalidMoveException(Exception):
pass
|
from django.db import models
# Create your models here.
class Resim(models.Model):
title = models.CharField(max_length = 50, verbose_name = "Başlık")
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.title |
r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2020
**Source Repository**
http://www.github.com/bsk... |
#!/usr/bin/python3
# -*- coding:utf8 -*-
# Author : Arthur Yan
# Date : 2019-02-17 16:36:03
# Description : 字符串使用
def main():
"""docstring for main"""
str1 = "hello, world!"
print(len(str1))
print(str1.capitalize())
print(str1.upper())
print(str1.find('or'))
print(str1.find('... |
#Programa: act17.py
#Propósito: Realiza un programa que pida por teclado el resultado (dato entero) obtenido al lanzar un dado de seis caras y muestre por pantalla el número en letras (dato cadena) de la cara opuesta al resultado obtenido.
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 17/10/2019
#
#Variables a usar:
# ca... |
# Author : Xiang Xu
# -*- coding: utf-8 -*-
class Point:
""" A utility class for reading points data. """
def __init__(self, x = 0., y = 0.):
self.x = x
self.y = y
self.clusterId = 0
self.classId = 0 # for analysis
def printSelf(self):
return "{0} {1} {2} {3}\... |
from flask import Flask
from flask_cors import CORS
# creating the Flask application
app = Flask(__name__)
CORS(app) # allow CORS |
import numpy as np
#import matplotlib.pyplot as plt
#from scipy.misc import imsave, imread
from scipy.ndimage import fourier_gaussian
from PIL import Image
"""
Gaussian filter via frequency domain methods
We use '1 - template' to get the highpass filter template, the core idea is ifft(fft(img) .* template)
Note that fo... |
class Solution:
def search(self, nums, target: int) -> bool:
i = 0
j = len(nums)-1
if j==-1:
return False
return self.searchHelper(nums,i,j,target)
def searchHelper(self,nums,i,j,target):
if i==j:
return nums[i]==target
if nums[i]==target ... |
from django.urls import path
from debt import views
app_name = "debt"
urlpatterns = [
path("", views.Index.as_view(), name="index"),
# Accounts
path("accounts/", views.AccountList.as_view(), name="account-list"),
path("accounts/add/", views.AccountCreate.as_view(), name="account-add"),
path("accou... |
# coding: utf-8
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
import itertools
ss = [None, None, "abc", "def", "ghi", "jkl", "mno", "pqrs", ... |
'''Convert numeric ids to labels in S57 shapefiles.
A new field will be added to each datasource containing a field to be
converted. This new label field will contain the label or labels corresponding
to the original value.
'''
from argparse import ArgumentParser
from collections import namedtuple
import csv
from fun... |
a,b,c = 1,1,1
while c < 49:
print (c) , " : ", print(type(b))
a, b, c = b, a+b, c + 1 |
import numpy as np
from sklearn.ensemble import RandomForestClassifier
def train_baseline(data_train_x, data_train_y, data_test_x, data_test_y):
clf = RandomForestClassifier(n_estimators=100, max_depth=9, random_state=550)
clf.fit(data_train_x, data_train_y)
train_acc = (clf.predict(data_train_x) == ... |
times = 0
#this is the first mole!
times = times+1
this = __file__
def change():
try:
with open(__file__, 'r')as this_file:
this = this_file.readlines()[2:]
temp = ''
for x in this:
temp = temp+x
this = temp
with open("mole"+str(times)+".py", 'w')as ... |
import pymysql
def get_monthly_data(config):
conn = pymysql.connect(**config)
cur = conn.cursor()
sql = """
SELECT DATE_FORMAT(sdate, '%m') AS `month`,
SUM(revenue) AS revenue, SUM(profit) AS profit
FROM sales_book
GROUP BY `month`
ORDER BY `month`;... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
s = ' ' + s
p = ' ' + p
dp = [[False] * len(p) for _ in range(len(s))]
dp[0][0] = True
for j in range(1, len(p)):
if p[j] == '*':
dp[0][j] = dp[0][j - 2]
for i in range(1, len(s))... |
# coding=UTF-8
#!/usr/bin/env python3
##################################################################################
# #
# Copyright (c) 2016 Yao Nien, Yang, paulyang0125@gmail.com #
# Licensed under the Apache L... |
def Score(string):
freq = dict()
freq['a'] = 14810
freq['b'] = 2715
freq['c'] = 4943
freq['d'] = 7874
freq['e'] = 21912
freq['f'] = 4200
freq['g'] = 3693
freq['h'] = 10795
freq['i'] = 13318
freq['j'] = 188
freq['k'] = 1257
freq['l'] = 7253
freq['m'] = 4761
freq['n'] = 12666
freq['o'] =... |
"""
使用python实现简单的后缀表达式
"""
class Stack(object):
"""
这里是基于列表的栈(将列表作为基础数据结构)
push 往里面放
peek 查看栈顶元素
pop 弹出栈顶元素,并返回这个方法的返回值
empty 判断栈是否为空
"""
def __init__(self):
self.datas = []
self.length = 0
def push(self,data):
self.datas.append(data)
self.length +... |
# Queue测试 q.get后队列是否为空
from queue import Queue
import threading
# from time import sleep
q1 = Queue()
q2 = Queue()
# q2 = Queue()
i = 1
def client1(q1, q2):
data = 'This is a message from client 1.'
q1.put(data)
data = 'This is a message from client 1.'
q1.put(data)
data = 'This is a message fr... |
import day16
import unittest
class Day2Tests(unittest.TestCase):
def test_True(self):
self.assertTrue(True)
def test_Day16_Expand(self):
self.assertEqual(day16.expand('1'), '100')
self.assertEqual(day16.expand('0'), '001')
self.assertEqual(day16.expand('11111'), '11111000000')... |
from pipeline.compilers import SubProcessCompiler
from os.path import dirname
import json
from django.conf import settings
from django.core.exceptions import SuspiciousFileOperation
class BrowserifyCompiler(SubProcessCompiler):
output_extension = 'browserified.js'
def match_file(self, path):
print('\n... |
class Rectangle:
def __init__(self, width, height):
self.width, self.height = width, height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.width * self.height
def get_perimeter(self):
return 2*(self.width + self.height)
... |
# Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's
# language"). That is, double every consonant and place an occurrence of "o" in between. For example,
# translate("this is fun") should return the string "tothohisos isos fofunon"
def character_Search(chr):
if (chr... |
from dataset import data_loader
from model import lstm_with_shop_cate_embedding
import train, infer
from numpy.random import seed
data_pickle_file_path = 'dataset/pickle/dataset_12step_shop_cate.pkl'
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
if __name__ == "__main__":
x_seq_len = 12
... |
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
if len(A[0]) == 0:
return [[]]
return [list(x) for x in list(zip(*A))]
print(Solution().transpose([[1]])) |
import os
import matplotlib.pyplot as plt
import torch
from datetime import datetime
class MetricManager:
"""
Class for tracking accuracy and loss values.
metrics
+ 'train_loss_list',
+ 'train_acc_list',
+ 'val_loss_list',
+ 'val_acc_list',
+ 'global_steps_list'
"""
... |
# -*- coding: utf-8 -*-
import logging
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, Upd... |
zzzz = " 顶层人控/手工 次层半自动按钮 3层及以下自动 "
from WindPy import w
from datetime import *
w.start(showmenu=True)
w.wsd("600000.SH","open,close", "2010-07-01",datetime.today(), "Fill=Previous")
w.wsd("600000.SH,600004.SH","low", '20150716', datetime.today(), "Fill=Previous")
w.tdaysoffset(-1)
# watch_list txt? excel!!! sh... |
'''
module : dbmgr
features firebase wrapper class called Dbmgr
'''
from firebase import firebase
from requests import HTTPError
from django.conf import settings
'''
class: Dbmgr
description:
- database manager class
attributes:
fdb : instance of the FirebaseApplication class
initializer input:
N... |
#!/usr/bin/env python
import unicorn
def get_arch(arch, mode):
if arch == unicorn.UC_ARCH_X86 and mode == unicorn.UC_MODE_32:
# NB: dynamic import
import ucutils.arch.x32
return ucutils.arch.x32
elif arch == unicorn.UC_ARCH_X86 and mode == unicorn.UC_MODE_64:
# NB: dynamic im... |
# t.py
import numpy as np
from astropy.io import fits
hdulist = fits.open('/PATH TO /new_image.fits') #path to new FITS file, edit!!
scidata = hdulist[0].data
#initalize array to keep track of what pixels are valid to be checked for cluster
#2 pixels wider than array in both dimensions for boundry co... |
import time
import boto3
import pytest
from aws_conduit import conduit, conduit_factory
STS = boto3.client('sts')
ACCOUNT_ID = STS.get_caller_identity().get('Account')
BUCKET_NAME = 'conduit-config-' + ACCOUNT_ID
def test_configure():
bucket = conduit.configure()
assert bucket.exists()
bucket.delete()
... |
# 动态创建类
def create_class(name):
if name == 'person':
class Person(object):
pass
return Person
else:
class Car(object):
pass
return Car
my_class = create_class('car')
print(my_class().__class__)
print(my_class)
# 使用type动态创建类
Person = type('Person', (ob... |
import adsk.core
import adsk.fusion
import traceback
from .Fusion360CommandBase import Fusion360CommandBase
def unsuppress_all():
app = adsk.core.Application.get()
design = adsk.fusion.Design.cast(app.activeProduct)
# Get All components in design
all_components = design.allComponents
for comp in... |
import os
import setuptools
def get_readme():
with open("README.md", "r") as f:
return f.read()
setuptools.setup(
name="rlutil",
version="0.1.0",
description="Utilities for RL algorithms",
long_description=get_readme(),
long_description_content_type="text/markdown",
python_require... |
from django.contrib import admin
from .models import Collection, Good, Image
class GoodInline(admin.StackedInline):
model = Good
extra = 3
class CollectionAdmin(admin.ModelAdmin):
# fieldsets = [
# (None, {'fields': ['title', 'description', 'cover']}),
# ]
prepopulated_fields =... |
#=========================================================================
# pisa_mul_test.py
#=========================================================================
import pytest
import random
import pisa_encoding
from pymtl import Bits
from PisaSim import PisaSim
from pisa_inst_test_utils import *
#---------... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pmtool', '0018_auto_20150212_1309'),
]
operations = [
migrations.AlterField(
model_name='wbs',
name=... |
# Copyright (c) 2012 Paul Osborne <osbpau@gmail.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 to use, copy, modify, mer... |
# -*- coding: utf-8 -*-
#
# * Copyright (c) 2009-2015. Authors: see NOTICE file.
# *
# * 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... |
import hashlib
from django.contrib.auth.models import AbstractBaseUser, AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .storage import OverwriteStorage
from .managers import UserManager
from ..subscriptions.helpers import SubscriptionModelMixin
class CustomUser... |
#__author: "Jing Xu"
#date: 2018/1/23
import app
import sys
print(app.add(1,4))
print(sys.path)
|
import pytest
from decimal import Decimal
from fuzzyfields import Domain, DomainError
def test_basic():
"""Hashable and unhashable choices
"""
ff = Domain(required=False, default='stub', choices=['foo', False, [1]])
# default does not go through domain validation
assert ff.parse('N/A') == 'stub'
... |
def gcd(a,b):
while b != 0:
a, b = b, a%b
return(a)
A = [3]*4 + [5]*4 + [7]*6
s = sum(A)
# for a in A:
# print( gcd(a, s-a))
def prime(n):
for i in range(2, int(n**(1/2))+1):
if n%i == 0:
return 0
else:
return n
primelist = []
for i in range(2, 20000):
if pr... |
#!env python3
# -*- coding: utf-8 -*-
import unittest
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return self.first_name + ' ' + self.last_name
class TestUser(unittest.TestCase):
def test_fullna... |
"shift-related helper functions"
from numpy import zeros,r_,nonzero,isclose,empty_like,argmin,count_nonzero
from ..general_functions import *
thinkaboutit_message = ("If you think about it, you"
" probably don't want to do this. You either want to fill with"
" zeros from... |
# @Title: 组合总和 II (Combination Sum II)
# @Author: 2464512446@qq.com
# @Date: 2019-11-22 17:21:45
# @Runtime: 44 ms
# @Memory: 11.5 MB
class Solution:
def combinationSum2(self, candidates, target):
size = len(candidates)
if size == 0:
return []
candidates.sort()
res = []... |
import os, sys
sys.path.append('/Users/Sam/Nasyno/Sites/django/tuto1/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings'
from article.models import Sensor
from article.models import Actuator
def before_all(context):
context.sensors_init = Sensor.objects.all()
context.sensors = Sensor.objects.all()
cont... |
import streamlit as st
import pandas as pd
def multiple_sheet(df):
st.write("**I noticed your file has multiple sheets.**")
sheet = st.selectbox(" Please select the sheet you would like to work on now.", df.sheet_names)
df = pd.read_excel(df, sheet)
return(df)
|
"""Stuff
TODO continue this
"""
import inspect
import fbx
from brenpy.core import bpDebug
from brenfbx.core import bfCore
from brenfbx.fbxsdk.core import bfProperty
class BfObject(
bfCore.BfObjectBase,
# bpDebug.BpDebugObject,
# bfCore.BfManagerBase
):
FBX_CLASS_ID = fbx.FbxObject.ClassId
de... |
from django.shortcuts import render,get_object_or_404,redirect
from django.urls import reverse,reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView,UpdateView,DeleteView,ListView
from django.views.generic import View
from cars.models import Make,Cars
from c... |
from rest_framework import serializers
from favorite.models import Favourite
class FavouriteSerializer(serializers.ModelSerializer):
user = serializers.CharField(source='user_id.name', read_only=True )
userImage = serializers.CharField(source='user_id.Image', read_only=True )
content = serializers.CharFiel... |
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
"""
@author:LiWei
@license:LiWei
@contact:877129310@qq.com
@version:v1.0
@var:信用陕西
@note:信用陕西_行政许可数据采集
"""
from scrapy.spiders import Spider
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose, Join
from xbzxproject.items import XingZhe... |
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from password.views import PasswordApi, PasswordView, PasswordEdit
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', auth_views.LoginView.as_view(), name='login-view'),... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.misc import format_date
from datetime import timedelta
class ProjectTaskType(models.Model):
_inherit = 'project.task.type'
is_closed = fields.Boolean('Is a ... |
import json
years = range(2010, 2018)
collated_data = []
for year in years:
fn = 'dataset/{}_data.json'.format(year)
with open(fn) as f:
data = json.loads(f.read())
collated_data.extend(data)
fn = 'dataset/{}_non_billboard_data.json'.format(year)
with open(fn) as f:
data = js... |
""" Test packing/unpacking User Control Message - SET_BUFFER_LENGTH event data (packed body). """
import struct
# Buffer length as a single integer (in milliseconds).
buffer_length = 3000
# Packed stream id of zero (4-byte) - unsigned integer.
print([struct.pack('>I', 0)])
# Unpacked stream id from the binary data,... |
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.applications import VGG16
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.optimizers import RMSprop
# # include_top=False 只加载卷积层参数,分类层参数未加载
conv_base ... |
import math
input_file = 'Day 25\\Input.csv'
text_file = open(input_file)
lines = text_file.read().split('\n')
regs = dict()
def inc(inp):
regs[inp[1]] += 1
return 1
def dec(inp):
regs[inp[1]] -= 1
return 1
def cpy(inp):
try:
if ord(inp[1]) >= 97:
regs[inp... |
#Fruit Fun (Bejewled copy)
#
#Swap fruits on a board and try to make horizontal and vertical rows.
import random, time, pygame, sys, copy
from pygame.locals import *
FPS = 30
WINDOWWIDTH = 550
WINDOWHEIGHT = 600
BOARDWIDTH = 9
BOARDHEIGHT = 9
SPACESIZE = 60
BOARDPIXELWIDTH = BOARDWIDTH * SPACESIZE
BOARDPIXELHEIGHT =... |
from os.path import expanduser
from libqtile import bar, widget
from libqtile.config import Screen
from libqtile.lazy import lazy
from widgets.owm import OpenWeatherMap
from widgets.volume import MyPulseVolume
from widgets.window_indicators import WindowIndicators
from classes import Helpers, Palette
dpi = Helpers.... |
# two sum
def solution(nums, target):
temp = {}
result = []
for i in nums:
if i in temp.keys():
temp[i] += 1
else:
temp[i] = 1
for i in temp.keys():
t = target - i
if t != i:
if t in temp.keys():
result.append(nums.inde... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: caramel
def main():
good_1 = 'cabbage'
good_2 = 'tomato'
good_3 = 'cucumber'
good_4 = 'bean'
good_5 = 'carrot'
#------One hundred items are omitted.
good_100 = 'potato'
print 'My mum saw %s in the vegetable market.' % (good_1)
print 'My mum saw %s in the ... |
#!/usr/bin/python
#-*-coding:utf-8-*-
from bs4 import BeautifulSoup
import requests
import re
from pymongo import *
from tinylog import glog
import time
ip = '204.152.220.23'
url = 'http://%s/forum.php?mod=forumdisplay&fid=883&filter=typeid&typeid=1096' % ip
logger = glog(__name__, './xyy.log')
headers = {'User-Agen... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
from simphony.api import CUDS
from simphony.core import CUBA
from simphony.cuds.meta.api import Material
from simphony.cuds.particles import Particle, Particles
from .lammps_data_file_parser import LammpsDataFileParser
from .lammps_data_file_writer import LammpsDataFileWriter
from .lammps_data_line_interpreter import ... |
#Project Euler Problem 16
# What is the sum of the digits in 2^1000?
sum=0
#for i in range(1,3):
# a*=a
a=pow(2,1000)
print(a)
b=str(a)
for j in range(0,len(b)):
sum+=int(b[j])
statement = ' the sum of the digits in 2^1000 is: '+repr(sum)
print(statement)
#Correct! |
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2021-03-12 21:14:12
LastEditor: John
LastEditTime: 2021-03-31 13:49:06
Discription:
Environment:
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
import math
clas... |
import os
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录
CASE_PATH = os.path.join(BASE_PATH, 'tests') # 用例脚本所在目录
DATA_PATH = os.path.join(BASE_PATH, 'data') # 用例数据目录
CONF_PATH = os.path.join(BASE_PATH, 'config') # 配置文件路径
REPORT_PATH = os.path.join(BASE_PATH, 'report') # 测试报告路径
LO... |
import math
from skimage import io
import numpy as np
import matplotlib.pyplot as plt
#puntos_p = [(370, 19), (1202, 48), (326, 1126), (1217, 1134)]
puntos_p = [(1234.538745387454, 60.3947368421052), (2872.560885608856, 247.61842105263145),
(1294.760147601476, 1636.6973684210527), (2932.7822878228785, 1370... |
from .base import Ui
class TextField(Ui):
def set_text(self, text):
self._web_element.send_keys(text)
@property
def text(self):
return self._web_element.text
|
"""
Composite:
The Composite composes objects into tree structures and lets clients treat individual objects and compositions
uniformly. Although the example is abstract, arithmetic expressions are Composites. An arithmetic expression
consists of an operand, an operator (+ - * /), and another operand. The operand can... |
import pandas as pd
import quandl, math
import numpy as np
from sklearn import preprocessing, svm
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = quandl.get('WIKI/GOOGL', api_key = "hWH3qS82LVUGJZ4-xBuq")
df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Clo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.