index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
984,500
45e842e2a1ea0bf4c5b0875f8c8189b751403f49
import json import logging import numpy as np import os import pickle from pyltp import Segmentor logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) """ SMP 分类工具类 """ class Data(object): """Load and ...
984,501
be9e62f29d913b2df85a58837509a321a4cb6345
# A Python program to demonstrate working of # findall() import re # A sample text string where regular expression # is searched. string = """Hello my Number is 123456789 and my friend's number is 987654321""" # A sample regular expression to find digits. regex = '\d+' match = re.findal...
984,502
cafce32193338657ab2909b4a1b827d56bc106c7
#!/usr/bin/python import sys, csv, os, time, pickle from subprocess import Popen, PIPE, STDOUT # # Computer Science 143 - PROJECT 2 - GRADING APPLICATION # # (this is the main script which should be run, set default variables in # default_vars.py) # IMPORTANT: If this script is not run from its own directory # saves...
984,503
0fbbe97f5e8cbc3cba4752726b330c682b40151a
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/12/8 上午10:22 # @Author : Aries # @Site : # @File : py077_name_space.py # @Software: PyCharm ''' 名称空间 ''' j, k = 1, 2 def proc1(): j, k = 3, 4 print 'j==%d and k==%d' % (j, k) k = 5 def proc2(): j = 6 proc1() print 'j==%d...
984,504
6f16858451d6aa166effa523789765d147c2f62d
print("hello every one") print("welcome to python") print("sum",44+77)
984,505
9279ca529b1c0bfa9287a476e1163efc9bf4b258
from . import load_config from . import yaml_helper from . import replay_buffer from .load_config import * from .yaml_helper import *
984,506
2c6bac8937be88f314be4de864c1ad53ee3f6c52
a, b = [int(i) for i in input().split()] ans = a * b if ans % 2 == 0: print('Even') else: print('Odd')
984,507
80224a950ebeefb8cb37896fdb719149d4386bae
from itertools import zip_longest import numpy as np def quadratic_interpolation(x_nodes, y_nodes, points_num, start_cond): n = len(x_nodes) h = [] for i in range(1, n, 1): h.append(x_nodes[i] - x_nodes[i - 1]) b = [] for i in range(1, n): b.append((y_nodes[i] - y_nodes[i - 1]) *...
984,508
d50a758f9a90f0c6aec861f5ffad724677ac112e
from django.apps import AppConfig, apps from django.core.checks import Error, Tags, Warning, register from django.utils.translation import gettext_lazy as _ __all__ = ["AdminIndexConfig"] class AdminIndexConfig(AppConfig): """Default configuration for the django_admin_index app.""" name = "django_admin_inde...
984,509
fbaf5505e1c77f3f7014a7af874491eb8a848f26
def getLatLongFromNMEA(nmeaSen): lat = nmeaSen[2] latDir = 1.0 if nmeaSen[3] == 'N' else -1.0 #Parse latitude to google maps coordinate hours = float(lat[0:2]) mins = float(lat[2:]) lat = latDir * (hours + mins / 60.0) lon = nmeaSen[4] lonDir = 1.0 if nm...
984,510
9b6459f9e21e4f23389ba5ba57b34142176c85c3
# 尝试t帧检测一次并进行追踪 import setup_path import airsim import cv2 import time import sys from collections import deque import numpy as np import math import msvcrt # Keyboard Input def printUsage(): print("Usage: python camera.py [depth|segmentation|scene]") cameraType = "scene" for arg in sys.argv[1:]: cameraTyp...
984,511
6e3298c6481ace28ef6c6e88a7065ced104ad498
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms import ModelForm from django import forms from .models import Usuarios class UsuarioFrm(ModelForm): class Meta: model = Usuarios fields = '__all__' class RegistroForm(ModelForm...
984,512
fad8ff65841cde1e1ef19ff799c90ea4f5cdb6ab
# encoding: utf-8 """ File: node.py Author: Rock Johnson """ class Node(object): """代表单个链表的节点.""" def __init__(self, data, next = None): """实例化一个Node它的next默认值为None.""" self.data = data self.next = next class TwoWayNode(object): """代表双个链表的节点.""" def __init__(self, data, previo...
984,513
6e2e2df8281f5a730e330c2d07da04954da5b170
print ("Hello World") user= ("My name is Qas") print (user)
984,514
0091ddd0684189d1d1524006bd0eb001ab40b60a
# FACT ENDPOINTS API_ENDPOINTS = { 'GET_RANDOM_FACTS': '/random', 'GET_FACT_BY_ID': '/{fact_id}' } # Status codes STATUS_CODE_200_OK = 200 STATUS_CODE_201_CREATED = 201 STATUS_CODE_202_ACCEPTED = 202 STATUS_CODE_204_NO_CONTENT = 204 STATUS_CODE_400_BAD_REQUEST = 400 STATUS_CODE_401_UNAUTHORIZED = 401 STATUS_CO...
984,515
bdcabd757666da7aae371b11621280ca12a56148
from Amount import Amount import logging logger = logging.getLogger('root') class Budget(object): def __init__(self, amount = Amount('USD', 0)): logger.debug("INIT BUDGET WITH %s", str(amount)) self.amounts = [] self.amounts.append(amount) self.main_currency = amount.currency ...
984,516
6c905cd40dd9a96356d761f454d7aa54014838d9
class Conveyor_Belt: def __init__(self): self.Conveyor_Belt = Conveyor_Belt #self.beltID #self.speedPWM def twistConveyorBelt(self): print("Conveyor Belt is running")
984,517
8138ae3d696ed7b312dc52f9a69acd3a70de6a49
# Time: O(n) # Space: O(1) # Let's call any (contiguous) subarray B (of A) a mountain # if the following properties hold: # # B.length >= 3 # There exists some 0 < i < B.length - 1 # such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] # (Note that B could be any subarray of A, including the ent...
984,518
ae04ebc490ac3ff77a1066146209d6a7676e5445
# write a Python program which accepts the radius of a circle from the user and computes area. Radius=float(input("Input the readius of the circle: ")) area=3.14*Radius*Radius print("The area of the circle with radius ",Radius,"is:",area)
984,519
1976f4ffbf104e17befdfecee3fd39ab244dd226
#Python Program to calculate the area of triangle: # Base and Height are the Parameters Belong to the Triangle: Base=float(input("Enter the Base of the Triangle: ")) Height=float(input("Enter the Height of the Triangle: ")) # Area of the Triangle is 1/2(Base*Height). In meters def area_triangle(Base,Height): i...
984,520
52c9054e7a136735cda5b47f12349a97cd040db0
from django_filters import CharFilter, ChoiceFilter from web.forms import ModelSearchFilter from .models import Template class TemplatesFilter(ModelSearchFilter): # Fields of the model that can be filtered template_name = CharFilter(lookup_expr='icontains', help_text='Use % for...
984,521
5ef76c570b8701e7f9bf9f99273aabaa1506bf0d
import os import scipy from scipy.misc import * import numpy as np from tflearn.data_utils import shuffle def load_data(): X_train = [] Y_train = [] img_ext = '.jpg' #reading c0 first input_path = "/home/mukul/Documents/major/dataset/data/train/c0/" i = 0 for x in os.listdir( input_path ):...
984,522
5fcfcb4c54f0f68e24878d54a14a8e0c8a756b5f
from typing import Set, Type, Any, List, Dict, Optional, Iterable, TYPE_CHECKING import warnings as py_warnings from antlr4 import InputStream from . import messages from . import warnings # pylint: disable=reimported from .parser import sa_systemrdl from .core.ComponentVisitor import RootVisitor from .core.ExprVisit...
984,523
9b6240c24a8e7c100f50957f5955e401d1c254bf
# -*- coding: utf-8 -*- """my URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, nam...
984,524
e6124e436f0d9b84a057d7c01b5dd55cc9043af8
import numpy as np import scipy as sp import tensorflow as tf from networks.utils.sampling import generate_real_images, generate_fake_images from tensorflow.keras.applications.inception_v3 import InceptionV3 class FIDCalculator: def __init__(self, image_processor, fid_res=128, n_fake_samples=128, n_real_samples=...
984,525
bddaf348594d98c93c70decac15cce130a27a35f
# Generated by Django 2.1.1 on 2020-01-09 03:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('skeleton', '0007_auto_20200108_1759'), ] operations = [ migrations.AlterField( model_name='leader', name='profile', ...
984,526
fa29eb72939c4fc6ccb1470a5996e58c3c024ec8
class Node(): def __init__(self,value): """ this is the initial method for class Node, it has two attributes: 1- the value: it contents the value of node. 2- the next: it contents the next's node. """ try: self.value=value self.next=Non...
984,527
b6d8db3619752b3f9a7013cfe049b211b63c49f9
from termcolor import colored, cprint a = float(input(colored('Escreve um número: ', 'blue'))) b = float(input(colored('Escreve outro número: ', 'blue'))) c = float(input(colored('E agora mais um: ', 'blue'))) menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c maior = a if b > c and b > a: ...
984,528
77839ffb98cd1cd259c494aba434dc0bf9e32efd
import FWCore.ParameterSet.Config as cms maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) readFiles = cms.untracked.vstring() secFiles = cms.untracked.vstring() source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles) readFiles.extend( [ '/store/mc/RunIISummer20UL...
984,529
04caf968e252d109f4859cb80211e60e44c8e8c8
# -*- coding: utf-8 -*- from flask import render_template #from ..email import send_email from . import main @main.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html') @main.route('/about') def about(): return render_template('about.html') @main.route('/services') def services()...
984,530
ed521d49a638a138f614ddc6f65ed1c652c9659b
from django.contrib import admin from .models import Data,pol admin.site.register(Data) admin.site.register(pol)
984,531
26ca8c18bd3eb1765fcf203dadeb9fb71cd9286e
#!/usr/bin/env python import yaml import re import imap_client import smtp_client import github_api import email import time import os default_recipients = ['Christos Tsirigotis <tsirif@gmail.com>'] from_list = [ 'Travis CI <notifications@travis-ci.org>', 'Travis CI <builds@travis-ci.org>'] def get_...
984,532
58cccb81c40156cfdc13a7225205264fb3c63e6a
from stable_baselines import ACER from stable_baselines.common.cmd_util import make_atari_env from stable_baselines.common.policies import CnnPolicy from stable_baselines.common.vec_env import VecFrameStack from rlbaselines.common_utils.utils import turn_off_log_warnings if __name__ == '__main__': # Turn off warn...
984,533
b07ec9b3ac7ae6b0b02f9309c0232520a4e9e213
# In python docs study for 'datetime' and 'time' modules regarding different # features , formats , methods , etc. # Write some example programs on this matter. import time import datetime # module "time" is commonly used to measure time and deal with time stamps start_time = time.time() print("--- %s seconds ---...
984,534
d541d978430ac9accc7340894efccef9675df3c6
from django.db import models from django.forms import ModelForm # Create your models here. ENTRANCE_CHOICE = (('G','Ganesha'),('K','Krishna'),('O','Others'),) class Customer(models.Model): customer_name = models.CharField(max_length = 50) customer_address = models.CharField(max_length = 200) landline = models.Char...
984,535
367003dcc39efa74f95a194f5b8ffd378451764d
d={} n=int(input("enter no:-")) for i in range(1,n): d[i]=i**2 print(d)
984,536
829818f8664b8589d06d8e9c13d976a94666d170
""" @author - Anirudh Sharma """ from typing import List class ListNode: def __init__(self, val=0, nextNode=None): self.val = val self.next = nextNode class MergeKSortedList: def mergeKLists(self, lists: List[ListNode]) -> ListNode: # Base condition if lists is None or len(li...
984,537
c568c98d68805d48219505719978d4dcd4d53405
# @Time : 2018/11/5 16:38 # @Author : Yanlin Wang # @Email : wangyl_a@163.com # @File : 1. Timestamps_Time Spans.py from time import clock import pandas as pd import numpy as np from datetime import datetime start = clock() # 新建时间戳 print(pd.Timestamp(datetime(2012, 5, 1))) # Timestamp('2012-05-01 00:00:00'...
984,538
cb69972e4f9cead0d768408a608bc4a247ef0489
import sys, math l = [0, 0] m = 1 n = int(sys.stdin.readline()) for i in range(1, n+1): num = int(sys.stdin.readline()) while m < num: m += 1 l.append(float("inf")) if m % 3 == 0: ii = int(m / 3) l[m] = min(l[ii] + 1, l[m]) if m % 2 == 0: ii =...
984,539
f4b6d6fcca4d0d2fb04f508d49ea40f1e36e731d
from __future__ import absolute_import from django.conf.urls import include, url from django.contrib.gis import admin import ebagis.urls import ebagis_ui.urls from .settings import REST_ROOT # admin pages admin.autodiscover() # standard django url patterns urlpatterns = [ # login/logout # I'm not sure what...
984,540
e5d9fc8d4a964d35724236afaa2ab994c6d13e9c
from django.contrib import admin from boards.models import Board, Card, BoardList class BoardAdmin(admin.ModelAdmin): list_display = ('user', 'title', 'created_date') class BoardListAdmin(admin.ModelAdmin): list_display = ('board', 'title', 'created_date') class CardAdmin(admin.ModelAdmin): list_displ...
984,541
f98ee0f66341856d1b0c64100316d7265978c8dc
import urlparse class URI(object): # def __new__(self, uri): # if isinstance(uri, URI): # return uri def __init__(self, uri): uri = urlparse.urlparse(uri) self.scheme = uri.scheme self.path = uri.path self.netloc = uri.netloc self.params = uri.params ...
984,542
45e77d84ea073bef8b386f01faead112c2d4c559
from django.conf.urls import url, include from blog.views import index, show from blog.admin import blog_admin urlpatterns = [ url(r'^index/', index), url(r'^show/(\d+)/', show), url(r'^admin/', include(blog_admin.urls)), ]
984,543
e98b483c6bdd687073c147b4791eec2df97ea0a0
import random as rand class Node: def __init__(self, value): self.label = value self.left = None self.right = None def getWrongRange(labelRange, minLabel, maxLabel): (mn, mx) = labelRange possibleRanges = [] if minLabel < mn: possibleRanges.append((minLabel, mn)) if maxLabel > mx: possib...
984,544
3013a56643d111237d78a93fdc45c1e53b67e6b5
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2008 Deltatech All Rights Reserved # Dorin Hongu <dhongu(@)gmail(.)com # # This program is free software: you can redistribute it and/or modify # it under the terms of...
984,545
00377bf07fb6fd1330c26801a66c8a00709a8f37
import numpy as np import scipy.misc def save_output(lr_img, prediction, hr_img, path): h = prediction.shape[0] hr_img = do_resize(_post_process(hr_img), [h, prediction.shape[1]]) lr_img = do_resize(_post_process(lr_img), [h, prediction.shape[1]]) eh_img = _post_process(prediction) out_img = np.co...
984,546
24d891f9dd9038da9a5c650f7c3d6807967371df
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QFileDialog, QMainWindow, QTextEdit, QHBoxLayout, QVBoxLayout, QPushButton from seqParser import seq_parser class Example(QMainWindow): log_out = None def __init__(self): super()....
984,547
dd18cff92d9d34cb830a6bb4c442b5f56c74b3a0
""" Implements the gradient test of DOI: 10.1175/JTECHO539.1 All questionable features result in a flag, in order to minimize false negatives """ import numpy def test(p, parameters): """ Runs the quality control check on profile p and returns a numpy array of quality control decisions with False where th...
984,548
872bc8e6b539af08b2fe2acc1d9d16b960d7ed47
def sorting(): items = input("Enter the sequence with hypen: ") for i in items: m = items.split('-') m.sort() print('-'.join(m)) sorting() # items=[n for n in input().split('-')] # items.sort() # print('-'.join(items))
984,549
44d9f5f78f494d2be3cbd11dd7663734b21858fd
#*-* coding: utf-8 *-* def distance(DNA1, DNA2): hamming = 0 z = zip(DNA1, DNA2) for i in range(len(z)): if z[i][0] != z[i][1]: hamming +=1 return hamming if __name__ == '__main__': input1 = raw_input() input2 = raw_input() print distance(input1, input2)
984,550
fb56a5c39c79821b6cd3a5bd25df388e1c590d8f
import tensorflow as tf from os.path import join import os import time import numpy as np import threading from image_utilities import ImageGenerator from image_utilities import * training_summaries = [] LOGDIR = '../tensorboard_dir/' TRAINING_IMAGES_DIR = '../res/training_images' MODELS_DIR = '../models' SAMPLES_DIR ...
984,551
ed04f0a8a317015ee636034ee526423748647541
from django.urls import path from chat import views urlpatterns = [ path("chatroom/<int:pk>", views.chatroom, name = "chatroom"), path("ajax/<int:pk>/", views.ajax_load_messages, name="chatroom-ajax"), path("messageDelete/", views.messageDelete, name="messageDelete"), path("chatroombase/", views.chatro...
984,552
b095f6559a04068b8554913f97c0a10d7215937a
import os import subprocess from pum.core.deltapy import DeltaPy class DropViews(DeltaPy): def run(self): self.write_message('Dropping sigip views') drop_sql = os.path.join(self.delta_dir, '..', 'drop_views.sql') cmd = 'psql service={} -f {}'.format(self.pg_service, drop_sql) sel...
984,553
c4d6d8f7a3f84e5d644553c0c6c6f84bfa40c73c
import sys from presentation.QForm import QForm from PySide.QtGui import QApplication from presentation.interceptor.Interceptor import Interceptor as Interceptor class Main: def __init__(self): app = QApplication(sys.argv) print 'Main----' form = QForm('Sentilyse') self.interceptor...
984,554
2cafbde7c54d898ffa7c7332e4f8a9df2cb88e17
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2017 Routevo # # You may use, distribute and modify this code under the # terms of the MIT license. # # You should have received a copy of the MIT license with # this file. If not, please visit <https://opensource.org/licenses/MIT> import json import requ...
984,555
eb221a05165270625b3cd91c5bbf41050ae865ae
from session.config_var import *
984,556
295ef8bd0669431584f5b9a94b3da22c680ed3ad
"""employees table Revision ID: 4bb68bfb6dfe Revises: Create Date: 2019-07-26 20:11:12.082336 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '4bb68bfb6dfe' down_revision = None branch_labels = None depends_on = None def ...
984,557
13c283333a4f0ca335d28b6ac452ba1abd7d411c
import ast from collections import Counter import random import numpy as np import pandas as pd from typing import List, Tuple, Dict, Any from lib.mr import MetamorphicTransformation import lib.metamorph as metamorph from lib.qfl import detect_divergence class QdiffG3XToHSSH(MetamorphicTransformation): def che...
984,558
fbd0f9c979db219adb7933da6fbf7def706b5c25
import random from words import words import string def get_valid_word(words): word = random.choice(words) #randomly chooses something from the list while '-' in word or ' ' in word: word = random.choice(words) return word.upper() def hangman(): word = get_valid_word(words) w...
984,559
867a3b397a1c4e6636455a7c9ccb8c00ae93af1a
"""Package metadata validation.""" import tomllib from homeassistant.const import REQUIRED_PYTHON_VER, __version__ from .model import Config, Integration def validate(integrations: dict[str, Integration], config: Config) -> None: """Validate project metadata keys.""" metadata_path = config.root / "pyproject...
984,560
50cd506a134c9f621cbe4b4379386c0f3baed6c5
from maggma.api.query_operator.dynamic import NumericQuery from maggma.api.resource import ReadOnlyResource from emmet.core.electrode import ConversionElectrodeDoc from emmet.api.core.global_header import GlobalHeaderProcessor from maggma.api.query_operator import PaginationQuery, SortQuery, SparseFieldsQuery from emm...
984,561
361fa6ecf48a30682517a11c48b6c9a8df5f464e
import numpy as np import pandas as pd import pickle from scipy.sparse import csr_matrix from sklearn.pipeline import Pipeline from .db_service import DbService from txtools.normalizer import TextNormalizer from txtools.similarity import Similarity class Model(DbService): def __init__(self, db_user: str, db_pa...
984,562
d09971fcce4053c58e7e313c8fd28d847242f64b
from collections import deque print("-------Queue----------") # FIFO principle q = deque() q.append('1st element') q.append('2nd Element') q.append('3rd Elements') print(q, '\n') a = q.popleft() print("The first popped elements is: ", a) b = q.popleft() print('The second popped elements is:', b) c = q.popleft() pr...
984,563
6813858e3036303e01bacf805bcb43bd630e56c4
def index_equals_value_search(arr): i = 0 j = len(arr) - 1 while i <= j: mid = int(i + (j - i) / 2) if arr[mid] == mid: return mid if arr[mid] > mid: j = mid - 1 else: i = mid + 1 return -1 # for i, a in enumerate(arr): # i...
984,564
1ee3c86ea5a125e0b725e28e5121042126d4e49a
import argparse import logging import math import sys from pathlib import Path import pandas as pd import yaml from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap def plot_nodes(df, nodes=None, states=None, ncol=3, sharey=False, figsize=None, cmap=None): """ Plots a grid of plo...
984,565
95793bc9b4d97241b152854372ceb809aabbb57a
#!/usr/bin/env python3 import subprocess as sp import numpy as np from PIL import Image from led import * # LED_TOP_COUNT = 32 LED_LEFT_COUNT = 18 LED_RIGHT_COUNT = 18 LED_BOTTOM_LEFT = 16 LED_BOTTOM_RIGHT = 16 # LED_BOTTOM_COUNT = LED_BOTTOM_LEFT + LED_BOTTOM_RIGHT TOTAL_PIXEL_COUNT = LED_TOP_COUNT + LED_LEFT_COUN...
984,566
4b2146e19d37a06d03477e5294ad28677d56a953
# !/usr/bin/env python3 # libraries import argparse import json #from random import Random import random import os import requests from enum import Enum from typing import List, Tuple, Dict, Union from string import Template as Tmpl from dataclasses import dataclass from copy import deepcopy # handling arguments par...
984,567
738131c4ce14c7c1126ac4cb3519d4af8c126403
def grd_ship(weight,flat=20): if weight <=2: return (1.50*weight)+flat elif weight > 2 and weight < 6: return (3.00*weight)+flat elif weight > 6 and weight < 10: return (4.00*weight)+flat elif weight == 'prm': return 125 else: return (4.75*weight)+flat #drone shipping costs def drn_ship(w...
984,568
fbec6ac2c1cec0843a54424c47853bf181a3162f
import json a = json.loads('{"books":[{"book_name":"string","progress":0,"total":0,"tip":"string"}],"user":"string"}') print(a)
984,569
b9f058a42d06fed8558e60df83965dc3c7f950d5
from django.shortcuts import render, redirect from django.urls import reverse from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from accounts.forms import ( RegistrationForm, EditProfileForm, UserProfileForm, ) from django.contrib.auth.decorators import permission_...
984,570
67149280a2467c961c109971c6aac8e87d8e7d91
# -*- coding: utf-8 -*- # @Time : 2020/12/6 18:38 # @Author : pengketong from time import sleep from appium.webdriver.common.mobileby import MobileBy from learn_python.work_appium.weixin_PO.page.app import App from learn_python.work_appium.weixin_PO.page.searcher_contact_result import SearcherContactResult clas...
984,571
98794529bdd0e96284f3fc46288c4519ce550f89
# -*- coding: utf-8 -*- """ @Time : 2018/2/5 17:05 @Author : Sunflower @FileName: 136. Single Number.py @Software: PyCharm @Blog :http://blog.csdn.net/sunflower_kris/article/ """ """ Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm sh...
984,572
5650cf18bf2c8ba8f5c858623ef141f5fd61621d
import json from sqlalchemy import create_engine from sqlalchemy.exc import InternalError from sqlalchemy.exc import IntegrityError import glob import re import csv import os from pathlib import Path import pandas as pd # Change the paths and sql_server.cfg to adjust this code. cfg_path = './WeatherForecast/sql_server...
984,573
ae835dffbdff9c98f78ff956ab0b7d99a267957b
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
984,574
4a90ae1b3df5b79ef329fbd9fa34e8bb440900fc
from django.urls import path from . import views # path(route, view[, kwargs, name]) # route is string that contains URL pattern. doesn't search GET/POST params ie mysite.com/polls/?page=3 # view calls the function from views.py with an HttpRequest object and any values from the route # name allows referencing # name...
984,575
2cb3e54962db55c56e02beb490712781ab5af927
import pytest import pandas as pd import numpy as np import pyarrow as pa from ray.air.constants import TENSOR_COLUMN_NAME from ray.air.util.data_batch_conversion import convert_batch_type_to_pandas from ray.air.util.data_batch_conversion import convert_pandas_to_batch_type from ray.air.util.data_batch_conversion imp...
984,576
2dc3596d8bd5e720e01035d190cd25fd4df40141
from create_headers import * import handle_users import socket status_to_path = { 400 : '400.html', 401 : '401.html', 405 : '405.html', 500 : '500.html' } def handle_error(user, status, connection_socket, metadata, stamp, request_parsed_data = '') : if not request_parsed_data : user.accept_...
984,577
440b9ed4d02994cd79caa747eb11d2b246b71d24
import datetime import io import pytest import attr from unittest import mock from django.utils import timezone from django.core.management import call_command from h1.models import Report as H1Report from .test_models import new_report from ..models import SingletonMetadata, Report is_datetime = attr.validators.ins...
984,578
38c029d9dc2c745843ecfa39a7b3fb2d05a405af
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-11-23 21:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('directorio', '0003_auto_20171121_1414'), ] operations = [ migrations.Remove...
984,579
a43cbbc59ba5919553ccff1495d7ce70aa069134
# coding=utf-8 import os import os.path import sys from ast import literal_eval import locale as Locale import ipAddress """Game config.""" class Config(object): """Class for storing config""" """Game title:""" title = "Chivy" """Game version:""" version = "0.6" """Configuration, that should...
984,580
cefcb324a9ae51657dbcf36a49fbd2745430cb9b
# Copyright 2019, Rigetti Computing # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import os from abc import ABCMeta, abstractmethod from itertools import product from typing import Callable import gym import gym.spaces...
984,581
bd8babdd16d82ac15dad352527fe06b676fed9f9
import os.path import urllib.request as req import pandas as pd from sklearn import svm, metrics from sklearn.model_selection import train_test_split # urlopen()으로 데이터 수집 url = "https://raw.githubusercontent.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv" file = 'iris2' if not os.path.exists('iris2...
984,582
8325b95ae623067a94790437d8159a0f9a6e02f3
import cv2 import numpy as np from annotate.mask import Mask from image_handlers import ImageHandler class CannyEdgeDetector(ImageHandler): def apply(self, image_np): edges = cv2.Canny(cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY), 100, 200) ret, thresh = cv2.threshold(edges, 127, 255, cv2.THRESH_B...
984,583
1b8d19efe8d76949d61cff2b60e7aace9c858cfd
from tkinter import * from tkinter import ttk from views.programacion_lineal import * from views.ruta_critica import * from tkinter import messagebox from views.index import * if __name__ == "__main__": principal=Tk() ancho_programa=816 alto_programa=490 ancho_pantalla=principal.winfo_screenwidth() ...
984,584
00c55e7ef8e37bca0e2cd6406e5d144f7630be78
#!/usr/bin/python # -*- coding: utf-8 -*- from naoqi import ALProxy from naoconfig import * import math proxyMo = ALProxy('ALMotion',robot_IP,robot_port) proxySonar = ALProxy("ALSonar",robot_IP,robot_port) proxySonar.subscribe("my_sonar") proxyMem = ALProxy("ALMemory",robot_IP,robot_port) def servo_off(): global p...
984,585
9fbe4192d7b5cdd501b6f45b9acafedf02570cba
import os from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, sent_tokenize import re import email replace_no_space = re.compile('(\.)|(;)|(:)|(!)|(\')|(\?)|(,)|(\")|(\()|(\))|(\[)|(])|(>)|(<)') replace_with_space = re.compile('(-)|(\t)') english_stop_words = stopwords.words('english') # Token...
984,586
a760f2eb48471d6e3890451e7c339f5e45ff73e2
from scripts.common import * from scripts import module_generator from scripts import plugin_generator ENGINE_VERSION = "4.23" def get_uproject_source(name, modules): # todo expose engine version into settings uproject_source = ('{\n' + ' "FileVersion": 3,\n' + ' ...
984,587
ab7bafb0426458063afef4325a12303d6eddbc0c
""" Data generators for loading training, validation and test data sets """ import numpy as np from keras.utils import Sequence, to_categorical from datetime import datetime class DataGenerator(Sequence): """ Data Generator to load training, validation and test batches """ def __init__(self, trip_dat...
984,588
0b0d2c5587d9a33f34ca715545457cb591e90164
import csv from datetime import datetime from collections import OrderedDict import collections from operator import itemgetter class DataFrame(object): @classmethod def from_csv(cls, file_path, delimiting_character=',', quote_character='"'): with open(file_path, 'rU') as infile: reader = ...
984,589
7fc7a9669651f469c820937b5e2ce1ce99d195aa
#https://stackoverflow.com/questions/25149892/how-to-get-the-width-of-text-using-pygame #https://stackoverflow.com/questions/6339057/draw-a-transparent-rectangle-in-pygame #https://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes#25176504 import pygame, sys, math, c...
984,590
802b1fc5d3f71775f1732a7b3e8f59a346766fea
""" Double priority queue implementation that keeps an arbitrary number of largest and smallest members Author: Julian Ding """ class DoublePriority: def __init__(self, num_smallest, num_largest, dtype=tuple): assert(dtype in [tuple, bool, int, float]) self.dtype = dtype self.num_smallest ...
984,591
e549e9a6183d56400298c7e2db4faf0b76717409
import json import re from urllib import request from bs4 import BeautifulSoup def get_challenge(row): title = row.find('a').get_text() year, name = re.search(r'(\d{1,2}): (.*)', title).groups() cells = [td.get_text().strip() for td in row.select('td table td')] ocd = cells[::2] best_known = cells...
984,592
cff2af2e99488cb79a4d308f7a09afecfefc6b7b
# coding: utf-8 import os CSRF_ENABLED = True SECRET_KEY = 'ksdlldsfnjkdw8er^(&&*@*jdsav2329sadl1' basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'mysql://root:5tgbfghG%@localhost/insta' #5tgbfghG% SQLALCHEMY_TRACK_MODIFICATIONS=True SMTP_USER = 'test@funinsta.ru'#'khigor777@mail.ru' ...
984,593
d5338bd284fe64f03210d8e2f7ca3606c9b64897
# ----------------------------------------------------------------------- # author: Huang Jintao # date: 2020-5-10 # # 该文件功能: # 1. 空间单车使用活度图(abs(in)+abs(out)) # 2. 空间单车使用活度图画网格(为调度时使用) # ----------------------------------------------------------------------- import matplotlib.pyplot as plt import numpy as np import pan...
984,594
998663debd955e7df2270f0793d0bbfb3fa06087
from __future__ import absolute_import from __future__ import print_function from __future__ import division import os import functools import math import tempfile from collections import defaultdict import veriloggen.core.vtypes as vtypes from veriloggen.seq.seq import Seq from veriloggen.fsm.fsm import FSM from ver...
984,595
6fbc1d6bb84c2488e398baa41256757595c389cd
import os # 窗口大小及背景颜色 screen_size = (680, 453) bg_color = (245,212,217) black = (0, 0, 0) skyblue = (135, 206, 235) darkgray = (169, 169, 169) gainsboro = (230, 230, 230) # 背景音乐路径 bgm_path = os.path.join(os.getcwd(), 'music\\bgm.mp3') print(bgm_path) # 字体路径 font_path = os.path.join(os.getcwd(), 'font\\stxingka.ttf')...
984,596
90ab44dd03a6c34d1f57f8c62dc921129d59b844
# Declares some simple test functions def py_func1(str, n): res = 0 for i in range(n): res = res + ord(str[i:i+1]) return res def py_func2(input): return not input
984,597
17c596807b2ba5bfe3cec077566c867e6e20556f
def shortestPath(ar,previndex=0,i=0): m = i+1 if len(ar)==0: return 0 if(i>= len(ar)): return 0 if(i==0): return ar[i][0] + shortestPath(ar,0,1) if(previndex == 0 ): result = min(ar[i][0],ar[i][1]) index = ar[i].index(result) return res...
984,598
4290ccdf9a2c62bf487d57465cb6f4a2567a5d12
#!/usr/bin/python import csv import sqlite3 import glob import os def Check_directory(dirname, db): for filename in glob.glob(os.path.join(dirname, '*.csv')): Check_file(filename, db) def Check_file(filename, db): with open(filename) as f: with db: data = csv.DictReader...
984,599
4c159d56b88dee61e822f97db7422e28c1d74052
def fib(): l = [1,1] while len(l) <= 100: l.append (l[-2]+l[-1]) return l