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 |
|---|---|---|---|---|
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py | '''
输入数据->卷积层1->激活层1->池化层1->卷积层2->激活层2->池化层2->非线性全连接层1->非线性全连接层2->全连接层3->SoftMax->Optimizer
输入数据: 24 * 24 * 3 (cifar10的图片都是32*32*3的,需要处理成24*24*3)
卷积层1:5*5 卷积核个数为K1 步长为1,输出为24 * 24 * K1
激活层1:ReLU
池化层1:3*3 步长为2,输出为12 * 12 * K1
卷积层2:5*5 卷积核个数为K2 步长为1,12 * 12 * K2
激活层2:ReLU
池化层2:3*3 步长为2 输出为6 * 6 * K2
非线性全连接层1:神经元个数200(这一层... | labels_holder: label_batch})
correct_predicted += np.sum(predictions)
accuracy_score = correct_predicted / total_examples
print('--------->Accuracy on Test Examples: ', accuracy_score)
results_list.append(['Accuracy on Test Examples: ', accuracy_score])
... | labels_holder : label_batch})
batch_accuracy = np.sum(predictions) / batch_size
results_list.append([training_step, loss_value, training_step, batch_accuracy])
print("Training Step:... | conditional_block |
02.代码实现-06Tensorflow-01Cifar10-01基本网络.py | '''
输入数据->卷积层1->激活层1->池化层1->卷积层2->激活层2->池化层2->非线性全连接层1->非线性全连接层2->全连接层3->SoftMax->Optimizer
输入数据: 24 * 24 * 3 (cifar10的图片都是32*32*3的,需要处理成24*24*3)
卷积层1:5*5 卷积核个数为K1 步长为1,输出为24 * 24 * K1
激活层1:ReLU
池化层1:3*3 步长为2,输出为12 * 12 * K1
卷积层2:5*5 卷积核个数为K2 步长为1,12 * 12 * K2
激活层2:ReLU
池化层2:3*3 步长为2 输出为6 * 6 * K2
非线性全连接层1:神经元个数200(这一层... | l1_out = Pool2d(conv1_out, pool=tf.nn.max_pool, k=3, stride=2, padding='SAME')
with tf.name_scope('Conv2d_2'): # 卷积层2
weights = WeightsVariable(shape=[5, 5, conv1_kernel_num, conv2_kernel_num], name_str='weights', stddev=5e-2)
biases = BiasesVariable(shape=[conv2_kernel_num], name_str='biases', ini... | poo | identifier_name |
enel645_group11_final_project.py | #%% Import Libraries
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#%% Load and prepare the data
INPUT_DIR = '/home/ahmadreza.nazari/train/image/'
TARGET_DIR = '/home/ahmadreza.nazari/train/label/'
IMG_SIZE = (240, 320)
N_CHANNELS = 3
CLASSES = {
0: 'Ball',
1: 'Field',
... | (self):
return len(self.target_paths)
def __getitem__(self, idx):
'''Returns tuple (input, target) correspond to batch #idx.'''
i = idx
path = self.input_paths[i]
target_path = self.target_paths[i]
img = tf.keras.preprocessing.image.load_img(path, color_mode='rgb', ... | __len__ | identifier_name |
enel645_group11_final_project.py | #%% Import Libraries
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#%% Load and prepare the data
INPUT_DIR = '/home/ahmadreza.nazari/train/image/'
TARGET_DIR = '/home/ahmadreza.nazari/train/label/'
IMG_SIZE = (240, 320)
N_CHANNELS = 3
CLASSES = {
0: 'Ball',
1: 'Field',
... | train_gen = DataSequence(train_input_paths, train_target_paths)
val_gen = DataSequence(val_input_paths, val_target_paths)
test_gen = DataSequence(test_input_paths, test_target_paths)
print('simulation data train_samples', train_samples)
print('simulation data val_samples', val_samples)
print('simulation data test_samp... | val_samples:train_samples + val_samples + test_samples]
| random_line_split |
enel645_group11_final_project.py | #%% Import Libraries
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#%% Load and prepare the data
INPUT_DIR = '/home/ahmadreza.nazari/train/image/'
TARGET_DIR = '/home/ahmadreza.nazari/train/label/'
IMG_SIZE = (240, 320)
N_CHANNELS = 3
CLASSES = {
0: 'Ball',
1: 'Field',
... |
def jaccard_coef(y_true, y_pred, smooth=1):
intersection = tf.keras.backend.sum(
tf.keras.backend.abs(y_true * y_pred), axis=-1)
sum_ = tf.keras.backend.sum(tf.keras.backend.abs(
y_true) + tf.keras.backend.abs(y_pred), axis=-1)
jac = (intersection + smooth) / (sum_ - intersection + smooth... | inputs = tf.keras.backend.flatten(inputs)
targets = tf.keras.backend.flatten(targets)
BCE = tf.keras.backend.binary_crossentropy(targets, inputs)
BCE_EXP = tf.keras.backend.exp(-BCE)
focal_loss = tf.keras.backend.mean(
alpha * tf.keras.backend.pow((1-BCE_EXP), gamma) * BCE)
return focal_loss | identifier_body |
enel645_group11_final_project.py | #%% Import Libraries
import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#%% Load and prepare the data
INPUT_DIR = '/home/ahmadreza.nazari/train/image/'
TARGET_DIR = '/home/ahmadreza.nazari/train/label/'
IMG_SIZE = (240, 320)
N_CHANNELS = 3
CLASSES = {
0: 'Ball',
1: 'Field',
... |
mapping = {
(31, 120, 180): 0,
(106, 176, 25): 1,
(156, 62, 235): 2,
(255, 255, 255): 3,
(69, 144, 232): 4,
(227, 26, 28): 5,
}
class DataSequence(tf.keras.utils.Sequence):
'''Helper to iterate over the data as Numpy arrays.'''
def __init__(self, in_paths, out_paths, img_size=IMG_SI... | print(input_path, '|', target_path) | conditional_block |
supplyGoodsList.js | /**
* 供应商品列表
* * 此页面 要求传入参数
* supplierId 供货商Id
* @author: chengfy@songxiaocai.com
* @description:
* @Date: 17/3/30 14:53
*/
import React from 'react';
import {
View,
Image,
TouchableOpacity,
ScrollView,
Text,
TextInput,
LayoutAnimation,
InteractionManager,
ListView,
Refres... | DeleteClick(rowData,sectionID,rowID) {
this.changeState({
currentRow: {
rowData,
rowID,
sectionID
}
}, ()=> {
this._sxcmodal._toggle();
})
}
/**
* 查看商品详情信息按钮
* @param rowData
* @private
... | rowData 商品信息
* @private
*/
_btn | conditional_block |
supplyGoodsList.js | /**
* 供应商品列表
* * 此页面 要求传入参数
* supplierId 供货商Id
* @author: chengfy@songxiaocai.com
* @description:
* @Date: 17/3/30 14:53
*/
import React from 'react';
import {
View,
Image,
TouchableOpacity,
ScrollView,
Text,
TextInput,
LayoutAnimation,
InteractionManager,
ListView,
Refres... | e={{textAlign: 'center'}}>提醒</SText>
</View>
<SText style={{ textAlign: 'center', marginTop: 20, marginLeft: 30, marginRight: 30,marginBottom:20}} fontSize="title" color="333">确认删除商品?</SText>
<Row>
<TouchableOpacity onPress={()=>this.props.sxcmodal._to... | lignItems:'center'}}>
<SText fontSize="headline" color="fff" styl | identifier_body |
supplyGoodsList.js | /**
* 供应商品列表
* * 此页面 要求传入参数
* supplierId 供货商Id
* @author: chengfy@songxiaocai.com
* @description:
* @Date: 17/3/30 14:53
*/
import React from 'react';
import {
View,
Image,
TouchableOpacity,
ScrollView,
Text,
TextInput,
LayoutAnimation,
InteractionManager,
ListView,
Refres... | name}</SText>
<SText fontSize="caption" color="orange" style={{marginLeft:3}}>{rowData.value}</SText>
</View>
)
}
/**
* 商品属性 展开隐藏事件
* @param rowData
* @private
*/
_itemSpreadClick(rowData) {
if (rowData.spread) {
rowData.spread=fa... | lor="999">{rowData. | identifier_name |
supplyGoodsList.js | /**
* 供应商品列表
* * 此页面 要求传入参数
* supplierId 供货商Id
* @author: chengfy@songxiaocai.com
* @description:
* @Date: 17/3/30 14:53
*/
import React from 'react';
import {
View,
Image,
TouchableOpacity,
ScrollView,
Text,
TextInput,
LayoutAnimation,
InteractionManager,
ListView,
Refres... | </TouchableOpacity>
{
// <TouchableOpacity onPress={()=>this._btnDetailsClick(rowData)} style={[s.itemButton,{marginLeft:15}]}>
// <SText fontSize="body" color="666" style={{color:"#2296f3"}} >详情</SText>
... | <SText fontSize="caption" color="333" style={s.text_right} >{rowData.currentPriceDes}</SText>
</View>
<View style={{flexDirection:'row',justifyContent:'flex-end',height:60,backgroundColor:'#fafafa',alignItems:'center',paddingRight:15}}>
<TouchableO... | random_line_split |
api_op_RecognizeUtterance.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package lexruntimev2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smith... |
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resol... | {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
} | conditional_block |
api_op_RecognizeUtterance.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package lexruntimev2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smith... | (ctx context.Context, params *RecognizeUtteranceInput, optFns ...func(*Options)) (*RecognizeUtteranceOutput, error) {
if params == nil {
params = &RecognizeUtteranceInput{}
}
result, metadata, err := c.invokeOperation(ctx, "RecognizeUtterance", params, optFns, c.addOperationRecognizeUtteranceMiddlewares)
if err ... | RecognizeUtterance | identifier_name |
api_op_RecognizeUtterance.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package lexruntimev2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smith... | // - Failed message - The failed message is returned if the Lambda function
// throws an exception or if the Lambda function returns a failed intent state
// without a message.
// - Timeout message - If you don't configure a timeout message and a timeout,
// and the Lambda function doesn't return within... | random_line_split | |
api_op_RecognizeUtterance.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package lexruntimev2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smith... |
func addRecognizeUtteranceResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opRecognizeUtteranceResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: op... | {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint re... | identifier_body |
admin.py | import operator
import re
from functools import reduce
import django
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.core.checks import Error
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db.models import Q
from django.forms.formset... |
else:
return []
def save_model(self, request, obj, form, change):
try:
if change:
version = request.POST.get(f'{concurrency_param_name}_{obj.pk}', None)
if version:
core._set_version(obj, version)
super().save_... | return request._concurrency_list_editable_errors | conditional_block |
admin.py | import operator
import re
from functools import reduce
import django
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.core.checks import Error
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db.models import Q
from django.forms.formset... |
def _get_concurrency_fields(self):
v = []
for pk, version in self._versions:
v.append(f'<input type="hidden" name="{concurrency_param_name}_{pk}" value="{version}">')
return mark_safe("".join(v))
def render(self, template_name=None, context=None, renderer=None):
ou... | self._versions = kwargs.pop('versions', [])
super().__init__(*args, **kwargs) | identifier_body |
admin.py | import operator
import re
from functools import reduce
import django
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.core.checks import Error
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db.models import Q
from django.forms.formset... | if hasattr(request, '_concurrency_list_editable_errors'):
return request._concurrency_list_editable_errors
else:
return []
def save_model(self, request, obj, form, change):
try:
if change:
version = request.POST.get(f'{concurrency_param_na... |
def _get_conflicts(self, request): | random_line_split |
admin.py | import operator
import re
from functools import reduce
import django
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.core.checks import Error
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db.models import Q
from django.forms.formset... | (self, request, queryset): # noqa
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and... | response_action | identifier_name |
soldev.datatable.js | /**
* THIS FILE CONTAINS SHARED FUNCTIONS RELATED TO DATATABLE
*/
$.fn.initDataTable = function(properties){
//add filter list if filterid is not null
if(typeof(properties.filterid)!=='undefined' && properties.filterid != null && properties.filterid.length != 0){
/* prepare wrapper for filters */
... | wrapper.append(
'<div class="filter_content_buttons">' +
'<button type="button" class="btn btn-primary btn-apply">Apply</button>' +
'</div>'
)
}
$.fn.removeFilter = function(){
var id = this.attr('id');
$('.add_filter_content .select_' + id).rem... | //add buttons | random_line_split |
soldev.datatable.js | /**
* THIS FILE CONTAINS SHARED FUNCTIONS RELATED TO DATATABLE
*/
$.fn.initDataTable = function(properties){
//add filter list if filterid is not null
if(typeof(properties.filterid)!=='undefined' && properties.filterid != null && properties.filterid.length != 0){
/* prepare wrapper for filters */
... |
else if(properties.select == 'multi'){
selectProperties.style ='multi';
}
}else selectProperties.style = 'os';
selectProperties.info = false;
dtTblProperties.select = selectProperties;
if(typeof(properties.destroy)!=='undefinded' && properties.destroy != null && properties.destroy.l... | {
selectProperties.style = 'single';
} | conditional_block |
main.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
var MAX_RESOURCE_QUANTITY = 30000; // UPDATE THIS <<<<<<<<<<<<<<<
... |
// Keyboard events
$window.keydown(event => {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
sen... | {
userList = users[0];
$('#users').empty();
for(user in userList) { console.log(user);
if(userList[user].username == username) {
var row = '';
row += '<tr class="leaderboard-user-row"><td></td>';
row += '<td>'+userList[user].age+'</td>';
row += ... | identifier_body |
main.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
var MAX_RESOURCE_QUANTITY = 30000; // UPDATE THIS <<<<<<<<<<<<<<<
... |
for(user in userList) {
if(myEmpire.aspects['diplomacy'].quantity >= userList[user].territory)
{
$('.treaty').show();
showUserActions = true;
}
else
$('.treaty').hide();
}
if(myEmpire.aspects['army'].quantity > 0 ||
myEmpire.aspects['science'].quantity > 0 ||
... | {
$('.tradedeal').hide();
} | conditional_block |
main.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
var MAX_RESOURCE_QUANTITY = 30000; // UPDATE THIS <<<<<<<<<<<<<<<
... |
var userList = {};
var silentMode = false;
var quietMode = false;
var blockList = [];
// ------------ //
// private info //
// ------------ //
function MyAspect(name, shortening, level, quantity, maxsize) {
this.name = name;
this.shortening = shortening;
this.level = level;
this.quant... | var $currentInput = $usernameInput.focus();
var socket = io(); | random_line_split |
main.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
var MAX_RESOURCE_QUANTITY = 30000; // UPDATE THIS <<<<<<<<<<<<<<<
... | (name,primary,secondary,primaryText,secondaryText)
{
str = '<span class="float" id="lvlup_'+name+'"><i class="fas fa-angle-double-up"></i></span>'+
'<span class="float_bottom" id="upgrade_'+name+'"><i class="fas fa-plus"></i></span>'+
'<div id="action_div1" class="'+name+'_div">' +
... | addActionDiv | identifier_name |
main.py | import requests
from bs4 import BeautifulSoup
from PIL import Image
import csv
import html_text
import webbrowser
#region zmienne globalne:
page = requests.get(
"https://codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/"
)
soup = BeautifulSoup(page.content, "html.parser")
#endregion
... |
def example7():
# Create top_items as empty list
all_products = []
# Extract and store in top_items according to instructions on the left
products = soup.select('div.thumbnail')
for product in products:
name = product.select('h4 > a')[0].text.strip()
description = product.sel... | n top_items according to instructions on the left
links = soup.select("a")
print("Liczba linków = ", len(links))
for ahref in links:
text = ahref.text
text = text.strip() if text is not None else ""
href = ahref.get("href")
href = href.strip() if href is not None else ""
... | identifier_body |
main.py | import requests
from bs4 import BeautifulSoup
from PIL import Image
import csv
import html_text
import webbrowser
#region zmienne globalne:
page = requests.get(
"https://codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/"
)
soup = BeautifulSoup(page.content, "html.parser")
#endregion
... | ():
# Create all_h1_tags as empty list
all_h1_tags = []
# Set all_h1_tags to all h1 tags of the soup
for element in soup.select("h1"):
all_h1_tags.append(element.text)
# Create seventh_p_text and set it to 7th p element text of the page
seventh_p_text = soup.select("p")[6].text
all... | example4 | identifier_name |
main.py | import requests
from bs4 import BeautifulSoup
from PIL import Image
import csv
import html_text
import webbrowser
#region zmienne globalne:
page = requests.get(
"https://codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/"
)
soup = BeautifulSoup(page.content, "html.parser")
#endregion
... | nu:\n1.przykła z zajęć\n2.Wyświetl tytuły produktów\n3.Znajdź produkt po tytule")
wybor = input("twój wybór:")
if wybor == "1":
print(top_items)
elif wybor == "2":
print("sprawdźmy jakie produkty są: ")
licznik = 0
while licznik<len(top_items):
print(top_items[lic... | elect("h4 > a.title")[0].text
review_label = elem.select("div.ratings")[0].text
info = {"title": title.strip(), "review": review_label.strip()}
top_items.append(info)
print("me | conditional_block |
main.py | import requests
from bs4 import BeautifulSoup
from PIL import Image
import csv
import html_text
import webbrowser
#region zmienne globalne:
page = requests.get(
"https://codedamn-classrooms.github.io/webscraper-python-codedamn-classroom-website/"
)
soup = BeautifulSoup(page.content, "html.parser")
#endregion
... | page_head = soup.head
print("Typ = ", type(page_head))
first_p = soup.select("p")[0].text
print("First p =\n", first_p)
another_p = soup.select("p")[1].text
print("Another p =\n", another_p)
print("Liczba zanaczników 'p' = ", len(soup.select("p")))
# title
print("TITLE")
pri... | # soup = BeautifulSoup(page.content, "html.parser")
soup = BeautifulSoup(html_doc, "lxml")
# Extract head of page | random_line_split |
upimg.js |
const db = wx.cloud.database();//初始化数据库
Page({
/**
* 页面的初始数据
*/
data: {
imgsrctest:"../../images/upimg/update.png",
foodname:"",
inputvaule:"",
imgData: [],
details:"",
maxNumber:15,//可输入最大字数
number: 0,//已输入字数
chosen: '',
imgs: [],
//当前选中数组的下标值pro... | 当前显示数据的索引的重新赋值
})
}
},
getfoodname(event) { //监听获取菜名
var _this=this;
console.log("菜名:", event.detail.value)
this.setData({
inputvaule: event.detail.value
})
},
uploadPhoto(e) { // 拍摄或从相册选取上传
let that = this;
var tempFilePaths
wx.c... | {
show2:true,
store:that.data.proCityArr[1][that.data.proCityIndex[1]],
canteennum:e.detail.value.picker[0]+1,
talknum:0,
cainum:0,
isaudit:false,
img_name:that.data.inputvaule,
img_src: 'ht... | identifier_body |
upimg.js |
const db = wx.cloud.database();//初始化数据库
Page({
/**
* 页面的初始数据
*/
data: {
imgsrctest:"../../images/upimg/update.png",
foodname:"",
inputvaule:"",
imgData: [],
details:"",
maxNumber:15,//可输入最大字数
number: 0,//已输入字数
chosen: '',
imgs: [],
//当前选中数组的下标值pro... | identifier_name | ||
upimg.js |
const db = wx.cloud.database();//初始化数据库
Page({
/**
* 页面的初始数据
*/
data: {
imgsrctest:"../../images/upimg/update.png",
foodname:"",
inputvaule:"",
imgData: [],
details:"",
maxNumber:15,//可输入最大字数
number: 0,//已输入字数
chosen: '',
imgs: [],
//当前选中数组的下标值pro... | proCityIndex //当前显示数据的索引的重新赋值
})
}
},
getfoodname(event) { //监听获取菜名
var _this=this;
console.log("菜名:", event.detail.value)
this.setData({
inputvaule: event.detail.value
})
},
uploadPhoto(e) { // 拍摄或从相册选取上传
let that = this;
var tempFileP... | 新赋值
})
}else{//第二列选中项数据被滑动修改了...
proCityIndex[1] = index;
this.setData({
[`proCityIndex`]: | conditional_block |
upimg.js | const db = wx.cloud.database();//初始化数据库
Page({
/**
* 页面的初始数据
*/
data: {
imgsrctest:"../../images/upimg/update.png",
foodname:"",
inputvaule:"",
imgData: [],
details:"",
maxNumber:15,//可输入最大字数
number: 0,//已输入字数
chosen: '',
imgs: [],
//当前选中数组的下标值proC... | )
{
console.log('form发生了submit事件,携带数据为:', e.detail.value)
console.log('form发生了submit事件,食堂序号为:', e.detail.value.picker[0])
console.log('form发生了submit事件,店名为:',this.data.proCityArr[1][this.data.proCityIndex[1]])
console.log('form发生了submit事件,提交数据:菜名:',this.data.inputvaule,"介绍:",this.da... | this.data.inputvaule!=''&&
this.data.details!='' | random_line_split |
train.py | import numpy as np
import configparser
from local.data_loader import load_speech_file_by_extension
from local.utils import benchmark, select_channels, squeeze_audio_to_float64
import argparse
import logging
import sys
import os
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from... |
cs[f], p = spearmanr(x_train[:, f], np.mean(y_train, axis=1))
select = np.argsort(np.abs(cs))[np.max([-nb_feats, -len(cs)]):]
return select
@benchmark
def train_estimators(estimators, x_train, y_train):
for mel_bin in range(len(estimators)):
estimators[mel_bin].fit(x_train, y_train[:, me... | cs[f] = 0
continue | conditional_block |
train.py | import numpy as np
import configparser
from local.data_loader import load_speech_file_by_extension
from local.utils import benchmark, select_channels, squeeze_audio_to_float64
import argparse
import logging
import sys
import os
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from... | # instead of 0.0016 as with the audio, resulting in 4 more frames. Cutting off in the
# beginning aligns the audio to the current frame.
# Quantize the logMel spectrogram
medians, borders, q_spectrogram = quantization(y_train, nb_intervals=9)
# F... | logger.info('No bad channels specified.')
x_train, y_train = compute_features(eeg, sfreq_eeg, audio, sfreq_audio)
y_train = y_train[20:-4] # Skip 24 samples too align the neural signals to the audio. 20 frames are needed to
# first to have all context for one sample. In a... | random_line_split |
train.py | import numpy as np
import configparser
from local.data_loader import load_speech_file_by_extension
from local.utils import benchmark, select_channels, squeeze_audio_to_float64
import argparse
import logging
import sys
import os
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from... | (y_train, nb_intervals=8):
"""
Quantize the logMel spectrogram
"""
medians, borders = compute_borders_logistic(y_train, nb_intervals=nb_intervals)
q_spectrogram = quantize_spectrogram(y_train, borders)
# print if a spec bin does not contain samples for a interval
for i in range(q_spectrogra... | quantization | identifier_name |
train.py | import numpy as np
import configparser
from local.data_loader import load_speech_file_by_extension
from local.utils import benchmark, select_channels, squeeze_audio_to_float64
import argparse
import logging
import sys
import os
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from... |
def train(eeg, audio, sfreq_eeg, sfreq_audio, bad_channels, nb_mel_bins=40):
# exclude bad channels
if len(bad_channels) > 0:
logger.info('EEG original shape: {} x {}'.format(*eeg.shape))
mask = np.ones(eeg.shape[1], bool)
mask[bad_channels] = False
eeg = eeg[:, mask]
... | x_train = herff2016_b(eeg, sfreq_eeg, 0.05, 0.01)
# resample audio to 16kHz
audio = decimate(audio, 3)
audio_sr = 16000
y_train = compute_spectrogram(audio, audio_sr, 0.016, 0.01)
return x_train, y_train | identifier_body |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... | (instructions: &[Instruction]) -> Program {
// we'll emit something that respects x86_64 system-v:
// rdi (1st parameter): pointer to cell array
// rsi (2nd parameter): pointer to output function
// rdx (3rd parameter): pointer to WriteWrapper
// rcx (4th parameter): pointer to input function
//... | transform | identifier_name |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... |
pub fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,... | {
unsafe { slice::from_raw_parts(self.program.contents, self.program.size) }
} | identifier_body |
mod.rs | /// Toy x86_64 JIT
use libc;
use std::alloc::{alloc, dealloc, Layout};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::c_void;
use std::io::{Read, Write};
use std::mem::transmute;
use std::ptr::write_bytes;
use std::slice;
mod x86;
use crate::ir::Instruction;
const PAGE_SIZE: usize = 4096;
... | unsafe { slice::from_raw_parts_mut(self.program.contents, self.program.size) }
}
pub fn lock(self) -> Program {
unsafe {
libc::mprotect(
self.program.contents as *mut libc::c_void,
self.program.size,
libc::PROT_NONE,
);
... | }
pub fn as_mut_slice(&mut self) -> &mut [u8] { | random_line_split |
csv_orders_with_feedback.py | # -*- coding: utf-8 -*-
"""
@author : MG
@Time : 2017/11/18
@author : MG
@desc : 监控csv文件(每15秒)
对比当前日期与回测csv文件中最新记录是否匹配,存在最新交易请求,生成交易请求(order*.csv文件)
追踪tick级行情实时成交(仅适合小资金)
追踪tick级行情本金买入点 * N % 止损
目前仅支持做多,不支持做空
每15秒进行一次文件检查
文件格式(csv xls),每个symbol一行,不可重复,例:卖出eth 买入eos, 不考虑套利的情况(套利需要单独开发其他策略)
显示如下(非文件格式,csv文件以‘,’为... | # 获取文件列表
file_name_list = os.listdir(self._folder_path)
if file_name_list is None or len(file_name_list) == 0:
# self.logger.info('No file')
return
# 读取所有 csv 文件
for file_name in file_name_list:
# 仅处理 order*.csv文件
if PATTERN_FEEDBAC... | random_line_split | |
csv_orders_with_feedback.py | # -*- coding: utf-8 -*-
"""
@author : MG
@Time : 2017/11/18
@author : MG
@desc : 监控csv文件(每15秒)
对比当前日期与回测csv文件中最新记录是否匹配,存在最新交易请求,生成交易请求(order*.csv文件)
追踪tick级行情实时成交(仅适合小资金)
追踪tick级行情本金买入点 * N % 止损
目前仅支持做多,不支持做空
每15秒进行一次文件检查
文件格式(csv xls),每个symbol一行,不可重复,例:卖出eth 买入eos, 不考虑套利的情况(套利需要单独开发其他策略)
显示如下(非文件格式,csv文件以‘,’为... | if not target_position.has_stop_loss:
self.do_order(md_dic, symbol, target_position.position, target_position.price,
target_position.direction, target_position.stop_loss_price, msg='当前无持仓')
else:
# 如果当前有持仓,执行两类动作:
# 1)若... | n_dic:
logging.debug("持仓数据中没有包含当前合约,最近一次成交回报时间:%s,跳过",
self.datetime_last_rtn_trade_dic[symbol])
self.get_position(symbol, force_refresh=True)
return
if self.datetime_last_rtn_trade_dic[symbol] > self.datetime_last_update_position... | identifier_body |
csv_orders_with_feedback.py | # -*- coding: utf-8 -*-
"""
@author : MG
@Time : 2017/11/18
@author : MG
@desc : 监控csv文件(每15秒)
对比当前日期与回测csv文件中最新记录是否匹配,存在最新交易请求,生成交易请求(order*.csv文件)
追踪tick级行情实时成交(仅适合小资金)
追踪tick级行情本金买入点 * N % 止损
目前仅支持做多,不支持做空
每15秒进行一次文件检查
文件格式(csv xls),每个symbol一行,不可重复,例:卖出eth 买入eos, 不考虑套利的情况(套利需要单独开发其他策略)
显示如下(非文件格式,csv文件以‘,’为... | hold_vol
def check_stop_loss(self, close):
"""
根据当前价格计算是否已经到达止损点位
如果此前已经到达过止损点位则不再比较,也不需重置状态
:param close:
:return:
"""
# 如果此前已经到达过止损点位则不再比较,也不需重置状态
if self.stop_loss_price is None or self.has_stop_loss:
return
self.has_stop_loss =... | ol = gap_thres | identifier_name |
csv_orders_with_feedback.py | # -*- coding: utf-8 -*-
"""
@author : MG
@Time : 2017/11/18
@author : MG
@desc : 监控csv文件(每15秒)
对比当前日期与回测csv文件中最新记录是否匹配,存在最新交易请求,生成交易请求(order*.csv文件)
追踪tick级行情实时成交(仅适合小资金)
追踪tick级行情本金买入点 * N % 止损
目前仅支持做多,不支持做空
每15秒进行一次文件检查
文件格式(csv xls),每个symbol一行,不可重复,例:卖出eth 买入eos, 不考虑套利的情况(套利需要单独开发其他策略)
显示如下(非文件格式,csv文件以‘,’为... | _position, symbol, target_price, \
# stop_loss_price, has_stop_loss, gap_threshold_vol = self.get_target_position(symbol)
if not target_position.has_stop_loss:
self.do_order(md_dic, symbol, target_position.position, target_position.price,
... | return
with self._mutex:
target_position = self.symbol_target_position_dic[symbol]
target_position.check_stop_loss(close_cur)
# self.logger.debug("当前持仓目标:%r", target_position)
# 撤销所有相关订单
self.cancel_order(symbol)
# 计算目标仓位方向及交易数量
... | conditional_block |
types.go | package binlog
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strconv"
"strings"
"time"
)
// ColumnType used in TableMapEvent and RowsEvent.
type ColumnType uint8
// ColumnType Constants
//
// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-... |
func fractionalSecondsNegative(meta uint16, r *reader) (int, error) {
n := (meta + 1) / 2
v := int(bigEndian(r.bytesInternal(int(n))))
if v != 0 {
bits := int(n * 8)
v = ^v & mask(bits)
v = (v & unsetSignMask(bits)) + 1
}
return v * int(math.Pow(100, float64(3-n))), r.err
}
func mask(bits int) int {
retu... | {
n := (meta + 1) / 2
v := bigEndian(r.bytesInternal(int(n)))
return int(v * uint64(math.Pow(100, float64(3-n)))), r.err
} | identifier_body |
types.go | package binlog
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strconv"
"strings"
"time"
)
// ColumnType used in TableMapEvent and RowsEvent.
type ColumnType uint8
// ColumnType Constants
//
// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-... | (precision int, scale int) int {
integral := precision - scale
uncompIntegral := integral / digitsPerInteger
uncompFractional := scale / digitsPerInteger
compIntegral := integral - (uncompIntegral * digitsPerInteger)
compFractional := scale - (uncompFractional * digitsPerInteger)
return uncompIntegral*4 + compre... | decimalSize | identifier_name |
types.go | package binlog
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strconv"
"strings"
"time"
)
// ColumnType used in TableMapEvent and RowsEvent.
type ColumnType uint8
// ColumnType Constants
//
// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-... |
return []byte(s.String()), nil
}
// A Decimal represents a MySQL Decimal/Numeric literal.
//
// https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html
type Decimal string
func (d Decimal) String() string { return string(d) }
// Float64 returns the number as a float64.
func (d Decimal) Float64() (float64, e... | {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(s.Members())
return buf.Bytes(), err
} | conditional_block |
types.go | package binlog
import (
"bytes"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strconv"
"strings"
"time"
)
// ColumnType used in TableMapEvent and RowsEvent.
type ColumnType uint8
// ColumnType Constants
//
// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-... | func (d Decimal) BigFloat() (*big.Float, error) {
f, _, err := new(big.Float).Parse(string(d), 0)
return f, err
}
func (d Decimal) MarshalJSON() ([]byte, error) {
return []byte(d), nil
}
// Json represents value of TypeJSON
//
// https://dev.mysql.com/doc/refman/8.0/en/json.html
type JSON struct{ Val interface{} }... |
// BigFloat returns the number as a *big.Float. | random_line_split |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... | return
}
if args.Term > rf.CurrentTerm {
rf.VotedFor = -1
rf.CurrentTerm = args.Term
rf.identity = FOLLOWER
}
if rf.VotedFor != -1 && rf.VotedFor != args.CandidateId {
reply.VoteGranted = false
return
}
var rfLogIndex int
var rfLogTerm int
if len(rf.Log) > 0 {
rfLogIndex = rf.Log[len(rf.Log)-1].... | if args.Term < rf.CurrentTerm {
reply.VoteGranted = false | random_line_split |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... | (snapshot []byte, index int) {
rf.mu.Lock()
defer rf.mu.Unlock()
rf.lastIncludedIndex = index
rf.lastIncludedTerm = rf.Log[index-rf.Log[0].Index].Term
w := new(bytes.Buffer)
e := gob.NewEncoder(w)
e.Encode(rf.lastIncludedIndex)
e.Encode(rf.lastIncludedTerm)
data := w.Bytes()
data = append(data, snapshot...)
... | TakeSnapshot | identifier_name |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... |
func (rf *Raft) RaftStateSize() int {
return rf.persister.RaftStateSize()
}
//
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here.
... | {
return rf.CurrentTerm, rf.identity == LEADER
} | identifier_body |
raft.go | package raft
//
// this is an outline of the API that raft must expose to
// the service (or tester). see comments below for
// each of these functions for more details.
//
// rf = Make(...)
// create a new Raft server.
// rf.Start(command interface{}) (index, term, isleader)
// start agreement on a new log entry
... |
rf.mu.Unlock()
}
}
func (rf *Raft) TakeSnapshot(snapshot []byte, index int) {
rf.mu.Lock()
defer rf.mu.Unlock()
rf.lastIncludedIndex = index
rf.lastIncludedTerm = rf.Log[index-rf.Log[0].Index].Term
w := new(bytes.Buffer)
e := gob.NewEncoder(w)
e.Encode(rf.lastIncludedIndex)
e.Encode(rf.lastIncludedTerm)
d... | {
//fmt.Println("peer", rf.me, "apply entry", i)
//fmt.Println("peer", rf.me, "'s commitIndex:", rf.CommitIndex)
rf.lastApplied = i
var args ApplyMsg
args.Index = i
//if rf.IsLeader() {
// fmt.Println("Leader")
//}
//fmt.Println(rf.Log)
//fmt.Println("i:", i)
//fmt.Println("rf.Log[0].I... | conditional_block |
kinematics.py | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Francesco Mannella <francesco.mannella@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, includi... | (self, distance) :
'''
get a point in the 2D space given a
distance from the first point of the chain
'''
if distance > 1 :
raise ValueError('distance must be a proportion of the polyline length (0,1)')
distance = sum(self.seg_lens)*distance
cum_ln... | get_point | identifier_name |
kinematics.py | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Francesco Mannella <francesco.mannella@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, includi... |
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
# ARM --------------------... | '''
return: the length of the current polyline
'''
return sum(self.seg_lens) | identifier_body |
kinematics.py | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Francesco Mannella <francesco.mannella@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, includi... | """
number_of_joint: (int) number of joints
joint_angles (list): initial joint angles
joint_lims (list): joint angles limits
segment_lengths (list): length of arm segmens
origin (list): origin coords of arm
"""
... | mirror = False
): | random_line_split |
kinematics.py | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Francesco Mannella <francesco.mannella@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, includi... |
# calculate x coords of arm edges.
# the x-axis position of each edge is the
# sum of its projection on the x-axis
# and all the projections of the
# previous edges
x = np.array([
sum([
self.segment_lengths[k] *
... | res_joint_angles = -res_joint_angles
res_joint_angles[0] += np.pi | conditional_block |
modeltranslator.go | // Copyright (c) 2020 The Jaeger 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 law or agree... |
return dbmodel.KeyValue{
Key: tracetranslator.TagError,
Value: "true",
Type: dbmodel.BoolType,
}, true
}
func getTagFromStatusMsg(statusMsg string) (dbmodel.KeyValue, bool) {
if statusMsg == "" {
return dbmodel.KeyValue{}, false
}
return dbmodel.KeyValue{
Key: tracetranslator.TagStatusMsg,
Value... | {
return dbmodel.KeyValue{}, false
} | conditional_block |
modeltranslator.go | // Copyright (c) 2020 The Jaeger 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 law or agree... |
// ConvertSpans converts spans from OTEL model to Jaeger Elasticsearch model
func (c *Translator) ConvertSpans(traces pdata.Traces) ([]*dbmodel.Span, error) {
rss := traces.ResourceSpans()
if rss.Len() == 0 {
return nil, nil
}
dbSpans := make([]*dbmodel.Span, 0, traces.SpanCount())
for i := 0; i < rss.Len(); i... | {
tagsKeysAsFieldsMap := map[string]bool{}
for _, v := range tagsKeysAsFields {
tagsKeysAsFieldsMap[v] = true
}
return &Translator{
allTagsAsFields: allTagsAsFields,
tagKeysAsFields: tagsKeysAsFieldsMap,
tagDotReplacement: tagDotReplacement,
}
} | identifier_body |
modeltranslator.go | // Copyright (c) 2020 The Jaeger 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 law or agree... | return tag
}
func attributeValueToInterface(attr pdata.AttributeValue) interface{} {
switch attr.Type() {
case pdata.AttributeValueSTRING:
return attr.StringVal()
case pdata.AttributeValueBOOL:
return attr.BoolVal()
case pdata.AttributeValueINT:
return attr.IntVal()
case pdata.AttributeValueDOUBLE:
retur... | tag.Value = strconv.FormatInt(attr.IntVal(), 10)
case pdata.AttributeValueDOUBLE:
tag.Type = dbmodel.Float64Type
tag.Value = strconv.FormatFloat(attr.DoubleVal(), 'g', 10, 64)
} | random_line_split |
modeltranslator.go | // Copyright (c) 2020 The Jaeger 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 law or agree... | (events pdata.SpanEventSlice) []dbmodel.Log {
if events.Len() == 0 {
return emptyLogList
}
logs := make([]dbmodel.Log, 0, events.Len())
for i := 0; i < events.Len(); i++ {
event := events.At(i)
if event.IsNil() {
continue
}
var fields []dbmodel.KeyValue
if event.Attributes().Len() > 0 {
fields = m... | logs | identifier_name |
bosh_exporter.go | package main
import (
"errors"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/cloudfoundry/bosh-cli/director"
"github.com/cloudfoundry/bosh-cli/uaa"
"github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-utils/system"
"github.com/prometheus/client_golang/prometheus"
"github.com/prom... | }
uaaConfig, err := uaa.NewConfigFromURL(uaaURLStr)
if err != nil {
return nil, err
}
uaaConfig.CACert = boshCACert
if *boshUAAClientID != "" && *boshUAAClientSecret != "" {
uaaConfig.Client = *boshUAAClientID
uaaConfig.ClientSecret = *boshUAAClientSecret
} else {
uaaConfig.Client = "bosh_c... | random_line_split | |
bosh_exporter.go | package main
import (
"errors"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/cloudfoundry/bosh-cli/director"
"github.com/cloudfoundry/bosh-cli/uaa"
"github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-utils/system"
"github.com/prometheus/client_golang/prometheus"
"github.com/prom... |
logger := logger.NewLogger(logLevel)
directorConfig, err := director.NewConfigFromURL(*boshURL)
if err != nil {
return nil, err
}
boshCACert, err := readCACert(*boshCACertFile, logger)
if err != nil {
return nil, err
}
directorConfig.CACert = boshCACert
anonymousDirector, err := director.NewFactory(lo... | {
return nil, err
} | conditional_block |
bosh_exporter.go | package main
import (
"errors"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/cloudfoundry/bosh-cli/director"
"github.com/cloudfoundry/bosh-cli/uaa"
"github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-utils/system"
"github.com/prometheus/client_golang/prometheus"
"github.com/prom... | (CACertFile string, logger logger.Logger) (string, error) {
if CACertFile != "" {
fs := system.NewOsFileSystem(logger)
CACertFileFullPath, err := fs.ExpandPath(CACertFile)
if err != nil {
return "", err
}
CACert, err := fs.ReadFileString(CACertFileFullPath)
if err != nil {
return "", err
}
ret... | readCACert | identifier_name |
bosh_exporter.go | package main
import (
"errors"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/cloudfoundry/bosh-cli/director"
"github.com/cloudfoundry/bosh-cli/uaa"
"github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-utils/system"
"github.com/prometheus/client_golang/prometheus"
"github.com/prom... | {
flag.Parse()
overrideFlagsWithEnvVars()
if *showVersion {
fmt.Fprintln(os.Stdout, version.Print("bosh_exporter"))
os.Exit(0)
}
log.Infoln("Starting bosh_exporter", version.Info())
log.Infoln("Build context", version.BuildContext())
boshClient, err := buildBOSHClient()
if err != nil {
log.Errorf("Erro... | identifier_body | |
main.py | import numpy as np
import copy
Gammes= [ [1,2,3],
[2,1,3],
[1,2,3]
]
S = [ [1,2,3],
[2,1,3],
[1,2,3]
]#s est une solution. On a une machine sur chaque ligne
N =3 #nb de pièces
M = 3 #nb dem
#numero_noeuds = 1 + (n -1)*m + n
INF = float('inf')
#conventions
print("quand d... | ,1,3],[1,2,3]]
def AUPLUTARD(s,afficher_commentaires=False,sommet_fin=len(GRAPHE(S))-1):
sommet_fin = len(GRAPHE(s))-1
solution = s
return AuPlusTard(Gammes,solution,sommet_fin, afficher_commentaires)
def auplustard(i,j,G=GRAPHE(S),solution = S,sommet_fin=len(GRAPHE(S))-1):
liste_plc = AUPLUTA... | seurs(Graphe,v)
auplustard[v] = min([ auplustard[w] - t(Graphe, v,w) for w in N_plus])
return auplustard
Gammes= [ [1,2,3],[2 | conditional_block |
main.py | import numpy as np
import copy
Gammes= [ [1,2,3],
[2,1,3],
[1,2,3]
]
S = [ [1,2,3],
[2,1,3],
[1,2,3]
]#s est une solution. On a une machine sur chaque ligne
N =3 #nb de pièces
M = 3 #nb dem
#numero_noeuds = 1 + (n -1)*m + n
INF = float('inf')
#conventions
print("quand d... | fficher_commentaires=False):
#j'initialise le graphe et j'ajoute les arcs, verts, rouge et noirs
graphe = fct_Matrice_Adjacence(gamme,afficher_commentaires)
#je m'assure que la solution et la gamme sont deux matrices
if 2+ len(s)*len(s[0]) != len(graphe):
print("erreur: le nombre de ligne d... | = 2 + len(Gammes)*len(Gammes[0])
taille_matrice = nb_noeuds
A = np.full((taille_matrice,taille_matrice),NOLINK)
#la même pièce i passe par des machines j: arcs noirs
for i in range(len(Gammes)):
for j in range (len(Gammes[0])-1): #on parcours les machines sauf la dernière
pièce ... | identifier_body |
main.py | import numpy as np
import copy
Gammes= [ [1,2,3],
[2,1,3],
[1,2,3]
]
S = [ [1,2,3],
[2,1,3],
[1,2,3]
]#s est une solution. On a une machine sur chaque ligne
N =3 #nb de pièces
M = 3 #nb dem
#numero_noeuds = 1 + (n -1)*m + n
INF = float('inf')
#conventions
print("quand d... | :
#j'initialise le graphe et j'ajoute les arcs, verts, rouge et noirs
graphe = fct_Matrice_Adjacence(gamme,afficher_commentaires)
#je m'assure que la solution et la gamme sont deux matrices
if 2+ len(s)*len(s[0]) != len(graphe):
print("erreur: le nombre de ligne de la gamme doit être égal a... | False) | identifier_name |
main.py | import numpy as np
import copy
Gammes= [ [1,2,3],
[2,1,3],
[1,2,3]
]
S = [ [1,2,3],
[2,1,3],
[1,2,3]
]#s est une solution. On a une machine sur chaque ligne
N =3 #nb de pièces
M = 3 #nb dem
#numero_noeuds = 1 + (n -1)*m + n
INF = float('inf')
#conventions
print("quand d... | liste_plc = PLC(G,sommet_depart=0)
indice_piece = i-1; indice_machine= j-1
indice_pièceETmachine = trouver_indice_couple(indice_piece,indice_machine,len(S[0]),len(S))
return liste_plc[indice_pièceETmachine]
print("plc(2,1)= ", plc(2,1))
print("fin question 2", end = "\n\n\n\n\n")
Gammes= [ [1,2,3],[2... | random_line_split | |
file_system.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... |
Ok(stat)
}
pub fn did_create_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_entries {
self.entries.lock().insert(Arc::as_ptr(entry) as usize, entry.clone());
}
}
pub fn will_destroy_dir_entry(&self, entry: &DirEntryHandle) {
if self.permanent_... | {
stat.f_frsize = stat.f_bsize as i64;
} | conditional_block |
file_system.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... | /// Returns `ENOSYS` if the `FileSystemOps` don't implement `stat`.
pub fn statfs(&self) -> Result<statfs, Errno> {
let mut stat = self.ops.statfs(self)?;
if stat.f_frsize == 0 {
stat.f_frsize = stat.f_bsize as i64;
}
Ok(stat)
}
pub fn did_create_dir_entry(&s... | ///
/// Each `FileSystemOps` impl is expected to override this to return the specific statfs for
/// the filesystem.
/// | random_line_split |
file_system.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... | (&self) -> &DirEntryHandle {
self.root.get().unwrap()
}
/// Get or create an FsNode for this file system.
///
/// If inode_num is Some, then this function checks the node cache to
/// determine whether this node is already open. If so, the function
/// returns the existing FsNode. If no... | root | identifier_name |
file_system.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use once_cell::sync::OnceCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std:... |
fn new_internal(
kernel: &Kernel,
ops: impl FileSystemOps,
permanent_entries: bool,
) -> FileSystemHandle {
Arc::new(FileSystem {
root: OnceCell::new(),
next_inode: AtomicU64::new(1),
ops: Box::new(ops),
dev_id: kernel.device_regi... | {
if root.inode_num == 0 {
root.inode_num = self.next_inode_num();
}
root.set_fs(self);
let root_node = Arc::new(root);
self.nodes.lock().insert(root_node.inode_num, Arc::downgrade(&root_node));
let root = DirEntry::new(root_node, None, FsString::new());
... | identifier_body |
agent.go | package agent
import (
"fmt"
"sync"
"time"
"github.com/toni-moreno/snmpcollector/pkg/agent/bus"
"github.com/toni-moreno/snmpcollector/pkg/agent/device"
"github.com/toni-moreno/snmpcollector/pkg/agent/output"
"github.com/toni-moreno/snmpcollector/pkg/agent/selfmon"
"github.com/toni-moreno/snmpcollector/pkg/con... | log.Infof("Device %s finished", cfg.ID)
// If device goroutine has finished, leave the bus so it won't get blocked trying
// to send messages to a not running device.
dev.LeaveBus(Bus)
}()
mutex.Unlock()
}
// LoadConf loads the DB conf and initializes the device metric config.
func LoadConf() {
MainConfig.D... | defer gatherWg.Done()
dev.StartGather() | random_line_split |
agent.go | package agent
import (
"fmt"
"sync"
"time"
"github.com/toni-moreno/snmpcollector/pkg/agent/bus"
"github.com/toni-moreno/snmpcollector/pkg/agent/device"
"github.com/toni-moreno/snmpcollector/pkg/agent/output"
"github.com/toni-moreno/snmpcollector/pkg/agent/selfmon"
"github.com/toni-moreno/snmpcollector/pkg/con... |
// End stops all devices polling.
func End() (time.Duration, error) {
start := time.Now()
log.Infof("END: begin device Gather processes stop... at %s", start.String())
// Stop all device processes and its measurements. Once finished they will be removed
// from the bus and node closed (snmp connections for measur... | {
LoadConf()
DeviceProcessStart()
} | identifier_body |
agent.go | package agent
import (
"fmt"
"sync"
"time"
"github.com/toni-moreno/snmpcollector/pkg/agent/bus"
"github.com/toni-moreno/snmpcollector/pkg/agent/device"
"github.com/toni-moreno/snmpcollector/pkg/agent/output"
"github.com/toni-moreno/snmpcollector/pkg/agent/selfmon"
"github.com/toni-moreno/snmpcollector/pkg/con... | else {
log.Printf("SELFMON disabled %+v\n", MainConfig.Selfmon)
}
}
// IsDeviceInRuntime checks if device `id` exists in the runtime array.
func IsDeviceInRuntime(id string) bool {
mutex.Lock()
defer mutex.Unlock()
if _, ok := devices[id]; ok {
return true
}
return false
}
// DeleteDeviceInRuntime removes ... | {
if val, ok := idb["default"]; ok {
// only executed if a "default" influxdb exist
val.Init()
val.StartSender(&senderWg)
selfmonProc.Init()
selfmonProc.SetOutDB(idb)
selfmonProc.SetOutput(val)
log.Printf("SELFMON enabled %+v", MainConfig.Selfmon)
// Begin the statistic reporting
selfmonP... | conditional_block |
agent.go | package agent
import (
"fmt"
"sync"
"time"
"github.com/toni-moreno/snmpcollector/pkg/agent/bus"
"github.com/toni-moreno/snmpcollector/pkg/agent/device"
"github.com/toni-moreno/snmpcollector/pkg/agent/output"
"github.com/toni-moreno/snmpcollector/pkg/agent/selfmon"
"github.com/toni-moreno/snmpcollector/pkg/con... | () bool {
reloadMutex.Lock()
defer reloadMutex.Unlock()
retval := reloadProcess
reloadProcess = true
return retval
}
// CheckAndUnSetReloadProcess unsets the reloadProcess flag.
// Returns its previous value.
func CheckAndUnSetReloadProcess() bool {
reloadMutex.Lock()
defer reloadMutex.Unlock()
retval := reloa... | CheckAndSetReloadProcess | identifier_name |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
}
impl<T, const CAPACITY: usize> MruArena<T, CAPACITY> {
// TODO(https://github.com/kaist-cp/rv6/issues/371): unsafe...
pub const fn new(entries: [MruEntry<T>; CAPACITY]) -> Self {
Self {
entries,
list: unsafe { List::new() },
}
}
pub fn init(self: Pin<&mut Sel... | {
(list_entry as *const _ as usize - Self::LIST_ENTRY_OFFSET) as *const Self
} | identifier_body |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
}
}
empty.map(|cell_raw| {
// SAFETY: `cell` is not referenced or borrowed. Also, it is already pinned.
let mut cell = unsafe { Pin::new_unchecked(&mut *cell_raw) };
n(cell.as_mut().get_pin_mut().unwrap().get_mut());
cell.borrow()
})
... | {
return Some(r);
} | conditional_block |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... | <F: FnOnce(&mut Self::Data)>(&self, f: F) -> Option<Rc<Self>> {
let inner = self.alloc_handle(f)?;
// SAFETY: `inner` was allocated from `self`.
Some(unsafe { Rc::from_unchecked(self, inner) })
}
/// Duplicate a given handle, and increase the reference count.
///
/// # Safety
... | alloc | identifier_name |
arena.rs | use core::convert::TryFrom;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref;
use core::pin::Pin;
use pin_project::pin_project;
use crate::list::*;
use crate::lock::{Spinlock, SpinlockGuard};
use crate::pinned_array::IterPinMut;
use crate::rc_cell::{RcCell, Ref, RefMut};
/// A homogeneous memory allocator, ... |
impl<T> MruEntry<T> {
// TODO(https://github.com/kaist-cp/rv6/issues/369)
// A workarond for https://github.com/Gilnaa/memoffset/issues/49.
// Assumes `list_entry` is located at the beginning of `MruEntry`
// and `data` is located at `mem::size_of::<ListEntry>()`.
const DATA_OFFSET: usize = mem::si... | {
guard.reacquire_after(f)
}
} | random_line_split |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... |
}
// The following should be removed, once we have all of the devices captured using the above
let default_devices = ["/dev/cu.usbserial", // MacOS X (presumably)
"/dev/cu.SLAB_USBtoUART", // MacOS X (Aeotech Z-Stick S2)
"/dev/cu.u... | {
error!("[OpenzwaveStateful] {:04x}:{:04x} {}",
info.vid,
info.pid,
port.device.display());
} | conditional_block |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... | (handle: &Handle, cfg: &Config) -> Result<(ZWave, Receiver<Notification<Item>>)> {
let cfg = cfg.clone();
let mut manager = {
let config_path = match cfg.sys_config {
Some(ref path) => path.as_ref(),
None => "/etc/openzwave",
};
let u... | new | identifier_name |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... |
}
impl Binding for ZWave {
type Config = Config;
type Error = Error;
type Item = Item;
fn new(handle: &Handle, cfg: &Self::Config) -> Result<(Self, Receiver<Notification<Item>>)> {
ZWave::new(handle, cfg)
}
fn get_value(&self, name: &str) -> Option<Item> {
always_lock(self.it... | {
always_lock(self.ozw_manager.lock())
} | identifier_body |
driver.rs | use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::fs;
use catt_core::util::always_lock;
use catt_core::binding::Binding;
use catt_core::binding::Notification;
use catt_core::value::Value;
use catt_core::item::Item as CItem;
use openzwave as ozw;
use openzwave::manager::Manager;
use openzw... | debug!("unknown controller state: {}",
zwave_notification.get_event().unwrap());
return;
}
};
match state {
ControllerState::Completed => {
let ... | Some(s) => s,
None => { | random_line_split |
array-virtual-repeat-strategy.ts | import { ICollectionObserverSplice, mergeSplice } from 'aurelia-binding';
import { ArrayRepeatStrategy, createFullOverrideContext } from 'aurelia-templating-resources';
import { IView, IVirtualRepeatStrategy, VirtualizationCalculation, IScrollerInfo, IVirtualRepeater, IViewSlot } from './interfaces';
import {
Math$ab... | (repeat: IVirtualRepeater, startIndex: number): void {
const views = (repeat.viewSlot as IViewSlot).children;
const viewLength = views.length;
const collection = repeat.items as any[];
const delta = Math$floor(repeat.topBufferHeight / repeat.itemHeight);
let collectionIndex = 0;
let view: IView... | updateAllViews | identifier_name |
array-virtual-repeat-strategy.ts | import { ICollectionObserverSplice, mergeSplice } from 'aurelia-binding';
import { ArrayRepeatStrategy, createFullOverrideContext } from 'aurelia-templating-resources';
import { IView, IVirtualRepeatStrategy, VirtualizationCalculation, IScrollerInfo, IVirtualRepeater, IViewSlot } from './interfaces';
import {
Math$ab... | }
const top_buffer_item_count_after_scroll_adjustment = first_index_after_scroll_adjustment;
const bot_buffer_item_count_after_scroll_adjustment = Math$max(0, newArraySize - top_buffer_item_count_after_scroll_adjustment - newViewCount);
repeat.$first = first_index_after_scroll_adjustment;
// repeat.... | random_line_split | |
array-virtual-repeat-strategy.ts | import { ICollectionObserverSplice, mergeSplice } from 'aurelia-binding';
import { ArrayRepeatStrategy, createFullOverrideContext } from 'aurelia-templating-resources';
import { IView, IVirtualRepeatStrategy, VirtualizationCalculation, IScrollerInfo, IVirtualRepeater, IViewSlot } from './interfaces';
import {
Math$ab... |
const top_buffer_item_count_after_scroll_adjustment = first_index_after_scroll_adjustment;
const bot_buffer_item_count_after_scroll_adjustment = Math$max(0, newArraySize - top_buffer_item_count_after_scroll_adjustment - newViewCount);
repeat.$first = first_index_after_scroll_adjustment;
// repeat._prev... | {
first_index_after_scroll_adjustment = Math$max(0, newArraySize - newViewCount);
} | conditional_block |
array-virtual-repeat-strategy.ts | import { ICollectionObserverSplice, mergeSplice } from 'aurelia-binding';
import { ArrayRepeatStrategy, createFullOverrideContext } from 'aurelia-templating-resources';
import { IView, IVirtualRepeatStrategy, VirtualizationCalculation, IScrollerInfo, IVirtualRepeater, IViewSlot } from './interfaces';
import {
Math$ab... |
initCalculation(repeat: IVirtualRepeater, items: any[]): VirtualizationCalculation {
const itemCount = items.length;
// when there is no item, bails immediately
// and return false to notify calculation finished unsuccessfully
if (!(itemCount > 0)) {
return VirtualizationCalculation.reset;
... | {
return items.length;
} | identifier_body |
fit_sed.py | """
John F. Wu
==========
Fitting infrared SEDs
Assume that the measured fluxes will be given in one of three ways:
(1) array-like with rows of [observed_wavelength, flux, flux_err]
(2) array-like with rows of ["Telescope filter", flux, flux_err]
(3) a valid filename that points to a space-delimited catalog with row... | observed wavelengths in microns
f_nu : 1d array
observed flux density in mJy
"""
waves, L_nu = read_K15_template(template)
# observed wavelengths
waves *= (1 + z)
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
D_L = cosmo.luminosity_distance(z)
# flux density [m... |
Returns
-------
waves : 1d array | random_line_split |
fit_sed.py | """
John F. Wu
==========
Fitting infrared SEDs
Assume that the measured fluxes will be given in one of three ways:
(1) array-like with rows of [observed_wavelength, flux, flux_err]
(2) array-like with rows of ["Telescope filter", flux, flux_err]
(3) a valid filename that points to a space-delimited catalog with row... |
else:
sys.exit('Incorrect PACS filter entered.')
elif 'spire' in telescope_filter:
pass
else:
sys.exit('"{}"" is not supported.'.format(telescope_filter))
clean_measurements[i, 0] = float(observed_wavelength)
t... | observed_wavelength = 160 | conditional_block |
fit_sed.py | """
John F. Wu
==========
Fitting infrared SEDs
Assume that the measured fluxes will be given in one of three ways:
(1) array-like with rows of [observed_wavelength, flux, flux_err]
(2) array-like with rows of ["Telescope filter", flux, flux_err]
(3) a valid filename that points to a space-delimited catalog with row... | (template):
"""Reads in a K15 template SED, returning an array of
wavelength and corresponding array of specific luminosity."""
template_fname = os.path.join(root_dir, 'data', 'kirkpatrick+15',
'Comprehensive_library', '{}.txt'.format(template))
if not os.path.isfile(template_fname)... | read_K15_template | identifier_name |
fit_sed.py | """
John F. Wu
==========
Fitting infrared SEDs
Assume that the measured fluxes will be given in one of three ways:
(1) array-like with rows of [observed_wavelength, flux, flux_err]
(2) array-like with rows of ["Telescope filter", flux, flux_err]
(3) a valid filename that points to a space-delimited catalog with row... |
def calculate_uncertainties(norm, modeled_fluxes, measured_fluxes,
measured_uncertainties, nsteps=500, nwalkers=100, nburnin=50,
nthreads=4, save_samples=False, plot_distribution=False):
"""Uses MCMC sampling to estimate uncertainties on the one parameter,
the normalization, which scales the uncerta... | assert template in K15_SED_templates
# get and unpack redshifted wavelengths and SED
waves, f_nu = model_sed(template, z)
# unpack measurements and then model what they should be
measured_waves, measured_fluxes, measured_uncertainties = measurements.T
modeled_fluxes = np.array([model_photometry(w... | identifier_body |
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use... |
pub unsafe fn get_executable_description(exe: &Path) -> Result<String, ()> {
let exe_utf16 = exe.to_str().unwrap().to_utf16_null();
let mut handle: DWORD = 0;
let size = GetFileVersionInfoSizeW(exe_utf16.as_ptr(), &mut handle);
if size == 0 {
error!("GetFileVersionInfoSizeW, err={}, exe={}", ... | {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if process == null_mut() {
return Err(Error::new("OpenProcess").into());
};
let _close_process = close_handle(process);
let mut name = [0u16; 32 * 1024];
let length = GetModuleFileNameExW(process, null_mut(), na... | identifier_body |
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute}; |
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use ntapi::ntrtl::RTL_USER_PROCESS_PARAMETERS;
use winapi::shared::guiddef::GUID;
use winapi::shared::minwindef::{BOOL, DWORD, FALSE, LPARAM, TRUE};
u... | use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut}; | random_line_split |
utils.rs | use std::ffi::{c_void, CStr};
use std::mem::{MaybeUninit, size_of_val, transmute};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use itertools::Itertools;
use log::error;
use ntapi::ntpebteb::PEB;
use ntapi::ntpsapi::{NtQueryInformationProcess, PROCESS_BASIC_INFORMATION, ProcessBasicInformation};
use... | (_config: &Config, mut pid: u32)
-> wrapperrs::Result<RequesterInfo> {
let mut process_stack = Vec::new();
while pid != 0 {
let window = find_primary_window(pid);
process_stack.push((pid, window));
pid = get_parent_pid(pid);
}
let main_process = process_stack.iter()
... | collect_requester_info | identifier_name |
mod.rs | /// cbindgen:ignore
mod communication;
/// cbindgen:ignore
mod endpoints;
pub mod error;
/// cbindgen:ignore
mod logging;
/// cbindgen:ignore
mod setup;
#[cfg(test)]
mod tests;
use crate::common::*;
use error::*;
use mio::net::UdpSocket;
/// The interface between the user's application and a communication session,
/... | }
// One of two endpoints for a control channel with a connector on either end.
// The underlying transport is TCP, so we use an inbox buffer to allow
// discrete payload receipt.
struct NetEndpoint {
inbox: Vec<u8>,
stream: TcpStream,
}
// Datastructure used during the setup phase representing a NetEndpoint ... | Equivalent,
New(Predicate),
Nonexistant, | random_line_split |
mod.rs | /// cbindgen:ignore
mod communication;
/// cbindgen:ignore
mod endpoints;
pub mod error;
/// cbindgen:ignore
mod logging;
/// cbindgen:ignore
mod setup;
#[cfg(test)]
mod tests;
use crate::common::*;
use error::*;
use mio::net::UdpSocket;
/// The interface between the user's application and a communication session,
/... |
}
// No errors! Time to modify `cu`
// create a new component and identifier
let Connector { phased, unphased: cu } = self;
let new_cid = cu.ips.id_manager.new_component_id();
cu.proto_components.insert(new_cid, cu.proto_description.new_component(module_name, identifier,... | {
return Err(Ace::WrongPortPolarity { port, expected_polarity });
} | conditional_block |
mod.rs | /// cbindgen:ignore
mod communication;
/// cbindgen:ignore
mod endpoints;
pub mod error;
/// cbindgen:ignore
mod logging;
/// cbindgen:ignore
mod setup;
#[cfg(test)]
mod tests;
use crate::common::*;
use error::*;
use mio::net::UdpSocket;
/// The interface between the user's application and a communication session,
/... | (&self, f: &mut Formatter) -> std::fmt::Result {
let (a, b) = self.id_parts();
write!(f, "v{}_{}", a, b)
}
}
impl SpecVal {
const FIRING: Self = SpecVal(1);
const SILENT: Self = SpecVal(0);
fn is_firing(self) -> bool {
self == Self::FIRING
// all else treated as SILENT
... | fmt | identifier_name |
mod.rs | /// cbindgen:ignore
mod communication;
/// cbindgen:ignore
mod endpoints;
pub mod error;
/// cbindgen:ignore
mod logging;
/// cbindgen:ignore
mod setup;
#[cfg(test)]
mod tests;
use crate::common::*;
use error::*;
use mio::net::UdpSocket;
/// The interface between the user's application and a communication session,
/... |
fn new_spec_var_stream(&self) -> SpecVarStream {
// Spec var stream starts where the current port_id stream ends, with gap of SKIP_N.
// This gap is entirely unnecessary (i.e. 0 is fine)
// It's purpose is only to make SpecVars easier to spot in logs.
// E.g. spot the spec var: { v0... | {
Self {
connector_id,
port_suffix_stream: Default::default(),
component_suffix_stream: Default::default(),
}
} | identifier_body |
zkdevice.py | '''
This script will do auto-check in/out for ZMM100 fingerprint access control
device by ZKSoftware.
At my office, the manager uses an application to load data from the
fingerprint device. After he loads data, log in device's database is cleared.
So in my case, I write this script to automate checking in/out everyday... |
add_log(uid, date, 'in')
add_log(uid, date, 'out')
def main():
today = '{:%d/%m/%Y}'.format(datetime.date.today())
parser = argparse.ArgumentParser()
parser.add_argument('action', help='`get`, `checkin`, `checkout`, '
'`add` or `fix` logs', default='get')... | delete_log(log[0]) | conditional_block |
zkdevice.py | '''
This script will do auto-check in/out for ZMM100 fingerprint access control
device by ZKSoftware.
At my office, the manager uses an application to load data from the
fingerprint device. After he loads data, log in device's database is cleared.
So in my case, I write this script to automate checking in/out everyday... | for uid in uids:
if args.action == 'get':
logs = get_logs(uid, start, end)
for log in logs:
print_log(*log)
elif args.action == 'checkin':
add_logs(uid, start, end, 'in', late=args.late)
elif args.action == 'checkout':
add_logs(... | start, end = args.range.split('-')
transfer_file(DEVICE_IP, server_ip, DB_PATH, cmd='ftpput')
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.