index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
1,300
753bdbf080e7a8652c39e40beeae51f74382d606
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `feat` package.""" from feat.detector import Detector from feat.data import Fex from feat.utils import get_resource_path from .utils import get_test_data_path import pandas as pd import feat import os import wget # def test_models(): # print("Downloading...
1,301
1e24952006afebb7bf10a83077fc4effd5cc9c58
#Sample Python Code print("Different Code!!!") #print("Hello World!")
1,302
fc26574ac8628d7e2896e3e6d055ac61264c7db0
import sys import pathlib from matplotlib import pyplot as plt import matplotlib as mpl script_name = pathlib.Path(sys.argv[0]).stem FIGURES_DIR = pathlib.Path( __file__).parents[2] / "figures" / "simulations" / script_name FIGURES_DIR.mkdir(exist_ok=True, parents=True) # mpl.rc("text", usetex=True) # mpl.rc("fo...
1,303
8ddb7abb480ea8ee674c59719c0946f133ef0a4b
from PyQt5.QtWidgets import QPushButton,QWidget,QApplication,QGridLayout,QListWidget,QLineEdit,QVBoxLayout,QLabel import pyqtgraph as pg import sys import numpy as np from tools import DataModel,HoldPositions from load_sina import LoadNet import time from get_day_histroy import history import pandas as pd from volume ...
1,304
c3de6cd76ca7180a1a4d236bb2a6a18f7594f38b
import sys numList = list(range(3)) for i in range(3): numList[i] = int(sys.stdin.readline()) result = numList[0] * numList[1] * numList[2] resultList = list(str(result)) intList = list(range(10)) for i in intList: print(resultList.count(str(i)))
1,305
8d8ea6ad7a3ed1a1e6e96ab75260ecf6e8211d32
#!/usr/bin/env python """ Script to download and plot RaspberryShake station data Also computes and plots theoretical phase arrival times and raypaths. See https://docs.obspy.org/packages/obspy.taup.html for more info on Earth models and phase-nmaing nomenclature. Stephen Hicks Imperial College London Feb 2020 """ ...
1,306
85c2a4163a3132794186b95b4068f6c6e1104828
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-27 21:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cms', '0020_old_tree_cleanup'), ('styleguide', '00...
1,307
38f9cddfde4787ead2314fc70c1f4d91a3da9687
# -*- coding: utf-8 -*- """Template parser for Faker""" from datetime import datetime from jinja2 import Template from faker import Faker from faker.providers.internet import Provider as InternetProvider from ..providers.file_data_source_provider import FileDataSourceProvider from ..providers.numbers_provider import Nu...
1,308
13da16ba89e4743b12d9b8e24929864747f8bbf2
from soppa.contrib import * class ModD(Soppa): needs = ['test_project.modf'] something = 1
1,309
3eb071fa826c838d847e3f97abe3b706760a1336
''' Faraday Penetration Test IDE Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/) See the file 'doc/LICENSE' for the license information ''' """ This module contains some useful functions to embedd an IPython shell. This allows to interactively test things. TODO: create a QT Widget capable of running the...
1,310
723d8819b5341f1397163533f59c17ba1a74b77d
""" get poly data(face center, face id, etc), select face, create object by face data setPosition for vertex (random) import sys module_path = '/home/shrimo/Desktop/course/git/vfx_dev/maya/general_lesson' if module_path not in sys.path: sys.path.append(module_path) import lesson_v01 reload(lesson_v01) lesson...
1,311
325efe65030ad3488a7fc45c0d4a289eb0b17196
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import datetime import json import logging import mock from parameterized import parameterized from buildbucket_proto import common_pb2 from buildbucket_pr...
1,312
aec311cae7cb6cbe3e3a927a133ec20a2d2afbf5
class Solution: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] result_set=[] letters={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} def permuta...
1,313
2dbb1051b35898288db629fd0c5b3887c429e9b8
## @file # Contains several utilitities shared by migration tools. # # Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full...
1,314
645f8f1ebd3bfa0ba32d5be8058b07e2a30ba9b5
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-10-02 14:41 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('barriers', '0011_auto_20170904_1658'), ...
1,315
a34584a71fdff65e5b1bb15a6304af79774dac2c
# # Copyright (C) 2017 Red Hat, 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 obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
1,316
a288e66e64d386afd13bfc7b5b13d4a47d15cd6d
# created by RomaOkorosso at 21.03.2021 # models.py from datetime import datetime from sqlalchemy import ( Column, Integer, String, Boolean, DateTime, ForeignKey, Date ) from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship from Database.database import Base ...
1,317
2ec41e02c95a270455c096e85829b7220eeda0c7
import xlrd from django.shortcuts import redirect from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.core import validators from utils.views import render_to from accounts.models import Account from .models import ExternalSubscriber from .forms import ExternalSubsc...
1,318
b42414b7d8ed80d8794ab7c49dfde1e5df0721f1
""" Django settings for gamelibrary project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import o...
1,319
449ae193f8817d4ee2fe67eadf72d9c19b2c5e53
# -*- coding: utf-8 -*- from __future__ import unicode_literals import markdown from django.db import models from django.contrib.auth.models import User from datetime import datetime class MovieRankings(models.Model): """ 各种电影排行榜. """ name = models.CharField(max_length=100) def __unicode__(self)...
1,320
902159d9ad3a1e36b69142518007b5d4bcaef0f3
from arcgis.geocoding import geocode from arcgis.gis import GIS import pandas as pd import Point_v1 """ This module is used to get the location information of different companies from arcgis API. """ def crawl(file): gis = GIS() map = gis.map("United States") map # read all kinds of job files jo...
1,321
bad13218a7a9e687fbd29099ca80771296789d36
import sys from PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton,QVBoxLayout, QLabel, QWidget from docx import Document from docx.shared import Inches class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) #set the size #Creat widgets...
1,322
029f4f015f558dbd4d6096b00c53f5f0fe69883d
from rest_framework import serializers from core.models import Curriculo class CurriculoSerializer(serializers.ModelSerializer): class Meta: model = Curriculo fields = ('id','name', 'description','image','create_at','update_at')
1,323
8e1eef3c5a9ca3ea504bbc269b48446527637626
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import swapper from haystack.constants import Indexable from haystack.fields import CharField, DateTimeField from haystack.indexes import SearchIndex class BasePageIndex(SearchIndex): text = CharField(document=True, use_template=True...
1,324
11ed7550c25ca9944ce7073d9655cb9af7bdeae9
from Distributions import UniformDistribution from EventGenerator import Generator from Processor import Processor class Modeller: def __init__(self, generator, operators, computers): self._generator = generator self._operators = operators self._computers = computers def event_mode...
1,325
d9a871fb6c889bcff455732007718af734859c72
# SSURGO_ExportMuRaster.py # # Convert MUPOLYGON featureclass to raster for the specified SSURGO geodatabase. # By default any small NoData areas (< 5000 sq meters) will be filled using # the Majority value. # # Input mupolygon featureclass must have a projected coordinate system or it will skip. # Input databas...
1,326
1b58d294f02ce85bf19da03f94100af87408081d
import stockquote import time import datetime from datetime import date from connection import db start_date='20100101' def prices(symbol): """ Loads the prices from the start date for the given symbol Only new quotes are downloaded. """ to = date.today().strftime("%Y%m%d") c = db.cursor() c.execute("SEL...
1,327
5d0a45b93bd7972333f5574188c65484c065e9cf
''' Created on June 10 2013 @author: Eugene Shim This unit test suite is designed to test the unitTestParser module. At the moment, the functions of that module are too simple to really unit test effectively ''' #Standard library modules import unittest #the module being tested import unitTest...
1,328
95ea811d38c314f5f19294500e16bae3d00d4fff
import sys import numpy as np import bpcs as bp from PIL import Image if len(sys.argv)<4: print("USAGE: {0} <PATH> <COLOR> <BIT>".format(sys.argv[0])) print(" PATH: image path") print(" COLOR: GRAY=-1, RED=0, GREEN=1, BLUE=2") print(" BIT : 0~7 (0:MSB, 7:LSB)") exit(1) PATH = sys...
1,329
60411e922bfec8f98028f959a370f954eef5437e
import re import itertools import setpath import functions import lib.jopts as jopts from operator import itemgetter import random __docformat__ = 'reStructuredText en' re_params=re.compile('(\w*):(.*)') def consumer(func): """A decorator, advances func to its first yield point when called. """ from fun...
1,330
df6fa0409500f97e5afde8f97796d6ed0cc4d746
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 26 23:42:11 2018 @author: pohsuanh Fully Covolutional Network FCN-32s. FCN-32s network is based on VGG-16 """ import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import data_load from datetime import datetime ...
1,331
20d09a616133295a6162a7ab1d7970ccbaf6de95
import pickle import torch data = pickle.load(open('dd0eb7901523d494d4aa324f474c782063e9e231.p', 'rb')) torch.nn.functional.adaptive_avg_pool3d(**data)
1,332
f69b4d022ebed5a0b660f55704bbe762d5d765d5
''' Given an expression with numbers, brackets and operators. But in this task only brackets are important. Brackets can be one of three types -- "{}" "()" "[]". Brackets are determine the scope or restricted some expression. So each if was opened, then must be closed with the same type. The scopes of brackets must not...
1,333
97a51d959ad642467c508cedc8786f636e4050bb
"""Test cases for the __main__ module.""" import pytest from click.testing import CliRunner from skimpy import __main__ from skimpy import generate_test_data from skimpy import skim @pytest.fixture def runner() -> CliRunner: """Fixture for invoking command-line interfaces.""" return CliRunner() def test_ma...
1,334
005650e2747c61b730960a29891b6ba6c8bd381b
# coding: utf-8 import os, sys import numpy as np from math import exp, sqrt, pi def factorial(n): value = 1 for i in range(n,1,-1): value *= i return value def double_factorial(n): k = 1 for i in range(n, 1, -2): k *= i #print("n:", n, "double factorial:", k) return k ...
1,335
26f466a6a2fd09bb108ca89e4537192c070ff83b
c = "こ に ち わ " print (len(c))
1,336
8c0a4d5a86d9ebd38ea05efb5b5b570368ce1449
#!/usr/bin/env python3 # Licensed under the Apache License, Version 2.0 or the MIT License. # SPDX-License-Identifier: Apache-2.0 OR MIT # Copyright Tock Contributors 2023. # Prints out the source locations of panics in a Tock kernel ELF # # This tool attempts to trace all panic locations in a Tock kernel ELF by # tr...
1,337
9b8db3407313a3e39d429b7c10897fc447fcdc27
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if not board or not board[0]: return not word self.length = len(word) def hasPathCore(row, col, depth=0): if self.length...
1,338
01ede703e36268dc9b3331b21726c24674a43817
lista = [] z = 0 j = 9 for i in range(0, 10): lista.append(int(input())) while z < j: c = lista[z] lista[z] = lista[j] lista[j] = c z += 1 j -= 1 print(lista)
1,339
2c960685eaa14861c1c5b3ddb38b366a3e0e8e86
#!/usr/bin/evn python #-*-coding:utf8 -*- import os, sys, json class settings(object): filename = '' config = {} def __init__(self): self.DEBUG = os.environ.get('RdsMonitor_DEBUG', 0) def get_settings(self): """Parses the settings from redis-live.conf. """ # TODO: Consider YAML. Human writable, mac...
1,340
5b33615e1890631bac68801310e4b606ac41cb13
# Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # This file is part of Neo4j. # # 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 # # https://www.apache.org/licenses/LICENSE-2...
1,341
33867677611ceb757f6973eb70368c9f75f3ce92
# system import os import numpy as np import random import copy import time # ROS import rospy import std_msgs.msg import sensor_msgs.msg import geometry_msgs.msg import visualization_msgs.msg import tf2_ros import rosbag import actionlib from actionlib_msgs.msg import GoalStatus import ros_numpy # spartan ROS import...
1,342
b59dfd97a2b52ddef4e37557ea96bff9edf34989
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2020, Yutong Xie, UIUC. Using recursion to construct binary tree from postorder and inorder traversal ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val ...
1,343
22afc6b9df87ef1eba284da20a807366278c24d4
#!/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 from ipywidgets import (Text, VBox, HBox, Label, Password...
1,344
83ce5ee4d2a18caeb364b74c3739015fc0e1474c
#!/usr/bin/env python import rospy import numpy as np from sensor_msgs.msg import Image import cv2, cv_bridge from geometry_msgs.msg import Twist, Pose2D from std_msgs.msg import String import pytesseract as ocr from PIL import Image as imagePil import os import time from roseli.srv import CreateMap, CreateMapRequest ...
1,345
0b2fd671b99b7012a14b132db2322318873b826c
''' Exercício 1: Estenda a classe Stack , que escrevemos durante as explicações do conteúdo, adicionando uma nova função chamada min_value() que irá retornar o menor valor inteiro presente na pilha. ''' from stack import Stack class Other_Operations_Stack(Stack): def min_value(self): min_value = self.pee...
1,346
68c2fd1d8ca9e1dd9373ca9f641c2920c87b2392
# helper functions to handle intcode from collections import defaultdict def read_code(string): """ string should be a comma-separated string. """ code = defaultdict(int) for i, x in enumerate(string.split(',')): code[i] = int(x) return code def to_ascii(line): """ Writes a ...
1,347
b7ebee3c96fd9cd3d8ddc69838363925085a944d
''' Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] ''' #卡了很久,还是列表的基本操作不太熟 #参考:https://zhidao.baidu.com/question/1244520812319200859.html def r...
1,348
51ef1c0f6a17e12b2324a80f962b2ce47cc05bcc
def _get_single_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=True, collections=None, caching_device=None, validate_shape=True, use_resource=None): 'Get or create a single Variable (e.g. a shard or entire variable).\n\n See t...
1,349
26a778f16cc50d1a8791fb672fb8907464865f3f
n = 5 a = '1' if n == 1: print(a) else: for i in range(2, n + 1): if i == 2: a = '11' else: count = 1 for j in range(len(a) - 1): if j == len(a) - 2 : if a[j] == a[j + 1]: count += 1 ...
1,350
ab12468b1da20c896e3578091fd9ba245dcfa0a4
# Generated by Django 3.0.4 on 2020-03-11 17:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20200310_1620'), ] operations = [ migrations.AddField( model_name='tag', name='name', ...
1,351
6e253747182716f84aa6326aafe15ff82be17378
import os import sys import time import json import socket from urllib import request, parse from concurrent.futures import ThreadPoolExecutor from multiprocessing import Process import psutil from daemon import DaemonBase from host_performence import * class MyDaemon(DaemonBase): """Real Daemon class""" d...
1,352
603708c830dadb6f1a3e5de00536d558f448b5fb
import requests from requests.adapters import HTTPAdapter from requests.exceptions import ConnectionError, Timeout, RequestException # import from `requests` because Jarvis / some platforms still have old urllib3 from requests.packages.urllib3.util.retry import Retry def retryable_session(retries=3, backoff_factor=0.5...
1,353
b8ab6b8c111876d6a781c82438f79307a849c47a
# -*- coding: utf-8 -*- import requests import Queue import codecs import os import urllib import base64 from threading import Thread from Crypto.Cipher import AES requests.packages.urllib3.disable_warnings() def check(q): while True: try: c = q.get() user = c.split(':')[0] ...
1,354
3ac13cc74a7eabef686ceb9d9e46f2ef109a225e
#!/usr/bin/env python # -*-coding:utf-8 -*- from common import http_requests_get,is_domain import re class Crt(object): def __init__(self, domain): self.domain=domain self.site='http://crt.sh/?q=%25.' self.result=[] def run(self): url = self.site + self.domain print u...
1,355
af4d2380f92ea636594695e5ad4ba766d6874dd3
# -*- coding: utf-8 -*- from fw.api import dadata_proxy from flask import current_app from fw.cache.cache_wrapper import CacheWrapper cache = CacheWrapper() def dadata_suggest(method, data): return dadata_proxy.dadata_suggest(method, data) def dadata_clean(method, data): return dadata_proxy.dadata_clean(...
1,356
a8ae59bb525c52ef852655f0ef1e32d96c8914d6
# -*- coding: utf-8 -*- # @Time : 2019/3/5 上午9:55 # @Author : yidxue from src.handler.base.base_handler import BaseHandler from src.utils.tools import read_model from tornado.options import options import os module_path = os.path.abspath(os.path.join(os.curdir)) model_path = os.path.join(module_path, 'model') cl...
1,357
9ed674513bebe65ece538e9ce2b3945bb0c532cc
import pyttsx3 import pyglet import time import logging import os from gtts import gTTS ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) class GoogleTTS: def utter_voice_message(self, message): try: # Google Text-to-Speech API - needs internet connectivity #filename = ROOT_D...
1,358
3496216de9f6b7d9d3db69eb4d8f8c0fdcd5123c
import operator import theano.tensor as T from collections import OrderedDict from lasagne.layers import get_output from stanza.research import config from neural import SimpleLasagneModel, NeuralLearner from vectorizers import SequenceVectorizer, BucketsVectorizer from neural import OPTIMIZERS, get_named_layers from ...
1,359
d30e2fa4d5b0a0965dad7d69b672b8f4ad137ff4
#!/usr/bin/python # -*- coding: utf-8 -*- import os import os.path import json from collections import defaultdict, Counter MOST_COMMON = 120000 savepath = r'D:\My Documents\My Project\experiment1\finished\test_vocabs.json' dirpath = 'D:\\My Documents\\My Project\\experiment1\\finished\\test' #dirpath = 'D:\\Corpus\...
1,360
16879598a8b1a0b23c5ea6de18f8fb0b0b77201c
from functools import reduce import confuse config = confuse.Configuration('SleepCycleWebhooks') config.set_file('config.yaml') def get(path): return reduce(lambda view, part: view[part], path.split('.'), config).get()
1,361
267695555e876dc2fe5820dc194490aad9e5e344
#library import pandas as pd import numpy as np import sys from tqdm import tqdm # appear the precess of running situation. import time from scipy.spatial.distance import pdist, squareform #0. Data Load data = pd.read_csv(sys.argv[1], delimiter='\t') # Load train (input text file) #1. Data Preprocessing all_element...
1,362
61f2fbed184ff6f842ba9527456da453844f8dc6
# DATA TYPES (DATA TİPLERİ) # STRİNGS (KARAKTER DİZİNLERİ) # Bir karakter dizinini tanımlamak için tırnaklar kullanılır. birkaç satır ka- # rakter dizini yazıyorsak 3 tırnak kullanılır: print("""Üç tırnaklı karakter dizinine örnek""") üç tırnaklı karakter dizinine örnek print('Tek tırnak: Tek satırlık...
1,363
2b87b8571664989e78790bd9df23eee9cbd44035
# @Time : 2019/12/12 15:54 # @Author : Libuda # @FileName: 远程服务器文件监控.py # @Software: PyCharm import itchat @itchat.msg_register(itchat.content.TEXT) def text_reply(msg): return msg.text itchat.auto_login() itchat.run()
1,364
9c3f6c368c764918da5cce44da574b7c041fa414
class Node: """ This class represent a node (vertex). """ def __init__(self, k: int = None, loc: tuple = None, **kwargs): """ Each node contain dew fields: key: node_id. location: node's position represent as 3DPoint. ni_out: a dictionary that holds all the "edge...
1,365
21d261dec6668a24030f37b7dcb87c0132e63528
from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from mysite.core.forms import SignUpForm,UserProfileForm from django.views.generic import UpdateView from .models import Profile from django.contrib.auth.mixins im...
1,366
c8565e1b5659dd0908aabf91e07738a798dc3232
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:-1].values y = dataset.iloc[:, dataset.shape[1]-1].values #Fitting the Decision Tree Regression from sklearn.tree import DecisionTreeRegressor regressor = DecisionTreeRegressor(r...
1,367
53cd9d5a79e97bb1af69446a82c747248c3cc298
""" Copyright (c) 2007 by the Pallets team. Some 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 above copyright notice, this list of conditions and the f...
1,368
ee5e970f32b1d601f9dc3ab37a5028ce7ff8a32e
# message 为定义的变量 message = 'Hello Python World ' print(message)
1,369
8d1067a9bb0629276ef27de91f63cf2370a44e24
from abc import ABCMeta, abstractmethod __author__ = 'Alexiy' class Protocol: """base protocol class""" __metaclass__ = ABCMeta FAIL = 'Failed' @abstractmethod def execute(self, command): """"execute command method""" class LocalProtocol(Protocol): """simple protocol for using bot...
1,370
1ffdc2845bc503c0a30407de444a152f8cc68d57
import os my_home = os.popen("echo $MYWORK_DIR").readlines()[0][:-1] import numpy from sys import path, argv path.append("D:/Github/astrophy-research/mylib") path.append("D:/Github/astrophy-research/multi_shear_detect") path.append('%s/work/mylib' % my_home) from Fourier_Quad import Fourier_Quad # import h5py # from pl...
1,371
7e5cf782692d9cfb2718b2efcc83efa2ecb815cd
""" Package: pgnumpy Description A class and a set of functions for interacting with a PostgreSql database. A C++ extension module allows returning results as a NumPy array. Numpy arrays can also be written to tables. The workhorse class is called PgNumpy This class has limited functio...
1,372
34f98d4a6a15c9a7b42f237cab204b736dc97136
{ # Theme information 'name' : 'Clarico CMS Blocks', 'category' : 'Website', 'version' : '1.0', 'summary': '13 CMS Building Blocks', 'description': """""", # Dependencies 'depends': [ 'snippet_style_1', 'snippet_style_2', 'snippet_style_3', 'snippet_style_4'...
1,373
c27c2df1830f066ca4f973c46967722869090d05
import tensorflow as tf class Config(object): # Source and Target files from_train_file='data/dev.en' to_train_file='data/dev.vi' # Special characters and ID's _PAD = b"_PAD" _GO = b"_GO" _EOS = b"_EOS" _UNK = b"_UNK" _START_VOCAB = [_PAD, _GO, _EOS, _UNK] PAD_ID = 0 GO_I...
1,374
153e7e66e2b796d011b78aed102d30e37bb0b80f
import gym from ddpg import DDPG def main(): #env = gym.make('LunarLanderContinuous-v2') #log_dir = 'log/lander' env = gym.make('Pendulum-v0') log_dir = 'log/pendulum' # paper settings # agent = DDPG(env, sigma=0.2, num_episodes=1000, buffer_size=1000000, batch_size=64, # ...
1,375
917a291c7b62dee392d7411c3e039949d74d7af8
# ------------------------------------------------------------------------------------------------------ # Copyright (c) Leo Hanisch. All rights reserved. # Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information. # ---------------------------------------------------------...
1,376
6455741bbda42b9d84428545ddd50a5d1b54a7ba
import tkinter from tkinter import ttk, filedialog, messagebox import serial.tools.list_ports from PIL import ImageTk, Image from read_bytes import read root = tkinter.Tk() root.title('ChadBotX') # Define constants for mode selection MODE_RECORD = 1 MODE_PLAYBACK = 2 # Define gui state portname = tkinter.StringVar(r...
1,377
e280b003c95681ed4a887b0939077efeac9deefe
import numpy as np from Ejercicio1 import norma_l2 def sorting_l2(mat): mat_l2 = norma_l2(mat) mat_sort_index = np.argsort(mat_l2) mat_sort_l2 = mat[mat_sort_index,:] return mat_sort_l2[::-1]
1,378
7aba77137b96071101078c38c1c9397bf837d92a
a = [66.25, 333, 333, 1, 1234.5] a.index(333) print(a)
1,379
a2e77298059104b403555af95430d7995f8a697b
import flask from flask.ext.classy import FlaskView, route, request from annotator_supreme.controllers.user_controller import UserController from annotator_supreme.views import view_tools from annotator_supreme.views import error_views from flask import render_template, flash, redirect, url_for from annotator_supreme i...
1,380
f0ac2e66cc7fe9730c77a8feb77a74e26986a3f8
import pygame class MenuManager(): def __init__(self, manager): print "Menu manager created. Continue? [y/n]" self.manager = manager self.paused = False self.intro_done = False self.menus = [] self.menus.append(Pause_menu(self)) self.menus.append(St...
1,381
0659df48bb150582917e333a7a25d2d25395dfda
from face_recognition.model import Backbone import torch import numpy class face_verifier(): def __init__(self, net_depth=50, drop_ratio=0.6, net_mode="ir_se", device="cuda"): # create model self.model = Backbone(net_depth, drop_ratio, net_mode).to(device) save_path = "face_recognit...
1,382
dccdca65cce2959b07657636e23e7c9ab8a4f96c
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. 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 requ...
1,383
ebbc79d6582f7d6139e0dcec6333b679bb86c63c
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 10 ** 9 + 7 dz = zip((1,0,-1,0),(0,1,0,-1)) dp = [[0]* n for x in range(m)] ...
1,384
2da6debb1f9ae2c966a17fdfb3b668160a3ef8d7
''' #조건문 예제 #fdragon50 #2016 ''' # 주석 : 도움말/덧글 / 미사용(추후 사용가능한) 코드 기록 # 여러줄의 문자열 표현은 ''' ''' 사이에 표현 가능하나 사용은 권장않음 # #으로 시작하는것은 문자열 자체가 아닌.. 무시되는 구간 # 주석은 누가봐도 이해할수있게 / 간결하게 # 더 좋은것은 누가봐도 이해할수 있는 코드임 # 가독성이 좋은 코드를 만들수 있도록.. #조건문 예제 #fdragon50 #2016 input = 11 real_fdragon50 = 11 #real_k8805 = "ab" if real_fdr...
1,385
deb8ee1d6327a6406244147a819821e8d2b2890e
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
1,386
d64140466e62b78506d0f200f451649023697a3b
from fabric.api import local,run INSTALL_STEPS = ['yes | sudo apt-get install libmysqlclient-dev python-dev python-mysqldb python-virtualenv', 'virtualenv --no-site-packages env', '. env/bin/activate;pip install -r requirements.txt'] def deps_local(): for step in INSTALL_STEPS: ...
1,387
8356bc92a3a8b561d55bf5f2d9aeb0da89b730ca
# -*- coding: utf-8 -*- from matplotlib import pyplot as plt from matplotlib import colors import numpy as np import sys max_value = int(sys.argv[1]) file1 = open(sys.argv[2]) file2 = open(sys.argv[3]) file3 = open(sys.argv[4]) histogram = np.zeros(max_value, dtype=int).tolist() highest_value = 0.0 sample_size = 0...
1,388
aaebd9eba8a5c51c64baaf60224720b87a6364e1
#聚类算法: # kmeans # 密度聚类:DBSCAN # 层次聚类:AgglomerativeClustering # 谱聚类:SpectralClustering # 分批kmeans:MiniBatchKMeans # 评价指标:FMI(Fowlkes–Mallows index) # 排除:特征聚类:FeatureAgglomeration# 亲和传播聚类(AP)聚类:affinity_propagation# 偏移均值向量:MeanShift import numpy as np import sklearn.cluster as cluster import os impo...
1,389
eb81b0e41743e1785b82e88f6a618dc91eba73e5
#train a neural network from input video feed import numpy as np import cv2 vid = cv2.VideoCapture('trackmania_test_vid.mp4') w = 1280//2 h = 720//2 vid_data = np.empty((360, 640, 3)) #print(vid_data.shape) def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) ...
1,390
b2d3ebe4b1ce8f6f0fde8495fb90542080b810ce
""" Benchmark module: can also compare multiple functions """ import gc from inspect import ( signature, getsourcelines ) from operator import itemgetter from time import perf_counter from SpeedIT.ProjectErr import Err from SpeedIT.Utils import ( format_time, get_table_rst_formatted_lines ) def _helper_...
1,391
4e30f0a9b420123c28858aad2a71040dcc952829
import fnmatch import hashlib from .mplog import MachopLog from .utils import MachopProcess, wait_for_interrupt from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class MachopWatchCommand(MachopProcess): class MachopHandler(PatternMatchingEventHandler): """...
1,392
d19310a45a684a7bbb456555a954439df8ae92b6
import urllib.request import praw from praw import reddit from praw.models.listing.mixins import submission def download_subreddit(sub): reddit = praw.Reddit(client_id='oFOYuOd31vUb4UstBWDhnQ', client_secret='0W_86zufGFCJlSE4lK3CwF_0UEQEQw', username='MarshallBranin', ...
1,393
f5b74ca95cb368d70139b5d36e3c8d553b8c5393
#!/usr/bin/python3 max_integer = __import__('9-max_integer').max_integer my_list = [1, 90, 2, 13, 34, 5, -13, 3] my_list1 = [] my_list2 = [1, 90, 2, 13, 34, 100, -13, 3] max_value = max_integer(my_list) max_value1 = max_integer(my_list1) max_value2 = max_integer(my_list2) max_value3 = max_integer() print("Max: {}".for...
1,394
09660cfcff7d5da0339da201cb18b6f63bec2df9
# Generated by Django 3.1.6 on 2021-07-17 10:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0032_product_sex'), ] operations = [ migrations.AddField( model_name='product', name='price_ret_sale', ...
1,395
7404dd324d54bb072e56985716bbae746b4dd219
import requests import json r = requests.get('http://pythonspot.com/') jsondata = str(r.headers).replace("'", '"') print(jsondata) #headerObj = json.loads(jsondata) #ERROR >> json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 556 (char 555) #print(headerObj)["server"] #print(headerObj)['content-leng...
1,396
90f1fd45d58c7e6f275a33cd9c693ff584b2df47
#-*- coding: utf-8 -*- def print99(): """ 打印99乘法口诀表 :return: """ for i in range(1,10): for j in range(1, i+1): print('%dX%d=%2s ' %(j,i,i*j)) print('\n') print99()
1,397
1e9afe6435285da6c6efb678177587d7ba5a01b2
import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import tornado.options import serial import time from datetime import timedelta import cv2 import time from datetime import datetime #for webcam users camera=cv2.VideoCapture(0) #for picam users #import picam #camera=picam.Op...
1,398
d9b6efce92e30267a9f992c4fea698fe14e0c3e4
from __future__ import print_function from __future__ import absolute_import from __future__ import division __all__ = [ 'mesh_add_vertex_to_face_edge' ] def mesh_add_vertex_to_face_edge(mesh, key, fkey, v): """Add an existing vertex of the mesh to an existing face. Parameters ---------- mesh :...
1,399
27d9e6a868cfc18780ec9615e8dbc3b5ea2fd0c3
from flask import Flask, request, render_template, redirect import os import smtplib from email.message import EmailMessage app = Flask(__name__) EMAIL_ADDRESS = os.environ.get('EMAIL_USER') EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') @app.route('/') def index(): return render_template('index.html') @app.ro...