text stringlengths 38 1.54M |
|---|
# import pandas
# print pandas.__version__
import sys
print(sys.path)
# for x in range(1,10):
# print x
|
'''
tind.py: code for interacting with Caltech.TIND.io
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2018-2019 by the California Institute of Technology. This code
is open-source software released under a 3-clause BSD license. Please see the
file "LICENSE"... |
#!/usr/bin/python
import getopt, sys
from boto.ec2.connection import EC2Connection
from datetime import datetime
import sys
#please note that i hold no responsibility of using this script use it on your own
#please make sure your file system is consistent before using the script "i.e locking a database"
#using this sc... |
a = [1,2,3,4]
print a
a.append(1) #.append sirve para agregar un elemento al final de la lista
print a
a.append("hola")
print a
a.append([1,2])
print a
a.pop() #sirve para eliminar el ultimo elemnto de la lista
print a
print a[1] #sirve para saber la posicion de un elemento en la lista, esto me arroja el valo... |
import sys
from tkinter import Tk
from Client import Client
if __name__ == "__main__":
try:
serverAddr = sys.argv[1] #"192.168.1.102"
serverPort = sys.argv[2] # 3000
rtpPort = sys.argv[3] #"3001"
fileName = sys.argv[4] #"movie.Mjpeg"
except:
print("[Usage: Cli... |
#!/usr/bin/env python
import argparse
import os
try:
import json
except ImportError:
import simplejson as json
class DockerInventory(object):
def __init__(self):
self.inventory = {}
self.docker_host = os.environ.get("DOCKER_HOST")
if not self.docker_host:
self.docker... |
#!/usr/bin/env python2
import pymisca.shell as pysh
import itertools
reload(pysh)
p = pysh.ShellPipe()
# p.chain('convert2bed -iwig')
# p.chain('bs ')
p.chain('tee test.out')
p.chain("awk '$1 > 5' ")
it = list(range(10))
it = map(str,it)
# it = ['%s\n'%x]
p.readIter(it, lineSep='\n')
res = p.checkResult(cmd=None)
pri... |
# Sureyya Betul AKIS
# Extra Assignment: COMP 1411 calculating grade
def main():
while True:
quiz = AcceptUsersInput_quizes()
programming_assignment_1 = AcceptUsersInput_programming_assignment_1()
programming_assignment_2 = AcceptUsersInput_programming_assignment_2()
programming_ass... |
from django import forms
from core.models import Grade, TermModel, Subject
class DateInput(forms.DateInput):
input_type = "date"
class AddStudentForm(forms.Form):
reg_number = forms.CharField(label="Reg Number", max_length=50, widget=forms.TextInput(attrs={"class": "form-control"}))
first_name = forms.... |
# -*- coding: utf-8 -*-
import os
if __name__ == "__main__":
os.system("python -m rasa_nlu.train --config nlu-config.yml --data data/ --path projects --verbose") |
import numpy as np
import matplotlib.pyplot as plt
from scipy.sparse import random as sr
def soft_thd(x, alpha):
sgn = np.sign(x)
mag = np.abs(x) - alpha
mag = np.clip(mag, 0, np.inf)
return sgn * mag
def obj_func(x, A, b):
rho = 1
return (1/2) * np.square(np.linalg.norm((A @ x) - b, 2)) + rh... |
import sqlite3
from string_func import *
import tkinter as tk
from tkinter import *
import time
import datetime
from tkinter import ttk
class Word:
#Format 'word':[[doc_id,[indexes],[doc_id,[indexes]]
words = {}
def __init__(self,word,doc_id,indexes):
#This function will only be used when... |
import datetime
def SCC_1(G):
#print(G)
explored = [False] * len(G)
f=[0] * len(G)
fback = [0] * len(G)
stack = [iter(range(len(G),0,-1))]
finish_time = 1
while stack:
try:
child = next(stack[-1])
#print('try:', child)
if not explored[child - 1]:
... |
import torch
from torch.utils.data import IterableDataset, Dataset as _TorchDataset
from monai.transforms import Compose, Randomizable, apply_transform, LoadImage, RandSpatialCropSamples
from monai.utils import NumpyPadMode
from monai.data.utils import iter_patch
import numpy as np
import cv2
from typing impor... |
import matplotlib.pyplot as plt
import numpy as np
from github import Github # PyGithub: https://github.com/PyGithub/PyGithub
# Returns a dictionary containing the language used and amount of repos that use them
def get_language_details(user):
language_dict = dict()
for repo in user.get_repos():
lan... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import glob
def find_histogram(clt):
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
ret... |
import math
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from xgboost import XGBClassifier
import xgboost as xgb
from sklearn import metrics
# result1=pd.read_csv('train_distance_times_days_... |
# coding=utf-8
from slipper.exc import SlipperException
class SlipperModelException(SlipperException):
pass
class InvalidContractDataError(SlipperModelException):
message = 'Invalid contract data: %(data)s.'
class NotRoutedContractError(SlipperModelException):
message = 'Contract has no route: %(data... |
"""
1) Bucket sort
Generate freq map
2 -> 10 2 appeared 10 times, etc...
5 -> 2
...
Buckets from 0 to n elements (most frequent is if all element are the same). Say there's 20 elements
[[],[],... []] 20 buckets representing freq. Dump numbers with the same freq into respective buckets
e.g. 2 has 10 frequency, s... |
# -*- coding: utf-8 -*-
# @Date : 2016-04-21 20:57:54
# @Author : mr0cheng
# @email : c15271843451@gmail.com
import sys,os
CURRENT_PATH=sys.path[-1]
ARTIST_FOLDER=os.path.join(CURRENT_PATH,'pic','artist')
ARTIST=os.path.join(CURRENT_PATH,'mars_tianchi_songs.csv')
SONGS=os.path.join(CURRENT_PATH,'mars_tianchi_... |
import re
from typing import Optional
import pandas as pd
from bs4 import BeautifulSoup
import logging
from pydantic import BaseModel
from pathlib import Path
logger = logging.getLogger(__name__)
class NextflowWorkflowExecInfo(BaseModel):
workflow: str
execution_id: str
start_time: str
completion_ti... |
# -*- coding: utf-8 -*-
"""
CIFAR-10 Convolutional Neural Networks(CNN) Example
next_batch function is copied from edo's answer
https://stackoverflow.com/questions/40994583/how-to-implement-tensorflows-next-batch-for-own-data
Author : solaris33
Project URL : http://solarisailab.com/archives/2325
"""
import ... |
def maxConsecutiveOnes(num , k):
maxSubArray = 0
currentCount = 0
arrayStart = 0
for arrayEnd in range(len(num)):
if num[arrayEnd] == 0:
if currentCount < k:
maxSubArray = max(maxSubArray, (arrayEnd - arrayStart) + 1)
currentCount += 1
e... |
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN PROGRESS
# UNTESTED. USERDATABASE IS A WORK IN ... |
from django.contrib import admin
from .models import User, Scan, Scanner, SeverityCount, Asset, Vulnerability
# Register your models here.
class ScanInline(admin.StackedInline):
model = SeverityCount
class ScanAdmin(admin.ModelAdmin):
inlines = [ScanInline]
admin.site.register(User)
admin.site.register(Sc... |
# -*- coding: utf-8 -*-
"""
libo 2020/6/21 11:13
"""
import random
import pygame
SCREEN_RECT=pygame.Rect(0,0,480,700)
FRAME_PER_SECOND=60
# 敌机定时器ID
CREAT_ENEMY_EVENT=pygame.USEREVENT
# 发射子弹事件ID
HERO_FIRE_EVENT=pygame.USEREVENT+1
# 继承游戏精灵
class GameSpirit(pygame.sprite.Sprite):
def __init__(self, imag... |
from typing import (
Any,
)
from eth.exceptions import (
HeaderNotFound,
)
from eth_utils import (
to_hex,
)
from lahja import (
BroadcastConfig,
EndpointAPI,
)
from trie.exceptions import (
MissingTrieNode,
)
from p2p.abc import CommandAPI, SessionAPI
from trinity.db.eth1.chain import BaseAs... |
import numpy as np
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch import optim, nn
import data_preprocess
import os
torch.manual_seed(1)
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
use_cuda = torch.cuda.is_available()
word2index, index2word, tag2index, index2tag = da... |
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
from django.contrib.auth.models import User
from .models import Profile
class RegistrationForm(UserCreationForm):
email = forms.EmailField(r... |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
#the slow one, I used this to find the series
from collections import deque
for N in range(10):
paths = deque([(0,0)])
pathsCounter = 0
while len(paths) > 0:
tmp = paths.popleft()
row, col = tmp
if row == N and col == N:
... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import threading
import time
def show(arg):
time.sleep(1)
print 'thread'+str(arg)
for i in range(10):
t = threading.Thread(target=show,args=(i,))
t.start()
print 'main thread stop'
|
from __future__ import annotations
from sqlalchemy import Column, Integer, String, Text, ForeignKey, LargeBinary
from sqlalchemy.orm import relationship
from sqlalchemy.types import TypeDecorator
from pydantic import BaseModel
from typing import Dict, Union, Optional
import logging
import numpy as np
from uuid import... |
"""
- UTF-8 is the default encoding for source code
- All string literals are Unicode
- the u prefix is allowed in Python 3.3
""" |
from rest_framework import generics, status
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from ninjasAPI.models import Product, SalesOrder, SalesOrderItem, Currency_R... |
import json, re, os
from essential.sentence import SplitIntoSentences, ExpendText
from findans.xlnet import find_ans
DATA_DIR = '/home/engine210/LE/dataset/split_dev/multi_dev/'
map_num_to_ans = {0:"A", 1:"B", 2:"C", 3:"D"}
total_ac = 0
total_wa = 0
entries = os.listdir(DATA_DIR)
for idx, entry in enumerate(entries)... |
class PointCloudObject(RhinoObject):
# no doc
def DuplicatePointCloudGeometry(self):
""" DuplicatePointCloudGeometry(self: PointCloudObject) -> PointCloud """
pass
PointCloudGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: PointCloudGeometry(self: PointCloudObject) ->... |
'''
Implements segment tree - a RMQ (Range-Minimum-Query) data structure that supports
range queries in a list of numbers
Query f() across an interval, i..j
e.g., f() can be sum of a[i..j], or min of a[i..j]
Update: updates a[i] to a new value x, and readjusts the segment tree so the RMQ is consistent with the upd... |
import re
import image_formatter
def parse_price(text):
return float(text.replace('$', '').replace(',', '').strip())
def scrape(save_path, soup, params):
data = {}
formatter = image_formatter.ImageFormatter()
data['name'] = params['name']
data['description'] = params['description']
data['price... |
# for j in range(1,11):
# print(1,"*",j,"=",1*j)
# i=3
# for j in range(1, 11):
# print(i, "*", j, "=", i * j)
for i in range (1,11):
print("---------------------")
for j in range(1, 11):
# print(i, "*", j, "=", i * j)
print('%s * %s= %s' %(i,j,i*j)) |
# -- coding: utf-8 --
"""
正常逻辑分类无法完成非线性分类
"""
from sklearn.datasets import make_circles
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets
X, y = make_circles(noise=0.2, factor=0.5, random_state=1)
print(X[:, 0].shape, y.shape)
# logreg = linear_m... |
# i and me is a bit more complex, since they both are "you" in reverse direction
# If you reverse "you", it is dependend wether "you" is used as subject or object
# Not sure how to handle that
directionalPronouns = [
("me", "you"),
("my", "your"),
("mine", "yours"),
("i", "yourself"),
("our", "your"), #importan... |
# Generated by Django 2.2.3 on 2019-07-31 04:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('cour... |
# cnf
def BiConElim(s):
if type(s) is str:
return s
elif s[0] == "iff":
return (["and",
["if",
BiConElim(s[1]),
BiConElim(s[2])],
["if",
BiConElim(s[2]),
BiConElim(s[1])]])
else:
... |
# TODO list flask app
from flask import Flask, redirect, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary... |
"""work URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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-based vi... |
'''
Created on 20-May-2014
@author: Abhinav
'''
from BeautifulSoup import BeautifulSoup
from urlgrabber import UrlGrabber
class HtmlBParser(object):
'''
Html parser using beautifulsoup
'''
def __init__(self, content):
'''
:param str content: HTML content to be parsed
'''
... |
import requests
import json
import math
token = "yourToken"
url = "PlaylistLink"
index = url.find("list=")
playlistId = url[index+5:]
maxResults = 50 # máximo de 50 vídeos por página
url = f"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults={maxResults}&playlistId={playlis... |
# This environment is created by Karen Liu (karen.liu@gmail.com)
import numpy as np
from gym import utils
from gym.envs.dart import dart_env
import pydart2 as pydart
class DartWAMReacherEnv(dart_env.DartEnv, utils.EzPickle):
def __init__(self):
n_dof = 7
obs_dim = 27
frame_skip = 4
... |
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
temp, new_head = None, None
while head:
temp, head, temp.next, new_head = head, head.next, new_head, temp
return new_head
'''
temp = head
... |
import discord
# bot
client = discord.Client()
# IMPORTANT
# placeChannelID Here
channel_ID = 855337824420364298
# placeBotToken here
botToken = "ODY0NDE2NjMzMDE4Mzg0NDA0.YO1IuQ.eoV7yQZ0jfyKVEEVTILBfn7zysM"
@client.event
async def on_ready():
print("Bot on!")
@client.event
async def on_message(m... |
# Generated by Django 2.1.5 on 2019-02-28 14:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0016_auto_20190228_1621'),
]
operations = [
migrations.AddField(
model_name='order',
name='user_email',
... |
"""
Ken Amamori
CS4375 - OS
Python Warm UP
"""
def response(cur, inp):
print("System:\t", end="")
if cur == 0:
if inp == "female":
print("How excellent! Are you a CS major?")
elif inp == "male":
print("Me too. Are you CS major?")
else:
print("Great! Anyways, are you CS major?")
elif cur == 1:
if... |
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
with open('india_covid.csv', 'r') as inFile:
fileReader = csv.reader(inFile)
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
def animate(i):
x = ['29-01-2020']
y = [0]
... |
from typing import List
class Solution:
# 遍历,备忘录
def trap1(self, height: List[int]) -> int:
n = len(height)
left_max = [0] * n
right_max = [0] * n
left_max[0] = height[0]
right_max[n - 1] = height[n - 1]
for i in range(1, n):
left_max[i] = max(heigh... |
import random
name = input("enter in your name: ")
arr = ["hello there", "sveiki", "privet"]
arr1 = ["off you pop", "go away", "ej prom"]
if name == "henrik" or "Henrik":
print(random.choice(arr))
else:
print(random.choice(arr1))
## for loop
for y in range(2,10):
print(y)
def bubbleSort(arr):
n ... |
import random
import time
def insertionSort(list):
n = len(list)
for i in range(n):
indice = list[i]
a = i-1
while (a >= 0 and list[a] > indice):
list[a+1] = list[a]
a = a-1
list[a+1] = indice
def calculateTime(list):
t = time.clock()
insertionSort(list)
... |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File Name: LinuxBashShellScriptForOps:pyUseMapImprovePerformance.py
Version: 0.0.1
Author: Guodong
Author Email: dgdenterprise@gmail.com
URL: https://github.com/Din... |
import sys
# ----------------------------------Data processing-----------------------
class Node:
def __init__(self, num: int, line_data: str):
self.number = num
if line_data:
self.near_by = [int(i) for i in line_data.split(" ")]
self.near_by.sort()
def _... |
# 4_speedTrap.py
# a program that takes the speed limit on a street and the speed of a car in as input,
# and outputs if you are going the legal speed limit, if you are speeding, or if you are excessively speeding
# Date: 9/15/2020
# Name: Ben Goldstone
# gets speed limit from user
speedLimit = int(input("What is the s... |
# -*- coding:utf-8 -*-
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Task
from .serializers import TaskSerializer
class TaskList(APIView):
def get(self, request, format=None):
tasks = Task.objects.all()
s... |
#
# Copyright (c) SAS Institute 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 agreed to in w... |
import click
from Game import Game
@click.group()
def cli():
pass
@cli.command()
@click.option(
"--number-of-players",
"numberOfPlayers",
type=int,
default=2,
prompt="How many players are joining the game party?",
help="Number of players join the games. Minimum 2 or Maximum 6 are allowed... |
# Generated by Django 3.1.2 on 2020-12-07 13:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Competition',
... |
from datetime import datetime
from hello_world_api.hello_api import hello_app
import json
@hello_app.route('/localtime', methods=['GET'])
def response_manager():
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
print("Local time {}".format(utc_dt.astimezone().isoformat()))
r... |
from django.urls import path
from . import views
from .views import *
app_name = 'ACCOUNTS'
urlpatterns = [
path('', Register, name = 'Register'),
path('Login', Login, name = 'Login'),
path('Logout', Logout, name = 'Logout'),
path('Home', Home, name = 'Home'),
path('About', About, name = 'About'),... |
#!/usr/bin/env python3
def main():
a = int(input())
b = int(input())
c = int(input())
p = (a + b + c) / 2
s = (p * (p - a) * (p - b) * (p - c)) ** (1 / 2)
print(s)
if __name__ == '__main__':
main()
|
# lambda_ex1.py
# Write a function that squares a number and returns the value.
# Write it again again using Lambda functions
def square(num):
return num * num
square2 = lambda num: num * num
print(square(9))
print(square2(9))
# lambda_ex2.py
# Write a lambda function for adding two numbers
add = lambda a... |
import unittest
import fermat.utils as utils
from tests.utils import PRIMES
class TestUtils(unittest.TestCase):
def test_compute_modular_inverse(self):
for p1 in PRIMES:
for p2 in PRIMES:
if p1 != p2:
inv = utils.compute_modular_inverse(p1, p2)
... |
# Generated by Django 2.1.3 on 2018-12-01 08:53
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [("core", "0001_initial")]
operations = [
migrations.AddField(
model_name="listitem",
name="pub_id",
field=m... |
import unittest
import torch
from tplinker.models_torch import TPLinkerBert, TPLinkerBiLSTM
from transformers import BertTokenizerFast
class ModelsTest(unittest.TestCase):
def test_tplinker_bert(self):
m = TPLinkerBert('data/bert-base-cased', 24, add_dist_embedding=True)
t = BertTokenizerFast.fr... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
from django.test import LiveServerTestCase
import time
class NewVistorTest(LiveServerTestCase):
def setUp(self):
self.browser=webdriver.Chrome()
self.browser.implicitly_wait(3)
def tearDown(self):
... |
import unittest
from pylazors.formats.bff import *
import tempfile
import os
bff_content = '''GRID START
o o o
o o o
B o o
GRID STOP
A 3
L 5 0 -1 1
L 5 6 -1 -1
P 4 1
P 0 3
'''
class TestBFFFormat(unittest.TestCase):
def test_bff_reader(self):
with tempfile.TemporaryDirectory() as tmp_dir:
... |
import time
from dataclasses import asdict, dataclass
from datetime import datetime
@dataclass
class OuiDataMeta:
timestamp: datetime
source_url: str
source_data_file: str
source_bytes: int
source_md5: str
source_sha1: str
source_sha256: str
vendor_count: int
def as_dict(self):
... |
from django.conf.urls import include
from django.contrib import admin
from django.urls import path
# from django.contrib.auth import views as auth_views
# from django.conf.urls import include, url
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('sharit.urls')),
# path('accounts/', includ... |
from password_philosophy import \
parse_password_data, \
password_is_valid, \
real_toboggan_password_is_valid, \
count_valid_passwords
import pytest
@pytest.fixture
def basic_data():
return [
'1-3 a: abcde',
'1-3 b: cdefg',
'2-9 c: ccccccccc',
... |
#__author__ = 'water'
def enroll(name, gender, age=6, city='Beijing'):
print 'name:', name
print 'gender:', gender
print 'age:', age
print 'city:', city
# print enroll('huaishuo','M',15,'hangzhou')
# print enroll('Bob', 'M', 7)
# print enroll('Bob', 'M', city='shaoxing')
def add_end(l=[]):
l.append... |
# Generic imports
import os
import math
import numpy as np
import matplotlib.pyplot as plt
import numba as nb
from datetime import datetime
from numba import jit
# Custom imports
from buff import *
### ************************************************
##... |
# Agenda con base de datos Sqlite3
import pymysql
def create_db():
'''Creación de la Base de datos'''
conexion = pymysql.connect(host='localhost', #127.0.0.1
user='root', #admin o cualquier otro usuario
password='Anabel08.',
... |
'''
Creado el 17/04/2015
Funcion calcularPrecio para la Tarea 2 de Ing. del Software (ABR-JUL 2015).
Modificacion del codigo legado por FragantSoft.
'''
from decimal import Decimal
from datetime import timedelta
# Maneja una tasa para los dias de semana y otra para los fines de semana.
class Tarifa(o... |
from flask import Flask, request, jsonify
from flask_restplus import Resource, Api, reqparse
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from datetime import datetime
import datetime
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'DATABASE'
app.config... |
"""
Manejo de colecciones y tuplas
@royerjmasache
"""
listA = [(100, 2), (20, 4), (30, 1)]
listB = ["a", "b", "c"]
# Transformación a mayúsculas
letter = map(lambda a: a.upper(), listB)
# Uso de .zip para adjuntar las listas, ordenamiento con .sorted y función anónima para seleccionar la posición
print(list(zip(sorte... |
# vim: ai ts=4 sts=4 et sw=4
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.http import require_GET
from mwana.apps.reports.utils.facilityfilter import get_rpt_facilities, get_rpt_districts, get_rpt_provinces
from mwana.apps.alerts.labresultsalert... |
from pymongo import MongoClient
###########################################################
client = MongoClient('localhost:27017', connect = False)
db_users = client['user']
db_images = client['images']
###########################################################
|
"""A set of functions for checking an environment details.
This file is originally from the Stable Baselines3 repository hosted on GitHub
(https://github.com/DLR-RM/stable-baselines3/)
Original Author: Antonin Raffin
It also uses some warnings/assertions from the PettingZoo repository hosted on GitHub
(https://github... |
# C1.py
# Modified from B2.py
# works for general d
# Computes the volume of a n-dimensioanl sphere
# Compares Numerical (Monte carlo) and analytic techniques for the computtaion
import random, math, pylab
import numpy as np
from operator import mul
# no of dimensions
dd=20
dimensions = range(1, dd)
Qs = []
Vol = []... |
import tensorflow as tf
import numpy as np
import os
import cv2
import glob
import math
import time
def getPadd(z, size_x, size_y):
return ((math.floor((size_x - z[0])/2),math.ceil((size_x - z[0])/2)),(math.floor((size_y - z[1])/2),math.ceil((size_y - z[1])/2)), (0,0))
def generateNpyDataFromInput(inputDir, outputDi... |
from flask_login import LoginManager, current_user, login_user, logout_user, login_required
from re import compile
domain = "email.wm.edu"
class EmailRegex:
def __init__(self):
self._email = compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
def validemail(self, e):
return self._... |
class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
dict = {c:i for i,c in enumerate(words)}
answer = []
for word in words:
n = len(word)
candidate = word[::-1]
if... |
import os
class EMProject(object):
def __init__(self):
self.core_home = os.environ['EM_CORE_HOME']
@staticmethod
def core_home():
return os.environ['EM_CORE_HOME']
def write_sql_task(self, sql_task):
self.name = sql_task
class SQLTask(object):
def __init__(self):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import SellPair, Sell
admin.site.register(SellPair)
admin.site.register(Sell)
|
def is_wrap(A, B, t, i):
if i == 0:
return False
return A[i] <= B[t]
def find_un(A, B, i):
ca = i - 1
while is_wrap(A, B, ca, i) and ca >= 0:
ca -= 1
return ca
def solution(A, B):
ans = [0] * (len(A) + 1)
for i in range(len(A)):
# for start
if i == 0:
... |
import discord
import requests
import random
from discord.ext import commands
class Cuties(commands.Cog):
def __init__(self, client):
self.client = client
# Events
@commands.Cog.listener()
async def on_ready(self):
print("shibashiba is online")
# Commands
@commands.c... |
"""Function from R-base that can be used as verbs"""
from typing import (
Any, Iterable, List, Mapping, Optional, Tuple, Union
)
import numpy
from pandas import DataFrame, Series, Categorical
from pipda import register_verb
from ..core.types import IntType, is_scalar
from ..core.contexts import Context
from ..cor... |
import numpy as np
import matplotlib.pyplot as plt
import torch
import math
def read(filename):
dataset = []
with open(filename, 'r') as f:
for line in f:
line = line.strip('\n')
line = line.split(',')
dataset.append(line)
# print(dataset[32])
re... |
import Address
class Provider:
address = Address()
longCoord = 0.0
latCoord = 0.0
ru = 0.0 #unique radius from provider
fu = 0.0 #unique fade [0-1] from provider
rd = 0.0 #default radius from resourceType
regions = [] ... |
input = """
c(2).
d(1,2).
e(2,1).
okay1(X):- c(X), #count{V:d(V,X),e(X,Y)} = 1.
okay2(X):- c(X), #count{V:e(X,Y), d(V,X)} = 1.
:- #count{V:d(V,X), e(V,Y)} > 1.
:- #count{V:e(V,Y), d(V,X)} > 2.
:- #count{V:d(V,a), e(V,b)} > 1.
:- #count{V:e(V,b), d(V,a)} > 2.
"""
output = """
{c(2), d(1,2), e(2,1), okay1(2), okay2(2)}
... |
import sqlite3
"""
Ebben a functionban hozódik létre az adatbázis amiben a bolt termékai vannak
"""
def connect():
conn = sqlite3.connect("products.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, nev text, ar real) ")
conn.commit()
conn... |
import pickle, json
from typing import List
from data_reader.binary_input import Instance
from scipy.sparse import csr_matrix, dok_matrix, find
import os
import csv
import pickle
import numpy as np
from data_reader.operations import sparsify, csr_mat_to_instances
def save(data, outfile='./data_reader/data/... |
#/*
# * Copyright (c) 2019,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * Bruce Ashfield <bruce.ashfield@xilinx.com>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import copy
import struct
import sys
import types
import unittest
import os
import getopt
import re
import subprocess
import shutil
fr... |
from django.contrib import admin
from parse.models import DayHistory
# Register your models here.
class DayHistoryAdmin(admin.ModelAdmin):
list_display = 'id', 'date'
admin.site.register(DayHistory, DayHistoryAdmin) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.