index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
4,800 | 139ccdaf7acb2a2d74649f0c32217d1fe71a954a | from flask import Blueprint
views = Blueprint('views', __name__)
from . import routes |
4,801 | 9ce406124d36c2baf09cf0d95fceb2ad63948919 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
4,802 | 3cb96607aaf58a7de3fa0a9cd61b7f4e3c6b061a | import daemon
import time
import sys
#out = open("~/tmp/stdout", "a+")
#err = open("~/tmp/stderr", "a+")
# 如果设定为标准输出,那么关闭终端窗口,退出守护进程。
# Ctrl+c 不会退出进程
# 关闭终端窗口,退出守护进程
def do_main_program():
print("start the main program...")
while True:
time.sleep(1)
print('another second passed')
context = d... |
4,803 | 7e8b192e77e857f1907d5272d03c1138a10c61f4 | import rasterio as rio
from affine import Affine
colour_data = []
def generate_colour_data(width, height, imagiry_data, pixel2coord):
"""Extract color data from the .tiff file """
for i in range(1, height):
for j in range(1, width):
colour_data.append(
[
... |
4,804 | 68b9f7317f7c6dcda791338ee642dffb653ac694 | import socket
import time
import sys
def main():
if len(sys.argv) != 2:
print("usage : %s port")
sys.exit()
port = int(sys.argv[1])
count = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socke... |
4,805 | 69cf28d32e6543271a0855d61a76808b03c06891 | '''
3、 编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
'''
def f(n):
if n%2==0:
sum=0
for x in range(2,n+1,2):
sum+=1/x
print(sum)
if n%2!=0:
sum=0
for x in range(1,n+1,2):
sum+=1/x
print(sum)
|
4,806 | d1944493b7f3e74462ca0163a8c0907e4976da06 | # Problem statement here: https://code.google.com/codejam/contest/975485/dashboard#s=p0
# set state of both bots
# for instruction i
# look at this instruction to see who needs to press their button now
# add walk time + 1 to total time
# decriment walk time of other bot by walk time +1 of current bot (rectif... |
4,807 | d72f9d521613accfd93e6de25a71d188626a0952 | """
Password Requirements
"""
# Write a Python program called "pw_validator" to validate a password based on the security requirements outlined below.
# VALIDATION REQUIREMENTS:
## At least 1 lowercase letter [a-z]
## At least 1 uppercase letter [A-Z].
## At least 1 number [0-9].
## At least 1 special character [~!@#... |
4,808 | 1855351b20c7965a29864502e4489ab4324c7859 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 17 13:07:47 2020
@author: mmm
"""
n = 2
n1 = 10
for i in range(n,n1):
if n > 1:
for j in range(2,i):
if (i % j!= 0):
else:
print(i)
|
4,809 | 74a0282495bf4bbd34b397e0922074659a66d6ff | #coding=utf-8
from django.contrib import admin
from models import *
#增加额外的方法
def make_published(modeladmin, request, queryset):
queryset.update(state=1)
class OrderInfoAdmin(admin.ModelAdmin):
list_display = ('ordernum', 'total', 'state')
search_fields = ('total', )
list_filter = ('bpub_date',)
ac... |
4,810 | f92b939bf9813e5c78bc450ff270d5fb6171792a | import tensorflow as tf
from vgg16 import vgg16
def content_loss(content_layer, generated_layer):
# sess.run(vgg_net.image.assign(generated_image))
# now we define the loss as the difference between the reference activations and
# the generated image activations in the specified layer
# return 1/2 * ... |
4,811 | 85c97dfeb766f127fa51067e5155b2da3a88e3be | s = input()
ans = 0
t = 0
for c in s:
if c == "R":
t += 1
else:
ans = max(ans, t)
t = 0
ans = max(ans, t)
print(ans)
|
4,812 | 41e3c18b02f9d80f987d09227da1fbc6bde0ed1d | from __future__ import division
import abc
import re
import numpy as np
class NGram(object):
SEP = ''
def __init__(self, n, text):
self.n = n
self.load_text(text)
self.load_ngram()
@abc.abstractmethod
def load_text(self, text):
pass
def load_ngram(self):
counts = self.empty_count()
... |
4,813 | ae9f1c4f70801dace0455c051ba4d4bfb7f3fe67 | from django.core import management
from django.conf import settings
def backup_cron():
if settings.DBBACKUP_STORAGE is not '':
management.call_command('dbbackup')
|
4,814 | 7821b07a49db9f3f46bedc30f2271160e281806f | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models
from torchvision.utils import make_grid
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from PIL import Image
from... |
4,815 | fa7246a4e7595393ca9aaec777fa85d782bb816e |
n = 0.3
c = 2
def func(x):
return x**c
def der_func(x):
return c * x**(c - 1)
def na_value(x):
return x - n*der_func(x)
def main():
x = 100
v_min = func(x)
for i in range(10):
cur_v = func(x)
x = na_value(x)
if cur_v < v_min:
v_min = cur_v
print... |
4,816 | 4296dc5b79fd1d2c872eb1115beab52a0f067423 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, q2-chemistree development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------... |
4,817 | e85f203e71c8fdad86bd82b19104263cca72caf1 | from hierarchical_envs.pb_envs.gym_locomotion_envs import InsectBulletEnv
import argparse
import joblib
import tensorflow as tf
from rllab.misc.console import query_yes_no
# from rllab.sampler.utils import rollout
#from pybullet_my_envs.gym_locomotion_envs import Ant6BulletEnv, AntBulletEnv, SwimmerBulletEnv
from hie... |
4,818 | 2b3983fd6a8b31604d6d71dfca1d5b6c2c7105e0 | import pandas as pd
import requests
import re
from bs4 import BeautifulSoup
from datetime import datetime
nbaBoxUrl = 'https://www.basketball-reference.com/boxscores/'
boxScoreClass = 'stats_table'
def getBoxScoreLinks():
page = requests.get(nbaBoxUrl)
soup = BeautifulSoup(page.content, 'html.parser')
ga... |
4,819 | 0475c6cab353f0d23a4c4b7f78c1b47ecc5f8d3b | '''
log.py
version 1.0 - 18.03.2020
Logging fuer mehrere Szenarien
'''
# Imports
import datetime
# Globale Variablen
ERROR_FILE = "error.log"
LOG_FILE = "application.log"
def error(msg):
__log_internal(ERROR_FILE, msg)
def info(msg):
__log_internal(LOG_FILE, msg)
def __log_internal(filenam... |
4,820 | dc7d75bf43f1ba55673a43f863dd08e99a1c0e0f | import unittest
from validate_pw_complexity import *
class Test_PW_Functions(unittest.TestCase):
def test_pw_not_long_enough_min(self):
sample_pass ="abcd"
expected_result = False
result = validate_pw_long(sample_pass)
self.assertEqual(expected_result, result)
def test_pw_ju... |
4,821 | ec9184fa3562ef6015801edf316faa0097d1eb57 | '''
236. Lowest Common Ancestor of a Binary Tree
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia:
“The lowest common ancestor is defined between two nodes p... |
4,822 | 191a57d3f13fcbe217ff6d0bd92dea163d5fb3cf | import re
from typing import Any, Dict, List
import aiosqlite
from migri.elements import Query
from migri.interfaces import ConnectionBackend, TransactionBackend
class SQLiteConnection(ConnectionBackend):
_dialect = "sqlite"
@staticmethod
def _compile(query: Query) -> dict:
q = query.statement
... |
4,823 | b8c7aa5ff7387eacb45d996fa47186d193b44782 | import re
def find_all_links(text):
result = []
iterator = re.finditer(r"https?\:\/\/(www)?\.?\w+\.\w+", text)
for match in iterator:
result.append(match.group())
return result |
4,824 | a1b579494d20e8b8a26f7636ebd444252d2aa250 | # Parsing the raw.csv generated by running lis2dh_cluster.py
g = 9.806
def twos_complement(lsb, msb):
signBit = (msb & 0b10000000) >> 7
msb &= 0x7F # Strip off sign bit
if signBit:
x = (msb << 8) + lsb
x ^= 0x7FFF
x = -1 - x
else:
x = (msb << 8) + lsb
x = x>>6 # Remove left justification of... |
4,825 | 97656bca3ce0085fb2f1167d37485fb7ee812730 | ##class Human:
## pass
##hb1-HB("Sudhir")
##hb2=HB("Sreenu")
class Student:
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
std1=Student("Siva",123)
|
4,826 | 1f345a20343eb859cb37bf406623c0fc10722357 | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import random
from utils.misc import *
from utils.adapt_helpers import *
from utils.rotation import rotate_batch, rotate_single_with_label
from utils.model import resnet18
from utils.train_helpers impor... |
4,827 | c8137aacfb0f35c9630515442d5bdda870e9908a | # Getting familiar with OOP and using Functions and Classes :)
class Dog():
species = 'mammal'
def __init__(self,breed,name):
self.breed = breed
self.name = name
def bark(self,number):
print(f'Woof! My name is {self.name} and the number is {number}')
my_dog = Dog('Corgi'... |
4,828 | 6bb7dafea73aff7aca9b0ddc1393e4db6fcf0151 | import numpy as np
#1
def longest_substring(string1,string2):
mat=np.zeros(shape=(len(string1),len(string2)))
for x in range(len(string1)):
for y in range(len(string2)):
if x==0 or y==0:
if string1[x]==string2[y]:
mat[x,y]=1
else:
... |
4,829 | d8da01433b2e6adb403fdadc713d4ee30e92c787 | from application.identifier import Identifier
if __name__ == '__main__':
idf = Identifier()
while raw_input('Hello!, to start listening press enter, to exit press q\n') != 'q':
idf.guess()
|
4,830 | a2aa615ac660f13727a97cdd2feaca8f6e457da4 | #!/usr/bin/env python
from application import app
import pprint
import sys
URL_PREFIX = '/pub/livemap'
class LoggingMiddleware(object):
def __init__(self, app):
self._app = app
def __call__(self, environ, resp):
errorlog = environ['wsgi.errors']
pprint.pprint(('REQUEST', environ), st... |
4,831 | 371c1c9e3ccf7dae35d435bdb013e0462f3add5d | from PIL import Image, ImageFilter
import numpy as np
import glob
from numpy import array
import matplotlib.pyplot as plt
from skimage import morphology
import scipy.ndimage
def sample_stack(stack, rows=2, cols=2, start_with=0, show_every=1, display1 = True):
if (display1):
new_list = []
new_list.a... |
4,832 | 0a23b16329d8b599a4ee533604d316bdfe4b579a | from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# driver = webdriver.Chrome('C:/automation/chromedriver')
# wait = W... |
4,833 | 3f4e8402bbd096a33ed159ca0fed250c74c2f876 | def label_modes(trip_list, silent=True):
"""Labels trip segments by likely mode of travel.
Labels are "chilling" if traveler is stationary, "walking" if slow,
"driving" if fast, and "bogus" if too fast to be real.
trip_list [list]: a list of dicts in JSON format.
silent [bool]: if True, does n... |
4,834 | 1f7007fcea490a8b28bd72163f99b32e81308878 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 22 19:29:50 2017
@author: marcos
"""
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from classes.imagem import Imagem
import numpy as np
def mudaCor(img, metodo='average', nTons=256):
nova = Imagem((img.altura, img.largura))
for x in rang... |
4,835 | 9b8b196e1ad845ab745dabe5abe3be7bea0d5695 | import csv
import sqlite3
import time
from datetime import datetime, timedelta
import pandas as pd
import pytz
import json
import urllib
import numpy as np
DATABASE = '/var/www/html/citibikeapp/citibikeapp/citibike_change.db'
def execute_query(cur,query, args=()):
cur = cur.execute(query, args)
rows = cur.fet... |
4,836 | 7c9b51ae7cde9c3a00888dac6df710b93af6dd7f | import os
import time
import re
import json
from os.path import join, getsize
from aiohttp import web
from utils import helper
TBL_HEAD = '''
<table class="table table-striped table-hover table-sm">
<thead>
<tr>
<th scope="col">Directory</th>
<th scope="col">Size</th>
</tr>
</thead>
<tbody>... |
4,837 | f70f4f093aa64b8cd60acbb846855ca3fed13c63 | # ""
# "deb_char_cont_x9875"
# # def watch_edit_text(self): # execute when test edited
# # logging.info("TQ : " + str(len(self.te_sql_cmd.toPlainText())))
# # logging.info("TE : " + str(len(self.cmd_last_text)))
# # logging.info("LEN : " + str(self.cmd_len))
# # if len(self.te_sql_cmd.toPlainText()) < ... |
4,838 | a0a9527268fb5f8ea24de700f7700b874fbf4a6b | """
SteinNS: BayesianLogisticRegression_KSD.py
Created on 10/9/18 6:25 PM
@author: Hanxi Sun
"""
import tensorflow as tf
import numpy as np
import scipy.io
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
########################################################################... |
4,839 | 4b552731fcfc661c7ad2d63c7c47f79c43a8ae5e | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... |
4,840 | 4b63df35b36b35f1b886b8981519921a9e697a42 | #
# Copyright (C) 2005-2006 Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
import argparse
import re
import os
from rd... |
4,841 | f3f5b14917c89c5bc2866dd56e212bd3ec8af1cd | import math
def Distance(t1, t2):
RADIUS = 6371000. # earth's mean radius in km
p1 = [0, 0]
p2 = [0, 0]
p1[0] = t1[0] * math.pi / 180.
p1[1] = t1[1] * math.pi / 180.
p2[0] = t2[0] * math.pi / 180.
p2[1] = t2[1] * math.pi / 180.
d_lat = (p2[0] - p1[0])
d_lon = (p2[1] - p1[1])
... |
4,842 | f720eaf1ea96ccc70730e8ba1513e1a2bb95d29d | import datetime
import time
import rfc822
from django.conf import settings
from urllib2 import Request, urlopen, URLError, HTTPError
from urllib import urlencode
import re
import string
try:
import django.utils.simplejson as json
except:
import json
from django.core.cache import cache
from tagging.models import T... |
4,843 | a9ebd323d4b91c7e6a7e7179329ae80e22774927 | import io
import xlsxwriter
import zipfile
from django.conf import settings
from django.http import Http404, HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic... |
4,844 | c9279434736d4e94564170fe98163ad3be9470b1 | """ Tests for challenge116 """
import pytest
from robber import expect
from pemjh.challenge116 import main
@pytest.mark.parametrize('input, expected',
[
pytest.param(5, 12, marks=pytest.mark.example),
pytest.param(50, 20492570... |
4,845 | 2fb299f5454c251dc1c77c2597ee23bf414c716e | learningRateBase = 0.001
learningRateDecreaseStep = 80
epochNum = 100
generateNum = 3
batchSize = 16
trainPoems = "./data/poems.txt"
checkpointsPath = "./model/" |
4,846 | 8c51b2c06f971c92e30d6b2d668fdd2fd75142d2 | class Reader:
@staticmethod
def read_file(file_path):
return '' |
4,847 | 4a913cfdbddb2f6b5098395814f5fc1203192b9a |
def f(p_arg, *s_args, **kw_args):
return (s_args[0] + kw_args['py'])+p_arg
r = f(3, 2, py = 1) ## value r => 6
|
4,848 | 75b13f4985fcf26fb9f7fb040554b52b13c1806d | def findOrder(numCourses,prerequisites):
d={}
for i in prerequisites:
if i[0] not in d:
d[i[0]]=[i[1]]
if i[1] not in d:
d[i[1]]=[]
else:
d[i[0]].append(i[1])
res=[]
while d:
for i in range(numCourses):
if d[i] == []:
res.append(d[i])
tmp=d[i]
del d[i]
for j in d:
if tmp i... |
4,849 | aa00e4569aeae58e3f0ea1a8326e35c0776f7727 | """Defines all Rady URL."""
from django.conf.urls import url, include
from django.contrib import admin
apiv1_urls = [
url(r"^users/", include("user.urls")),
url(r"^meetings/", include("meeting.urls")),
url(r"^docs/", include("rest_framework_docs.urls")),
url(r"^auth/", include("auth.urls")),
url(... |
4,850 | be566041402dc1705aa9d644edc44de8792fbb3c | from extras.plugins import PluginTemplateExtension
from .models import BGPSession
from .tables import BGPSessionTable
class DeviceBGPSession(PluginTemplateExtension):
model = 'dcim.device'
def left_page(self):
if self.context['config'].get('device_ext_page') == 'left':
return self.x_page... |
4,851 | 7d0d1a53a249167edade24a4e9305c95288a8574 | def chess():
row = 0
line = 0
chess1 = []
chess2 = []
for line in range(3):
x1 = (0,line)
chess1.append(x1)
for line in range(3):
x2 = (1,line)
chess2.append(x2)
print(chess1)
print(chess2)
for x in range(len(chess1))
if chess2[x][1] != chess1[... |
4,852 | 2e448176a755828e5c7c90e4224102a285098460 | from django.conf import settings
from django.db import migrations, models
import django_otp.plugins.otp_totp.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
nam... |
4,853 | 09a468e11651eb60e0805c151bda270e0ebecca9 | #!/usr/bin/env python
'''
fix a time and then draw the instant geopotential (contour) from
/gws/nopw/j04/ncas_generic/users/renql/ERA5_subdaily/ERA5_NH_z_1989.nc,
spatial filtered relative vorticity (shaded) from
~/ERA5-1HR-lev/ERA5_VOR850_1hr_1995_DET/ERA5_VOR850_1hr_1995_DET_T63filt.nc
and identified feature poin... |
4,854 | 9109e649a90730df022df898a7760140275ad724 | # -*- coding:utf-8 -*-
#实现同义词词林的规格化
with open('C:\\Users\\lenovo\\Desktop\\哈工大社会计算与信息检索研究中心同义词词林扩展版.txt') as f:
with open('convert.txt','a') as w:
for line in f:
data = line[8:-1].split()
for item in data:
tmp = data.copy()
... |
4,855 | 05edbf3662936465eee8eee0824d1a0cca0df0e5 | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
import pathlib
from PIL import Image
if __name__ == '__main__':
img_path = (pathlib.Path('..') / 'images' / 'tiger.jpg').resolve()
# image load
with Image.open(str(img_path)) as img:
# image info
print('IMAGE: {}'.format(str(img_path)))
... |
4,856 | dd23cd068eea570fc187dad2d49b30376fbd4854 | from django.urls import path
from django.conf.urls import include, url
from . import views
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
appname = 'home'
urlpatterns = [
path('', views.home, name='home'),
]
urlpatterns += staticfiles_urlpatterns() |
4,857 | d414e4497bae23e4273526c0bbdecd23ed665cac | # Copyright 2018 The Cornac 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 applicable ... |
4,858 | 750565af03d945fbdc32e26347b28977b203e9dc | # Give a string that represents a polynomial (Ex: "3x ^ 3 + 5x ^ 2 - 2x - 5") and
# a number (whole or float). Evaluate the polynomial for the given value.
#Horner method
def horner( poly, x):
result = poly[0]
for i in range(1 , len(poly)):
result = result*x + poly[i]
return result
# Let us evalua... |
4,859 | 705755340eef72470fc982ebd0004456469d23e4 | #!/usr/bin/env python
from postimg import postimg
import argparse
import pyperclip
import json
def main(args):
if not args.quiet:
print("Uploading.....")
resp = postimg.Imgur(args.img_path).upload()
if not resp['success']:
if not args.quiet:
print(json.dumps(resp, sort_keys=True,... |
4,860 | 5c1324207e24f2d723be33175101102bd97fe7a2 | # #!/usr/bin/python
# last edit abigailc@Actaeon on jan 27 2017
#pulling the taxonomy functions out of makespeciestree because I need to make them faster...
#insects is running for literally >20 hours.
names_file = "/Users/abigailc/Documents/Taxonomy_Stuff/taxdump/names.dmp"
nodes_file = "/Users/abigailc/Documents/... |
4,861 | 01a6283d2331590082cdf1d409ecdb6f93459882 | import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from models.nutrient import *
class SoilRecord(db.Model):
year=db.DateProperty(auto_now_add=True)
stats=NutrientProfile()
amendmen... |
4,862 | c3e313805c6f91f9aac77922edfd09650143f905 | import cv2
import numpy as np
from math import *
def appendimages(im1,im2):
""" Return a new image that appends the two images side-by-side. """
# select the image with the fewest rows and fill in enough empty rows
rows1 = im1.shape[0]
rows2 = im2.shape[0]
if rows1 < rows2:
im1 = np.concat... |
4,863 | aeaab602cbb9fa73992eb5259e8603ecb11ba333 | import mlcd,pygame,time,random
PLAYER_CHAR=">"
OBSTACLE_CHAR="|"
screenbuff=[[" "," "," "," "," "," "," "," "," "," "," "," "],
[" "," "," "," "," "," "," "," "," "," "," "," "]]
player={"position":0,"line":0,"score":000}
game={"speed":4.05,"level":2.5,"obstacle":0}
keys={"space":False,"quit":False,"nex... |
4,864 | b80ccee42489aefb2858b8491008b252f6a2b9b7 | ii = [('CookGHP3.py', 2), ('MarrFDI.py', 1), ('GodwWSL2.py', 2), ('ChanWS.py', 6), ('SadlMLP.py', 1), ('WilbRLW.py', 1), ('AubePRP2.py', 1), ('MartHSI2.py', 1), ('WilbRLW5.py', 1), ('KnowJMM.py', 1), ('AubePRP.py', 2), ('ChalTPW2.py', 1), ('ClarGE2.py', 2), ('CarlTFR.py', 3), ('SeniNSP.py', 4), ('GrimSLE.py', 1), ('Ros... |
4,865 | b4992a5b396b6809813875443eb8dbb5b00eb6a9 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Import the otb applications package
import otbApplication
def ComputeHaralick(image, chan, xrad, yrad):
# The following line creates an instance of the HaralickTextureExtraction application
HaralickTextureExtraction = otbApplication.Registry.CreateApplication("Haral... |
4,866 | 49c15f89225bb1dd1010510fe28dba34f6a8d085 | # -*- coding: utf-8 -*-
from sqlalchemy import or_
from ..extensions import db
from .models import User
def create_user(username):
user = User(username)
db.session.add(user)
return user
def get_user(user_id=None, **kwargs):
if user_id is not None:
return User.query.get(user_id)
username ... |
4,867 | c31c59d172b2b23ca4676be0690603f33b56f557 | from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.skincare, name="skin"),
path('productSearch/', views.productSearch, name="productSearch"),
path('detail/', views.detail, name="detail"),
] |
4,868 | fbcbad9f64c0f9b68e29afde01f3a4fdba012e10 | """
Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану.
Медианой называется элемент ряда, делящий его на две равные части:
в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы.
Примечание: задачу можно решить без сортировки исходного м... |
4,869 | efe13de4ed5a3f42a9f2ece68fd329d8e3147ca2 | <<<<<<< HEAD
{'_data': [['Common', [['Skin', u'Ospecifika hud-reakti oner'], ['General', u'Tr\xf6tthet']]],
['Uncommon',
[['GI',
u'Buksm\xe4rta, diarr\xe9, f\xf6r-stoppnin g, illam\xe5ende (dessa symptom g\xe5r vanligt-vis \xf6ver vid fortsatt behandling).']]],
['Rare',
... |
4,870 | eeedf4930a7fa58fd406a569db6281476c2e3e35 | #+++++++++++++++++++exp.py++++++++++++++++++++
#!/usr/bin/python
# -*- coding:utf-8 -*-
#Author: Squarer
#Time: 2020.11.15 20.20.51
#+++++++++++++++++++exp.py++++++++++++++++++++
from pwn import*
#context.log_level = 'debug'
context.arch = 'amd64'
elf = ELF('./npuctf_2020_easyheap')
libc = ... |
4,871 | ebbc6f9115e6b4ca7d1050a59cf175d123b6f3aa | from flask import Flask
from threading import Timer
from crypto_crawler.const import BITCOIN_CRAWLING_PERIOD_SEC, COIN_MARKET_CAP_URL
from crypto_crawler.crawler import get_web_content, filter_invalid_records
app = Flask(__name__)
crawl_enabled = True
def crawl_bitcoin_price():
print("start crawling!")
bitc... |
4,872 | 8c7dcff80eeb8d7d425cfb25da8a30fc15daf5f9 | import tcod as libtcod
import color
from input_handlers import consts
from input_handlers.ask_user_event_handler import AskUserEventHandler
class SelectIndexHandler(AskUserEventHandler):
"""
Handles asking the user for an index on the map.
"""
def __init__(self, engine):
super().__init__(eng... |
4,873 | 0b1e6a95ee008c594fdcff4e216708c003c065c8 | # -*- coding: utf-8 -*-
import logging
from django.shortcuts import render, redirect, HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.hashers import make_password
from django.core.paginator im... |
4,874 | ae4f8eb71939ff212d05d12f65edeaecf66f2205 | from launch import LaunchDescription
from launch_ros.actions import Node
import os
params = os.path.join(
'INSERT_PATH/src/beckhoff_ros',
'config',
'params.yaml'
)
def generate_launch_description():
return LaunchDescription([
Node(
package='beckhoff_ros',
executable='beckhof... |
4,875 | f1972baee8b399c9a52561c8f015f71cb9922bb0 | version https://git-lfs.github.com/spec/v1
oid sha256:7f0b7267333e6a4a73d3df0ee7f384f7b3cb6ffb14ed2dc8a5894b853bac8957
size 1323
|
4,876 | b84a2093a51e57c448ee7b4f5a89d69dfb14b1b6 | import os
import sys
from flask import Flask, request, abort, flash, jsonify, Response
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_migrate import Migrate
import random
import unittest
from models import db, Question, Category
# set the number of pages fpr pagination
QUESTIONS_PER_PA... |
4,877 | d583661accce8c058f3e6b8568a09b4be1e58e4e |
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, HttpResponseServerError
from django.shortcuts import render
from django.template import RequestContext
import json
import datetime
... |
4,878 | 8b598703df67fb8287fe6cdccda5b73bf2892da8 | # -*- coding: utf-8 -*-
import requests
import os
def line(body):
url = "https://notify-api.line.me/api/notify"
access_token = 'I89UnoDRgRSInUXJOTg5fAniBE08CUuxVqj8ythMLt8'
headers = {'Authorization': 'Bearer ' + access_token}
message = body
payload = {'message': message}
r = requests.post(url... |
4,879 | a7050ebd545c4169b481672aed140af610aea997 | from card import Card;
from deck import Deck;
import people;
import chip;
import sys;
import time;
def display_instructions() :
print('\nInstructions: The objective of this game is to obtain a hand of cards whose value is as close to 21 ');
print('as possible without going over. The numbered cards hav... |
4,880 | 82c3419679a93c7640eae48b543aca75f5ff086d | from msl.equipment.connection import Connection
from msl.equipment.connection_demo import ConnectionDemo
from msl.equipment.record_types import EquipmentRecord
from msl.equipment.resources.picotech.picoscope.picoscope import PicoScope
from msl.equipment.resources.picotech.picoscope.channel import PicoScopeChannel
cla... |
4,881 | 7df94c86ff837acf0f2a78fe1f99919c31bdcb9b | from .dla import get_network as get_dla
from lib.utils.tless import tless_config
_network_factory = {
'dla': get_dla
}
def get_network(cfg):
arch = cfg.network
heads = cfg.heads
head_conv = cfg.head_conv
num_layers = int(arch[arch.find('_') + 1:]) if '_' in arch else 0
arch = arch[:arch.find... |
4,882 | 834fa5d006188da7e0378246c1a019da6fa413d2 | You are given a 2 x N board, and instructed to completely cover the board with
the following shapes:
Dominoes, or 2 x 1 rectangles.
Trominoes, or L-shapes.
For example, if N = 4, here is one possible configuration, where A is
a domino, and B and C are trominoes.
A B B C
A B C C
Given an in... |
4,883 | 0349a8a4841b024afd77d20ae18810645fad41cd | from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from datetime import datetime, timedelta
def sendmail(subject, template, to, context):
template_str = 'app/' + template + '.html'
html_msg = render_to_string(template_str, {'data... |
4,884 | 8ad5f3e5f73eae191a3fe9bc20f73b4bfcfedc8c | #Pràctica 9 Condicionals, Exercici 2:
print("Introduce un valor par:")
numpar=int(input())
print("Introduce un valor impar:")
numimp=int(input())
if numpar==numimp*2:
print(numpar," es el doble que ",numimp,".")
else:
print(numpar," no es el doble que ",numimp,".") |
4,885 | 8039430f1b65cc76f9a78b1094f110de29f0f965 | from utils import *
from Dataset.input_pipe import *
from Learning.tf_multipath_classifier import *
def config_graph():
paths = []
path = {}
path['input_dim'] = 4116
path['name'] = 'shared1'
path['computation'] = construct_path(path['name'], [512, 512], batch_norm=False, dropout=True, dropout_rate=0.5, noise=Fa... |
4,886 | 364150d6f37329c43bead0d18da90f0f6ce9cd1b | #coding=utf-8
import yaml
import os
import os.path
import shutil
import json
import subprocess
import sys
sys.path.append(os.path.split(os.path.realpath(__file__))[0])
import rtool.taskplugin.plugin.MultiProcessRunner as MultiProcessRunner
import rtool.utils as utils
logger = utils.getLogger('CopyRes')
def run():
lo... |
4,887 | ce365e011d8cc88d9aa6b4df18ea3f4e70d48f5c | #https://codecombat.com/play/level/village-champion
# Incoming munchkins! Defend the town!
# Define your own function to fight the enemy!
# In the function, find an enemy, then cleave or attack it.
def attttaaaaacccckkkk():
enemy = hero.findNearest(hero.findEnemies())
#enemy = hero.findNearestEnemy()
if e... |
4,888 | 480e636cfe28f2509d8ecf1e6e89924e994f100d | #!/usr/bin/env python3
import gatt
class AnyDevice(gatt.Device):
def connect_succeeded(self):
super().connect_succeeded()
print("[%s] Connected" % (self.mac_address))
def connect_failed(self, error):
super().connect_failed(error)
print("[%s] Connection failed: %s" % (self.mac_a... |
4,889 | 202670314ad28685aaa296dce4b5094daab3f47a | #
# PySNMP MIB module Nortel-MsCarrier-MscPassport-AtmEbrMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AtmEbrMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4... |
4,890 | 0754103c2d8cef0fd23b03a8f64ade8f049bce48 | from django.apps import AppConfig
class GerenciaLedsConfig(AppConfig):
name = 'gerencia_leds'
|
4,891 | 86849d0e63cdb93a16497ca56ff9c64c15a60fa7 | IEX_CLOUD_API_TOKEN = 'Tpk_5d9dc536610243cda2c8ef4787d729b6' |
4,892 | d8e8ecbf77828e875082abf8dcbfbc2c29564e20 | #!/usr/bin/env python
# -*- coding: utf-8 -*
#Perso
from signalManipulation import *
from manipulateData import *
#Module
import pickle
from sklearn import svm, grid_search
from sklearn.linear_model import ElasticNetCV, ElasticNet, RidgeClassifier
from sklearn.metrics import confusion_matrix, f1_score, accuracy_score... |
4,893 | b4783540224902b10088edbd038d6d664934a237 | def findFirst(arr,l,h,x):
if l>h:
return -1
mid=(l+h)//2
if arr[mid]==x:
return mid
elif arr[mid]>x:
return findFirst(arr,l,mid-1,x)
return findFirst(arr,mid+1,h,x)
def indexes(arr, x):
n=len(arr)
ind=findFirst(arr,0,n-1,x)
if ind==-1:
return [-... |
4,894 | 17f91b612fad14200d2911e2cb14e740b239f9ff | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
if my_list is None or len(my_list) == 0:
return None
new = []
for num in my_list:
if num % 2 == 0:
new.append(True)
else:
new.append(False)
return new
|
4,895 | 6e17fef4507c72190a77976e4a8b2f56880f2d6f | import tensorflow as tf
import bbox_lib
def hard_negative_loss_mining(c_loss, negative_mask, k):
"""Hard negative mining in classification loss."""
# make sure at least one negative example
k = tf.maximum(k, 1)
# make sure at most all negative.
k = tf.minimum(k, c_loss.shape[-1])
neg_c_loss = ... |
4,896 | ccd32a6ca98c205a6f5d4936288392251522db29 | # -*- coding: utf-8 -*-
__all__ = ["kepler", "quad_solution_vector", "contact_points"]
import numpy as np
from .. import driver
def kepler(mean_anomaly, eccentricity):
mean_anomaly = np.ascontiguousarray(mean_anomaly, dtype=np.float64)
eccentricity = np.ascontiguousarray(eccentricity, dtype=np.float64)
... |
4,897 | 9af71eaf8f6f4daacdc1def7b8c5b29e6bac6b46 | # Generated by Django 2.2.6 on 2019-12-08 22:18
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='company'... |
4,898 | 6c426d2b165e01a7cec9f7ddbd96113ae05668f6 | import math
n, m, a = map(int, input().split())
top = math.ceil(n/a)
bottom = math.ceil(m/a)
print(top*bottom)
|
4,899 | f4df7688ed927e1788ada0ef11f528eab5a52282 | import pytest
from mine.models import Application
class TestApplication:
"""Unit tests for the application class."""
app1 = Application("iTunes")
app1.versions.mac = "iTunes.app"
app2 = Application("HipChat")
app3 = Application("Sublime Text")
app3.versions.linux = "sublime_text"
app4 = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.