text
stringlengths
38
1.54M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 30 15:48:18 2018 @author: kazuki.onodera """ import numpy as np import pandas as pd import os import utils utils.start(__file__) #============================================================================== PREF = 'f110_' KEY = 'SK_ID_CURR' os....
from assets.models import Server,Label,Project,IDC,ServerLog from django import forms from django.forms import widgets from django.forms import fields from django.utils.translation import gettext_lazy as _ def server_log(*args,**kwargs): try: rows = kwargs.get('rows') ServerLog.objects.create(**ro...
import densetorch.data import densetorch.engine import densetorch.misc import densetorch.nn try: from .version import __version__ # noqa: F401 except ImportError: pass
"""To check if string is palindrome or not A string is said to be palindrome if the reverse of the string is the same as string. For example, “malayalam” is a palindrome, but “music” is not a palindrome.""" def isPalindrome(check): reverse_string=check[::-1] if check==reverse_string: return "Str...
def main(): print("hello world") # TODO: Setup the tests # TODO: Get inputs in JSON format # TODO: Setup the ojects: Algorithm, Team member -> developer, management, Task # TODO: Find random solution # TODO: Add logical rules before solution finding if __name__ == '__main__': main()
from django.shortcuts import render from django import forms import pandas as pd from datetime import datetime def home(request): df = pd.read_csv("/home/siddharth/Stock-Market-Analysis-master/Stock-Market-App/data.csv") date = df.ix[:,0].apply(lambda x: datetime.strptime(x,"%Y-%m-%d").date()) date = date.to_json(o...
import random def calcRandom(_amplitude, _perc_random): return _amplitude - random.uniform(_amplitude-((_perc_random*_amplitude)/100),_amplitude+((_perc_random*_amplitude)/100))
#!/usr/bin/env -S python3 -W ignore """ Retrieves the bitcoin price in euros """ import requests try: r = requests.get('https://api.kraken.com/0/public/Ticker?pair=BTCEUR') ticker = r.json() print('%.2f€' % float(ticker['result']['XXBTZEUR']['c'][0])) except Exception: print('No data.')
#!/usr/bin/python print ("Jonathan, recuerda esfozarte y ser mejor persona cada dia ") print ("Tus conocimientos, como Ingeniero de Sistemas, Informatica, Software y Computacion demostraras de lo que heres")
# 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, software # d...
from sqlalchemy import exc from flask import Blueprint, jsonify, request from jsonpatch import JsonPatch, JsonPatchException, JsonPatchConflict from jsondiff import diff import pprint from datetime import datetime import re from project import db from project.api.models import User, School, Site from project.tests.u...
""" Django settings for sit project. Generated by 'django-admin startproject' using Django 1.11.13. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ from __future...
import main import setup import constants as c import pygame as pg class AiMode(main._Mode): def __init__(self): super().__init__() def startup(self): pass def update(self, surface): pass def get_event(self, event): pass
""" So this is a script for showing todays prime number. Started 21. September 2019. For some reason. Please know that this is a inside joke so dont expect understanding anything. """ from datetime import date f_date = date(2019, 9, 21) l_date = date.today() f = [] n_days = f_date - l_date m_days = n_days.days m_days...
""" 题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 """ """ 解题思路 第一个栈stack_1临时保存插入的数据,当调用弹出函数时候,若stack_2不为空则直接弹出, 若为空,则把stack_1中的数据全部弹出放到stack_2中。 注:stack_2都是存放的旧的数据,弹出时一定符合队列的规律。 """ class Solution: def __init__(self): self.stack_1 = [] self.stack_2 = [] def push(self,node): self.stack...
number = str(input()) # разделение числа на две части first_half = int(number) // 1000 second_half = int(number) % 1000 # цифры первой половины first = first_half // 100 second = first_half % 100 // 10 third = first_half % 100 % 10 # цифры второй половины fourth = second_half // 100 fifth = second_half % 100 // 10 s...
n=int(input()) a=[0]*(n+1) a[1]=1 for i in range(2,n+1): a[i]=a[i-1]+a[i-2] print(a[n-1],a[n],end=' ')
# coding:utf-8 # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # 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 req...
import socketio import eventlet sio = socketio.Server(cors_allowed_origins='*') app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print('connect ', sid) sio.emit('NEW_CONNECTION',{"id":"01234567","money":56450,"passport":"Pasaporte platino full"}) if __name__ == '__main__': eventlet.wsgi...
from celery import Celery from music_aekt.downloaders.zing import ZingDownloader from music_aekt.downloaders.nhaccuatui import NCTDownloader from music_aekt.player import moc app = Celery('tasks', backend='redis://localhost', broker='redis://localhost') SAVE_LOCATION = '/tmp' HEADERS = {'U...
def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 operations = {"+":add, "-":subtract, "*":multiply, "/":divide } def calculator(): num1 = float(i...
import random def answers(ch): if ch==1: print("It is certain") elif ch==2: print("Good outlook") elif ch==3: print("Most likely") elif ch==4: print("Reply hazy") elif ch==5: print("Cannot predict now") elif ch==6: print("ConceNtrate and ask again") elif ch==7: print("My ...
# ---> # Created by liumeiyu on 2020/3/16. # '_' import cv2 import numpy as np import matplotlib.pyplot as plt from graphy import Graph '''图像二值化''' class Binary(Graph): def __init__(self, img_path): super().__init__(img_path) def img_biny_np(self, thrd): img_b = self.copy_img() for ...
# CodeSkulptor runs Python programs in your browser. # Click the upper left button to run this simple demo. # CodeSkulptor runs in Chrome 18+, Firefox 11+, and Safari 6+. # Some features may work in other browsers, but do not expect # full functionality. It does NOT run in Internet Explorer. import simplegui import ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KoubeiMerchantDepartmentCreateModel(object): def __init__(self): self._auth_code = None self._dept_name = None self._label_code = None self._parent_dept_id = None ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import numpy from .tf_idf import TfIDf from .build_vsm import BuildVsm from sklearn.cluster import KMeans from .save_to_redis import r, remove_to_redis from .save_to_redis import save_to_redis, remove_to_redis from .config import load_data_set, classify_...
import sys VOWELS = set(['a', 'e', 'i', 'o', 'u']) def count_vowels_consonants(string): if not isinstance(string, basestring): raise TypeError('Input must be a string') vowels_count = dict( a=0, e=0, i=0, o=0, u=0 ) total_consonants = 0 for char in string: if not char.isalpha(): continue c...
from dataloader import DataLoader import torch from collections import namedtuple import pickle import utils print('> Loading DataLoader') class opt: debug = 0 dataloader = DataLoader(None, opt, 'i80') print('> Loading splits') splits = torch.load('/home/atcold/vLecunGroup/nvidia-collab/traffic-data-atcold/data_i...
# -*- coding: UTF-8 -*- from nameko.rpc import rpc import pymysql from docx import Document from docx.enum.table import WD_ROW_HEIGHT_RULE from docx.shared import RGBColor, Pt from docx.enum.text import WD_UNDERLINE, WD_LINE_SPACING from docx.oxml.ns import qn class Compute(object): name = "test" ...
__author__ = 'Amit' from bs4 import BeautifulSoup # noinspection PyUnresolvedReferences from WS_Specs import ws_specs def title_string_scrap(html_response_data): """ A) Takes html response data (bytes)--> Returns string value in the title section """ soup = BeautifulSoup(html_response_data) retur...
# Generated by Django 2.1.2 on 2019-03-01 06:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('inventario', '0034_auto_20190228_2056'), ] operations = [ migrations.DeleteModel( name='Direccion_Envio', ), migrations....
''' If a runner runs 10 miles in 30 minutes and 30 seconds, What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km) ''' #Calculate speed in miles per second time_seconds = (30*60) + 30 distance_miles = 10 speed_miles_per_second = distance_miles / time_seconds #Convert speed (miles per second) t...
import socket import random import conmysql class UserClient: def __init__(self): self.client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.ip = socket.gethostbyname(socket.gethostname()) self.port = -1 def connect(self,hostip): port = -1 while port ...
#!/usr/bin/python import math class PaginationHelper: # The constructor takes in an array of items and a integer indicating # how many items fit within a single page def __init__(self, collection, items_per_page): self.collection = collection self.items_per_page = items_per_page ## returns the number...
#import pd from pymisp import (MISPEvent, MISPSighting, MISPTag, MISPOrganisation, MISPObject) from pymisp import MISPEvent, MISPObject, PyMISP, ExpandedPyMISP, MISPSharingGroup import argparse import csv #import pandas as pd import requests import io import os import time import datetime import json #impor...
# Generated by Django 2.0.1 on 2018-01-22 06:10 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ApplicationDomainTable', f...
#!/usr/bin/env python #from localOptionsAll import * from localOptionsAll import * ## datasets = [ # 'MET', # 'MET_data_Reco', ## 'AMSB_mGrav50K_0p5ns_Reco', ## 'AMSB_mGrav50K_1ns_Reco', ## 'AMSB_mGrav50K_5ns_Reco', ## 'Wjets', ## 'ZJetsToNuNu', ## 'TTbar', ## 'QCD', ## 'DY', ## ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 10 17:26:37 2019 @author: matteo """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.stats as sts import math import os import glob import warnings import potion.envs import gym env = gym.make("LQ-v0") small_eps...
# coding=utf-8 from unittest import TestCase from squirrel_play import squirrel_play class SquirrelPlayTest(TestCase): def test_squirrelplay_no_sun(self): self.assertTrue(squirrel_play(70, False)) def test_squirrelplay_sun(self): self.assertTrue(squirrel_play(95, True)) def test_squirrel...
import maya.cmds as cmds def createLoc(type): print type if cmds.objExists("loc_Grp_1"): print "it exists already" else: if type == "first": filePath = "R:/Jx4/tools/dcc/maya/scripts/autoRigger/importFiles/biped/" elif type == "third": filePath = "R:/Jx4/tools...
# Generated by Django 3.1.2 on 2020-10-29 14:42 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
#TRABAJO CONJUNTO REALIZADO POR JOSE LUIS, SANDRA Y JAUME# version = "1.0" #Nombre del proyecto - BrisCards #--------------------------------Este archivo contiene el juego #Imports import random import time import os import sys import msvcrt #--------------------------------------------------------------...
# -*- coding: utf-8 -*- """ Created on Nov 12 15:22:30 2015 @author: frickjm """ import helperFuncs import matplotlib.pyplot as plt import skimage.io as io from skimage.transform import resize import numpy as np from os import listdir from os.path import isdir from os import mkdir from os.path import isfile from r...
################################################################################ # Copyright 2019-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the LICENSE file for details. # SPDX-License-Identifier: MIT # # Fusion models for Atomic and molecular STructures (FAST) # File util...
#!/usr/bin/python3 import sys; import argparse; import random; ##This script is for predecting toss between "Lengaburu" and "Enchai" teams #function definition: ***toss_result()*** def toss_result(): teams=['lengaburu','enchai']; for team in teams: if (team == "lengaburu") : if (weather == "clear") & (match_...
import datetime from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.hashers import check_password from django.shortcuts import get_object_or_404 from ninja import Schema from ninja.errors import ValidationError from ninja.orm import create_schema from pydantic impor...
from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Book # Create your views here. class BookListView(ListView): model = Book context_object_name = 'book_list' ## Can access it with this name else would had to use template_nam...
#!/usr/bin/env python from termcolors import * import sys tc = [] for n in xrange(len(tf)): tc.append((tf[n], tfl[n])) for b in tb: for c, lc in tc: sys.stdout.write("%s %s " % \ (globals()[b](globals()[c]('XXXXX')), globals()[b](globals()[lc]('OOOOO')))) print('\n')
#!/usr/bin/env python2.7 from __future__ import print_function # This is a placeholder for a Google-internal import. from grpc.beta import implementations import tensorflow as tf from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 import base64 import os tf.ap...
from .Instruccion import Instruccion from .Mensaje import * from enum import Enum class TIPO_ARITMETICA(Enum) : SUMA = 1, RESTA = 2, MULTIPLICACION = 3, DIVISION = 4, RESIDUO = 5, ABSOLUTO = 6 class Aritmetica(Instruccion) : def __init__(self, izquierda, derecha, tipo, linea, columna) : ...
# Generated by Django 2.2.1 on 2019-08-09 16:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Pay', fields=[ ('id', models.AutoField(auto...
from .parser import xlsxParser from math import floor from random import shuffle from .settings import * class Classes: parser = xlsxParser() def __init__(self, blocks): #constructor and intializing the data from the database self.blocks = blocks self.subjectChoices = [[name[0].lower(), [nam...
# Cody Holthus - Rip City Robotics import dash_bootstrap_components as dbc import dash_html_components as html import dash_table class TabContents: def __init__(self): self.dut_config_tab = dbc.Card( dbc.CardBody( [ html.P("Configure the DUT", className="ca...
from __future__ import with_statement import os import sys import datetime import flask import simplejson def todfo(ci): cijson=ci.to_json() cidict=simplejson.loads(cijson) return cidict def todfl(cil): cijsonl=[e.to_json() for e in cil] cidictl=[simplejson.loads(e) for e in cijsonl] return c...
# -*- coding: utf-8 -*- """ Created on Thu Nov 16 10:47:43 2017 @author: Jon Wee """ import numpy as np #import pandas as pd import matplotlib.pyplot as plt #from scipy import stats ## ln consumption growth samples = 1000 #epsilon = np.random.normal(loc=0, scale=1,samples) # random function epsilon...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
#Out of Boundary Paths from collections import defaultdict class Solution: def findPaths(self, m, n, N, i, j): dp = defaultdict(lambda: 0) dp[(i,j)] = 1 M = pow(10, 9) + 7 count = 0 directions = [ [1, 0], [-1, 0], [0, 1], [0, -1] ] for k in range(N): new_...
from random import randint import pytest from yadm import Document from yadm import fields # from yadm.aio.aggregation import AioAggregator class Doc(Document): __collection__ = 'docs' i = fields.IntegerField() @pytest.fixture(scope='function') def docs(loop, db): async def gen_docs(): async w...
import sys sys.stdin = open("input.txt") from collections import deque T = int(input()) def func(start) : queue = deque([(start, 0)]) visited = [0] * (V+1) # 인덱스 맞추기 위해 앞에 한칸 비우기 while queue : # 큐가 빌때까지 now, distance = queue.popleft() if now == G : # 도착하면 거리 반환 return distance ...
from django.urls import path from .views import BlogPageView, AboutPageView, BlogDetailView, BlogCreateView,BlogUpdateView, BlogDeleteView urlpatterns=[ path('', BlogPageView.as_view(), name='main-home'), path('about/', AboutPageView.as_view(), name='home-about'), path('post/<int:pk>/', BlogDetailView.as_...
from torch import nn from torch.nn import functional as func from torchsupport.modules.basic import MLP from betafold.generate.angles import \ TorsionConditionalPrior, TorsionConditionalEncoder, TorsionConditionalDecoder class ReshapeMLP(nn.Module): def __init__(self, in_size, out_size, **kwargs): super(Resh...
#Input values to an array from the user and sort the array in ascending order. arr=[] n=int(input("length of array:")) for j in range(0,n): m=int(input()) arr.append(m) for i in range(0,n): for j in range(i+1,n): if(arr[i] < arr[j]): temp = arr[i]; arr[i] = arr[j]...
def ration(user_breakfast_calories, user_breakfast_proteins, user_breakfast_fats, user_breakfast_carbohydrates, user_dinner_calories, user_dinner_proteins, user_dinner_fats, user_dinner_carbohydrates, user_supper_calories, user_supper_proteins, user_supper_fats, user_supper_carbohydrates, file): ''' (int......
import sys import preprocessing from models import ConvModel, FCModel, A3CModel, GRUModel import numpy as np class HyperParams: def __init__(self, arg_hyps=None): hyp_dict = dict() hyp_dict['string_hyps'] = { "exp_name":"default", "model_type":"gru",...
from typing import List from collections import defaultdict class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int: maxLength = 0 seqDict = defaultdict(int) for num in arr: seqDict[num] = max(seqDict[num], 1+ seqDict[num-difference]) maxL...
from tkinter import ttk from tkinter import font from tkinter import * from tkinter import messagebox from tkinter.ttk import * import requests import io from PIL import Image, ImageTk from urllib.request import urlopen import os apiKey = os.environ.get('API_KEY') def getLocation(): url = "https://ip-geo-location...
from api.models.data_engine_job import DataEngineJob import threading class __Singleton(type): """Utility for making the JobQueue service a singleton.""" instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = super().__call__(*args, **kwargs) ...
obj_model_def = "ObjectDetector/config/yolov3.cfg" obj_weights_path = "ObjectDetector/weights/yolov3.weights" obj_class_path = "ObjectDetector/data/coco.names" obj_img_size = 416 class ObjDetectorInfo: def __init__(self): self.model_def = obj_model_def self.weights_path = obj_weights_path se...
from datetime import datetime class Bokning: def __init__(self, starttid, sluttid, kund, sporthall): self._starttid = starttid self._sluttid = sluttid self._kund = kund self._sporthall = sporthall def getHall(self): return self._sporthall def getDates(self): ...
import socket import os ROOT_PATH = '/home/dev1/share/' UPLOAD_PATH = '/home/dev1/uploads/' def create_listen_sock(port=8080): listen_fd = socket.socket() listen_fd.bind(('', port)) listen_fd.listen(5) return listen_fd def parse_client_data(data: bytes): return data.split(b':')[0].strip() de...
from setuptools import setup, find_packages import sys, os version = '0.0.1' setup(name='geeknote', version=version, description="GeekNote python evernote client", long_description="""\ a python evernote client """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction...
from django.conf.urls import url from django.urls import path from drf_yasg import openapi from drf_yasg.views import get_schema_view from . import views from rest_framework_jwt.views import obtain_jwt_token schema_view = get_schema_view( openapi.Info( title='API', default_version='v1' ), ) ...
def exist(x): global now for i in list(str(x)): now[int(i)] += 1 if 0 in now: return True else: return False num = int(input()) count = 0 for cases in range(1,num+1): n = int(input()) count += 1 if n == 0: print('Case #'+str(count)+': INSOMNIA\n') ...
import requests import json import pandas as pd import xlwings as xw from time import sleep from datetime import datetime, time , timedelta import os import numpy as np pd.set_option('display.width',1500) pd.set_option('display.max_columns',75) pd.set_option('display.max_rows',1500) url_oc = "https://www...
import factory from django_eth_events import models class DaemonFactory(factory.DjangoModelFactory): class Meta: model = models.Daemon block_number = 0
""" Authors: Kevin Eckert General Control File for Sensor Test This is simply a script that allows one to get data from the BMP388 sensor and see it printed on screen, as well as access more detailed, stored information which is place in a CSV formatted txt file. """ from time import sleep from machine imp...
# -*- coding: utf-8 -*- """ Workflows to grab input file structures. """ import logging as log import os import nipype.pipeline.engine as pe from hansel.operations import joint_value_map, valuesmap_to_dict from nipype.interfaces.io import DataSink from nipype.interfaces.utility import IdentityInterface from neuro_pyp...
def countConstruct(target, word_bank): tab = [0 for _ in range(len(target)+1)] # seed - there's only 1 way to construct an empty string tab[0] = 1 for i in range(len(target)+1): if tab[i] != 0: for word in word_bank: if target[i:].startswith(word): tab[i+len(word)] += tab[i] return tab[-1] pri...
buildings = [(1,11,5), (3,6,7), (3,13,9), (12,7,16), (16,3,25), (19,18,22)] edges = [] edges.extend([building[0],building[2]] for building in buildings) edges = sorted(sum(edges,[])) #sorting and flatening the list of building edges current = 0 points = [] for i in edges: active = [] active.exten...
MESSAGE_TIMESPAN = 2000 SIMULATED_DATA = False I2C_ADDRESS = 0x76 GPIO_PIN_ADDRESS = 24 BLINK_TIMESPAN = 1000
# Generated by Django 2.2.1 on 2019-08-07 05:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BlogCategory', fields=[ ('id', models.AutoF...
import time from base.base_action import BaseAction from base.driver import get_driver from page.page import Page class TestShortCut: def setup(self): self.driver = get_driver() self.page = Page(self.driver) def teardown(self): time.sleep(3) self.driver.quit() # 9.6 王茹楠 ...
#for extracting images from urllib.request import urlopen from bs4 import BeautifulSoup import re #opening extracted images from PIL import Image import requests from io import BytesIO #convertine image to text import pytesseract #storing data into json file import json #goes to where tesseract download is saved pytes...
class Environment: def setup(self): raise NotImplementedError def start(self): raise NotImplementedError def reset(self): raise NotImplementedError def clear(self): raise NotImplementedError def pull(self): raise NotImplementedError # return data,...
import math l = int(input('enter lower input')) x = l while x >= l: y = str(x) sum1 = 0 for i in y: num = int(i) f = math.factorial(num) sum1=sum1+f if sum1==x: print(x) else: pass x = x + 1
"""JSON helper functions""" import os import calendar from datetime import date import json import traceback from functools import wraps from django.views.decorators.csrf import csrf_exempt from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse from rest_framework_simplejwt.auth...
import sys from pathlib import Path #sys.path.append(str(Path('./..').resolve())) import numpy as np from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchnet as tnt import pandas as pd import yaml from utils import logger...