text stringlengths 8 6.05M |
|---|
import math
import redis
NEWS_FIELDS = (
"title",
"img_url",
"content",
"is_valid",
"news_type",
"created_at",
"updated_at"
)
class RedisNews(object):
def __init__(self):
# 如果返回是二进制类似 b'3\xe6\x9c\x885\xe6\x97\xa5\xe...'需要加decode_responses=True
try:
self.r =... |
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import cgi
import sys
import sqlite3
import time
import json
import random
#import numpy as np
import percentile as p
conn = sqlite3.connect('sqlite/hemap_gexp_raw.db')
c = conn.cursor()
pa = {}
conn.text_factory = str
qform = cgi.FieldStorage()
#inparam = "AML"#
inparam =... |
import signal
import time
class TimedOutExc(Exception):
pass
def deadline(timeout, *args):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args):
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
return f... |
"""zixiangERP URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
number=int(input("enter integer:"))
def int_to_string(number):
d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', \
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', \
11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', \
15 : 'fifteen', ... |
# Default box content, used for game reset and move check
defaultBoard = ["1","2","3","4","5","6","7","8","9"]
# Define box content for the first time
boardDraw = ["1","2","3","4","5","6","7","8","9"]
# Winning Condition
winCond = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
# Player symbol
play... |
# Copyright 2016-2017 Red Hat Inc & Xena Networks.
#
# 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 ag... |
"""Background job to perform a DNS lookup and insert into or update in the db.
Attributes:
DNS_SERVERS: A list of strs representing which DNS servers to use
DNS_BLOCKLIST: A str representing the blocklist to send a DNS lookup to
"""
import dns.resolver
from models import IPDetails, ResponseCode
# Spamhaus w... |
from django.contrib import admin
from .models import Mensagem
# Register your models here.
admin.site.register(Mensagem)
|
if (len(my_str) == 0):
print("did it")
elif (my_str != "password"):
print("did it")
|
from flask import Blueprint
leads = Blueprint('leads', __name__)
import app.leads.forms
import app.leads.models
import app.leads.views
|
from Model.HyperNetwork import *
network = HyperNetwork(1000)
optimBase = torch.optim.Adam(network.base.parameters(), lr=0.001, betas=(0.9, 0.98), eps=1e-9)
criterion = nn.CrossEntropyLoss()
mse = nn.MSELoss()
import torch.utils.data as data_utils
epoches = 100
for epoch in range(epoches):
print(e... |
#!/usr/bin/python3
"""
List all states matching given name from a MySQL db on localhost at port 3306
"""
from mysqlman import MySQLMan
from MySQLdb import Error
from sys import argv, exit, stderr
HELP = '{} username password database search'.format(argv[0])
HOST = 'localhost'
PORT = 3306
if __name__ == '__main__':... |
class Solution:
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if s == '' or s[0] == '0':
return 0
store = [-1 for _ in range(len(s)+1)]
store[0], store[1] = 1, 1
def count(n):
if store[n] != -1:
r... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 14:50:36 2019
@author: Lenovo
"""
#from nltk.corpus import names #some of corpus import
#print(names.words()[:10])
#from nltk.stem.porter import PorterStemmer
#porter_stemmer = PorterStemmer() #stemming the tokens
#print(porter_stemmer.stem('l... |
#!/usr/bin/env python2.4
# -*- coding: UTF-8 -*-
import os,sys,Gnuplot,time
from sys_info import SysInfo
from file_managers import frames
nom_fitxer_stressos = "historia_stress"
def wait(for_this=0.01):
time.sleep(for_this)
def main(directori):
g = Gnuplot.Gnuplot()
nom_fitxer = os.path.join(directori, ... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
import collections
def solution(A):
# write your code in Python 3.6
dict_A = dict(collections.Counter(A))
for key, value in dict_A.items():
if (value % 2) != 0:
return key
|
#!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
t=cnt=0
n,k=input().split()
if len(n)<=int(k):
print(len(n)-1)
else:
k=int(k)
for a,i in enumerate(n[::-1]):
if i!='0':
t+=1
else:
cnt+=1
if cnt==k:
break
print(t if t!=len(n)-n.count('0') else len(... |
import hmac
import time
import hashlib
class BlocktaneAuth:
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
def generate_auth_dict(self) -> dict:
"""
Returns headers for authenticated api request.
"""
nonce... |
from pytube import YouTube
from pprint import pprint
import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import sys
import os
import sqlite3
path = '../Songs/'
def insert_in_database(database, f) :
cursor = database.execute("SELECT name FROM SONGS WHERE name = (?)", (f,))
data = cursor.fetchone()
... |
# @author: SFQRM
# first edit time = 2019-10-8
# function:
# Zachary’s karate club is a commonly used social network where nodes represent members of
# a karate club and the edges their mutual relations. While Zachary was studying the karate club,
# a conflict arose between the administrator and the instructor which... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.cluster import KMeans
from scipy.sparse import csc_matrix, csr_matrix
from utils import MaskedLinear
class LeNet(nn.Module):
def __init__(self, mask=False):
super(LeNet, self).__init__()
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-02-24 19:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... |
from re import compile
from math import pi, log, tan, ceil
import json
from shapely.wkb import loads
from shapely.geometry import asShape
from .ops import transform
float_pat = compile(r'^-?\d+\.\d+(e-?\d+)?$')
charfloat_pat = compile(r'^[\[,\,]-?\d+\.\d+(e-?\d+)?$')
# floating point lat/lon precision for each zoom l... |
#main.py
import torch
import math
import torch.optim as optim
#import Policy
#import Data_train
#setting up counter
counter_global=0
#Model
Q_model=Q_learning()
#Load initial data
state,next_state,chrom,chrom_new,Chr,cnv,start_loci,end_loci,wgd,step,advantage,valid=Load_data()
#setting up optimizer
optim... |
# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
def plot_loss_history(model):
if isinstance(model, str):
with np.load(model) as f:
train_err_mem = f['train_err_mem']
valid_err_mem = f['val_err_mem']
else:
train_err_mem = model.train_err_mem
va... |
# write a program to print sum of the three numbers
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
sum_num=a+b+c
print(f"the sum of number:",sum_num)
|
from flask import Flask, render_template
from flask import redirect, url_for
app= Flask (__name__)
@app.route("/")
def default():
return redirect (url_for('about'))
@app.route("/home")
def home():
return render_template("home.html")
@app.route("/about")
def about():
return render_template("about.html")
... |
def main():
# solve for puzzle input
input = open("part1_input.txt").read()
print(solve(input))
def solve(captcha):
sum = 0
for i, c in enumerate(captcha):
if c == captcha[(i + 1) % len(captcha)]:
sum += int(c)
return sum
main()
|
import numpy as np
def test_n_componets_from_reducer():
from pymks import MKSStructureAnalysis
from pymks import DiscreteIndicatorBasis
from sklearn.manifold import LocallyLinearEmbedding
reducer = LocallyLinearEmbedding(n_components=7)
dbasis = DiscreteIndicatorBasis(n_states=3, domain=[0, 2])
... |
class Person:
def setpersonval(self,name,age,adrs):
self.name=name
self.age=age
self.adrs=adrs
print(self.name,self.age,self.adrs)
class Parent:
def setparentval(self,name,phnno):
self.name=name
self.phnno=phnno
print(self.name,self.phnno)
class Employee(P... |
SEQUENCE_TYPES = (list, tuple)
DEFAULT_ENCODING = 'utf-8'
def to_unicode(value, encoding='utf-8'):
"""Converts a value to unicode, even if it is already a unicode string.
"""
if isinstance(value, str):
return value
elif isinstance(value, bytes):
try:
value = value.decode(en... |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2017. 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.0... |
n1=int(input("Enter 1st no"))
n2=int(input("Enter 2nd no"))
n3=int(input("Enter 3rd no"))
if n1>n2 and n1>n3:
print("%d is the largest no"%(n1))
elif n2>n1 and n2>n3:
print("%d is the largest no"%(n2))
else:
print("%d is the largest no"%(n3)) |
import requests
from optparse import OptionParser
import tempfile
import os
class XssFuzzer:
payloads = [
"<script>alert(1)</script>",
"\"><script>alert(1)</script>",
"\" onerror=\"alert(1)\""
]
def __init__(self, verbose=False):
self.verbosity = verbose
def getPayloads(self):
return self.payloads
def ... |
class TreeNode:
def __init__(self, x,left = None,right = None):
self.val = x
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root==None:
return True
return self.isMirror(root.left,root.right)
de... |
from tkinter import *
wd1=Tk()
wd1.title("Gyanvriksh")
#wd1.configure(background="blue")
#wd1.configure(bg="#00ff00")
wd1.configure(bg="#ffffff")
wd1.configure( height=400, width=350, bg="#ff00ff")
wd1.geometry("340x400+260+130")
wd1.geometry("340x400+0+0")
wd1.geometry("340x400+260+0")
wd1.geometry("340x400+... |
import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
import markdown
from attachments.markdown_extensions import connect_attachments
class Category(models.Model):
"""A category of blog post"""
name = models.CharFie... |
# functionality to make a climatology from the daily file made by SNAP through interpolation
if __name__ == '__main__':
import os
import xarray as xr
import numpy as np
import argparse
# parse some args
parser = argparse.ArgumentParser( description='make a climatology NetCDF file of Sea Ice Co... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""Returns indices of the two numbers such that they add up to target
Args:
nums (List[int]): integer array
target (int): integer target
Returns:
Li... |
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(fmt=logging.Formatter(fmt=logging.BASIC_FORMAT))
log.addHandler(handler)
|
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems 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.o... |
from app.common.conn_varnish import VarnishManager
import requests
class Cache_flush(object):
def __init__(self, host):
self.host = host
|
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from dragbutton import DragButton
from wiringgraphicsview import *
import collections
import subprocess
import icons_rc
app = QApplication([])
scene = MyScene()
menu = QMenu()
widget_container = QWidget()
#dictonaries for dragbuttons (used later for connecting th... |
#returns the result of the club conquest command
import commands.advancedhelp as ah
import discord
import json
import os
OPENINGS_COMMAND = '!openings'
clubs = None
guild_id = None
def set_clubs():
#read the json resource for the clubs and save them in a dictionary
cur_path = os.path.dirname(__file__)
cur_path ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 25 12:14:13 2018
@author: HP
"""
import numpy as np
import pandas as pd
from scipy.signal import savgol_filter
from sklearn.preprocessing import LabelBinarizer
from sklearn.svm import SVR
def preprocessing(filepath):
df = pd.read_csv(filepath)
... |
import numpy as np
eng_words = []
hin_words = []
with open('spa.txt') as fp:
contents = fp.read()
for line in contents.split('\n'):
entry = line.split('\t')
if len(entry) > 1:
eng_words.append(entry[0][:-1])
hin_words.append(entry[1][:-1])
print(len(eng_words))
np.sav... |
##This program will calculate stability of Cavity
import numpy as np
##Constants, mirrors
L = 0.5 #distance between mirrors in m
lam = lam = 0.00000000542 #wavelength of beam
#concave mirrors of + sign, vice versa
R1 = 0.2 #radius of curvature of mirror 1
R2 = 0.4 #radius of curvature of mirror 2
#g-params
g1 = 1.0 -... |
# однострочный комментарий
a = 99837854
b = 888
print("a = ", a)
print("b = ", b)
print("a + b = ", a + b) # сложение чисел
print("a - b = ", a - b) # вычитание чисел
print("a * b = ", a * b) # умножение чисел
print("a / b = ", a / b) # деление чисел
print("a // b = ", a // b) # деление с округлением вниз до целог... |
import datetime
last_id = 0
class Note:
'''Represent a note in the notebook. Match against a string in searches and store tags for each note'''
def __init__(self, memo=None, tags=''):
'''Initialize a note with memo and optional space-separated tags. Automatically set the note's
creation date ... |
"""
Author: Sidhin S Thomas (sidhin@trymake.com)
Copyright (c) 2017 Sibibia Technologies Pvt Ltd
All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
"""
from django.conf.urls import url
from trymake.website.vendor import views
urlpatterns = [
... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework.routers import DefaultRouter
from posts.views import PostViewSet
router = DefaultRouter()
router.register('post', PostViewSet, base_name='post')
url... |
#Implementation of KNN in Python
def optimalKSelection():
"""
Identify the optimal value of K Nearest Neighbour
"""
pass
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/copyright.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(... |
from __future__ import unicode_literals
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from activity.models import Comment
from activity.serializers import CommentSerializer
class CommentList(generics.ListCreateAPIView):
serializer_class = CommentSerializ... |
#_*_coding:utf-8_*_
# Create your views here.
from django.http import Http404
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from models import KxSoftBug
from hash... |
# Rulett alternativ 3
# Tar utgangspunkt i hvilke farger som gjelder
# Brukeren oppgir verdi på ruletten
tall = int(input('Hva er tallet på ruletten: '))
# Tester på gyldig verdi og beregner riktig farge for gyldige verdier
if tall >= 0 and tall <= 36:
if tall == 0:
print('Tallet er markert g... |
# Load required libraries
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Global Dataframes from Original CS... |
import random
import pygame
# Init
pygame.init()
# color variables
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# screen sizes
display_width = 800
display_height = 600
# card sizes
card_width = int((500 * .25))
card_height = int((726 * .25))
start_y = -card_height - 2
discard_pos = (card_width + 5... |
# reduce
# reduction -> reduce
# reduce = binary>function,swquence
from functools import reduce
# def func(x, y):
# return x * y
#
# a = [1, 2, 3, 4, 5]
b = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5, 6])
print(b)
|
import os
import sys
import stat
from git import Repo # pip install --user gitpython
import read_config
from flask import Flask, jsonify, request, json
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
# Flask application initialization
app = Flask(__name__)
CORS(app)
api = Api(app)
####... |
import os
import numpy as np
import json
import torch
import random
import pandas
import re
import copy
from torch.utils.data import DataLoader, Dataset
class Dataloader(object):
def __init__(self, train_name, val_name, test_name):
if train_name:
with open(train_name) as f:
self... |
'''
Write a function that returns a list of strings is sorted given a specific alphabet
A list of N words and the K-sized alphabet are given.
input: words = ["cat", "bat", "tab"]
alphabet = ['c', 'b', 'a', 't']
Note that we want to determine if the *list* of words is sorted, not the individual words
input: words... |
import os, time
def last_modified_fileinfo(filepath):
filestat = os.stat(filepath)
date = time.localtime((filestat.st_mtime))
# Extract year, month and day from the date
year = date[0]
month = date[1]
day = date[2]
# Extract hour, minute, second
hour = date[3]
minute = date[4]
second = date[5]
... |
from django.db import models
class WebsiteText(models.Model):
text = models.CharField(max_length=1000000, blank=True)
website_url = models.CharField(max_length=250)
class WebsiteImages(models.Model):
images = models.CharField(max_length=1000000, blank=True)
website_url = models.CharField(max_length=... |
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
import face_recognition
class FaceIdAuthBackend(ModelBackend):
def authenticate(self, username=None, password=None, face_id=None, **kwargs):
try:
user = User.objects.get(username=username)
... |
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums = sorted(nums)
if len(nums) < 2:
return 0
i, j = 0, 1
res = set()
while i < len(nums) and j < len(nums):
... |
"""
Author: Rawley Collins
Program: set_membership.py
"""
def in_set(some_input, some_set):
return some_input in some_set
if __name__ == '__main__':
test_var = 56
my_set = set('123467')
print("Is {} in {}, {}".format(test_var, my_set, in_set(str(test_var), my_set)))
|
from pypoly import X
import numpy as np
def lagrange(datos):
"""
Entrada: Un conjunto de datos (ti, yi)
Salida: Polinomio interpolante del conjunto de datos con metodo de Lagrange
"""
n, pol = len(datos), 0
for j in range(n):
y = datos[j][1]
prod1, prod2 = 1, 1
for k in ... |
import numpy as np
import re
class Frame(object):
def __init__(self, init_data=None, filter=0.5):
self.data = init_data
self.filter = filter
# DATA PROPERTY (32, 8)
@property
def data(self):
return self._data
@data.setter
def data(self, new):
replace = None
... |
import socket
s = socket.socket()
host = "0.0.0.0"
port = 12345
s.bind((host, port))
BACKLOG = 5
s.listen(BACKLOG)
while True:
c, addr = s.accept()
print("conn addr : ", addr)
c.send("hello word")
c.close()
import socket
s = socket.socket()
host = '0.0.0.0'
port = 12345
s.connect((host, port))
print(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: xavier
"""
import pandas as pd
import datetime
import pydoop.hdfs as hdfs
import pandas_datareader.data as web
from pandas import Series, DataFrame
import os
class stockYahooLoader():
pd_total = {}
def __init__(self,startDate, endDate, symbols_file... |
import sys
error = 'name'
if (error == 'name'):
x = 25 + a
elif(error == 'type'):
x = 25 + 'a'
elif(error == 'attrib'):
attribute = -error
#elif(error == 'syntax')
|
from datetime import date
from onegov.ballot import List
from onegov.ballot import ListCollection
from onegov.ballot import ProporzElection
def test_lists(session):
election = ProporzElection(
title="Election",
domain='federation',
date=date(2015, 6, 14)
)
election.lists.append(
... |
################################################################
## Load package and set path ##
################################################################
import os,sys
import pygeos
import pandas as pd
import numpy as np
import geopandas as gpd
from pathlib import Path
#from pgpkg impor... |
# Generated by Django 2.2.5 on 2019-10-05 14:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('donation', '0003_donation'),
]
operations = [
migrations.AlterField(
model_name='donation',
name='phone_number',
... |
# Generated by Django 2.2.1 on 2019-05-09 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Usuarios',
fields=[
('id', models.AutoField... |
#!/usr/bin/python2.7 -tt
from socket import *
import sys
#FILENAME = "server_port"
BUFFER_SIZE = 1024
HOST = "localhost"
response_string_for_invalid_request = "HTTP/1.1 404 Not Found\r\n" \
"Content-type: text/html\r\nContent-length: 135\r\n" \
"<... |
# https://www.reddit.com/r/dailyprogrammer/comments/wvc21/7182012_challenge_79_easy_counting_in_steps/
import math
def step_count(a, b, step):
difference = b - a
count = difference/(step-1)
numList = []
for i in range(step):
numList.append(a + (i*count))
print(numList)
print(step_count(1... |
import os
import easygui as g
def main():
#遍历文件夹 找出指定格式文件
# targettype = ['.py','.pyw','.txt']
targettype = ['.py','.pyw']
getdir = g.diropenbox()
mode_strict = g.ynbox(msg='是否严格检定(筛除注释行)?' ,default_choice='No')
list1 = os.walk(getdir)
dict1 ={}#统计各指定格式文件的数量
dict2 ={}#统计行数
f... |
from tacticalrmm.test import TacticalTestCase
from core.tasks import core_maintenance_tasks
class TestCoreTasks(TacticalTestCase):
def setUp(self):
self.setup_coresettings()
self.authenticate()
def test_core_maintenance_tasks(self):
task = core_maintenance_tasks.s().apply()
se... |
# -*- coding: utf-8 -*-
import os
from django import template
from main.models import Reunion, Punto
register = template.Library()
@register.filter
def filename(value):
return os.path.basename(value.file.name)
@register.simple_tag
def reunion_asistentes(pk):
reunion = Reunion.objects.get(pk=pk)
return ... |
import logging
class State(object):
"""
Super class for all pod states
"""
def __init__(self, controllers):
self.logger = logging.getLogger('SM')
self.logger.debug("[+] State change: ", str(self))
self.controllers = controllers
def on_event(self, event):
pass
... |
import itertools
import logging
import os
import warnings
from collections import Counter
from collections import defaultdict
from contextlib import suppress
import humanize
import joblib
import numpy as np
import pandas as pd
import psutil
import tensorflow as tf
import yaml
from tqdm import tqdm
from questions.util... |
from dash.dependencies import Input, Output
from app import app
from datetime import datetime as dt
from datetime import date, timedelta
from components.functions import df_pc
from components.functions import update_first_datatable, update_graph,df_pc,update_pie
#callback de mise à jour de la table de données à partir... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... |
import protest
protest.images("trees")
|
import pygame
# SpriteSheet er en klasse som tar inn en bilde-fil og kan dele den opp i flere bilder
class SpriteSheet:
def __init__(self, filename, spriteWidth, spriteHeight):
self.spriteSheet = pygame.image.load(filename).convert_alpha()
self.spriteWidth = spriteWidth
self.spriteHeight = ... |
# -*- coding: utf-8 -*-
"""Classes for ACM Certificates."""
class CertificateManager:
"""Manage an ACM Certificate."""
def __init__(self, session):
"""Manage an ACM Certificate."""
self.session = session
self.client = self.session.client('acm', region_name='us-east-1')
def cert_... |
class Execution():
def __init__(self, liq_tol):
self.liq_tol = liq_tol
def ExecutePortfolio(self, algorithm, portfolio):
# algorithm.Log(f"Executing portfolio trades...")
liquidate_securities = portfolio[abs(portfolio) < self.liq_tol].index
holding_port = portfolio[abs(portfol... |
import argparse
import os
import torch
from tqdm.auto import tqdm, trange
from torch_geometric.nn import Node2Vec
import src.experimentutils as experutils
import src.dataprocessing as dataproc
def main():
parser = argparse.ArgumentParser(description="Run the training on ethereum graph")
parser.add_argument("... |
class Solution(object):
def isOneEditDistance(self, s, t):
if not s and not t: return False
m, n = len(s), len(t)
if abs(m - n) > 1: return False
if m > n: return self.isOneEditDistance(t, s)
i, diff = 0, n - m
while i < m and s[i] == t[i] : i += 1
if diff == ... |
import threading
from django.contrib.auth.models import User
from rest_framework import serializers
from social_network.post.models import Post
from social_network.post.utils import fetch_name_data, verify_email, populate_clearbit_user_data_async
class UserSerializer(serializers.HyperlinkedModelSerializer):
pas... |
#coding:utf-8
import torch
import torch.utils.data as data
import numpy as np
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.nn.functional as F
from torch.optim import lr_scheduler
from tensorboardX import SummaryWriter
writer = Summ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# === sqlalchemy_tree.tests -----------------------------------------------===
# Copyright © 2011-2012, RokuSigma Inc. and contributors. See AUTHORS for more
# details.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms of the software as well ... |
'''
NoI __init__
Creates globals
'''
from flask_alchemydumps import AlchemyDumps
from flask_assets import Bundle, Environment
from flask_security import Security
from flask_cache import Cache
from flask_babel import Babel
from flask_bcrypt import Bcrypt
from flask_mail import Mail
from flask_s3 import FlaskS3
from fl... |
import numpy as np
def nullify_non_alphanum(dataframe, fields=None):
"""
Nullify in place any values that have no alphanumeric characters (note: does not take into account latin chars.
Nullified values are converted to NaNs.
:param dataframe:
:param fields: optional list of fieldnames to be nullif... |
if __name__ == "__main__":
cities = {
'groningen': {
'country': 'netherlands',
'population': '200366',
'fact': 'My current home!'
},
'valthermond': {
'country': 'netherlands',
'population': '3488',
'fact': 'My ancestral ... |
#!/usr/bin/env python
import argparse
import re
import matplotlib as mpl
parser = argparse.ArgumentParser(description="""Plot the band structure, with
consideration of spin-polarization. Accepts input file 'EIGENVAL', or 'vasprun.xml'.""")
parser.add_argument('-f', metavar='filepath', default='EIGENVAL', h... |
from random import randint
import json
def lcs():
names = ["MUHAMMADUSAMA", "ABDULMUSAWWIR"]
for i in range(10):
seqs = []
for name in names:
seq1 = ""
lenstr = randint(30, 100)
while len(seq1) < lenstr:
seq1 += name[randint(0, len(name)-1)]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.