text
stringlengths
38
1.54M
import os from pathlib import Path from urllib.parse import urlparse def get_absolute_path(path: str): if path.startswith("http") or path.startswith("https"): return path else: try: if Path(path): return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) ...
from typing import Final, List from aiohttp import web from aiohttp.web_routedef import RouteDef from hibernia.server.kvstore.handlers import set_handler, get_handler, del_handler ROUTES: Final[List[RouteDef]] = [ web.post('/{key}', set_handler), web.get('/{key}', get_handler), web.delete('/{key}', del_h...
from sys import stdin def IsPrime(x): for i in range(2, int(x ** 0.5) + 1): if not x % i: return False return True for x in stdin: x = x[:-1] y = x[::-1] a = IsPrime(int(x)) b = IsPrime(int(y)) if not a: print("%s is not prime." %x) elif (a and not ...
import re ccd = """ VALUE $fipsf '01'='Alabama' '02'='Alaska' '04'='Arizona' '05'='Arkansas' '06'='California' '08'='Colorado' '09'='Connecticut' '10'='Delaware' '11'='District of Columbia' '12'='Florida' '13'='Georgia' '15'='Hawa...
def main(): word = "answer" numbers = [0, 0, 0, 0] for i in range(4): number = int(input()) numbers[i] = number if((numbers[0] == 9 or numbers[0] == 8) and (numbers[1] == numbers[2]) and (numbers[3] == 9 or numbers[3] == 8)): word = "ignore" print(word) if __name__ == '__ma...
from globais import BLOSUM_62, PENALIDADE_INDEL import sys class Celula: def __init__(self, valor=None, ponteiro=''): self.valor = valor self.ponteiro = ponteiro def sequencia_arquivo(nome_arquivo): seq = '' try: with open(nome_arquivo, 'r') as arquivo: for linha in arq...
import os from src import webscrape_data from db.models import TransitLine, View, Location, Anxiety from flask import Flask, render_template, request from flask_cors import CORS, cross_origin from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker app = Flask(__name__) scraper = webscrape_dat...
"""ChemBase URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.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-base...
from pynput import mouse, keyboard import functools from queue import Queue import logging class MouseEvent(): def __init__(self, action, x, y, button=None, pressed=None, time=None): self.action = action self.x = x self.y = y class KeyBoardEvent(): def __init__(self, key, time=None): ...
from pathlib import Path from dataclasses import dataclass @dataclass(frozen=True) class DoccommentLine: file: Path "Path for file that originally contained this doc comment." line: int "Line in `self.file` that contained this doc comment." column: int "Column in `self.file` that contained thi...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by cyy on 2019/10/21 import numpy as np import os from sklearn.model_selection import train_test_split import pandas as pd from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.metrics import confusion_matrix import matplotlib.pypl...
print("Nancy Srivastava 1900300109006") print("hello world") print("enter the lengths of the triangle sides: ") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) if a == b == c: print("Equilateral triangle") elif a==b or b==c or c==a: print("isosceles triangle") else: print("Scalene tria...
fruits1 = ['mango','apple','guava'] # fruits1.append('grapes') # fruits1.insert(1,'grapes') #to add data to list at a particular position # print(fruits1) fruits2=['litchi','pomegranate'] # fruits = fruits1+fruits2 # to conacatenate two list # print(fruits) # EXTEND_METHOD fruits1.extend(fruits2) fruit...
from logging import root from kivymd.app import MDApp from kivymd.uix.floatlayout import MDFloatLayout from kivy.properties import ObjectProperty, StringProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivymd.uix.picker import MDDatePicker from kivymd.uix.picker import MDThemePicker from kivy.core...
import sdl2 import sdl2.ext import time import figures class Render: def __init__(self): """ Создание инструментов pysdl2 для рисовашек """ try: print("Grafics initializing... ", end = '') sdl2.ext.init() self.BLACK_COLOR = sdl2.ext.Color(128, 12...
from corehq import toggles from corehq.apps.app_manager.dbaccessors import get_case_types_from_apps from corehq.apps.app_manager.util import all_case_properties_by_domain from corehq.apps.data_dictionary.models import CaseProperty, CaseType from corehq.apps.export.models.new import CaseExportDataSchema class OldExpor...
# -*- coding: utf-8 -*- import pytest from pangres.helpers import validate_chunksize_param # # Tests @pytest.mark.parametrize('value', [-1, 0, 10, 'abc']) def test_valid_chunksize_values(_, value): # 10 is the only valid value here if value == 10: validate_chunksize_param(value) return # ...
class Solution: def calculate(self, s: str) -> int: stack = [] cur = None operator = None operand = None n = len(s) i = 0 while i < n: c = s[i] if c == "(": stack.append([cur, operator]) cur = None ...
import numpy as np import torch, os from numpy import nan from CCM import CCM from DMTS import DMTS from dmts_frontex import save_data computer = "cpu" dev_str = 'cpu' cores = 6 num_workers = 4 * cores enc = torch.float64 dev = torch.device(computer) info = False reject = False plot = False ...
# +,-,*,/,% a=4 b=2 c =a+b print(c,type(c)) c= a/b print(c,type(c)) #by default floating division c=a//b #// integer division this discards fractional part print(c,type(c)) c=a*b print(c,type(c)) c= a-b print(c,type(c)) b=2.2 c =a-b print(c,type(c)) # string + opertor is a joining operator
import torch import csv # For Ploting import matplotlib.pyplot as plt from matplotlib.pyplot import figure def plot_learning_curve(loss_record, title=''): ''' Plot learning curve of your DNN (train & dev loss) ''' total_steps = len(loss_record['train']) x_1 = range(total_steps) x_2 = x_1[...
from io import BytesIO from dubbo.codec.hessian2 import Decoder, _desc_to_cls_names, _cls_names_to_desc, encode_object, DubboRequest, DubboResponse, DubboHeartBeatResponse, DubboHeartBeatRequest, new_object from dubbo.java_class import JavaList def test_encode_object(): assert encode_object(None) == b'N' asse...
def a(n): return n/2 + 1 t = int(raw_input()) for i in range(0,t): n = int(raw_input()) print a(n)
import os import re import logging import logging.config import time from emop.lib.emop_settings import EmopSettings from emop.lib.emop_api import EmopAPI # from emop.lib.emop_stdlib import EmopStdlib logger = logging.getLogger('emop') class EmopBase(object): def __init__(self, config_path): self.settin...
import copy from typing import List, Tuple import lightgbm as lgb import numpy as np import pandas as pd from lightgbm import Booster class LightGBM: def train_and_predict( self, train: pd.DataFrame, valid: pd.DataFrame, weight, categorical_features: List[str], tar...
# Sentiment Analysis Module # Text classifier # can be apply for any label text as long as they have to categories # spam msg classifier # Now we stop shuffling our data, now we know which is positive and which is negative. import nltk import random from nltk.corpus import movie_reviews from nltk.classify.scikitlearn ...
import RPi.GPIO as GPIO import time output_pins = { 'JETSON_XAVIER': 18, 'JETSON_NANO': 33, 'JETSON_NX': 33, } output_pin = output_pins.get(GPIO.model, None) if output_pin is None: raise Exception('PWM not supported on this board') def main(): # Pin Setup: # Board pin-numbering scheme GPI...
from django.shortcuts import redirect, render_to_response, render from django.contrib.auth import login from django.contrib.auth.models import User from django.template.context import RequestContext from django.contrib.auth.decorators import login_required from hackaglobal.models import Event, Attendee, HackaCity from ...
import ast from ..df.types import Definition from ..df.base import op # Definitions InputStr = Definition(name="InputStr", primitive="str") EvaluatedStr = Definition(name="EvaluatedStr", primitive="generic") @op( inputs={"str_to_eval": InputStr}, outputs={"str_after_eval": EvaluatedStr}, conditions=[],...
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # --- Match keyword length with message length --- # def prepKeywd(message, keyword): keyWdProg = 0 newKeyWd = "" for i in range(0, len(message)): keyIndex = i % len(keyword) #modulo divides i by the keyword length then returns the remainder. ...
import torch import numpy as np def make_divisible(v, divisor=8, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v+divisor/2)//divisor * divisor) if new_v < 0.9 * v: new_v += divisor return new_v def make_model_name(cfg): return cfg['model']...
import random from collections import deque import numpy as np import pygame from pygame.locals import * from framework.core import Environment from framework.environments.snake_objects import * """---SnakeAbstract class""" class SnakeAbstractFramed(Environment): """An abstract Reinforcement Learning represent...
import sys from time import sleep import pygame from bullet import Bullet from alien import Alien def check_events(ai_settings, screen, ship, bullets): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEY...
import FOL.Alphabet as symb from FOL.Term import Term, Variable def exchange_left(s_upper, s_lower): if s_upper.succedent != s_lower.succedent: return False if len(s_upper.antecedent) != len(s_lower.antecedent): return False antecedent_uniq = [] for i in range(len(s_upper.antecedent)):...
from model import cliente from model import compra from model import connection from model import fornecedor from model import funcionario from model import gerente from model import produto from model import sessao from model import venda from model import vendedor
import os from flask import Flask, jsonify, request, flash, url_for from werkzeug.utils import secure_filename import cv2 import imutils import numpy as np import api UPLOAD_FOLDER = '/Users/iandavisSSD/programming/tp/TP_App_Backend/fileuploads' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app =...
import subprocess import sys import datetime import os import logging from preprocessing import download_dump_files from preprocessing import strip_text_and_extract_fields from preprocessing import wiki_dump_to_dataframe_lxml DOWNLOAD_URL_LIST_FILE = '/home/s2575760/project/wiki_bigdata/resources/wikidumps_source_dow...
#!/usr/bin/python3 """ Get all states """ import MySQLdb from sys import argv if __name__ == '__main__': """Get all states""" conn = MySQLdb.connect(host='localhost', port=3306, user=argv[1], password=argv[2], db=argv[3]) cur = conn.cursor() cur.execute("SELECT cities....
import json class KillRecord: def __init__(self, user_id, user_name, kill_count): self.user_id = user_id self.user_name = user_name self.kill_count = kill_count def from_json(cls, record_as_json: str): record = json.loads(record_as_json) return cls(user_id=record['user_id'], user_name=record['...
#7-9 主流程封装及错误解决调试 # #coding:utf-8 import sys,requests sys.path.append(r"../DjangoInterfaceTest") sys.path.append(r'../DjangoInterface/data') from base.runmethod import RunMethod from data.get_data import GetData class RunTest: def __init__(self): self.run_method = RunMethod() self.data = GetData() ...
from PyQt5 import QtWidgets ,QtCore, QtGui from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog, QAction,QTableWidget from GUI import Ui_MainWindow from sound_class import sound import os import sys import matplotlib.pyplot as plot import librosa from pydub import AudioSegment from tempfile impor...
import unittest from Range import Range class TestRange(unittest.TestCase): def setUp(self): self.rngObj = Range(3, 8) def test_contains(self): self.assertTrue(self.rngObj.contains(4)) self.assertTrue(self.rngObj.contains(7)) self.assertFalse(self.rngObj.contains(-1)) ...
from sc2scout.wrapper.feature.feature_extractor import FeatureExtractor import math class ImgLocalFeatExtractor(FeatureExtractor): def __init__(self, compress_width, local_range): self.env = None self._compress_width = compress_width self._local_range = local_range self._x_radius = ...
import datetime import logging import threading import time from django.conf import settings from django.contrib.auth.models import User from djutils.queue.bin.consumer import QueueDaemon from djutils.queue.decorators import crontab, queue_command, periodic_command from djutils.queue.queue import QueueCommand, Period...
import subprocess as sp import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.model_selection import train_test_split from sklearn import preprocessing from datetime import time class PrepGenerationData: def __init__(self,filename...
import numpy as np from ZOHA_Optimizer import ZOHA_Sphere_lr_euclid from insilico_Exp import ExperimentEvolve #%% mode_dict = ["inv","lin","exp"] def optim_result(param): pop_size = int(param[0,0]) select_rate = param[0,1] select_size = int(pop_size * select_rate) lr = param[0,2] mu_init = param[0,3...
#!/usr/bin/env python # -*- coding: utf-8 -*- def sum_of_min_and_max(arr): arr = sorted(arr) total_sum = arr[0] + arr[-1] return total_sum # Examples: print sum_of_min_and_max([1,2,3,4,5,6,8,9]) # print sum_of_min_and_max([-10,5,10,100])
import time,random def qu_ben(n=2**24): def a(a,1,h) if 1<h: p=par(a,1,h) q(a,1,p) a(a;p+1,h) def par(a,1,h): piv_in(=r.ran(1,h) piv=a[piv_in] i=1-1 j=h+1 while true: j-=1 if a[j]<=piv: break if i>j: return j temp=a[i] a[i]=a[i] a[j]=temp starts=time.time() a=[r.ran(0,n)for i in range(0,n)] q(a,0,lenb(a)-1) end=time.ti...
import sys import rlogin from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from time import sleep login_url = "https://ssl.realworld.jp/auth/?site=gendama_jp&rid=&af=&frid=&token=&goto=http%3A%2F%2Fwww.gendama.jp%2Frace" rloginC...
''' Permutes the contents of a canonical array via a bijective mapping each cell in [1..9] to a new value in [1..9]. ''' import random def make_mixer(): a = list(range(1, 10)) b = list(range(1, 10)) random.shuffle(a) random.shuffle(b) mixer = dict(list(zip(a, b))) return mixer def permute_arr...
from datetime import datetime, timedelta from airflow import DAG from airflow.contrib.operators.dataproc_operator import DataprocClusterCreateOperator, \ DataProcPySparkOperator, DataprocClusterDeleteOperator, DataProcSparkOperator from airflow.utils.trigger_rule import TriggerRule # Loads of Info here https://air...
import microcircuit.constants as const from microcircuit.viz import show import networkx as nx from microcircuit.connectome import Connectome a=nx.DiGraph() a.add_edge(1,2, {const.CONNECTOME_CHEMICAL_SYNAPSE:1, const.CONNECTOME_ELECTRICAL_SYNAPSE:2}) a.add_edge(2,1, {const.CONNECTOME_ELECTRICAL_SYNAPSE:2}) a.add_edge(...
import configparser config=configparser.RawConfigParser() config.read("./configuration/config.ini") class ReadConfig: @staticmethod def get_base_URL(): url=config.get("Version_4","base_url") return url @staticmethod def get_user_name(): user_name=config.get("Version_4","user_...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField from wtforms.validators import DataRequired from datetime import datetime class DeviceForm(FlaskForm): name = StringField ('Device Name', validators=[DataRequired()] ) macAddress = TextAreaField ('Mac Address' , valida...
import getpass import glob import multiprocessing import numpy import os import subprocess import time ################################################## # Safety ################################################## username = getpass.getuser() if (username != "sobhatta") : print "WARNING!!! Probably running ...
"""[ contains the edit side operator ]""" from bpy.props import StringProperty, IntVectorProperty, BoolVectorProperty from bpy.types import Operator from bpy import ops as O import bmesh from ..MaterialManagers import ManagerInstance class EditSide(Operator): """[ allows the editing of one specific side of a me...
import json import threading import time from datetime import datetime, timedelta from typing import List from uuid import uuid4 from acquisition.core.bugsbunny import spin from acquisition.utils.common import datetime_to_utc, now from acquisition.utils.logs import log # pyright: reportMissingImports=false ...
import math import termtables as tt def main(s): f = open("GCD.txt", "w") for i in range(0, len(s)): a = s[i][0] b = s[i][1] q = math.floor(a / b) r = a - q * b out = "{:d} = {:d}({:d}) + {:d}".format(int(a), int(b), int(q), int(r)) f.write(out + "\n") ll...
import unittest from DNSQuestionSection import DNSQuestionSection class DNSQuestionSectionTest(unittest.TestCase): def test_construct_qname(self): qsection = DNSQuestionSection('www.naver.com', 1, 1) self.assertEqual(qsection.to_bytes(), b'\x03www\x05naver\x03com\x00\x00\x01\x00\x01') if __name...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, RadioField from wtforms.validators import DataRequired class TweetForm(FlaskForm): #ID = IntegerField('tID', validators=[DataRequired()]) #givenID = IntegerField('givenID') selected_text = StringField('Selected Text') #given_...
#!/usr/bin/python3 ''' Este Script recopilará los datos del estudio del Proyecto de Fin de Grado - ASIR 2019/2020 Describiré diferentes funciones que recopilaran los datos de las pruebas, serán almacenadas en formato CSV. Los datos que recopilaré son: RAM usado por la aplicacion Uso de lectura de disco Uso...
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import DeleteView, UpdateView from django.contrib.auth.models import User from django.core.paginator import Paginator from django.http import JsonResponse fr...
from scrapy import Spider from scrapy.selector import Selector from news.items import NewsItem from news.spiders.src import topic class NewsSpider(Spider): #subscribe = Topic() my_url = "https://www.ndtv.com/topic/" #strng = subscribe.topic() content = topic().replace(" ","-") name = 'news' allowed_domains = ["...
import boto3 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication def lambda_handler(event, context): ses = boto3.client("ses") s3 = boto3.client("s3") client = boto3.client("rekognition") for i in event[...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * exe = context.binary = ELF('babyformat') def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: if args.REMOTE: ...
#!/usr/bin/python # -*- coding: utf_8 -*- # By Flip Wester (flip_wester@sil.org) ############################################################################### ################################ INTRODUCTION ################################# #############################################################################...
import sys from xpectacle.active_window import ActiveWindow x, y, width, height = map(int, sys.argv[1:]) ActiveWindow().move(x=x, y=y).resize(width=width, height=height).apply()
from SimPy.Simulation import activate, reactivate, now, hold, Process from trace import Tracer from record import ecorecord as record from market import Bid from messages import * from traders.buyer import Buyer from traders.processes import * class SBBuyer(Buyer): def __init__(self, job, rationale, ttl=2, **kw):...
def isLeaf(node): if node is not None and node.left is None and node.right is None: return True return False def boundaryOfBT(root): temp = root.left left_boudnary = [root.val] while temp is not None: if not isLeaf(temp) left_boudnary.append(temp.val) if temp.le...
from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd import numpy as np from keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences def create_tf_idf(tweets): """ Creates tf-idf features. It fits a vectorizer in the training d...
import argparse from code.front_end.parser import run from code.utils.directory import input_path,output_path ''' Content principal compiler routines ''' # todo make the compiler # todo please use venv while make the compiler print("Vamos a correr el Compilador en el path de input:") print(input_path) print...
import unittest from unittest import mock from mopidy_alsamixer import Extension, mixer class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn("[alsamixer]", config) self.assertIn("enabled = tr...
def solution(cb, cy): # x + y = (cb + 4) / 2 # total num of tiles: x * y = cb + cy # ax^2 + bx + c = 0 a = 1 b = -int((cb + 4) / 2) c = cb + cy x = (-b + int((b**2) - 4 * a * c) ** 0.5) / (2 * a) y = -b - x return [x, y]
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #import os #my_dir = os.getcwd() #os.chdir(my_dir) #import sys import pandas as pd import numpy as np #import scipy.fft import streamlit as st import plotly.express as px from streamlit_multiApp import MultiApp from tdi_ca...
# # Copyright 2017 XEBIALABS # # 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, merge, publish, distribute, subli...
# encoding:utf-8 import os import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import datetime from matplotlib.ticker import MultipleLocator import matplotlib.dates as mdate import pandas import csv now = datetime.datetime.now() now.strftime('%Y-%m-%d %H:%M') nowtime = now.strftime('%...
from models.Conexion import Conexion from models.entities.Persona import Persona class PersonaModel(Conexion): def getTable(self): self.conectar() if self.conexion: cursor = self.conexion.cursor() sql = "SELECT codigo, nombre, apellido, fecha_nacimiento FROM persona;" ...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import datasets,linear_model def get_data(filename): data = pd.read_csv(filename) X_parameter=[] Y_parameter = [] # print data # print zip(data['square_feet'],data['price']) for single_square_feet,single_price_va...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import GridSearchCV from datetime import datetime import hashlib import pickle # 読み込み df_train = pd.read_csv("./data/train_prep_nontree_base.csv") ...
import sys T = int(sys.stdin.readline().strip()) for it in xrange(T): k, c, s = map(int, sys.stdin.readline().strip().split()) print "Case #%d:" % (it + 1), " ".join(map(lambda x: str(1 + x * k ** (c - 1)), xrange(k)))
n=13 print n while (n!=1): if ((n%2)==0): n=n/2 print n else: n=(n*3)+1 print n #with break n=13 print n while (True): if (n == 1): break if ((n%2)==0): n=n/2 print n else: n=(n*3)+1 print n
chemin_absolubis = 'C:\\Users\\jujug\\OneDrive - mines-paristech.fr\\Documents\\Mines\\1A\\EC\\Mini-projet\\repo_git\\' #à adapter à chaque ordinateur chemin_absolu = 'C:\\Users\\cotil\\Desktop\\COURS\\Mines\\Energie_et_societe\\Poster\\PopulationEtEnergie\\' import sys sys.path.append(chemin_absolu + 'populationeten...
"""\ The Most Wanted Letter You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case. While checking for the most wanted letter, casing does not matter, so for the purp...
#---------------------------------------------------------------------------------- # Module shareGraphicFunction: there are functions that are shared between graphic modules #---------------------------------------------------------------------------------- #-----------------------------------------------------------...
import os import sys import numpy as np import scipy.io import scipy.misc import tensorflow as tf import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from nst_utils import * import imageio from PIL import Image import shutil """ Input Parameters - Start """ content_img_path = '/Users/adeelqureshi/Dow...
import numpy as np import ConnectionDB as Connection ''' Constantes ''' IDMODEL = 6 def insertCoordinates(params): try: conn = Connection.createConnectionSQLServer() with conn.cursor() as cursor: query = "INSERT INTO cc_locationCol (id, code, longitude, latitude) VALUES (?,?,?,?)" ...
from pyflann import * from pyflann.exceptions import FLANNException import numpy as np from figet.utils import get_logging from figet.Constants import COARSE_FLAG, FINE_FLAG, UF_FLAG from figet.hyperbolic import poincare_distance import torch from operator import itemgetter log = get_logging() cos_sim_func = torch.nn...
from mrjob.job import MRJob from mrjob.step import MRStep import heapq # Number of top items to capture TopN = 10 # # By default mrjob executes mapper_init, mapper, mapper_final, reducer_init, # reducer and reducer_final # # Run with: # python ./TopN.py --jobconf mapreduce.job.reduces=1 --jobconf mapreduce.job.m...
import doc2topic from py2neo import Graph, Node, Relationship import threading import re import requests from flask import Flask, json, request import time import os import file_map app = Flask(__name__) class Graph2(Graph): def exists(self, node): found_nodes = list(self.find('document', property_key='doc...
import matplotlib.pyplot as plt import numpy as np import cv2 import os from ..configs import config from ..modules import dataset as ds from ..modules import metrics as ms LABEL_COLOUR = { 1: (1., 1., 1.), 0: (1., .6, .6), -1: (1., 1., 1.) } def visualize_bbox(img, bbox, category_id_to_name, colour=LAB...
# -*- coding: utf-8 -*- import pymysql from Bigfish.web_utils.connection import conn class runtime_data(): def __init__(self,userid): self._userid=userid self._conn=conn def __del__(self): self._conn.close() def get_code(self): cur = conn.cursor(pymysql.cursors.DictCursor...
import re import datetime def time_parser(event): regex = re.findall(r'[0-9]{4}|[0-9]{2}-[0-9]{2}|[0-9]{2}:[0-9]{2}', event.postback.params["datetime"]) if(len(regex)==3): str = regex[0] + '-' + regex[1] + ' ' + regex[2] date = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M') return date def ...
"""Point-mass domain.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_con...
def numrepeatfrac(n): decimal = str(n) if decimal[0] == decimal[1] or decimal[1] == decimal[2]: return 1 for x in range(1,len(decimal)/2): if decimal[0:x] == decimal[x:x+x]: return x y = 0 z = 0 for x in range(999,2,-1): tempnum = numrepeatfrac(10**5000/x) if tempnum > y...
"""Configurable for configuring the IPython inline backend This module does not import anything from matplotlib. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the BSD 3-Clause License. from traitlets.config.configurable import SingletonConfigurable from traitlets import ( Dict, I...
import urllib.request as req import urllib.parse as parse from django.http import HttpResponse def index(request): url = parse.quote(request.GET.get('url')) url = url.replace('%3A', ':') headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) Firefox/106.0.1', 'Accept': 'text/html,appli...
# coding=utf-8 from typing import List # 执行用时:40 ms, 在所有 Python3 提交中击败了60.05%的用户 # 内存消耗:14.8 MB, 在所有 Python3 提交中击败了80.38%的用户 class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: n = len(matrix); m = len(matrix[0]) dx = [0, 1, 0, -1]; dy = [1, 0, -1, 0] st = [[False ...
import utils def main(): users = utils.getUsers() todos = utils.getTodoItems() for user in users: userTodos = [t for t in todos if t.userId == user.id] print("{} ({})".format(user.name, len(userTodos))) if __name__ == '__main__': main()
# coding: utf-8 import flopy import os import sys import config import SGD import re import ast from pathlib import Path,PureWindowsPath import utils d = utils.read_ref() ws = Path(d['model_ws']) fname = [f for f in ws.iterdir() if f.suffix == '.nam'][0] m = flopy.seawat.Seawat.load(str(fname),exe_name = config.swe...