uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
741321b89ab548c525901a0d
train
class
class _ROIAlign(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = input...
class _ROIAlign(Function): @staticmethod
def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = input.size() output = _C.roi_align_forward...
(c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from .. import _C # from apex import amp class _ROIAlign(Function): @staticmethod
73
73
244
10
62
Chillee/benchmark
torchbenchmark/models/maskrcnn_benchmark/maskrcnn_benchmark/layers/roi_align.py
Python
_ROIAlign
_ROIAlign
12
45
12
13
5019a3c15d221492b08de9efe537acfa484ca259
bigcode/the-stack
train
1fa2ac26cabee7ee0d5ad9c2
train
function
def record(testsignal,fs,inputChannels,outputChannels): sd.default.samplerate = fs sd.default.dtype = 'float32' print("Input channels:", inputChannels) print("Output channels:", outputChannels) # Start the recording recorded = sd.playrec(testsignal, samplerate=fs, input_mapping = inputChannel...
def record(testsignal,fs,inputChannels,outputChannels):
sd.default.samplerate = fs sd.default.dtype = 'float32' print("Input channels:", inputChannels) print("Output channels:", outputChannels) # Start the recording recorded = sd.playrec(testsignal, samplerate=fs, input_mapping = inputChannels,output_mapping = outputChannels) sd.wait() ret...
import os from scipy.io.wavfile import write as wavwrite import numpy as np import sounddevice as sd #-------------------------- def record(testsignal,fs,inputChannels,outputChannels):
41
64
91
13
28
Felix-Yan/pyrirtool
utils.py
Python
record
record
8
19
8
9
31236b7fcb2bfafb8d46e66ded4b805484ef3d19
bigcode/the-stack
train
191e0a239addd733414195e8
train
function
def saverecording(RIR, RIRtoSave, testsignal, recorded, fs): dirflag = False counter = 1 dirname = 'recorded/newrir1' while dirflag == False: if os.path.exists(dirname): counter = counter + 1 dirname = 'recorded/newrir' + str(counter) ...
def saverecording(RIR, RIRtoSave, testsignal, recorded, fs):
dirflag = False counter = 1 dirname = 'recorded/newrir1' while dirflag == False: if os.path.exists(dirname): counter = counter + 1 dirname = 'recorded/newrir' + str(counter) else: os.mkdir(dirname) di...
,outputChannels): sd.default.samplerate = fs sd.default.dtype = 'float32' print("Input channels:", inputChannels) print("Output channels:", outputChannels) # Start the recording recorded = sd.playrec(testsignal, samplerate=fs, input_mapping = inputChannels,output_mapping = outputChannels) ...
105
105
350
20
85
Felix-Yan/pyrirtool
utils.py
Python
saverecording
saverecording
23
54
23
24
5fa79e3d20de94414bd32523b66c4bda54f25a59
bigcode/the-stack
train
927c524cfc12c1103711ad92
train
class
class mercado (Exchange): def describe(self): return self.deep_extend(super(mercado, self).describe(), { 'id': 'mercado', 'name': 'Mercado Bitcoin', 'countries': ['BR'], # Brazil 'rateLimit': 1000, 'version': 'v3', 'has': { ...
class mercado (Exchange):
def describe(self): return self.deep_extend(super(mercado, self).describe(), { 'id': 'mercado', 'name': 'Mercado Bitcoin', 'countries': ['BR'], # Brazil 'rateLimit': 1000, 'version': 'v3', 'has': { 'CORS': True, ...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import ArgumentsReq...
96
256
4,194
5
90
alok46/ccxt
python/ccxt/mercado.py
Python
mercado
mercado
13
466
13
14
632cc7109bb35153f548206600152bf3ea461e64
bigcode/the-stack
train
91d06e72bcb0bf60432957a7
train
function
def permission(db): key = db.db.reference("App").get()["key"] cipher_suite = Fernet(key) with open('.env/permission.bin', 'rb') as file_object: for line in file_object: encryptedpwd = line uncipher_text = (cipher_suite.decrypt(encryptedpwd)) plain_text_encryptedpassword = bytes(uncipher_text).decode("u...
def permission(db):
key = db.db.reference("App").get()["key"] cipher_suite = Fernet(key) with open('.env/permission.bin', 'rb') as file_object: for line in file_object: encryptedpwd = line uncipher_text = (cipher_suite.decrypt(encryptedpwd)) plain_text_encryptedpassword = bytes(uncipher_text).decode("utf-8") #convert to st...
admin_key.txt","r") as admin_key: output = admin_key.read().split("\n") os.system("rm admin_key.txt") return output def upload_book(self,name,path): self.storage.blob("books/"+name).upload_from_filename(path) return True def permission(db):
64
64
113
4
59
OgiBalboa/E-Book_Cryptology
db.py
Python
permission
permission
42
53
42
42
38afe76b24b3fa10f5ae1648569bc0f132f63b20
bigcode/the-stack
train
b682162cd9edee3a1b782f1f
train
class
class db: def __init__(self): cred = credentials.Certificate('.env/marun-bks.json') self.firebase = firebase.Firebase(config) #self.storage = self.firebase.storage() self.auth = self.firebase.auth() self.user = None self.app = firebase_admin.initialize_app(cred,config) self.books = db_.reference(...
class db:
def __init__(self): cred = credentials.Certificate('.env/marun-bks.json') self.firebase = firebase.Firebase(config) #self.storage = self.firebase.storage() self.auth = self.firebase.auth() self.user = None self.app = firebase_admin.initialize_app(cred,config) self.books = db_.reference("books") ...
et import firebase import firebase_admin from firebase_admin import credentials,storage,auth from firebase_admin import db as db_ import sys # Fetch the service account key JSON file contents import base64 # Initialize the app with a service account, granting admin privileges import time sys.path.append(".env...
74
74
248
3
70
OgiBalboa/E-Book_Cryptology
db.py
Python
db
db
15
40
15
15
14327186464f28c0d61be6b36f92fbd563812469
bigcode/the-stack
train
a0da7264e5200c8940864f66
train
class
class Featurizer: @classmethod def populate_parser(cls, parser): parser.add_argument('--model', type=str, choices=['decoar', 'decoar2', 'bertphone'], help="Which model to featurize with") parser.add_argument('--params', type=str, help="Model parameter file") par...
class Featurizer: @classmethod
def populate_parser(cls, parser): parser.add_argument('--model', type=str, choices=['decoar', 'decoar2', 'bertphone'], help="Which model to featurize with") parser.add_argument('--params', type=str, help="Model parameter file") parser.add_argument('--gpu', type=int, ...
import argparse import logging import math from pathlib import Path from subprocess import check_call, CalledProcessError from tempfile import TemporaryDirectory import kaldi_io import torch import numpy as np from collections import OrderedDict class Featurizer: @classmethod
58
130
434
9
48
ishine/speech-representations
src/speech_reps/featurize.py
Python
Featurizer
Featurizer
14
68
14
17
6622d36b46d0bd4010a75f6ff22258548d4a9a1a
bigcode/the-stack
train
c3096ff1e72af942acfae901
train
class
class DeCoARFeaturizer(Featurizer): def __init__(self, params_file, gpu=None): super().__init__() # Load the model from .models.decoar import DeCoAR self._model = DeCoAR() models = torch.load(params_file)['model'] component_state_dict = OrderedDict() for k...
class DeCoARFeaturizer(Featurizer):
def __init__(self, params_file, gpu=None): super().__init__() # Load the model from .models.decoar import DeCoAR self._model = DeCoAR() models = torch.load(params_file)['model'] component_state_dict = OrderedDict() for key in models.keys(): compo...
CoAR2Featurizer(params_file, args.gpu) elif args.model.startswith('bertphone'): featurizer = BertPhoneFeaturizer(params_file, args.gpu) if args.in_wav and args.out_npy: in_wav = Path(args.in_wav) out_npy = Path(args.out_npy) featurizer.wav_to_npy(in_wav,...
222
222
741
13
208
ishine/speech-representations
src/speech_reps/featurize.py
Python
DeCoARFeaturizer
DeCoARFeaturizer
71
152
71
73
0a38f3d1417cf7b3a3d5bf7da0f76ee986a2717d
bigcode/the-stack
train
bfb1913d14f4f946d369d1f8
train
class
class DeCoAR2Featurizer(Featurizer): def __init__(self, params_file, gpu): super().__init__() from .models.decoar2 import DeCoAR2 self._model = DeCoAR2() models = torch.load(params_file)['model'] component_state_dict = OrderedDict() for key in models.keys(): ...
class DeCoAR2Featurizer(Featurizer):
def __init__(self, params_file, gpu): super().__init__() from .models.decoar2 import DeCoAR2 self._model = DeCoAR2() models = torch.load(params_file)['model'] component_state_dict = OrderedDict() for key in models.keys(): component_state_dict[key] = model...
" final_scp = temp_dir / "final.scp" cmd = f"apply-cmvn --norm-vars=true scp:{cmvn_scp} scp:{feat_scp} ark,scp:{final_ark},{final_scp}" _run_cmd(cmd) with final_scp.open('rb') as fp: feats = [features for _, features in kaldi_io.read_mat_scp(fp)][0] ...
217
217
725
14
202
ishine/speech-representations
src/speech_reps/featurize.py
Python
DeCoAR2Featurizer
DeCoAR2Featurizer
154
234
154
156
68faa6a2b522cebec462c43cae5142de6c579bea
bigcode/the-stack
train
8c9969437ecfc7cca6a6c8e8
train
class
class BertPhoneFeaturizer(Featurizer): def __init__(self, params_file, gpu=None): super().__init__() # Load the model from .models.bertphone import BertPhone import mxnet as mx self._model = BertPhone('bert_12_768_12', prefix='OpenSpeechModel_') self._ctx = mx.gpu(g...
class BertPhoneFeaturizer(Featurizer):
def __init__(self, params_file, gpu=None): super().__init__() # Load the model from .models.bertphone import BertPhone import mxnet as mx self._model = BertPhone('bert_12_768_12', prefix='OpenSpeechModel_') self._ctx = mx.gpu(gpu) if gpu is not None else mx.cpu() ...
f"compute-cmvn-stats scp:{feat_scp} ark,scp:{cmvn_ark},{cmvn_scp}" _run_cmd(cmd) # Apply CMVN final_ark = temp_dir / "final.ark" final_scp = temp_dir / "final.scp" cmd = f"apply-cmvn --norm-vars=true scp:{cmvn_scp} scp:{feat_scp} ark,scp:{final_ark},{fin...
256
256
1,041
11
244
ishine/speech-representations
src/speech_reps/featurize.py
Python
BertPhoneFeaturizer
BertPhoneFeaturizer
236
338
236
237
6025e5b8091f53bcd806ef3f8bf08a669698c882
bigcode/the-stack
train
5ec10ade0b2e920a79d455dc
train
function
def check_forbid(curPlayer,noncurPlayer,x,y,adjacent,direction,width): i,j=0,0 adjacent+=1 if direction>=4: adjacent=-adjacent if direction%4==0: i=x-adjacent j=y elif direction%4==1: i=x-adjacent j=y+adjacent elif direction%4==2: i=x j=y+a...
def check_forbid(curPlayer,noncurPlayer,x,y,adjacent,direction,width):
i,j=0,0 adjacent+=1 if direction>=4: adjacent=-adjacent if direction%4==0: i=x-adjacent j=y elif direction%4==1: i=x-adjacent j=y+adjacent elif direction%4==2: i=x j=y+adjacent elif direction%4==3: i=x+adjacent j=y+adjac...
Player,x,y,adjacent[i+4],i+4,width)==0: cnt3+=1 if cnt4>=2 or cnt3>=2: return 1 return 0 def check_forbid(curPlayer,noncurPlayer,x,y,adjacent,direction,width):
64
64
202
19
44
Demiandalou/Gomoku_RL
Forbidden_Moves0.py
Python
check_forbid
check_forbid
257
281
257
257
01e886f3785375a18eecae5778bfc567b03a23a8
bigcode/the-stack
train
05e4067121ccfd853a90960d
train
function
def forbidden_move(curPlayer,noncurPlayer,x,y,width): # up, right-up, right, right-down, down, left-down, left, left-up # res=[0]*8 adjacent=[0]*8 adjacent_blank=[0]*8 jump_one=[0]*8 jump_blank=[0]*8 jump_blank_same=[0]*8 # up # for i in range(x,8): # if curPlayer[i][y] ...
def forbidden_move(curPlayer,noncurPlayer,x,y,width): # up, right-up, right, right-down, down, left-down, left, left-up # res=[0]*8
adjacent=[0]*8 adjacent_blank=[0]*8 jump_one=[0]*8 jump_blank=[0]*8 jump_blank_same=[0]*8 # up # for i in range(x,8): # if curPlayer[i][y] i=x-1 while i>=0 and curPlayer[i][y]==1: # board[i][y] is black i-=1 adjacent[0]+=1 while i>=0 and noncurPlayer[i]...
def forbidden_move(curPlayer,noncurPlayer,x,y,width): # up, right-up, right, right-down, down, left-down, left, left-up # res=[0]*8
43
256
2,864
43
0
Demiandalou/Gomoku_RL
Forbidden_Moves0.py
Python
forbidden_move
forbidden_move
2
252
2
4
b6e32e02e0f8939b1fbe57fcb270c1843537d9fc
bigcode/the-stack
train
0fbb791335e1000bc03fb26b
train
function
def markov(text, chain=None): if not chain: intdict = lambda: defaultdict(int) chain = defaultdict(intdict) words = text.split(' ') word_count = len(words) for i, word in enumerate(words): if word_count > i + 1: chain[word][words[i+1]] += 1 return chain
def markov(text, chain=None):
if not chain: intdict = lambda: defaultdict(int) chain = defaultdict(intdict) words = text.split(' ') word_count = len(words) for i, word in enumerate(words): if word_count > i + 1: chain[word][words[i+1]] += 1 return chain
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import random from collections import defaultdict def markov(text, chain=None):
38
64
79
8
29
bunchesofdonald/sixwordmemoirbot
markov.py
Python
markov
markov
10
22
10
10
eb1e8cbb3ba4929434ea43321e43868576ff1961
bigcode/the-stack
train
87aab8bb48c5cd9d357e3ab3
train
function
def generate_text(chain, max_size=25): word = random.choice(chain.keys()) result = [word, ] while word and len(result) < max_size: try: possible_words = [] for possible, count in chain[word].items(): possible_words = possible_words + [possible] * count ...
def generate_text(chain, max_size=25):
word = random.choice(chain.keys()) result = [word, ] while word and len(result) < max_size: try: possible_words = [] for possible, count in chain[word].items(): possible_words = possible_words + [possible] * count word = random.choice(possible_wor...
defaultdict(intdict) words = text.split(' ') word_count = len(words) for i, word in enumerate(words): if word_count > i + 1: chain[word][words[i+1]] += 1 return chain def generate_text(chain, max_size=25):
64
64
99
10
53
bunchesofdonald/sixwordmemoirbot
markov.py
Python
generate_text
generate_text
25
40
25
25
71025ce4d1621c37d0e715be2c5026ed5306fa13
bigcode/the-stack
train
ccc1bf00beba351f8403d5b4
train
class
class NginxSyntax: # https://packagecontrol.io/packages/nginx SYNTAX_FILE = 'Packages/nginx/Syntaxes/nginx.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('nginx.conf')
class NginxSyntax: # https://packagecontrol.io/packages/nginx
SYNTAX_FILE = 'Packages/nginx/Syntaxes/nginx.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('nginx.conf')
= 'Packages/Dockerfile Syntax Highlighting/Syntaxes/Dockerfile.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('.Dockerfile') or filename.endswith('/Dockerfile') class NginxSyntax: # https://packagecontrol.io/packages/nginx
64
64
58
17
47
malexer/sublime-fix-syntax-highlighting-detection
fix_syntax_highlighting.py
Python
NginxSyntax
NginxSyntax
15
22
15
17
102ac9fa4a4fbd027c2012ec16d50165daad17b7
bigcode/the-stack
train
7cbbb110814ac392c6ebb345
train
function
def syntax_exists(package_based_path): """Check if syntax file exists. :type package_based_path: str :param package_based_path: syntax file specified in Sublime Text's packages format. .. note:: Sublime Text specifies syntax file path in format:: Pac...
def syntax_exists(package_based_path):
"""Check if syntax file exists. :type package_based_path: str :param package_based_path: syntax file specified in Sublime Text's packages format. .. note:: Sublime Text specifies syntax file path in format:: Packages/Python/Python.sublime-syntax ...
NTAX_FILE = 'Packages/nginx/Syntaxes/nginx.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('nginx.conf') SYNTAXES = ( DockerfileSyntax, NginxSyntax, ) def syntax_exists(package_based_path):
64
64
110
7
57
malexer/sublime-fix-syntax-highlighting-detection
fix_syntax_highlighting.py
Python
syntax_exists
syntax_exists
31
50
31
31
8ab00b1dd109af6da778aa5f91b968b37707e915
bigcode/the-stack
train
2ca1e82b9f6dd4d099a7d2fe
train
class
class DockerfileSyntax: # https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting SYNTAX_FILE = 'Packages/Dockerfile Syntax Highlighting/Syntaxes/Dockerfile.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('.Dockerfile') or filename.endswith('/Dock...
class DockerfileSyntax: # https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting
SYNTAX_FILE = 'Packages/Dockerfile Syntax Highlighting/Syntaxes/Dockerfile.sublime-syntax' @staticmethod def is_my_file(filename): return filename.endswith('.Dockerfile') or filename.endswith('/Dockerfile')
import sublime import sublime_plugin class DockerfileSyntax: # https://packagecontrol.io/packages/Dockerfile%20Syntax%20Highlighting
31
64
76
24
6
malexer/sublime-fix-syntax-highlighting-detection
fix_syntax_highlighting.py
Python
DockerfileSyntax
DockerfileSyntax
5
12
5
7
3d2955d70f40713de58122c228ddbf7935daaec9
bigcode/the-stack
train
268685ea7d3eaab7b99ff676
train
class
class FixSyntaxHighlighterEventListener(sublime_plugin.EventListener): def on_load_async(self, view): filename = view.file_name() if filename: for syntax in SYNTAXES: if syntax.is_my_file(filename): if syntax_exists(syntax.SYNTAX_FILE): ...
class FixSyntaxHighlighterEventListener(sublime_plugin.EventListener):
def on_load_async(self, view): filename = view.file_name() if filename: for syntax in SYNTAXES: if syntax.is_my_file(filename): if syntax_exists(syntax.SYNTAX_FILE): view.set_syntax_file(syntax.SYNTAX_FILE) ...
Packages/Python/Python.sublime-syntax Packages/User/Python-custom.sublime-syntax """ try: sublime.load_binary_resource(package_based_path) return True except OSError: return False class FixSyntaxHighlighterEventListener(sublime_plugin.EventListener):
64
64
80
14
49
malexer/sublime-fix-syntax-highlighting-detection
fix_syntax_highlighting.py
Python
FixSyntaxHighlighterEventListener
FixSyntaxHighlighterEventListener
53
63
53
54
3b15f163a6bf71ee971491a6150de5e51937d6b2
bigcode/the-stack
train
35e50a5022170b90196caa46
train
class
class ExpandFqcnCommand(sublime_plugin.TextCommand): def run(self, edit, leading_separator=False): view = self.view self.region = view.word(view.sel()[0]) symbol = view.substr(self.region) if re.match(r"\w", symbol) is None: return sublime.status_message('Not a valid sym...
class ExpandFqcnCommand(sublime_plugin.TextCommand):
def run(self, edit, leading_separator=False): view = self.view self.region = view.word(view.sel()[0]) symbol = view.substr(self.region) if re.match(r"\w", symbol) is None: return sublime.status_message('Not a valid symbol "%s" !' % symbol) self.namespaces = find...
import sublime import sublime_plugin import re from ..utils import find_symbol class ExpandFqcnCommand(sublime_plugin.TextCommand):
30
74
247
13
16
risingphoenix/SublimePHPCompanion
php_companion/commands/expand_fqcn_command.py
Python
ExpandFqcnCommand
ExpandFqcnCommand
8
30
8
8
dc3e441520d20f23bf9219790e876e06787a7718
bigcode/the-stack
train
cf18bd2e81ec91ee6404c998
train
class
class MapSource(object): """Base class for implementing a map source / provider """ attribution_osm = 'Maps & Data © [i][ref=http://www.osm.org/copyright]OpenStreetMap contributors[/ref][/i]' attribution_thunderforest = 'Maps © [i][ref=http://www.thunderforest.com]Thunderforest[/ref][/i], Data © [...
class MapSource(object):
"""Base class for implementing a map source / provider """ attribution_osm = 'Maps & Data © [i][ref=http://www.osm.org/copyright]OpenStreetMap contributors[/ref][/i]' attribution_thunderforest = 'Maps © [i][ref=http://www.thunderforest.com]Thunderforest[/ref][/i], Data © [i][ref=http://www.osm.org/...
# coding=utf-8 __all__ = ["MapSource"] from kivy.metrics import dp from math import cos, ceil, log, tan, pi, atan, exp from mapview import MIN_LONGITUDE, MAX_LONGITUDE, MIN_LATITUDE, MAX_LATITUDE, \ CACHE_DIR from mapview.downloader import Downloader from mapview.utils import clamp import hashlib class ...
87
256
1,666
5
81
JacobLiebenow/Waves-In-Motion
mapview/source.py
Python
MapSource
MapSource
14
141
14
14
5856fb8f0a531450e2c94589a1ba9ed1ed691623
bigcode/the-stack
train
6f1bafa5cb122d5e83b0e9e3
train
class
class SNEA(nn.Module): r"""The signed graph attentional layers operator from the `"Learning Signed Network Embedding via Graph Attention" <https://ojs.aaai.org/index.php/AAAI/article/view/5911>`_ paper Args: node_num (int): The number of nodes. edge_index_s (LongTensor): The edgelist with si...
class SNEA(nn.Module):
r"""The signed graph attentional layers operator from the `"Learning Signed Network Embedding via Graph Attention" <https://ojs.aaai.org/index.php/AAAI/article/view/5911>`_ paper Args: node_num (int): The number of nodes. edge_index_s (LongTensor): The edgelist with sign. (e.g., torch.LongTe...
from collections import defaultdict from random import randint import scipy.sparse as sp import torch import torch.nn.functional as F import torch.nn as nn from torch import Tensor import numpy as np from torch_sparse import coalesce from .SNEAConv import SNEAConv class SNEA(nn.Module):
69
256
1,802
7
61
SherylHYX/pytorch_geometric_signed_directed
torch_geometric_signed_directed/nn/signed/SNEA.py
Python
SNEA
SNEA
15
213
15
15
606a37bdf560176136b209b2c29dfa7c0edf101a
bigcode/the-stack
train
55556d6149d9bb3f99c92833
train
function
@app.task def trigger_webhook(data): r = requests.post(SERVER_WEBHOOK_URL, json=data) logger.info(r.json())
@app.task def trigger_webhook(data):
r = requests.post(SERVER_WEBHOOK_URL, json=data) logger.info(r.json())
# -*- coding : utf-8 -*- from __future__ import absolute_import import requests from celery_app import app from celery.utils.log import get_task_logger from env import SERVER_WEBHOOK_URL from pprint import pprint logger = get_task_logger(__name__) @app.task def trigger_webhook(data):
64
64
29
9
55
vedantrathore/chowkidar
agent/src/tasks.py
Python
trigger_webhook
trigger_webhook
13
16
13
14
6df4c098290d56aedc1645b3fc7549a11343d98e
bigcode/the-stack
train
af6db1deb8748fea7f1b3911
train
function
def write_to_file(filepath, filelines): """Writes a list of lines to a file. Args: filepath: str. The path of the file to write to. filelines: list(str). The lines to write to the file. """ with python_utils.open_file(filepath, 'w') as f: for line in filelines: f.wri...
def write_to_file(filepath, filelines):
"""Writes a list of lines to a file. Args: filepath: str. The path of the file to write to. filelines: list(str). The lines to write to the file. """ with python_utils.open_file(filepath, 'w') as f: for line in filelines: f.write(line)
a file. Args: filepath: str. The path of the file to read. Returns: list(str). The list of lines in the file. """ with python_utils.open_file(filepath, 'r') as f: return f.readlines() def write_to_file(filepath, filelines):
64
64
80
9
55
oswalgopal/oppia
scripts/release_scripts/update_changelog_and_credits_test.py
Python
write_to_file
write_to_file
71
80
71
71
6aaac39b5f4a13d7be527e3920ba81ea83b5bb2f
bigcode/the-stack
train
6af0452e701c256e547655f4
train
function
def read_from_file(filepath): """Reads the lines from a file. Args: filepath: str. The path of the file to read. Returns: list(str). The list of lines in the file. """ with python_utils.open_file(filepath, 'r') as f: return f.readlines()
def read_from_file(filepath):
"""Reads the lines from a file. Args: filepath: str. The path of the file to read. Returns: list(str). The list of lines in the file. """ with python_utils.open_file(filepath, 'r') as f: return f.readlines()
'UPDATED_CHANGELOG_FOR_REMOVAL_TEST') MOCK_UPDATED_AUTHORS_FILEPATH = os.path.join( RELEASE_TEST_DIR, 'UPDATED_AUTHORS') MOCK_UPDATED_CONTRIBUTORS_FILEPATH = os.path.join( RELEASE_TEST_DIR, 'UPDATED_CONTRIBUTORS') def read_from_file(filepath):
64
64
67
6
58
oswalgopal/oppia
scripts/release_scripts/update_changelog_and_credits_test.py
Python
read_from_file
read_from_file
58
68
58
58
627362f0ea22d7422808d98a37710fcee9b8c75b
bigcode/the-stack
train
03d8ac81ab93362a3714c95b
train
class
class ChangelogAndCreditsUpdateTests(test_utils.GenericTestBase): """Test the methods for automatic update of changelog and credits.""" def setUp(self): super(ChangelogAndCreditsUpdateTests, self).setUp() def mock_get_current_branch_name(): return 'release-1.2.3' def mock_ru...
class ChangelogAndCreditsUpdateTests(test_utils.GenericTestBase):
"""Test the methods for automatic update of changelog and credits.""" def setUp(self): super(ChangelogAndCreditsUpdateTests, self).setUp() def mock_get_current_branch_name(): return 'release-1.2.3' def mock_run_cmd(unused_cmd): pass def mock_get_git_ref(u...
PATH = os.path.join( RELEASE_TEST_DIR, 'UPDATED_CHANGELOG') MOCK_UPDATED_CHANGELOG_FILEPATH_FOR_REMOVAL_TEST = os.path.join( RELEASE_TEST_DIR, 'UPDATED_CHANGELOG_FOR_REMOVAL_TEST') MOCK_UPDATED_AUTHORS_FILEPATH = os.path.join( RELEASE_TEST_DIR, 'UPDATED_AUTHORS') MOCK_UPDATED_CONTRIBUTORS_FILEPATH = os.path...
256
256
5,986
13
243
oswalgopal/oppia
scripts/release_scripts/update_changelog_and_credits_test.py
Python
ChangelogAndCreditsUpdateTests
ChangelogAndCreditsUpdateTests
83
687
83
83
1e1eb4f6f508ffe5286205d57f9b38a1a88d528b
bigcode/the-stack
train
446f892ede7babecaa7c962b
train
class
class StatefulSetList(pulumi.CustomResource): """ StatefulSetList is a collection of StatefulSets. """ def __init__(self, __name__, __opts__=None, items=None, metadata=None): if not __name__: raise TypeError('Missing resource name argument (for URN creation)') if not isinstan...
class StatefulSetList(pulumi.CustomResource):
""" StatefulSetList is a collection of StatefulSets. """ def __init__(self, __name__, __opts__=None, items=None, metadata=None): if not __name__: raise TypeError('Missing resource name argument (for URN creation)') if not isinstance(__name__, str): raise TypeError...
import pulumi import pulumi.runtime from ... import tables class StatefulSetList(pulumi.CustomResource):
24
87
291
10
13
rosskevin/pulumi-kubernetes
sdk/python/pulumi_kubernetes/apps/v1beta2/StatefulSetList.py
Python
StatefulSetList
StatefulSetList
6
37
6
6
7586036e217d69778b677a688c2e1794b18a4c91
bigcode/the-stack
train
915734b81b5117c458a19b96
train
function
def generate_data(N_A, N_B, p_A, p_B, days=None, control_label='A', test_label='B'): """Returns a pandas dataframe with fake CTR data Example: Parameters: N_A (int): sample size for control group N_B (int): sample size for test group Note: final sample size ma...
def generate_data(N_A, N_B, p_A, p_B, days=None, control_label='A', test_label='B'):
"""Returns a pandas dataframe with fake CTR data Example: Parameters: N_A (int): sample size for control group N_B (int): sample size for test group Note: final sample size may not match N_A provided because the group at each row is chosen at random (50/50). ...
import scipy.stats as scs import pandas as pd # import numpy as np def generate_data(N_A, N_B, p_A, p_B, days=None, control_label='A', test_label='B'):
47
153
512
29
17
miaojunlee/MixBABA
mixbaba/src/data.py
Python
generate_data
generate_data
6
69
6
7
7e47e51b9be77df30dc48768ccebf4c5361201b6
bigcode/the-stack
train
89dea0cce89f66a9f242ad21
train
class
@due.dcite(references.COGNITIVE_ATLAS, description="Introduces the Cognitive Atlas.") class CogAtLemmatizer(object): """Replace synonyms and abbreviations with Cognitive Atlas identifiers in text. Parameters ---------- ontology_df : :obj:`pandas.DataFrame`, optional DataFrame with three columns...
@due.dcite(references.COGNITIVE_ATLAS, description="Introduces the Cognitive Atlas.") class CogAtLemmatizer(object):
"""Replace synonyms and abbreviations with Cognitive Atlas identifiers in text. Parameters ---------- ontology_df : :obj:`pandas.DataFrame`, optional DataFrame with three columns (id, name, alias) and one row for each alias (e.g., synonym or abbreviation) for each term in the Cognitive ...
"""Automated annotation of Cognitive Atlas labels.""" import logging import re import numpy as np import pandas as pd from .. import references from ..due import due from ..extract import download_cognitive_atlas from ..utils import uk_to_us from . import utils LGR = logging.getLogger(__name__) @due.dcite(references...
98
189
631
30
68
JulioAPeraza/NiMARE
nimare/annotate/cogat.py
Python
CogAtLemmatizer
CogAtLemmatizer
17
92
17
18
76f577f2c193ca56f2c3cd2312656b37c604a8c2
bigcode/the-stack
train
a5e4c28bf9c7e583f2023a8f
train
function
def expand_counts(counts_df, rel_df=None, weights=None): """Perform hierarchical expansion of counts across labels. Parameters ---------- counts_df : (D x T) :obj:`pandas.DataFrame` Term counts for a corpus. T = term, D = document. rel_df : :obj:`pandas.DataFrame` Long-form DataFram...
def expand_counts(counts_df, rel_df=None, weights=None):
"""Perform hierarchical expansion of counts across labels. Parameters ---------- counts_df : (D x T) :obj:`pandas.DataFrame` Term counts for a corpus. T = term, D = document. rel_df : :obj:`pandas.DataFrame` Long-form DataFrame of term-term relationships with at least three columns:...
=gazetteer, index=text_df.index, data=count_arr) for term_idx in id_df.index: term = id_df["alias"].loc[term_idx] term_id = id_df["id"].loc[term_idx] pattern = regex_dict[term] counts_df[term_id] += text_df[text_column].str.count(pattern).astype(int) text_df[text_column] = te...
119
119
399
14
104
JulioAPeraza/NiMARE
nimare/annotate/cogat.py
Python
expand_counts
expand_counts
162
205
162
162
76fc995a2d8aa17e101642394e964669d5cd6732
bigcode/the-stack
train
b0b745f59ec36ad2e5521f81
train
function
@due.dcite(references.COGNITIVE_ATLAS, description="Introduces the Cognitive Atlas.") def extract_cogat(text_df, id_df=None, text_column="abstract"): """Extract Cognitive Atlas terms and count instances using regular expressions. Parameters ---------- text_df : (D x 2) :obj:`pandas.DataFrame` P...
@due.dcite(references.COGNITIVE_ATLAS, description="Introduces the Cognitive Atlas.") def extract_cogat(text_df, id_df=None, text_column="abstract"):
"""Extract Cognitive Atlas terms and count instances using regular expressions. Parameters ---------- text_df : (D x 2) :obj:`pandas.DataFrame` Pandas dataframe with at least two columns: 'id' and the text. D = document. id_df : (T x 3) :obj:`pandas.DataFrame` Cognitive Atla...
uk=True): """Replace terms in text with unique Cognitive Atlas identifiers. Parameters ---------- text : :obj:`str` Text to convert. convert_uk : :obj:`bool`, optional Convert British English words in text to American English versions. Default...
204
204
682
37
166
JulioAPeraza/NiMARE
nimare/annotate/cogat.py
Python
extract_cogat
extract_cogat
95
159
95
96
51dba4ebb2f5cb814cfca70a9b204b91465af386
bigcode/the-stack
train
b62c4e1c8f233911dfebeab8
train
function
@csrf_exempt def setting_post(request): return_text = {} if request.method == 'POST': url = request.POST['url'] tags = request.POST['tags'] tags_map = request.POST['map'] table = request.POST['table'] html = request.POST['html'] return_text['URL'] = url re...
@csrf_exempt def setting_post(request):
return_text = {} if request.method == 'POST': url = request.POST['url'] tags = request.POST['tags'] tags_map = request.POST['map'] table = request.POST['table'] html = request.POST['html'] return_text['URL'] = url return_text['html'] = html if url ...
from selenium import webdriver from django.shortcuts import render from crawler.parser_geneerator import Setting from selenium.webdriver.chrome.options import Options import os from django.views.decorators.csrf import csrf_exempt @csrf_exempt def setting_post(request):
52
79
264
10
41
wu87988622/parseltongue
setting/parser_setting.py
Python
setting_post
setting_post
9
39
9
10
13f8f7eecf0b2511c5cf05a08414bf008e7dd26f
bigcode/the-stack
train
50d71562e3a44037125cac89
train
class
class TestTransactionSearch(unittest.TestCase): def test_advanced_search_no_results(self): collection = Transaction.search([ TransactionSearch.billing_first_name == "no_such_person" ]) self.assertEqual(0, collection.maximum_size) def test_advanced_search_searches_all_text_fi...
class TestTransactionSearch(unittest.TestCase):
def test_advanced_search_no_results(self): collection = Transaction.search([ TransactionSearch.billing_first_name == "no_such_person" ]) self.assertEqual(0, collection.maximum_size) def test_advanced_search_searches_all_text_fields_at_once(self): first_name = "Tim%s"...
from tests.test_helper import * class TestTransactionSearch(unittest.TestCase):
14
256
11,425
8
6
futureironman/braintree_python
tests/integration/test_transaction_search.py
Python
TestTransactionSearch
TestTransactionSearch
3
1,581
3
3
7c1cce90d20205c1be833df007c78622d1a1b2b3
bigcode/the-stack
train
22ff8069c7da2f891fb93d63
train
function
def video_edge(): if video_text.get() != '': cap = cv2.VideoCapture(video_text.get()) if (cap.isOpened()== False): print("Error opening video stream or file") frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) size = (frame_width, frame_height) ...
def video_edge():
if video_text.get() != '': cap = cv2.VideoCapture(video_text.get()) if (cap.isOpened()== False): print("Error opening video stream or file") frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) size = (frame_width, frame_height) result = cv2.Vid...
act_label.place(x=20, y=435) act_btn = Button(app, text='Show Example', command=example_contour,fg='red') act_btn.place(x=50, y=480) act_remind=Label(app, text="This example's photo is \n default. Your image \nentry doesn't use for\nthis example.", font="Times, 9") act_remind.place(x=20, y=540) ############...
102
102
343
4
97
emreeser/Image-Processing-Application
app.py
Python
video_edge
video_edge
657
691
657
657
70d669855e63a326c7a29c4437baa253de4c4c60
bigcode/the-stack
train
9e2bf7223169610e056e0103
train
function
def myfilter(): if image_text.get() != '': image = cv2.imread(image_text.get()) gamma_corrected = np.array(255 * (image / 255) ** 0.5, dtype='uint8') usmask = unsharp_mask(gamma_corrected, radius=20, amount=1) usmask = cv2.resize(usmask, (700, 600)) image = cv2.resize(image, ...
def myfilter():
if image_text.get() != '': image = cv2.imread(image_text.get()) gamma_corrected = np.array(255 * (image / 255) ** 0.5, dtype='uint8') usmask = unsharp_mask(gamma_corrected, radius=20, amount=1) usmask = cv2.resize(usmask, (700, 600)) image = cv2.resize(image, (700, 600)) ...
="Times, 11",fg='green') vd_label.place(x=20, y=285) vd_btn = Button(app, text='Show', command=video_edge,fg='green') vd_btn.place(x=80, y=330) ###### my filter for social media def myfilter():
64
64
141
4
59
emreeser/Image-Processing-Application
app.py
Python
myfilter
myfilter
701
712
701
701
1f71dc4b95ccdf4118d99f8aabce3f1e583db065
bigcode/the-stack
train
47bf382253e4d6fea87a6f59
train
function
def in_filt(image): if filvar.get() == 'prewitt': image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) prew=prewitt(image) cv2.imshow('Current Image', image) cv2.imshow("However Prewitt", prew) cv2.waitKey(0) cv2.destroyAllWindows() save_image(prew) if filvar....
def in_filt(image):
if filvar.get() == 'prewitt': image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) prew=prewitt(image) cv2.imshow('Current Image', image) cv2.imshow("However Prewitt", prew) cv2.waitKey(0) cv2.destroyAllWindows() save_image(prew) if filvar.get() == 'threshold'...
ORPH_CROSS, kernel) cv2.imshow('Current Image', image) cv2.imshow("However Crossing", img_crossing) cv2.waitKey(0) cv2.destroyAllWindows() save_image(img_crossing) if morvar.get() == 'Ellipse': kernel = np.ones((8,8), np.uint8) img_ellipse = cv2.morphologyEx(i...
253
253
845
6
246
emreeser/Image-Processing-Application
app.py
Python
in_filt
in_filt
806
885
806
806
7d0386a13777b5ac18652740f2e448155abb549d
bigcode/the-stack
train
ae101d0ef6af8676c8cdbaaa
train
function
def save_image(image): result = tkinter.messagebox.askquestion('SAVE Image', 'Do you want to save the image?') if result == 'yes': result2 = tkinter.simpledialog.askstring("Name of the Image File","You should write the image file name correctly\n(etc: wolf.jpg {.png/.jpg/.jpeg})") if result2 is ...
def save_image(image):
result = tkinter.messagebox.askquestion('SAVE Image', 'Do you want to save the image?') if result == 'yes': result2 = tkinter.simpledialog.askstring("Name of the Image File","You should write the image file name correctly\n(etc: wolf.jpg {.png/.jpg/.jpeg})") if result2 is not None: i...
1, (700, 500)) cv2.imshow('Original Image(first)', image1) open_button1 = Button(app, text='Open Image', font="Times, 10",fg='blue', command=open_image) open_button1.place(x=30, y=75) def save_image(image):
64
64
149
5
59
emreeser/Image-Processing-Application
app.py
Python
save_image
save_image
47
56
47
47
1fb30e3214103286e768175b276bd86e23819f5c
bigcode/the-stack
train
f9484714f07a4a8da7f1ccbd
train
function
def do_inten(): if invar.get() == 'Piecewise': if image_text.get() != '': image = cv2.imread(image_text.get()) image = cv2.resize(image, (700, 500)) pixelVal_vec = np.vectorize(pixelval) if pie_input.get()=='' and pie_input2.get() == '': piece=...
def do_inten():
if invar.get() == 'Piecewise': if image_text.get() != '': image = cv2.imread(image_text.get()) image = cv2.resize(image, (700, 500)) pixelVal_vec = np.vectorize(pixelval) if pie_input.get()=='' and pie_input2.get() == '': piece=pixelVal_vec(ima...
Windows() save_image(img_rectangular) morphologicals = {'Opening','Closing','Gradient','Tophat','Blackhat','Erosion','Dilation','Crossing','Ellipse','Rectangular','! NONE !'} morvar = StringVar() morvar.set('Morphologicals') mormenu = OptionMenu(app, morvar, *morphologicals) label_m...
173
173
577
5
167
emreeser/Image-Processing-Application
app.py
Python
do_inten
do_inten
512
558
512
512
9e509d92af42fb5961d37ceb654312927c5dbab3
bigcode/the-stack
train
49d83cbd6357d1b02337b2d2
train
function
def do_transform(): if geovar.get() == 'Resizing': if image_text.get() != '': image = cv2.imread(image_text.get()) resized = cv2.resize(image,(1200, 600)) image = cv2.resize(image, (600, 500)) if morvar.get() == 'Morphologicals' or morvar.get() =='! NONE !': ...
def do_transform():
if geovar.get() == 'Resizing': if image_text.get() != '': image = cv2.imread(image_text.get()) resized = cv2.resize(image,(1200, 600)) image = cv2.resize(image, (600, 500)) if morvar.get() == 'Morphologicals' or morvar.get() =='! NONE !': if ...
cv2.cvtColor(imgh2, cv2.COLOR_BGR2GRAY) imgh = cv2.resize(imgh, (400, 400)) image= cv2.resize(image, (400, 400)) hiseq = cv2.resize(hiseq, (400, 400)) imgh2 = cv2.resize(imgh2, (400, 400)) horizontalStack =np.concatenate((image,imgh,hiseq,imgh2), axis=1) horizontalStack ...
256
256
1,149
4
251
emreeser/Image-Processing-Application
app.py
Python
do_transform
do_transform
258
360
258
258
db0dd41b55e21e2d574868ead26374a7c473479f
bigcode/the-stack
train
0e2e85be65e44746ceb7df0c
train
function
def do_morpho(): if morvar.get() == 'Opening': if image_text.get() != '': image = cv2.imread(image_text.get()) kernel = np.ones((5, 5), np.uint8) img_opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) image = cv2.resize(image, (700, 500)) im...
def do_morpho():
if morvar.get() == 'Opening': if image_text.get() != '': image = cv2.imread(image_text.get()) kernel = np.ones((5, 5), np.uint8) img_opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) image = cv2.resize(image, (700, 500)) img_opening = cv2.r...
2.imshow('Original Image', image) cv2.imshow("Flip", yansi) cv2.waitKey(0) cv2.destroyAllWindows() save_image(yansi) elif morvar.get() != 'Morphologicals' or morvar.get() !='! NONE !': in_mor(yansi) e...
256
256
1,457
6
249
emreeser/Image-Processing-Application
app.py
Python
do_morpho
do_morpho
377
499
377
377
fb3c2a785477f107d1c37c8ec46d224bba214b9c
bigcode/the-stack
train
5dd3f4322828a892a42b7671
train
function
def example_contour(): image= cv2.imread(r'ronaldo.jpg') image= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('ronaldo_gray.png', image) def circle_points(resolution, center, radius): radians = np.linspace(0, 2*np.pi, resolution) c = center[1] + radius*np.cos(radians) ...
def example_contour():
image= cv2.imread(r'ronaldo.jpg') image= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('ronaldo_gray.png', image) def circle_points(resolution, center, radius): radians = np.linspace(0, 2*np.pi, resolution) c = center[1] + radius*np.cos(radians) r = center[0] + radius...
etc: 2)', font="Times, 11") etc_p_label2.place(x=620, y=418) intensities = {'Piecewise','Gamma','Log Transform'} invar = StringVar() invar.set('Intensities') inmenu = OptionMenu(app, invar, *intensities) label_i = Label(app, text="Select a Intensity Transformation", font="Times, 11",fg='purple') label_i.p...
160
160
534
5
154
emreeser/Image-Processing-Application
app.py
Python
example_contour
example_contour
604
647
604
604
ef23f30e589b33d675ce132c7df50ae9090b6b26
bigcode/the-stack
train
302b9611cfbc8404b6f99eaa
train
function
def open_video(): if video_text.get() != '': cap = cv2.VideoCapture(video_text.get()) while True: ret, frame = cap.read() cv2.imshow('Original Video -- for exit press Q', frame) if cv2.waitKey(50) & 0xFF == ord('q'): break cap.release() ...
def open_video():
if video_text.get() != '': cap = cv2.VideoCapture(video_text.get()) while True: ret, frame = cap.read() cv2.imshow('Original Video -- for exit press Q', frame) if cv2.waitKey(50) & 0xFF == ord('q'): break cap.release() cv2.destroyAl...
, alpha=(255.0)) cv2.imwrite(result2, image) tkinter.messagebox.showinfo('SAVED', 'Saving was completed successfully') else: tkinter.messagebox.showinfo('NOT SAVED', 'You did not save the image \n You can continue') def open_video():
64
64
83
4
60
emreeser/Image-Processing-Application
app.py
Python
open_video
open_video
58
67
58
58
80494d4033f26c79b6a0b17c78c5c74588914739
bigcode/the-stack
train
8b1dfba8ef646d874bedb123
train
function
def do_filter(): if filvar.get() == 'prewitt': if image_text.get() != '': image = cv2.imread(image_text.get(), 1) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) prew=prewitt(image) prew = cv2.resize(prew, (600, 500)) image = cv2.resize(image, (600...
def do_filter():
if filvar.get() == 'prewitt': if image_text.get() != '': image = cv2.imread(image_text.get(), 1) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) prew=prewitt(image) prew = cv2.resize(prew, (600, 500)) image = cv2.resize(image, (600, 500)) ...
the image?') if result == 'yes': result2 = tkinter.simpledialog.askstring("Name of the Image File","You should write the image file name correctly\n(etc: wolf.jpg {.png/.jpg/.jpeg})") if result2 is not None: image = cv2.convertScaleAbs(image, alpha=(255.0)) cv2.imwrite(resul...
256
256
1,375
4
251
emreeser/Image-Processing-Application
app.py
Python
do_filter
do_filter
75
197
75
75
bffdeb7ff16e32e6d0bb25e400b371d83341d370
bigcode/the-stack
train
363585dd5dd619a79b5aa5f7
train
function
def pixelval(pix, r1, s1, r2, s2): if 0 <= pix <= r1: return (s1 / r1) * pix elif r1 < pix <= r2: return ((s2 - s1) / (r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2) / (255 - r2)) * (pix - r2) + s2
def pixelval(pix, r1, s1, r2, s2):
if 0 <= pix <= r1: return (s1 / r1) * pix elif r1 < pix <= r2: return ((s2 - s1) / (r2 - r1)) * (pix - r1) + s1 else: return ((255 - s2) / (255 - r2)) * (pix - r2) + s2
, 500)) cv2.imshow('Original Image', image) cv2.imshow("Log Transformation", logt) cv2.waitKey(0) cv2.destroyAllWindows() save_image(logt) def pixelval(pix, r1, s1, r2, s2):
64
64
107
18
46
emreeser/Image-Processing-Application
app.py
Python
pixelval
pixelval
560
566
560
560
db4faff6502cbe26dc53bdde6dad3b86e042f866
bigcode/the-stack
train
2c11686def031b540c6bc5bc
train
function
def open_image(): if image_text.get() != '': image1 = cv2.imread(image_text.get()) image1 = cv2.resize(image1, (700, 500)) cv2.imshow('Original Image(first)', image1)
def open_image():
if image_text.get() != '': image1 = cv2.imread(image_text.get()) image1 = cv2.resize(image1, (700, 500)) cv2.imshow('Original Image(first)', image1)
Var() part_entry = Entry(app, textvariable=video_text) part_entry.place(x=10, y=155) part_label2 = Label(app, text='(etc: video.mp4)', font="Times, 13") part_label2.place(x=180, y=150) def open_image():
64
64
51
4
60
emreeser/Image-Processing-Application
app.py
Python
open_image
open_image
39
43
39
39
2e27eca89a91b66c70327d5fa5cb7502f3a4649b
bigcode/the-stack
train
6166565d185fb81efff1350d
train
function
def in_mor(image): if morvar.get() == 'Opening': kernel = np.ones((5, 5), np.uint8) img_opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) cv2.imshow('Current Image', image) cv2.imshow("However Opening", img_opening) cv2.waitKey(0) cv2.destroyAllWindows() ...
def in_mor(image):
if morvar.get() == 'Opening': kernel = np.ones((5, 5), np.uint8) img_opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) cv2.imshow('Current Image', image) cv2.imshow("However Opening", img_opening) cv2.waitKey(0) cv2.destroyAllWindows() save_image(img_o...
,fg='green') vd_btn.place(x=80, y=330) ###### my filter for social media def myfilter(): if image_text.get() != '': image = cv2.imread(image_text.get()) gamma_corrected = np.array(255 * (image / 255) ** 0.5, dtype='uint8') usmask = unsharp_mask(gamma_corrected, radius=20, amount=1) ...
256
256
931
6
249
emreeser/Image-Processing-Application
app.py
Python
in_mor
in_mor
721
801
721
721
1ea9b5552b9036b68210c27ff935b4ef2ec81a29
bigcode/the-stack
train
0e0b5cebd483d0743da48584
train
function
def histogram_equ(): if image_text.get() != '': image = cv2.imread(image_text.get(),0) hiseq = cv2.equalizeHist(image) hist, bins = np.histogram(image.flatten(), 256, [0, 256]) cdf = hist.cumsum() cdf_normalized = cdf * hist.max() / cdf.max() plt.plot(cdf_normalized, ...
def histogram_equ():
if image_text.get() != '': image = cv2.imread(image_text.get(),0) hiseq = cv2.equalizeHist(image) hist, bins = np.histogram(image.flatten(), 256, [0, 256]) cdf = hist.cumsum() cdf_normalized = cdf * hist.max() / cdf.max() plt.plot(cdf_normalized, color='red') ...
var.set('Filtering') filter_names = {'prewitt', 'threshold', 'gabor', 'hessian', 'meijering', 'sobel', 'unsharp_mask', 'sato', 'median', 'roberts','! NONE !'} filter_menu = OptionMenu(app, filvar, *filter_names) label_f = Label(app, text="Select \na Filter",font="Times, 11",fg='red') label_f.place(x=383, y=...
157
157
524
4
152
emreeser/Image-Processing-Application
app.py
Python
histogram_equ
histogram_equ
211
250
211
211
94082f8787536997dce15b939e6d2326e8186979
bigcode/the-stack
train
2236d6275b9c42df053d5225
train
class
class RandomAffine: def __init__(self, rotation_range=None, translation_range=None, shear_range=None, zoom_range=None, interp='bilinear', lazy=False): """ Perform an affine transforms with vario...
class RandomAffine:
def __init__(self, rotation_range=None, translation_range=None, shear_range=None, zoom_range=None, interp='bilinear', lazy=False): """ Perform an affine transforms with various sub-transforms, us...
""" Affine transforms implemented on torch tensors, and requiring only one interpolation """ import math import random import torch as th from ..utils import th_affine2d, th_random_choice class RandomAffine:
46
194
648
4
41
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomAffine
RandomAffine
13
92
13
14
04f6b9e4c54998993e40b2d869db2e8a1e8e1e63
bigcode/the-stack
train
c8f0dec09836c1dea6baeb36
train
class
class RandomTranslate: def __init__(self, translation_range, interp='bilinear', lazy=False): """ Randomly translate an image some fraction of total height and/or some fraction of total width. If the image has multiple channels, the...
class RandomTranslate:
def __init__(self, translation_range, interp='bilinear', lazy=False): """ Randomly translate an image some fraction of total height and/or some fraction of total width. If the image has multiple channels, the same translation will b...
self.value rotation_matrix = th.FloatTensor([[math.cos(theta), -math.sin(theta), 0], [math.sin(theta), math.cos(theta), 0], [0, 0, 1]]) if self.lazy: return rotation_matrix outputs = [] idx ...
121
121
404
4
117
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomTranslate
RandomTranslate
322
371
322
323
4dba48f85922759b0c8eae3fb16a95779e5d6263
bigcode/the-stack
train
854070ea7b9d1f0ea19cfc8b
train
class
class Zoom: def __init__(self, value, interp='bilinear', lazy=False): """ Arguments --------- value : float Fractional zoom. =1 : no zoom >1 : zoom-in (value-1)% <1 : zoom-out (1-value...
class Zoom:
def __init__(self, value, interp='bilinear', lazy=False): """ Arguments --------- value : float Fractional zoom. =1 : no zoom >1 : zoom-in (value-1)% <1 : zoom-out (1-value)% i...
Probs must sum to 1') self.p = p self.interp = interp self.lazy = lazy def __call__(self, *inputs): zx = th_random_choice(self.values, p=self.p) zy = th_random_choice(self.values, p=self.p) if self.lazy: return Zoom([zx, zy], lazy=True)(inputs[0]) ...
102
102
342
3
99
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
Zoom
Zoom
733
782
733
734
785e17820b144e8a31180f8f117b1991e29d886c
bigcode/the-stack
train
183597ee12f1d997869185eb
train
class
class RandomChoiceRotate: def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly rotate an image from a list of values. If the image has multiple channels, the same rotation will be applied to each...
class RandomChoiceRotate:
def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly rotate an image from a list of values. If the image has multiple channels, the same rotation will be applied to each channel. Argument...
affine transform matrix and return that if false, perform the transform on the tensor and return the tensor """ self.rotation_range = rotation_range self.interp = interp self.lazy = lazy def __call__(self, *inputs): degree = random.uniform(-self.rotation_range, ...
111
111
370
5
105
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomChoiceRotate
RandomChoiceRotate
223
270
223
224
b992178bf50503912ad93515810c43a69cf8fcf4
bigcode/the-stack
train
271a3bba6d0d3ffbfdf7e9fd
train
class
class RandomShear: def __init__(self, shear_range, interp='bilinear', lazy=False): """ Randomly shear an image with radians (-shear_range, shear_range) Arguments --------- shear_range : float radian bounds on t...
class RandomShear:
def __init__(self, shear_range, interp='bilinear', lazy=False): """ Randomly shear an image with radians (-shear_range, shear_range) Arguments --------- shear_range : float radian bounds on the shear transform ...
if self.lazy: return translation_matrix outputs = [] idx = None for idx, _input in enumerate(inputs): input_tf = th_affine2d(_input, translation_matrix, mode=interp[idx], center=True) outputs.append(input_tf) return outputs if idx >= 1 else outputs[0...
75
75
250
5
70
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomShear
RandomShear
484
517
484
485
db5a10546f6bceb6a81bbddd9ad97dcf5f42c9d2
bigcode/the-stack
train
1bda172827479b4f09e112e2
train
class
class RandomZoom: def __init__(self, zoom_range, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image Arguments --------- zoom_range : tuple or list with 2 values, both between (0, infinity) ...
class RandomZoom:
def __init__(self, zoom_range, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image Arguments --------- zoom_range : tuple or list with 2 values, both between (0, infinity) lower and uppe...
not isinstance(zoom_range, tuple): raise ValueError('zoom_range must be tuple or list with 2 values') self.zoom_range = zoom_range self.interp = interp self.lazy = lazy def __call__(self, *inputs): zx = random.uniform(self.zoom_range[0], self.zoom_range[1]) zy =...
118
118
395
4
114
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomZoom
RandomZoom
639
680
639
640
d0b2724353046cb1e14213651a491dd0e6bdf48a
bigcode/the-stack
train
8c0be03b3159e4b1ccf78948
train
class
class Shear: def __init__(self, value, interp='bilinear', lazy=False): self.value = value self.interp = interp self.lazy = lazy def __call__(self, *inputs): if not isinstance(self.interp, (tuple,list)): interp = [se...
class Shear:
def __init__(self, value, interp='bilinear', lazy=False): self.value = value self.interp = interp self.lazy = lazy def __call__(self, *inputs): if not isinstance(self.interp, (tuple,list)): interp = [self.interp]*len...
__(self, *inputs): shear = th_random_choice(self.values, p=self.p) if self.lazy: return Shear(shear, lazy=True)(inputs[0]) outputs = Shear(shear, interp=self.interp)(*inputs) return outputs class Shear:
64
64
210
4
59
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
Shear
Shear
570
598
570
571
3d4c69b451fba93be97bd084549ee5cd7a409152
bigcode/the-stack
train
2074c0962fa372276d974e20
train
class
class AffineCompose: def __init__(self, transforms, interp='bilinear'): """ Apply a collection of explicit affine transforms to an input image, and to a target image if necessary Arguments --------- transforms : list or tuple ...
class AffineCompose:
def __init__(self, transforms, interp='bilinear'): """ Apply a collection of explicit affine transforms to an input image, and to a target image if necessary Arguments --------- transforms : list or tuple each element in...
__call__(self, *inputs): if not isinstance(self.interp, (tuple,list)): interp = [self.interp]*len(inputs) else: interp = self.interp outputs = [] idx = None for idx, _input in enumerate(inputs): input_tf = th_affine2d(_input, self.tform_matri...
106
106
356
5
101
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
AffineCompose
AffineCompose
133
182
133
134
d453ffb410de1564de6219c2aaa2ab9afff162a1
bigcode/the-stack
train
144d628317bfb1125e5087ef
train
class
class Affine: def __init__(self, tform_matrix, interp='bilinear'): """ Perform an affine transforms with various sub-transforms, using only one interpolation and without having to instantiate each sub-transform individually. Arguments ...
class Affine:
def __init__(self, tform_matrix, interp='bilinear'): """ Perform an affine transforms with various sub-transforms, using only one interpolation and without having to instantiate each sub-transform individually. Arguments --------- ...
0](inputs[0]) for tform in self.transforms[1:]: tform_matrix = tform_matrix.mm(tform(inputs[0])) self.tform_matrix = tform_matrix if self.lazy: return tform_matrix outputs = Affine(tform_matrix, interp=self.interp)(*inputs) return outputs class Affine: ...
79
79
266
4
74
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
Affine
Affine
95
130
95
96
218691fed34279c25779a8711b4063412019e8bd
bigcode/the-stack
train
ccaa1cbe7d95c45529bad33f
train
class
class RandomChoiceZoom: def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image with a value sampled from a list of values Arguments --------- ...
class RandomChoiceZoom:
def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image with a value sampled from a list of values Arguments --------- values : a list or tuple...
with 2 values') self.zoom_range = zoom_range self.interp = interp self.lazy = lazy def __call__(self, *inputs): zx = random.uniform(self.zoom_range[0], self.zoom_range[1]) zy = random.uniform(self.zoom_range[0], self.zoom_range[1]) if self.lazy: return ...
112
112
375
5
107
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomChoiceZoom
RandomChoiceZoom
683
730
683
684
4c74d09c5ef7f98c3517ad3797602dcf58bff484
bigcode/the-stack
train
f213d225f7b1586e71c04b2a
train
class
class Rotate: def __init__(self, value, interp='bilinear', lazy=False): """ Randomly rotate an image between (-degrees, degrees). If the image has multiple channels, the same rotation will be applied to each channel. Arguments ...
class Rotate:
def __init__(self, value, interp='bilinear', lazy=False): """ Randomly rotate an image between (-degrees, degrees). If the image has multiple channels, the same rotation will be applied to each channel. Arguments --------- ...
(1.0-sum(p)) > 1e-3: raise ValueError('Probs must sum to 1') self.p = p self.interp = interp self.lazy = lazy def __call__(self, *inputs): degree = th_random_choice(self.values, p=self.p) if self.lazy: return Rotate(degree, lazy=True)(inputs[0]) ...
110
110
369
3
106
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
Rotate
Rotate
273
319
273
274
1a11870afa06611d99a605f0681d7458fa950627
bigcode/the-stack
train
a06b27946f67476abdbce675
train
class
class RandomRotate: def __init__(self, rotation_range, interp='bilinear', lazy=False): """ Randomly rotate an image between (-degrees, degrees). If the image has multiple channels, the same rotation will be applied to each channel. ...
class RandomRotate:
def __init__(self, rotation_range, interp='bilinear', lazy=False): """ Randomly rotate an image between (-degrees, degrees). If the image has multiple channels, the same rotation will be applied to each channel. Arguments -...
]*len(inputs) else: interp = self.interp outputs = [] idx = None for idx, _input in enumerate(inputs): input_tf = th_affine2d(_input, tform_matrix, mode=interp[idx]) outputs.append(...
79
79
265
4
75
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomRotate
RandomRotate
185
220
185
186
468afeb19b85696a94376e7e821786f686c2f682
bigcode/the-stack
train
1b66b0a232edac3f929aa93d
train
class
class Translate: def __init__(self, value, interp='bilinear', lazy=False): """ Arguments --------- value : float or 2-tuple of float if single value, both horizontal and vertical translation will be this va...
class Translate:
def __init__(self, value, interp='bilinear', lazy=False): """ Arguments --------- value : float or 2-tuple of float if single value, both horizontal and vertical translation will be this value * total height...
1.0-sum(p)) > 1e-3: raise ValueError('Probs must sum to 1') self.p = p self.interp = interp self.lazy = lazy def __call__(self, *inputs): random_height = th_random_choice(self.values, p=self.p) random_width = th_random_choice(self.values, p=self.p) i...
133
133
444
3
129
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
Translate
Translate
428
481
428
429
98af23235b5217b979b4ac63aac4ac26ac4a710b
bigcode/the-stack
train
6ce1697a1fe842c7b635da2b
train
class
class RandomSquareZoom: def __init__(self, zoom_range, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image Arguments --------- zoom_range : tuple or list with 2 values, both between (0, infinity) ...
class RandomSquareZoom:
def __init__(self, zoom_range, interp='bilinear', lazy=False): """ Randomly zoom in and/or out on an image Arguments --------- zoom_range : tuple or list with 2 values, both between (0, infinity) lower and upper b...
_matrix = th.FloatTensor([[1, -math.sin(theta), 0], [0, math.cos(theta), 0], [0, 0, 1]]) if self.lazy: return shear_matrix outputs = [] idx = None for idx, _input in enumerate(inputs): ...
113
113
379
5
108
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomSquareZoom
RandomSquareZoom
601
637
601
602
2fd22ccd08bd3c176a53b2c46d79513f04e51457
bigcode/the-stack
train
d0ae42fa424da4a1f36fd4fb
train
class
class RandomChoiceTranslate: def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly translate an image some fraction of total height and/or some fraction of total width from a list of potential valu...
class RandomChoiceTranslate:
def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly translate an image some fraction of total height and/or some fraction of total width from a list of potential values. If the image has ...
self.width_range = translation_range[1] self.interp = interp self.lazy = lazy def __call__(self, *inputs): # height shift random_height = random.uniform(-self.height_range, self.height_range) # width shift random_width = random.uniform(-self.width_range, self.width_...
122
122
409
5
116
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomChoiceTranslate
RandomChoiceTranslate
374
425
374
375
5443d53dc1de8d549fe8424e4664214dcf220b45
bigcode/the-stack
train
b288fe69a3bbe7ab43b734b0
train
class
class RandomChoiceShear: def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly shear an image with a value sampled from a list of values. Arguments --------- values : a list or tup...
class RandomChoiceShear:
def __init__(self, values, p=None, interp='bilinear', lazy=False): """ Randomly shear an image with a value sampled from a list of values. Arguments --------- values : a list or tuple the values ...
true, only create the affine transform matrix and return that """ self.shear_range = shear_range self.interp = interp self.lazy = lazy def __call__(self, *inputs): shear = random.uniform(-self.shear_range, self.shear_range) if self.lazy: return Shear(she...
107
107
359
6
100
achaiah/pywick
pywick/transforms/affine_transforms.py
Python
RandomChoiceShear
RandomChoiceShear
520
567
520
521
4c2ded0355ff1996c934c4ff570346f25344d2d1
bigcode/the-stack
train
954dd56d9dae13e684b246f3
train
class
class TestApiDiscovery(base.BaseBaremetalTest): """Tests for API discovery features.""" @decorators.idempotent_id('a3c27e94-f56c-42c4-8600-d6790650b9c5') def test_api_versions(self): _, descr = self.client.get_api_description() expected_versions = ('v1',) versions = [version['id'] f...
class TestApiDiscovery(base.BaseBaremetalTest):
"""Tests for API discovery features.""" @decorators.idempotent_id('a3c27e94-f56c-42c4-8600-d6790650b9c5') def test_api_versions(self): _, descr = self.client.get_api_description() expected_versions = ('v1',) versions = [version['id'] for version in descr['versions']] for v ...
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from ironic_tempest_plug...
81
81
270
10
70
NaohiroTamura/ironic
ironic_tempest_plugin/tests/api/admin/test_api_discovery.py
Python
TestApiDiscovery
TestApiDiscovery
18
43
18
18
1bf167804db7c17aa82b8068fe609937bc199a61
bigcode/the-stack
train
e994847acbac0a6de04cf3c3
train
class
class BaseCommand(metaclass=abc.ABCMeta): logger: logging.Logger = None @property @abc.abstractmethod def name(self) -> str: """ :return: The short name for the command. """ @property @abc.abstractmethod def description(self) -> str: """ :return: The...
class BaseCommand(metaclass=abc.ABCMeta):
logger: logging.Logger = None @property @abc.abstractmethod def name(self) -> str: """ :return: The short name for the command. """ @property @abc.abstractmethod def description(self) -> str: """ :return: The description for this command """ ...
import abc import logging import argparse from colorlog import ColoredFormatter from freezing.model import init_model from freezing.sync.config import config, init_logging from freezing.sync.exc import CommandError class BaseCommand(metaclass=abc.ABCMeta):
53
146
488
12
40
freezingsaddles/freezing-process
freezing/sync/cli/__init__.py
Python
BaseCommand
BaseCommand
12
104
12
12
767558cec0e4fd6c7fac975043ac8e06b1d3cd29
bigcode/the-stack
train
bc25bbd1bf7d8499d8d5263e
train
function
def get_pwsh_script(path: str) -> str: """ Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to reduce the data we send across as much as possible. Source: https://github.com/jborean93/pypsrp :param path: The filename of the script in pypsrp...
def get_pwsh_script(path: str) -> str:
""" Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to reduce the data we send across as much as possible. Source: https://github.com/jborean93/pypsrp :param path: The filename of the script in pypsrp/pwsh_scripts to get. :return: The ...
import logging def get_pwsh_script(path: str) -> str:
15
64
192
12
2
maybe-hello-world/tortilla-scvmm
scvmmapi/utils.py
Python
get_pwsh_script
get_pwsh_script
4
27
4
4
12e18271ec1bed4f16255fda288dbfcfa189bcb3
bigcode/the-stack
train
013fb5d9e74be114775556f0
train
class
class NoHeaderErrorFilter(logging.Filter): """Filter out urllib3 Header Parsing Errors due to a urllib3 bug.""" def filter(self, record): """Filter out Header Parsing Errors.""" return "Failed to parse headers" not in record.getMessage()
class NoHeaderErrorFilter(logging.Filter):
"""Filter out urllib3 Header Parsing Errors due to a urllib3 bug.""" def filter(self, record): """Filter out Header Parsing Errors.""" return "Failed to parse headers" not in record.getMessage()
line = line.strip() if block_comment: block_comment = not line.endswith('#>') elif line.startswith('<#'): block_comment = True elif line and not line.startswith('#'): new_lines.append(line) return '\n'.join(new_lines) class NoHeaderErrorFilter(logging.Fi...
64
64
53
8
56
maybe-hello-world/tortilla-scvmm
scvmmapi/utils.py
Python
NoHeaderErrorFilter
NoHeaderErrorFilter
30
35
30
30
7f1439bf4191a130b9ff9847234d61eb7c12141b
bigcode/the-stack
train
10e519df3a93fd77b1767044
train
function
def create(kernel): result = Tangible() result.template = "object/tangible/ship/attachment/weapon/shared_hutt_medium_weapon2_s02.iff" result.attribute_template_id = 8 result.stfName("item_n","ship_attachment") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def create(kernel):
result = Tangible() result.template = "object/tangible/ship/attachment/weapon/shared_hutt_medium_weapon2_s02.iff" result.attribute_template_id = 8 result.stfName("item_n","ship_attachment") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel):
46
64
73
4
42
obi-two/GameServer
data/scripts/templates/object/tangible/ship/attachment/weapon/shared_hutt_medium_weapon2_s02.py
Python
create
create
7
17
7
7
6a5f5718d1f3a0d4cf02f91921a31a7a3cb67a56
bigcode/the-stack
train
78c9be941f700a1da79fbe63
train
function
def relaxation_tau(k_arr, T, N_theta): """ Compute scattering probability for each k from k_arr \param T temperature in hoomd units \param N_theta number of theta-points return w_k_res - total scattering rate vs k (array of size N_k) w_k_theta - 2D array, each row w_k_theta[i,...
def relaxation_tau(k_arr, T, N_theta):
""" Compute scattering probability for each k from k_arr \param T temperature in hoomd units \param N_theta number of theta-points return w_k_res - total scattering rate vs k (array of size N_k) w_k_theta - 2D array, each row w_k_theta[i,:] is w(theta) distribution for k_i ...
F_inv = hbar/m_e*psm.compute_cumulative_Fkkp_inv(fkkp, k_arr, tol=0.1) return w_k, W_inv, wk_ph, F_inv, Y_inv, vmin, vmax def relaxation_tau(k_arr, T, N_theta):
64
64
169
11
52
kmoskovtsev/Electrons-on-Helium-Scripts
diffArray_p_scatter_only.py
Python
relaxation_tau
relaxation_tau
51
65
51
51
57f5666af1bf55bf36c9d7c233b44fa591a8c93e
bigcode/the-stack
train
eb6b43f92de171c75e4755b9
train
function
def scattering_wrapper(kmin, kmax, Nk, N_W, N_theta_rpl, Ntheta, NY, T): k_arr = np.linspace(kmin, kmax, Nk) #Ripplon scattering parameters rsm.init(unit_M, unit_D, unit_E) W_resampled = np.linspace(0,1, N_W) theta_arr_rpl = np.linspace(0, 2*np.pi, N_theta_rpl) w_k, W_inv, W_cumul, vmin, v...
def scattering_wrapper(kmin, kmax, Nk, N_W, N_theta_rpl, Ntheta, NY, T):
k_arr = np.linspace(kmin, kmax, Nk) #Ripplon scattering parameters rsm.init(unit_M, unit_D, unit_E) W_resampled = np.linspace(0,1, N_W) theta_arr_rpl = np.linspace(0, 2*np.pi, N_theta_rpl) w_k, W_inv, W_cumul, vmin, vmax = rsm.scattering_parameters(T, kmin, kmax, Nk, N_W, N_theta_rpl) ...
Agg') import matplotlib.pyplot as plt import hoomd import hoomd.md import gsd #import matplotlib.pyplot as plt import numpy as np from scipy.special import erf as erf import os import sys import datetime import ewald_module as em import md_tools27 as md_tools import time import pickle from shutil import ...
133
133
444
26
106
kmoskovtsev/Electrons-on-Helium-Scripts
diffArray_p_scatter_only.py
Python
scattering_wrapper
scattering_wrapper
26
49
26
26
15d07bfc684ac61d310c3ec1f240d445895b7230
bigcode/the-stack
train
7ad3446ed4201217874db1e0
train
function
def revocation_listener(): """ This configures and starts the revocation listener. It is designed to be started in a separate process. """ if config.has_option('cloud_agent', 'listen_notifications'): if not config.getboolean('cloud_agent', 'listen_notifications'): return # keep...
def revocation_listener():
""" This configures and starts the revocation listener. It is designed to be started in a separate process. """ if config.has_option('cloud_agent', 'listen_notifications'): if not config.getboolean('cloud_agent', 'listen_notifications'): return # keep old typo "listen_notficati...
bitxor(decrypted_U, decrypted_V) # be very careful printing K, U, or V as they leak in logs stored on unprotected disks if config.INSECURE_DEBUG: logger.debug("U: %s", base64.b64encode(decrypted_U)) logger.debug("V: %s", base64.b64encode(decrypted_V)) logger.debug("K...
192
192
643
5
186
mit-ll/keylime
keylime/keylime_agent.py
Python
revocation_listener
revocation_listener
553
625
553
553
049ced8b9a2042b939369e3388a14551d9ad8e9c
bigcode/the-stack
train
07cf29219fa4e018c81ec767
train
class
class Handler(BaseHTTPRequestHandler): parsed_path = '' def do_HEAD(self): """Not supported""" web_util.echo_json_response(self, 405, "HEAD not supported") def do_GET(self): """This method services the GET request typically from either the Tenant or the Cloud Verifier. Onl...
class Handler(BaseHTTPRequestHandler):
parsed_path = '' def do_HEAD(self): """Not supported""" web_util.echo_json_response(self, 405, "HEAD not supported") def do_GET(self): """This method services the GET request typically from either the Tenant or the Cloud Verifier. Only tenant and cloudverifier uri's are su...
file import io import importlib import shutil import subprocess import psutil from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from keylime import config from keylime import keylime_logging from keylime import cmd_exec from...
256
256
3,072
6
250
mit-ll/keylime
keylime/keylime_agent.py
Python
Handler
Handler
64
374
64
64
4606eff26ceaba37be5ead83ea09a02adaedfc60
bigcode/the-stack
train
b829c5f9e22ce476a5b7c18e
train
class
class CloudAgentHTTPServer(ThreadingMixIn, HTTPServer): """Http Server which will handle each request in a separate thread.""" # Do not modify directly unless you acquire uvLock. Set chosen for uniqueness of contained values u_set = set() v_set = set() rsaprivatekey = None rsapublickey = None ...
class CloudAgentHTTPServer(ThreadingMixIn, HTTPServer):
"""Http Server which will handle each request in a separate thread.""" # Do not modify directly unless you acquire uvLock. Set chosen for uniqueness of contained values u_set = set() v_set = set() rsaprivatekey = None rsapublickey = None rsapublickey_exportable = None mtls_cert_path = ...
s/unzipped", initscript, secdir) else: logger.info("Executing payload script: %s/unzipped/%s", secdir, initscript) payload_thread = threading.Thread(target=initthread, daemon=True) else: logger.info("Decrypting payload to %s...
256
256
1,693
13
242
mit-ll/keylime
keylime/keylime_agent.py
Python
CloudAgentHTTPServer
CloudAgentHTTPServer
380
550
380
380
39986f784d6031c5d1c2280cd8ce443c2bf1e37f
bigcode/the-stack
train
a7c4e7c8e70794a019b705c9
train
function
def main(): for ML in [config.MEASUREDBOOT_ML, config.IMA_ML]: if not os.access(ML, os.F_OK): logger.warning("Measurement list path %s not accessible by agent. Any attempt to instruct it to access this path - via \"keylime_tenant\" CLI - will result in agent process dying", ML) ima_log_file...
def main():
for ML in [config.MEASUREDBOOT_ML, config.IMA_ML]: if not os.access(ML, os.F_OK): logger.warning("Measurement list path %s not accessible by agent. Any attempt to instruct it to access this path - via \"keylime_tenant\" CLI - will result in agent process dying", ML) ima_log_file = None ...
localactions = actionlisttxt.strip().split(',') for action in localactions: if not action.startswith('local_action_'): logger.warning("Invalid local action: %s. Must start with local_action_", action) else: actionli...
255
256
1,968
3
253
mit-ll/keylime
keylime/keylime_agent.py
Python
main
main
628
811
628
628
7226cb0143b9d4d4e9c2b50fd123701239488760
bigcode/the-stack
train
352e1ec62723a61131d78645
train
class
class Poller(_AsyncIO, _future._AsyncPoller): """Poller returning asyncio.Future for poll results.""" def _watch_raw_socket(self, loop, socket, evt, f): """Schedule callback for a raw socket""" selector = _get_selector(loop) if evt & self._READ: selector.add_reader(socket, l...
class Poller(_AsyncIO, _future._AsyncPoller):
"""Poller returning asyncio.Future for poll results.""" def _watch_raw_socket(self, loop, socket, evt, f): """Schedule callback for a raw socket""" selector = _get_selector(loop) if evt & self._READ: selector.add_reader(socket, lambda *args: f()) if evt & self._WRITE...
get_selector = _get_selector_noop class _AsyncIO: _Future = Future _WRITE = selectors.EVENT_WRITE _READ = selectors.EVENT_READ def _default_loop(self): return asyncio.get_event_loop() class Poller(_AsyncIO, _future._AsyncPoller):
64
64
150
14
50
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
Poller
Poller
106
122
106
106
ab570e46a09d6e4479c886181108c8fe8d663c01
bigcode/the-stack
train
ac9d58478e90c94d3ed27f00
train
class
class ZMQEventLoop(SelectorEventLoop): """DEPRECATED: AsyncIO eventloop using zmq_poll. pyzmq sockets should work with any asyncio event loop as of pyzmq 17. """ def __init__(self, selector=None): _deprecated() return super(ZMQEventLoop, self).__init__(selector)
class ZMQEventLoop(SelectorEventLoop):
"""DEPRECATED: AsyncIO eventloop using zmq_poll. pyzmq sockets should work with any asyncio event loop as of pyzmq 17. """ def __init__(self, selector=None): _deprecated() return super(ZMQEventLoop, self).__init__(selector)
remove_reader(self._fd) Poller._socket_class = Socket class Context(_zmq.Context): """Context for creating asyncio-compatible Sockets""" _socket_class = Socket # avoid sharing instance with base Context class _instance = None class ZMQEventLoop(SelectorEventLoop):
64
64
74
10
53
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
ZMQEventLoop
ZMQEventLoop
163
171
163
163
e4bd051b200dac5831c8bf75b259c1da61817d29
bigcode/the-stack
train
eb6b6d0bb718c06f61da39fc
train
class
class ProactorSelectorThreadWarning(RuntimeWarning): """Warning class for notifying about the extra thread spawned by tornado We automatically support proactor via tornado's AddThreadSelectorEventLoop"""
class ProactorSelectorThreadWarning(RuntimeWarning):
"""Warning class for notifying about the extra thread spawned by tornado We automatically support proactor via tornado's AddThreadSelectorEventLoop"""
import warnings from asyncio import SelectorEventLoop, Future from weakref import WeakKeyDictionary import zmq as _zmq from zmq import _future # registry of asyncio loop : selector thread _selectors: WeakKeyDictionary = WeakKeyDictionary() class ProactorSelectorThreadWarning(RuntimeWarning):
64
64
38
9
55
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
ProactorSelectorThreadWarning
ProactorSelectorThreadWarning
23
26
23
23
a6276029eee18309190581f690e93fbc81af9296
bigcode/the-stack
train
ad216b9918c9f1cb0dda84d6
train
class
class Socket(_AsyncIO, _future._AsyncSocket): """Socket returning asyncio Futures for send/recv/poll methods.""" _poller_class = Poller def _get_selector(self, io_loop=None): if io_loop is None: io_loop = self._get_loop() return _get_selector(io_loop) def _init_io_state(se...
class Socket(_AsyncIO, _future._AsyncSocket):
"""Socket returning asyncio Futures for send/recv/poll methods.""" _poller_class = Poller def _get_selector(self, io_loop=None): if io_loop is None: io_loop = self._get_loop() return _get_selector(io_loop) def _init_io_state(self, io_loop=None): """initialize the i...
def _unwatch_raw_sockets(self, loop, *sockets): """Unschedule callback for a raw socket""" selector = _get_selector(loop) for socket in sockets: selector.remove_reader(socket) selector.remove_writer(socket) class Socket(_AsyncIO, _future._AsyncSocket):
64
64
186
12
52
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
Socket
Socket
125
148
125
125
036b039f8b160607d12e75573208f98a8b9908cf
bigcode/the-stack
train
1748fe4722eaa3ca0bc6e777
train
function
def _deprecated(): if _deprecated.called: # type: ignore return _deprecated.called = True # type: ignore warnings.warn( "ZMQEventLoop and zmq.asyncio.install are deprecated in pyzmq 17. Special eventloop integration is no longer needed.", DeprecationWarning, stacklevel=3, ...
def _deprecated():
if _deprecated.called: # type: ignore return _deprecated.called = True # type: ignore warnings.warn( "ZMQEventLoop and zmq.asyncio.install are deprecated in pyzmq 17. Special eventloop integration is no longer needed.", DeprecationWarning, stacklevel=3, )
loop using zmq_poll. pyzmq sockets should work with any asyncio event loop as of pyzmq 17. """ def __init__(self, selector=None): _deprecated() return super(ZMQEventLoop, self).__init__(selector) _loop = None def _deprecated():
64
64
79
4
59
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
_deprecated
_deprecated
177
186
177
177
38ff148b89c547da591a03a0a5d15d73655086a6
bigcode/the-stack
train
babafa4f34a65cfc1242d5b1
train
class
class Context(_zmq.Context): """Context for creating asyncio-compatible Sockets""" _socket_class = Socket # avoid sharing instance with base Context class _instance = None
class Context(_zmq.Context):
"""Context for creating asyncio-compatible Sockets""" _socket_class = Socket # avoid sharing instance with base Context class _instance = None
event handler called once at close """ loop = self._current_loop if loop and not loop.is_closed() and self._fd != -1: self._get_selector(loop).remove_reader(self._fd) Poller._socket_class = Socket class Context(_zmq.Context):
64
64
40
7
56
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
Context
Context
154
160
154
154
40f74546ce8c018b92655cbb339fdada124ff4f6
bigcode/the-stack
train
ce85519e9f2b9a7d606fe66c
train
function
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop: """no-op on non-Windows""" return loop
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop:
"""no-op on non-Windows""" return loop
loop.close! asyncio_loop.close = loop_close _selectors.pop(asyncio_loop, None) selector_loop.close() asyncio_loop.close = _close_selector_and_loop return selector_loop else: return asyncio_loop def _get_selector_noop(loop) -> asyncio.AbstractEventLoop:
64
64
27
14
49
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
_get_selector_noop
_get_selector_noop
86
88
86
86
4b6ef783e2401ca403e2363b9017e775a68b606d
bigcode/the-stack
train
90801fa2b418353256be7861
train
function
def _get_selector_windows( asyncio_loop, ) -> asyncio.AbstractEventLoop: """Get selector-compatible loop Returns an object with ``add_reader`` family of methods, either the loop itself or a SelectorThread instance. Workaround Windows proactor removal of *reader methods, which we need for zmq s...
def _get_selector_windows( asyncio_loop, ) -> asyncio.AbstractEventLoop:
"""Get selector-compatible loop Returns an object with ``add_reader`` family of methods, either the loop itself or a SelectorThread instance. Workaround Windows proactor removal of *reader methods, which we need for zmq sockets. """ if asyncio_loop in _selectors: return _selectors...
PyZMQ Developers. # Distributed under the terms of the Modified BSD License. import asyncio import selectors import sys import warnings from asyncio import SelectorEventLoop, Future from weakref import WeakKeyDictionary import zmq as _zmq from zmq import _future # registry of asyncio loop : selector thread _selecto...
135
135
450
17
118
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
_get_selector_windows
_get_selector_windows
29
83
29
31
a2326e7ca80b12a14d88dc7a9cfb9ca31f2091a4
bigcode/the-stack
train
a5735d15384ebf8026b294ca
train
function
def install(): """DEPRECATED: No longer needed in pyzmq 17""" _deprecated()
def install():
"""DEPRECATED: No longer needed in pyzmq 17""" _deprecated()
ignore warnings.warn( "ZMQEventLoop and zmq.asyncio.install are deprecated in pyzmq 17. Special eventloop integration is no longer needed.", DeprecationWarning, stacklevel=3, ) _deprecated.called = False # type: ignore def install():
64
64
22
3
60
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
install
install
192
194
192
192
e4a368c89647b85bfa1c7af3a1e210dd3fc64eb6
bigcode/the-stack
train
cb379da787329985eff4444a
train
class
class _AsyncIO: _Future = Future _WRITE = selectors.EVENT_WRITE _READ = selectors.EVENT_READ def _default_loop(self): return asyncio.get_event_loop()
class _AsyncIO:
_Future = Future _WRITE = selectors.EVENT_WRITE _READ = selectors.EVENT_READ def _default_loop(self): return asyncio.get_event_loop()
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop: """no-op on non-Windows""" return loop if sys.platform == "win32": _get_selector = _get_selector_windows else: _get_selector = _get_selector_noop class _AsyncIO:
64
64
41
5
58
ajayiagbebaku/NFL-Model
venv/Lib/site-packages/zmq/asyncio.py
Python
_AsyncIO
_AsyncIO
97
103
97
97
18882062d5dd21dd6390dd22f9f2ddbb092b8be2
bigcode/the-stack
train
d6873a59b97cd2f7182d8f76
train
function
@source("/from") @destination("/to") def ruleNestedElement(s): return s
@source("/from") @destination("/to") def ruleNestedElement(s):
return s
# Expect: ValueError # a rules file must not contain two rules with the same name. # If so, python would overwrite those rules and only use the # second rule. from ruledxml import destination, source @source("/from") @destination("/to") def ruleNestedElement(s):
62
64
20
16
45
meisterluk/ruledxml
ruledxml/tests/data/010_rules.py
Python
ruleNestedElement
ruleNestedElement
10
13
10
12
7afc4ec6698989053bef5556971a0ffe9a805d3b
bigcode/the-stack
train
86da5e54deaeaacb73d42fbb
train
function
@source("/from") @destination("/to") def ruleNestedElement(s): return s
@source("/from") @destination("/to") def ruleNestedElement(s):
return s
name. # If so, python would overwrite those rules and only use the # second rule. from ruledxml import destination, source @source("/from") @destination("/to") def ruleNestedElement(s): return s @source("/from") @destination("/to") def ruleNestedElement(s):
64
64
20
16
47
meisterluk/ruledxml
ruledxml/tests/data/010_rules.py
Python
ruleNestedElement
ruleNestedElement
15
18
15
17
7afc4ec6698989053bef5556971a0ffe9a805d3b
bigcode/the-stack
train
adeb232245ab013755500343
train
class
class Html: def __init__(self, html_str): self.__html_str = html_str self.__markup_safe = Markup(html_str) self.__plain_text = None @property def as_plain_text(self): if self.__plain_text is None: self.__plain_text = self.__markup_safe.striptags() ...
class Html:
def __init__(self, html_str): self.__html_str = html_str self.__markup_safe = Markup(html_str) self.__plain_text = None @property def as_plain_text(self): if self.__plain_text is None: self.__plain_text = self.__markup_safe.striptags() return sel...
license: "MIT" maintainer: "Md. Sabuj Sarker" email: "md.sabuj.sarker@gmail.com" status: "Development" """ from markupsafe import Markup from synamic.core.standalones.functions.md import render_content_markdown class Html:
64
64
190
3
60
SabujXi/SynamicX
src/synamic/core/services/types/types.py
Python
Html
Html
15
46
15
15
428278230cae42fca7c2789ed223b73a002c2bc5
bigcode/the-stack
train
d1af631188da86ee29d12332
train
class
class Markdown: def __init__(self, site, md_str, value_pack=None, md_cpath=None, cfields=None): self.__site = site self.__md_str = md_str self.__value_pack = value_pack self.__md_cpath = md_cpath self.__cfields = cfields self.__html_obj = None self.__p...
class Markdown:
def __init__(self, site, md_str, value_pack=None, md_cpath=None, cfields=None): self.__site = site self.__md_str = md_str self.__value_pack = value_pack self.__md_cpath = md_cpath self.__cfields = cfields self.__html_obj = None self.__plain_text = None ...
is not None: return self.as_plain_text[:limit] else: return self.as_plain_text @property def as_str(self): return self.__html_str @property def as_markup(self): """Returns markup object from markupsafe""" return self.__markup_safe ...
99
100
336
3
96
SabujXi/SynamicX
src/synamic/core/services/types/types.py
Python
Markdown
Markdown
49
95
49
49
734da5f563ec3a4c0ee538c098a60f2eacd100dd
bigcode/the-stack
train
8d5d79d08a9e580a97843225
train
function
def AC_pade_thiele_diag(sigma, omega): """ Analytic continuation to real axis using a Pade approximation from Thiele's reciprocal difference method Reference: J. Low Temp. Phys. 29, 179 (1977) Returns: coeff: 2D array (ncoeff, norbs) omega: 2D array (norbs, npade) """ idx = r...
def AC_pade_thiele_diag(sigma, omega):
""" Analytic continuation to real axis using a Pade approximation from Thiele's reciprocal difference method Reference: J. Low Temp. Phys. 29, 179 (1977) Returns: coeff: 2D array (ncoeff, norbs) omega: 2D array (norbs, npade) """ idx = range(1,40,6) sigma1 = sigma[:,idx]....
= coeff[-1]*(freqs-zn[-2]) for i in range(nfit-1): idx = nfit-i-1 X = coeff[idx]*(freqs-zn[idx-1])/(1.+X) X = coeff[0]/(1.+X) return X def AC_pade_thiele_diag(sigma, omega):
78
78
263
12
65
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
AC_pade_thiele_diag
AC_pade_thiele_diag
509
531
509
509
44efeea0e4bc725c1ac0c527f06ba323bf091c35
bigcode/the-stack
train
6390d73dfa52b5e8d74bf49b
train
function
def get_rho_response_head(gw, omega, mo_energy, qij): ''' Compute head (G=0, G'=0) density response function in auxiliary basis at freq iw ''' nkpts, nocc, nvir = qij.shape nocc = gw.nocc kpts = gw.kpts # Compute Pi head Pi_00 = 0j for i, kpti in enumerate(kpts): eia = mo_en...
def get_rho_response_head(gw, omega, mo_energy, qij):
''' Compute head (G=0, G'=0) density response function in auxiliary basis at freq iw ''' nkpts, nocc, nvir = qij.shape nocc = gw.nocc kpts = gw.kpts # Compute Pi head Pi_00 = 0j for i, kpti in enumerate(kpts): eia = mo_energy[i,:nocc,None] - mo_energy[i,None,nocc:] e...
m])/np.pi sigma[k][norbs_occ:] += -einsum('mn,mw->nw',Wmn[:,norbs_occ:],g0_vir[km])/np.pi return sigma, omega def get_rho_response_head(gw, omega, mo_energy, qij):
64
64
174
17
46
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
get_rho_response_head
get_rho_response_head
353
367
353
353
2caf38eb1c766c8cdd23734eb0b9660bfc6402e3
bigcode/the-stack
train
709e4fdd8d89699a725a77b2
train
function
def two_pole(freqs, coeff): cf = coeff[:5] + 1j*coeff[5:] return cf[0] + cf[1]/(freqs+cf[3]) + cf[2]/(freqs+cf[4])
def two_pole(freqs, coeff):
cf = coeff[:5] + 1j*coeff[5:] return cf[0] + cf[1]/(freqs+cf[3]) + cf[2]/(freqs+cf[4])
+ cf[1]/(omega+cf[3]) + cf[2]/(omega+cf[4]) - sigma f[0] = f[0]/0.01 return np.array([f.real,f.imag]).reshape(-1) def two_pole(freqs, coeff):
64
64
57
9
55
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
two_pole
two_pole
466
468
466
466
3956a6c22fa3b7720e1d0d407100ca75a1e663fa
bigcode/the-stack
train
b94acdcd8f18f08c2191fcfc
train
function
def _get_scaled_legendre_roots(nw): """ Scale nw Legendre roots, which lie in the interval [-1, 1], so that they lie in [0, inf) Ref: www.cond-mat.de/events/correl19/manuscripts/ren.pdf Returns: freqs : 1D ndarray wts : 1D ndarray """ freqs, wts = np.polynomial.legendre.legg...
def _get_scaled_legendre_roots(nw):
""" Scale nw Legendre roots, which lie in the interval [-1, 1], so that they lie in [0, inf) Ref: www.cond-mat.de/events/correl19/manuscripts/ren.pdf Returns: freqs : 1D ndarray wts : 1D ndarray """ freqs, wts = np.polynomial.legendre.leggauss(nw) x0 = 0.5 freqs_new ...
./(mo_energy[i][nocc:,None] - mo_energy[i][None,:nocc]) dens = enm.T * q_mo_mo_grad qij[i] = dens / np.sqrt(cell.vol) return qij def _get_scaled_legendre_roots(nw):
64
64
162
11
52
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
_get_scaled_legendre_roots
_get_scaled_legendre_roots
424
438
424
424
37a695a6c2be4e8cf820e981b22cf40e3fd5f6dc
bigcode/the-stack
train
7d43cff78a70daa0da839cae
train
function
def _get_clenshaw_curtis_roots(nw): """ Clenshaw-Curtis qaudrature on [0,inf) Ref: J. Chem. Phys. 132, 234114 (2010) Returns: freqs : 1D ndarray wts : 1D ndarray """ freqs = np.zeros(nw) wts = np.zeros(nw) a = 0.2 for w in range(nw): t = (w+1.0)/nw * np.pi/2. ...
def _get_clenshaw_curtis_roots(nw):
""" Clenshaw-Curtis qaudrature on [0,inf) Ref: J. Chem. Phys. 132, 234114 (2010) Returns: freqs : 1D ndarray wts : 1D ndarray """ freqs = np.zeros(nw) wts = np.zeros(nw) a = 0.2 for w in range(nw): t = (w+1.0)/nw * np.pi/2. freqs[w] = a / np.tan(t) ...
0.5 freqs_new = x0*(1.+freqs)/(1.-freqs) wts = wts*2.*x0/(1.-freqs)**2 return freqs_new, wts def _get_clenshaw_curtis_roots(nw):
64
64
202
14
49
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
_get_clenshaw_curtis_roots
_get_clenshaw_curtis_roots
440
458
440
440
5bea1d5c4fb3fcec966f7ce330dc6685e6d4418d
bigcode/the-stack
train
8f964680fc96866502b1d2c5
train
function
def get_sigma_diag(gw, orbs, kptlist, freqs, wts, iw_cutoff=None, max_memory=8000): ''' Compute GW correlation self-energy (diagonal elements) in MO basis on imaginary axis ''' mo_energy = np.array(gw._scf.mo_energy) mo_coeff = np.array(gw._scf.mo_coeff) nocc = gw.nocc nmo = gw.nmo n...
def get_sigma_diag(gw, orbs, kptlist, freqs, wts, iw_cutoff=None, max_memory=8000):
''' Compute GW correlation self-energy (diagonal elements) in MO basis on imaginary axis ''' mo_energy = np.array(gw._scf.mo_energy) mo_coeff = np.array(gw._scf.mo_coeff) nocc = gw.nocc nmo = gw.nmo nkpts = gw.nkpts kpts = gw.kpts nklist = len(kptlist) nw = len(freqs) ...
, nmo = Lpq.shape nocc = gw.nocc kpts = gw.kpts kscaled = gw.mol.get_scaled_kpts(kpts) kscaled -= kscaled[0] # Compute Pi for kL Pi = np.zeros((naux,naux),dtype=np.complex128) for i, kpti in enumerate(kpts): # Find ka that conserves with ki and kL (-ki+ka+kL=G) a = kidx[i] ...
256
256
2,390
31
224
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
get_sigma_diag
get_sigma_diag
185
351
185
185
8a12f1bdc6e4e1643f6a704182590d7ac4ae1e8f
bigcode/the-stack
train
cfc41e90024654f778d8533c
train
function
def pade_thiele(freqs,zn,coeff): nfit = len(coeff) X = coeff[-1]*(freqs-zn[-2]) for i in range(nfit-1): idx = nfit-i-1 X = coeff[idx]*(freqs-zn[idx-1])/(1.+X) X = coeff[0]/(1.+X) return X
def pade_thiele(freqs,zn,coeff):
nfit = len(coeff) X = coeff[-1]*(freqs-zn[-2]) for i in range(nfit-1): idx = nfit-i-1 X = coeff[idx]*(freqs-zn[idx-1])/(1.+X) X = coeff[0]/(1.+X) return X
fit): g[i:,i] = (g[i-1,i-1]-g[i:,i-1])/((zn[i:]-zn[i-1])*g[i:,i-1]) a = g.diagonal() return a def pade_thiele(freqs,zn,coeff):
64
64
86
11
52
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
pade_thiele
pade_thiele
500
507
500
500
07e534ca6ca1302bd783f35c3e88761380db80f2
bigcode/the-stack
train
2c4b4a752097150ebeefcfdc
train
function
def get_qij(gw, q, mo_coeff, uniform_grids=False): ''' Compute qij = 1/Omega * |< psi_{ik} | e^{iqr} | psi_{ak-q} >|^2 at q: (nkpts, nocc, nvir) through kp perturbtation theory Ref: Phys. Rev. B 83, 245122 (2011) ''' nocc = gw.nocc nmo = gw.nmo nvir = nmo - nocc kpts = gw.kpts nk...
def get_qij(gw, q, mo_coeff, uniform_grids=False):
''' Compute qij = 1/Omega * |< psi_{ik} | e^{iqr} | psi_{ak-q} >|^2 at q: (nkpts, nocc, nvir) through kp perturbtation theory Ref: Phys. Rev. B 83, 245122 (2011) ''' nocc = gw.nocc nmo = gw.nmo nvir = nmo - nocc kpts = gw.kpts nkpts = len(kpts) cell = gw.mol mo_energy = g...
kpts = gw.kpts # Compute Pi wing Pi = np.zeros(naux,dtype=np.complex128) for i, kpti in enumerate(kpts): eia = mo_energy[i,:nocc,None] - mo_energy[i,None,nocc:] eia = eia/(omega**2+eia*eia) eia_q = eia * qij[i].conj() Pi += 4./nkpts * einsum('Pia,ia->P',Lpq[i][:,:nocc,no...
145
145
485
17
127
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
get_qij
get_qij
386
422
386
386
ca91cb66820dea464fb9385639f87810221a0f80
bigcode/the-stack
train
261f940f2a9834a05f7562bb
train
function
def two_pole_fit(coeff, omega, sigma): cf = coeff[:5] + 1j*coeff[5:] f = cf[0] + cf[1]/(omega+cf[3]) + cf[2]/(omega+cf[4]) - sigma f[0] = f[0]/0.01 return np.array([f.real,f.imag]).reshape(-1)
def two_pole_fit(coeff, omega, sigma):
cf = coeff[:5] + 1j*coeff[5:] f = cf[0] + cf[1]/(omega+cf[3]) + cf[2]/(omega+cf[4]) - sigma f[0] = f[0]/0.01 return np.array([f.real,f.imag]).reshape(-1)
ts[w] = a*np.pi/2./nw/(np.sin(t)**2) else: wts[w] = a*np.pi/4./nw/(np.sin(t)**2) return freqs[::-1], wts[::-1] def two_pole_fit(coeff, omega, sigma):
64
64
89
11
53
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
two_pole_fit
two_pole_fit
460
464
460
460
617c6ec01451dd125c23fe5e36df0fa45ee07452
bigcode/the-stack
train
54f7794ff0d1e453ac520bc3
train
function
def get_rho_response(gw, omega, mo_energy, Lpq, kL, kidx): ''' Compute density response function in auxiliary basis at freq iw ''' nkpts, naux, nmo, nmo = Lpq.shape nocc = gw.nocc kpts = gw.kpts kscaled = gw.mol.get_scaled_kpts(kpts) kscaled -= kscaled[0] # Compute Pi for kL Pi ...
def get_rho_response(gw, omega, mo_energy, Lpq, kL, kidx):
''' Compute density response function in auxiliary basis at freq iw ''' nkpts, naux, nmo, nmo = Lpq.shape nocc = gw.nocc kpts = gw.kpts kscaled = gw.mol.get_scaled_kpts(kpts) kscaled -= kscaled[0] # Compute Pi for kL Pi = np.zeros((naux,naux),dtype=np.complex128) for i, kpti...
reshold=nmo) for k in range(nkpts): logger.debug(gw, ' GW mo_energy @ k%d =\n%s', k,mo_energy[k]) numpy.set_printoptions(threshold=1000) return conv, mo_energy, mo_coeff def get_rho_response(gw, omega, mo_energy, Lpq, kL, kidx):
81
81
272
22
58
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
get_rho_response
get_rho_response
163
183
163
163
3d678adde534674f95852420651c98610c64a4d7
bigcode/the-stack
train
d284552b11bbe4ea584be6cb
train
function
def kernel(gw, mo_energy, mo_coeff, orbs=None, kptlist=None, nw=None, verbose=logger.NOTE): '''GW-corrected quasiparticle orbital energies Returns: A list : converged, mo_energy, mo_coeff ''' mf = gw._scf if gw.frozen is None: frozen = 0 else: frozen = gw.fro...
def kernel(gw, mo_energy, mo_coeff, orbs=None, kptlist=None, nw=None, verbose=logger.NOTE):
'''GW-corrected quasiparticle orbital energies Returns: A list : converged, mo_energy, mo_coeff ''' mf = gw._scf if gw.frozen is None: frozen = 0 else: frozen = gw.frozen assert (frozen == 0) if orbs is None: orbs = range(gw.nmo) if kptlist is None:...
GW-CD (N^4) and analytic GW (N^6) methods. GW-AC is recommended for valence states only, and is inaccuarate for core states. Method: See T. Zhu and G.K.-L. Chan, arxiv:2007.03148 (2020) for details Compute Sigma on imaginary frequency with density fitting, then analytically continued to real frequency. ...
256
256
1,268
30
225
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
kernel
kernel
48
161
48
49
4d41df8ce7b24d03b8e30f3cda13d1ab1b1e6107
bigcode/the-stack
train
69e6919f9d4dc856f75f44fa
train
function
def thiele(fn,zn): nfit = len(zn) g = np.zeros((nfit,nfit),dtype=np.complex128) g[:,0] = fn.copy() for i in range(1,nfit): g[i:,i] = (g[i-1,i-1]-g[i:,i-1])/((zn[i:]-zn[i-1])*g[i:,i-1]) a = g.diagonal() return a
def thiele(fn,zn):
nfit = len(zn) g = np.zeros((nfit,nfit),dtype=np.complex128) g[:,0] = fn.copy() for i in range(1,nfit): g[i:,i] = (g[i-1,i-1]-g[i:,i-1])/((zn[i:]-zn[i-1])*g[i:,i-1]) a = g.diagonal() return a
=(omega[p], sigma[p])) if xopt.success is False: print('WARN: 2P-Fit Orb %d not converged, cost function %e'%(p,xopt.cost)) coeff[:,p] = xopt.x.copy() return coeff def thiele(fn,zn):
64
64
102
7
56
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
thiele
thiele
491
498
491
491
3ab31c51a30e01069cdd561ed7488d74607da851
bigcode/the-stack
train
b31f512dd782a5887640a23f
train
function
def get_rho_response_wing(gw, omega, mo_energy, Lpq, qij): ''' Compute wing (G=P, G'=0) density response function in auxiliary basis at freq iw ''' nkpts, naux, nmo, nmo = Lpq.shape nocc = gw.nocc kpts = gw.kpts # Compute Pi wing Pi = np.zeros(naux,dtype=np.complex128) for i, kpti i...
def get_rho_response_wing(gw, omega, mo_energy, Lpq, qij):
''' Compute wing (G=P, G'=0) density response function in auxiliary basis at freq iw ''' nkpts, naux, nmo, nmo = Lpq.shape nocc = gw.nocc kpts = gw.kpts # Compute Pi wing Pi = np.zeros(naux,dtype=np.complex128) for i, kpti in enumerate(kpts): eia = mo_energy[i,:nocc,None] - ...
ia*eia) Pi_00 += 4./nkpts * einsum('ia,ia->',eia,qij[i].conj()*qij[i]) return Pi_00 def get_rho_response_wing(gw, omega, mo_energy, Lpq, qij):
64
64
199
21
42
QuESt-Calculator/pyscf
pyscf/pbc/gw/krgw_ac.py
Python
get_rho_response_wing
get_rho_response_wing
369
384
369
369
c058b4a4af5f1053ada1c0239d5ec50add8be58f
bigcode/the-stack
train