seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5292164947 | #right now, I am using this script to play around w/ differnt definitions of signal and control regions
import ROOT
from TIMBER.Analyzer import HistGroup, CutGroup
from TIMBER.Tools.Common import CompileCpp
from argparse import ArgumentParser
from XHYbbWW_class import XHYbbWW
from collections import OrderedDict
def K... | michaelhesford/XHYbbWW_semileptonic | MXvsMY_studies.py | MXvsMY_studies.py | py | 8,394 | python | en | code | 0 | github-code | 6 |
33186103812 | from simplejson import dumps
from webob import Response
from pycurl import Curl
from subprocess import Popen, PIPE
from multiprocessing import Queue
from traceback import format_exc
from time import sleep
import logging
import tarfile
import os
import os.path
import urllib
import uuid
import sys
import os
from config... | JeremyGrosser/repoman | repoman/buildbot.py | buildbot.py | py | 7,178 | python | en | code | 84 | github-code | 6 |
9345182500 | from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import lib.db
from lib.helper import remove_tags, open_selenium
from lib.log import log_text as log
url = "https://2e.aonprd.com/Ancestries.aspx"
def upload_heritage_data():
log("S... | sean-francis113/pf2edatascraper | lib/heritages.py | heritages.py | py | 13,500 | python | en | code | 0 | github-code | 6 |
7002219401 | import sendgrid
from ...common import config
sg = sendgrid.SendGridClient(config.sendgrid_api_key)
def send(name, email, subject, html):
message = sendgrid.Mail()
message.add_to('{}'.format(email))
message.set_subject(subject)
message.set_html(html)
message.set_from(config.from_header)
status, msg = sg.sen... | minupalaniappan/gradfire | daviscoursesearch/flaskapp/service/email.py | email.py | py | 330 | python | en | code | 12 | github-code | 6 |
28128126397 | '''
Count the nodes in the global phylogeny
python3 count_nodes.py after_usher_optimized_fasttree_iter6.tree
'''
import sys
from ete3 import Tree
t = Tree(sys.argv[1])
ct = 0
for node in t.traverse('postorder'):
if node.is_leaf():
ct += 1
print(ct)
| bpt26/parsimony | 2_optimize_starting_tree/results/2.3.5/count_nodes.py | count_nodes.py | py | 270 | python | en | code | 2 | github-code | 6 |
436459396 | from gensim.corpora import TextCorpus, TextDirectoryCorpus
from gensim.models.doc2vec import TaggedDocument
from trec.treccorpus import TrecCorpus
def test_get_texts():
path = "F:/Corpus/trectest/"
file = path + "fr881.dat"
# with open(file, 'r') as fp:
# print(fp.read())
trecc = TrecCorpus... | kongyq/Project-Arcs | trec/test_treccorpus.py | test_treccorpus.py | py | 2,325 | python | en | code | 1 | github-code | 6 |
30754133985 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split(' ')))
if a[0] < 0:
neg = True
a0 = a[0]
else:
neg = False
a0 = a[0]
somme = 0
for i in range(1, n):
if a[i] < 0 and neg:
a0 = max(a0, a[i])
elif a[i] > 0... | Tanguyvans/Codeforces | 636/C.py | C.py | py | 607 | python | en | code | 0 | github-code | 6 |
24082328734 | #!/usr/bin/python3
"""
Make petitions to the Reddit API
"""
from requests import get
def number_of_subscribers(subreddit):
"""
Takes a subreddit and compute the quantity of subs
"""
base_url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit)
header = {
'User-Agent': 'Linux:api... | WardenCode/holbertonschool-system_engineering-devops | 0x16-api_advanced/0-subs.py | 0-subs.py | py | 584 | python | en | code | 0 | github-code | 6 |
24025809080 | __author__ = 'sivvaidyanathan'
from urllib2 import urlopen
from bs4 import BeautifulSoup
import codecs, sys
filename = sys.argv[0]
reader = open(filename, 'r')
writer = codecs.open(filename + "_canonical", 'w', 'utf-8')
for line in reader:
url = line.strip()
if url.find("http") == -1:
url = "http://... | sivaramakrishnanvaidyanathan/crawler | histogram/link_canonical.py | link_canonical.py | py | 520 | python | en | code | 0 | github-code | 6 |
26538911991 | import hashlib
import os.path
from typing import List, Optional
import requests
from connectors.Triage.const import TRIAGE_URL, TRIAGE_LAST_100_RESULTS_FROM_NOW, TRIAGE_HEADER, OUTPUT_FOLDER
from connectors.utils import upload_file_to_malstream
def get_last_100_analysis() -> List:
r = requests.get(f"{TRIAGE_URL... | CorraMatte/malstream | connectors/Triage/connector.py | connector.py | py | 1,374 | python | en | code | 3 | github-code | 6 |
15260123974 | import datetime
import hashlib
import json
from flask import Flask, jsonify
# Building a Blockchain
class Blockchain:
def __init__(self):
"""
Create Blockchain and a genesis block
"""
self.chain = []
self.create_block(proof=1, previous_hash='0')
def create_block(self, ... | imnishant/Blockchain | main.py | main.py | py | 3,966 | python | en | code | 0 | github-code | 6 |
12701283102 | import sys
ground = []
ground_data = dict()
TIME_BY_DIG, TIME_BY_PUT = 2, 1
min_time, that_height = 128000000, 0
def try_to_make(ground_data, trying_height):
time = 0
for data in ground_data.items():
if data[0] < trying_height:
time += TIME_BY_PUT * data[1] * (trying_height - data[0])
... | MinChoi0129/Algorithm_Problems | BOJ_Problems/18111.py | 18111.py | py | 1,158 | python | en | code | 2 | github-code | 6 |
18464680736 | #!/usr/bin/python3
#encoding: utf-8
import requests
import re
from bs4 import BeautifulSoup
import json
#登录获取cookie
login_url = "http://210.30.1.140/index.php/Public/checkLogin"
#登录信息
logindata={
"txtName":"2015083216",
"txtPass":"2015083216",
"txtCheck":"no",
}
#获取cookie
logind = requests.p... | chinazhenzhen/PythonLearn | RE4/5+.py | 5+.py | py | 1,019 | python | en | code | 0 | github-code | 6 |
51412731 | from typing import *
class Solution:
def countTriplets(self, nums: List[int]) -> int:
M = max(nums)
cnt = [0]*(M+1)
for i in nums:
for j in nums:
# AND can only decrease the number
cnt[i&j] += 1
res = 0
for k in nums:
... | code-cp/leetcode | solutions/982/main.py | main.py | py | 436 | python | en | code | 0 | github-code | 6 |
42366132351 | import tensorflow as tf
import numpy as np
IMG_MEAN = np.array((103.939, 116.779, 123.68), dtype=np.float32)
def read_image_label_list(data_dir, data_list):
"""Reads txt file containing paths to images and ground truth masks.
Args:
data_dir: path to the directory with images and masks.
... | rashmi-patil-1492/video-semantic-segmentation-network | tools/image_reader.py | image_reader.py | py | 11,641 | python | en | code | 0 | github-code | 6 |
38544511106 |
import cv2
import mss
from PIL import Image
import numpy as np
import time
import json
import math
with open('Crypt.json', 'r') as json_file:
data = json.load(json_file)
with open('ItemGroups.json', 'r') as json_file:
item_data = json.load(json_file)
# record video of screen using cv2
fps = 30
fourcc = cv2.Vi... | debug-it/DarkAndDarker-MapHelper | record.py | record.py | py | 4,278 | python | en | code | 0 | github-code | 6 |
22003370311 | from reviewminer.core import *
import pandas as pd
import reviewminer as rm
reviews_df = pd.read_csv("./reviews.csv")
print("comment" in reviews_df.columns)
rm = ReviewMiner(reviews_df.head(100), 'id', 'comments')
rm.aspect_opinon_for_all_comments()
rm.popular_aspects_view(_testing=True)
print(rm.top_aspects)
rm.... | tianyiwangnova/2021_project__ReviewMiner | sample_data/work_on_sample_data.py | work_on_sample_data.py | py | 1,668 | python | en | code | 5 | github-code | 6 |
926386452 | import os
from unittest.mock import patch
import pytest
from rotkehlchen.db.dbhandler import DBHandler
from rotkehlchen.externalapis.etherscan import Etherscan
from rotkehlchen.tests.utils.mock import MockResponse
from rotkehlchen.typing import ExternalService, ExternalServiceApiCredentials
@pytest.fixture(scope='f... | fakecoinbase/rotkislashrotki | rotkehlchen/tests/external_apis/test_etherscan.py | test_etherscan.py | py | 2,080 | python | en | code | 0 | github-code | 6 |
3889512912 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 11:25:11 2017
Dempster-Shafer Combination rule
@author: Zhiming
"""
from numpy import *
def DSCombination (Dic1, Dic2):
## extract the frame dicernment
sets=set(Dic1.keys()).union(set(Dic2.keys()))
Result=dict.fromkeys(sets,0)
## C... | Zhiming-Huang/Dempster-shafer-combination-rules | DS.py | DS.py | py | 784 | python | en | code | 16 | github-code | 6 |
16312524711 | import jax.numpy as np
from jax import grad, nn, random, jit
from jax.experimental import stax, optimizers
from jax.experimental.optimizers import l2_norm
from jax.numpy import linalg
from jax.experimental.stax import Dense, Relu, Tanh, Conv, MaxPool, Flatten, Softmax, LogSoftmax, Sigmoid
from jax.tree_util import tree... | ChrisWaites/data-deletion | src/d2d/projected_mnist/debug_for_seth.py | debug_for_seth.py | py | 2,756 | python | en | code | 5 | github-code | 6 |
34197263982 | import sys, math
from math import pi as pi
import numpy as np
import cv2
from PyQt5.QtCore import QPoint, QRect, QSize, Qt, QPointF, QRectF, pyqtSignal, QTimer
from PyQt5.QtGui import (QBrush, QConicalGradient, QLinearGradient, QPainter, QPainterPath, QPalette, QPen, QPixmap, QPolygon, QRadialGradient, QColor, QTransfo... | RoboticsLabURJC/2016-tfg-irene-lope | AutoPark_Practice/referee.py | referee.py | py | 19,643 | python | en | code | 1 | github-code | 6 |
39610762661 | from nltk.corpus import brown
import nltk
cfd = nltk.ConditionalFreqDist(
(genre,word)
for genre in brown.categories()
for word in brown.words(categories=genre))
genre_word = [(genre, word)
for genre in ['news']
for word in brown.words(categories=genre)]
print(len(genre_word))
print(genre_word[:5]) | milliongashawbeza/PublicNLPA | counting_words.py | counting_words.py | py | 319 | python | en | code | 0 | github-code | 6 |
38290564345 | # Find the path with the maximum sum in a given binary tree.
# Write a function that returns the maximum sum.
# A path can be defined as a sequence of nodes between any two nodes and
# doesn’t necessarily pass through the root.
import math
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val =... | nanup/DSA | 8. Depth First Search Revisit I/124. Binary Tree Maximum Path Sum.py | 124. Binary Tree Maximum Path Sum.py | py | 1,614 | python | en | code | 0 | github-code | 6 |
31877451015 | import os
import math
import copy
import codecs
import numpy as np
import srt
import subprocess
import datetime
from utils import mkdir, basename_without_ext
from voice_detector import VoiceDetector
from tqdm import tqdm
def shift_by_delay(bin_arr2, delay_by_frames):
if delay_by_frames < 0:
return bin_arr... | derrick56007/getsub | src/get_sub.py | get_sub.py | py | 6,510 | python | en | code | 5 | github-code | 6 |
4397925600 | from multiprocessing import Process,Array
from time import time
import sqlite3
from .config import KASTEN_ANZ,VOK_DIR
class vokabelKartei(Process):
def __init__(self):
self.conn = sqlite3.connect(VOK_DIR+"kartei.sqlite")
self.conn.text_factory = str
self.c = self.conn.cursor()
self... | tuxor1337/voktrainer | vok/core/kartei.py | kartei.py | py | 7,065 | python | en | code | 1 | github-code | 6 |
41195169929 | import tensorflow.compat.v1 as tf
import pandas as pd
import numpy as np
import time
tf.disable_v2_behavior()
def filterData():
df = pd.read_csv('diabetic_data.csv')
print("how large the data sould be?")
data_size = input()
data = df.drop(['encounter_id', 'patient_nbr', 'weight', 'payer... | sschwarcz/Diabetic-Re-admission-prediction | Codes/SoftmaxTensorflow.py | SoftmaxTensorflow.py | py | 4,003 | python | en | code | 0 | github-code | 6 |
34493734325 | from typing import Dict, List, Optional, Tuple, Union
from flask import (
abort, g, jsonify, render_template, request, make_response, Response
)
from werkzeug.exceptions import (
BadRequest, Forbidden, HTTPException, InternalServerError, NotFound
)
from plot_weather import (BAD_REQUEST_IMAGE_DATA,
... | pipito-yukio/plot_weather_flaskapp | src/plot_weather/views/app_main.py | app_main.py | py | 26,178 | python | ja | code | 0 | github-code | 6 |
71888723067 | import numpy
from sklearn.metrics import cohen_kappa_score, classification_report
import torch
from torch.autograd import Variable
from tqdm import tqdm
import torch.nn as nn
from sklearn.metrics import cohen_kappa_score, classification_report
from models import FitNet_4
from torch import optim
import numpy as np
def... | Fivethousand5k/Pytorch-implemented-ECNN | eval.py | eval.py | py | 1,542 | python | en | code | 3 | github-code | 6 |
36096748364 | from threading import Thread
import time
import classifierAlexa
import classifier_pyqt5
def main():
try:
classifierAlexa_thread = Thread(target=classifierAlexa.app.run)
classifierAlexa_thread.start()
time.sleep(1)
classifier_thread = Thread(target=classifier_pyqt5.startApp())
... | KAIST-ITC/fall_detection | alexa_posture_classifier/main.py | main.py | py | 472 | python | en | code | 1 | github-code | 6 |
6871646913 | import numpy as np
from PIL import Image
def normalize(x):
min = np.min(x)
max = np.max(x)
print(min,max)
return ((x - min)/(max - min) * 255).astype(int)
W=np.load('./data/W.npy')
b=np.load('./data/b.npy')
zero = np.zeros(W.shape)
nag = normalize(np.minimum(W,0))
pos = normalize(np.maximum(W,0))
pri... | tuntunwin/tf-tutorial | mnist1-plotmodel.py | mnist1-plotmodel.py | py | 745 | python | en | code | 0 | github-code | 6 |
30709482723 |
import cv2 as cv
import numpy as np
from process import Resize, NormalizeImage
class PicoDetProcess():
def __init__(self,
trainsize=[320,320],
mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225],
score_threshold=0.4,
nms_thres... | guojin-yan/Automatic_aiming | aiming/person_process.py | person_process.py | py | 6,767 | python | en | code | 3 | github-code | 6 |
70383323069 | import copy
from typing import List, Optional
def deep_merge_dicts(original: dict, new_dict: dict) -> dict:
"""
Overview:
Merge two dicts by calling ``deep_update``
Arguments:
- original (:obj:`dict`): Dict 1.
- new_dict (:obj:`dict`): Dict 2.
Returns:
- merged_dict (:o... | opendilab/GoBigger | gobigger/utils/config_utils.py | config_utils.py | py | 2,978 | python | en | code | 483 | github-code | 6 |
34961662452 | import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
class DynamicEvolutionStats:
def __init__(self, seeds, specialist_type):
self.seeds = seeds
self.specialist_type = specialist_type
self.init_data()
def init_data(self):
self.da... | arthur-plautz/curriculum-learning | models/specialist/stats/dynamic_evolution_stats.py | dynamic_evolution_stats.py | py | 2,023 | python | en | code | 0 | github-code | 6 |
75342220666 | from django.shortcuts import render
from .forms import getData, getTraningInfo
import requests
from bs4 import BeautifulSoup
from datetime import date, datetime
import folium
import geocoder
# Create your views here.
runs = {}
def calculate_difference(key):
run_date_str = runs[key]["date"][:10] + " 0:0:0"
t... | kaczorwarka/Running-Events-Search-Engine-and-Traning-Plan-Generator | runsite/views.py | views.py | py | 26,067 | python | en | code | 0 | github-code | 6 |
19270736433 | named_params = {
"Rest_time_T": float,
"Duration_step": float,
"Record_every_dT": float,
"Record_every_dE": float,
"Record_every_dI": float,
"E_Range": int,
"I_Range": int,
"Current_step": float,
"Voltage_step": float,
"Scan_Rate": float,
"vs_initial": bool,
"Test1_Config... | dgbowl/tomato | src/tomato/drivers/biologic/tech_params.py | tech_params.py | py | 2,286 | python | en | code | 2 | github-code | 6 |
41714902184 | from Crypto.Util.number import getPrime
from Crypto.Util.number import inverse
import hashlib
import socket
from threading import Thread
host = 'localhost'
port = 6000
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
mysocket.connect((host, port))
except socket.error :
print("connexio... | samyberkane23/chat_s-curis- | client.py | client.py | py | 2,458 | python | en | code | 0 | github-code | 6 |
14852849903 | from collections import ChainMap
import yaml
with open('eve_static_data/invFlags.yaml') as flags_file:
INV_FLAGS = {item['flagID']: item for item in yaml.full_load(flags_file)}
INVENTORY_POSITIONS = [
*range(92, 99+1), # Rigs
*range(27, 34+1), # High Slots
*range(19, 26+1), # Med Slots
*range(... | DeForce/py_killboard | helpers/static.py | static.py | py | 386 | python | en | code | 1 | github-code | 6 |
41860678548 | import logging
log = logging.getLogger(__name__)
import re
import requests
from bs4 import BeautifulSoup
try:
# Python 2 has a standard urlparse library
from urlparse import urlparse, ParseResult
except:
# Python 3 has the same library hidden in urllib.parse
from urllib.parse import urlparse, ParseRes... | xethorn/metadata_parser | metadata_parser/__init__.py | __init__.py | py | 25,325 | python | en | code | null | github-code | 6 |
43967691056 | #!/usr/bin/env python
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="split blast results by organism")
parser.add_argument("blast", type=argparse.FileType("r"))
args = parser.parse_args()
blast = [x.split("\t") for x in args.blast.readlines()]
for row in ... | TAMU-CPT/galaxy-tools | tools/blast/split_blast.py | split_blast.py | py | 576 | python | en | code | 5 | github-code | 6 |
18075698551 | def plunder(city, people_to_kill, gold_to_steal):
town = [t for t in towns if t.name == city][0]
town.population -= people_to_kill
town.gold -= gold_to_steal
print(f"{city} plundered! {gold_to_steal} gold stolen, {people_to_kill} citizens killed.")
if town.population <= 0 or town.gold <= 0:
... | liusska/Python-Fundamentals-Jan-2021 | Final Exam Solutions/04.04.2020_2/p!rates_CLASS_solution_03.py | p!rates_CLASS_solution_03.py | py | 2,146 | python | en | code | 0 | github-code | 6 |
11214657296 | import pika
import sys
conn = pika.BlockingConnection(pika.URLParameters('amqp://guest:guest@localhost:25672/%2F'))
channel = conn.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or "Hello Worl... | lamida/rabbit-hole | 04-routing/emit_log_direct.py | emit_log_direct.py | py | 465 | python | en | code | 0 | github-code | 6 |
39255343614 | from django.conf.urls import url
from network.views import views_auth
from network.views import views_app
urlpatterns = [
# Main page
url(r'^home/(?P<msg>.*)$', views_auth.main_page, name="Home"),
# url(r'$', views_auth.main_page, name="Home"),
# Auth urls
url(r'^login/(?P<info>.*)$', views_aut... | Sipleman/Course-work_SocialNetwork | network/urls.py | urls.py | py | 1,612 | python | en | code | 0 | github-code | 6 |
4818229922 | import numpy as np
def linan(s1, s2):
try:
a1, b1, c1 = map(float, s1.split(" "))
a2, b2, c2 = map(float, s2.split(" "))
a = np.array([[a1, b1], [a2, b2]])
b = np.array([c1, c2])
solution = np.linalg.solve(a, b)
return f"{solution[0]} {solution[1]}"
except np.li... | SmartOven/itmo-ml | lab1/task1.py | task1.py | py | 439 | python | en | code | 0 | github-code | 6 |
11995663710 | #!/usr/bin/env python3
import rospy
import numpy as np
from geometry_msgs.msg import Point, PointStamped
from queenie.msg import ExtremePoints
import tf2_ros
import tf2_geometry_msgs
import time
class PointTransform:
def __init__(self):
self.tf_buffer = tf2_ros.Buffer() # tf buffer length
se... | arehman1806/queenie | src/nodes/point_transform.py | point_transform.py | py | 2,827 | python | en | code | 0 | github-code | 6 |
30543883588 | from . import pblm
import sys
import torch
import torch.nn as nn
class CNN_A(pblm.PrebuiltLightningModule):
def __init__(self, classes):
super().__init__(self.__class__.__name__)
# Model Layer Declaration
self.conv1 = nn.Conv1d(1, 16, kernel_size=5, stride=2)
self.conv2 = nn.Conv1... | kendreaditya/heart-auscultation | src/models/modules/CNN/CNN.py | CNN.py | py | 1,135 | python | en | code | 2 | github-code | 6 |
7584763107 | import random
import os
from modnn import Neuron
from modnn import Connection
from modnn import utils
class Genome:
def __init__(self, config):
self.config = config
self.input_num = self.config['INPUT_NUM']
self.output_num = self.config['OUTPUT_NUM']
self.normal_num = self.config['N... | kato-mahiro/modnn | modnn/genome.py | genome.py | py | 4,986 | python | en | code | 0 | github-code | 6 |
30754324975 | from heapq import heappop, heappush
n = int(input())
a = list(map(int, input().split()))
hp = 0
ans = 0
pt = list()
for i in range(n):
if a[i] > 0:
hp += a[i]
ans += 1
elif hp + a[i] >= 0:
hp += a[i]
ans += 1
heappush(pt, a[i])
elif pt:
a1 = heappop(pt)
... | Tanguyvans/Codeforces | 723/C2.py | C2.py | py | 459 | python | en | code | 0 | github-code | 6 |
36317150759 | import numpy as np
def P_generator(MatingPool,Boundary,Coding,MaxOffspring):
# % 交叉, 变异并生成新的种群
# % 输入: MatingPool, 交配池, 其中每第i个和第i + 1
# 个个体交叉产生两个子代, i为奇数
# % Boundary, 决策空间, 其第一行为空间中每维的上界, 第二行为下界
# % Coding, 编码方式, 不同的编码方式采用不同的交叉变异方法
# % MaxOffspring, 返回的子代数目, 若缺省则返回所有产生的子代, 即和交配池的大小相同
# % 输出: Offspring, 产生的子代... | DevilYangS/NSGA-II-python | NSGA_II/public/P_generator.py | P_generator.py | py | 3,156 | python | en | code | 5 | github-code | 6 |
35782338526 | #%%
import numpy as np
import matplotlib.pyplot as plt
#%%
x = np.arange(0, 6 * np.pi, 0.025)
y_true = np.sin(x)
y = y_true + np.random.normal(scale=1, size=len(x))
plt.scatter(x, y, color="k")
plt.plot(x, y_true, color="red")
#%%
np.random.seed(42)
from sklearn.ensemble import HistGradientBoostingRegressor
from sk... | moritzwilksch/DataScienceEducation | ML-Basics/fancy_gif.py | fancy_gif.py | py | 1,801 | python | en | code | 1 | github-code | 6 |
70337573629 | import math
import copy
import numpy as np
import pprint
import torch
import torch.nn as nn
import torch.nn.functional as F
from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats
import slowfast.models.losses as losses
import slowfast.models.optimizer as optim
import slowfast.utils.checkpoint as cu
import sl... | alimottaghi/slowfast | tools/train_mme.py | train_mme.py | py | 22,644 | python | en | code | 0 | github-code | 6 |
26225206883 | # Unedited
def reallocate(banks):
n = len(banks)
i = banks.argmax()
k = banks[i]
banks[i] = 0
for j in range(1, k + 1):
banks[(i + j) % n] += 1
k -= 1
counter = 0
while True:
reallocate(banks)
counter += 1
tup = tuple(banks)
if tup in tracker:
print(counter,... | pirsquared/Advent-of-Code | 2017/Day06.py | Day06.py | py | 415 | python | en | code | 1 | github-code | 6 |
23061764300 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import re
import os
import random
import time
from time import sleep
import json
from collections import OrderedDict
def dropSameListEle(inList):
outList=[]
for x in inList:
if x not in outList and x != '':
outList.append(x)
... | pplost/for-test | tools/新建文件夹/fetch - 副本.py | fetch - 副本.py | py | 3,180 | python | en | code | 0 | github-code | 6 |
34508776850 | # https://practice.geeksforgeeks.org/problems/maximum-index-1587115620/1/?track=md-arrays&batchId=144
def max_index(a,n ):
max_diff = -1
for i in range(n):
j = n-1
while i < j:
if a[i] <=a[j] and max_diff < (j-i):
max_diff = j-i
j = j-1
return ... | ved93/deliberate-practice-challenges | code-everyday-challenge/n195_max_index.py | n195_max_index.py | py | 1,399 | python | en | code | 0 | github-code | 6 |
19115978156 | s = input()
count = 0
for i in s:
if i == 'R':
count += 1
elif i != 'R' and count == 0:
continue
else:
break
print(count)
'''
#alternative solution
S = input()
print(S.count("R") if S.count("R") != 2 else 2 if S[1] == "R" else 1)#See separate sheet
'''
| NPE-NPE/code | python/abc/175/a.py | a.py | py | 290 | python | en | code | 0 | github-code | 6 |
21844969705 | texts = []
for i in range(4):
text = input()
texts.append(text)
length = int(input("Enter length you want to check: "))
is_found = False
for i in texts:
if length > len(i):
is_found = True
else:
is_found = False
if is_found:
print("Available")
else:
print("Unavailable") | Areg14/DroneEduLab | Lesson12/Problem6.py | Problem6.py | py | 313 | python | en | code | 0 | github-code | 6 |
2518952492 | # 删除一个字符串所有的a,并复制所有的b
def str_remove(str):
n = len(str)
count = 0
i = 0
j = 0
while i < len(str):
if str[i] == "a":
str= str[:i] + str[i+1:]
i -=1
i +=1
while j < len(str):
if str[j] =="b":
count +=1
j +=1
return str,count... | youyuebingchen/Algorithms | qiyue_alg/str_02.py | str_02.py | py | 1,054 | python | en | code | 0 | github-code | 6 |
9179526990 | import os
import stat
import string
from absl.testing import absltest
from src.test.py.bazel import test_base
# pylint: disable=g-import-not-at-top
if os.name == 'nt':
import win32api
class LauncherTest(test_base.TestBase):
def _buildJavaTargets(self, bazel_bin, binary_suffix):
self.RunBazel(['build', '//fo... | bazelbuild/bazel | src/test/py/bazel/launcher_test.py | launcher_test.py | py | 26,523 | python | en | code | 21,632 | github-code | 6 |
24293929563 | def sqrt(x):
low = 0
high = x
while high - low > 0.001:
mid = (high + low) / 2
if abs(mid ** 2 - x) < 0.0001:
return mid
if mid ** 2 > x:
high = mid
elif mid ** 2 < x:
low = mid
return round((high+low)/2, 3)
def main():
assert sqr... | ckallum/Daily-Interview-Pro | solutions/square_root.py | square_root.py | py | 374 | python | en | code | 16 | github-code | 6 |
32505732795 | # -*- coding: utf-8 *-
import pprint
import re
import sys
import importlib
from Symfopy.Component.HttpFoundation import Request, Response
class Router(object):
var_regex = re.compile(r'\{(\w+)(?::([^}]+))?\}')
def __init__(self, routes = {}):
self.routes = dict()
for name in routes:
... | alculquicondor/Symfopy | vendor/Symfopy/Component/Routing.py | Routing.py | py | 3,380 | python | en | code | 0 | github-code | 6 |
2398607314 | """
Makes a movie of the previously downloaded GEOS data
"""
import os
import pathlib
from typing import List, Tuple, Union
import numpy as np
import matplotlib.pyplot as plt
import DownloadData
import ReadNetCDF4
import VideoWriter
plt.style.use('myDarkStyle.mplstyle')
# ===========================... | dpilger26/GOES | scripts/MakeMovie.py | MakeMovie.py | py | 7,699 | python | en | code | 1 | github-code | 6 |
34291432876 | import os, csv
class CarBase:
def __init__(self, brand, photo_file_name, carrying):
self.photo_file_name = photo_file_name
self.brand = brand
self.carrying = carrying
def get_photo_file_ext(self):
return os.path.splitext(self.photo_file_name)[1]
class Car(CarBase):
def __... | evgp/learning_python | w3_cars/w3_2_autodrom.py | w3_2_autodrom.py | py | 2,251 | python | en | code | 0 | github-code | 6 |
22165701043 | inteiros = [1,3,4,5,7,8,9]
pares = [x for x in inteiros if x % 2 == 0]
print(pares)
quadrados = [n*n for n in inteiros]
print(quadrados)
frutas = ["maçã", "banana", "laranja", "melancia"]
frutas = [fruta.upper() for fruta in frutas]
print(frutas) | sergiaoprogramador/introducaozinha-rapida-python | list_comprehensions.py | list_comprehensions.py | py | 250 | python | pt | code | 0 | github-code | 6 |
43926964501 | # Coda con priorita' per creare la frontiera
from queue import PriorityQueue
# put per inserire
# get per prendere
class StrutturaMappa():
def __init__(self):
self.mappa = dict()
def aggiungiVia(self, viaInput):
# inserisce nodo senza collegamento e senza peso
self.mappa.update({v... | GianmarcoMo/ProgettoICon | grafo.py | grafo.py | py | 3,474 | python | it | code | 0 | github-code | 6 |
75079239548 | from dal import autocomplete
from django import forms
from .models import Tag
class TForm(forms.ModelForm):
class Meta:
model = Tag
fields = ('Tag_name')
widgets = {
'Tag_name': autocomplete.ModelSelect2(url='test')
}
| codebottlehun/WithMe | tag/forms.py | forms.py | py | 270 | python | en | code | 0 | github-code | 6 |
36090200838 | """Some useful functions to deal with GitHub."""
import datetime
from github import Github
from github import UnknownObjectException
import click
class GitHubMux:
"""Class that let's you operate in multiple repos of the same org at the same time."""
def __init__(self, organization, token, exclude):
... | napalm-automation/tooling | gh_tools/github_helpers.py | github_helpers.py | py | 13,728 | python | en | code | 1 | github-code | 6 |
8417498337 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
... | SarthakPradhan/LeetCode | remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.py | remove-duplicates-from-sorted-list.py | py | 679 | python | en | code | 0 | github-code | 6 |
2736199577 | import keras
from keras import backend as K
from keras.callbacks import Callback
import numpy as np
class BitsLogger(Callback):
def __init__(self, nConvs=9, **kwargs):
self.norm = 1./np.log(float(nConvs))
self.bits_history=[]
self.filterLayers=[]
super(BitsLogger, self).__init__(**kwargs)
def o... | twoev/APEMEN | utils/callbacks.py | callbacks.py | py | 2,012 | python | en | code | 0 | github-code | 6 |
25226116736 | from sklearn import datasets
import pandas as pd
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris.data)
iris_df.columns = iris.feature_names
iris_df['target'] = iris.target
# original target = 0,1,2 int32
print(iris_df.target)
# changing them by using DF.astype(type)
print(iris_df.target.astype(float)) | HawkingLaugh/Data-Processing-Using-Python | Week4/28. inconsistent_data_handling.py | 28. inconsistent_data_handling.py | py | 313 | python | en | code | 0 | github-code | 6 |
35425394354 | from yaml_parser import parse_yaml
from voluptuous import Schema,Object, Range, Coerce, All, Any, Optional, Lower, Invalid
import re
import sys
import argparse
"""
Python YAML validator
"""
list_of_ints = All([Coerce(int)], msg='invalid list of ints')
from datetime import datetime
def check_date(datestring):
try... | philippmack/europython2015-pmack | config/validator.py | validator.py | py | 1,633 | python | en | code | 1 | github-code | 6 |
3008185523 | # Day 8
import numpy as np
from copy import copy
def run_part_1(data):
hidden, max_x, max_y = prepare_data(data)
for x in range(1, max_x - 1):
for y in range(1, max_y - 1):
sides = [
data[x, :y], data[x, y+1:],
data[:x, y], data[x+1:, y]]
if any(... | swemoney/AdventOfCode | 2022/08/day.py | day.py | py | 1,334 | python | en | code | 0 | github-code | 6 |
41646398531 | """ Module containing routines to setup the training of policies.
"""
import argparse
from typing import Optional, Sequence
from aizynthfinder.training.utils import Config
from aizynthfinder.training.keras_models import (
train_expansion_keras_model,
train_filter_keras_model,
train_recommender_keras_model,... | AlanHassen/modelsmatter | aizynthfinder/training/training.py | training.py | py | 1,085 | python | en | code | 1 | github-code | 6 |
3749581806 | import glob
import platform
import setuptools
import Cython.Build
# By compiling this separately as a C library, we avoid problems
# with passing C++-specific flags when building the extension
lrslib = ('lrslib', {'sources': glob.glob("solvers/lrs/*.c")})
cppgambit = setuptools.Extension(
"pygambit.lib.libgambit"... | vignesh7056/gambit | src/setup.py | setup.py | py | 2,265 | python | en | code | null | github-code | 6 |
6066153310 | import pygame
from _draw import *
from _utils import *
class gui():
def __init__(self,
white,
screen,
width,
height,
smallNokiaFont,
hugeNokiaFont,
font,
bigFont,
hugeFont,
smallFont,
nanoFont,
themeColo... | murchie85/bumdee | _gui.py | _gui.py | py | 12,565 | python | en | code | 0 | github-code | 6 |
73787039549 | """
Code to explore the PDF and CDF of weight distributions.
We use truncated lognormals to define the distribution of excitatory connections.
We scale that by -8 for inhibitory connections.
We represent the inhibitory connections with a negative number as a convention to be consistent
with the network simulator (NEST... | comp-neural-circuits/tctx | tctx/analysis/wdist.py | wdist.py | py | 4,725 | python | en | code | 1 | github-code | 6 |
24222566552 | from tkinter import*
from PIL import Image ,ImageTk
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
import urllib.request
urllib.request.urlretrieve(
'https://iocl.com/images/indane_1.jpg',
"indane1.png")
urllib.request.urlretrieve(
'https://cdn5.newsnationtv.com/imag... | anonymouslyfadeditzme/Anonymously-Faded | booking.py | booking.py | py | 19,472 | python | en | code | 0 | github-code | 6 |
43256048913 | import os
import xlsxwriter
# Change basepath if applicable
basepath = "C:\\Users\\AYuen\\Environmental Protection Agency (EPA)\\ECMS - Documents\\newfiles\\"
workbook = xlsxwriter.Workbook(basepath+'fileandid.xlsx')
worksheet = workbook.add_worksheet("Sheet 1")
# Start from the first cell.
# Rows and columns are z... | USEPA/Document_Processing_Scripts | getidfilename.py | getidfilename.py | py | 827 | python | en | code | 1 | github-code | 6 |
14835956764 | import torch
import torchaudio
import numpy as np
import opensmile
from collections import namedtuple
from .scan_data import scan_rootdir, CHANNELS
from .load_data import load_anno_tensor, load_vad_df
from .segment_data import SegmentEgs
class ChunkOpenSmileDataSet:
def __init__(self, rootdir,
... | medbar/maga_sis | 3/ULM/utils/chunk_opensmile_dataset.py | chunk_opensmile_dataset.py | py | 3,414 | python | en | code | 0 | github-code | 6 |
17388621437 | # Import necessary Tkinter and sqlite3 libraries.
import tkinter as tk
import sqlite3
from sqlite3 import Error
from PIL import Image, ImageTk
import tkinter.messagebox as messagebox
# Making things object oriented, define a class.
class School_Data:
'''Constructor to initialize the GUI window'''
def __init__(... | rohan-sahuji/Repo1 | Tkinter_GUI.py | Tkinter_GUI.py | py | 17,391 | python | en | code | 0 | github-code | 6 |
14003038546 | from app.custom_queue import CustomQueue
from app.logger import get_logger
from datetime import datetime, timedelta
LOGGER = get_logger(__name__)
QUEUE_MAX_SIZE = 20
class Queues():
def __init__(self):
self.LS = CustomQueue(QUEUE_MAX_SIZE, 'LeftSingle')
self.LT = CustomQueue(QUEUE_MAX_SIZE, 'Left... | ViniciusLinharesAO/ski-slope-problem-uece-ppc | app/queues.py | queues.py | py | 3,005 | python | en | code | 0 | github-code | 6 |
18598274205 | import requests
from data_access.openWeatherMap.client import OpenWeatherMap
from business_logic.services import GetWeatherService
from config import OWM_API_KEY, OWM_BASE_URL
from .server import Request, Response
def get_weather_controller(request: Request) -> Response:
cities = request.params.get('query')[0]
... | pyteacher123/py35-onl | weather_app_refactored/presentation/web/application.py | application.py | py | 2,199 | python | en | code | 2 | github-code | 6 |
6679634602 | import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
import argparse, sys
import joblib
import warnings
warnings.filterwarnings('ignore')
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
from torch.util... | gdqb233/inm363 | baseline.py | baseline.py | py | 11,328 | python | en | code | 0 | github-code | 6 |
38144650744 | import unittest
from src.BinaryTree import BinaryTree, BinaryTreeNode
class TestBinaryTree(unittest.TestCase):
"""
This class tests the BinaryTree class
"""
def test_constructor(self):
"""
Tests the state of a binary tree's root after initialization
"""
try: # test inv... | snitkdan/BlackJack | test/test_binarytree.py | test_binarytree.py | py | 2,631 | python | en | code | 0 | github-code | 6 |
21051188362 | from django.db import models
from django_countries.fields import CountryField
from product.models import product, product_version
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth import get_user_model
User = get_user_model()
from decimal import Decimal
from django.con... | Shafag42/SuperB_E-commerce | order/models.py | models.py | py | 7,334 | python | en | code | 1 | github-code | 6 |
42539411350 | from django.shortcuts import render, redirect
from .models import *
import os
from django.conf import settings
from django.http import HttpResponse
import json
# Create your views here.
def cargarInicio(request):
productos = Producto.objects.all()
producto_perros = Producto.objects.filter(categoria_id=1)
... | GuillermoVillacuraTorres/PGY3121-012D | django/apps/Tienda/views.py | views.py | py | 2,897 | python | es | code | null | github-code | 6 |
33706250276 | import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QGroupBox, QRadioButton
aplicacao = QApplication(sys.argv)
janela = QMainWindow()
# setGeometry(esquerda, topo, largura, altura)
janela.setGeometry( 100, 50, 300, 200 )
janela.setWindowTitle("Primeira Janela")
# cria uma instancia de um grupo de sel... | leuribeiru/QtforPhyton | componentes_basicos/radio.py | radio.py | py | 865 | python | pt | code | 1 | github-code | 6 |
32605878813 | import discord
import youtube_dl
from bot_token import TOKEN
if not TOKEN:
raise ValueError("Please add your token to bot_token.py")
client = discord.Client()
@client.event
async def on_message(message):
if message.author== client.user :
return
elif message.content.startswith("*l"):
msg =... | F3YoD/Bot-python | tamer2.py | tamer2.py | py | 669 | python | en | code | 0 | github-code | 6 |
43529823665 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 22 11:51:37 2019
@author: javie
"""
import plotly_express as px
from plotly.offline import plot
def pl(df, r, var):
tmp = df[df.randomSeed.isin(r)]
plot(px.line(tmp, height=300 * len(r), x="tick",
y = var,
color="FirmNumID"... | javiergarciasanchez/businessCycles | businessCycles/exploreData/Python/Graphs_plotly.py | Graphs_plotly.py | py | 871 | python | en | code | 0 | github-code | 6 |
35049082181 | """
3D convolutions using GPU accelereration for Theano (using conv2d)
https://github.com/jaberg/TheanoConv3d2d
"""
import theano
from theano.gradient import DisconnectedType
from theano.gof import Op, Apply
from theano import tensor
import theano.sandbox.cuda as cuda
def get_diagonal_subtensor_view(x, i0, i1):
... | lpigou/Theano-3D-ConvNet | convnet3d/conv3d2d.py | conv3d2d.py | py | 10,163 | python | en | code | 83 | github-code | 6 |
1360579310 | import pandas as pd
import pathlib as pl
import numpy as np
import RootPath
from abc import abstractmethod
from Utils.Data.Features.RawFeatures import *
from Utils.Data.Dictionary.MappingDictionary import *
def map_column_single_value(series, dictionary):
mapped_series = series.map(dictionary).astype(np.int32)
... | MaurizioFD/recsys-challenge-2020-twitter | Utils/Data/Features/MappedFeatures.py | MappedFeatures.py | py | 8,608 | python | en | code | 39 | github-code | 6 |
14731423365 | from datetime import datetime
import pandas as pd
import pydash as _
from bs4 import BeautifulSoup
from Base import NSEBase
class NSE(NSEBase):
"""
A class to interact with NSE (National Stock Exchange) API.
Attributes:
valid_pcr_fields : list of valid fields for put-call ratio calc... | Sampad-Hegde/Bharat-SM-Data | Bharat_sm_data/Derivatives/NSE.py | NSE.py | py | 13,281 | python | en | code | 2 | github-code | 6 |
1592231392 | import asyncio
from flask import Blueprint, abort, flash, redirect, render_template, request, jsonify, url_for, Response
from werkzeug.utils import secure_filename
import socket
from flask_socketio import SocketIO, emit
from app import app, db, socketio
import os
import time
HOST = "127.0.1.1"
WEBSOCKET_PORT = 9999
CH... | isaacbrasil/My-youtube-flask | app/blueprints/client.py | client.py | py | 5,180 | python | pt | code | 0 | github-code | 6 |
10242082365 | # -*- coding: utf-8 -*-
"""The Simulator takes in a :obj:`seagull.Board`, and runs a simulation given a
set number of iterations and a rule. For each iteration, the rule is applied to
the Board in order to evolve the lifeforms. After the simulation, run
statistics are returned.
.. code-block:: python
import seag... | ljvmiranda921/seagull | seagull/simulator.py | simulator.py | py | 6,209 | python | en | code | 167 | github-code | 6 |
3116557557 |
import torch
import torch.nn as nn
from torch.optim import Adam
import torch.nn.functional as F
from random import randint
import numpy as np
# import subprocess
# import multiprocessing
# import concurrent.futures
from time import time
from math import sqrt
CHANNEL = 256
BLOCKNUM = 40
BOARDSIZE = 8
BATCH = 50
EPOCHS... | wxwoo/yanxue | train_py.py | train_py.py | py | 12,641 | python | en | code | 1 | github-code | 6 |
22397762010 | import cv2
import pandas as pd
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class COVIDChestXRayDataset(Dataset):
def __init__(self, path, size=128, augment=None):
super(COVIDChestXRayDataset, self).__init__()
print('{} initialized with size={}, augment={}'.format(s... | defeatcovid19/defeatcovid19-net-pytorch | datasets/covid_chestxray_dataset.py | covid_chestxray_dataset.py | py | 2,205 | python | en | code | 9 | github-code | 6 |
71689560509 | # Import packages.
import glob
import numpy as np
import os
# import cvxpy as cp
##################################################################################
# Data import
##################################################################################
folder = 'runD'
n_robots = '30'
min_votes = '3... | NESTLab/DistributedSemanticMaps | PythonScripts/vscbpp_cluster.py | vscbpp_cluster.py | py | 8,797 | python | en | code | 0 | github-code | 6 |
26470760841 | """ Problem 3: Largest Prime Factor
https://projecteuler.net/problem=3
Goal: Find the largest prime factor of N.
Constraints: 10 <= N <= 1e12
Fundamental Theorem of Arithmetic: There will only ever be a unique set of prime
factors for any number.
e.g.: N = 10
prime factors = {2, 5}
largest = 5
"""
from... | bog-walk/project-euler-python | solution/batch0/problem3.py | problem3.py | py | 1,835 | python | en | code | 0 | github-code | 6 |
10918154737 | import os
import ast
import subprocess
import uuid
import json
import hashlib
import socket
import psutil
from ipykernel.ipkernel import IPythonKernel
def make_except_safe(code):
code = code.replace('\n', '\n ')
code = 'try:\n ' + code
code = code + '\nexcept: pass\n'
try:
ast.parse(code)
... | depaul-dice/sciunit-NBv1 | __main__.py | __main__.py | py | 4,282 | python | en | code | 0 | github-code | 6 |
40565271392 | # Crea una función llamada promedio que tome una lista de números como parámetro y devuelva el promedio de esos números.
usuario = input(
'Ingresa un una lista de numeros separados por coma "," : ').split(",")
def promedio(args):
acumulador = 0
cantidad = len(args)
for i in args:
acumulador ... | maximiliano1997/informatorio-2023 | Week-4/ejercicios/ejercicio9.py | ejercicio9.py | py | 413 | python | es | code | 0 | github-code | 6 |
42663501049 | import os
import torch
import datetime
import numpy as np
import pandas as pd
from src.attn_analysis import gradcam
from src.attn_analysis import iou_analysis
from src.attn_analysis import blue_heatmap
from src.attn_analysis import extract_disease_reps
from src.attn_analysis import make_2d_plot_and_3d_gif
import warn... | rachellea/explainable-ct-ai | src/run_attn_analysis.py | run_attn_analysis.py | py | 26,139 | python | en | code | 3 | github-code | 6 |
33180088903 | from itertools import *
def repl(a):
if a == '01': return 712
elif a == '02': return 673
elif a == '03': return 1075
elif a == '04': return 875
elif a == '05': return 1622
elif a == '06': return 423
elif a == '10': return 712
elif a == '12': return 1385
elif a == '13': retu... | Ethryna/InfTasks | 2 полугодие/airports.py | airports.py | py | 2,639 | python | en | code | 2 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.