index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
15,900 | 6a45e98c33aa499319a06e5d4a6af2aad2e9f5d4 | """
476. Number Complement
Difficulty: Easy
Related Topic: Bit Manipulate, XOR
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could ... |
15,901 | 9fb7eda46e731951d9bd7d59b886815ec599e539 | import numpy as np
import emcee
import scipy.optimize as op
import matplotlib.pyplot as plt
import corner
import os
import scipy.stats as sstats
# local imports
import beer
def lnlike(theta, model, x, y, yerr):
""" The log likelihood function.
"""
return -np.nansum(0.5 * np.log([2 * np.pi] * len(y)))\
... |
15,902 | 8237b4491eea11cc2c05647f0115f609d6ecdeb4 | import json
import re
import scrapy
from scrapy.http import JsonRequest
from locations.dict_parser import DictParser
from locations.hours import OpeningHours, day_range
from locations.spiders.vapestore_gb import clean_address
class FoodLionUSSpider(scrapy.Spider):
name = "foodlion_us"
item_attributes = {"br... |
15,903 | 721f0fdf53d7bdf7fafefe343ee456598cd0e78c | from pylab import *
import seaborn as sns
import json
# load data
migrationEffect1 = {}
migrationEffect2 = {}
# f = open("migrationEffect","r")
# migrationEffect1 = json.loads(f.read())
# f.close()
f = open("migrationEffect4","r")
migrationEffect2 = json.loads(f.read())
f.close()
# show data
# sns.set_palette("Pair... |
15,904 | 149f44bae19ba03471c2fbacc392ae1434637b5a | #!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2015-2016,2018 Contributor
#
# 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... |
15,905 | b38634efc4da8049953a8110b954afd3516f67ef | #bernouli multinomial ou gaussiana
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import con... |
15,906 | 9f6bf5d8ca38ad4d83127931504ea37b63574055 |
import os
import sys
import glob
import json
import numpy
import pandas
import datetime
import subprocess
import matplotlib
from matplotlib import pyplot
import covid_utils as utils
def main():
### plot summary of data for USA
choice_run_us_summary = input('\nPlot data summary for USA? [y/N] ')
if cho... |
15,907 | c4d798ae99a2e628dfdf43388854fdb874ec8b47 | import random
from .postgres import Pg
from .classifiedStyle import ClassifiedStyle
from .rasterStyle import RasterStyle
from matplotlib.colors import rgb2hex
from .support import str_to_num
class StyleSld (ClassifiedStyle, RasterStyle, Pg):
"""
This is the main style class for generating the SLD files.
... |
15,908 | 08d5e94e816b03456f48b074d7d1d162a6f6a68f | from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Store, Client
from django.http import HttpResponseNotFound
from django.contrib.auth.models import User
from django.contrib impor... |
15,909 | 074f440002fbb57996f95c719b48c027f107b272 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import numpy as np
import cv2
from cv_bridge import CvBridge
from sensor_msgs.msg import Image, CompressedImage
class DetectSign():
def __init__(self):
# parameter for communication
# rospy.set_param('/tb2/mission_start', False)
... |
15,910 | fdbbd644f18849263b99dd867946f9dcf0974b4f | #!/bin/python
# -*- coding:utf-8 -*-
import os
import os.path
import MySQLdb
import time
import re
import redis
import random
r = redis.Redis(host="10.66.137.165", port = 6379, password="yeejay501")
random.seed(int(time.time()))
nums={}
for i in range(1,20):
num = random.randint(100001,999999)
nums[num] =... |
15,911 | d7199620d85a15459a44fda78c9402280e65f956 | from seg_master import UNet
import glob
import cv2
import numpy as np
from PIL import Image
src_path = "D:/2. data/total_iris/original_4/"
dst_path = "D:/2. data/total_iris/only_iris_4/"
image_paths = sorted(glob.glob(src_path + "*.png"))
images_rgb_np = []
images_bgr = []
image_names = []
size = 640, 480
for i, ima... |
15,912 | e09d449aa497fc1d0d3fc37ca29b36e70d11b1cc | def resolve():
MAX_N = 100
MAX_W = 10000
dp = [[0] * (MAX_W + 1) for _ in range(MAX_N + 1)] # メモ化テーブル
n = int(input())
w = int(input())
wv = []
for i in range(n):
wv.append(list(map(int, input().split(" "))))
# 末端からループを回す
for node in range(n - 1, -1, -1):
# 表の列のすべての... |
15,913 | db6c791fa71f82ca103b0fcc870ed79b8980320d | from django.apps import AppConfig
class CookieappConfig(AppConfig):
name = 'cookieapp'
|
15,914 | 924aea1905aa8ed3841b9e34ba2310377dd07176 | from flask import Flask, request, jsonify, make_response
import requests
import json
app = Flask(__name__)
def is_sha1(maybe_sha):
if len(maybe_sha) != 40:
return False
try:
int(maybe_sha, 16)
except:
return False
return True
# api 1
@app.route('/api/v1/users', methods=['PU... |
15,915 | e2cfc0c0b1766ed1864359efde2e6073db4b781b | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import gym
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Memory:
def __init__(self):
self.actions = []
#in our case self.inputs =... |
15,916 | f90702994999ed20780f4d587ee70b65478dfbfb | from Bio import SeqIO
from Bio import pairwise2
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna# i need to change it
from Bio.SubsMat import MatrixInfo as matlist
from tkinter import filedialog
import tkinter.messagebox
import tkinter as tk
import pyperclip
from tkinter import ttk
from dict_values import *... |
15,917 | 23846d7ee46b5179d47df2a212b1232419786abc | students = [
{'name': 'Rezso', 'age': 9.5, 'candies': 2},
{'name': 'Gerzson', 'age': 10, 'candies': 1},
{'name': 'Aurel', 'age': 7, 'candies': 3},
{'name': 'Zsombor', 'age': 12, 'candies': 5}
]
def many_candies():
for i in students:
if i["candies"] > 4:
print(i["... |
15,918 | 66a7f931409aed302bce698737d190053f870d0f | class Graph:
def __init__(self, graphDictionary = None):
if graphDictionary is None:
graphDictionary = {}
self.graphDictionary = graphDictionary
def getVertices(self):
return list(self.graphDictionary.keys())
def edges(self):
return self.findEdges()
def findEdges(self):
edgeName = []
for vertex i... |
15,919 | 107fc08ab288fe2258f92e73b997b17bf8be0d26 | import sys
import argparse
import logging
import shutil
import time
import os
from inspect import signature, Parameter
from pathlib import Path
import pandas as pd
from pyispace.example import save_opts
from pyispace.trace import trace_build_wrapper, make_summary, _empty_footprint
from pyispace.utils import save_footp... |
15,920 | 747e8f0aaa5ee872bcc56f78e5793cec1f63d4fc | #Input : {“Gfg” : [4, 7, 5], “Best” : [8, 6, 7], “is” : [9, 3, 8]}, K = 2
#Output : [5, 7, 8]
from operator import itemgetter
input = {"gfg" : [4, 7, 5], "best" : [8, 6, 7], "abc" : [9, 3, 8]}
k=0
final=[]
for ind,val in enumerate(input.values()):
print(ind,val)
final.append(val[k])
print(final)
... |
15,921 | 05c913aa2227e64c1166fcf18c2583ddf835511e | """
Bonfire Core Cache
(c) 2019,2020 The Bonfire Project
License: See LICENSE
"""
from myhdl import Signal,intbv,modbv, concat, \
block,always_comb,always_seq, always, instances, enum, now
from rtl.util import int_log2
import rtl.cache.cache_way as cache_way
from rtl.cache.config import CacheConf... |
15,922 | cc7465e3e3357d1524c576ed19071b092f30e76a | # Copyright: 2019, NLnet Labs and the Internet.nl contributors
# SPDX-License-Identifier: Apache-2.0
import json
from django.http import HttpResponseRedirect
from django.views.decorators.http import require_http_methods
from .util import check_valid_user, batch_async_generate_results
from .util import get_site_url, A... |
15,923 | 6c1115cec25714a0a7c9f7ac953e12b747d8a8f5 | import sys, traceback
import json
from NLP.Utils.TextUtilities import fix_bad_unicode_textacy as fix_bad_unicode
from NLP.Utils.Words import Words
from NLP.Utils.text_normalization import plain_text_abstract
class NlpProc():
def __init__(self):
self._nlp = None
self.language = 'en'
@proper... |
15,924 | 4f3442e03f199088f686f655643cd80df74d3f60 | #!/usr/bin/env python
'''
This file includes examples of how to use the API. You will have to obtain your own API Key to use the API.
The API Key must be put in the request header of all requests to the API. There are two main ways to use
the API-- the first is to retrieve proxies, and teh second is to report their... |
15,925 | 8c50bcafd0b116cc85acd3e1821dea2475c72a4a | from django.test import TestCase
from model_mommy import mommy
from examples.models import ExampleState
from projects.models import ProjectType
from projects.tests.utils import prepare_project
class TestExampleState(TestCase):
def setUp(self):
self.project = prepare_project(ProjectType.SEQUENCE_LABELING)... |
15,926 | 8a716aceb8ddf618f6466377805486a7c482f3b5 | class LuasSegititiga():
def hitung(self,alas:float,tinggi:float):
return 0.5*alas*tinggi
#kubus,balok,kerucut,bola,tabung,limas segitiga,prisma segitiga |
15,927 | 44d3c523c36bb23e36a607ecece59ae0f4060567 | import torch.utils.data as data
import os
import numpy as np
# this function can be optimized
def default_flist_reader(ply_data_dir, flist):
"""
flist format: pts_file seg_file label for each line
"""
ffiles = open(flist, 'r')
lines = [line.rstrip() for line in ffiles.readlines()]
pts_fi... |
15,928 | 6220c3c08af6c6db5713c5565de86f79d21f34e1 | import keras
import tensorflow as tf
import sys
import os
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator #para preprocesar las imagenes
from tensorflow.python.keras import optimizers
from tensorflow.python.keras.models import Sequential #para hacer CNN secuenciales
from tensorflow.python.ker... |
15,929 | dffbb97eeaf1a8d1de9dc818815fc7ce3d122f68 | from sklearn.cross_validation import cross_val_score, ShuffleSplit
from sklearn.datasets import load_boston#波士顿房屋价格预测
from sklearn.ensemble import RandomForestRegressor
import numpy as np
#集成学习ensemble库中的随机森林回归RandomForestRegressor
#Load boston housing dataset as an example
boston = load_boston()
X = boston["data"]
Y ... |
15,930 | e0c9e99f7baa7d34a2ca1661d1dacf677146284b | #!/usr/bin/env python2.7
# encoding: utf-8
# Copyright (c) 2016 Dilusense Inc. All Rights Reserved.
# all api is for frontend interface
import json
from custom_libs.custom_decorator import check_login
from flask_application import app
@app.route('/config')
def config():
return json.dumps({
'code': 0,
... |
15,931 | 3f02f6789aaf4ebc9c537dc7e5f037c05e9abdf9 | from PyQt4 import QtCore, QtWebKit, QtGui
from GUI.main import BrowserGUI, BrowserTabGUI
actions = {"Alt+Left" : QtWebKit.QWebPage.Back, "Alt+Right" : QtWebKit.QWebPage.Forward, "F5" : QtWebKit.QWebPage.Reload }
class BaseBrowser(BrowserGUI):
"""
This class is the base for a simple web browser
In... |
15,932 | ac05aa863c772b14eeb932049dca608e163e0df5 | #增加留言
import requests
from AutoInterface.configs.config import HOST
from AutoInterface.lib.apiLib.login import Login
#1--封装类
class Msg:
def add_msg(self, inToken, inData):#增加留言
'''
:param inToken: 登录接口获取的token
:param inData: 留言新增的body
:return: 响应体
'''
url = f'{HOST}/... |
15,933 | 94ae40ea04b98126c8ae53453044addd10c357c3 | '''
Based on pyzmq-ctypes and pyzmq
Updated to work with latest ZMQ shared object
https://github.com/zeromq/pyzmq
https://github.com/svpcom/pyzmq-ctypes
'''
from zmq.bindings import *
from zmq.socket import *
from zmq.error import _check_rc, _check_ptr
import weakref
class Context(object):
def __init__(self, io... |
15,934 | 56b3c753e950ebb6592d26c5e14f96f673bbb006 | import torch
from torch import nn
import os
import pickle as pkl
import numpy as np
from typing import List
import random
exp_name = 'all_comb'
exp_dir = exp_name
save_result_dir = exp_dir + '/results/'
num_vocab = 40
end_of_sequence = num_vocab
start_of_sequence = num_vocab + 1
seq_length = 40
device = 'cuda' if torc... |
15,935 | a7ac7f33ea3c191b5af8ad0b74dc94a468efacd0 | import click
from src.model_data_retriever.ecmwf_request import ecmwfRetriever
from src.model_data_retriever.cds_request import cdsRetriever
from src.tools.data_tools import dataTools
@click.command()
@click.argument(
'request-file',
type=click.Path(exists=True))
@click.option(
'--dates',
'-d',
na... |
15,936 | 758d7f090c7616e495c1d12c83ebfdd378905345 | from Google import send_message
from ml_tracker import price_tracker
from cli import drawMenuScreen, drawConfigScreen, drawHelpScreen
from dotenv import load_dotenv
from bt_hours import weekly_check_hours
from conf import config_env_file
import os
def env_data_inputs():
print(drawConfigScreen())
MY_MAIL = inpu... |
15,937 | 109c3a002c54666904ff132ea5725ca7800afe79 | #!/usr/bin/env python
import os.path,sys
sys.path.insert(0,os.path.join(os.path.dirname(__file__),'lib'))
from model.user import User
from lib import db_engine
from controller import main,factory,resource,log,configuration
import cherrypy
#initial Configuration for Vserver-GUI
config = os.path.join(os.path.dirname(_... |
15,938 | ffa1060bbcadd98fbb5b641754758d1fe63922d1 | from django.db.models.signals import post_save
from django.dispatch import receiver
from andr_omeda.andr_bot.models.bot import Bot
from andr_omeda.andr_bot.tasks import async_set_webhook
|
15,939 | 03913b5253818f2b4fe19421c6ef72c3b26e73fe | # models.py
from db import db
from sqlalchemy import and_
class User(db.Model):
# (设置表名)
__tablename__ = 'user_list'
# (设置主键)
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255),)
password = db.Column(db.String(255),)
# 返回一个可以用来表示对象的可打印字符串:(相当于java的toString)
... |
15,940 | c236c12e50caac63526242e6e31376ba219fdaf9 | from .decorators import captchaform
from . import settings
# A simple shortcut/"default" field name for the captcha
captcha = captchaform(settings.DEFAULT_FIELD_NAME)
|
15,941 | 5088a387dd1abc225a24cece252095c2b77e446d | from flask import Flask, request, make_response
from verify_email import VerifyEmail
import json
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
'''
Http请求方式 POST
Content-Type application/json
传参格式(Http流传输):
[
"zhzhi2008@126.com",
"529781013@qq.com",
"2121kk@toytoystimple.net"
... |
15,942 | d0cd6f49f2dc7fe56fb7efc7baa42caaab7fce09 | # _*_ coding utf-8 _*_
# __author: Jason
# Date: 2018/12/20
'''
按逗号分隔列表。
'''
L = [1,2,3,4,5]
#利用JOIN将通过迭代器生成的字符串进行拼接
s1 = ','.join(str(n) for n in L)
print(s1)
print(type(s1))
L = [1, 2, 3, 4, 5]
L = repr(L)[1:-1]
print(L)
print(type(L)) |
15,943 | b64e9fea26ec95f03db1e430f8bdc38f8c5d31a3 | # from @cigar666
"""
注:
1. 主要用来求解两圆和多圆相交的交集部分的示意(如果是空集会出问题)
2. Intersection_n_circle是没有基于前两个类的,其实就用它也就行了
3. 可以用来做一些类似文氏图之类的,其他凸区域的交集可使用类似的方法写出来(如果谁有兴趣可以写一下)
"""
from manimlib.imports import *
class Irregular_shape(VMobject):
def __init__(self, *curves, **kwargs):
VMobject.__init__(self, **... |
15,944 | f2373b372abad41cc6a9bf4237c692bb7fe155bd | # -*- coding: UTF-8 -*-
import olympe
from olympe.messages.ardrone3.Piloting import TakeOff, moveBy, Landing, NavigateHome, moveTo
import olympe_deps as od
from olympe.messages.ardrone3.PilotingState import FlyingStateChanged
from olympe.messages.camera import take_photo, set_camera_mode, set_photo_mode, photo_progress... |
15,945 | ce8b50c49b67596f39e3e2ebf1e97ff86b1d0911 | from foolbox.distances import LpDistance
import numpy as np
import eagerpy as ep
from math import ceil
import pandas as pd
from attack.criteria import TargetedMisclassification
import torch
# Here defines the maximum allowed batch size:
MAX_BATCH = 128
def collect_attack_search_statistics(trials):
typect = {}
... |
15,946 | 54332ff9eed2cd36b601ce0409faf64be849f64f | """ User serializers """
# Django REST Framework
from rest_framework import serializers
# Models
from valoracion.users.models import User
class UserModelSerializer(serializers.ModelSerializer):
""" User model serializer """
email = serializers.EmailField(required=True)
username = serializers.CharField... |
15,947 | cb2705b1f286b1998f9e87625e989769c51f473a | from urllib.parse import urlparse, urlunparse, urlsplit, urlunsplit, urljoin, urlencode, parse_qs, parse_qsl, quote, \
unquote
"""1. urlparse()"""
# urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
# scheme://netloc/path;params?query#fragment
# scheme only works when no scheme specified in URL
# a... |
15,948 | 5f649a8733879ea04830ee1024492d6848b66abc | from django.db import models
from django.conf import settings
import uuid
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class RegistrationToken(models.Model):
token = models.UUIDField(default=uuid.uuid4)
created_at = models.DateTimeField(auto_now=... |
15,949 | 6716acabb6389ff4dd37a50cf0afbf67422a6298 | import json
from pprint import pprint
from string import Template
from presentation import generate_template
def calculateLikesFrom(likesDict, username):
for user, likeCount in likesDict.iteritems():
if user == username:
return likeCount
return 0
def extractFirstName(s):
res = s.split('*')[0].split('/')[-1]... |
15,950 | 10b72df1eff861e6eb3a6ce446adda231d054d9c | from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
from time import sleep
class tempSensorDS:
def __init__(self, pin_nb):
self.pin = Pin(pin_nb, Pin.IN)
self.ow = DS18X20(OneWire(self.pin))
self.ds_sensor = self.scan()
def scan(self):
try:
... |
15,951 | 8c0e722951de6173e3aa1d5f3401153b41050b63 | def artifact_removal(self, csp, info, layout):
print("This CLI will help you remove features that look like artifacts.")
print("Please enter an integer number (starting from 0) for each of the patterns you would like to drop.")
print("Once you are done, enter a negative integer")
drops = []
while 1:... |
15,952 | b8c632ef4b69bc0a15142fc8057c607e1751e58c | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 8 15:03:25 2021
@author: Moritz
"""
# for every itemID, a popularity score is calculated based on clicks, basket, and orders
# Additonally, the main topic and popularity rank for the main topic is added as an item attribute.
# Look at data frame... |
15,953 | d73c77e327197260d1316f2ba06f33386c485b96 | from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework import status, response, views
from foundations.models import Sensor
from sensor.serializers import SensorRetrieveSerializer
def sensor_retrieve_page(request, id):
return render(request, "sensor/retrieve.html",... |
15,954 | 6d8814e4dbd4926e5989c89d44a0bd12839bd100 | ### 8/20/2020
### Using arbitrary keyword arguments
def seat_profile(first_name, last_name, **passenger_info):
"""Build a dictionary containing all passenger information"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in passenger_info.items():
profile[key] = value
retu... |
15,955 | e531793fa19d52a5164166677384f10273ce3b82 | import shutil
import tempfile
import os
import json
from typing import Optional
import asyncio
import electrum_mona
from electrum_mona.wallet_db import WalletDB
from electrum_mona.wallet import Wallet
from electrum_mona import constants
from electrum_mona import util
from .test_wallet import WalletTestCase
# TODO a... |
15,956 | 21734c02e6899f155c815b6aa64a5596c8fa6472 | import io
from django.conf import settings
from django.core.management import BaseCommand
from buyer.models import Buyer
from core.helpers import generate_csv, upload_file_object_to_s3
class Command(BaseCommand):
help = 'Generate the FAB buyers CSV dump and uploads it to S3.'
def handle(self, *args, **opti... |
15,957 | 064b6130bc10227ea8349d7a04279b9067a573b4 | from django.apps import AppConfig
class WebDemoConfig(AppConfig):
name = 'web_demo'
|
15,958 | 288e8b579bee64ca61b95edbefb04a45c4d2afaa | # 78.子集(Medium)
# 题目描述:
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
# 说明:解集不能包含重复的子集,[1, 2] 和 [2, 1] 这种子集算重复
# 示例:
# 输入: nums = [1,2,3]
# 输出:
# [[3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []]
class Solution(object):
def subsets(self, nums):
"""
:type nums... |
15,959 | 4420fcf7dff3fdf0c1851d4bb5e8db0d704abc06 | '''
创建集合使用 {} 或 set() ,但是如果要创建空集合只能使用set(),因为{} 用来创建空字典
'''
s1 = {10, 20, 40, 50}
# add()
# s1.add(100)
# s1.add(10)
# print(s1)
# update() 增加的数据是序列
# s1.update([10, 20, 30, 40])
# print(s1)
# remove() 删除集合中的制定数据,如果数据不存在则报错
# s1.remove(10)
# discard() 删除集合中的制定数据,如果数据不存在也不会报错
# s1.discard(20)
# pop()
# del_num = s1... |
15,960 | 12277b4e22f9a5f0f6a9cbbd2026ca2a4d6ca047 | __author__ = 'Esmidth'
class stepper:
def __getitem__(self, item):
return self.data[item]
x = stepper()
x.data = 'Spam'
print(x[1])
for item in x:
print(item)
print('a' in x) |
15,961 | 79176269d65c1f0a9ae74e49e6ba090849a0728a | import msgpack
from nanomsg import (
PUB,
SUB,
SUB_SUBSCRIBE,
PAIR,
DONTWAIT,
Socket,
NanoMsgAPIError,
EAGAIN
)
class Channel(object):
type_map = {
'Sub': SUB,
'Pub': PUB,
'Pair': PAIR
}
def __init__(self, address, channel_type, is_server):
... |
15,962 | 64d87fec80e32d04c21cf281d7f36ee5a080f7bf | #!/usr/bin/env python3 -B
import unittest
from cromulent import vocab
from tests import TestKnoedlerPipelineOutput, classified_identifiers
vocab.add_attribute_assignment_check()
class PIRModelingTest_AR38(TestKnoedlerPipelineOutput):
'''
AR-38: Knoedler stock numbers not correctly identified on physical obj... |
15,963 | 067337f07f9d652a02891205fd175a4901a5a2c9 | # Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
#
# Example 1:
#
# Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
# Output: [["... |
15,964 | e5181e4bca3367d66726d37d007a4712649cab98 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
x=100
n=2
def raiz(x,n):
r=x**(1/float(n))
return r
print(raiz(x,n)) |
15,965 | f39931f5bc2fdea0107199f14db4e38227979514 | #/usr/bin/env python3
import requests
import re
import sys
from termcolor import colored
(banner) = """
__ __ _
\ \ / /__ _ __ __| |_ __ _ __ ___ ___ ___
\ \ /\ / / _ \| '__/ _` | '_ \| '__/ _ \/ __/ __|
\ V V / (_) | | | (_| | |_) | | | __/\__ \__ \
\_/... |
15,966 | 04e896e7d4d04e37baf3281788f4b1ed5743049d | from database import Base
from sqlalchemy import Column, Integer, String, SmallInteger, ForeignKey, Float
from sqlalchemy import DateTime, func
from datetime import datetime
from sqlalchemy.orm import relationship
from models.users import User
class Transaction(Base):
__tablename__ = "transactions"
id = Colum... |
15,967 | 9a8f977a732ddca744a53e4cd488110d1ca1087d | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 26 19:32:24 2017
@author: xu.2727
using my pre-trained net to extract features
"""
import caffe
import numpy as np
import os
import scipy.io as sio
from random import shuffle
from PIL import Image
import pdb
class_map = {
(255,255,255):0,
(0,0,255):1,
(0,255,255):2... |
15,968 | 2b2ad73cfe1439a2d478024bc6a868c28cfa4dfe | #!/usr/bin/env python
#-*-coding:utf8-*-
import re
import requests
url = 'https://pt.sjtu.edu.cn/torrents.php?inclbookmarked=0&incldead=0&spstate=0&cat=429&page=0'
class spider:
def __init__(self):
self.url = url
print "start crawling ..."
def getContent(self):
response = reques... |
15,969 | fb361cf718c6ccf03cb12ce00cf52db48a1a1593 | from random import randint
c = randint(1,50)
for var in range(1,6) :
u = int(input("Your guess : "))
if u < c :
print("Be Big Think Big")
elif u > c :
print("Be in limits and think lower")
else :
print("You have won the game ")
break
if var == 5 :
print(... |
15,970 | 05bfd69829a9adf6b0877ea98a2ee2c854eb23f3 | import feedparser
from variables import get_variable_value_cascaded,expand_string_variables,safe_parse_split
def check_for_new_links(feed):
"""Given the normal feed object, return a list of new feed entries. Ordered oldest to newest."""
#read the feed
feed_url = feed["feed_url"]
feed_data = feedparser.... |
15,971 | 8917e9761208c9138707a265d5d2c8c715db6895 | from pwn import *
p=remote('shell.actf.co',19010)
#p=process('./o')
def do_write(n):
code=''
for i in range(3):
byte = (n>>(i*8))&0xff
root = int(byte**0.5)
code += '+'*(byte-root*root)+'>'
code += '[-]'+root*'+'
code += '[<'+'+'*root+'>-]'
#clean
for i in rang... |
15,972 | 867661597d32e503e5acdbddb3ad54d7c885fff2 | # -------------
# This module delivers helper functions
# to get a driver instance for the chrome webdriver
# make sure the path to the webdriver is right
# -------------
import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import settings
impor... |
15,973 | 2bc1a6147d59bd82d941c13bd47187618bac53ab | #Create list of exceptions
#sample from https://www.thoughtco.com/irregular-plural-nouns-in-english-1692634
#utimately, this should read a file
exceptionList = {
"addendum":"Addenda",
"aircraft":"Aircraft",
"alumna":"Alumnae",
"alumnus":"Alumni",
"analysis":"Analyses",
"antenna":"Antennae",
"antithesis":"antitheses",
... |
15,974 | 0da02ccb0148cd68dd11e931a6987b0069c08eba |
"""
Component which holds data about a sprite.
"""
class RenderComponent:
def __init__(self, sprite):
"""Sprite needs to be a pygame.image object."""
self.sprite = sprite
|
15,975 | 4b7a574904900d4fa2b703e683aa0da61418d900 | import RPi.GPIO as GPIO
import time
import board
import busio
import digitalio
import adafruit_bmp280
AO_pin = 0
SPICLK = 21
SPIMISO = 19
SPIMOSI = 20
SPICS = 8
def init():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
... |
15,976 | a76b352f72c8b715bf17cf678a4d0bd263b049ee | # def func():
# def func2():
# print('this is func2')
# return func2
#
#
# f = func()
# f()
#
# def f1(x):
# print(x)
# return 123
#
#
# def f2():
# ret = f1('s')
# print(ret)
#
#
# f2()
#
# def func():
# def func2():
# return 'a'
# return func2
#
# func2 = func()
# print... |
15,977 | 17acab7d4d2ccda31dc52af8d41788cf8f2dba58 | from django.shortcuts import (render, redirect, reverse,
HttpResponse, get_object_or_404)
from django.contrib import messages
from shop.models import Product
from django.contrib.auth.decorators import login_required
@login_required
def shopping_bag(request):
"""
Returns Shopping ... |
15,978 | d283fe3b93bebb5bd27eb4e0d49ef6674e8aa664 | """ Distribution specific override class for CentOS family (RHEL, Fedora) """
import logging
from typing import Any
from certbot import errors
from certbot import util
from certbot_apache._internal import apache_util
from certbot_apache._internal import configurator
from certbot_apache._internal import parser
from cer... |
15,979 | 275fc40622a91046a4a613d830a43264d2a87f36 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import sys
import os
def print_help():
print('''[this py] <cmd>
cmd:命令名称,如:mvn node
示例:
[this py] mvn -> 打开mvn环境变量所在文件夹
''')
def open_path_in_explore(path):
os.system("explorer.exe \"{}\"".format(path))
def... |
15,980 | c88e012a342fe2c512d10f23f2c84e03202f91c6 | ###################################################################
#
###################################################################
import argparse
import os
class AppBuilder:
def __init__(self, name):
# supported features
self.sp_database = False
self.sp_logging = False # T... |
15,981 | 48c1e36918fe14e63fc2fe40169fc4fafdcb3709 | version https://git-lfs.github.com/spec/v1
oid sha256:f1ff30b52cb24bb73fb81207bf41852644551b23338fddd7b4f11e3f62dd4aaa
size 4518
|
15,982 | d05842be515ca5bbddbc4d1b263cde3e66cb7269 | """
Holds all classification functions
"""
#cv and math imports
import numpy as np
from matplotlib import pyplot as plt
import cv2
from math import radians, cos, sin, asin, sqrt,atan,atan2,degrees
#metadata, locations
import PIL.ExifTags
import PIL.Image
import utm #latqlong to utm-wgs84 transformations
#general li... |
15,983 | e4bf9bf609a4d78034441e53d9d7563d46952b79 |
import glob
import cv2
import os
path_relative = os.getcwd()
def processar(path_in, separator, path_out,res,ton):
if ton == 'rgb':
img = cv2.imread(path_in) # lê
img = cv2.resize(img, (res, res)) # redimensiona
nome_img = path_in.split(separator)[1]
cv2.imwrite(path_out + nome_... |
15,984 | 2ad23f5d24ea8582fd9c34880e3e32be8df1a6a9 | """
Routines for power spectra estimation and debiasing.
"""
import healpy as hp, numpy as np
from pspy import pspy_utils,so_mcm
from pixell import curvedsky
def get_spectra(alm1, alm2=None, spectra=None):
"""Get the power spectrum of alm1 and alm2, we use healpy.alm2cl for doing this.
for the spin0 and spin2 ... |
15,985 | 3d9378040ae604c475184908326dd2ef91c6837c | # If the peasant is damaged, the flowers will shrink!
def summonSoldiers():
if hero.gold >= hero.costOf("soldier"):
hero.summon("soldier")
# Define the function: commandSoldiers
def commandSoldiers():
for friend in hero.findFriends():
enemy = friend.findNearestEnemy()
if enemy and frie... |
15,986 | 96ddc8d8b74ea03738a3f7355bc8b0b096a9472e | import fractions
from algebra import cancel
from integer import digitsToNumber
for i in range(10,99) :
for j in range(i + 1, 100) :
if i % 10 and j % 10 :
f = cancel(list(str(i)), list(str(j)))
f0 = digitsToNumber(f[0])
f1 = digitsToNumber(f[1])
if 0 < f0 < 10 and 0 < f1 < 10 :
if fractio... |
15,987 | e24b50cdb48c29e24a3e387efcf4f5650677e2d8 | # uncompyle6 version 3.7.3
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.16 (default, Oct 10 2019, 22:02:15)
# [GCC 8.3.0]
# Embedded file name: o.py
# Compiled at: 2020-08-22 12:50:28
import os, sys, time
from time import sleep
os.system('clear')
os.system('xdg-open https://m.youtube.com/channel/UCSqjFO... |
15,988 | 8ca95f043239a5b432b102d6b80289d02c16baf9 | num1=3
num2=4
num3=5
if(num1>num2) and (num1>num3):
largest=num1
elif(num2>num1) and (num2>num3):
largest=num2
else:
largest=num3
print("",largest)
|
15,989 | 06dae6f0c45d56086378e9db047603ede9ca20b7 | from django.shortcuts import redirect, render
from .models import Versao
def home(request):
nome='sobre'
return render(request, 'logicgirl/sobre.html', {'nome':nome})
def sugestao(request):
nome='avaliacao'
return render(request, 'logicgirl/sugestao.html', {'nome':nome})
def reverter(lista):
... |
15,990 | 6a03616863c333d974b023593977105a142c9207 | class lexicon(object):
def __init__(self):
self.words = []
def __isDirection__(self, word):
"""
Check if the given word is a direction. Return True in case it is together with the tuple('direction', value)
:param word:
:returns tuple('direction', value) as first para... |
15,991 | c6df8803e40e95497d46a920b3641fdb074698b5 | from core.node import Node
class Constant(Node):
def __init__(self, val):
super().__init__()
self.value = val
def perform(self):
return self.value
def derivative(self, wrt):
return 0
def toString(self):
return str(self.value) |
15,992 | 51a8c294bb72efce2ea30575c98eaf79d65117fb | bufA = input()
count_word = 1
if bufA == "": #입력이 없으면 0를 출력
print(0)
else:
for i in bufA:
if i == " ": #공백문자를 계산
count_word += 1
if bufA[-1] == " ": #마지막 글자가 공백이라면
count_word -= 1
if bufA[0] == " ": #첫 글자가 공백이라면
count_word -= 1
print(count_word)
|
15,993 | f3b1ccbca2800a8d61659e6e5027088fcde37dcb | /home/jlin246/anaconda3/lib/python3.6/codecs.py |
15,994 | fd3828ae9c68715b3e507d2cc6d0064abc151be8 | import subprocess
curl_auth_URL = '''
curl 'https://www.linkedin.com/uas/js/authuserspace?v=0.0.1191-RC8.56523-1429&api_key=4XZcfCb3djUl-DHJSFYd1l0ULtgSPl9sXXNGbTKT2e003WAeT6c2AqayNTIN5T1s&credentialsCookie=true' -H 'Accept-Encoding: gzip, deflate, sdch, br' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla... |
15,995 | 77ef4bda8fa7b0148a30d51267800e0978d06b4f | import torch
import numpy as np
def Interlace(inp,intermediate,scale):
if (inp.shape[1]!=intermediate.shape[1]):
print('Wrong Dimensions')
return 0
else:
if repr(type(inp[8:8+5])) == 'torch':
output=torch.Tensor(inp.shape[0]+intermediate.shape[0],inp.shape[1])
el... |
15,996 | a3c3a2163f30f3cea8400c359b8a679c0a7463ec | import random
import re
import time
import requests
from lxml import etree
from selenium import webdriver
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9",
"cache-co... |
15,997 | da0658b5fc5ce8e077644d70ad73ceaba4001897 | from datetime import datetime
from flask import (
Blueprint,
abort,
current_app,
jsonify,
make_response,
request,
safe_join,
send_from_directory,
)
import requests
from werkzeug.exceptions import Unauthorized
from dashboard.bearer_auth import BearerAuth
from dashboard.extensions import ... |
15,998 | 8f0a70c1dbcfedf0961c3290c83431b2ebf6e42f | #!/usr/bin/env python3
import os
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
import yaml
import ast
import logging
import socket
import subprocess
import darc
from darc.definitions import CONFIG_FILE
# setup logger
logger = logging.getLogger('darc.control')
handler = logging.StreamHandler(s... |
15,999 | b9d4b5d4bf69a1a73569d95c88edd38aad6be704 | class Computer:
position = 0
nextStep = 0
resultPosition = 0
def __init__(self, commandArray, resultPosition):
self.data = commandArray
self.resultPosition = resultPosition
def addition(self):
self.data[self.data[self.position + 3]] = self.data[self.data[self.position + 1]]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.