index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
9,700
60b70171dededd758e00d6446842355a47b54cc0
#!/usr/bin/env python3 import sys import collections as cl def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) MOD = 998244353 def main(): N, K = MI() kukan = [] for _ in range(K): ...
9,701
51868f26599c5878f8eb976d928c30d0bf61547d
import collections def range(state): ran = state["tmp"]["analysis"]["range"] rang = { key : [ state["rank"][i] for i in val & ran ] for key, val in state["tmp"]["analysis"]["keys"].items() if val & ran } for item in state["tmp"]["items"]: item.setdefault("rank", 0) item_keys = set(item.keys()) rang_...
9,702
986df5a41bc87ecb390dfbd1db9e1f5cd6c5b8fb
import argparse import cv2 import numpy as np refPt = [] cropping = False def click_and_crop(event, x, y, flags, param): global refPt, cropping if event == cv2.EVENT_LBUTTONDOWN: refPt = [(x, y)] cropping = True elif event == cv2.EVENT_LBUTTONUP: refPt.append((x, y)) cropping = False cv2.rect...
9,703
dd0e96a1f93cbffedc11262a883dda285f5c224c
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func from extensions import bcrypt db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(255)) password = db.Column(db.String(255)) posts = db.relationship( 'Post', ...
9,704
78c4e14e5afdf857082b60bf4020f0f785d93a0d
from p5 import * import numpy as np from numpy.random import default_rng from boids import Boid from data import Data n=30; width = 1920 height = 1080 flock=[] infected=[] rng = default_rng() frames=0 for i in range(n): x = rng.integers(low=0, high=1920) y = rng.integers(low=0, high=1080) if i==0: ...
9,705
7764effac0b95ad8f62b91dd470c1d0e40704a7d
''' tk_image_view_url_io.py display an image from a URL using Tkinter, PIL and data_stream tested with Python27 and Python33 by vegaseat 01mar2013 ''' import io # allows for image formats other than gif from PIL import Image, ImageTk try: # Python2 import Tkinter as tk from urllib2 import urlopen except...
9,706
91806afea92587476ac743346b88098b197a033c
import pygame import time from menus import MainMenu from scenes import TestWorldGen from scenes import TestAnimation from scenes import TestLevel2 from scenes import MainGame import random class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), ...
9,707
4f06d87ec79c20206ff45ba72ab77844076be553
import pandas as pd from greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df def get_runs_counts_by_match(): ipl_df = read_csv_data_to_df("data/ipl_dataset.csv") df1 = pd.DataFrame(ipl_df[['match_code','runs','venue']]) df2 = df1.groupby(['match_code','runs'], as_index=Fals...
9,708
4b78c99dd6156afe960effcacb25804446310f7c
# MIT LICENSE # # Copyright 1997 - 2019 by IXIA Keysight # # 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,...
9,709
0a42c54ef1412b7f3b8e95da1d65ee05dfa14089
from dataframe import * from chaid import SuperCHAID, SuperCHAIDVisualizer supernode_features = [manufacturing_region] features_list = [customer_region, product_family, make_vs_buy] dependant_variable = gm super_tree = SuperCHAID(supernode_features, features_list, dependant_variable) super_tree.fit(df) visualizer = ...
9,710
239f055fd76a3ecb5f384c256ad850ea42739b8f
import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import math from tkinter import * from tkinter.ttk import * from facedetectandtrack import * x_vals = [] root = Tk() counter=0 #def graph(): plt.style.use('seaborn') def animate(i): data = pd.read_csv('data.csv...
9,711
35647ed5e2c128a5bf819a1e47ead7e958172b1c
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 24 22:05:12 2019 @author: admin """ for index in range(test_set.shape[0]): print(index)
9,712
6907a1e08d728732eebf81fec7c0dab8729448e2
# Generated by Django 2.1.5 on 2019-01-20 18:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Destination', fields=[ ...
9,713
e3417980599448f1293b56cb95312088e7a8abe3
import os import imageio import h5py import numpy as np def create_segmentation_test_data(data_path, raw_key, label_key, shape, chunks): with h5py.File(data_path, 'a') as f: f.create_dataset(raw_key, data=np.random.rand(*shape), chunks=chunks) f.create_dataset(label_key, data=np.random.randint(0, ...
9,714
b7a7941b3555b30ac7e743a5457df76f9eb7cb15
#write a program that displays the wor "Hello!" print("Hello!")
9,715
c9be3d25824093528e2bee51c045d05e036daa67
import sklearn.metrics as metrics import sklearn.cross_validation as cv from sklearn.externals import joblib import MachineLearning.Reinforcement.InternalSQLManager as sqlManager class ReinforcementLearner: def __init__(self, clf=None, load=False, clfName=None): """ Initialise the Classifier, eith...
9,716
13c55c313c740edce48fc979e8956fdd018e8aab
"""This module contains a class supporting composition of AugraphyPipelines""" class ComposePipelines: """The composition of multiple AugraphyPipelines. Define AugraphyPipelines elsewhere, then use this to compose them. ComposePipelines objects are callable on images (as numpy.ndarrays). :param pipel...
9,717
bcdd36b534fd3551de9cb40efc11581f4d95a002
import sys from Node import Node from PriorityQueue import PriorityQueue def Print(text): if text is None or len(text) == 0: print('invalid text.') print('--------------------------------------------------------------') return text_set = set() for i in text: t...
9,718
ae7fc034249b7dde6d6bca33e2e6c8f464284cfc
#!/usr/bin/env python3 import datetime import time import board from busio import I2C import adafruit_bme680 # Create library object using our Bus I2C port i2c = I2C(board.SCL, board.SDA) bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False) # change this to match the location's pressure (hPa) at sea level b...
9,719
76664114382bdeb0bffb996e4dd4448b6c87520d
import sys def ler (t): i =0 for s in sys.stdin: l=s.split(" ") t.append(l) def melhor (t): i=1 x=int(t[0][0].strip("\n")) n=len(t) while(i<n): u=int((t[i][2]).strip()) if(u<x) i+=1 def vendedor(): t=[] ler(t) melhor(t) vendedor()
9,720
e0874554c326bb11b53552e362bc8073bb57bc93
import widget import column class Columns(widget.Widget): def __init__(self, parent): super(Columns, self).__init__(parent) # self.root.mouse.on_drag_release.append(self.on_drag_release) """ def on_drag_release(self, x0, y0, x, y): if not self.contains_point(x0, y0): re...
9,721
843901b65a556e57470f73be2657e9fd3c0facc6
def parse(num): strnum = str(num) words = [] for item in range(len(strnum)-1, -1, -1): words.append(strnum[item]) hundred = words[:3] thousand = words[3:6] million = words[6:len(words)] hundred = hundred[::-1] thousand = thousand[::-1] million = million[::-1] units = [...
9,722
b2a2e06c5db8b12acbc852bafc4ea869b006c1c8
import itertools import urllib import word2vec # MSD: http://corpus.leeds.ac.uk/mocky/ru-table.tab # Universal: http://universaldependencies.org/ru/pos/index.html def convert_pos_MSD_to_Universal(pos): if pos.startswith('A'): return 'ADJ' elif pos.startswith('C'): return 'CCONJ' elif pos....
9,723
fb82724aab7e0819c9921d41dcb612b304b25753
import pandas as pd import numpy as np import matplotlib.pyplot as plt #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 차트에 한글 가능하도록 from matplotlib import font_manager, rc, rcParams font_name = font_manager.FontProperties( fname="c:/windows/Fonts/malgun.ttf").get_name() rc('font',family=font_name)...
9,724
4ea266d4f4c18efbba4204d7301652f8966c18a5
# -*- coding: utf-8 -*- """ Animation practical output The code that follows builds on the "Communications.py" file Additional code that follows has in part been modified from that of https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/index.html https://www.geog.leeds.ac.uk/courses...
9,725
c2b6e51622681ac916e860ed4ff5715808dff102
import numpy as np import matplotlib as plt import math from DoublePendulum import DP #imports useful modules and double pendulum class from DoublePendulum.py import json import pandas as pd import copy from pathlib import Path #accessing config file with open('config.json') as config_file: initdata = ...
9,726
e686d8617360c5a3ce35bd4d2bdeb2376b33f53a
#!/usr/bin/env python import re pdfs_file = './pdf_names_2017.txt' sessions_file = './session_names_2017.txt' with open(pdfs_file) as f: pdf_names = f.read().splitlines() with open(sessions_file) as f: session_names = f.read().splitlines() #for i in xrange(0,len(pdf_names)): # print str(i+1).zfill(3) +...
9,727
5cb390b06026bc0899c0b10dc93f3ec1f2ffefa6
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Sponge_sy" # Date: 2021/9/11 import numpy from tqdm import tqdm from bert4keras.tokenizers import Tokenizer from bert4keras.models import build_transformer_model from bert4keras.snippets import sequence_padding, DataGenerator from utils import * class d...
9,728
c9bc331f4805a956146619c59d183fc3bcbe47cb
from conans import ConanFile, CMake, tools import os class Demo(ConanFile): name = "Demo" version = "0.1" license = "<Put the package license here>" url = "<Package recipe repository url here, for issues about the package>" description = "<Description of Testlib here>" settings = "os", "compile...
9,729
b4d48427dddc7c0240cf05c003cbf7b0163279ee
from django.contrib import admin from .models import (AddressLink, Address, Child, Citation, Configuration, Event, Exclusion, FactType, Family, Group, Label, LinkAncestry, Link, MediaLink, Multimedia, Name, Person, Place, ResearchItem,...
9,730
3a96ede91069df0c71905415e598dbbd9d3056fd
import os import sys import re import traceback import logging import queue import threading from logging.handlers import TimedRotatingFileHandler from pathlib import Path import click import inotify.adapters from inotify.constants import (IN_ATTRIB, IN_DELETE, IN_MOVED_FROM, IN_MOVED_TO,...
9,731
0726a4fa3af196e2ba1592019f09afb0e7bb47d7
import os import requests def download(url: str, dest_folder: str): #https://stackoverflow.com/a/56951135/8761164 if not os.path.exists(dest_folder): os.makedirs(dest_folder) # create folder if it does not exist filename = url.split('/')[-1].replace(" ", "_") # be careful with file names fil...
9,732
9ad36f157abae849a1550cb96e650746d57f491d
from collections import Counter from docx import Document import docx2txt plain_text = docx2txt.process("kashmiri.docx") list_of_words = plain_text.split() #print(Counter(list_of_words)) counter_list_of_words = Counter(list_of_words) elements = counter_list_of_words.items() # for a, b in sorted(elements, key=lambda x:...
9,733
7016a7dda80c0cfae0e15cf239f6ae64eb9004b7
# Jeremy Jao # University of Pittsburgh: DBMI # 6/18/2013 # # This is the thing that returns the dictionary of the key. we can edit more code to return different values in the keys (gene) in each dictionary inside the dictionary. # my sys.argv isn't working in my situation due to my IDE (nor do I not know how it w...
9,734
b8b20d6c977a6c1df6a592188c6e799f12da6a23
########################################################################################## ## Scene Classification ## ## Authors : Chris Andrew, Santhoshini Reddy, Nikath Yasmeen, Sai Hima, Sriya Ragini ## ###############################################...
9,735
c77ca4aa720b172d75aff2ceda096a4969057a00
# coding=utf-8 # __author__ = 'liwenxuan' import random chars = "1234567890ABCDEF" ids = ["{0}{1}{2}{3}".format(i, j, k, l) for i in chars for j in chars for k in chars for l in chars] def random_peer_id(prefix="F"*8, server_id="0000"): """ 用于生成随机的peer_id(后四位随机) :param prefix: 生成的peer_id的前八位, 测试用prefix为...
9,736
972c479ea40232e14fbf678ca2ccf9716e473fe8
from rest_framework import serializers from .models import data from django.contrib.auth.models import User class dataSerializer(serializers.ModelSerializer): class Meta: model = data fields = ['id','task','duedate','person','done', 'task_user'] class userSerializer(serializers.ModelSerializer): ...
9,737
0d07ad60c58828ce19153063fb5d7d80135cb9ec
from django.http import HttpResponse from django.shortcuts import render from dashboard.models import Farmer import random, json, requests from django.core import serializers from collections import namedtuple def sendSMS(message): if message: assert isinstance(message, (str, unicode)) payload = {...
9,738
a5b74c31aed103b55404afc538af60c3eb18cb1b
"""TcEx Framework Key Value Redis Module""" class KeyValueRedis: """TcEx Key Value Redis Module. Args: context (str): The Redis context (hash) for hashed based operations. redis_client (redis.Client): An instance of redis client. """ def __init__(self, context, redis_client): ...
9,739
a67612e8301728d1fb366d7c8909fa830f04bf45
#Max Low #9-25-17 #quiz2.py -- numbers , bigger smaller same, divisible by 3, product and correct person numone = int(input('Enter a number: ')) numtwo = int(input('Enter a 2nd number: ')) if numone > numtwo: print('The first number is bigger') elif numtwo > numone: print('The second number is bigger') else: ...
9,740
cd8d95e2bf433020db2db06a21263f75e3f81331
#!/bin/python """ len() lower() upper() str() """ parrot = "Norwegian Blue" print len(parrot)
9,741
2b8b5b893d61d11d2795f5be96fde759256a15e8
""" This is the main script """ import datetime import sqlite3 from sqlite3 import Error import nltk.sentiment from chatterbot import ChatBot from pythonosc import udp_client def _create_connection(db_file): """ Create a database connection to the SQLite database """ try: conn = sqlite3.connect(db_fi...
9,742
a315d01f0fb16f0c74c447c07b76f33e6ff6427d
from auth_passwordreset_reset import auth_passwordreset_reset from auth_register import auth_register from data import * import pytest #invalid reset code def test_auth_passwordreset_reset1(): #create a test account register = auth_register("Someemial@hotmail.com.au", "Hello123", "First", "Last") ...
9,743
75b1674066958a8fa28e74121a35d688bcc473d9
from odoo import models, fields, api, _ class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" date_start_invoice_timesheet = fields.Date( string='Start Date', help="Only timesheets not yet invoiced (and validated, if applicable) from this period will be inv...
9,744
a718d82713503c4ce3d94225ff0db04991ad4094
# Generated by Django 3.0 on 2020-05-04 16:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('game_skeleton', '0001_initial'), ('contenttypes', '0002_remove_content_type_name'), ('clas...
9,745
afdb14d60374049753b3c980c717a13456c7ff5c
from django.contrib import admin from django.urls import path from .views import NewsCreateListView, NewsDetailGenericView urlpatterns = [ path('news/', NewsCreateListView.as_view()), path('news_detailed/<int:id>/', NewsDetailGenericView.as_view()), ]
9,746
cb6f68c8b8a6cead1d9fcd25fa2a4e60f7a8fb28
import math def upsample1(d, p): # 普通结界 assert 1 <= p <= 10 return d + p def upsample2(d, p): # 倍增结界 assert 2 <= p <= 3 return d * p def downsample(d, p): # 聚集结界 assert 2 <= p <= 10 return math.ceil(d / p) # 初始化杀伤力范围 lethal_radius = 1 # 结界参数(z, p) config = [(1, 6), ...
9,747
0972bd1241ad91f54f8dfde6327ee226c27bf2ca
from datetime import datetime import time from os import system import RPi.GPIO as GPIO import firebase_admin from firebase_admin import credentials from firebase_admin import db GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) # este pin es de salida carro GPIO.setup(26, GPIO.OUT) # este pin es...
9,748
f8c222b1a84a092a3388cb801a88495bc227b1d5
import datetime import hashlib import json from flask import Flask, jsonify, request import requests from uuid import uuid4 from urllib.parse import urlparse from Crypto.PublicKey import RSA # Part 1 - Building a Blockchain class Blockchain: #chain(emptylist) , farmer_details(emptylist), nodes(set), cre...
9,749
a1e563f94044ff7cd7e0e55542bc4ca2db81df28
# # Author:: Noah Kantrowitz <noah@coderanger.net> # # Copyright 2014, Noah Kantrowitz # # 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 # # Unles...
9,750
084299da1c2f41de96e60d37088466c7b61de38e
from appJar import gui app = gui("Calculator", "560x240") ### FUNCTIONS ### n1, n2 = 0.0, 0.0 result = 0.0 isFirst = True calc = "" def doMath(btn): global result, n1, n2, isFirst, calc inputNumber() if(btn == "Add"): calc = "a" if(btn == "Substract"): calc = "s" if(btn == "Multiply"): calc =...
9,751
3319614d154b16190f3cd8f4f65c3b0e0da277e9
# -*- coding: utf-8 -*- class Solution: """ @param head: The first node of the linked list. @return: The node where the cycle begins. if there is no cycle, return null """ def detectCycle(self, head): # write your code here # 先确定是否有环,然后确定环的大小,再遍历确定位置。 cycle_...
9,752
b93f6c3192f8dd58b96dfdc6ea2b17e12cce34d0
from collections import defaultdict, deque N = int(input()) adj_list = defaultdict(list) E = [] V_number = [None]*N for _ in range(N-1): a, b = map(int, input().split()) E.append((a, b)) adj_list[a].append(b) adj_list[b].append(a) C = sorted(list(map(int, input().split())), reverse=True) q = deque([1])...
9,753
9535335c70129f997d7b8739444a503d0b984ac8
import json import os import pickle import random import urllib.request from pathlib import Path import tensorflow as tf from matplotlib import pyplot as plt class CNN(object): def __init__(self): self.model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_...
9,754
76f2312a01bf8475220a9fcc16209faddfccd2ae
import os import sys import logging.config import sqlalchemy as sql from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Float, String, Text, Integer import pandas as pd import numpy as np sys.path.append('./config') import config logging.basicC...
9,755
388904b6b826a1c718b85f2951a3189bb5abea2a
# import adafruit_ads1x15 as adс # from adafruit_ads1x15 import ads1x15 as adc # from adafruit_ads1x15 import analog_in import time import busio import board from adafruit_ads1x15 import ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1015(i2c...
9,756
01128ebd156b24791548c50c92d2fc1969c42e70
import numpy as np import sklearn.cluster as sc import sklearn.metrics as sm import matplotlib.pyplot as mp x = np.loadtxt('C:\\Users\\Administrator\\Desktop\\sucai\\ml_data\\perf.txt', delimiter=',') # 准备训练模型相关数据 epsilons, scores, models = np.linspace(0.3, 1.2, 10), [], [] # 遍历所有的半径,训练模型,查看得分 for epsilon in eps...
9,757
9cad36de6231f310ef9022f16f6ed0da83a003b3
# -*- coding: utf-8 -*- """ Created on Mon Mar 6 12:20:45 2017 @author: 7 """ from os import listdir from PIL import Image as PImage from scipy import misc import numpy as np from Image_loader import LoadImages """ def LoadImages(path): # return array of images imagesList = listdir(path) ...
9,758
0fb424dafaac184882ea56f36265e0b19b5a4c50
import torch import torch.nn.functional as f import time import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np dtype = torch.float device = torch.device("cpu") # device = torch.device("cuda:0") # Uncomment this to run on GPU N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D...
9,759
09d32b48ae88b1066dd0aa435a351c4fb1fc04ec
from flask import Flask, request, render_template from random import choice, sample app = Flask(__name__) horoscopes = [ 'your day will be awesome', 'your day will be terrific', 'your day will be fantastic', 'neato, you have a fantabulous day ahead', 'your day will be oh-so-not-meh', 'this day...
9,760
5a895c864c496e1073d75937909c994432a71d75
import socket import json from typing import Dict listadionica = ["GS", "MS", "WFC", "VALBZ", "BOND", "VALE", "XLF"] class Burza: def __init__ (self, test): if test: host_name = "test-exch-partitivnisumari" port = 25000 else: host_name = "production" ...
9,761
1ae69eaaa08a0045faad13281a6a3de8f7529c7a
# -*- coding: utf-8 -*- import csv import datetime from django.conf import settings from django.contrib import admin from django.http import HttpResponse from django.utils.encoding import smart_str from djforms.scholars.models import * def export_scholars(modeladmin, request, queryset): """Export t...
9,762
0e73153d004137d374637abf70faffabf0bab1fb
# Generated by Django 3.1 on 2020-09-09 15:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('orders', '0001_initial'), ] operations = [ migrations.RenameField( model_name='orderproduct', old_name='products', ...
9,763
398f9f52b83ffddfb452abbeaad2e83610580fee
# -*- coding: utf-8 -*- # project: fshell # author: s0nnet # time: 2017-01-08 # desc: data_fuzzhash import sys sys.path.append("./dao") from fss_data_fuzzhash_dao import * class FssFuzzHash: @staticmethod def insert_node(agent_id, data): return FssFuzzHashDao.insert_node(agent_id, data)
9,764
ac5c6a534d5131438d9590b070e6b392d4ebed0c
from pynhost.grammars import extension from pynhost.grammars import baseutils as bu class AtomExtensionGrammar(extension.ExtensionGrammar): activate = '{ctrl+alt+8}' search_chars = bu.merge_dicts(bu.OPERATORS, bu.ALPHABET, bu.CHAR_MAP) def __init__(self): super().__init__() self.app_conte...
9,765
3aa8c9b39174f0ed5799d6991516b34ca669b7d6
from django.db import models # db에 있는 models을 가져옴 from django.utils import timezone # 유틸에 있는 timezone을 가져옴 # Create your models here. class Post(models.Model): # Post라는 객체를 정의함 인수로 장고모델을 가져왔음 # 장고모델이기 때문에 데이터베이스에 저장된다. author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크 title = models.Char...
9,766
1fbdb0b40f0d65fffec482b63aa2192968b01d4b
#define the simple_divide function here def simple_divide(item, denom): # start a try-except block try: return item/denom except ZeroDivisionError: return 0 def fancy_divide(list_of_numbers, index): denom = list_of_numbers[index] return [simple_divide(item, denom) for item in lis...
9,767
9e511c769f6ccedc06845a382171fb3729913d05
import generic name = __name__ def options(opt): generic._options(opt, name) def configure(cfg): generic._configure(cfg, name, incs=('czmq.h',), libs=('czmq',), pcname = name.lower(), uses = 'LIBZMQ', mandatory=True)
9,768
69ebdab4cd1f0b5154305410381db252205ff97d
#!/usr/bin/env python # -*- coding:UTF-8 -*- ''' @Description: 数据库迁移 @Author: Zpp @Date: 2020-03-30 11:01:56 @LastEditors: Zpp @LastEditTime: 2020-04-28 09:55:26 ''' import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) from flask impor...
9,769
bf04bf41f657a6ada4777fe5de98d6a68beda9d3
import scipy.sparse from multiprocessing.sharedctypes import Array from ctypes import c_double import numpy as np from multiprocessing import Pool import matplotlib.pyplot as plt from time import time import scipy.io as sio import sys # np.random.seed(1) d = 100 n = 100000 k=10 learning_rate = 0.4 T_freq = 100 num_t...
9,770
ebc2acbcbab787b07c97b0a4ea8fbaeb9d8e30aa
30. Convertir P libras inglesas a D dólares y C centavos. Usar el tipo de cambio $2.80 = 1 libra p=2.80 x=int(input("Desea convertir sus libras a dolar(1) o a centavos(2)")) if x == 1: d=float(input("¿Cuantas libras desea convertir a dólar?\n")) conversion = (d/p) if x == 2: c=float(input("¿Cuan...
9,771
eafe89de10c4187057b0cc1e0e9772f03a576b0d
__version__ = "1.2.0" import hashlib from collections import Counter from re import findall from secrets import choice from string import ascii_letters, ascii_lowercase, ascii_uppercase from string import digits as all_digits from string import punctuation import requests def check_password(password): """Check ...
9,772
e7b96c0161e65f3f22f2ad0832fc6d1bb529f150
""" In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class...
9,773
13e27c29839286988b37d2d3685f54d42fd57973
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the ...
9,774
f72cdf8d91c31760335b96052a34615307f48727
from cpp_service.SubService import SubService import config if __name__ == "__main__": gateway = config.gateway["trading_system_gateway"] host = gateway["host"] port = gateway["port"] server_id = gateway["server_id"] licences = gateway["licences"] service = SubService(host, port, server_id, li...
9,775
00b4a57537358797bfe37eee76bbf73ef42de081
#Define a function max_of_three() that takes three numbers as #arguments and returns the largest of them. def max_of_three(a,b,c): max=0 if a > b: max = a else: max = b if max > c : return max else: return c print max(234,124,43) def max_of_three2(a, b, ...
9,776
286953e381d03c0817d57f9ee4e15f2a0ce808a9
from django_evolution.mutations import ChangeField MUTATIONS = [ ChangeField('ReviewRequest', 'depends_on', initial=None, null=False), ChangeField('ReviewRequestDraft', 'depends_on', initial=None, null=False), ]
9,777
8279f8a80d96a7231e35100d2c39fa5e1f34f5f5
from scipy.cluster.hierarchy import dendrogram, linkage from get_train import get, pre import matplotlib.pyplot as plt #%% index = [ 'BAC', 'JPM', 'GS', 'C', 'AAPL', 'IBM', 'MSFT', 'ORCL' ] years = [ 2010, 2013, ...
9,778
6339a1a06319a748030b3411c7a8d00f36336e65
# 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 # distributed under t...
9,779
2f9a081845685a4748c8b028ae4ee3a056a10284
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of CbM (https://github.com/ec-jrc/cbm). # Author : Konstantinos Anastasakis # Credits : GTCAP Team # Copyright : 2021 European Commission, Joint Research Centre # License : 3-Clause BSD import os import glob from ipywidgets import (Text, Label...
9,780
c2f859e0ed0e812768dec04b2b1f9ddd349350f6
# open a converted base to bits file and convert it back to the base sequences seq2 = '' with open('chr01.txt') as a: while 1: seq = a.read(2) # print(seq) seq = seq.replace('00', 'c').replace('01', 'g').replace('10', 'a').replace('11', 't') seq2 += seq if not seq: ...
9,781
451a36eb205a269a05e3b3d89541278633d12aaa
class ChartType: Vanilla = "Vanilla" Neopolitan = "Neopolitan"
9,782
4ed6f4db4c9c3319d6289ba402f81bbd8accf915
import numpy as np import dxchange import ptychotomo if __name__ == "__main__": # read object u = dxchange.read_tiff('data/init_object.tiff') u = u+1j*u/2 nz, n, _ = u.shape # parameters center = n/2 ntheta = 384 ne = 3*n//2 ngpus = 1 pnz = nz//2 theta = np.linspace(0...
9,783
21c581131cff8cf2f4aa407055184d56865a6335
#!/usr/bin/env python # Title : STACK_BostonHousing.py # Description : Stacking was the natural progression of our algorithms trial. # In here, we'll use prediction from a number of models in order # to improve accuracy as it add linearly independent data to our # ...
9,784
41ca762fe6865613ae4ef2f657f86b516353676f
from django.contrib.auth import authenticate, login, logout from django.template import loader from django.http import (HttpResponse, JsonResponse, HttpResponseForbidden, HttpResponseBadRequest) from django.shortcuts import redirect from django.views.decorators.http import require_POST import ...
9,785
518dcdca8f5e6b42624083e4327143dfba59b2ba
def emphasize(sentence): words = sentence.split(" ") for i, word in enumerate(words): words[i] = word[0].upper() + word[1:].lower() return " ".join(words) exp1 = "Hello World" ans1 = emphasize("hello world") assert ans1 == exp1, f"expected {exp1}, got {ans1}" exp2 = "Good Morning" ans2 = emphasiz...
9,786
1c55cfa03cd9210b7cf9e728732afe19930e9a41
import yet import pickle sources = pickle.load(open("./db/source_list")) addr_list = sources.keys() ''' for i in range(len(addr_list)): print addr_list[i], try: a = yet.tree(None, sources[addr_list[i]]) print ' Owner :', for i in a.owner.keys(): print i+ '() ' + a.owner[...
9,787
a78bbb85f4912e5f7ea23f689de65cb16a38d814
import asyncio from . import edit_or_reply, udy plugin_category = "utils" @udy.cod_cmd( pattern="as$", command=("as", plugin_category), info={ "header": "salam.", "usage": "{tr}as", }, ) async def _(event): "animation command" event = await edit_or_reply(event, "as") awai...
9,788
fd059ae6e5eb3f7dc18dff6f9ed206002cea5fb2
import os print(os.name) #print(os.environ) print(os.environ.get('PATH')) print(os.path.abspath('.')) os.path.join(os.path.abspath('.'),'testdir') os.mkdir(os.path.abspath('.'))
9,789
44e4151279884ce7c5d5a9e5c82916ce2d3ccbc2
import random from datetime import timedelta from typing import Union, Type, Tuple, List, Dict from django import http from django.test import TestCase, Client from django.utils import timezone from exam_web import errors from exam_web.models import Student, AcademyGroup, uuid_str, ExamSession, \ UserSession, Que...
9,790
1fda8274024bdf74e7fbd4ac4a27d6cfe6032a13
from distutils.core import setup setup(name='greeker', version='0.3.2-git', description="scrambles nouns in an XML document to produce a specimen for layout testing", author="Brian Tingle", author_email="brian.tingle.cdlib.org@gmail.com", url="http://tingletech.github.com/greeker.py/", ...
9,791
75217256d88c32ed1c502bc104c30092bf74382d
# Find sum/count of Prime digits in a number
9,792
acd0b9019ef413699b47ecb2b66a0980cf3aa81f
from cudasim.ParsedModel import ParsedModel import re import copy class Writer: def __init__(self): pass # replace the species and parameters recursively @staticmethod def rep(string, find, replace): ex = find + "[^0-9]" while re.search(ex, string) is not None: res...
9,793
c9b62328a463fd38f3dbd1e7b5e1990f7eec1dba
from django.shortcuts import render from django.http import HttpResponse def view1(request): return HttpResponse(" Hey..,This is the first view using HttpResponce!") def view2(request): context={"tag_var":"tag_var"} return render(request,"new.html",context) # Create your views here.
9,794
6cd250b3bffd87657ec7cc28eaffe817c6d9f73f
# Generated by Django 2.0.3 on 2018-04-30 16:25 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('threads', '0007_auto_20180430_1617'), ] operations = [ migrations.AlterField( model_name='thread', ...
9,795
00099cab0c816c76fc0fa94d7905175feb6919cf
import django.dispatch property_viewed = django.dispatch.Signal(providing_args=["property","user", "request", "response"])
9,796
8de36400f21bfb4e24703d5a65471a961e1afddc
#coding=utf-8 from selenium import webdriver wd=webdriver.Firefox() wd.get('https://www.baidu.com/') wd.find_element_by_id('kw').send_keys(u'哈哈') wd.quit()
9,797
a52f009a755b45f8ed653a4a0385b1eb667f2318
__author__ = 'changwoncheo' # -*- coding: utf-8 -*- import threading import logging logging.basicConfig(filename='crawl2.log',level=logging.DEBUG) class NoParsingFilter(logging.Filter): def filter(self, record): msg = record.getMessage() return not ('Starting' in msg or 'GET' in msg) logger = loggin...
9,798
93e534e8d425510b59310dcbfc5bca9cc32f245e
import sys import random #import matplotlib.pyplot as plt import numpy as np import time class Waterfilling: """ initializes x and r with optimal flow allocations and link fair share rates for traffic matrix routes and link capacities c, and level with number of levels after running the waterfillin...
9,799
c4c24c36fe0afba61f8046055690f0c36df7098c
# Developed by : Jays Patel (cyberthreatinfo.ca) # This script is use to find the python Composer packages vulnerabilities from linux machine and python source project. import time import glob2 import random import os.path from os import path import ast import sys import commands import re import requests from pkg_res...