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 |
|---|---|---|---|---|
script.js | ///IMPORTS-----------------------------------------
import screens from './components/screens.js'
import PausedTimeout from './functions/pausedTimeout.js'
import map1 from './maps/map1.js'
import map2 from './maps/map2.js'
import map3 from './maps/map3.js'
import map4 from './maps/map4.js'
import map5 from './maps/map... | timeouts[timeout].stopTimeout()
delete timeouts[timeout]
}
}
window.rotationPercentage = function(){
let ratio
(rotationAngle%360)/360 < 0 ? ratio = Math.abs((rotationAngle%360)/360 + 1) : ratio = (rotationAngle%360)/360
if(ratio >= 0.5) ratio = (1 - ratio)
ratio*=4
if(rat... | window.destroyTimeouts = function(){
for(let timeout in timeouts){ | random_line_split |
script.js | ///IMPORTS-----------------------------------------
import screens from './components/screens.js'
import PausedTimeout from './functions/pausedTimeout.js'
import map1 from './maps/map1.js'
import map2 from './maps/map2.js'
import map3 from './maps/map3.js'
import map4 from './maps/map4.js'
import map5 from './maps/map... |
//EVENT LISTENERS ---------------------------------------------------
window.initListeners = function(){
document.addEventListener('keypress',e=>{
//WHEN YOU PRESS THE SPACEBAR
if(e.keyCode==32){
//PAUSES GAME
if(!state.paused){
screens({
title:'Paused',
... | {
myIntervals.moving = setInterval(()=>{
if(state.paused) return
let ratio = (rotationAngle%360)/360
if(ratio < 0 ) ratio=Math.abs(ratio + 1)
let ratio2 = (10 * (ratio*4))
if(ratio2 > 20) ratio2 -= 2*(ratio2 - 20)
let ratio3 = (10 * (ratio*4))
... | identifier_body |
codon_usage.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 17:34:32 2019
@author: fanlizhou
Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt'
Plot heatmap of amino acid usage and codon usage
Plot codon usage in each gene for each amino acid. Genes were arranged so that
the ge... | # codon usage difference between SP and LP groups
AAs = []
for AA in codon_dict.keys():
AAs.append(AA)
if len(codon_dict[AA]) == 2:
file.write('%s: %s, %s\n' %
(AA, codon_dict[AA][0], codon_dict[AA][1]))
else:
file.write('%s... | file = io.open('AAs_to_compare.txt', 'w')
file.write('Compare following AAs\n')
# AAs that have only two codon choices and show significant | random_line_split |
codon_usage.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 17:34:32 2019
@author: fanlizhou
Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt'
Plot heatmap of amino acid usage and codon usage
Plot codon usage in each gene for each amino acid. Genes were arranged so that
the ge... |
def get_AA(self, codon):
# dict key: codon -> AA
codon_map = {
'TTT':'Phe', 'TTC':'Phe', 'TTA':'Leu', 'TTG':'Leu',
'TCT':'Ser', 'TCC':'Ser', 'TCA':'Ser', 'TCG':'Ser',
'TAT':'Tyr', 'TAC':'Tyr', 'TAA':'STOP', 'TAG':'STOP',
'TGT':'Cys', 'TGC':'Cys', 'TGA':'S... | file = io.open(filename)
# list of selected gene sequences, excluded genes that are non-triple
all_seq = []
gene_seq = ''
count_all = 0
count_non_triple = 0
for line in file:
# read a gene information line
if line[0]=='>':
coun... | identifier_body |
codon_usage.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 17:34:32 2019
@author: fanlizhou
Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt'
Plot heatmap of amino acid usage and codon usage
Plot codon usage in each gene for each amino acid. Genes were arranged so that
the ge... | (sp_AA_dict, lp_AA_dict):
# plot each AA
for AA in list(sp_AA_dict.keys()):
# list of codon usage information
codon_data = []
# List of codon names
codons = []
for codon in sp_AA_dict[AA]:
# LP group data is displayed from lowest expressed ge... | plot_SP_LP | identifier_name |
codon_usage.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 17:34:32 2019
@author: fanlizhou
Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt'
Plot heatmap of amino acid usage and codon usage
Plot codon usage in each gene for each amino acid. Genes were arranged so that
the ge... |
# read a gene sequence line
else:
gene_seq += line.strip()
file.close()
print('%s:\n%d genes added\n%d are non-triple\n'%
(filename[:2],count_all, count_non_triple))
return (... | count_all += 1
# if a gene has been read, then append it to all_seq if the
# sequence is triple
if gene_seq!='':
if len(gene_seq)%3:
count_non_triple += 1
else:
... | conditional_block |
game.rs | use std::ops::Add;
use super::rand::{thread_rng, Rng};
use super::direction::Direction;
/// A mask with a single section of 16 bits set to 0.
/// Used to extract a "horizontal slice" out of a 64 bit integer.
pub static ROW_MASK: u64 = 0xFFFF;
/// A `u64` mask with 4 sections each starting after the n * 16th bit.
/// ... | ///
/// // | F | E | D | C | | F | B | 7 | 3 |
/// // | B | A | 9 | 8 | => | E | A | 6 | 2 |
/// // | 7 | 6 | 5 | 4 | | D | 9 | 5 | 1 |
/// // | 3 | 2 | 1 | 0 | | C | 8 | 4 | 0 |
///
/// assert_eq!(Game::transpose(0xFEDC_BA98_7654_3210), 0xFB73_EA62_D951_C840);
/// `... | random_line_split | |
game.rs | use std::ops::Add;
use super::rand::{thread_rng, Rng};
use super::direction::Direction;
/// A mask with a single section of 16 bits set to 0.
/// Used to extract a "horizontal slice" out of a 64 bit integer.
pub static ROW_MASK: u64 = 0xFFFF;
/// A `u64` mask with 4 sections each starting after the n * 16th bit.
/// ... | { pub board: u64 }
impl Game {
/// Constructs a new `tfe::Game`.
///
/// `Game` stores a board internally as a `u64`.
///
/// # Examples
///
/// Simple example:
///
/// ```
/// use tfe::Game;
///
/// let mut game = Game::new();
/// # println!("{:016x}", game.board);
... | Game | identifier_name |
svg.go | // +build darwin
package bg
import (
"encoding/xml"
"fmt"
"image"
"io"
"log"
"regexp"
"strconv"
"strings"
"text/scanner"
//polyclip "github.com/akavel/polyclip-go"
"github.com/paulsmith/gogeos/geos"
)
type svgVert struct {
X, Y float64
}
type svgPolyline struct {
RawPoints string `xml:"points,attr"`
... | }
verts = append(verts, geos.NewCoord(p.Points[0].X, p.Points[0].Y))
if poly == nil {
newPoly, err := geos.NewPolygon(verts)
if err != nil {
log.Fatal(fmt.Errorf("New poly creation error: %+v", err))
}
poly = newPoly
} else {
uPoly, _ := geos.NewPolygon(verts)
uPolyTy... | random_line_split | |
svg.go | // +build darwin
package bg
import (
"encoding/xml"
"fmt"
"image"
"io"
"log"
"regexp"
"strconv"
"strings"
"text/scanner"
//polyclip "github.com/akavel/polyclip-go"
"github.com/paulsmith/gogeos/geos"
)
type svgVert struct {
X, Y float64
}
type svgPolyline struct {
RawPoints string `xml:"points,attr"`
... |
func (poly *svgPolygon) generatePoints() {
vals := strings.FieldsFunc(poly.PointsData, func(r rune) bool {
return (r == ' ' || r == '\t' || r == ',')
})
poly.Points = make([]svgVert, len(vals)/2)
for idx, _ := range poly.Points {
x, _ := strconv.ParseFloat(vals[idx*2], 32)
y, _ := strconv.ParseFloat(vals[id... | {
wall := jsonWedPolygon{Mode: poly.Mode}
wall.Verts = make([]image.Point, len(poly.Points))
for idx, pt := range poly.Points {
wall.Verts[idx].X = int(pt.X)
wall.Verts[idx].Y = int(pt.Y)
}
return wall
} | identifier_body |
svg.go | // +build darwin
package bg
import (
"encoding/xml"
"fmt"
"image"
"io"
"log"
"regexp"
"strconv"
"strings"
"text/scanner"
//polyclip "github.com/akavel/polyclip-go"
"github.com/paulsmith/gogeos/geos"
)
type svgVert struct {
X, Y float64
}
type svgPolyline struct {
RawPoints string `xml:"points,attr"`
... | () {
if len(group.Polygons) > 0 {
var poly *geos.Geometry
for _, p := range group.Polygons {
if len(p.Points) > 2 {
verts := make([]geos.Coord, 0)
for _, v := range p.Points {
verts = append(verts, geos.NewCoord(v.X, v.Y))
}
verts = append(verts, geos.NewCoord(p.Points[0].X, p.Points[0].Y)... | MergePolygons | identifier_name |
svg.go | // +build darwin
package bg
import (
"encoding/xml"
"fmt"
"image"
"io"
"log"
"regexp"
"strconv"
"strings"
"text/scanner"
//polyclip "github.com/akavel/polyclip-go"
"github.com/paulsmith/gogeos/geos"
)
type svgVert struct {
X, Y float64
}
type svgPolyline struct {
RawPoints string `xml:"points,attr"`
... |
return paths
}
func geosPolygonToPolygon(poly *geos.Geometry) svgPolygon {
shell, err := poly.Shell()
if err != nil {
log.Fatal(fmt.Errorf("Shell creation error: %+v", err))
}
mergedPoly := svgPolygon{}
coords, err := shell.Coords()
if err != nil {
log.Fatal(fmt.Errorf("Coords error: %+v", err))
}
for _... | {
p := &paths[idx]
for pIdx, _ := range p.Polygons {
poly := &p.Polygons[pIdx]
for vIdx, _ := range poly.Points {
v := &poly.Points[vIdx]
v.X += group.translate.X
v.Y += group.translate.Y
}
}
} | conditional_block |
db_feeds.go | package database
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
)
//GetFeedInfo -- Pulls the rss feed from the website and dumps the needed info into the database
func GetFeedInfo(db *sql.DB, feedID int64) (err error) {
var feedData *gofeed.Feed
//Get the URl
url, err := GetFeedUR... |
if !strings.EqualFold(data, "") {
//Need to convert the data to a gofeed object
feedParser := gofeed.NewParser()
feedData, err = feedParser.Parse(strings.NewReader(data))
if err != nil {
return feed, fmt.Errorf("gofeed parser was unable to parse data: %s -- %s", data, err.Error())
}
}
var tags []stri... | {
return feed, fmt.Errorf("No data to retrieve: %s", err.Error())
} | conditional_block |
db_feeds.go | package database
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
)
//GetFeedInfo -- Pulls the rss feed from the website and dumps the needed info into the database
func GetFeedInfo(db *sql.DB, feedID int64) (err error) {
var feedData *gofeed.Feed
//Get the URl
url, err := GetFeedUR... | (db *sql.DB, url string) bool {
var id int64
var result bool
row := db.QueryRow("SELECT id FROM feeds WHERE uri = $1", url)
err := row.Scan(&id)
if err != nil {
if err != sql.ErrNoRows {
log.Fatalf("Error happened when trying to check if the feed (%s) exists: %s", url, err.Error())
}
} else {
result = t... | FeedURLExist | identifier_name |
db_feeds.go | package database
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
)
//GetFeedInfo -- Pulls the rss feed from the website and dumps the needed info into the database
func GetFeedInfo(db *sql.DB, feedID int64) (err error) {
var feedData *gofeed.Feed
//Get the URl
url, err := GetFeedUR... |
//GetFeedAuthor -- returns the feed author
func GetFeedAuthor(db *sql.DB, feedID int64) (name, email string, err error) {
stmt := "SELECT authors.name, authors.email FROM feeds INNER JOIN authors ON authors.id = feeds.author_id WHERE feeds.id = $1"
row := db.QueryRow(stmt, feedID)
err = row.Scan(&name, &email)
re... | {
var feedData *gofeed.Feed
url, err := GetFeedURL(db, id)
if err != nil {
log.Fatal(err)
}
title, err := GetFeedTitle(db, id)
if err != nil {
log.Fatal(err)
}
if strings.EqualFold(title, "") {
title = url
}
data, err := GetFeedRawData(db, id)
if err != nil {
return feed, fmt.Errorf("No data to re... | identifier_body |
db_feeds.go | package database
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/mmcdole/gofeed"
)
//GetFeedInfo -- Pulls the rss feed from the website and dumps the needed info into the database
func GetFeedInfo(db *sql.DB, feedID int64) (err error) {
var feedData *gofeed.Feed
//Get the URl
url, err := GetFeedUR... | }
return result, nil
} | if err != nil {
log.Fatal(err) | random_line_split |
rtmDiskUsage.js | Ext.define('rtm.src.rtmDiskUsage', {
extend: 'Exem.DockForm',
title : common.Util.TR('Disk Usage'),
layout: 'fit',
width : '100%',
height: '100%',
isClosedDockForm: false,
listeners: {
beforedestroy: function() {
this.isClosedDockForm = true;
this.stopRefre... | id.drawGrid();
adata = null;
}
});
| a.rows[ix][0], // mount name
adata.rows[ix][1], // file system
adata.rows[ix][2], // ratio
Math.trunc(+adata.rows[ix][3]), // used size
Math.trunc(+adata.rows[ix][4]) // tota size
... | conditional_block |
rtmDiskUsage.js | Ext.define('rtm.src.rtmDiskUsage', {
extend: 'Exem.DockForm',
title : common.Util.TR('Disk Usage'),
layout: 'fit',
width : '100%',
height: '100%',
isClosedDockForm: false,
listeners: {
beforedestroy: function() {
this.isClosedDockForm = true;
this.stopRefre... | }); | random_line_split | |
exif-tags.ts | import { ExifMetadataType } from "./types";
export interface TagNames {
[id: number]: string;
}
export interface IfdTags {
[ExifMetadataType.Exif]: TagNames;
[ExifMetadataType.Gps]: TagNames;
[ExifMetadataType.Interoperability]: TagNames;
}
const tags: IfdTags = {
// Exif tags
[ExifMetadataType.Exif] : {... | 0xC716 : "PreviewApplicationName",
0xC717 : "PreviewApplicationVersion",
0xC718 : "PreviewSettingsName",
0xC719 : "PreviewSettingsDigest",
0xC71A : "PreviewColorSpace",
0xC71B : "PreviewDateTime",
0xC71C : "RawImageDigest",
0xC71D : "OriginalRawFileDigest",
0xC71E : "SubTileBlockSize... | 0xC715 : "ForwardMatrix2", | random_line_split |
preprocessing_lpba40.py | import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
import scipy.stats as stats
DEFAULT_CUTOFF = 0.01, 0.99
STANDARD_RANGE = 0, 100
def resample_image(itk_image, out_spacing=(2.0, 2.0, 2.0), is_label=False):
original_spacing = itk_image.GetSpacing()
original_size = itk_image.GetSize(... | import os
import subprocess | random_line_split | |
preprocessing_lpba40.py | import os
import subprocess
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
import scipy.stats as stats
DEFAULT_CUTOFF = 0.01, 0.99
STANDARD_RANGE = 0, 100
def resample_image(itk_image, out_spacing=(2.0, 2.0, 2.0), is_label=False):
original_spacing = itk_image.GetSpacing()
origin... |
if not os.path.exists(str(output_path_mask)):
os.makedirs(str(output_path_mask))
for i in list(range(1, 41, 1)):
for j in list(range(1, 41, 1)):
# ~~~~~~~~~~~~~~~ images ~~~~~~~~~~~~~~~
volpath = os.path.join(input_path, 'l{}_to_l{}.nii'.format(str(i), str(j)))
... | os.makedirs(str(output_path_hs_small)) | conditional_block |
preprocessing_lpba40.py | import os
import subprocess
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
import scipy.stats as stats
DEFAULT_CUTOFF = 0.01, 0.99
STANDARD_RANGE = 0, 100
def resample_image(itk_image, out_spacing=(2.0, 2.0, 2.0), is_label=False):
original_spacing = itk_image.GetSpacing()
origin... |
def _get_average_mapping(percentiles_database):
"""Map the landmarks of the database to the chosen range.
Args:
percentiles_database: Percentiles database over which to perform the
averaging.
"""
# Assuming percentiles_database.shape == (num_data_points, num_percentiles)
pc1 ... | quartiles = np.arange(25, 100, 25).tolist()
deciles = np.arange(10, 100, 10).tolist()
all_percentiles = list(percentiles_cutoff) + quartiles + deciles
percentiles = sorted(set(all_percentiles))
return np.array(percentiles) | identifier_body |
preprocessing_lpba40.py | import os
import subprocess
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
import scipy.stats as stats
DEFAULT_CUTOFF = 0.01, 0.99
STANDARD_RANGE = 0, 100
def resample_image(itk_image, out_spacing=(2.0, 2.0, 2.0), is_label=False):
original_spacing = itk_image.GetSpacing()
origin... | (array, landmarks, mask=None, cutoff=None, epsilon=1e-5):
cutoff_ = DEFAULT_CUTOFF if cutoff is None else cutoff
mapping = landmarks
data = array
shape = data.shape
data = data.reshape(-1).astype(np.float32)
if mask is None:
mask = np.ones_like(data, np.bool)
mask = mask.reshape(-1... | normalize | identifier_name |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | let _ = std::fs::remove_dir_all(&self.local_path);
self.update_repo()
}
else {
// Reset the repo to his original state after the check
if current_branch_name != master_refname {
self.checkout_branch(&repo, ¤t_branch_name)?;
... | let path = self.local_path.to_string_lossy().to_string() + "\\*.*";
let _ = SystemCommand::new("attrib").arg("-r").arg(path).arg("/s").output();
}
| conditional_block |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | self, contents: &str) -> Result<()> {
let mut file = BufWriter::new(File::create(self.local_path.join(".gitignore"))?);
file.write_all(contents.as_bytes()).map_err(From::from)
}
/// This function switches the branch of a `GitIntegration` to the provided refspec.
pub fn checkout_branch(&self... | d_gitignore(& | identifier_name |
git.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | Err(_) => return Ok(GitResponse::NoLocalFiles),
};
// Just in case there are loose changes, stash them.
// Ignore a fail on this, as it's possible we don't have contents to stash.
let current_branch_name = Reference::normalize_name(repo.head()?.name().unwrap(), ReferenceForm... | let mut repo = match Repository::open(&self.local_path) {
Ok(repo) => repo,
// If this fails, it means we either we don´t have the repo downloaded, or we have a folder without the .git folder. | random_line_split |
RPMutils.py | """Utility functions and global parameters for the model."""
import time
import math
import os
from ca.nengo.model import SimulationMode
from ca.nengo.model import Units
from ca.nengo.model.impl import FunctionInput
from ca.nengo.model.nef.impl import NEFEnsembleFactoryImpl
from ca.nengo.math import PDFTools
from ca.... | #prediction of blank cell from neural module
def hypothesisFile(modulename):
return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, modulename + "_hypothesis_" + str(JOB_ID) + ".txt")
#file to record the rules used to solve a matrix
def ruleFile():
return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, "rule... |
#rule output from neural module
def resultFile(modulename):
return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, modulename + "_result_" + str(JOB_ID) + ".txt")
| random_line_split |
RPMutils.py | """Utility functions and global parameters for the model."""
import time
import math
import os
from ca.nengo.model import SimulationMode
from ca.nengo.model import Units
from ca.nengo.model.impl import FunctionInput
from ca.nengo.model.nef.impl import NEFEnsembleFactoryImpl
from ca.nengo.math import PDFTools
from ca.... | (names, vectors):
return [FunctionInput(names[i], [ConstantFunction(1,x) for x in vec], Units.UNK) for i,vec in enumerate(vectors)]
#load vectors from a file and create corresponding output functions
def loadInputVectors(filename):
file = open(filename)
vectors = [str2floatlist(line) for line in file]
... | makeInputVectors | identifier_name |
RPMutils.py | """Utility functions and global parameters for the model."""
import time
import math
import os
from ca.nengo.model import SimulationMode
from ca.nengo.model import Units
from ca.nengo.model.impl import FunctionInput
from ca.nengo.model.nef.impl import NEFEnsembleFactoryImpl
from ca.nengo.math import PDFTools
from ca.... |
#normalize vec
def normalize(vec):
l = length(vec)
if l == 0:
return vec
return [x/l for x in vec]
#calculate similarity between vec1 and vec2
def similarity(vec1, vec2):
if len(vec1) != len(vec2):
System.err.println("vectors not the same length in RPMutils.similarity(), something is ... | return math.sqrt(sum([x**2 for x in vec])) | identifier_body |
RPMutils.py | """Utility functions and global parameters for the model."""
import time
import math
import os
from ca.nengo.model import SimulationMode
from ca.nengo.model import Units
from ca.nengo.model.impl import FunctionInput
from ca.nengo.model.nef.impl import NEFEnsembleFactoryImpl
from ca.nengo.math import PDFTools
from ca.... |
return float(sum(vec)) / len(vec)
#calculate the words in vocab that vec1 and vec2 have in common
def calcSame(vec1, vec2, vocab, threshold, weight1, weight2):
vec1 = [x*weight1 for x in vec1]
vec2 = [x*weight2 for x in vec2]
vec = vecsum(vec1,vec2)
ans = [0 for i in range(len(vec))]
for ... | return 0.0 | conditional_block |
runtime.py | # Copyright (c) 2015 - 2022, Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
"""Tools to support runtime implementations that use the GEOPM service
"""
import math
import time
import subprocess # nosec
import sys
import shlex
from . import pio
class TimedLoop:
"""Object that can be iterated over ... | """Execute control loop defined by agent
Interfaces with PlatformIO directly through the geopmdpy.pio module.
Args:
argv (list(str)): Arguments for application that is executed
policy (object): Policy for Agent to use during the run
Returns:
str: Human rea... | identifier_body | |
runtime.py | # Copyright (c) 2015 - 2022, Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
"""Tools to support runtime implementations that use the GEOPM service
"""
import math
import time
import subprocess # nosec
import sys
import shlex
from . import pio
class TimedLoop:
"""Object that can be iterated over ... | return self._returncode
def run(self, argv, policy=None, profile=None):
"""Execute control loop defined by agent
Interfaces with PlatformIO directly through the geopmdpy.pio module.
Args:
argv (list(str)): Arguments for application that is executed
policy ... | random_line_split | |
runtime.py | # Copyright (c) 2015 - 2022, Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
"""Tools to support runtime implementations that use the GEOPM service
"""
import math
import time
import subprocess # nosec
import sys
import shlex
from . import pio
class TimedLoop:
"""Object that can be iterated over ... | (self):
"""Get the target time interval for the control loop
Returns:
float: Time interval in seconds
"""
raise NotImplementedError('Agent is an abstract base class')
def get_report(self):
"""Summary of all data collected by calls to update()
The repor... | get_period | identifier_name |
runtime.py | # Copyright (c) 2015 - 2022, Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
"""Tools to support runtime implementations that use the GEOPM service
"""
import math
import time
import subprocess # nosec
import sys
import shlex
from . import pio
class TimedLoop:
"""Object that can be iterated over ... |
for control_idx, new_setting in zip(self._controls_idx, new_settings):
pio.adjust(control_idx, new_setting)
pio.write_batch()
self._agent.run_end()
except:
raise
finally:
pio.restore_control()
self._returnco... | break | conditional_block |
FutureWork.py | '''In this script, we will produce preliminary results for the ideas that are
emitted in the disrtation entiteled "A new Bayesian framework for the
interpretation of geophysical data".
Those ideas are:
1) Building a prior with a fixed, large number of layers
2) Propagating the posterior model space from close-by poi... | pool.terminate() | conditional_block | |
FutureWork.py | '''In this script, we will produce preliminary results for the ideas that are
emitted in the disrtation entiteled "A new Bayesian framework for the
interpretation of geophysical data".
Those ideas are:
1) Building a prior with a fixed, large number of layers
2) Propagating the posterior model space from close-by poi... | ():
'''BUILDMODELSET is a function that will build the benchmark model.
It does not take any arguments. '''
# Values for the benchmark model parameters:
TrueModel1 = np.asarray([0.01, 0.05, 0.120, 0.280, 0.600]) # Thickness and Vs for the 3 layers (variable of the problem)
TrueModel2 = np.asarray... | buildMODELSET_MASW | identifier_name |
FutureWork.py | '''In this script, we will produce preliminary results for the ideas that are
emitted in the disrtation entiteled "A new Bayesian framework for the
interpretation of geophysical data".
Those ideas are:
1) Building a prior with a fixed, large number of layers
2) Propagating the posterior model space from close-by poi... |
forwardFun = funcSurf96
forward = {"Fun":forwardFun,"Axis":Periods}
# Building the function for conditions (here, just checks that a sampled model is inside the prior)
cond = lambda model: (np.logical_and(np.greater_equal(model,Mins),np.less_equal(model,Maxs))).all()
# Initialize the model paramet... | import numpy as np
from pysurf96 import surf96
Vp = np.asarray([0.300, 0.750, 1.5]) # Defined again inside the function for parallelization
rho = np.asarray([1.5, 1.9, 2.2]) # Idem
nLayer = 3 # Idem
Frequency = np.logspace(0.1,1.5,50) # I... | identifier_body |
FutureWork.py | '''In this script, we will produce preliminary results for the ideas that are
emitted in the disrtation entiteled "A new Bayesian framework for the
interpretation of geophysical data".
Those ideas are:
1) Building a prior with a fixed, large number of layers
2) Propagating the posterior model space from close-by poi... | if ParallelComputing:
pool = pp.ProcessPool(mp.cpu_count())# Create the parallel pool with at most the number of available CPU cores
ppComp = [True, pool]
else:
ppComp = [False, None] # No parallel computing
'''1) Building a prior with fixed, large number of layers'''
if Ru... | seed(0)
| random_line_split |
MultinomialAdversarialNetwork.py | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... | (self, k, m, model_params=None, log_params=None):
super().__init__(k,m,model_params,log_params)
def prepare_data(self,d):
"""
Assume d is a dictionary of dataset where d[domain] = another dataset class
Assume labeled domain = train set, unlabeled = test
"""
t... | __init__ | identifier_name |
MultinomialAdversarialNetwork.py | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... |
def transform(self, d, *args, **kwargs):
F_d = self.F_d[opt.domains[0]]
self.F_s.eval()
F_d.eval()
self.C.eval()
_,_,_,it = self.prepare_data(d)
it = it[opt.unlabeled_domains[0]]
correct = 0
total = 0
confusion = ConfusionMeter(opt.num_la... | train_loaders, train_iters, unlabeled_loaders, unlabeled_iters = self.prepare_data(d)
#Training
self.F_s = MlpFeatureExtractor(d['train'].X.shape[1], opt.F_hidden_sizes,opt.shared_hidden_size, opt.dropout)
self.F_d = {}
for domain in opt.domains:
self.F_d[domain] = MlpFeature... | identifier_body |
MultinomialAdversarialNetwork.py | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... |
return train_loaders, train_iters, unlabeled_loaders, unlabeled_iters
def fit(self, d, *args, **kwargs):
#minibatches = create_minibatch(X, y, z, batch_size)
#TODO: make this able to fit consecutively
train_loaders, train_iters, unlabeled_lo... | features, target = torch.from_numpy(d[domain].X.todense().astype('float32')), torch.from_numpy(d[domain].y)#.reshape(-1,1))
uset = data_utils.TensorDataset(features,target)
unlabeled_loaders[domain] = DataLoader(uset,opt.batch_size, shuffle = True)
unlabeled_iters[domain] = iter(unla... | conditional_block |
MultinomialAdversarialNetwork.py | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... | elif opt.loss.lower() == 'l2':
d_targets = utils.get_random_domain_label(opt.loss, len(d_inputs))
l_d = functional.mse_loss(d_outputs, d_targets)
if opt.lambd > 0:
l_d *= opt.lambd
... | random_line_split | |
fid_pics.py | # This script creates plots for experiments from
# ICLR 2018 submission by Bousquet, Gelly, Tolstikhin, Bernhard.
# 1. Random samples
# 2. Interpolations:
# a. Between points of the test set, linearly
# b. Take a random point from Pz and make a whole circle on geodesic
# 3. Test reconstructions
import os
import sy... |
def create_dir(d):
if not tf.gfile.IsDirectory(d):
tf.gfile.MakeDirs(d)
main()
| if len(pic.shape) == 4:
pic = pic[0]
height = pic.shape[0]
width = pic.shape[1]
fig = plt.figure(frameon=False, figsize=(width, height))#, dpi=1)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
if exp.symmetrize:
pic = (pic + 1.) / 2.
if exp.datase... | identifier_body |
fid_pics.py | # This script creates plots for experiments from
# ICLR 2018 submission by Bousquet, Gelly, Tolstikhin, Bernhard.
# 1. Random samples
# 2. Interpolations:
# a. Between points of the test set, linearly
# b. Take a random point from Pz and make a whole circle on geodesic
# 3. Test reconstructions
import os
import sy... |
elif exp_name == 'celeba_vae':
exp = exp9
exp_list = [exp]
for exp in exp_list:
output_dir = os.path.join(OUT_DIR, exp.alias)
create_dir(output_dir)
z_dim = exp.z_dim
pz_std = exp.pz_std
dataset = exp.dataset
model_path = exp.trained_model_path
... | exp = exp8 | conditional_block |
fid_pics.py | # This script creates plots for experiments from
# ICLR 2018 submission by Bousquet, Gelly, Tolstikhin, Bernhard.
# 1. Random samples
# 2. Interpolations:
# a. Between points of the test set, linearly
# b. Take a random point from Pz and make a whole circle on geodesic
# 3. Test reconstructions
import os
import sy... | self.symmetrize = None
self.dataset = None
self.alias = None
self.test_size = None
def main():
exp_name = sys.argv[-1]
create_dir(OUT_DIR)
exp_names = ['mnist_gan', 'mnist_mmd', 'celeba_gan', 'celeba_mmd']
cluster_mnist_mmd_path = './mount/GANs/results_mnist_pot_sota_wo... | random_line_split | |
fid_pics.py | # This script creates plots for experiments from
# ICLR 2018 submission by Bousquet, Gelly, Tolstikhin, Bernhard.
# 1. Random samples
# 2. Interpolations:
# a. Between points of the test set, linearly
# b. Take a random point from Pz and make a whole circle on geodesic
# 3. Test reconstructions
import os
import sy... | (d):
if not tf.gfile.IsDirectory(d):
tf.gfile.MakeDirs(d)
main()
| create_dir | identifier_name |
server_utils.go | //
// (C) Copyright 2021-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package server
import (
"bytes"
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.c... |
engine.RUnlock()
// Retrieve up-to-date hugepage info to check that we got the requested number of hugepages.
mi, err := getMemInfo()
if err != nil {
return err
}
// Calculate mem_size per I/O engine (in MB) from number of hugepages required per engine.
nrPagesRequired := srv.cfg.NrHugepages / len(srv.cfg.E... | {
srv.log.Debugf("skipping mem check on engine %d, no bdevs", ei)
engine.RUnlock()
return nil
} | conditional_block |
server_utils.go | //
// (C) Copyright 2021-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package server
import (
"bytes"
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.c... |
const scanMinHugePageCount = 128
func getBdevCfgsFromSrvCfg(cfg *config.Server) storage.TierConfigs {
var bdevCfgs storage.TierConfigs
for _, engineCfg := range cfg.Engines {
bdevCfgs = append(bdevCfgs, engineCfg.Storage.Tiers.BdevConfigs()...)
}
return bdevCfgs
}
func cfgGetReplicas(cfg *config.Server, look... | {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, errors.Wrapf(err, "unable to split %q", addr)
}
iPort, err := strconv.Atoi(port)
if err != nil {
return nil, errors.Wrapf(err, "unable to convert %q to int", port)
}
addrs, err := lookup(host)
if err != nil {
return nil, errors.Wrapf... | identifier_body |
server_utils.go | //
// (C) Copyright 2021-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package server
import (
"bytes"
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.c... | f, err := os.OpenFile(path, os.O_WRONLY, 0644)
if err != nil {
// Work around a testing oddity that seems to be related to launching
// the server via SSH, with the result that the /proc file is unwritable.
if os.IsPermission(err) {
log.Debugf("Unable to write core dump filter to %s: %s", path, err)
retur... | return filepath.Join(cfg.Engines[0].Storage.Tiers.ScmConfigs()[0].Scm.MountPoint, "control_raft")
}
func writeCoreDumpFilter(log logging.Logger, path string, filter uint8) error { | random_line_split |
server_utils.go | //
// (C) Copyright 2021-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package server
import (
"bytes"
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.c... | (srv *server, engine *EngineInstance, allStarted *sync.WaitGroup) {
// Register callback to publish engine process exit events.
engine.OnInstanceExit(createPublishInstanceExitFunc(srv.pubSub.Publish, srv.hostname))
// Register callback to publish engine format requested events.
engine.OnAwaitFormat(createPublishFo... | registerEngineEventCallbacks | identifier_name |
path_test.go | // Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package common
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/cli-utils/pkg/testutil"
)
const (
packageDir = ... |
})
}
}
func TestFilterInputFile(t *testing.T) {
tf := testutil.Setup(t)
defer tf.Clean()
testCases := map[string]struct {
configObjects [][]byte
expectedObjects [][]byte
}{
"Empty config objects writes empty file": {
configObjects: [][]byte{},
expectedObjects: [][]byte{},
},
"Only inventor... | {
assert.Equal(t, err.Error(), tc.errFromDemandOneDirectory)
} | conditional_block |
path_test.go | // Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package common
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/cli-utils/pkg/testutil"
)
const (
packageDir = ... | (configs ...[]byte) []byte {
r := []byte{}
for i, config := range configs {
if i > 0 {
r = append(r, []byte(configSeparator)...)
}
r = append(r, config...)
}
return r
}
func TestProcessPaths(t *testing.T) {
tf := setupTestFilesystem(t)
defer tf.Clean()
trueVal := true
testCases := map[string]struct {... | buildMultiResourceConfig | identifier_name |
path_test.go | // Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package common
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/cli-utils/pkg/testutil"
)
const (
packageDir = ... |
func TestProcessPaths(t *testing.T) {
tf := setupTestFilesystem(t)
defer tf.Clean()
trueVal := true
testCases := map[string]struct {
paths []string
expectedFileNameFlags genericclioptions.FileNameFlags
errFromDemandOneDirectory string
}{
"empty slice means reading from StdIn": {
... | {
r := []byte{}
for i, config := range configs {
if i > 0 {
r = append(r, []byte(configSeparator)...)
}
r = append(r, config...)
}
return r
} | identifier_body |
path_test.go | // Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package common
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/cli-runtime/pkg/genericclioptions"
"sigs.k8s.io/cli-utils/pkg/testutil"
)
const (
packageDir = ... | }
})
}
}
func TestFilterInputFile(t *testing.T) {
tf := testutil.Setup(t)
defer tf.Clean()
testCases := map[string]struct {
configObjects [][]byte
expectedObjects [][]byte
}{
"Empty config objects writes empty file": {
configObjects: [][]byte{},
expectedObjects: [][]byte{},
},
"Only inve... | assert.Equal(t, tc.expectedFileNameFlags, fileNameFlags)
if err != nil && err.Error() != tc.errFromDemandOneDirectory {
assert.Equal(t, err.Error(), tc.errFromDemandOneDirectory) | random_line_split |
pandas_gp.py | # -*- coding: utf-8 -*-
"""
Standard GP Algorithm (Strongly typed)
Created on Sun Aug 21 10:40:14 2016
@author: jm
"""
import operator
import math
import random
import cPickle
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from deap import algorithms
from... |
return sharpe,
toolbox.register('evaluate', evalFitness, points=train)
toolbox.register('select', tools.selTournament, tournsize=3)
toolbox.register('mate', gp.cxOnePoint)
toolbox.register('expr_mut', gp.genFull, min_=0, max_=3)
toolbox.register('mutate', gp.mutUniform, expr=toolbox.expr_mut,... | sharpe = -99999 | conditional_block |
pandas_gp.py | # -*- coding: utf-8 -*-
"""
Standard GP Algorithm (Strongly typed)
Created on Sun Aug 21 10:40:14 2016
@author: jm
"""
import operator
import math
import random
import cPickle
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from deap import algorithms
from... |
if __name__ == '__main__':
#random.seed(10)
pop = toolbox.population(n=200)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register('avg', np.mean)
stats.register('min', np.min)
stats.register('max', np.max)
pop, log = algorithms.eaMuPlus... | nodes, edges, labels = gp.graph(individual)
g = nx.Graph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)
pos = nx.drawing.nx_agraph.graphviz_layout(g, prog="dot")
nx.draw_networkx_nodes(g, pos)
nx.draw_networkx_edges(g, pos)
nx.draw_networkx_labels(g, pos, labels)
plt.show() | identifier_body |
pandas_gp.py | # -*- coding: utf-8 -*-
"""
Standard GP Algorithm (Strongly typed)
Created on Sun Aug 21 10:40:14 2016
@author: jm
"""
import operator
import math
import random
import cPickle
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from deap import algorithms
from... | (left, right):
return left - right
def pd_multiply(left, right):
return left * right
def pd_divide(left, right):
return left / right
def pd_diff(df_in, _periods):
return df_in.diff(periods=abs(_periods))
def sma(df_in, periods):
return pd.rolling_mean(df_in, abs(periods))
def ewma(df_... | pd_subtract | identifier_name |
pandas_gp.py | # -*- coding: utf-8 -*-
"""
Standard GP Algorithm (Strongly typed)
Created on Sun Aug 21 10:40:14 2016
@author: jm
"""
import operator
import math
import random
import cPickle
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from deap import algorithms
from... | pd_df_float,
pd_df_float,
pd_df_float,
pd_df_float,
pd_df_bool,
pd_df_bool],
pd_df_bool)
pse... | pset = gp.PrimitiveSetTyped('MAIN', [pd_df_float, | random_line_split |
gke.go | /**
* Copyright (c) 2019-present Future Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicab... | () (*model.Report, error) {
if r.error != nil {
return nil, r.error
}
managerList, err := compute.NewInstanceGroupManagersService(r.s).AggregatedList(r.projectID).Do()
if err != nil {
return nil, err
}
// add instance group name of cluster node pool to Set
gkeNodePoolInstanceGroupSet, err := r.getGKEInstan... | Recovery | identifier_name |
gke.go | /**
* Copyright (c) 2019-present Future Corporation | * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed ... | * | random_line_split |
gke.go | /**
* Copyright (c) 2019-present Future Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicab... |
var res []*container.Cluster
for _, cluster := range l {
if cluster.ResourceLabels[label] == value {
res = append(res, cluster)
}
}
return res
}
| { //TODO Temp impl
return l
} | conditional_block |
gke.go | /**
* Copyright (c) 2019-present Future Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicab... |
func (r *GKENodePoolCall) Resize(size int64) (*model.Report, error) {
if r.error != nil {
return nil, r.error
}
// get all instance group mangers list
managerList, err := compute.NewInstanceGroupManagersService(r.s).AggregatedList(r.projectID).Do()
if err != nil {
return nil, err
}
// add instance group ... | {
if r.error != nil {
return r
}
r.targetLabel = labelName
r.targetLabelValue = value
return r
} | identifier_body |
blob.go | package types
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
)
const (
/*
* Currently only to support Legacy VPN plugins, and Mac App Store
* but intended to replace all the various platform code, dev code etc. bits.
*/
CS_SIGNER_TYPE_UNKNOWN = 0
CS_SIGNER_TYPE_LEGACYVPN = 5
CS_SIGNE... | return "Launch Constraint (parent)"
case CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE:
return "Launch Constraint (responsible proc)"
case CSSLOT_LIBRARY_CONSTRAINT:
return "Library Constraint"
case CSSLOT_ALTERNATE_CODEDIRECTORIES:
return "Alternate CodeDirectories 0"
case CSSLOT_ALTERNATE_CODEDIRECTORIES1:
retur... | case CSSLOT_LAUNCH_CONSTRAINT_SELF:
return "Launch Constraint (self)"
case CSSLOT_LAUNCH_CONSTRAINT_PARENT: | random_line_split |
blob.go | package types
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
)
const (
/*
* Currently only to support Legacy VPN plugins, and Mac App Store
* but intended to replace all the various platform code, dev code etc. bits.
*/
CS_SIGNER_TYPE_UNKNOWN = 0
CS_SIGNER_TYPE_LEGACYVPN = 5
CS_SIGNE... |
if err := binary.Write(buf, o, s.Index); err != nil {
return fmt.Errorf("failed to write SuperBlob indices to buffer: %v", err)
}
for _, blob := range s.Blobs {
if err := binary.Write(buf, o, blob.BlobHeader); err != nil {
return fmt.Errorf("failed to write blob header to superblob buffer: %v", err)
}
if... | {
return fmt.Errorf("failed to write SuperBlob header to buffer: %v", err)
} | conditional_block |
blob.go | package types
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
)
const (
/*
* Currently only to support Legacy VPN plugins, and Mac App Store
* but intended to replace all the various platform code, dev code etc. bits.
*/
CS_SIGNER_TYPE_UNKNOWN = 0
CS_SIGNER_TYPE_LEGACYVPN = 5
CS_SIGNE... |
func (b Blob) Bytes() ([]byte, error) {
buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.BigEndian, b.BlobHeader); err != nil {
return nil, fmt.Errorf("failed to write blob header to buffer: %v", err)
}
if err := binary.Write(buf, binary.BigEndian, b.Data); err != nil {
return nil, fmt.Errorf("fail... | {
h := sha256.New()
if err := binary.Write(h, binary.BigEndian, b.BlobHeader); err != nil {
return nil, fmt.Errorf("failed to hash blob header: %v", err)
}
if err := binary.Write(h, binary.BigEndian, b.Data); err != nil {
return nil, fmt.Errorf("failed to hash blob header: %v", err)
}
return h.Sum(nil), nil
} | identifier_body |
blob.go | package types
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
)
const (
/*
* Currently only to support Legacy VPN plugins, and Mac App Store
* but intended to replace all the various platform code, dev code etc. bits.
*/
CS_SIGNER_TYPE_UNKNOWN = 0
CS_SIGNER_TYPE_LEGACYVPN = 5
CS_SIGNE... | () ([]byte, error) {
h := sha256.New()
if err := binary.Write(h, binary.BigEndian, b.BlobHeader); err != nil {
return nil, fmt.Errorf("failed to hash blob header: %v", err)
}
if err := binary.Write(h, binary.BigEndian, b.Data); err != nil {
return nil, fmt.Errorf("failed to hash blob header: %v", err)
}
retur... | Sha256Hash | identifier_name |
storage.go | package callosum
import (
"database/sql"
"fmt"
"log"
"sync"
_ "github.com/mattn/go-sqlite3" //sqllite DB driver import
)
//UserRow holds the data obtained from fetching a row from the `users` table.
type UserRow struct {
ID int64
ScreenName string
Description string
LastLookedAt ... |
}
//StoreScreenName inserts the given screenName into the `screenames` table
func (s *Storage) StoreScreenName(screenName string) {
_, err := s.db.Exec("INSERT OR IGNORE INTO screennames (screen_name) VALUES (?)", screenName)
if err != nil {
log.Fatal(err)
}
}
//StoreUser inserts the Twitter user details into t... | {
log.Fatalf("%q: %s\n", err, sqlStmt)
return
} | conditional_block |
storage.go | package callosum
import (
"database/sql"
"fmt"
"log"
"sync"
_ "github.com/mattn/go-sqlite3" //sqllite DB driver import
)
//UserRow holds the data obtained from fetching a row from the `users` table.
type UserRow struct {
ID int64
ScreenName string
Description string
LastLookedAt ... | }
mutex.Unlock()
return s
}
func (s *Storage) setupTables() {
tableName := "users"
s.makeTable(tableName, fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
user_id INTEGER PRIMARY KEY,
screen_name TEXT CONSTRAINT uniquescreenname UNIQUE,
description TEXT CONSTRAINT defaultdesc DEFAULT "",
... | s.setupTables() | random_line_split |
storage.go | package callosum
import (
"database/sql"
"fmt"
"log"
"sync"
_ "github.com/mattn/go-sqlite3" //sqllite DB driver import
)
//UserRow holds the data obtained from fetching a row from the `users` table.
type UserRow struct {
ID int64
ScreenName string
Description string
LastLookedAt ... | (userID int64, lastLookedAt, latestTweetID int64) {
chQueryArgs <- &queryArgs{"UPDATE users SET last_looked_at=?, latest_tweet_id=? where user_id=?", []interface{}{lastLookedAt, latestTweetID, userID}}
}
//MarkUserLatestFriendsCollected sets the `latest_following_id` to the latest id of the users given userID
//is fo... | MarkUserLatestTweetsCollected | identifier_name |
storage.go | package callosum
import (
"database/sql"
"fmt"
"log"
"sync"
_ "github.com/mattn/go-sqlite3" //sqllite DB driver import
)
//UserRow holds the data obtained from fetching a row from the `users` table.
type UserRow struct {
ID int64
ScreenName string
Description string
LastLookedAt ... |
//StoreUser inserts the Twitter user details into the `users` table.
func (s *Storage) StoreUser(userID int64, screenName, description string, protected bool, blob []byte) {
chQueryArgs <- &queryArgs{"INSERT OR IGNORE INTO users (user_id, screen_name, description, protected, blob) VALUES (?, ?, ?, ?, ?)",
[]interf... | {
_, err := s.db.Exec("INSERT OR IGNORE INTO screennames (screen_name) VALUES (?)", screenName)
if err != nil {
log.Fatal(err)
}
} | identifier_body |
equilibrium_computation.py | """
@version $Id: equilibrium_computation.py 2017-02-10 16:08 denis $
Module to compute the resting equilibrium point of a Virtual Epileptic Patient module
"""
import numpy
from scipy.optimize import root
from sympy import symbols, exp, solve, lambdify
from tvb_epilepsy.base.constants import X1_DEF, X1_EQ_CR_DEF, X0_... | jac_e_x1o = -numpy.dot(i_x0, K[:,iE]) * w[iE][:,ix0]
jac_x0_x0e = numpy.zeros((no_x0,no_e),dtype = type)
jac_x0_x1o = numpy.diag(4 + 3 * x[ix0] ** 2 + 4 * x[ix0] + K[ix0] * numpy.sum(w[ix0][:,ix0], axis=1)) \
- numpy.dot(i_x0, K[:, ix0]) * w[ix0][:, ix0]
jac = numpy.zeros((n_regions,n_... |
jac_e_x0e = numpy.diag(- 4 * rx0[iE]) | random_line_split |
equilibrium_computation.py | """
@version $Id: equilibrium_computation.py 2017-02-10 16:08 denis $
Module to compute the resting equilibrium point of a Virtual Epileptic Patient module
"""
import numpy
from scipy.optimize import root
from sympy import symbols, exp, solve, lambdify
from tvb_epilepsy.base.constants import X1_DEF, X1_EQ_CR_DEF, X0_... |
return x2eq, y2eq
# def pop2eq_calc(n_regions,x1eq,zeq,Iext2):
# shape = x1eq.shape
# type = x1eq.dtype
# #g_eq = 0.1*x1eq (1)
# #y2eq = 6*(x2eq+0.25)*x1eq (2)
# #-x2eq**3 + x2eq -y2eq+2*g_eq-0.3*(zeq-3.5)+Iext2 =0=> (1),(2)
# #-x2eq**3 + x2eq -6*(x2eq+0.25)*x1eq+2*0.1*x1eq-0.3*(zeq-3.5)+Iext2 ... | x2eq[0 ,i] = numpy.min(numpy.real(numpy.roots([-1.0, 0.0, 1.0, p0[0 ,i]]))) | conditional_block |
equilibrium_computation.py | """
@version $Id: equilibrium_computation.py 2017-02-10 16:08 denis $
Module to compute the resting equilibrium point of a Virtual Epileptic Patient module
"""
import numpy
from scipy.optimize import root
from sympy import symbols, exp, solve, lambdify
from tvb_epilepsy.base.constants import X1_DEF, X1_EQ_CR_DEF, X0_... | (X1_DEF, X1_EQ_CR_DEF, n_regions):
#The default initial condition for x1 equilibrium search
return numpy.repeat(numpy.array((X1_EQ_CR_DEF + X1_DEF) / 2.0), n_regions)
def x1_lin_def(X1_DEF, X1_EQ_CR_DEF, n_regions):
# The point of the linear Taylor expansion
return numpy.repeat(numpy.array((X1_EQ_CR_D... | x1eq_def | identifier_name |
equilibrium_computation.py | """
@version $Id: equilibrium_computation.py 2017-02-10 16:08 denis $
Module to compute the resting equilibrium point of a Virtual Epileptic Patient module
"""
import numpy
from scipy.optimize import root
from sympy import symbols, exp, solve, lambdify
from tvb_epilepsy.base.constants import X1_DEF, X1_EQ_CR_DEF, X0_... |
def zeq_6d_calc(x1eq, y0, Iext1):
return fx1_6d_calc(x1eq, z=0, y0=y0, Iext1=Iext1)
def y1eq_calc(x1eq, d=5.0):
return 1 - d * x1eq ** 2
def pop2eq_calc(x1eq, zeq, Iext2):
shape = x1eq.shape
type = x1eq.dtype
# g_eq = 0.1*x1eq (1)
# y2eq = 0 (2)
y2eq = numpy.zeros(shape, dtype=type)
... | return fx1_2d_calc(x1eq, z=0, y0=y0, Iext1=Iext1) | identifier_body |
hverse-encounter-helper.user.js | /* eslint-disable max-len */
// ==UserScript==
// @name HentaiVerse Encounter Unclicker
// @namespace PrincessRTFM
// @version 3.2.1
// @description Massively improves the useability/interface of the HentaiVerse random encounters system; tracks the time since the last event (and what it was), automatic... | news.first().prepend(eventPane);
}
else if (gallery.length) {
gallery.after(eventPane);
}
}
if (!eventPane
.find('a[href]')
.filter((i, e) => (e.href || '').toLowerCase().includes('hentaiverse.org'))
.length
) {
eventPane.append('<p><a href="https://hentaiverse.org/">Enter the HentaiVerse</a></p>... | const gallery = $('#nb');
if (news.length) { | random_line_split |
hverse-encounter-helper.user.js | /* eslint-disable max-len */
// ==UserScript==
// @name HentaiVerse Encounter Unclicker
// @namespace PrincessRTFM
// @version 3.2.1
// @description Massively improves the useability/interface of the HentaiVerse random encounters system; tracks the time since the last event (and what it was), automatic... | this);
for (let i = 0; i < 5; i++) {
s += bits.splice(Math.floor(Math.random() * bits.length), 1);
}
return s;
},
});
// SCRIPT CORE BEGINS \\
((window, $, moment) => {
// eslint-disable-next-line no-extend-native
Set.prototype.addAll = Set.prototype.addAll || function addAll(iterable) {
Array.from(iter... | from( | identifier_name |
hverse-encounter-helper.user.js | /* eslint-disable max-len */
// ==UserScript==
// @name HentaiVerse Encounter Unclicker
// @namespace PrincessRTFM
// @version 3.2.1
// @description Massively improves the useability/interface of the HentaiVerse random encounters system; tracks the time since the last event (and what it was), automatic... | LAST_EVENT_TIMESTAMP_KEY, 0) || Date.now().valueOf());
const expandTemplate = (tmpl, durationObj, eventKey) => {
const durationStr = durationObj.humanize();
return tmpl
.replace(/\$PERIOD\$/gu, durationStr)
.replace(
/\$PERIOD.SHORT\$/gu,
durationStr
.replace(/^a\s+few\s+/ui, "0 ")
.replace... | nt.js library').css('border-bottom', '2px dotted red');
return;
}
const lastEvent = () => moment(GM_getValue( | conditional_block |
hverse-encounter-helper.user.js | /* eslint-disable max-len */
// ==UserScript==
// @name HentaiVerse Encounter Unclicker
// @namespace PrincessRTFM
// @version 3.2.1
// @description Massively improves the useability/interface of the HentaiVerse random encounters system; tracks the time since the last event (and what it was), automatic... | moment) => {
// eslint-disable-next-line no-extend-native
Set.prototype.addAll = Set.prototype.addAll || function addAll(iterable) {
Array.from(iterable).forEach(e => this.add(e));
};
const genid = () => ([1e7] + 1e3 + 4e3 + 8e3 + 1e11)
.repeat(2)
.replace(
/[018]/gu,
c => (c ^ crypto.getRandomValues(n... | s);
for (let i = 0; i < 5; i++) {
s += bits.splice(Math.floor(Math.random() * bits.length), 1);
}
return s;
},
});
// SCRIPT CORE BEGINS \\
((window, $, | identifier_body |
experiment_types.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is ... | // Noted that at most one reward metric is allowed
// If more than one reward criterion is included, the first would be used while others would be omitted
// +optional
Criteria []Criterion `json:"criteria,omitempty"`
// TrafficControl provides instructions on traffic management for an experiment
// +optional
Tr... | // Criteria contains a list of Criterion for assessing the target service | random_line_split |
Blockchain.go | package BLC
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/boltdb/bolt"
"log"
"math/big"
"os"
"strconv"
)
type Blockchain struct {
Tip []byte // BlockHash of top Block
DB *bolt.DB // A pointer to the database
}
func CreateBlockchainWithGenesisBlock(address string, nodeID string) |
// Convert command variables to Transaction Objects
func (blockchain *Blockchain) hanldeTransations(from []string, to []string, amount []string, nodeId string) []*Transaction {
var txs []*Transaction
utxoSet := &UTXOSet{blockchain}
for i := 0; i < len(from); i++ {
amountInt, _ := strconv.Atoi(amount[i])
tx :=... | {
DBName := fmt.Sprintf(DBName, nodeID)
if DBExists(DBName) {
fmt.Println("Genesis block already exist!")
os.Exit(1)
}
fmt.Println("Creating genesis block....")
db, err := bolt.Open(DBName, 0600, nil)
if err != nil {
log.Panic(err)
}
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
b, err... | identifier_body |
Blockchain.go | package BLC
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/boltdb/bolt"
"log"
"math/big"
"os"
"strconv"
)
type Blockchain struct {
Tip []byte // BlockHash of top Block
DB *bolt.DB // A pointer to the database
}
func CreateBlockchainWithGenesisBlock(address string, nodeID string) {
DB... | fmt.Println("没找到对应交易")
} else {
//fmt.Println("preTxs___________________________________")
//fmt.Println(prevTxs)
}
//验证
return tx.VerifyTransaction(prevTxs)
//return true
}
func (bc *Blockchain) GetAllUTXOs() map[string]*UTXOArray {
iterator := bc.Iterator()
utxoMap := make(map[string]*UTXOArray)
//已花费... | if len(prevTxs) == 0 { | random_line_split |
Blockchain.go | package BLC
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/boltdb/bolt"
"log"
"math/big"
"os"
"strconv"
)
type Blockchain struct {
Tip []byte // BlockHash of top Block
DB *bolt.DB // A pointer to the database
}
func CreateBlockchainWithGenesisBlock(address string, nodeID string) {
DB... | ame := fmt.Sprintf(DBName, nodeID)
if DBExists(DBName) {
db, err := bolt.Open(DBName, 0600, nil)
if err != nil {
log.Panic(err)
}
defer db.Close()
var blockchain *Blockchain
err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(BlockBucketName))
if b != nil {
hash := b.Get([]byte("l"))... | *Blockchain {
DBN | conditional_block |
Blockchain.go | package BLC
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/boltdb/bolt"
"log"
"math/big"
"os"
"strconv"
)
type Blockchain struct {
Tip []byte // BlockHash of top Block
DB *bolt.DB // A pointer to the database
}
func CreateBlockchainWithGenesisBlock(address string, nodeID string) {
DB... | ).Cmp(bigInt) == 0 {
break
}
}
return blocksHashes
}
func (bc *Blockchain) GetBlockByHash(hash []byte) *Block {
var block Block
DBName := fmt.Sprintf(DBName, os.Getenv("NODE_ID"))
db, err := bolt.Open(DBName, 0600, nil)
if err != nil {
log.Panic(err)
}
defer db.Close()
err = db.View(func(tx *bolt.Tx) ... | .NewInt(0 | identifier_name |
channel.pb.go | // Copyright (c) 2018 NEC Laboratories Europe GmbH.
//
// Authors: Wenting Li <wenting.li@neclab.eu>
// Sergey Fedorov <sergey.fedorov@neclab.eu>
//
// 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... | }.Build()
File_channel_proto = out.File
file_channel_proto_rawDesc = nil
file_channel_proto_goTypes = nil
file_channel_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure t... | random_line_split | |
channel.pb.go | // Copyright (c) 2018 NEC Laboratories Europe GmbH.
//
// Authors: Wenting Li <wenting.li@neclab.eu>
// Sergey Fedorov <sergey.fedorov@neclab.eu>
//
// 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... |
type Channel_PeerChatServer interface {
Send(*Message) error
Recv() (*Message, error)
grpc.ServerStream
}
type channelPeerChatServer struct {
grpc.ServerStream
}
func (x *channelPeerChatServer) Send(m *Message) error {
return x.ServerStream.SendMsg(m)
}
func (x *channelPeerChatServer) Recv() (*Message, error)... | {
return srv.(ChannelServer).PeerChat(&channelPeerChatServer{stream})
} | identifier_body |
channel.pb.go | // Copyright (c) 2018 NEC Laboratories Europe GmbH.
//
// Authors: Wenting Li <wenting.li@neclab.eu>
// Sergey Fedorov <sergey.fedorov@neclab.eu>
//
// 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... |
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_channel_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_channel_proto_goTypes,
Depen... | {
file_channel_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Message); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
} | conditional_block |
channel.pb.go | // Copyright (c) 2018 NEC Laboratories Europe GmbH.
//
// Authors: Wenting Li <wenting.li@neclab.eu>
// Sergey Fedorov <sergey.fedorov@neclab.eu>
//
// 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... | () ([]byte, []int) {
return file_channel_proto_rawDescGZIP(), []int{0}
}
func (x *Message) GetPayload() []byte {
if x != nil {
return x.Payload
}
return nil
}
var File_channel_proto protoreflect.FileDescriptor
var file_channel_proto_rawDesc = []byte{
0x0a, 0x0d, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x2e,... | Descriptor | identifier_name |
ag.py | #!/bin/python3
import os
import re
import sys
import json
from pprint import pprint
from shorthand import *
from amyhead import *
#charset_namespace="[A-Za-z0-9_$]+" # in 'shorthand'
#parser_goal=re.compile('[ \t]*([0-9]+)[ \t](.+)')
token_item=r'([\n]|^)([ \t]*\~?[0-9]+|[ \t]*\~?include|[ \t]*\~?gonear)... | return rtv
'''
learn file
a learn file records ordered goals of the successful paths
probably
'''
def loadNextGoalFile(self,filename=None):
# return True on error
# else False
if isNone(filename): filename=self.filename
if isNone(filename) or os.path.isfile(filename)==False: return True
... | x.size()
for k,v in tmp.items(): rtv[k]+=v
| conditional_block |
ag.py | #!/bin/python3
import os
import re
import sys
import json
from pprint import pprint
from shorthand import *
from amyhead import *
#charset_namespace="[A-Za-z0-9_$]+" # in 'shorthand'
#parser_goal=re.compile('[ \t]*([0-9]+)[ \t](.+)')
token_item=r'([\n]|^)([ \t]*\~?[0-9]+|[ \t]*\~?include|[ \t]*\~?gonear)... | ef fromStr(self,s,cd='./',extView=None):
s=s.replace('\r','')
'''
\r\n , \n\r , \n -> \n
format: see self.fromTxt
'''
# unset filename
self.filename=None
self.extendedView=extView
#old=self.sets
p=self.__class__.parser_set
s=re.sub("(\n\r|\n|\r\n)[ \t]*(\n\r|\n|\r\n)","\n\n",s)
def... | rn [ k for k in self.sets if self.getSucc(k)=='-' ]
d | identifier_body |
ag.py | #!/bin/python3
import os
import re
import sys
import json
from pprint import pprint
from shorthand import *
from amyhead import *
#charset_namespace="[A-Za-z0-9_$]+" # in 'shorthand'
#parser_goal=re.compile('[ \t]*([0-9]+)[ \t](.+)')
token_item=r'([\n]|^)([ \t]*\~?[0-9]+|[ \t]*\~?include|[ \t]*\~?gonear)... | self.constraints=[] # [ (int(label),item,negate?) ... ]
self.maxLabel=-1
self.including=False
self.arrangeNeeded=False
self.extendedView=None # inherit from Goaltree
def __eq__(self,rhs):
self.arrange()
if isinstance(rhs,self.__class__):
return self.constraints==rhs.constraints
else:
ra... | random_line_split | |
ag.py | #!/bin/python3
import os
import re
import sys
import json
from pprint import pprint
from shorthand import *
from amyhead import *
#charset_namespace="[A-Za-z0-9_$]+" # in 'shorthand'
#parser_goal=re.compile('[ \t]*([0-9]+)[ \t](.+)')
token_item=r'([\n]|^)([ \t]*\~?[0-9]+|[ \t]*\~?include|[ \t]*\~?gonear)... | f,k):
return self.sets[k][2]
def getSuccsStr(self,k):
return self.sets[k][3][0]
def getPrecs(self,k):
return self.sets[k][4]
def getOpts(self,k):
rtv=dict(self.sets[k][5])
for i in rtv: rtv[i]=rtv[i][1]
return rtv
def getFinals(self):
return [ k for k in self.sets if self.getSucc(k)=='-' ]
... | uccs(sel | identifier_name |
daemon.go | /*
* Copyright 2020 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
if opt.Security.Cert == "" || opt.Security.Key == "" {
return nil, -1, errors.New("empty cert or key for tls")
}
// Create the TLS ClientOption with the CA pool and enable Client certificate validation
if opt.Security.TLSConfig == nil {
opt.Security.TLSConfig = &tls.Config{}
}
tlsConfig := opt.Security.TLS... | {
return ln, port, err
} | conditional_block |
daemon.go | /*
* Copyright 2020 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... |
func (cd *clientDaemon) ExportPeerHost() *scheduler.PeerHost {
return cd.schedPeerHost
}
| {
return cd.PeerTaskManager
} | identifier_body |
daemon.go | /*
* Copyright 2020 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | schedPeerHost: host,
Option: *opt,
RPCManager: rpcManager,
PeerTaskManager: peerTaskManager,
PieceManager: pieceManager,
ProxyManager: proxyManager,
UploadManager: uploadManager,
StorageManager: storageManager,
GCManager: gc.NewManager(opt.GCInterval.Duration),
}, nil
}
f... | once: &sync.Once{},
done: make(chan bool), | random_line_split |
daemon.go | /*
* Copyright 2020 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable la... | (opt config.SecurityOption) (credentials.TransportCredentials, error) {
// Load certificate of the CA who signed client's certificate
pemClientCA, err := ioutil.ReadFile(opt.CACert)
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pemClientCA) {
return nil, fmt... | loadGPRCTLSCredentials | identifier_name |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... |
struct SearchService;
impl NewService for SearchService {
type ReqBody = Body;
type ResBody = Body;
type Error = ServiceError;
type Service = SearchService;
type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>;
type InitError = ServiceError;
fn new_service(&self) -... | {
futures::future::ok(
Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET")
.header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type")
... | identifier_body |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... | (query: SearchPaginate, db: &Connection) -> FutureResult<Body, ServiceError> {
let text = &query.text;
let results = fetch_search_results(text.to_string(), query.page, db);
futures::future::ok(Body::from(
json!({
"meta": { "text": text, "page": query.page, "total": results.1 },
... | search_text | identifier_name |
main.rs | extern crate bible_reference_rs;
extern crate chrono;
extern crate futures;
extern crate hyper;
extern crate postgres;
extern crate serde;
extern crate url;
#[macro_use]
extern crate serde_json;
mod models;
use bible_reference_rs::*;
use futures::future::{Future, FutureResult};
use hyper::service::{NewService, Service... | .unwrap(),
)
}
struct SearchService;
impl NewService for SearchService {
type ReqBody = Body;
type ResBody = Body;
type Error = ServiceError;
type Service = SearchService;
type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>;
type InitError = ServiceError... | .header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET")
.header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type")
.body(body) | random_line_split |
domain_randomization.py | # Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... | def randomizer(self) -> DomainRandomizer:
# Forward to the wrapped DomainRandWrapper
return self._wrapped_env.randomizer
@randomizer.setter
def randomizer(self, dr: DomainRandomizer):
# Forward to the wrapped DomainRandWrapper
self._wrapped_env.randomizer = dr
def adapt... |
self.dp_mapping = dp_mapping
@property | random_line_split |
domain_randomization.py | # Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... |
return env
| env = remove_env(env, DomainRandWrapper) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.