file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
neurosky_ecg.py | # -*- coding: utf-8 -*-
"""
NeuroSky ECG algorithm library
This python module serves as a wrapper around the C library, giving efficent access
to the library methods used to record and analyze ECG data, obtained with the
NeuroSky CardioChip
Created on Wed Jan 14 17:37:11 2015
@author: mpesavento
"""
from ctypes im... | (self):
"""
return the total number of RRIs held in the algorithm buffer
"""
return self.analyze.tg_ecg_get_total_rri_count()
def ecgalgAnalyzeRaw(self, D, nHRV=30): #, dataqueue):
"""
test to see if we have values in the ecg_buffer, and if so, pass
the most... | getTotalNumRRI | identifier_name |
neurosky_ecg.py | # -*- coding: utf-8 -*-
"""
NeuroSky ECG algorithm library
This python module serves as a wrapper around the C library, giving efficent access
to the library methods used to record and analyze ECG data, obtained with the
NeuroSky CardioChip
Created on Wed Jan 14 17:37:11 2015
@author: mpesavento
"""
from ctypes im... |
#if sample_count%256==0:
# time.sleep(0.05)
plt.draw()
#let the queue know we are done processing its
nskECG.ecg_buffer.task_done()
# stop the thread, ctrl-C
pass
| plt.axes(ax2)
ymin = float(min(hrv))-10
ymax = float(max(hrv))+10
ax2.set_ylim((ymin,ymax))
hrvtrace.set_xdata(hrv_t)
hrvtrace.set_ydata(hrv)
ax2.relim()
ax2.autoscale_view() | conditional_block |
cloud4.py | # uzawa, last
import torch, torch.nn as nn, torch.optim as optim, torch.nn.functional as functional, torch.utils.data as torchdata
import pprint, inspect, collections, os, time, sys, argparse, ot, numpy as np, matplotlib.pyplot as plt, scipy.stats as st
from sklearn.datasets import make_circles, make_moons
from sklearn... | g, h = (c - a) / (b - d), (f - e) / (b - d)
if nblocks < 10 : # point cloud
x = np.linspace(- 20, 10, 100)
y = g * x + h
fig, ax = plt.subplots(3, 3, sharex = 'all', sharey = 'all')
fig.set_size_inches(18, 18)
fig.suptitle('Transformed test data after epoch {}. Linear classifier slope {} intercept {}'.forma... |
def plotmetrics(outs_, X_test, Y_test, gouts_, epoch, model, nblocks, folder):
F, C, W = [], [], []
a, b, c, d = model.fcOut.weight[0, 0].item(), model.fcOut.weight[0, 1].item(), model.fcOut.weight[1, 0].item(), model.fcOut.weight[1, 1].item()
e, f = model.fcOut.bias[0].item(), model.fcOut.bias[1].item() | random_line_split |
cloud4.py | # uzawa, last
import torch, torch.nn as nn, torch.optim as optim, torch.nn.functional as functional, torch.utils.data as torchdata
import pprint, inspect, collections, os, time, sys, argparse, ot, numpy as np, matplotlib.pyplot as plt, scipy.stats as st
from sklearn.datasets import make_circles, make_moons
from sklearn... |
def forward(self, x):
z = self.bn(self.fc1(x)) if self.batchnorm else self.fc1(x)
z = functional.relu(z)
z = self.fc2(z)
return z + x, z
class OneRepResNet(nn.Module):
def __init__(self, nblocks, inputdim, hiddendim, batchnorm, nclasses, learnclassifier, yintercept, initialize):
super(OneRepResNet, self).... | super(ResBlock, self).__init__()
self.batchnorm = batchnorm
self.fc1 = nn.Linear(inputdim, hiddendim)
if batchnorm:
self.bn = nn.BatchNorm1d(hiddendim, track_running_stats = True)
self.fc2 = nn.Linear(hiddendim, inputdim) | identifier_body |
cloud4.py | # uzawa, last
import torch, torch.nn as nn, torch.optim as optim, torch.nn.functional as functional, torch.utils.data as torchdata
import pprint, inspect, collections, os, time, sys, argparse, ot, numpy as np, matplotlib.pyplot as plt, scipy.stats as st
from sklearn.datasets import make_circles, make_moons
from sklearn... | (ndata, testsize, data, noise, factor, dataseed, modelseed, nblocks, datadim, hiddendim, batchnorm, nclasses, learnclassifier,
yintercept, biginit, biginitstd, lambdatransport, lambdaloss0, tau, uzawasteps, batchsize, nepochs, learningrate, beta1, beta2):
folder0 = ('circles' if data == 1 else 'moons') + '-dd' ... | makefolder | identifier_name |
cloud4.py | # uzawa, last
import torch, torch.nn as nn, torch.optim as optim, torch.nn.functional as functional, torch.utils.data as torchdata
import pprint, inspect, collections, os, time, sys, argparse, ot, numpy as np, matplotlib.pyplot as plt, scipy.stats as st
from sklearn.datasets import make_circles, make_moons
from sklearn... |
initialize = partial(initialize_, biginit, biginitstd)
model = OneRepResNet(nblocks, inputdim, hiddendim, batchnorm, nclasses, learnclassifier, yintercept, initialize)
print('--- model', model)
global inps, outs, gouts
inps, outs, gouts = collections.defaultdict(list), collections.defaultdict(list), collections.d... | torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.manual_seed(modelseed)
np.random.seed(modelseed) | conditional_block |
BAAFNet.py | from os.path import exists, join
from os import makedirs
from sklearn.metrics import confusion_matrix
from helper_tool import DataProcessing as DP
import tensorflow as tf
import numpy as np
import helper_tf_util
import time
import math
from utils.sampling import tf_sampling
def log_out(out_str, f_out):
f_out.writ... | (feature, interp_idx):
"""
:param feature: [B, N, d] input features matrix
:param interp_idx: [B, up_num_points, 1] nearest neighbour index
:return: [B, up_num_points, d] interpolated features matrix
"""
feature = tf.squeeze(feature, axis=2)
batch_size = tf.shape(... | nearest_interpolation | identifier_name |
BAAFNet.py | from os.path import exists, join
from os import makedirs
from sklearn.metrics import confusion_matrix
from helper_tool import DataProcessing as DP
import tensorflow as tf
import numpy as np
import helper_tf_util
import time
import math
from utils.sampling import tf_sampling
def log_out(out_str, f_out):
f_out.writ... |
@staticmethod
def nearest_interpolation(feature, interp_idx):
"""
:param feature: [B, N, d] input features matrix
:param interp_idx: [B, up_num_points, 1] nearest neighbour index
:return: [B, up_num_points, d] interpolated features matrix
"""
feature = tf.squeez... | """
:param feature: [B, N, d] input features matrix
:param pool_idx: [B, N', max_num] N' < N, N' is the selected position after pooling
:return: pool_features = [B, N', d] pooled features matrix
"""
feature = tf.squeeze(feature, axis=2)
num_neigh = tf.shape(pool_idx)[-1]
... | identifier_body |
BAAFNet.py | from os.path import exists, join
from os import makedirs
from sklearn.metrics import confusion_matrix
from helper_tool import DataProcessing as DP
import tensorflow as tf
import numpy as np
import helper_tf_util
import time
import math
from utils.sampling import tf_sampling
def log_out(out_str, f_out):
f_out.writ... | neigh_feat_offsets = helper_tf_util.conv2d(xyz_info, feature.get_shape()[-1].value, [1, 1], name + 'mlp6', [1, 1], 'VALID', True, is_training) # B, N, k, d_out/2
shifted_neigh_feat = neigh_feat + neigh_feat_offsets # B, N, k, d_out/2
xyz_encoding = helper_tf_util.conv2d(xyz_info, d_out//2, [1, ... | neigh_xyz_offsets = helper_tf_util.conv2d(feat_info, xyz.get_shape()[-1].value, [1, 1], name + 'mlp5', [1, 1], 'VALID', True, is_training) # B, N, k, 3
shifted_neigh_xyz = neigh_xyz + neigh_xyz_offsets # B, N, k, 3
xyz_info = tf.concat([neigh_xyz - tile_xyz, shifted_neigh_xyz, tile_xyz],... | random_line_split |
BAAFNet.py | from os.path import exists, join
from os import makedirs
from sklearn.metrics import confusion_matrix
from helper_tool import DataProcessing as DP
import tensorflow as tf
import numpy as np
import helper_tf_util
import time
import math
from utils.sampling import tf_sampling
def log_out(out_str, f_out):
f_out.writ... |
else:
return tf.gather_nd(pts, idx), tf.gather_nd(feature, idx)
class Network:
def __init__(self, dataset, config):
flat_inputs = dataset.flat_inputs
self.config = config
# Path of the result folder
if self.config.saving:
if self.config.saving_path is None:... | return tf.gather_nd(pts, idx) | conditional_block |
mod.rs | //! [RFC 7230](https://tools.ietf.org/html/rfc723) compliant HTTP 1.1 request parser
mod util;
use std::io::prelude::*;
use std::net::TcpStream;
use std::collections::HashMap;
use std::sync::Arc;
use self::util::*;
pub use self::util::ParseError;
use self::util::TokenType::{TChar, Invalid};
/// A container for the ... | ) -> &HashMap<String, String> {
&self.headers
}
/// Convert this request builder into a full request
pub fn into_request(self) -> Option<Request> {
match self {
RequestBuilder {
version: Some(version),
method: Some(method),
target:... | aders(&self | identifier_name |
mod.rs | //! [RFC 7230](https://tools.ietf.org/html/rfc723) compliant HTTP 1.1 request parser
mod util;
use std::io::prelude::*;
use std::net::TcpStream;
use std::collections::HashMap;
use std::sync::Arc;
use self::util::*;
pub use self::util::ParseError;
use self::util::TokenType::{TChar, Invalid};
/// A container for the ... | match it.get_inner().read_to_end(builder.get_body()) {
Ok(0) => Ok(()),
Ok(_) => {
println!("Body read complete");
Ok(())
},
Err(e) => Err(ParseError::new_server_error(e)),
}*/
}
}
unsafe impl Send for Request {}
// nb... | random_line_split | |
listing.go | package main
// Import the AWS SDK for Go
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/TuneDB/env"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/rcrowley/go-metrics"
"log"
"os"
"strings"
"sync"
"time"
)
/**... |
// TODO Should look at changing this to func definitions that are loaded into a struct and called dynamically
func printObject(object *ListObject) string {
var output string
switch cfg.OutputFormat {
case "csv":
output = printCsv(object)
case "json":
output = printJson(object)
default:
log.Fatal("Unknown ... | {
log.Printf("Retrieving object listing for %v/%v using service: %+v", bucket, prefix, svc.ClientInfo.Endpoint)
params := &s3.ListObjectsInput{
Bucket: aws.String(bucket), // Required
MaxKeys: aws.Int64(int64(cfg.MaxKeys)),
}
if delimiter != "" {
params.Delimiter = aws.String(delimiter)
}
if prefix != "... | identifier_body |
listing.go | package main
// Import the AWS SDK for Go
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/TuneDB/env"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/rcrowley/go-metrics"
"log"
"os"
"strings"
"sync"
"time"
)
/**... | }
if delimiter != "" {
params.Delimiter = aws.String(delimiter)
}
if prefix != "" {
params.Prefix = aws.String(prefix)
}
pageNum := 0
objectNum := 0
err := svc.ListObjectsPages(params, func(page *s3.ListObjectsOutput, lastPage bool) bool {
pageNum++
log.Printf("Processing page %v for %v/%v", pageNum... | params := &s3.ListObjectsInput{
Bucket: aws.String(bucket), // Required
MaxKeys: aws.Int64(int64(cfg.MaxKeys)), | random_line_split |
listing.go | package main
// Import the AWS SDK for Go
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/TuneDB/env"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/rcrowley/go-metrics"
"log"
"os"
"strings"
"sync"
"time"
)
/**... |
go func() {
ListAllObjectsProducer(listAllObjectsQueue)
close(listAllObjectsQueue)
}()
wg.Wait()
}
func ListAllObjectsProducer(listAllObjectsQueue chan ListAllObjectsRequest) {
log.Println("Starting producer")
// Create services we will use, inlining the config instead of using `session`
// V4 signing req... | {
log.Printf("Starting worker%d", i+1)
worker := NewListObjectRequestWorker(i+1, listAllObjectsQueue, doneCallback)
wg.Add(1)
go func() {
// wg.Add(1)
worker.Start()
}()
} | conditional_block |
listing.go | package main
// Import the AWS SDK for Go
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/TuneDB/env"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/rcrowley/go-metrics"
"log"
"os"
"strings"
"sync"
"time"
)
/**... | () {
output = stdoutOutput
listAllObjectsQueue := make(chan ListAllObjectsRequest, 5)
var wg sync.WaitGroup
doneCallback := func() {
defer wg.Done()
log.Printf("worker done")
}
for i := 0; i < cfg.ListAllWorkersCount; i++ {
log.Printf("Starting worker%d", i+1)
worker := NewListObjectRequestWorker(i+1, ... | run | identifier_name |
spacing.rs | extern crate std as ruststd ;
use core :: hash :: { self , Hash } ;
use core ::intrinsics:: {arith_offset ,assume} ;
use core::iter::FromIterator;
use core :: mem;
use core::ops::{ Index ,IndexMut };
const CAPACITY :usize = 2*B-1;
fn foo ( a ... |
pub fn capacity( & self ) -> usize {
self . buf . cap ( )
}
pub fn reserve(& mut self, additional: usize) {
self. buf .reserve(self. len ,additional) ;
}
pub fn into_boxed_slice( mut self ) -> Box < [ T ] > {
unsafe{
self . shrink_to_fit ( ... | {
Vec{
buf :RawVec::from_raw_parts(ptr, capacity) ,
len :length ,
}
} | identifier_body |
spacing.rs | extern crate std as ruststd ;
use core :: hash :: { self , Hash } ;
use core ::intrinsics:: {arith_offset ,assume} ;
use core::iter::FromIterator;
use core :: mem;
use core::ops::{ Index ,IndexMut };
const CAPACITY :usize = 2*B-1;
fn foo ( a ... | <R>(&mut self,range:R)->Drain<T>where R:RangeArgument <usize>{
let len = self.len();
let start = * range.start() .unwrap_or( & 0 ) ;
let end = * range. end().unwrap_or( & len ) ;
assert!(start <= end);
assert!(end <= len);
}
}
impl<T:Clone>Vec<T>{
pub ... | drain | identifier_name |
spacing.rs | extern crate std as ruststd ;
use core :: hash :: { self , Hash } ;
use core ::intrinsics:: {arith_offset ,assume} ;
use core::iter::FromIterator;
use core :: mem;
use core::ops::{ Index ,IndexMut };
const CAPACITY :usize = 2*B-1;
fn foo ( a ... | }
}
pub fn capacity( & self ) -> usize {
self . buf . cap ( )
}
pub fn reserve(& mut self, additional: usize) {
self. buf .reserve(self. len ,additional) ;
}
pub fn into_boxed_slice( mut self ) -> Box < [ T ] > {
unsafe{
self . s... | random_line_split | |
spacing.rs | extern crate std as ruststd ;
use core :: hash :: { self , Hash } ;
use core ::intrinsics:: {arith_offset ,assume} ;
use core::iter::FromIterator;
use core :: mem;
use core::ops::{ Index ,IndexMut };
const CAPACITY :usize = 2*B-1;
fn foo ( a ... |
r+=1 ;
}
self.truncate(w);
}
}
}
pub fn from_elem < T : Clone > ( elem :T ,n:usize) -> Vec <T>{
}
impl < T :Clone >Clone for Vec <T>{
fn clone(&self) -> Vec<T> {
< [ T ] > :: to_vec ( & * * self )
}
... | {
if r!=w{
let p_w = p_wm1.offset(1);
mem::swap( & mut * p_r , & mut * p_w );
}
w += 1;
} | conditional_block |
SFRF_backend.py | from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfile, asksaveasfilename
import datetime
from datetime import datetime, timedelta
import SFRF_interface as inter
import sqlite3
import tkinter.font as tkFont
import tkinter.ttk as ttk
from openpyxl import Workbook
from... | cell_ano.alignment = alignment_left
current_sheet.merge_cells('A12:B12')
current_sheet['A12'] = "MÊS: "+mes
current_sheet['H12'] = "ANO:"
current_sheet['I12'] = ano
cell_day = current_sheet['A14']
cell_day.font, cell_day.alignment = font_bold, alignment_center
current_sheet['A14'] = "DIA"
current_... |
cell_mes_str.font, cell_ano_str.font, cell_ano.font = font_normal, font_normal, font_normal
cell_mes_str.alignment, cell_ano_str.alignment = alignment_left, alignment_right | random_line_split |
SFRF_backend.py | from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfile, asksaveasfilename
import datetime
from datetime import datetime, timedelta
import SFRF_interface as inter
import sqlite3
import tkinter.font as tkFont
import tkinter.ttk as ttk
from openpyxl import Workbook
from... | ipo=='d':
dias = ["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"
,"21","22","23","24","25","26","27","28","29","30","31"]
for dia in dias:
data_com_dia = date+"/"+ dia
linha = dia+" de "+mes+" de "+ano
if setor != "Não Ativos":
c... | unter = timedelta()
cursor.execute("SELECT entrada, saida FROM Frequencia WHERE entrada LIKE ? and cpf = ? and saida IS NOT NULL",((date+'%', colab[0])))
for frequencia in cursor.fetchall():
entrada = retorna_objeto_date(frequencia[0])
saida = retorna_objeto_date(frequencia[1])
counter += (s... | conditional_block |
SFRF_backend.py | from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfile, asksaveasfilename
import datetime
from datetime import datetime, timedelta
import SFRF_interface as inter
import sqlite3
import tkinter.font as tkFont
import tkinter.ttk as ttk
from openpyxl import Workbook
from... | (" ")
return split1[0]
def retorna_dia(data_str):
split1 = data_str.split(" ")
split2 = split1[0]
data = split2.split("/")
return data[2]
def retorna_hora(data_str):
split1 = data_str.split(" ")
return split1[1]
class McListBox(object):
def __init__(self, container_o, header, lista):
self.tree = None
sel... | except:
inter.pop_up("ERROR", "Consulta Inválida")
return False
def retorna_data_sem_hora(data_str):
split1 = data_str.split | identifier_body |
SFRF_backend.py | from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfile, asksaveasfilename
import datetime
from datetime import datetime, timedelta
import SFRF_interface as inter
import sqlite3
import tkinter.font as tkFont
import tkinter.ttk as ttk
from openpyxl import Workbook
from... | ogo):
cursor = con.cursor
conexao = con.conexao
if nome.get() != "" and sigla.get()!="":
try:
if logo.get() != "":
file_type = ImageMethods.get_file_type(logo.get())
file_binary = ImageMethods.get_binary(logo.get())
cursor.execute("INSERT INTO Setor VALUES (?, ?, ?, ?)", (nome.get(), sigla.get(), fi... | (nome, sigla, l | identifier_name |
xcode.rs | use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::hash::BuildHasher;
use std::io::{BufRead, BufReader, Cursor};
use std::path::{Path, PathBuf};
use std::process;
use anyhow::{format_err, Context, Result};
use if_chain::if_chain;
use lazy_static::lazy_static;
use log::warn;
use regex::Reg... |
Ok(())
}
}
/// Returns true if we were invoked from xcode
#[cfg(target_os = "macos")]
pub fn launched_from_xcode() -> bool {
if env::var("XCODE_VERSION_ACTUAL").is_err() {
return false;
}
let mut pid = unsafe { getpid() as u32 };
while let Some(parent) = mac_process_info::get_pare... | {
show_notification("Sentry", &format!("{} finished", self.task_name))?;
} | conditional_block |
xcode.rs | use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::hash::BuildHasher;
use std::io::{BufRead, BufReader, Cursor};
use std::path::{Path, PathBuf};
use std::process;
use anyhow::{format_err, Context, Result};
use if_chain::if_chain;
use lazy_static::lazy_static;
use log::warn;
use regex::Reg... | {
let mut vars = HashMap::new();
vars.insert("FOO_BAR".to_string(), "foo bar baz / blah".to_string());
assert_eq!(
expand_xcodevars("A$(FOO_BAR:rfc1034identifier)B", &vars),
"Afoo-bar-baz-blahB"
);
assert_eq!(
expand_xcodevars("A$(FOO_BAR:identifier)B", &vars),
"Afoo... | identifier_body | |
xcode.rs | use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::hash::BuildHasher;
use std::io::{BufRead, BufReader, Cursor};
use std::path::{Path, PathBuf};
use std::process;
use anyhow::{format_err, Context, Result};
use if_chain::if_chain;
use lazy_static::lazy_static;
use log::warn;
use regex::Reg... | <'a> {
output_file: Option<TempFile>,
#[allow(dead_code)]
task_name: &'a str,
}
impl<'a> MayDetach<'a> {
fn new(task_name: &'a str) -> MayDetach<'a> {
MayDetach {
output_file: None,
task_name,
}
}
/// Returns true if we are deteached from xcode
pub f... | MayDetach | identifier_name |
xcode.rs | use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::hash::BuildHasher;
use std::io::{BufRead, BufReader, Cursor};
use std::path::{Path, PathBuf};
use std::process;
use anyhow::{format_err, Context, Result};
use if_chain::if_chain;
use lazy_static::lazy_static;
use log::warn;
use regex::Reg... |
/// Shows a dialog in xcode and blocks. The dialog will have a title and a
/// message as well as the buttons "Show details" and "Ignore". Returns
/// `true` if the `show details` button has been pressed.
#[cfg(target_os = "macos")]
pub fn show_critical_info(title: &str, message: &str) -> Result<bool> {
use serd... | random_line_split | |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... |
fn init_maps(&self, buf: &[u8], idx: usize, sec: &SectionHeader) -> Result<Vec<Map>, Error> {
let mut maps = Vec::new();
let data = buf.get(sec.file_range()).ok_or_else(|| {
format_err!("`maps` section data {:?} out of bound", sec.file_range())
})?;
let nr_maps = self... | {
if self.obj.header.e_type != ET_REL || self.obj.header.e_machine != EM_BPF {
bail!("not an eBPF object file");
}
if self.obj.header.endianness()? != scroll::NATIVE {
bail!("endianness mismatch.")
}
let mut license = None;
let mut version = None... | identifier_body |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... | (
&self,
programs: &mut [Program],
maps: &[Map],
maps_idx: Option<usize>,
text_idx: Option<usize>,
) -> Result<(), Error> {
for (idx, sec) in &self.obj.shdr_relocs {
if let Some(prog) = programs.iter_mut().find(|prog| prog.idx == *idx) {
tr... | relocate_programs | identifier_name |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... | debug!(
"{:?} kernel program #{} @ section `{}` with {} insns",
ty,
idx,
name,
insns.len()
);
programs.push((name, ty, attach, idx, insns.t... | random_line_split | |
elf.rs | use std::convert::TryInto;
use std::ffi::CStr;
use std::mem;
use std::ptr;
use std::slice;
use failure::{bail, format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog... |
BPF_VERSION_SEC if sec.sh_type == SHT_PROGBITS => {
version = Some(u32::from_ne_bytes(section_data()?.try_into()?));
debug!("kernel version: {:x}", version.as_ref().unwrap());
}
BPF_MAPS_SEC => {
debug!("`{}` s... | {
license = Some(
CStr::from_bytes_with_nul(section_data()?)?
.to_str()?
.to_owned(),
);
debug!("kernel license: {}", license.as_ref().unwrap());
} | conditional_block |
disk.go | package main
import (
"errors"
"time"
"code.google.com/p/go.crypto/curve25519"
"code.google.com/p/goprotobuf/proto"
"github.com/agl/pond/bbssig"
"github.com/agl/pond/client/disk"
pond "github.com/agl/pond/protos"
)
// erasureRotationTime is the amount of time that we'll use a single erasure
// storage value b... | m := &disk.Draft{
Id: proto.Uint64(draft.id),
Body: proto.String(draft.body),
Attachments: draft.attachments,
Detachments: draft.detachments,
Created: proto.Int64(draft.created.Unix()),
}
if draft.to != 0 {
m.To = proto.Uint64(draft.to)
}
if draft.inReplyTo != 0 {
m.In... | var drafts []*disk.Draft
for _, draft := range c.drafts { | random_line_split |
disk.go | package main
import (
"errors"
"time"
"code.google.com/p/go.crypto/curve25519"
"code.google.com/p/goprotobuf/proto"
"github.com/agl/pond/bbssig"
"github.com/agl/pond/client/disk"
pond "github.com/agl/pond/protos"
)
// erasureRotationTime is the amount of time that we'll use a single erasure
// storage value b... | () []byte {
var err error
var contacts []*disk.Contact
for _, contact := range c.contacts {
cont := &disk.Contact{
Id: proto.Uint64(contact.id),
Name: proto.String(contact.name),
GroupKey: contact.groupKey.Marshal(),
IsPending: proto.Bool(contact.isPending),
... | marshal | identifier_name |
disk.go | package main
import (
"errors"
"time"
"code.google.com/p/go.crypto/curve25519"
"code.google.com/p/goprotobuf/proto"
"github.com/agl/pond/bbssig"
"github.com/agl/pond/client/disk"
pond "github.com/agl/pond/protos"
)
// erasureRotationTime is the amount of time that we'll use a single erasure
// storage value b... |
func (c *client) marshal() []byte {
var err error
var contacts []*disk.Contact
for _, contact := range c.contacts {
cont := &disk.Contact{
Id: proto.Uint64(contact.id),
Name: proto.String(contact.name),
GroupKey: contact.groupKey.Marshal(),
IsPending: proto.B... | {
c.server = *state.Server
if len(state.Identity) != len(c.identity) {
return errors.New("client: identity is wrong length in State")
}
copy(c.identity[:], state.Identity)
curve25519.ScalarBaseMult(&c.identityPublic, &c.identity)
group, ok := new(bbssig.Group).Unmarshal(state.Group)
if !ok {
return errors.... | identifier_body |
disk.go | package main
import (
"errors"
"time"
"code.google.com/p/go.crypto/curve25519"
"code.google.com/p/goprotobuf/proto"
"github.com/agl/pond/bbssig"
"github.com/agl/pond/client/disk"
pond "github.com/agl/pond/protos"
)
// erasureRotationTime is the amount of time that we'll use a single erasure
// storage value b... |
inbox = append(inbox, m)
}
var outbox []*disk.Outbox
for _, msg := range c.outbox {
if time.Since(msg.created) > messageLifetime {
continue
}
m := &disk.Outbox{
Id: proto.Uint64(msg.id),
To: proto.Uint64(msg.to),
Server: proto.String(msg.server),
Created: proto.Int64(m... | {
if m.Message, err = proto.Marshal(msg.message); err != nil {
panic(err)
}
} | conditional_block |
appstate.go | package conchapp
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/blockchainworkers/conch/crypto"
"github.com/blockchainworkers/conch/libs/log"
"github.com/jmoiron/sqlx"
"math/big"
"sync"
)
// AccountState means current account's info
type AccountState struct {
syn... | () error {
sqlStr := "select content from state where id=1"
var text string
err := hdSt.db.QueryRowx(sqlStr).Scan(&text)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
return json.Unmarshal([]byte(text), hdSt)
}
// SyncToDisk to db
func (hdSt *HeaderState) SyncToDisk() error {
dat, er... | LoadHeaderState | identifier_name |
appstate.go | package conchapp
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/blockchainworkers/conch/crypto"
"github.com/blockchainworkers/conch/libs/log"
"github.com/jmoiron/sqlx"
"math/big"
"sync"
)
// AccountState means current account's info
type AccountState struct {
syn... |
sqlStr := "replace into funds(address, amount) values "
for _, val := range as.accounts {
sqlStr = sqlStr + fmt.Sprintf(" ('%s', '%s'),", val.Address, val.Amount.String())
}
sqlStr = sqlStr[0 : len(sqlStr)-1]
_, err := as.db.Exec(sqlStr)
as.accounts = make(map[string]*Account)
return err
}
//Account ...
typ... | {
return nil
} | conditional_block |
appstate.go | package conchapp
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/blockchainworkers/conch/crypto"
"github.com/blockchainworkers/conch/libs/log"
"github.com/jmoiron/sqlx"
"math/big"
"sync"
)
// AccountState means current account's info
type AccountState struct {
syn... |
// UpdateTx append tx
func (txState *TxState) UpdateTx(tx *Transaction) {
txState.Lock()
defer txState.Unlock()
txState.log.Error("one tx has been executed.......")
txState.Txs = txState.Txs.AppendTx(tx)
}
// SyncToDisk write tx to db
func (txState *TxState) SyncToDisk(height int64) (hashRoot string, err error) ... | {
return &TxState{
Txs: Transactions{},
log: log,
db: db,
}
} | identifier_body |
appstate.go | package conchapp
import (
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/blockchainworkers/conch/crypto"
"github.com/blockchainworkers/conch/libs/log"
"github.com/jmoiron/sqlx"
"math/big"
"sync"
) | // AccountState means current account's info
type AccountState struct {
sync.RWMutex
accounts map[string]*Account
log log.Logger
db *sqlx.DB
isDirty bool
}
// NewAccountState return AccountState inst
func NewAccountState(db *sqlx.DB, log log.Logger) *AccountState {
return &AccountState{
accounts: m... | random_line_split | |
list.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... |
Some(self.id())
}
fn draw(&self, draw_handle: &mut dyn DrawHandle, mgr: &event::ManagerState, disabled: bool) {
let disabled = disabled || self.is_disabled();
let solver = layout::RowPositionSolver::new(self.direction);
solver.for_children(&self.widgets, draw_handle.get_clip_r... | {
return child.find_id(coord);
} | conditional_block |
list.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... | (&mut self, index: usize) -> Option<&mut dyn WidgetConfig> {
self.widgets.get_mut(index).map(|w| w.as_widget_mut())
}
}
impl<D: Directional, W: Widget> Layout for List<D, W> {
fn size_rules(&mut self, size_handle: &mut dyn SizeHandle, axis: AxisInfo) -> SizeRules {
let dim = (self.direction, se... | get_child_mut | identifier_name |
list.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... | self.list = &self.list[1..];
Some(item)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl<'a, W: Widget> ExactSizeIterator for ListIter<'a, W> {
fn len(&self) -> usize {
... | impl<'a, W: Widget> Iterator for ListIter<'a, W> {
type Item = &'a W;
fn next(&mut self) -> Option<Self::Item> {
if !self.list.is_empty() {
let item = &self.list[0]; | random_line_split |
list.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! A row or column with run-time adjustable contents
use ... |
/// Reserves capacity for at least `additional` more elements to be inserted
/// into the list. See documentation of [`Vec::reserve`].
pub fn reserve(&mut self, additional: usize) {
self.widgets.reserve(additional);
}
/// Remove all child widgets
///
/// Triggers a [reconfigure ac... | {
self.widgets.capacity()
} | identifier_body |
config_global.go | package config
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"golang.org/x/crypto/ed25519"
)
type Global struct {
// Signing identity contains the server name, ... | (configErrs *ConfigErrors) {
}
// ServerNotices defines the configuration used for sending server notices
type ServerNotices struct {
Enabled bool `yaml:"enabled"`
// The localpart to be used when sending notices
LocalPart string `yaml:"local_part"`
// The displayname to be used when sending notices
DisplayName s... | Verify | identifier_name |
config_global.go | package config
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"golang.org/x/crypto/ed25519"
)
type Global struct {
// Signing identity contains the server name, ... | // MaxIdleConns returns maximum idle connections to the DB
func (c DatabaseOptions) MaxIdleConns() int {
return c.MaxIdleConnections
}
// MaxOpenConns returns maximum open connections to the DB
func (c DatabaseOptions) MaxOpenConns() int {
return c.MaxOpenConnections
}
// ConnMaxLifetime returns maximum amount of t... | func (c *DatabaseOptions) Verify(configErrs *ConfigErrors) {}
| random_line_split |
config_global.go | package config
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"golang.org/x/crypto/ed25519"
)
type Global struct {
// Signing identity contains the server name, ... |
if c.Enabled {
checkNotEmpty(configErrs, "global.report_stats.endpoint", c.Endpoint)
}
}
// The configuration to use for Sentry error reporting
type Sentry struct {
Enabled bool `yaml:"enabled"`
// The DSN to connect to e.g "https://examplePublicKey@o0.ingest.sentry.io/0"
// See https://docs.sentry.io/platform... | {
c.Endpoint = "https://panopticon.matrix.org/push"
} | conditional_block |
config_global.go | package config
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"golang.org/x/crypto/ed25519"
)
type Global struct {
// Signing identity contains the server name, ... |
func (c *Global) SplitLocalID(sigil byte, id string) (string, spec.ServerName, error) {
u, s, err := gomatrixserverlib.SplitID(sigil, id)
if err != nil {
return u, s, err
}
if !c.IsLocalServerName(s) {
return u, s, fmt.Errorf("server name %q not known", s)
}
return u, s, nil
}
func (c *Global) VirtualHost(... | {
if c.ServerName == serverName {
return true
}
for _, v := range c.VirtualHosts {
if v.ServerName == serverName {
return true
}
}
return false
} | identifier_body |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... |
}
/// Waste at most the remaining ref time weight of `meter`.
///
/// Tries to come as close to the limit as possible.
pub(crate) fn waste_at_most_ref_time(meter: &mut WeightMeter) {
let Ok(n) = Self::calculate_ref_time_iters(&meter) else { return };
meter.consume(T::WeightInfo::waste_ref_time_iter(n)... | {
Err(())
} | conditional_block |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... |
/// Set how much of the remaining `proof_size` weight should be consumed by `on_idle`.
///
/// `1.0` means that all remaining `proof_size` will be consumed. The PoV benchmarking
/// results that are used here are likely an over-estimation. 100% intended consumption will
/// therefore translate to less than ... | {
T::AdminOrigin::ensure_origin_or_root(origin)?;
ensure!(compute <= RESOURCE_HARD_LIMIT, Error::<T>::InsaneLimit);
Compute::<T>::set(compute);
Self::deposit_event(Event::ComputationLimitSet { compute });
Ok(())
} | identifier_body |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... | }
Self::deposit_event(Event::PalletInitialized { reinit: witness_count.is_some() });
TrashDataCount::<T>::set(new_count);
Ok(())
}
/// Set how much of the remaining `ref_time` weight should be consumed by `on_idle`.
///
/// Only callable by Root or `AdminOrigin`.
#[pallet::call_index(1)]
pub f... | (new_count..current_count).for_each(TrashData::<T>::remove); | random_line_split |
lib.rs | // This file is part of Substrate.
// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://... | (origin: OriginFor<T>, storage: FixedU64) -> DispatchResult {
T::AdminOrigin::ensure_origin_or_root(origin)?;
ensure!(storage <= RESOURCE_HARD_LIMIT, Error::<T>::InsaneLimit);
Storage::<T>::set(storage);
Self::deposit_event(Event::StorageLimitSet { storage });
Ok(())
}
}
impl<T: Config> Pallet<T> ... | set_storage | identifier_name |
house.go | package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"loveHome/models"
"encoding/json"
"strconv"
"fmt"
"github.com/astaxie/beego/cache"
"loveHome/utils"
"time"
"path"
)
type HouseInfo struct {
Area_id string `json:"area_id"` //归属地的区域编号
Title string `json:"ti... | //从redis中拿到数据
house_search_info:=cache_conn.Get(house_search_key)
if house_search_info!=nil{
beego.Debug("======= get house_search_info from CACHE!!! ========")
//存解码后的数据
house_info:=[]map[string]interface{}{}
//解码json数据
json.Unmarshal(house_search_info.([]byte),&house_info)
//把解码后的数据打包成json传给前端
resp... | resp["errno"]=models.RECODE_REQERR
resp["errmsg"]=models.RecodeText(models.RECODE_REQERR)
return
} | random_line_split |
house.go | package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"loveHome/models"
"encoding/json"
"strconv"
"fmt"
"github.com/astaxie/beego/cache"
"loveHome/utils"
"time"
"path"
)
type HouseInfo struct {
Area_id string `json:"area_id"` //归属地的区域编号
Title string `json:"ti... | le=reqData.Title
house.Price,_=strconv.Atoi(reqData.Price)
house.Price=house.Price*100
house.Address=reqData.Address
house.Room_count,_=strconv.Atoi(reqData.Room_count)
house.Acreage,_=strconv.Atoi(reqData.Acreage)
house.Unit=reqData.Unit
house.Beds=reqData.Beds
house.Capacity,_=strconv.Atoi(reqData.Capacity)
... | {}
house.Tit | identifier_name |
house.go | package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"loveHome/models"
"encoding/json"
"strconv"
"fmt"
"github.com/astaxie/beego/cache"
"loveHome/utils"
"time"
"path"
)
type HouseInfo struct {
Area_id string `json:"area_id"` //归属地的区域编号
Title string `json:"ti... | ecodeText(models.RECODE_OK)
defer this.RetData(resp)
//1.从session获取用户的user_id
user_id:=this.GetSession("user_id")
if user_id==nil{
resp["errno"]=models.RECODE_SESSIONERR
resp["errmsg"]=models.RecodeText(models.RECODE_SESSIONERR)
return
}
//2.从数据库中拿到user_id对应的house数据
//这里先拿到house结构体对象
/*
这里需要注意,因为我们需要查询的... | rno"]=models.RECODE_OK
resp["errmsg"]=models.R | identifier_body |
house.go | package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"loveHome/models"
"encoding/json"
"strconv"
"fmt"
"github.com/astaxie/beego/cache"
"loveHome/utils"
"time"
"path"
)
type HouseInfo struct {
Area_id string `json:"area_id"` //归属地的区域编号
Title string `json:"ti... | spData["url"]=utils.AddDomain2Url(uploadResponse.RemoteFileId)
//7.返回给前端json
resp["data"]=respData
}
//请求首页房源
func (this *HouseController) GetHouseIndex() {
resp:=make(map[string]interface{})
resp["errno"]=models.RECODE_OK
resp["errmsg"]=models.RecodeText(models.RECODE_OK)
defer this.RetData(resp)
var respData ... | ls.RecodeText(models.RECODE_DBERR)
return
}
//6.拼接完整域名url_fileid
respData:=make(map[string]string)
re | conditional_block |
SearchEngine.py | import json
import re
import os
import numpy as np
from bs4 import BeautifulSoup as bs
from nltk.stem import PorterStemmer
from collections import defaultdict
from nltk.tokenize import RegexpTokenizer
from collections import Counter
from nltk.corpus import stopwords
import pickle
import time
import sys
hashseed = os.ge... |
elif i%2 == 0:
if i > 2:
os.remove("temp2.json")
f = open("temp2.json", 'w')
f1 = open(files[i])
f2 = open(files[i+1])
line1 = f1.readline()
line2 = f2.readline()
while(line1 != "" or line2 != ""):
jsonObj1 = {"~~~": ""... | if i > 2:
os.remove("temp1.json")
f = open("temp1.json", 'w') | conditional_block |
SearchEngine.py | import json
import re
import os
import numpy as np
from bs4 import BeautifulSoup as bs
from nltk.stem import PorterStemmer
from collections import defaultdict
from nltk.tokenize import RegexpTokenizer
from collections import Counter
from nltk.corpus import stopwords
import pickle
import time
import sys
hashseed = os.ge... |
def main():
#makeIndex()
#merge_partitions()
#delete_partitions()
#calculate_helpers()
query_prompt()
return 0
if __name__=='__main__':
main() | ps = PorterStemmer()
tokenizer = RegexpTokenizer(r"[a-zA-Z0-9']+")
# start prompt
start = input("Enter 'start'(s) to get started or 'quit'(q) to quit: \n")
start = start.lower()
while(start != "start" and start != "s"):
if start == 'q' or start == 'quit':
exit()
start = ... | identifier_body |
SearchEngine.py | import json
import re
import os
import numpy as np
from bs4 import BeautifulSoup as bs
from nltk.stem import PorterStemmer
from collections import defaultdict
from nltk.tokenize import RegexpTokenizer
from collections import Counter
from nltk.corpus import stopwords
import pickle
import time
import sys
hashseed = os.ge... | ():
for file in os.listdir(os.getcwd()):
if re.match(r'^P\d\.json$', file):
os.remove(file)
try:
os.remove("temp1.json")
except:
pass
try:
os.remove("temp2.json")
except:
pass
def merge_partitions():
files = []
for file in os.listdir(os.ge... | delete_partitions | identifier_name |
SearchEngine.py | import json
import re
import os
import numpy as np
from bs4 import BeautifulSoup as bs
from nltk.stem import PorterStemmer
from collections import defaultdict
from nltk.tokenize import RegexpTokenizer
from collections import Counter
from nltk.corpus import stopwords
import pickle
import time
import sys
hashseed = os.ge... | json.dump({word:f2.tell()}, f3)
f3.write('\n')
json.dump(tf_idf, f2)
f2.write('\n')
f1.close()
f2.close()
f3.close()
# calculate simhash
f = open("simhash_scores.json", 'w')
for ID, hashed_words in simhash_dict.items():
simhash_score = ''
... | except KeyError:
simhash_dict[docID] = {sim_hashfn(word): score}
| random_line_split |
kelliptic.go | // Copyright 2010 The Go Authors. All rights reserved.
// Copyright 2011 ThePiachu. All rights reserved.
// Use of this source code is governed by a BSD-style | // fields.
//
// This package operates, internally, on Jacobian coordinates. For a given
// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1)
// where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole
// calculation can be performed within the transform (as in ScalarMult and
// ... | // license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime | random_line_split |
kelliptic.go | // Copyright 2010 The Go Authors. All rights reserved.
// Copyright 2011 ThePiachu. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime
// fields.
//
// This package ope... | nce.Do(initAll)
return secp256k1
}
func CompressPoint(curve *Curve, X, Y *big.Int) (cp []byte) {
return curve.CompressPoint(X, Y)
}
// Point Compression Routines. These could use a lot of testing.
func (curve *Curve) CompressPoint(X, Y *big.Int) (cp []byte) {
by := new(big.Int).And(Y, big.NewInt(1)).Int64()
bx :=... | nito | identifier_name |
kelliptic.go | // Copyright 2010 The Go Authors. All rights reserved.
// Copyright 2011 ThePiachu. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime
// fields.
//
// This package ope... | cobian takes two points in Jacobian coordinates, (x1, y1, z1) and
// (x2, y2, z2) and returns their sum, also in Jacobian form.
func (curve *Curve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperellipticurve.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
... | w(big.Int).SetInt64(1)
return curve.affineFromJacobian(curve.addJacobian(x1, y1, z, x2, y2, z))
}
// addJa | identifier_body |
kelliptic.go | // Copyright 2010 The Go Authors. All rights reserved.
// Copyright 2011 ThePiachu. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime
// fields.
//
// This package ope... | to s * 2^e for an odd s (i.e.
// reduce all the powers of 2 from p-1)
//
s := new(big.Int)
s.Sub(p, ONE)
e := new(big.Int)
e.Set(ZERO)
for c.Mod(s, TWO).Cmp(ZERO) == 0 {
s.Div(s, TWO)
e.Add(e, ONE)
}
// Find some 'n' with a legendre symbol n|p = -1.
// Shouldn't take long.
//
n := new(big.Int)
n.Set(... | c.Div(c, FOUR)
c.Exp(a, c, p)
return c
}
// Partition p-1 | conditional_block |
xmlpipe2.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, chardet, codecs, math, pymongo, Queue, os, re
from foofind.utils import u, logging
from threading import Thread
from multiprocessing import Pool
class EntitiesFetcher(Thread):
def __init__(self, server, results):
super(EntitiesFetcher, self).__init... | count = error_count = 0
logging.warn("Comienza indexado en servidor %s."%server)
if self.pool:
for doc, extra in self.pool.imap(generate_file, (generate_id(afile, part) for afile in ff)):
count+=1
if doc:
outwrite(doc)
... | if headers: self.generate_header() | random_line_split |
xmlpipe2.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, chardet, codecs, math, pymongo, Queue, os, re
from foofind.utils import u, logging
from threading import Thread
from multiprocessing import Pool
class EntitiesFetcher(Thread):
def __init__(self, server, results):
super(EntitiesFetcher, self).__init... | FilesFetcher(server, entities_server, afilter, batch_size, stop_set, stop_set_len, last_count, self.processes)
ff.start()
if headers: self.generate_header()
count = error_count = 0
logging.warn("Comienza indexado en servidor %s."%server)
if self.pool:
for doc, extra ... | identifier_body | |
xmlpipe2.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, chardet, codecs, math, pymongo, Queue, os, re
from foofind.utils import u, logging
from threading import Thread
from multiprocessing import Pool
class EntitiesFetcher(Thread):
def __init__(self, server, results):
super(EntitiesFetcher, self).__init... | (self):
gconn = None
not_found_count = 0
with open("nf_ntts.csv", "w") as not_found_ntts:
while True:
# obtiene peticiones de buscar entidades
afile = self.requests.get(True)
if afile is None:
self.requests.task_done... | run | identifier_name |
xmlpipe2.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, chardet, codecs, math, pymongo, Queue, os, re
from foofind.utils import u, logging
from threading import Thread
from multiprocessing import Pool
class EntitiesFetcher(Thread):
def __init__(self, server, results):
super(EntitiesFetcher, self).__init... | if "se" in f and f["se"]:
self.entities.requests.put(f)
else:
self.results.put(f)
self.entities.requests.put(None)
self.entities.requests.join()
# actualiza el nuevo stop set
if self.stop_set_len:
self.stop_set = new_sto... | dd_to_stop_set and self.stop_set:
new_stop_set.update(self.stop_set)
break
| conditional_block |
script.js | 'use strict';
/*
* COPYRIGHT Joe Iddon
*
* https://joeiddon.github.io/projects/javascript/balls
* https://github.com/joeiddon/balls
*
* TODO:
* - coefficient of restitution (not in right places and not at all in bollards)
* - floor behaviour - balls phase through after a while...
* - bollard behavi... | (points, color){
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++){
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
ctx.fillStyle = color;
ctx.fill();
}
| fill_polygon | identifier_name |
script.js | 'use strict';
/*
* COPYRIGHT Joe Iddon
*
* https://joeiddon.github.io/projects/javascript/balls
* https://github.com/joeiddon/balls
*
* TODO:
* - coefficient of restitution (not in right places and not at all in bollards)
* - floor behaviour - balls phase through after a while...
* - bollard behavi... | balls[b].vy += gravity * time_delta_s;
}
}
function wall_collisions(){
for (let i = 0; i < balls.length; i++){
let ball = balls[i];
let nx = ball.x + ball.vx * time_delta_s;
let ny = ball.y + ball.vy * time_delta_s;
//set ball's position to over the wall so come... | function apply_gravity(){
for (let b = 0; b < balls.length; b++){
| random_line_split |
script.js | 'use strict';
/*
* COPYRIGHT Joe Iddon
*
* https://joeiddon.github.io/projects/javascript/balls
* https://github.com/joeiddon/balls
*
* TODO:
* - coefficient of restitution (not in right places and not at all in bollards)
* - floor behaviour - balls phase through after a while...
* - bollard behavi... | {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++){
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
ctx.fillStyle = color;
ctx.fill();
} | identifier_body | |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | else {
let pgid_ptr = &p.ptr as *const usize as *const pgid_t;
self.ids.reserve(count - idx);
let mut pgids_slice = unsafe {
slice::from_raw_parts(pgid_ptr.offset(idx as isize), count)
};
self.ids.append(&mut pgids_slice.to_vec());
... | {
self.ids.clear();
} | conditional_block |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... |
// reload reads the freelist from a page and filters out pending items.
pub fn reload(&mut self, p: &Page) {
self.read(p);
// Build a cache of only pending pages.
let mut pcache: HashSet<pgid_t> = HashSet::new();
for pending_ids in self.pending.values() {
for pend... | {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update the header flag.
p.flags |= FREELIST_PAGE_FLAG;
// The page.count can only hold up to 64k elementes so if we overflow that
// number then we handle it by putting the size in the first element.
... | identifier_body |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | () {
// Create a page.
let mut buf: [u8; 4096] = [0; 4096];
let page: *mut Page = buf.as_mut_ptr() as *mut Page;
unsafe {
(*page).flags = FREELIST_PAGE_FLAG;
(*page).count = 2;
}
// Insert 2 page ids
let ids_ptr: *mut pgid_t = unsafe {
... | freelist_read | identifier_name |
freelist.rs | use types::{txid_t, pgid_t};
use page::{Page, get_page_header_size, merge_pgids, merge_pgids_raw, FREELIST_PAGE_FLAG};
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::mem;
use std::slice;
// FreeList represents a list of all pages that are available for allocation.
// It als... | // writes the page ids onto a freelist page. All free and pending ids are
// saved to disk since in the event of a program crash, all pending ids will
// become free.
pub fn write(&self, p: &mut Page) {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update th... | }
| random_line_split |
basic_agent.py | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoidi... |
def set_destination(self, location):
"""
This method creates a list of waypoints from agent's position to destination location
based on the route returned by the global router
"""
start_waypoint = self._map.get_waypoint(self._vehicle.get_location())
end_waypoint = ... | """
:param vehicle: actor to apply to local planner logic onto
"""
super(BasicAgent, self).__init__(vehicle)
self.stopping_for_traffic_light = False
self._proximity_threshold = 10.0 # meters
self._state = AgentState.NAVIGATING
args_lateral_dict = {
... | identifier_body |
basic_agent.py | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoidi... |
self._state = AgentState.NAVIGATING
self.braking_intial_speed = None
# standard local planner behavior
control = self._local_planner.run_step(debug=debug)
if self.stopping_for_traffic_light:
control.steer = 0.0
# Prevent from steering randomly when stopped
... | random_line_split | |
basic_agent.py | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoidi... |
self._set_target_speed(max(0, new_target_speed))
return new_target_speed
def _set_target_speed(self, target_speed: int):
"""
This function updates all the needed values required to actually set a new target speed
"""
self._target_speed = target_speed
self._... | TRAFFIC_LIGHT_SECONDS_AWAY = 3
METERS_TO_STOP_BEFORE_TRAFFIC_LIGHT = 8
get_traffic_light = self._vehicle.get_traffic_light() # type: carla.TrafficLight
nearest_traffic_light, distance = get_nearest_traffic_light(self._vehicle) # type: carla.TrafficLight, float
distance_... | conditional_block |
basic_agent.py | #!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoidi... | (Agent):
"""
BasicAgent implements a basic agent that navigates scenes to reach a given
target destination. This agent respects traffic lights and other vehicles.
"""
def __init__(self, vehicle, target_speed=20):
"""
:param vehicle: actor to apply to local planner logic onto
... | BasicAgent | identifier_name |
APISchedFetch.js | import React, { Component } from 'react';
import {SideBarGame} from './SideBarGame.js';
import {ActiveGameArea} from './ActiveGameArea.js';
import '../css/APISchedFetch.css';
import { BounceLoader } from 'react-spinners';
import NHLShieldLogo from '../resources/NHL-Shield-Logo.svg';
import { MyDatePicker } from './MyDa... | } else {
this.setState({
loading:false,
liveGames: allGames[0],
scheduledGames:allGames[1],
finalGames:allGames[2],
gamesData:allGamesJSON,
gamesContentData:gamesContentData,
records:records
});
}
})
.catch(err =>... | gamesData:allGamesJSON,
gamesContentData:gamesContentData,
records:records
}); | random_line_split |
APISchedFetch.js | import React, { Component } from 'react';
import {SideBarGame} from './SideBarGame.js';
import {ActiveGameArea} from './ActiveGameArea.js';
import '../css/APISchedFetch.css';
import { BounceLoader } from 'react-spinners';
import NHLShieldLogo from '../resources/NHL-Shield-Logo.svg';
import { MyDatePicker } from './MyDa... | () {
this.refreshData();
this._interval = window.setInterval(this.refreshData,10000); // set refresh interval to 5s
}
componentWillUnMount() {
this._interval && window.clearInterval(this._interval); // remove refresh interval when unmounted
}
sideBarClick(gameFID) {
this.setState({mainGamePk: ... | componentDidMount | identifier_name |
APISchedFetch.js | import React, { Component } from 'react';
import {SideBarGame} from './SideBarGame.js';
import {ActiveGameArea} from './ActiveGameArea.js';
import '../css/APISchedFetch.css';
import { BounceLoader } from 'react-spinners';
import NHLShieldLogo from '../resources/NHL-Shield-Logo.svg';
import { MyDatePicker } from './MyDa... |
allGames = [liveGames,scheduledGames,finalGames,data];
allGamesJSON = allGamesJSON.concat(gameData);
})
);
// content data is available at a different endpoint and needs its own fetch
fetches.push(
fetch(apiContentString)
.then(contentRaw => {
ret... | {
finalGames = finalGames.concat(gameData);
} | conditional_block |
APISchedFetch.js | import React, { Component } from 'react';
import {SideBarGame} from './SideBarGame.js';
import {ActiveGameArea} from './ActiveGameArea.js';
import '../css/APISchedFetch.css';
import { BounceLoader } from 'react-spinners';
import NHLShieldLogo from '../resources/NHL-Shield-Logo.svg';
import { MyDatePicker } from './MyDa... |
backButtonClick() {
this.setState({mobileActive:'list'}); // used for mobile to provide back button functionality
}
handleDateChange(date) {
this.setState({
date:date,
liveGames: [], // array of game data for live games
scheduledGames: [], // array of game data for scheduled gam... | {
this.setState({mainGamePk: gameFID, mobileActive:'gameView'}); // handles sidebar game click
} | identifier_body |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... | (f: File) -> Scanners {
let buf = BufReader::new(f);
let mut scanners = HashMap::new();
let mut max_depth = 0;
let mut max_range = 0;
for line in buf.lines() {
let split = line.expect("io error")
.split(": ")
.map(|s| s.parse::<i32>().expect("parse int err"))
... | get_scanners | identifier_name |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... | // 0 1 2 3 4 5 6
// [ ] ( ) ... ... [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// 0 1 2 3 4 5 6
// [ ] (S) ... ... [ ] ... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] [ ]
... | // [ ] [ ]
// Picosecond 1:
| random_line_split |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... |
let mi = r - 1; /* max index of the scanner range */
let unique_positions = r * 2 - 2; /* how many different states the scanner can be in. Whenever the scanner is at an end, it can only be turning around. Whenever a scanner is in a middle position, it could be going back or forward*/
... | {
return Some(0);
} | conditional_block |
13.1.rs | // --- Day 13: Packet Scanners ---
// You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner.
// By studying the firewall briefly, you are able to record (in your puzzle in... |
fn main() {
let fname = "src/13/data";
// let fname = "src/13/testdata";
let f = File::open(fname).expect(&format!("Couldn't open {}", fname));
let scanners = get_scanners(f);
println!(
"Advent 13-1: severity {} at offset 0.",
severity(&0, &scanners)
);
let m... | {
let mut d: i32 = 0;
while d <= scanners.max_depth {
let scanner_time = d + offset;
if scanners.collides(&d, &scanner_time) {
return true;
}
d += 1;
}
false
} | identifier_body |
config.js | var config = {
style: 'mapbox://styles/brittanyyee/ck1goz6tl5d021cki0jl15r65',
accessToken: 'pk.eyJ1IjoiYnJpdHRhbnl5ZWUiLCJhIjoiY2sxczhzMWhrMDJwazNtcWd4b204Zno2cSJ9.vQDXWGzRH8W2ys-VlQi9bg',
showMarkers: false,
theme: 'dark',
alignment: 'left',
title: 'Australian Adventure',
subtitle: ... | bearing: 0
},
onChapterEnter: [
{
layer: 'ports',
opacity: 1
}
],
onChapterExit: [
{
layer: 'ports',
opacity: 0
... |
location: {
center: [151.235148, -33.851759],
zoom: 4.5,
pitch: 60,
| random_line_split |
cache.go | package cache
import (
"errors"
"fmt"
"github.com/go-redis/cache/v7/internal/lrucache"
"github.com/go-redis/cache/v7/internal/singleflight"
"log"
"reflect"
"sync/atomic"
"time"
"github.com/go-redis/redis/v7"
)
var ErrCacheMiss = errors.New("cache: key is missing")
var errRedisLocalCacheNil = errors.New("cac... | }
obj = d
}
if !item.doNotReturn {
m.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(obj))
}
items[i] = item
i++
}
return cd.Set(items...)
}
return nil
}
func (cd *Codec) mSetItems(items []*Item) error {
var pipeline redis.Pipeliner
if cd.Redis != nil {
pipeline = cd.Redis.Pipeli... | item = &Item{
Key: key,
Object: d,
Expiration: mItem.Expiration, | random_line_split |
cache.go | package cache
import (
"errors"
"fmt"
"github.com/go-redis/cache/v7/internal/lrucache"
"github.com/go-redis/cache/v7/internal/singleflight"
"log"
"reflect"
"sync/atomic"
"time"
"github.com/go-redis/redis/v7"
)
var ErrCacheMiss = errors.New("cache: key is missing")
var errRedisLocalCacheNil = errors.New("cac... |
func (cd *Codec) setItem(item *Item) ([]byte, error) {
object, err := item.object()
if err != nil {
return nil, err
}
b, err := cd.Marshal(object)
if err != nil {
log.Printf("cache: Marshal key=%q failed: %s", item.Key, err)
return nil, err
}
if cd.localCache != nil {
cd.localCache.Set(item.Key, b)
... | {
if len(items) == 1 {
_, err := cd.setItem(items[0])
return err
} else if len(items) > 1 {
return cd.mSetItems(items)
}
return nil
} | identifier_body |
cache.go | package cache
import (
"errors"
"fmt"
"github.com/go-redis/cache/v7/internal/lrucache"
"github.com/go-redis/cache/v7/internal/singleflight"
"log"
"reflect"
"sync/atomic"
"time"
"github.com/go-redis/redis/v7"
)
var ErrCacheMiss = errors.New("cache: key is missing")
var errRedisLocalCacheNil = errors.New("cac... |
elementType := mapType.Elem()
// non-pointer values not supported yet
if elementType.Kind() != reflect.Ptr {
return fmt.Errorf("dst value type must be a pointer, %v given", elementType.Kind())
}
// get the value that the pointer elementType points to.
elementType = elementType.Elem()
// allocate a new map, ... | {
return fmt.Errorf("dst key type must be a string, %v given", keyType.Kind())
} | conditional_block |
cache.go | package cache
import (
"errors"
"fmt"
"github.com/go-redis/cache/v7/internal/lrucache"
"github.com/go-redis/cache/v7/internal/singleflight"
"log"
"reflect"
"sync/atomic"
"time"
"github.com/go-redis/redis/v7"
)
var ErrCacheMiss = errors.New("cache: key is missing")
var errRedisLocalCacheNil = errors.New("cac... | () {
if cd.defaultRedisExpiration < time.Second {
cd.defaultRedisExpiration = time.Hour
}
}
func (cd *Codec) Delete(keys ...string) error {
if cd.localCache != nil {
for _, key := range keys {
cd.localCache.Delete(key)
}
}
if cd.Redis == nil {
if cd.localCache == nil {
return errRedisLocalCacheNil... | ensureDefaultExp | identifier_name |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | else {
match *value {
Lit::Str(ref value, _) => attrs.checks.push((String::from(ident.as_ref()), value.clone())),
_ => panic!("Other checks must have RHS String."),
}
... | {
match *value {
Lit::Str(ref value, _) => {
if value.ends_with("?") {
attrs.type_name = Some(value[.. value.len()-1].to_string());
... | conditional_block |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... |
/// Accepts Name to construct enum
fn impl_object_for_enum(ast: &DeriveInput, variants: &Vec<Variant>) -> quote::Tokens {
let id = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let ser_code: Vec<_> = variants.iter().map(|var| {
quote! {
#id... | {
let attrs = GlobalAttrs::from_ast(&ast);
if attrs.is_stream {
match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(r... | identifier_body |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(ref data) => impl_object_for_struct(ast, data.fields()),
Body... | random_line_split | |
lib.rs | //! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each o... | (ast: &DeriveInput, fields: &[Field]) -> quote::Tokens {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let attrs = GlobalAttrs::from_ast(&ast);
let parts: Vec<_> = fields.iter()
.map(|field| {
let (key, default, skip) = field_attrs(fi... | impl_object_for_struct | identifier_name |
swarm_test.go | package swarm_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
mocknetwork "github.com/libp2p/go-libp2p/core/network/mocks"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2... |
func TestResourceManagerAcceptStream(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
rcmgr1 := mocknetwork.NewMockResourceManager(ctrl)
s1 := GenSwarm(t, WithSwarmOpts(swarm.WithResourceManager(rcmgr1)))
defer s1.Close()
rcmgr2 := mocknetwork.NewMockResourceManager(ctrl)
s2 := GenSwarm(t,... | {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
rcmgr1 := mocknetwork.NewMockResourceManager(ctrl)
s1 := GenSwarm(t, WithSwarmOpts(swarm.WithResourceManager(rcmgr1)))
defer s1.Close()
s2 := GenSwarm(t)
defer s2.Close()
connectSwarms(t, context.Background(), []*swarm.Swarm{s1, s2})
rerr := errors.New(... | identifier_body |
swarm_test.go | package swarm_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
mocknetwork "github.com/libp2p/go-libp2p/core/network/mocks"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2... | if s2.LocalPeer() == s1.LocalPeer() {
continue // dont send to self...
}
wg.Add(1)
go send(s2.LocalPeer())
}
wg.Wait()
}()
// receive "pong" x MsgNum from every peer
go func() {
defer close(errChan)
count := 0
countShouldBe := MsgNum * (len(swarms) - 1)
for stream := range... | // read it later
streamChan <- stream
}
for _, s2 := range swarms { | random_line_split |
swarm_test.go | package swarm_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
mocknetwork "github.com/libp2p/go-libp2p/core/network/mocks"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2... |
wg.Add(1)
go send(s2.LocalPeer())
}
wg.Wait()
}()
// receive "pong" x MsgNum from every peer
go func() {
defer close(errChan)
count := 0
countShouldBe := MsgNum * (len(swarms) - 1)
for stream := range streamChan { // one per peer
// get peer on the other side
p := stream.Conn(... | {
continue // dont send to self...
} | conditional_block |
swarm_test.go | package swarm_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
mocknetwork "github.com/libp2p/go-libp2p/core/network/mocks"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2... | (t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
rcmgr1 := mocknetwork.NewMockResourceManager(ctrl)
s1 := GenSwarm(t, WithSwarmOpts(swarm.WithResourceManager(rcmgr1)))
defer s1.Close()
s2 := GenSwarm(t)
defer s2.Close()
connectSwarms(t, context.Background(), []*swarm.Swarm{s1, s2})
rerr... | TestResourceManagerNewStream | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.