index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
8,300
cf6d3a0fbf2a2daf8432622f780e138784ec505d
import re IS_WITH_SINGLETON_REGEX = re.compile("(!=|==)\s*(True|False|None)") def check_is_with_singleton(physical_line, line_number): match_obj = IS_WITH_SINGLETON_REGEX.search(physical_line) if match_obj is not None: offset = match_obj.span()[0] return (0, 12, (line_number, offset), "Use eq...
8,301
f317d67b98eab1f0f192fa41f9bcc32b0c1e8eb0
# Run 'python setup.py build' on cmd import sys from cx_Freeze import setup, Executable import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 't...
8,302
3b15767988f1d958fc456f7966f425f93deb9017
""" Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings. """ from collections import Counter import math import os import random import re import sys # Com...
8,303
97029ac9f05037bf9304dacf86c35f5534d887c4
class Solution: def sumSubarrayMins(self, A: List[int]) -> int: stack = [] prev = [None] * len(A) for i in range(len(A)): while stack and A[stack[-1]] >= A[i]: stack.pop() prev[i] = stack[-1] if stack else -1 stack.append(i) stack =...
8,304
56d5915d30e85285da549cc69ef25714bacc6f3a
from .alexnet import * from .lenet import * from .net import * from .vae import *
8,305
09420360ddcf2f74c2e130b4e09ae2a959e42e50
class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: word_count = {} A = A.split() B = B.split() whole = A + B for word in whole: if word not in word_count: word_count[word] = 1 else: word_count[...
8,306
0964121d88fad2906311de7532eac52ff784fff6
""" Main CLI endpoint for GeoCube """ import importlib.metadata import click from click import group import geocube.cli.commands as cmd_modules from geocube import show_versions CONTEXT_SETTINGS = { "help_option_names": ["-h", "--help"], "token_normalize_func": lambda x: x.replace("-", "_"), } def check_ve...
8,307
dce7fd0c9ed8e1d433f9131a8d137c8dcca4ac56
#!/bin/python3 # TODO: implement the stack O(N) version ''' Naive: O(N^3) or sum_{k=1...N}( O(N^2 (N-K)) ) for each size N for each window of size N in the array traverse the window to find the max Naive with heap: O(N^2 log N) for each size N O(N) traverse array and accumulate window of size N O(N...
8,308
758e5b9a65132c4bdee4600e79c27f9c0f272312
import pymysql import pymssql import socket import threading from time import sleep address = ('127.0.0.1', 20176) usermode = {1: 'Wangcz_Students', 2: 'Wangcz_Teachers', 3: 'Wangcz_Admin' } def checkuser(username, password, cursor, user_db): cursor.execute('''select * from %s...
8,309
dc28c3426f47bef8b691a06d54713bc68696ee44
#!/usr/bin/env python3 import numpy as np import os import random import pandas as pd def read_chunk(reader, chunk_size): data = {} for i in range(chunk_size): ret = reader.read_next() for k, v in ret.items(): if k not in data: data[k] = [] data[k].appe...
8,310
a5eeafef694db04770833a4063358e8f32f467b0
import os from typing import List, Optional, Sequence import boto3 from google.cloud import storage from ..globals import GLOBALS, LOGGER def set_gcs_credentials(): if os.path.exists(GLOBALS.google_application_credentials): return secrets_client = boto3.client( "secretsmanager", reg...
8,311
398c28265e61831ba65b4ae2a785e57c0fa5b6d2
class Solution: def toGoatLatin(self, S: str) -> str: def exchange(str2): if str2[0] in "aeiou": str2 = str2+"ma" else: str2 = str2[1:]+str2[0]+"ma" list2 = S.split(" ") for i in list2: res.append(exchange(i)) ...
8,312
b16ad4bae079159da7ef88b61081d7763d4ae9a0
#!/usr/bin/env python ##!/work/local/bin/python ##!/work/local/CDAT/bin/python import sys,getopt import matplotlib.pyplot as plt def read(): x = [] y = [] for line in sys.stdin: v1,v2 = line.split()[:2] x.append(float(v1)) y.append(float(v2)) return x,y #def plot(x,y): def ...
8,313
19f202c32e1cf9f7ab2663827f1f98080f70b83e
from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from linebot import LineBotApi, WebhookParser from linebot.exceptions import InvalidSignatureError, LineBotApiError from linebot.models import ...
8,314
fd6cf903490ff4352e4721282354a68437ecb1e0
from socket import * from multiprocessing import Process import sys ADDR = ("127.0.0.1", 8888) udp_socket = socket(AF_INET, SOCK_DGRAM) # udp_socket.bind(("0.0.0.0",6955)) # udp套接字在一段时间不链接后,会自动重新分配端口,所以需要绑定 def login(): while True: name = input("请输入昵称(不能重复)") msg = "LOGIN" + "##" + name u...
8,315
88445d8466d7acbf29d2525c7e322611d66494cd
import sys if sys.version_info.major == 2: from itertools import izip else: izip = zip
8,316
6e07dcc3f3b8c7fbf8ce8d481b9612e7496967bd
Ylist = ['yes', 'Yes', 'Y', 'y'] Nlist = ['no', 'No', 'N', 'n'] America = ['America', 'america', 'amer', 'rica'] TRW = ['1775', 'The Revolutionary war', 'the Revolutionary war', 'the revolutionary war', 'The Revolutionary War', 'trw', 'Trw', 'TRW'] TCW = ['1861', 'The civil war', 'The civil War', 'The Civil...
8,317
fcd2bd91dff3193c661d71ade8039765f8498fd4
''' Created on Dec 18, 2011 @author: ppa ''' import unittest from ultrafinance.pyTaLib.indicator import Sma class testPyTaLib(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSma(self): sma = Sma(period = 3) expectedAvgs = [1, 1.5, 2, 3, 4] ...
8,318
0699c9f70f1c16b4cb9837edf7a4ef27f021faec
def modCount(n, m): if(m <= n): inBetween = n - m dividible = [] for x in range(m+1, n): if(x%m == 0): dividible.append(x) return 'There are {} numbers between {} and {} \nand the ones that are dividible by {} are {}'.format(inBetween, m, n, m, dividib...
8,319
81c9cabaa611f8e884708d535f0b99ff83ec1c0d
from setuptools import setup from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='SumoSound', packages=['SumoSound'], version='1.0.2', license='MIT', description='A pyt...
8,320
edf704d720abdb09d176937664c9ba98bcd253a5
message = input() vowel = 'aeiouAEIOU' consonant = 'bcdfghjklmnpqrstvwxyz' consonant += consonant.upper() vowel_count = 0 consonant_count = 0 for c in message: if c in vowel: vowel_count += 1 elif c in consonant: consonant_count += 1 print(vowel_count, consonant_count)
8,321
ad9bb34fdb05ab885f4871693729449f3618603a
#Script to extract features from chess score data file stockfish.csv import numpy as np import pandas as pd #Load in and format raw chess game scoring data raw_scores = [line.strip().split(",")[1].split() for line in open("stockfish.csv")][1:] #Initialize containers for features to extract game_length = [] average_sc...
8,322
45dc9d362a2ddfd408f93452bda0b7338057ca81
from django.db import models from django.utils import timezone from pprint import pprint class Cast(models.Model): name = models.CharField(max_length=50, blank=True, null=True) image = models.ImageField(upload_to='cast', blank=True, null=True) description = models.CharField(max_length=400, blank=True, null...
8,323
19221823f14cf06a55d445fc241fc04e64e5873c
# This is the template file for Lab #5, Task #1 import numpy import lab5 def digitize(samples,threshold): return 1*(samples > threshold) class ViterbiDecoder: # given the constraint length and a list of parity generator # functions, do the initial set up for the decoder. The # following useful instance ...
8,324
32227029cb4e852536611f7ae5dec5118bd5e195
# SPDX-License-Identifier: Apache-2.0 """ .. _example-lightgbm-pipe: Convert a pipeline with a LightGbm model ======================================== .. index:: LightGbm *sklearn-onnx* only converts *scikit-learn* models into *ONNX* but many libraries implement *scikit-learn* API so that their models can be inclu...
8,325
1e292872c0c3c7f4ec0115f0769f9145ef595ead
# -*- coding: utf-8 -*- # __author__ = 'XingHuan' # 3/27/2018 import os import imageio import time os.environ['IMAGEIO_FFMPEG_EXE'] = 'D:/Program Files/ffmpeg-3.4/bin/ffmpeg.exe' reader = imageio.get_reader('test1080.mov') print reader fps = reader.get_meta_data()['fps'] print fps # for i, im in enumerate(reader)...
8,326
e265b2b2ccc0841ccb8b766de4ae2a869f2d280d
import tensorflow as tf from keras import layers, Model, Input from keras.utils import Progbar, to_categorical from keras.datasets.mnist import load_data import numpy as np import matplotlib.pyplot as plt import config import datetime img_height, img_width, _ = config.IMAGE_SHAPE (X, Y), (_, _) = load_data() X = X.re...
8,327
950b2906853c37cdeaa8ed1076fff79dbe99b6f8
import typing import torch.nn as nn from .torch_utils import get_activation, BatchNorm1d from dna.models.torch_modules.torch_utils import PyTorchRandomStateContext class Submodule(nn.Module): def __init__( self, layer_sizes: typing.List[int], activation_name: str, use_batch_norm: bool, use_skip: bo...
8,328
4e94e9e2b45d3786aa86be800be882cc3d5a80b5
""" table.py [-m] base1 base2 ... baseN Combines output from base1.txt, base2.txt, etc., which are created by the TestDriver (such as timcv.py) output, and displays tabulated comparison statistics to stdout. Each input file is represented by one column in the table. Optional argument -m shows a final column with the m...
8,329
0ac471d2cb30a21c1246106ded14cdc4c06d2d40
#!/usr/bin/env python3 from collections import OrderedDict import torch.nn as nn from fairseq.models import FairseqMultiModel, register_model from pytorch_translate import common_layers, utils @register_model("multilingual") class MultilingualModel(FairseqMultiModel): """ To use, you must extend this class ...
8,330
4dda122a8c3a2aab62bb202945f6fb9cb73cf772
from numpy import sqrt def Schout2ConTank(a, b, d): # This function converts parameters from Schoutens notation to Cont-Tankov # notation ## Code th = d * b / sqrt(a ** 2 - b ** 2) k = 1 / (d * sqrt(a ** 2 - b ** 2)) s = sqrt(d / sqrt(a ** 2 - b ** 2)) return th, k, s
8,331
c9f1768e2f2dd47d637c2e577067eb6cd163e972
from functools import partial def power_func(x, y, a=1, b=0): return a*x**y + b new_func = partial(power_func, 2, a=4) print(new_func(4, b=1)) print(new_func(1))
8,332
7eefcfdb9682cb09ce2d85d11aafc04977016ba4
from urllib import request, parse import pandas as pd import json import os class BusInfo: url = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:Bus' url_busstop = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:BusstopPole.json' url_routes = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:BusroutePatt...
8,333
7e23f5598ccfe9aff74d43eb662f860b0404b7ec
#!/usr/bin/env python """ A package that determines the current day of the week. """ from datetime import date import calendar # Set the first day of the week as Sunday. calendar.firstday(calendar.SUNDAY) def day_of_the_week(arg): """ Returns the current day of the week. """ if arg == "day": ...
8,334
61c2a6499dd8de25045733f9061d660341501314
#!/usr/bin/python2 import gmpy2 p = 24659183668299994531 q = 28278904334302413829 e = 11 c = 589000442361955862116096782383253550042 t = (p-1)*(q-1) n = p*q # returns d such that e * d == 1 modulo t, or 0 if no such y exists. d = gmpy2.invert(e,t) # Decryption m = pow(c,d,n) print "Solved ! m = %d" % m
8,335
4a8fa195a573f8001e55b099a8882fe71bcca233
"""storeproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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-...
8,336
8c71bc5d53bf5c4cb20784659eddf8a97efb86ef
# #----------------------------------------# # 3.4 # # Question: # Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. #
8,337
98fb70e1911522365292c86603481656e7b86d73
from django.contrib import admin from .models import CarouselImage, Budget admin.site.register(CarouselImage) admin.site.register(Budget)
8,338
30986eb0a6cd82f837dd14fb383529a6a41def9a
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('c4c_app', '0006_c4cjob_complete'), ] operations = [ migrations.AlterModelOptions( ...
8,339
e560f2f202e477822729d1361b8d7ef7831a00e6
# ------------------------------------------ # # Project: VEXcode VR Maze Solver # Author: Hyunwoo Choi # Created: January 12 2021 # Description: Solves a VEXcode VR maze using the right hand rule # # ------------------------------------------ # Library imports from vexcode import * #main def main...
8,340
800573786913ff2fc37845193b5584a0a815533f
# use local image import io import os from google.cloud import vision from google.oauth2 import service_account creds = service_account.Credentials.from_service_account_file('./key.json') client = vision.ImageAnnotatorClient( credentials=creds, ) # The name of the image file to annotate file_name = os.path.joi...
8,341
75837ab778e94693151de1c17b59e12f8b2336d3
def divide(file): index = 0 head = '' while True: if file[index].isnumeric(): head_index = index break if file[index].isalpha(): head += file[index].lower() else: head += file[index] index += 1 while True: if index ...
8,342
b7632cc7d8fc2f9096f7a6bb61c471dc61689f70
import pandas as pd import numpy as np import urllib.request import urllib.parse import json def predict(input_text): URL = "http://127.0.0.1:8000/api/v1/predict/" values = { "format": "json", "input_text": input_text, } data = urllib.parse.urlencode({'input_text': i...
8,343
1c8145007edb09d77a3b15de5c34d0bc86c0ba97
import argparse # for handling command line arguments import collections # for container types like OrderedDict import configparser import hashlib # for SHA-1 import os import re import sys import zlib # git compresses everything using zlib argparser = argparse.ArgumentParser(description="The stupid content tracker") ...
8,344
257a4d0b0c713624ea8452dbfd6c5a96c9a426ad
import pymysql import logging import socket from models.platformconfig import Pconfig class ncbDB(Pconfig): # I have to retrieve basic configuration attributes, listed below, from system config file # on ApplSrv, for example : /etc/ncb_applsrv/ncb_applsrv.conf hostname = None conferenceMediaStoragePa...
8,345
15ca54aff4c688733c9c514ba5856e6bf29a3292
""" Compare 1-D analytical sphere solution to 1-D numerical and 3-D Comsol solutions for transient heat conduction in solid sphere with constant k and Cp. Assumptions: Convection boundary condition at surface. Symmetry about the center of the solid. Heat transfer via radiation assumed to be negligable. Particle does n...
8,346
3b41bd59c133bb04dae3aa48dc0699388d5bf3d4
import os import json import random chapter_mode = True setname = 'test_other' use_chapter = '_chapter' minlen = 1000 maxlen = 1000 context = '_1000' info_json = 'bookinfo{}_{}{}.json'.format(use_chapter, setname, context) book_ID_mapping = {} with open('speaker_book.txt') as fin: for line in fin: elems ...
8,347
27fc11ae68531c7dbafdcf134f0eef019210e2de
from django import forms from django.forms import widgets from tsuru_dashboard import settings import requests class ChangePasswordForm(forms.Form): old = forms.CharField(widget=forms.PasswordInput()) new = forms.CharField(widget=forms.PasswordInput()) confirm = forms.CharField(widget=forms.PasswordInput...
8,348
73e6930c6866d3ccdbccec925bfc5e7e4702feb9
""" eulerian_path.py An Eulerian path, also called an Euler chain, Euler trail, Euler walk, or "Eulerian" version of any of these variants, is a walk on the graph edges of a graph which uses each graph edge in the original graph exactly once. A connected graph has an Eulerian path iff it has at most two graph vertices ...
8,349
c00a8bfec46ed829e413257bf97c44add564080d
#!/usr/bin/env python import rospy import rosnode import csv import datetime import rosbag import sys import os import matplotlib.pyplot as plt import argparse import math from math import hypot import numpy as np from sensor_msgs.msg import LaserScan from std_msgs.msg import String import yaml as yaml start_time = Non...
8,350
a52762fb13c04ced07a41a752578c4173d1eac42
from queue import Queue class Node(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def array_to_tree_dfs(array): n = len(array) if n>0: root = Node(array[0]) def dfs(node, index): # if index >= n: ...
8,351
12396130dc52866cc54d6dc701cf0f9a41a168b6
from PyInstaller.utils.hooks import collect_data_files hiddenimports = ['sklearn.utils.sparsetools._graph_validation', 'sklearn.utils.sparsetools._graph_tools', 'sklearn.utils.lgamma', 'sklearn.utils.weight_vector'] datas = collect_data_files('sklearn')
8,352
8ca16947054b681a5f43d8b8029191d031d3a218
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Swking @File : ZDT.py @Date : 2018/12/28 @Desc : """ import numpy as np class ZDT1: def __init__(self): self.dimension = 30 self.objFuncNum = 2 self.isMin = True self.min = np.zeros(self.dimension) self.max = np.zeros(self.dimension) + 1 self.s...
8,353
55ffcf5e6120cc07da461e30979dd8a36a599bee
#------------------------------------------------------------------------------- # rtlconverter.py # # PyCoRAM RTL Converter # # Copyright (C) 2013, Shinya Takamaeda-Yamazaki # License: Apache 2.0 #------------------------------------------------------------------------------- import sys import os import subprocess im...
8,354
2e6f04c3ff3e47a2c3e9f6a7d93e7ce2955a2756
from __future__ import print_function from __future__ import absolute_import from builtins import str from builtins import range from builtins import object import hashlib from xml.sax.saxutils import escape from struct import unpack, pack import textwrap import json from .anconf import warning, error, CONF, enable_c...
8,355
1deab16d6c574bf532c561b8d6d88aac6e5d996c
# Importing datasets wrangling libraries import numpy as np import pandas as pd incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns)
8,356
c0f4f9eef12d99d286f5ad56f6554c5910b7cc71
users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, ...
8,357
4d0b08f8ca77d188aa218442ac0689fd2c057a89
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os, shutil, time, pickle, warnings, logging import yaml from sklearn import preprocessing from sklearn.model_selection import StratifiedKFold, KFold from sklearn import metrics from scipy.special import erfinv from scipy.stats import mode wa...
8,358
84d096a51fa052ee210e975ab61c0cbbf05bc5ae
class Day8MemoryManeuver: def __init__(self, use_reference_count=False): """ Args: use_reference_count (bool): True: If an entry has child nodes, the meta data are referring to the results of the child node False: Sum all meta data up ...
8,359
e18ebf961c2daa7dd127d08f85edb6ea519e3470
#!/usr/bin/python """ Expression Parser Tree for fully parenthesized input expression """ from bintree import BinaryTree from stackModule import Stack def buildParseTree(expression): expList = expression.split() empTree = BinaryTree('') parentStack = Stack() parentStack.push(empTree) currentNode ...
8,360
a4c4a5cc63c345d1fa8cbf426f7857a0f3d4357f
# Generated by Django 3.2.4 on 2021-06-16 13:41 import ckeditor.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('FAQ', '0004_auto_20210616_1253'), ] operations = [ migrations.RemoveField( model_name='question', nam...
8,361
ad94118b43e130aec5df3976fd0460164de17511
#!/usr/bin/python # coding: utf-8 # # import re # # import urllib # # # # # # def getHtml(url): # # page = urllib.urlopen(url) # # html = page.read() # # return html # # # # # # def getMp4(html): # # r = r"href='(http.*\.mp4)'" # # re_mp4 = re.compile(r) # # mp4List = re.findall(re_mp4, html) ...
8,362
28851979c8f09f3cd1c0f4507eeb5ac2e2022ea0
''' Run from the command line with arguments of the CSV files you wish to convert. There is no error handling so things will break if you do not give it a well formatted CSV most likely. USAGE: python mycsvtomd.py [first_file.csv] [second_file.csv] ... OUTPUT: first_file.md second_file.md ... ''' import sys import cs...
8,363
37fdfddb471e2eec9e5867d685c7c56fc38c5ae7
import json import logging import os import sys from io import StringIO import pytest from allure.constants import AttachmentType from utils.tools import close_popups _beautiful_json = dict(indent=2, ensure_ascii=False, sort_keys=True) # LOGGING console ##############################################################...
8,364
9320926c9eb8a03d36446f3692f11b242c4fc745
#!/usr/bin/env python3 # coding=utf-8 # date 2020-10-22 10:54:38 # author calllivecn <c-all@qq.com> import sys import random import asyncio import argparse def httpResponse(msg): response = [ "HTTP/1.1 200 ok", "Server: py", "Content-Type: text/plain", "Content-Le...
8,365
90a402cccf383ed6a12b70ecdc3de623e6e223f9
def ex7(*siruri, x=1, flag=True): res = () for sir in siruri: chars = [] for char in sir: if ord(char) % x == (not flag): chars.append(char) res += (chars,) return res print(ex7("test", "hello", "lab002", x=2, flag=False))
8,366
6e73625adc10064cdb1b5f0546a4fc7320e9f5dc
from django import template import random register = template.Library() @register.simple_tag def random_quote(): """Returns a random quote to be displayed on the community sandwich page""" quotes = [ "Growth is never by mere chance; it is the result of forces working together.\n-James Cash Penney", ...
8,367
158b39a64d725bdbfc78acc346ed8335613ae099
#common method to delete data from a list fruits=['orange','apple','mango','grapes','banana','apple','litchi'] #l=[] #[l.append(i) for i in fruits if i not in l] #print(l) print(set(fruits)) print(fruits.count("orange")) #pop method in a list used to delete last mathod from a lis...
8,368
802eb0502c5eddcabd41b2d438bf53a5d6fb2c82
from django.db import models from NavigantAnalyzer.common import convert_datetime_string import json # A custom view-based model for flat outputs - RÖ - 2018-10-24 # Don't add, change or delete fields without editing the view in the Db class Results_flat(models.Model): race_id = models.IntegerField() race_name...
8,369
77ae3ef1f6f267972a21f505caa7be29c19a6663
from models import Session, FacebookUser, FacebookPage, FacebookGroup from lib import get_scraper, save_user, save_page import logging logging.basicConfig(level=logging.DEBUG) session = Session() scraper = get_scraper(True) for user in session.query(FacebookUser).filter(FacebookUser.data=="todo").filter("username ~ '...
8,370
b0a49f5876bc3837b69a6dc274f9587a37351495
import myThread def main(): hosts={"127.0.0.1":"carpenter"} myThread.messageListenThread(hosts) if __name__ == '__main__': main()
8,371
f039ab104093eb42c3f5d3c794710a0997e85387
# coding: utf-8 # Aluno: Héricles Emanuel # Matrícula: 117110647 # Atividade: É quadrado Mágico? def eh_quadrado_magico(m): somas_all = [] eh_magico = True soma = 0 for e in range(len(m[0])): soma += m[0][e] # Linhas for i in range(len(m)): somados = 0 for e in range(len(m[i])): somados += (m[i][e]) s...
8,372
14e304f30364932910986f2dda48223b6d4b01c0
from tqdm import tqdm import fasttext import codecs import os import hashlib import time def make_save_folder(prefix="", add_suffix=True) -> str: """ 1. 現在時刻のハッシュをsuffixにした文字列の生成 2. 生成した文字列のフォルダが無かったら作る :param prefix:save folderの系統ラベル :param add_suffix: suffixを付与するかを選ぶフラグ, True: 付与, False: 付与しない ...
8,373
96936b7f6553bee06177eb66a2e63064c1bf51a6
from __future__ import unicode_literals import requests try: import json except ImportError: import simplejson as json def main(app, data): MEDIUM_API_ENDPOINT = 'https://medium.com/{0}/latest?format=json' r = requests.get(MEDIUM_API_ENDPOINT.format(data.get('username'))) response_content = r....
8,374
36fb0d936be5c5d305c4076fd1c497664c9b770a
# -*- coding: utf-8 -*- from ..general.utils import log_errors from googleapiclient import discovery from oauth2client.client import SignedJwtAssertionCredentials from django.conf import settings from celery import shared_task from logging import getLogger import httplib2 _logger = getLogger(__name__) def create_ev...
8,375
64935ae910d5f330722b637dcc5794e7e07ab52d
from eval_lib.classification_results import analyze_one_classification_result from eval_lib.classification_results import ClassificationBatches from eval_lib.cloud_client import CompetitionDatastoreClient from eval_lib.cloud_client import CompetitionStorageClient from eval_lib.dataset_helper import DatasetMetadata from...
8,376
7491a17256b9bc7af0953202e45f0fd9d5c34c40
import ctypes import time from order_queue.order import Order class stock(ctypes.Structure): _fields_ = [('stock_id', ctypes.c_int), ('order_type',ctypes.c_int),('Time',ctypes.c_char * 40),('user_id',ctypes.c_int),('volume',ctypes.c_int), ('price',ctypes.c_double) ] class exchange(ctypes.St...
8,377
443ce5c2ec86b9f89ad39ef2ac6772fa002e7e16
class NumMatrix(object): def __init__(self, matrix): if matrix: self.dp = [[0] * (len(matrix[0]) + 1) for i in range(len(matrix)+1)] for i in xrange(1,len(matrix)+1): for j in xrange(1,len(matrix[0])+1): self.dp[i][j] = self.dp[i-1][j] + self....
8,378
2e3c1bf0a4c88bda35a48008cace8c21e071384e
disk = bytearray (1024*1024); def config_complete(): pass def open(readonly): return 1 def get_size(h): global disk return len (disk) def can_write(h): return True def can_flush(h): return True def is_rotational(h): return False def can_trim(h): return True def pread(h, count, of...
8,379
dfd2b515e08f285345c750bf00f6a55f43d60039
"""David's first approach when I exposed the problem. Reasonable to add in the comparison? """ import numpy as np from sklearn.linear_model import RidgeCV from sklearn.model_selection import ShuffleSplit def correlation(x, y): a = (x - x.mean(0)) / x.std(0) b = (y - y.mean(0)) / y.std(0) return a.T @ b / ...
8,380
7e985f55271c8b588abe54a07d20b89b2a29ff0d
from codecool_class import CodecoolClass from mentor import Mentor from student import Student codecool_bp = CodecoolClass.create_local
8,381
6ba830aafbe8e4b42a0b927328ebcad1424cda5e
class Solution: ''' 先遍历整个string,并记录最小的character的出现次数。 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可; 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。 ''' ...
8,382
ae7a2de8742e353818d4f5a28feb9bce04d787bb
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 17:34:32 2019 @author: fanlizhou Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt' Plot heatmap of amino acid usage and codon usage Plot codon usage in each gene for each amino acid. Genes were arranged so that the ge...
8,383
e0c6fb414d87c0a6377538089226e37b044edc70
from django.shortcuts import render from django_filters.rest_framework import DjangoFilterBackend from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http import JsonResponse, Http404 from .serializers import * from .models import * from .filter import * from r...
8,384
3001534be3364be1148cd51a4a943fd8c975d87e
from flask import (Flask, render_template, request, url_for, redirect, flash, jsonify) app = Flask(__name__) @app.route('/', methods=['GET']) def showHomepage(): return render_template('home.html') if __name__ == '__main__': print('app started') app.secret_key = 'secretkey' app.run(debug=True)
8,385
2f64aac7032ac099870269659a84b8c7c38b2bf0
import pandas as pd import subprocess import statsmodels.api as sm import numpy as np import math ''' This function prcesses the gene file Output is a one-row file for a gene Each individual is in a column Input file must have rowname gene: gene ENSG ID of interest start_col: column number which the gene exp value st...
8,386
edc66bdc365f9c40ee33249bd2d02c0c5f28256a
import torch import torch.nn as nn class ReconstructionLoss(nn.Module): def __init__(self, config): super(ReconstructionLoss, self).__init__() self.velocity_dim = config.velocity_dim def forward(self, pre_seq, gt_seq): MSE_loss = nn.MSELoss() rec_loss = MSE_loss(pre_seq[:, 1:-...
8,387
9ca769ae8bbabee20b5dd4d75ab91d3c30e8d1bf
def filter(txt): # can be improved using regular expression output = [] for t in txt: if t == "(" or t == ")" or t == "[" or t == "]": output.append(t) return output result = [] while True: raw_input = input() line = filter(raw_input) if raw_input != ".": stack = [] err = False for l in line: ...
8,388
a8659ca7d7a5870fc6f62b3dfee1779e33373e7b
#!/usr/bin/python2.7 '''USAGE: completeness.py BLAST_output (tab formatted) Prints % completeness based on marker gene BLAST of caled genes from a genome Markers from Lan et al. (2016) ''' import sys with open(sys.argv[1],'r') as blastOut: geneHits = [] orgHits = [] hits = 0.0 for line in blastOut: hits += 1.0 ...
8,389
dc2c9293040204f0ec2156c41b8be624f4e5cf99
# 라이브러리 환경 import pandas as pd import numpy as np # sklearn 테이터셋에서 iris 데이터셋 로딩 from sklearn import datasets iris = datasets.load_iris() # iris 데이터셋은 딕셔너리 형태이므로, key 값 확인 ''' print(iris.keys()) print(iris['DESCR']) print("데이터 셋 크기:", iris['target']) print("데이터 셋 내용:\n", iris['target']) ''' # data 속성의 데이터셋 크기 print("...
8,390
4c9a3983180cc75c39da41f7f9b595811ba0dc35
import urllib.request from urllib.request import Request, urlopen import json from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup """ Web Scraper ====================================================================== """ ...
8,391
e11a04cad967ae377449aab8b12bfde23e403335
import webbrowser import time total = 3 count = 0 while count<total: webbrowser.open('https://www.youtube.com/watch?v=GoSBNNgf_Vc') time.sleep(5*60*60) count+=1
8,392
689c6c646311eba1faa93cc72bbe1ee4592e45bc
#!/usr/bin/env python3 from typing import ClassVar, List print(1, 2) # Annotated function (Issue #29) def foo(x: int) -> int: return x + 1 # Annotated variables #575 CONST: int = 42 class Class: cls_var: ClassVar[str] def m(self): xs: List[int] = [] # True and False are keywords in Python ...
8,393
a9947884e805cc8fcb6bff010a5f6e0ff0bb01fe
import math import numpy as np # import tkinter import tensorflow as tf from matplotlib import axis import os from sklearn.base import BaseEstimator, TransformerMixin from sklearn.cluster import KMeans from sklearn.metrics import confusion_matrix class MD(BaseEstimator, TransformerMixin): def __init__(self, data,...
8,394
86f33895e9ae0e026d7d6e40e611796b2dc2c713
"""@brief the routes for Flask application """ import hashlib import json import time import requests from flask import render_template, url_for from soco import SoCo from app import app app.config.from_pyfile("settings.py") sonos = SoCo(app.config["SPEAKER_IP"]) def gen_sig(): """@brief return the MD5 checksum...
8,395
4a14265a9a2338be66e31110bba696e224b6a70f
from django.shortcuts import render from django.http import HttpResponse from chats.models import Chat from usuario.models import Usuario # Create your views here. def chat(request): chat_list = Chat.objects.order_by("id_chat") chat_dict = {'chat': chat_list} return render(request,'chats/Chat.html', ...
8,396
9816a8265bcdb8c099f599efbe1cfe1a554e71f5
from django.conf.urls import url from price_App import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^api/price/(?P<pk>[0-9]+)$', views.product_price), url(r'^api/price_history/(?P<pk>[0-9]+)$', views.product_history),] urlpatterns = format_suffix...
8,397
76a22408bb423d9a5bc5bc007decdbc7c6cc98f7
""" Neuraxle Tensorflow V1 Utility classes ========================================= Neuraxle utility classes for tensorflow v1. .. Copyright 2019, Neuraxio 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 obta...
8,398
8364264851895ccabeb74fd3fab1d4f39da717f8
from django.apps import AppConfig class StonewallConfig(AppConfig): name = 'stonewall'
8,399
e6010ec05ec24dcd2a44e54ce1b1f11000e775ce
######################################################################### # 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...