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 |
|---|---|---|---|---|
kmp.py | import numpy as np
import sys
import os
import matplotlib.pyplot as plt
import copy
import math
np.set_printoptions(threshold=sys.maxsize, linewidth=np.inf)
class ReferenceTrajectoryPoint:
def __init__(self, t=None, mu=None, sigma=None):
self.t = t
self.mu = mu
self.sigma = sigma
class GM... |
if(len(via_pt)==2): #The assumption here is that 1st and last point are always start and end point
if via_pt_ind==0 or via_pt_ind==len(via_pts)-1:
via_pt = np.append(np.array(via_pt), self.ref_traj[replace_ind].mu[2:4])
else:
d = distB... | min_dist = dist
# print("min_dist: ", min_dist)
replace_ind = i | conditional_block |
kmp.py | import numpy as np
import sys
import os
import matplotlib.pyplot as plt
import copy
import math
np.set_printoptions(threshold=sys.maxsize, linewidth=np.inf)
class ReferenceTrajectoryPoint:
def __init__(self, t=None, mu=None, sigma=None):
self.t = t
self.mu = mu
self.sigma = sigma
class GM... |
#######################################################################################################################
class KMP: #Assumptions: Input is only time; All dofs of output are continuous TODO: Generalize
def __init__(self, input_dofs, robot_dofs, demo_dt, ndemos, data_address):
self.input_dof... | L = np.zeros((self.num_states,data.shape[1]))
for i in range(self.num_states):
L[i,:] = self.priors[i]*gaussPDF(data,self.mu[:,i],self.sigma[i,:,:])
L_axis0_sum = np.sum(L,axis=0)
gamma = np.divide(L, np.repeat(L_axis0_sum.reshape(1,L_axis0_sum.shape[0]), self.num_states, axis=0))
... | identifier_body |
kmp.py | import numpy as np
import sys
import os
import matplotlib.pyplot as plt
import copy
import math
np.set_printoptions(threshold=sys.maxsize, linewidth=np.inf)
class ReferenceTrajectoryPoint:
def __init__(self, t=None, mu=None, sigma=None):
self.t = t
self.mu = mu
self.sigma = sigma
class GM... | plt.show() | plt.title('KMP generalization over new via points') | random_line_split |
kmp.py | import numpy as np
import sys
import os
import matplotlib.pyplot as plt
import copy
import math
np.set_printoptions(threshold=sys.maxsize, linewidth=np.inf)
class ReferenceTrajectoryPoint:
def __init__(self, t=None, mu=None, sigma=None):
self.t = t
self.mu = mu
self.sigma = sigma
class GM... | : #Assumptions: Input is only time; All dofs of output are continuous TODO: Generalize
def __init__(self, input_dofs, robot_dofs, demo_dt, ndemos, data_address):
self.input_dofs = input_dofs
self.robot_dofs = robot_dofs
self.ndemos = ndemos
self.demo_dt = demo_dt
self.norm_d... | KMP | identifier_name |
main_model.py | import torch
import torchvision
import torchvision.models as models
import numpy as np
import torch.optim as optim
import time
import torch.nn.functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import cv2
from torch.utils.data import Dataset, Sampler, DataLoader
import os
import PIL.Image... |
prob = self.product/self.sum_
prob[prob < 0] = 0
idx = choice(self.num_levels, p = prob)
self.product[idx] = self.product[idx] - self.weight_vector[idx]
self.sum_ = self.sum_ - self.weight_vector[idx]
idx2 = choice(len(self.samples[idx]))
ret2 = self.samples[idx]... | raise StopIteration | conditional_block |
main_model.py | import torch
import torchvision
import torchvision.models as models
import numpy as np
import torch.optim as optim
import time
import torch.nn.functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import cv2
from torch.utils.data import Dataset, Sampler, DataLoader
import os
import PIL.Image... |
def __len__(self):
return len(os.listdir(self.array_dir))*self.num_sketch_levels
def __getitem__(self, sampler):
idx = next(sampler)
sketch_fp = os.path.join(self.sketch_dir, idx[0], idx[1])
fname = os.path.splitext(idx[1])[0]
array_fp = os.path.join(self.array_dir, fn... | self.sketch_dir = sketch_dir
self.array_dir = array_dir
self.num_sketch_levels = len(os.listdir(sketch_dir)) | identifier_body |
main_model.py | import torch
import torchvision
import torchvision.models as models
import numpy as np
import torch.optim as optim
import time
import torch.nn.functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import cv2
from torch.utils.data import Dataset, Sampler, DataLoader
import os
import PIL.Image... | (model, dataloader, j = 0):
"""
test model, output different loss for each category
"""
model.float()
model.to(device)
model.eval()
criterion = nn.MSELoss()
val_loss = 0
num_batches = 0
variances = np.array(0)
for i, data in enumerate(dataloader):
num_batches += 1
... | test | identifier_name |
main_model.py | import torch
import torchvision
import torchvision.models as models
import numpy as np
import torch.optim as optim
import time
import torch.nn.functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import cv2
from torch.utils.data import Dataset, Sampler, DataLoader
import os
import PIL.Image... | self.fc1 = nn.Linear(128 * 6 * 6, 1028)
# self.fc2 = nn.Linear
def forward(self, x):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = self.relu(self.conv3(x))
x = self.pool1(x)
x = x.view(16 , -1)
x = self.relu(self.fc1(x))
... | random_line_split | |
row.component.ts | import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpUtilService} from '@service/http-util.service';
import {environment} from '@env/environment';
import {urls} from '@model/url';
import {NzModalRef, NzModalService, NzNotificationSe... | pattern: false,
}
},
{
name: '列表/视图', eName: 'tableName', type: 'text', validateCon: '请输入列表/视图', require: true,
validators: {
require: true,
pattern: false,
}
},
{
name: '列表字段', eName: 'colEname', type: 'text', validateCon: '请输入列表字段', require: true,
... | name: '列名称', eName: 'colCname', type: 'text', validateCon: '请输入列名称', require: true,
validators: {
require: true, | random_line_split |
row.component.ts | import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpUtilService} from '@service/http-util.service';
import {environment} from '@env/environment';
import {urls} from '@model/url';
import {NzModalRef, NzModalService, NzNotificationSe... | xport`;
this.http.post(url, this.searchData, {responseType: 'blob'}).subscribe(
res => {
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
let objectUrl = URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = objectUrl;
a.target = '_blan... | a.length = data.length || this.pageSize; //最好有
this.searchData = data;
this.listLoading = true;
this.getListSearch(data);
}
btnClick(data: any): void {
switch (data.type.buttonId) {
case 'Export': { //导出
this.btnExport();
}
break;
}
}
/**
* 导出按钮
*/
btnEx... | identifier_body |
row.component.ts | import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpUtilService} from '@service/http-util.service';
import {environment} from '@env/environment';
import {urls} from '@model/url';
import {NzModalRef, NzModalService, NzNotificationSe... | isConsignee))},
{label: '承运人', value: 'isCarrier',checked: Boolean(Number(data.data[0].isCarrier))}
];
this.modalValidateForm.get('userType').setValue(checkOptions);
}
// 删除
btnDelete(data: any): void {
if (data.data.length < 1) {
this.tplModal = this.nm.warning({
nzTitle: '提示信息',... | .data[0]. | identifier_name |
row.component.ts | import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpUtilService} from '@service/http-util.service';
import {environment} from '@env/environment';
import {urls} from '@model/url';
import {NzModalRef, NzModalService, NzNotificationSe... | ironment.baseUrl}column/selectColumnList`;
params.data = data;
this.httpUtilService.request(params).then(
(res: any) => {
this.listLoading = false;
if (res.success) {
this.dataSet = res.data.data.data;
this.totalPage = res.data.data.total;
}
}
);
}
... | this.listLoading = true;
const params = {url: '', data: {}, method: 'POST'};
params.url = `${env | conditional_block |
ingredients.go | package ingredients
//go:generate go run corpus/main.go
//go:generate gofmt -w corpus.go
import (
"bytes"
// "encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strings"
"time"
json "github.com/goccy/go-json"
"github.com/jinzhu/inflection"
log "github.com/schollz/logger"
"golang.org/x/net/html"
"golang... |
if len(arrayMap) == 0 {
err = fmt.Errorf("nothing to parse")
return
}
parseMap(arrayMap[0], &lineInfo)
err = nil
} else {
parseMap(regMap, &lineInfo)
err = nil
}
return
}
func parseMap(aMap map[string]interface{}, lineInfo *[]LineInfo) {
for _, val := range aMap {
switch val.(type) {
case m... | {
return
} | conditional_block |
ingredients.go | package ingredients
//go:generate go run corpus/main.go
//go:generate gofmt -w corpus.go
import (
"bytes"
// "encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strings"
"time"
json "github.com/goccy/go-json"
"github.com/jinzhu/inflection"
log "github.com/schollz/logger"
"golang.org/x/net/html"
"golang... | () {
inflection.AddSingular("(clove)(s)?$", "${1}")
inflection.AddSingular("(potato)(es)?$", "${1}")
inflection.AddSingular("(tomato)(es)?$", "${1}")
inflection.AddUncountable("molasses")
inflection.AddUncountable("bacon")
}
// Recipe contains the info for the file and the lines
type Recipe struct {
FileName ... | init | identifier_name |
ingredients.go | package ingredients
//go:generate go run corpus/main.go
//go:generate gofmt -w corpus.go
import (
"bytes"
// "encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strings"
"time"
json "github.com/goccy/go-json"
"github.com/jinzhu/inflection"
log "github.com/schollz/logger"
"golang.org/x/net/html"
"golang... | err = nil
} else {
parseMap(regMap, &lineInfo)
err = nil
}
return
}
func parseMap(aMap map[string]interface{}, lineInfo *[]LineInfo) {
for _, val := range aMap {
switch val.(type) {
case map[string]interface{}:
parseMap(val.(map[string]interface{}), lineInfo)
case []interface{}:
parseArray(val.(... | if len(arrayMap) == 0 {
err = fmt.Errorf("nothing to parse")
return
}
parseMap(arrayMap[0], &lineInfo) | random_line_split |
ingredients.go | package ingredients
//go:generate go run corpus/main.go
//go:generate gofmt -w corpus.go
import (
"bytes"
// "encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strings"
"time"
json "github.com/goccy/go-json"
"github.com/jinzhu/inflection"
log "github.com/schollz/logger"
"golang.org/x/net/html"
"golang... |
// NewFromHTML generates a new parser from a HTML text
func NewFromHTML(name, htmlstring string) (r *Recipe, err error) {
r = &Recipe{FileName: name}
r.FileContent = htmlstring
err = r.parseHTML()
return
}
func IngredientsFromURL(url string) (ingredients []Ingredient, err error) {
r, err := NewFromURL(url)
if ... | {
client := http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
html, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return NewFromHTML(url, string(html))
} | identifier_body |
tidy_toys.py | #!/usr/bin/env python3
#
# Bespoke re-write for the Tidy up the Toys PiWars 2021 challenge
# Last updated:
# 23 Jan 20
# BUGS / ISSUES (Open):
# Need to try and move the distance() and position() functions out of the find_colour() function
# BUGS / ISSUES (Closed):
# Uses global variables throughout, now reduced by u... | # movement
print("Movement Control")
def grabber(): # grabber control
print("Grabber Control")
# HSV COLOURSPACE START
def find_toy(frame, target_toy):
# convert captured image to HSV colour space to detect colours
toy = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#cv2.imshow("toy", toy)
#key ... | ving(): | identifier_name |
tidy_toys.py | #!/usr/bin/env python3
#
# Bespoke re-write for the Tidy up the Toys PiWars 2021 challenge
# Last updated:
# 23 Jan 20
# BUGS / ISSUES (Open):
# Need to try and move the distance() and position() functions out of the find_colour() function
# BUGS / ISSUES (Closed):
# Uses global variables throughout, now reduced by u... | elif cx < 320:
print("steering right")
drive = "steering right"
# Enter motor controls here
#TB.SetMotor1(0.5)
#TB.SetMotor2(0.25)
driveLeft = 0.50
driveRight = 0.25
cv2.putText(frame, drive, (50, 50), cv2.FONT_HERSHE... | nt("steering left")
drive = "steering left"
#Enter motor controls here
#TB.SetMotor1(0.25)
#TB.SetMotor2(0.5)
driveLeft = 0.25
driveRight = 0.50
cv2.putText(frame, drive, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
... | conditional_block |
tidy_toys.py | #!/usr/bin/env python3
#
# Bespoke re-write for the Tidy up the Toys PiWars 2021 challenge
# Last updated:
# 23 Jan 20
# BUGS / ISSUES (Open):
# Need to try and move the distance() and position() functions out of the find_colour() function
# BUGS / ISSUES (Closed):
# Uses global variables throughout, now reduced by u... | # DISTANCE (z) BEGIN
# initialise the known distance from the camera to the object which is 300mm 11.81102 inches
KNOWN_DISTANCE = 100
Z = KNOWN_DISTANCE
# initialise the know object width, which is 50mm or 1.968504 inches
KNOWN_WIDTH = 0.5
D = KNOWN_WIDTH
# d = width in pixels at 100cm... | def distance(w, frame):
#global Z
print("distance, z") #Debugging | random_line_split |
tidy_toys.py | #!/usr/bin/env python3
#
# Bespoke re-write for the Tidy up the Toys PiWars 2021 challenge
# Last updated:
# 23 Jan 20
# BUGS / ISSUES (Open):
# Need to try and move the distance() and position() functions out of the find_colour() function
# BUGS / ISSUES (Closed):
# Uses global variables throughout, now reduced by u... | ef main_loop():
# capture the video frames (0) = first camera
cap = cv2.VideoCapture(0)
# define the video capture frame size
cap.set(3, image_width) # set as a global variable
cap.set(4, image_height) # set as a global variable
while True:
# check toys list
# if no toys l... | SetMotor1(driveLeft)
TB.SetMotor2(driveRight)
d | identifier_body |
TkUtil.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import object
"""Tkinter utilities
History:
2004-10-08 ROwen
2004-10-12 ROwen Modified getWi... |
if self.offsetFlipped[ii]:
# offset is distance from bottom/right of window to bottom/right of screen
# to avoid tk bugs, the constrained result will NOT use this convention
corner_ii = usableScreenExtent_ii - (corner_ii + extent_ii)
... | extent_ii = usableScreenExtent_ii | conditional_block |
TkUtil.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import object
"""Tkinter utilities
History:
2004-10-08 ROwen
2004-10-12 ROwen Modified getWi... | (self):
if not self._root:
self._root = _getTkWdg().winfo_toplevel()
return self._root.wm_maxsize()
def toTkStr(self, includeExtent=None):
"""Return the geometry as a tk geometry string
Inputs:
- includeExtent: include extent information? One of:
... | screenExtent | identifier_name |
TkUtil.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import object
"""Tkinter utilities
History:
2004-10-08 ROwen
2004-10-12 ROwen Modified getWi... |
class Geometry(object):
"""A class representing a tk geometry
Fields include the following two-element tuples:
- offset: x,y offset of window relative to screen; see also offsetFlipped
- offsetFlipped: is the meaning of x,y offset flipped?
if False (unflipped) then offset is the distance ... | return self.tclFuncName | identifier_body |
TkUtil.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import object
"""Tkinter utilities
History:
2004-10-08 ROwen
2004-10-12 ROwen Modified getWi... |
# windowing system constants
WSysAqua = "aqua"
WSysX11 = "x11"
WSysWin = "win32"
# internal globals
g_tkWdg = None
g_winSys = None
g_tkVersion = None
def addColors(*colorMultPairs):
"""Add colors or scale a color.
Inputs:
- A list of one or more (color, mult) pairs.
Returns sum of (R, G, B)... | import tkinter
import RO.OS | random_line_split |
cleaner.go | package goose
import (
"container/list"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"log"
"regexp"
"strings"
)
type cleaner struct {
config configuration
}
func NewCleaner(config configuration) cleaner {
return cleaner{
config: config,
}
}
var divToPElementsPatt... |
func (this *cleaner) cleanEMTags(doc *goquery.Document) *goquery.Document {
ems := doc.Find("em")
ems.Each(func(i int, s *goquery.Selection) {
images := s.Find("img")
if images.Length() == 0 {
this.config.parser.dropTag(s)
}
})
if this.config.debug {
log.Printf("Cleaning %d EM tags\n", ems.Size())
}
... | {
tags := [3]string{"id", "name", "class"}
articles := doc.Find("article")
articles.Each(func(i int, s *goquery.Selection) {
for _, tag := range tags {
this.config.parser.delAttr(s, tag)
}
})
return doc
} | identifier_body |
cleaner.go | package goose
import (
"container/list"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"log"
"regexp"
"strings"
)
type cleaner struct {
config configuration
}
func NewCleaner(config configuration) cleaner {
return cleaner{
config: config,
}
}
var divToPElementsPatt... | (doc *goquery.Document) *goquery.Document {
spans := doc.Find("span")
spans.Each(func(i int, s *goquery.Selection) {
parent := s.Parent()
if parent != nil && parent.Length() > 0 && parent.Get(0).DataAtom == atom.P {
node := s.Get(0)
node.Data = s.Text()
node.Type = html.TextNode
}
})
return doc
}
fu... | cleanParaSpans | identifier_name |
cleaner.go | package goose
import (
"container/list"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"log"
"regexp"
"strings"
)
type cleaner struct {
config configuration
}
func NewCleaner(config configuration) cleaner {
return cleaner{
config: config,
}
}
var divToPElementsPatt... | return output
}
func (this *cleaner) replaceWithPara(div *goquery.Selection) {
if div.Size() > 0 {
node := div.Get(0)
node.Data = atom.P.String()
node.DataAtom = atom.P
}
}
func (this *cleaner) tabsAndNewLinesReplacements(text string) string {
text = strings.Replace(text, "\n", "\n\n", -1)
text = tabsRegEx... |
for _, o := range output {
o.NextSibling = nil
} | random_line_split |
cleaner.go | package goose
import (
"container/list"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"log"
"regexp"
"strings"
)
type cleaner struct {
config configuration
}
func NewCleaner(config configuration) cleaner {
return cleaner{
config: config,
}
}
var divToPElementsPatt... |
})
}
return doc
}
func (this *cleaner) cleanParaSpans(doc *goquery.Document) *goquery.Document {
spans := doc.Find("span")
spans.Each(func(i int, s *goquery.Selection) {
parent := s.Parent()
if parent != nil && parent.Length() > 0 && parent.Get(0).DataAtom == atom.P {
node := s.Get(0)
node.Data = s.Te... | {
log.Printf("%d naughty %s elements found", cont, selector)
} | conditional_block |
新的分钟数据整合.py | import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month='201911'
contract_kind='NI'
rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
main_code_path='C:/Users/lenovo/Documents/WeCha... | #分割到的长度放入容器中
target_num=len(target_df)
#理论长度
theory_num=len(time_0931_15)
#实际上两种情况:1.是交易日但完全没有数据2.是交易日,只有部分数据 3.是交易日,数据也是完整的
if target_num>0:
#开始区分2,3情况
have_time=target_df['time'].values.tolist()
lac... | # 设置了存放按月填充的路径
for date_index in range(len(target_date)):
#按日期进行分割
target_df=final_df.loc[final_df['date2']==target_date[date_index]] | random_line_split |
新的分钟数据整合.py | import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month='201911'
contract_kind='NI'
rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
main_code_path='C:/Users/lenovo/Documents/WeCha... | for row_index in range(len(result)):
target_row=result.iloc[row_index].tolist()
clean_row=target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{c... | if result.shape[0]>0:
| conditional_block |
新的分钟数据整合.py | import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month='201911'
contract_kind='NI'
rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
main_code_path='C:/Users/lenovo/Documents/WeCha... | path:str,rar_data_file_path:str,clean_data_path:str,time_range_path:str,end_date:str,commodity_bool=True):
'''
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据... | ct_kind:str,main_code_ | identifier_name |
新的分钟数据整合.py | import numpy as np
import pandas as pd
from unrar import rarfile
import numpy as np
import pandas as pd
import tushare as ts
import os
year_month='201911'
contract_kind='NI'
rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'
main_code_path='C:/Users/lenovo/Documents/WeCha... | '字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
... | identifier_body | |
conf.go | // Copyright 2019 Huawei Technologies Co.,Ltd.
// 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 ag... | "time"
)
type urlHolder struct {
scheme string
host string
port int
}
type config struct {
securityProviders []securityProvider
urlHolder *urlHolder
pathStyle bool
cname bool
sslVerify bool
endpoint string
signature SignatureType
region s... | "strconv"
"strings" | random_line_split |
conf.go | // Copyright 2019 Huawei Technologies Co.,Ltd.
// 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 ag... | (headerTimeout int) configurer {
return func(conf *config) {
conf.headerTimeout = headerTimeout
}
}
// WithProxyUrl is a configurer for ObsClient to set HTTP proxy.
func WithProxyUrl(proxyURL string) configurer {
return func(conf *config) {
conf.proxyURL = proxyURL
}
}
// WithMaxConnections is a configurer fo... | WithHeaderTimeout | identifier_name |
conf.go | // Copyright 2019 Huawei Technologies Co.,Ltd.
// 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 ag... |
func (conf *config) prepareConfig() {
if conf.connectTimeout <= 0 {
conf.connectTimeout = DEFAULT_CONNECT_TIMEOUT
}
if conf.socketTimeout <= 0 {
conf.socketTimeout = DEFAULT_SOCKET_TIMEOUT
}
conf.finalTimeout = conf.socketTimeout * 10
if conf.headerTimeout <= 0 {
conf.headerTimeout = DEFAULT_HEADER_TIM... | {
return func(conf *config) {
conf.enableCompression = enableCompression
}
} | identifier_body |
conf.go | // Copyright 2019 Huawei Technologies Co.,Ltd.
// 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 ag... |
conf.transport.Proxy = http.ProxyURL(proxyURL)
}
tlsConfig := &tls.Config{InsecureSkipVerify: !conf.sslVerify}
if conf.sslVerify && conf.pemCerts != nil {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(conf.pemCerts)
tlsConfig.RootCAs = pool
}
conf.transport.TLSClientConfig = tlsConfig
co... | {
return err
} | conditional_block |
PROGRAM.py | # -*- coding: utf-8 -*-
from LIBRARY import *
script_name='PROGRAM'
def MAIN(mode,text=''):
if (mode==0 or mode==1): FIX_KEYBOARD(mode,text)
elif mode==2: SEND_MESSAGE()
elif mode==3: DMCA()
elif mode==4: HTTPS_TEST()
elif mode==5: SERVERS_TYPE()
elif mode==6: GLOBAL_SEARCH(text)
elif mode==7: VERSION()
elif ... | (mode,text):
keyboard=text
if keyboard=='': return
if mode==1:
try:
window_id = xbmcgui.getCurrentWindowDialogId()
window = xbmcgui.Window(window_id)
keyboard = mixARABIC(keyboard)
window.getControl(311).setLabel(keyboard)
except: pass
elif mode==0:
ttype='X'
check=isinstance(keyboard, unicode)
... | FIX_KEYBOARD | identifier_name |
PROGRAM.py | # -*- coding: utf-8 -*-
from LIBRARY import *
script_name='PROGRAM'
def MAIN(mode,text=''):
if (mode==0 or mode==1): FIX_KEYBOARD(mode,text)
elif mode==2: SEND_MESSAGE()
elif mode==3: DMCA()
elif mode==4: HTTPS_TEST()
elif mode==5: SERVERS_TYPE()
elif mode==6: GLOBAL_SEARCH(text)
elif mode==7: VERSION()
elif ... | "}'
# #auth=("api", "my personal api key"),
# #response = requests.request('POST',url, data=payload, headers='', auth='')
# response = requests.post(url, data=payload, headers='', auth='')
# if response.status_code == 200:
# xbmcgui.Dialog().ok('تم الارسال بنجاح','')
# else:
# xbmcgui.Dialog().ok('خطأ في الارس... | sage+' | conditional_block |
PROGRAM.py | # -*- coding: utf-8 -*-
from LIBRARY import *
script_name='PROGRAM'
def MAIN(mode,text=''):
if (mode==0 or mode==1): FIX_KEYBOARD(mode,text)
elif mode==2: SEND_MESSAGE()
elif mode==3: DMCA()
elif mode==4: HTTPS_TEST()
elif mode==5: SERVERS_TYPE()
elif mode==6: GLOBAL_SEARCH(text)
elif mode==7: VERSION()
elif ... | cgui.Dialog().textviewer(message1,message2+message3)
return ''
def RANDOM():
headers = { 'User-Agent' : '' }
url = 'https://www.bestrandoms.com/random-arabic-words'
payload = { 'quantity' : '4' }
data = urllib.urlencode(payload)
#xbmcgui.Dialog().ok('',str(data))
html = openURL(url,data,headers,'','PROGRAM-RAND... | ب','',99,'','',search)
addDir('[COLOR FFC89008]=========================[/COLOR]','',9999)
addDir('13. [COLOR FFC89008]SHA [/COLOR]'+search+' - موقع شاهد فوريو','',119,'','',search)
addDir('14. [COLOR FFC89008]HLA [/COLOR]'+search+' - موقع هلا سيما','',89,'','',search)
xbmcplugin.endOfDirectory(addon_handle)
r... | identifier_body |
PROGRAM.py | # -*- coding: utf-8 -*-
from LIBRARY import *
script_name='PROGRAM'
def MAIN(mode,text=''):
if (mode==0 or mode==1): FIX_KEYBOARD(mode,text)
elif mode==2: SEND_MESSAGE()
elif mode==3: DMCA()
elif mode==4: HTTPS_TEST()
elif mode==5: SERVERS_TYPE()
elif mode==6: GLOBAL_SEARCH(text)
elif mode==7: VERSION()
elif ... |
#PLAY_VIDEO(url,script_name,'yes')
return | random_line_split | |
api_op_ListSMSSandboxPhoneNumbers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package sns
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"
"github.com/aw... |
func (m *opListSMSSandboxPhoneNumbersResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleS... | {
return "ResolveEndpointV2"
} | identifier_body |
api_op_ListSMSSandboxPhoneNumbers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package sns
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"
"github.com/aw... |
return nil
}
// ListSMSSandboxPhoneNumbersAPIClient is a client that implements the
// ListSMSSandboxPhoneNumbers operation.
type ListSMSSandboxPhoneNumbersAPIClient interface {
ListSMSSandboxPhoneNumbers(context.Context, *ListSMSSandboxPhoneNumbersInput, ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error... | {
return err
} | conditional_block |
api_op_ListSMSSandboxPhoneNumbers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package sns
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"
"github.com/aw... |
// A list of the calling account's pending and verified phone numbers.
//
// This member is required.
PhoneNumbers []types.SMSSandboxPhoneNumber
// A NextToken string is returned when you call the ListSMSSandboxPhoneNumbersInput
// operation if additional pages of records are available.
NextToken *string
// ... |
noSmithyDocumentSerde
}
type ListSMSSandboxPhoneNumbersOutput struct { | random_line_split |
api_op_ListSMSSandboxPhoneNumbers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package sns
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"
"github.com/aw... | () bool {
return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0)
}
// NextPage retrieves the next ListSMSSandboxPhoneNumbers page.
func (p *ListSMSSandboxPhoneNumbersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if !p.HasMorePages() {
... | HasMorePages | identifier_name |
app.js | // Instancia o método de leitura de arquivo da API do HTML5
var fileReader = new FileReader();
// Carrega a o método da API para leitura do arquivo ao carregar a página
window.onload = function init() {
fileReader.onload = lerArquivo;
};
var error = document.getElementsByClassName('reader-ocorren__error')[0];
var... | '</tr>';
};
div += '</table>';
// Seta a div montada com os dados
areaUpload.classList.add('hidden');
btnNewReader.classList.remove('hidden');
// Exibe os dados
exibeArquivo.innerHTML = div;
};
btnNewReader.addEventListener('click', function() {
areaUpload.classList.remove('hid... | Verifica se o registro é de uma ocorrência
if (fileLine[j].slice(0, 3) == '342') {
var ocorrencia = dadosOcorrencia(fileLine[j].slice(28, 30));
div += '<td>' + ocorrencia.cod + '</td>';
div += '<td>' + ocorrencia.descricao + '</td>';
}
};... | conditional_block |
app.js | // Instancia o método de leitura de arquivo da API do HTML5
var fileReader = new FileReader();
// Carrega a o método da API para leitura do arquivo ao carregar a página
window.onload = function init() {
fileReader.onload = lerArquivo;
};
var error = document.getElementsByClassName('reader-ocorren__error')[0];
var... | // Passa os dados do arquivo para um aray onde cada índice é uma linha do arquivo
var fileArr = e.target.result.split('\n');
// Monta a div que irá exibir os dados
var cnpj = fileArr[2].slice(3, 17);
var div = '<p><strong>CNPJ:</strong> ' + formataCnpj(cnpj) + '</p>';
div += '<p><strong>Transport... | o(e) {
| identifier_name |
app.js | // Instancia o método de leitura de arquivo da API do HTML5
var fileReader = new FileReader();
// Carrega a o método da API para leitura do arquivo ao carregar a página
window.onload = function init() {
fileReader.onload = lerArquivo;
};
var error = document.getElementsByClassName('reader-ocorren__error')[0];
var... | };
btnNewReader.addEventListener('click', function() {
areaUpload.classList.remove('hidden');
btnNewReader.classList.add('hidden');
exibeArquivo.innerHTML = '';
});
var formataCnpj = function(cnpj) {
return cnpj.slice(0, 2) + '.' +
cnpj.slice(2, 5) + '.' +
cnpj.slice(5, 8) + '/' +
... | random_line_split | |
app.js | // Instancia o método de leitura de arquivo da API do HTML5
var fileReader = new FileReader();
// Carrega a o método da API para leitura do arquivo ao carregar a página
window.onload = function init() {
fileReader.onload = lerArquivo;
};
var error = document.getElementsByClassName('reader-ocorren__error')[0];
var... | rrencias = [
{cod: '00', descricao: "Processo de Transporte já Iniciado"},
{cod: '01', descricao: "Entrega Realizada Normalmente"},
{cod: '02', descricao: "Entrega Fora da Data Programada"},
{cod: '03', descricao: "Recusa por Falta de Pedido de Compra"},
{cod: '04', descricao: "... | identifier_body | |
mc.py | """
Montecarlo agent
"""
from player import BasePlayer
from domino import Event
from copy import deepcopy
from random import shuffle, choice
from math import log
import numpy as np
from common.logger import add_logger, DEBUG, INFO
logger = add_logger('mcts', INFO)
logger.disabled = False
def canonical(piece):
... | for i in range(4):
# Player `i` don't have any remaining piece
if (mask >> (7 * i)) & ((1 << 7) - 1) == 0:
winner_team = i & 1
break
hand = 0
for j in range(7):
if (mask >> (i * 7 + j)) & 1:
hand += sum(distribution[i][j])
... | light_player = set()
| random_line_split |
mc.py | """
Montecarlo agent
"""
from player import BasePlayer
from domino import Event
from copy import deepcopy
from random import shuffle, choice
from math import log
import numpy as np
from common.logger import add_logger, DEBUG, INFO
logger = add_logger('mcts', INFO)
logger.disabled = False
def canonical(piece):
... |
assert len(order) == 0
return pieces
def choice(self):
self.feed()
NUM_SAMPLING = 10
NUM_EXPANDED = 2000
scores = {} # Score of each move (piece, head)
winpredictions = {}
for _ in range(NUM_SAMPLING):
distribution = self.sample()
... | if pos == self.position:
pieces[pos] = deepcopy(self.pieces)
else:
r = self.remaining[pos]
pieces[pos] = order[:r]
order = order[r:]
assert len(pieces[pos]) == r | conditional_block |
mc.py | """
Montecarlo agent
"""
from player import BasePlayer
from domino import Event
from copy import deepcopy
from random import shuffle, choice
from math import log
import numpy as np
from common.logger import add_logger, DEBUG, INFO
logger = add_logger('mcts', INFO)
logger.disabled = False
def canonical(piece):
... | (self):
self.feed()
NUM_SAMPLING = 10
NUM_EXPANDED = 2000
scores = {} # Score of each move (piece, head)
winpredictions = {}
for _ in range(NUM_SAMPLING):
distribution = self.sample()
cscores, cwinpredictions = montecarlo(distribution, tuple(se... | choice | identifier_name |
mc.py | """
Montecarlo agent
"""
from player import BasePlayer
from domino import Event
from copy import deepcopy
from random import shuffle, choice
from math import log
import numpy as np
from common.logger import add_logger, DEBUG, INFO
logger = add_logger('mcts', INFO)
logger.disabled = False
def canonical(piece):
... | """
state: (bitmask, heads, pos)
bitmask: 7 bits each player 2**28 states that denotes which pieces are still holding relative to `distribution`
parent visit count: PC
visit count: VC
win count: WC
exploration control: K
WC / VC +... | identifier_body | |
csn.py | """
MIT License
Copyright (c) 2018 Nicola Di Mauro
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, including without limitation the rights
to use, copy, modify, merge, publis... |
def check_correctness(self,k):
mean = 0.0
for world in itertools.product([0,1], repeat=k):
prob = np.exp(self._score_sample_log_proba(world))
mean = mean + prob
return mean
def show(self):
""" WRITEME """
print ("Learned Cut Set Network")
# ... | self.min_instances = min_instances
self.min_features = min_features
self.alpha = alpha
self.depth = depth
self.data = data
self.node = TreeNode()
self.multilabel = multilabel
self.n_labels = n_labels
self.ml_tree_structure = ml_tree_structure
self.... | identifier_body |
csn.py | """
MIT License
Copyright (c) 2018 Nicola Di Mauro
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, including without limitation the rights
to use, copy, modify, merge, publis... | ll = ((l_ll+np.log(left_weight))*left_data.shape[0] + (r_ll+np.log(right_weight))*right_data.shape[0])/self.data.shape[0]
else:
ll = -np.inf
if ll>bestlik:
bestlik = ll
best_clt_l = CL_l
best_clt_r = CL_r
... | random_line_split | |
csn.py | """
MIT License
Copyright (c) 2018 Nicola Di Mauro
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, including without limitation the rights
to use, copy, modify, merge, publis... | (self, X):
Prob = X[:,0]*0.0
for i in range(X.shape[0]):
Prob[i] = np.exp(self.score_sample_log_proba(X[i]))
return Prob
def or_cut(self):
print(" > trying to cut ... ")
sys.stdout.flush()
found = False
bestlik = self.orig_ll
be... | score_samples_proba | identifier_name |
csn.py | """
MIT License
Copyright (c) 2018 Nicola Di Mauro
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, including without limitation the rights
to use, copy, modify, merge, publis... |
self.node.cltree = Cltree()
self.node.cltree.fit(data, alpha=self.alpha,
multilabel = self.multilabel, n_labels=self.n_labels, ml_tree_structure=self.ml_tree_structure)
self.orig_ll = self.node.cltree.score_samples_log_proba(self.dat... | for f in range(data.shape[1]):
if data[r,f]>0:
COC[r].append(f) | conditional_block |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... | loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
last_tick_time = now;
}
*/
self.receive_clients();
self.receive_packets();
... | random_line_split | |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... |
fn start(mut self) {
println!("Listening for connections...");
//let mut last_tick_time = SystemTime::now();
loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
... | { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index in finished_indicies {
let ... | identifier_body |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... | (&mut self) {
let num_clients = self.clients.len();
for client in 0..num_clients {
let mut packets = self.clients[client]
.connection
.receive_packets();
for packet_batch in packets.drain(..) {
for packet in PacketDecoder::new_batch... | receive_packets | identifier_name |
network.rs | extern crate openssl;
extern crate rand;
extern crate reqwest;
use crate::utils;
use crate::mojang::{Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;... |
}
fn poll_mojang(&mut self) { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index i... | {
self.clients.push(client);
} | conditional_block |
tautils.py | #Copyright (c) 2007-8, Playful Invention Company.
#Copyright (c) 2008-10, Walter Bender
#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, including without limitation the rig... | (top):
""" When we undock, retract the 'arm' that extends from 'sandwichtop'. """
if top is not None and top.name in ['sandwichtop', 'sandwichtop_no_label']:
if top.ey > 0:
top.reset_y()
def grow_stack_arm(top):
""" When we dock, grow an 'arm' from 'sandwichtop'. """
if top is not ... | reset_stack_arm | identifier_name |
tautils.py | #Copyright (c) 2007-8, Playful Invention Company.
#Copyright (c) 2008-10, Walter Bender
#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, including without limitation the rig... |
def data_from_string(text):
""" JSON load data from a string. """
return json_load(text.replace(']],\n', ']], '))
def data_to_file(data, ta_file):
""" Write data to a file. """
file_handle = file(ta_file, "w")
file_handle.write(data_to_string(data))
file_handle.close()
def data_to_string(... | """ Open the .ta file, ignoring any .png file that might be present. """
file_handle = open(ta_file, "r")
#
# We try to maintain read-compatibility with all versions of Turtle Art.
# Try pickle first; then different versions of json.
#
try:
_data = pickle.load(file_handle)
except:
... | identifier_body |
tautils.py | #Copyright (c) 2007-8, Playful Invention Company.
#Copyright (c) 2008-10, Walter Bender
#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, including without limitation the rig... | while _blk is not None:
if _blk.name in COLLAPSIBLE:
return None
if _blk.name in ['repeat', 'if', 'ifelse', 'forever', 'while']:
if blk != _blk.connections[len(_blk.connections) - 1]:
return None
if _blk.name in ['sandwichtop', 'sandwichtop_no_label',
... | def find_sandwich_top(blk):
""" Find the sandwich top above this block. """
# Always follow the main branch of a flow: the first connection.
_blk = blk.connections[0] | random_line_split |
tautils.py | #Copyright (c) 2007-8, Playful Invention Company.
#Copyright (c) 2008-10, Walter Bender
#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, including without limitation the rig... |
elif dock2 == 2 and blk2.connections[1] is not None:
if blk2.connections[1].name == 'string':
if not numeric_arg(blk2.connections[1].values[0]):
return False
return True
def xy(event):
""" Where is the mouse event? """
return map(int, event.get_coor... | if not numeric_arg(blk2.connections[2].values[0]):
return False | conditional_block |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... | pub fn light_brown() -> Color { rgb_bytes(233 , 185 , 110) }
/// Chocolate - Regular - #C17D11
pub fn brown() -> Color { rgb_bytes(193 , 125 , 17 ) }
/// Chocolate - Dark - #8F5902
pub fn dark_brown() -> Color { rgb_bytes(143 , 89 , 2 ) }
/// Straight Black.
pub fn black() -> Color { rgb_byt... | /// Chocolate - Light - #E9B96E | random_line_split |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... | (self, h: f32, s: f32, l: f32, a: f32) -> Self {
self.color(hsla(h, s, l, a))
}
/// Set the color of the widget from hsl values.
fn hsl(self, h: f32, s: f32, l: f32) -> Self {
self.color(hsl(h, s, l))
}
}
| hsla | identifier_name |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... |
else {
(clampf32((1.0 - r) * 0.75 + r),
clampf32((1.0 - g) * 0.25 + g),
clampf32((1.0 - b) * 0.25 + b))
}
};
let a = clampf32((1.0 - a) * 0.75 + a);
rgba(r, g, b, a)
}
/// Return the Color's invert.
pub fn in... | { (r + 0.4, g + 0.2, b + 0.2) } | conditional_block |
color.rs | //!
//! A library providing simple `Color` and `Gradient` types along with useful transformations and
//! presets.
//!
//!
//! Inspiration taken from [elm-lang's color module]
//! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
//!
//!
//! Module for working with colors. ... |
/// Return either black or white, depending which contrasts the Color the most. This will be
/// useful for determining a readable color for text on any given background Color.
pub fn plain_contrast(self) -> Color {
if self.luminance() > 0.5 { black() } else { white() }
}
/// Extract the ... | {
match *self {
Color::Rgba(r, g, b, _) => (r + g + b) / 3.0,
Color::Hsla(_, _, l, _) => l,
}
} | identifier_body |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | / Grammar with support of type annotations. Works as a decorator.
///
/// # Examples
///
/// ```
/// use arithmetic_parser::grammars::{F32Grammar, Parse};
/// use arithmetic_typing::Annotated;
///
/// # fn main() -> anyhow::Result<()> {
/// let code = "x: [Num] = (1, 2, 3);";
/// let ast = Annotated::<F32Grammar>::pars... | ConstraintSet::default()
}
}
// | identifier_body |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | : InputSpan<'a>) -> NomResult<'a, Self::Type> {
use nom::combinator::map;
map(TypeAst::parse, |ast| ast.extra)(input)
}
}
/// Supports all syntax features.
impl<T: ParseLiteral> Parse<'_> for Annotated<T> {
type Base = Self;
const FEATURES: Features = Features::all();
}
| type(input | identifier_name |
lib.rs | //! Hindley–Milner type inference for arithmetic expressions parsed
//! by the [`arithmetic-parser`] crate.
//!
//! This crate allows parsing type annotations as a part of a [`Grammar`], and to infer
//! and check types for expressions / statements produced by `arithmetic-parser`.
//! Type inference is *partially* comp... | /// # assert_eq!(ast.statements.len(), 1);
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Annotated<T>(PhantomData<T>);
impl<T: ParseLiteral> ParseLiteral for Annotated<T> {
type Lit = T::Lit;
fn parse_literal(input: InputSpan<'_>) -> NomResult<'_, Self::Lit> {
<T as ParseLiteral>::parse_lit... | /// let code = "x: [Num] = (1, 2, 3);";
/// let ast = Annotated::<F32Grammar>::parse_statements(code)?; | random_line_split |
NJ.py | #!/usr/bin/env python
import numpy
import math
import logging
from scipy.stats import poisson
import networkx as nx
import NetworkX_Extension as nxe
# from GSA import Edge
class NJTree:
logger = logging.getLogger("NJTree")
def __init__(self, mrca, alpha, beta, gamma, gain, loss, synteny):
self.graph = nx.Graph(... |
else:
my_species = self.mrca
self.graph.add_node(newNode, species=my_species)
# replace first merged leave by newNode then shift everything after the 2nd merged leave
self.graph.add_edge(unadded_nodes[minp[0]], newNode, homology_dist=mp0_mp_dist, synteny_dist=syn0_mp_dist)
self.graph.add_edge(unadde... | my_species = self.graph.node[unadded_nodes[minp[0]]]['species'] | conditional_block |
NJ.py | #!/usr/bin/env python
import numpy
import math
import logging
from scipy.stats import poisson
import networkx as nx
import NetworkX_Extension as nxe
# from GSA import Edge
class NJTree:
logger = logging.getLogger("NJTree")
def __init__(self, mrca, alpha, beta, gamma, gain, loss, synteny):
self.graph = nx.Graph(... | (self):
if self.rootedTree:
processed = ['root']
current_leaves = list(self.rootedTree['root'])
# nwk = "(" + ",".join(current_leaves) + ");"
# nwk = ",".join(current_leaves)
nwk = "(" + current_leaves[0] + ":" + str(self.rootedTree['root'][current_leaves[0]]['homology_dist']) + ',' + current_leaves[1]... | getNewick | identifier_name |
NJ.py | #!/usr/bin/env python
import numpy
import math
import logging
from scipy.stats import poisson
import networkx as nx
import NetworkX_Extension as nxe
# from GSA import Edge
class NJTree:
logger = logging.getLogger("NJTree")
def __init__(self, mrca, alpha, beta, gamma, gain, loss, synteny):
self.graph = nx.Graph(... | new_trees = []
new_root_edges = []
futur_roots = [root[1][0], root[1][1]]
self.graph.remove_edge(root[1][0], root[1][1])
new_graphs = nx.connected_component_subgraphs(self.graph)
for n in new_graphs:
for futur_root in futur_roots: # loop here, but next if selects only 1 iteration
if futur_root in n.no... | identifier_body | |
NJ.py | #!/usr/bin/env python
import numpy
import math
import logging
from scipy.stats import poisson
import networkx as nx
import NetworkX_Extension as nxe
# from GSA import Edge
class NJTree:
logger = logging.getLogger("NJTree")
def __init__(self, mrca, alpha, beta, gamma, gain, loss, synteny):
self.graph = nx.Graph(... | def calcMostEdgesToLeaves(unprocN, leaf, TG):
"""
unprocN = list of nodes that are not leaves?
leaf = list of (node, species_name)
TG = graph
"""
mostLeaves = -1
retNode = None
l_zero = []
for l in leaf:
l_zero.append(l[0])
for n in unprocN:
e_count = 0
for e in TG[n]:
if e in l_zero:
... | random_line_split | |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... |
}
fn read_train_data(labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(outpu... | {
TrainDataPair { input, output }
} | identifier_body |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | (labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(output, _)| output.value_co... | read_train_data | identifier_name |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | input: input_value,
output: output_value,
} = &data;
assert_eq!(output_value.value_count(), 1);
input.set_value(input_value.clone().into());
output.set_expect_output(output_value.clone());
... | let mut accuracy = 0f64;
for data in &data_pair[range] {
let TrainDataPair { | random_line_split |
main.rs | use std::convert::TryInto;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::time::Instant;
use clap::{App, Arg};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
u... | else {
0.
}
}
};
sum_of_loss += *output_loss.get([]).unwrap() as f64;
if back_propagate {
output.clear_gradient_all();
output.b... | {
1.
} | conditional_block |
structs.go | package queue_list
import (
"encoding/xml"
"github.com/tmconsulting/amadeus-ws-go/formats"
)
type QueueList struct {
XMLName xml.Name `xml:"http://xml.amadeus.com/QDQLRQ_11_1_1A Queue_List"`
// presence implies that this is a follow up scrolling entry to a previous entry. Absence implies start of a new search
... | type TransportIdentifierType struct {
// Company identification.
CompanyIdentification *CompanyIdentificationTypeI `xml:"companyIdentification,omitempty"`
// Flight details.
FlightDetails *ProductIdentificationDetailsTypeI `xml:"flightDetails,omitempty"`
}
type TravellerInformationTypeI struct {
// Traveller sur... | // identifies the category or categories.
SubQueueInfoDetails *SubQueueInformationDetailsTypeI `xml:"subQueueInfoDetails,omitempty"`
}
| random_line_split |
tkteach.py | # tkteach.py
# By Ryan M. Mones
# www.Comet.cool
#
# Modified by Serhiy Shekhovtsov
#
# Written on Python 2.7.13 (64-bit)
# Tested on Python 3.6.1 (64-bit)
#
# __________ __ _______________ __________ ____ __
# / ____/ __ \/ |/ / ____/_ __/ / ____/ __ \/ __ \/ /
# / / / / / / /|_/ / _... |
# MIDDLE FRAME VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
self.frameMIDDLE = tk.Frame(master, bd=2)
self.frameMIDDLE.pack(side=tk.LEFT)
self.imgStage = tk.Label(self.frameMIDDLE, text="", height=self.default_size[1], width=self.default_size[0])
self.imgStage.pack()
self.imgFileName = tk.Label(se... | self.frameSeperator01 = tk.Frame(master,width=20,height=1)
self.frameSeperator01.pack(side=tk.LEFT)
| random_line_split |
tkteach.py | # tkteach.py
# By Ryan M. Mones
# www.Comet.cool
#
# Modified by Serhiy Shekhovtsov
#
# Written on Python 2.7.13 (64-bit)
# Tested on Python 3.6.1 (64-bit)
#
# __________ __ _______________ __________ ____ __
# / ____/ __ \/ |/ / ____/_ __/ / ____/ __ \/ __ \/ /
# / / / / / / /|_/ / _... | (self):
print("-->skipToImage")
try:
tryImageSelection = int(self.imageNumberInput.get())
if (tryImageSelection>=0) and (tryImageSelection<len(self.imageListDir)):
self.imageSelection = tryImageSelection
self.loadImage()
else:
self.statusBar.config(text="ERROR! Image does not exist.")
... | skipToImage | identifier_name |
tkteach.py | # tkteach.py
# By Ryan M. Mones
# www.Comet.cool
#
# Modified by Serhiy Shekhovtsov
#
# Written on Python 2.7.13 (64-bit)
# Tested on Python 3.6.1 (64-bit)
#
# __________ __ _______________ __________ ____ __
# / ____/ __ \/ |/ / ____/_ __/ / ____/ __ \/ __ \/ /
# / / / / / / /|_/ / _... |
else:
#Check if this is an ad-hoc keybind for a category selection...
try:
if self.categoriesListbox.selection_includes(self.keyBindings.index(key.char.lower())):
self.categoriesListbox.selection_clear(self.keyBindings.index(key.char.lower()))
else:
self.categoriesListbox.selection_set... | self.zoomOutButton.config(relief=tk.SUNKEN)
self.zoomOutButton.update_idletasks()
self.zoomOut()
time.sleep(0.05)
self.zoomOutButton.config(relief=tk.RAISED) | conditional_block |
tkteach.py | # tkteach.py
# By Ryan M. Mones
# www.Comet.cool
#
# Modified by Serhiy Shekhovtsov
#
# Written on Python 2.7.13 (64-bit)
# Tested on Python 3.6.1 (64-bit)
#
# __________ __ _______________ __________ ____ __
# / ____/ __ \/ |/ / ____/_ __/ / ____/ __ \/ __ \/ /
# / / / / / / /|_/ / _... |
def select_defaults(self):
print("-->select_defaults")
if len(self.dataSetsListStr) == 1:
self.dataSetsListbox.selection_set(0)
self.loadDataSet()
def initialize(self):
print("-->initialize")
#Set parameters:
self.imgScaleFactor = 1
#Sub-initializations
self.initializ... | print("-->__init__")
self.master = master
self.default_size = (800, 400)
master.title("tkteach version 002")
master.bind("<Key>", self.keyPressed)
# Create GUI elements:
self.titleLabel = tk.Label(master, text="tkteach version 002")
self.titleLabel.pack()
# BOTTOM "STATUS B... | identifier_body |
v3_alarm_test.go | // Copyright 2017 The etcd 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 agreed t... | (t *testing.T) {
integration.BeforeTest(t)
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kvc := integration.ToGRPC(clus.RandClient()).KV
mt := integration.ToGRPC(clus.RandClient()).Maintenance
alarmReq := &pb.AlarmRequest{
MemberID: 123,
Action: pb.AlarmReq... | TestV3AlarmDeactivate | identifier_name |
v3_alarm_test.go | // Copyright 2017 The etcd 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 agreed t... | select {
case <-stopc:
t.Fatalf("timed out waiting for alarm")
case <-time.After(10 * time.Millisecond):
}
}
// txn with non-mutating Ops should go through when NOSPACE alarm is raised
_, err = kvc0.Txn(context.TODO(), &pb.TxnRequest{
Compare: []*pb.Compare{
{
Key: key,
Result: ... | random_line_split | |
v3_alarm_test.go | // Copyright 2017 The etcd 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 agreed t... |
ctx, cancel := context.WithTimeout(context.TODO(), integration.RequestWaitTimeout)
defer cancel()
// small quota machine should reject put
if _, err := kvc0.Put(ctx, &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
t.Fatalf("past-quota instance should reject put")
}
// large quota machine should rej... | {
t.Fatal(err)
} | conditional_block |
v3_alarm_test.go | // Copyright 2017 The etcd 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 agreed t... |
func TestV3CorruptAlarmWithLeaseCorrupted(t *testing.T) {
integration.BeforeTest(t)
lg := zaptest.NewLogger(t)
clus := integration.NewCluster(t, &integration.ClusterConfig{
CorruptCheckTime: time.Second,
Size: 3,
SnapshotCount: 10,
SnapshotCatchUpEntries: 5,... | {
integration.BeforeTest(t)
lg := zaptest.NewLogger(t)
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 3, UseBridge: true})
defer clus.Terminate(t)
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
if _, err := clus.Client(0).Put(context.TODO(), "k... | identifier_body |
agent.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"syscall"
"time"
"github.com/lf-edge/eden/sdn/vm/api"
"github.com/lf-edge/eden/sdn/vm/pkg/configitems"
"github.com/lf-edge/eden/sdn/vm/pkg/maclookup"
dg "github.com/lf-edge/eve/libs/depgraph"
"g... |
}
func (a *agent) linkSubscribe(doneChan <-chan struct{}) chan netlink.LinkUpdate {
linkChan := make(chan netlink.LinkUpdate, 64)
linkErrFunc := func(err error) {
log.Errorf("LinkSubscribe failed %s\n", err)
}
linkOpts := netlink.LinkSubscribeOptions{
ErrorCallback: linkErrFunc,
}
if err := netlink.LinkSubs... | {
log.Infof("Fixed config items: %s",
strings.Join(fixed, ", "))
} | conditional_block |
agent.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"syscall"
"time"
"github.com/lf-edge/eden/sdn/vm/api"
"github.com/lf-edge/eden/sdn/vm/pkg/configitems"
"github.com/lf-edge/eden/sdn/vm/pkg/maclookup"
dg "github.com/lf-edge/eve/libs/depgraph"
"g... |
func (a *agent) run(linkChan chan netlink.LinkUpdate) {
for {
select {
case netModel := <-a.newNetModel:
// Network model is already validated, applying...
a.Lock()
a.netModel = netModel
a.updateCurrentState()
a.updateIntendedState()
a.reconcile()
a.Unlock()
case <-a.resumeReconciliation:... | {
a.ctx = context.Background()
linkChan := a.linkSubscribe(a.ctx.Done())
a.macLookup = &maclookup.MacLookup{}
a.macLookup.RefreshCache()
registry := &reconciler.DefaultRegistry{}
if err := configitems.RegisterItems(registry, a.macLookup); err != nil {
return err
}
a.registry = registry
a.newNetModel = make(c... | identifier_body |
agent.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"syscall"
"time"
"github.com/lf-edge/eden/sdn/vm/api"
"github.com/lf-edge/eden/sdn/vm/pkg/configitems"
"github.com/lf-edge/eden/sdn/vm/pkg/maclookup"
dg "github.com/lf-edge/eve/libs/depgraph"
"g... | (doneChan <-chan struct{}) chan netlink.LinkUpdate {
linkChan := make(chan netlink.LinkUpdate, 64)
linkErrFunc := func(err error) {
log.Errorf("LinkSubscribe failed %s\n", err)
}
linkOpts := netlink.LinkSubscribeOptions{
ErrorCallback: linkErrFunc,
}
if err := netlink.LinkSubscribeWithOptions(
linkChan, don... | linkSubscribe | identifier_name |
agent.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"syscall"
"time"
"github.com/lf-edge/eden/sdn/vm/api"
"github.com/lf-edge/eden/sdn/vm/pkg/configitems"
"github.com/lf-edge/eden/sdn/vm/pkg/maclookup"
dg "github.com/lf-edge/eve/libs/depgraph"
"g... | if !found {
return nil
}
var fflags uint64
filter := netlink.Route{}
fflags |= netlink.RT_FILTER_TABLE
filter.Table = syscall.RT_TABLE_MAIN
fflags |= netlink.RT_FILTER_OIF
filter.LinkIndex = hostPort.IfIndex
family := syscall.AF_INET
if ipv6 {
family = syscall.AF_INET6
}
nlRoutes, err := netlink.RouteLi... | func (a *agent) getHostGwIP(ipv6 bool) net.IP {
hostPort, found := a.macLookup.GetInterfaceByMAC(hostPortMACPrefix, true) | random_line_split |
client.go | /**
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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 requir... |
func validatePushItemInput(owner string, item model.Item) error {
if len(item.ID) < 1 {
return ErrItemIDEmpty
}
if len(item.Data) < 1 {
return ErrItemDataEmpty
}
return nil
}
| {
if c.observer == nil || c.observer.ticker == nil {
return nil
}
if !atomic.CompareAndSwapInt32(&c.observer.state, running, transitioning) {
level.Error(c.logger).Log(xlog.MessageKey(), "Stop called when a listener was not in running state", "err", ErrListenerNotStopped)
return ErrListenerNotRunning
}
c.o... | identifier_body |
client.go | /**
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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 requir... | return ErrListenerNotStopped
}
c.observer.ticker.Reset(c.observer.pullInterval)
go func() {
for {
select {
case <-c.observer.shutdown:
return
case <-c.observer.ticker.C:
outcome := SuccessOutcome
ctx := c.setLogger(context.Background(), c.logger)
items, err := c.GetItems(ctx, "")
if... | }
if !atomic.CompareAndSwapInt32(&c.observer.state, stopped, transitioning) {
level.Error(c.logger).Log(xlog.MessageKey(), "Start called when a listener was not in stopped state", "err", ErrListenerNotStopped) | random_line_split |
client.go | /**
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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 requir... | (options acquire.RemoteBearerTokenAcquirerOptions) bool {
return len(options.AuthURL) < 1 || options.Buffer == 0 || options.Timeout == 0
}
func buildTokenAcquirer(auth *Auth) (acquire.Acquirer, error) {
if !isEmpty(auth.JWT) {
return acquire.NewRemoteBearerTokenAcquirer(auth.JWT)
} else if len(auth.Basic) > 0 {
... | isEmpty | identifier_name |
client.go | /**
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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 requir... |
err := validateConfig(&config)
if err != nil {
return nil, err
}
if getLogger == nil {
getLogger = func(ctx context.Context) log.Logger {
return log.NewNopLogger()
}
}
if setLogger == nil {
setLogger = func(ctx context.Context, _ log.Logger) context.Context {
return ctx
}
}
tokenAcquirer, err ... | {
return nil, ErrNilMeasures
} | conditional_block |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | let (v,f) = self.finalize_source();
let mut s = Shader::new(&v, &f)?;
for (idx, attrib_name) in attributes.iter().enumerate() {
unsafe {
gl::BindAttribLocation(s.gl_handle, 1 + idx as u32, attrib_name.as_ptr());
}
}
unsafe {
gl::BindAttribLocation(s.gl_handle, 0, b"position\0".as_ptr() as _);
... | .collect::<Vec<_>>();
| random_line_split |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... |
pub fn attribute(mut self, name: &str, ty: &str) -> Self {
if name == "position" {
println!("Tried to overwrite 'position' attribute while building shader - ignoring");
return self
}
self.attributes.push(format!("{} {}", ty, name)); self
}
pub fn varying(mut self, name: &str, ty: &str) -> Self {
se... | {
self.uniforms.push(format!("{} u_{}", ty, name)); self
} | identifier_body |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | <V>(&self, uniform: &str, v: V) where V: Into<Vec3> {
assert!(self.is_bound(), "Tried to set uniform '{}' on unbound shader", uniform);
unsafe {
let v = v.into();
gl::Uniform3f(self.get_uniform_loc(&uniform), v.x, v.y, v.z);
}
}
pub fn set_uniform_vec4<V>(&self, uniform: &str, v: V) where V: Into<Vec4> ... | set_uniform_vec3 | identifier_name |
shader.rs | #![allow(dead_code)]
use std;
use math::*;
use rendering::gl;
use std::fmt::Write;
#[derive(Copy, Clone, Debug)]
pub struct Shader {
pub gl_handle: u32,
pub proj_loc: i32,
pub view_loc: i32,
}
impl Shader {
pub fn new(vertex_shader_src: &str, fragment_shader_src: &str) -> Result<Shader, String> {
use std::ff... | else {
gl_position.push_str("vec4(position, 0.0, 1.0);\n");
}
self.vertex_body = format!("{}{}", gl_position, self.vertex_body);
let mut bodies = [&mut self.vertex_body, &mut self.fragment_body];
for (sh, body) in [&mut vert_src, &mut frag_src].iter_mut().zip(bodies.iter_mut()) {
write!(sh, "\n{}\n", v... | {
gl_position.push_str("vec4(position, 1.0);\n");
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.