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
main.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
.multiple(true) .number_of_values(1) .help( "Bind to another service to form a producer/consumer relationship, \ specified as name:service:group", ), ) .arg( Arg::with_name("NO_DOCKER_IMAG...
random_line_split
main.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // 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 r...
{ match val.parse::<u32>() { Ok(_) => Ok(()), Err(_) => Err(format!("{} is not a natural number", val)), } }
identifier_body
config.go
// // (C) Copyright 2018-2019 Intel Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
(i int) error { // avoid mutating subject during iteration, instead access through // config/parent object srv := &c.Servers[i] srv.CliOpts = append( srv.CliOpts, "-t", strconv.Itoa(srv.Targets), "-g", c.SystemName, "-s", srv.ScmMount) if c.Modules != "" { srv.CliOpts = append(srv.CliOpts, "-m", c.Modu...
populateCliOpts
identifier_name
config.go
// // (C) Copyright 2018-2019 Intel Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
// override config with commandline supplied options c.cmdlineOverride(cliOpts) for i := range c.Servers { srv := &c.Servers[i] if err := c.populateCliOpts(i); err != nil { return errors.WithMessagef( err, "populating I/O service options") } // add to existing config file EnvVars srv.EnvVars...
}
random_line_split
config.go
// // (C) Copyright 2018-2019 Intel Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
func (c *configuration) setPath(path string) error { if path != "" { c.Path = path } if !filepath.IsAbs(c.Path) { newPath, err := c.ext.getAbsInstallPath(c.Path) if err != nil { return err } c.Path = newPath } return nil } // loadConfigOpts derives file location and parses configuration options /...
{ bytes, err := yaml.Marshal(c) if err != nil { return err } return ioutil.WriteFile(filename, bytes, 0644) }
identifier_body
config.go
// // (C) Copyright 2018-2019 Intel Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable la...
if err := config.loadConfig(); err != nil { return config, errors.WithMessagef(err, "loading %s", config.Path) } log.Debugf("DAOS config read from %s", config.Path) // Override certificate support if specified in cliOpts if cliOpts.Insecure { config.TransportConfig.AllowInsecure = true } // get unique id...
{ return config, errors.WithMessage(err, "set path") }
conditional_block
main.js
// $(".seven-wonders").append('<div class="great-wall">the great wall of china</div>') $(".seven-wonders").append('<div class="welcome"></div>') $(".welcome").append('<p id="wel">welcome to our website! Lets take you on a tour </p>') $(".welcome").append('<img id="image1" src="https://velvetescape.com/wp-content/uploa...
$(".colosseum").append('<br>') $(".colosseum").append('<br>') //rome 4 $(".colosseum").append('<img id="colosseum4" src="https://cdn.civitatis.com/italia/roma/galeria/coliseo-roma-noche.jpg"/>') $(".colosseum").append('<div class="rome4">In medieval times, the Colosseum was used as a church, then as a fortress by two...
$(".colosseum").append('<img id="colosseum3" src="https://cdn.britannica.com/s:700x500/69/94469-050-4340CF77/Colosseum-Rome.jpg"/>') $(".colosseum").append('<div class="rome3">At present the Colosseum is, along with the Vatican City, Romes greatest tourist attraction. Each year 6 million tourists visit it. On 7 July 20...
random_line_split
DebugModule.go
package sweetiebot import ( "fmt" "sort" "strings" "strconv" "github.com/blackhole12/discordgo" ) type DebugModule struct { } // Name of the module func (w *DebugModule) Name() string { return "Debug" } // Commands in the module func (w *DebugModule) Commands() []Command { return []Command{ &echoCommand{...
URL: url, Name: msg.Author.Username + "#" + msg.Author.Discriminator, IconURL: fmt.Sprintf("https://cdn.discordapp.com/avatars/%s/%s.jpg", msg.Author.ID, msg.Author.Avatar), }, Color: int(color), Fields: fields, } info.SendEmbed(channel, embed) return "", false, nil } func (c *echoEmbedCommand...
Type: "rich", Author: &discordgo.MessageEmbedAuthor{
random_line_split
DebugModule.go
package sweetiebot import ( "fmt" "sort" "strings" "strconv" "github.com/blackhole12/discordgo" ) type DebugModule struct { } // Name of the module func (w *DebugModule) Name() string { return "Debug" } // Commands in the module func (w *DebugModule) Commands() []Command { return []Command{ &echoCommand{...
func (c *updateCommand) UsageShort() string { return "[RESTRICTED] Updates sweetiebot." } func (c *updateCommand) Roles() []string { return []string{"Princesses"} } func (c *updateCommand) Channels() []string { return []string{} } type dumpTablesCommand struct { } func (c *dumpTablesCommand) Name() string { retu...
{ return &CommandUsage{Desc: "Tells sweetiebot to shut down, calls an update script, rebuilds the code, and then restarts."} }
identifier_body
DebugModule.go
package sweetiebot import ( "fmt" "sort" "strings" "strconv" "github.com/blackhole12/discordgo" ) type DebugModule struct { } // Name of the module func (w *DebugModule) Name() string { return "Debug" } // Commands in the module func (w *DebugModule) Commands() []Command { return []Command{ &echoCommand{...
return msg.Content[indices[0]:], false, nil } func (c *echoCommand) Usage(info *GuildInfo) *CommandUsage { return &CommandUsage{ Desc: "Makes Sweetie Bot say the given sentence in `#channel`, or in the current channel if no channel is provided.", Params: []CommandUsageParam{ {Name: "#channel", Desc: "The chan...
{ if len(args) < 2 { return "```You have to tell me to say something, silly!```", false, nil } info.SendMessage(arg[2:len(arg)-1], msg.Content[indices[1]:]) return "", false, nil }
conditional_block
DebugModule.go
package sweetiebot import ( "fmt" "sort" "strings" "strconv" "github.com/blackhole12/discordgo" ) type DebugModule struct { } // Name of the module func (w *DebugModule) Name() string { return "Debug" } // Commands in the module func (w *DebugModule) Commands() []Command { return []Command{ &echoCommand{...
(args []string, msg *discordgo.Message, indices []int, info *GuildInfo) (string, bool, *discordgo.MessageEmbed) { _, isOwner := sb.Owners[SBatoi(msg.Author.ID)] sb.dg.State.RLock() guilds := append([]*discordgo.Guild{}, sb.dg.State.Guilds...) sb.dg.State.RUnlock() sort.Sort(guildSlice(guilds)) s := make([]string,...
Process
identifier_name
plugin.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
(elt string, name string) []string { var suffix = []string{elt, name} return append(namespacePrefix, suffix...) } // GetConfigPolicy returns config policy // It returns error in case retrieval was not successful func (p *dfCollector) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { cp := cpolicy.New() rule, _ :=...
createNamespace
identifier_name
plugin.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
return nil } // GetMetricTypes returns list of available metric types // It returns error in case retrieval was not successful func (p *dfCollector) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) { mts := []plugin.MetricType{} for _, kind := range metricsKind { mts = append(mts, plugin.Metric...
{ procPathStats, err := os.Stat(procPath.(string)) if err != nil { return err } if !procPathStats.IsDir() { return errors.New(fmt.Sprintf("%s is not a directory", procPath.(string))) } p.proc_path = procPath.(string) }
conditional_block
plugin.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
// GetMetricTypes returns list of available metric types // It returns error in case retrieval was not successful func (p *dfCollector) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) { mts := []plugin.MetricType{} for _, kind := range metricsKind { mts = append(mts, plugin.MetricType{ Namespa...
}
random_line_split
plugin.go
// +build linux /* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ...
// GetConfigPolicy returns config policy // It returns error in case retrieval was not successful func (p *dfCollector) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { cp := cpolicy.New() rule, _ := cpolicy.NewStringRule("proc_path", false, "/proc") node := cpolicy.NewPolicyNode() node.Add(rule) cp.Add([]stri...
{ var suffix = []string{elt, name} return append(namespacePrefix, suffix...) }
identifier_body
aes.rs
//! Interface to the AES peripheral. //! //! Note that the AES peripheral is only available on some MCUs in the L0/L1/L2 //! families. Check the datasheet for more information. //! //! See STM32L0x2 reference manual, chapter 18. use core::{ convert::TryInto, ops::{Deref, DerefMut}, pin::Pin, }; use as_sli...
<Buffer, Channel>( self, dma: &mut dma::Handle, buffer: Pin<Buffer>, channel: Channel, ) -> Transfer<Self, Channel, Buffer, dma::Ready> where Self: dma::Target<Channel>, Buffer: Deref + 'static, Buffer::Target: AsSlice<Element = u8>, Channel: dma::...
write_all
identifier_name
aes.rs
//! Interface to the AES peripheral. //! //! Note that the AES peripheral is only available on some MCUs in the L0/L1/L2 //! families. Check the datasheet for more information. //! //! See STM32L0x2 reference manual, chapter 18. use core::{ convert::TryInto, ops::{Deref, DerefMut}, pin::Pin, }; use as_sli...
} } /// An active encryption/decryption stream /// /// You can get an instance of this struct by calling [`AES::enable`]. pub struct Stream { aes: AES, /// Can be used to write data to the AES peripheral pub tx: Tx, /// Can be used to read data from the AES peripheral pub rx: Rx, } impl Stre...
rx: Rx(()), tx: Tx(()), }
random_line_split
peer.rs
use std::io::BufferedReader; use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; use std::option::Option; use std::io::timer::sleep; use uuid::{Uuid, UuidVersion, Version4Random}; use super::super::events::*; use super::parsers::{read_rpc, as_network_msg, make_id_bytes}; use super::types::*; static CON...
(&mut self) { match self.mgmt_port.try_recv() { Ok(msg) => { match msg { AttachStreamMsg(id, mut stream) => { if id == self.conf.id { self.attach_stream(stream); } } ...
check_mgmt_msg
identifier_name
peer.rs
use std::io::BufferedReader; use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; use std::option::Option; use std::io::timer::sleep; use uuid::{Uuid, UuidVersion, Version4Random}; use super::super::events::*; use super::parsers::{read_rpc, as_network_msg, make_id_bytes}; use super::types::*; static CON...
fn new(id: u64, config: NetPeerConfig, to_raft: Sender<RaftMsg>, mgmt_port: Receiver<MgmtMsg>) -> NetPeer { NetPeer { id: id, conf: config, stream: None, to_raft: to_raft, mgmt_port: mgmt_port, shutdown: false, } } f...
{ let (mgmt_send, mgmt_port) = channel(); let conf = conf.clone(); spawn(proc() { let mut netpeer = NetPeer::new(id, conf, to_raft, mgmt_port); netpeer.peer_loop(); }); mgmt_send }
identifier_body
peer.rs
use std::io::BufferedReader; use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; use std::option::Option; use std::io::timer::sleep; use uuid::{Uuid, UuidVersion, Version4Random}; use super::super::events::*; use super::parsers::{read_rpc, as_network_msg, make_id_bytes}; use super::types::*; static CON...
break; } } let mut replies = 0; // We should get the votes back out on the port that we were waiting on debug!("test_spawn(): waiting for replies"); spawn(proc() { match recv1.recv() { VRQ(recvote, chan) => { ...
stream.write(vote_bytes); count += 1; debug!("[test_spawn()] Sent {} vote requests.", count); if count > 1 {
random_line_split
peer.rs
use std::io::BufferedReader; use std::io::net::ip::SocketAddr; use std::io::net::tcp::TcpStream; use std::option::Option; use std::io::timer::sleep; use uuid::{Uuid, UuidVersion, Version4Random}; use super::super::events::*; use super::parsers::{read_rpc, as_network_msg, make_id_bytes}; use super::types::*; static CON...
StopMsg => { self.shutdown = true; self.stream = None; } } } _ => { } } } /* * Send an RPC up to Raft, waiting for a reply if we need to. */ fn send...
{ if self.stream.is_some() { self.send_rpc(rpc, self.stream.clone().unwrap()); } }
conditional_block
import_videos.py
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
:param rating: rating of the video, highest by default. """ self.video_id = video_id self.base_path = base_path self.file_path = path self.rating = rating def import_worker(thread_index): """ Thread worker that deals with tasks. :return: """ THREAD_S...
""" Create an import task object. :param video_id: a pre-allocated video_id in number, so we don't need to lock db in multiple thread. :param base_path: path prefix that will be ignored when creating keywords from path. :param path: path of the file
random_line_split
import_videos.py
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
duration = float(duration) flip_num = float(flip_num) interval = duration / flip_num if interval <= 0.0: tlog = get_logger(current_thread().name) tlog.error("Cannot generate flips. Duration: {0} FlipNum:{1}".format(duration, flip_num)) return False fps = 'fps=1/' + str(inte...
return True
conditional_block
import_videos.py
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
(video_path, dest_path): tlog = get_logger(current_thread().name) if os.path.isfile(dest_path): tlog.info('#Already converted, skip: {0}'.format(dest_path)) return True tlog.info('#Converting: {0} => {1}\n', video_path, dest_path) cmd = ['ffmpeg', '-i', video_path, '-vcodec', 'h264', '-...
convert_video_to_mp4
identifier_name
import_videos.py
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
def gen_thumb(video_path, thumb_path): """ Generate thumb image for the given video, and grabs duration from output :return: (success, duration) """ if os.path.isfile(thumb_path): os.remove(thumb_path) global THUMB_SIZE cmd = ['ffmpeg', '-itsoffset', '-5', '-i', video_path, '-vfr...
return './static/cover/' + str(fn) + '.png'
identifier_body
DoJetFakeFactors.py
""" Interactive script to plot data-MC histograms out of a set of trees. """ # Parse command-line options from argparse import ArgumentParser p = ArgumentParser() p.add_argument('--baseDir', default=None, dest='baseDir', help='Path to base directory containing all ntuples') p.add_argument('--bas...
def ApplySinglePhotonFF( cut_str, cut_vals, eta_cuts, ptbins, fake_factors) : labels = cut_vals.keys() samp = samplesData.get_samples(name='Data') sampEval = samplesData.get_samples(name='WjetsZjets') for lab in labels : ec = eta_cuts[lab] vals = cut_vals[lab] ...
draw_cmd_base = 'mu_passtrig25_n>0 && mu_n==1 && ph_n > 1 && dr_ph1_ph2 > 0.3 && m_ph1_ph2>15 && dr_ph1_leadLep>0.4 && dr_ph2_leadLep>0.4 && ph_hasPixSeed[0]==0 && ph_hasPixSeed[1]==0 ' samp = samplesData.get_samples(name='Muon') for r1,r2 in regions : draw_cmd = draw_cmd_base + ' && is%s_leadph12...
identifier_body
DoJetFakeFactors.py
""" Interactive script to plot data-MC histograms out of a set of trees. """ # Parse command-line options from argparse import ArgumentParser p = ArgumentParser() p.add_argument('--baseDir', default=None, dest='baseDir', help='Path to base directory containing all ntuples') p.add_argument('--bas...
return output main()
bin = (reg, 15, max ) if bin in output : continue num_count = num_hist.Integral( num_hist.FindBin( 15), num_hist.FindBin(max ) - 1 ) den_count = den_hist.Integral( den_hist.FindBin( 15), den_hist.FindBin(max ) - 1 ) factor = num_count/den_count ...
conditional_block
DoJetFakeFactors.py
""" Interactive script to plot data-MC histograms out of a set of trees. """ # Parse command-line options from argparse import ArgumentParser p = ArgumentParser() p.add_argument('--baseDir', default=None, dest='baseDir', help='Path to base directory containing all ntuples') p.add_argument('--bas...
( cut_str, cut_vals, eta_cuts, ptbins, fake_factors) : labels = cut_vals.keys() samp = samplesData.get_samples(name='Data') sampEval = samplesData.get_samples(name='WjetsZjets') for lab in labels : ec = eta_cuts[lab] vals = cut_vals[lab] cuts_den = cut_str%vals cuts_...
ApplySinglePhotonFF
identifier_name
DoJetFakeFactors.py
""" Interactive script to plot data-MC histograms out of a set of trees. """ # Parse command-line options from argparse import ArgumentParser p = ArgumentParser() p.add_argument('--baseDir', default=None, dest='baseDir', help='Path to base directory containing all ntuples') p.add_argument('--bas...
N_FF_TT = LL_count*ff_lead*ff_subl print 'Lead pt = %d - %d, subl pt = %d - %d' %( min, max, 15, max ) print 'N_LL = ', LL_count print 'N_LT = ', LT_count print 'N_TL = ', TL_count print 'N_FF_TL = ', N_FF_TL print 'N_FF_LT = ', N_FF...
N_FR_TT = N_FR_LT*ff_lead
random_line_split
huffman.rs
//! Length-limited Huffman Codes. use crate::bit; use alloc::{vec, vec::Vec}; use core::cmp; use core2::io; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(wid...
else if x_weight < y_weight { z.push(x.next().unwrap()); } else { z.push(y.next().unwrap()); } } z } fn package(mut nodes: Vec<Node>) -> Vec<Node> { if nodes.len() >= 2 { let new_len = nodes.len() / 2; for ...
{ z.extend(x); break; }
conditional_block
huffman.rs
//! Length-limited Huffman Codes. use crate::bit; use alloc::{vec, vec::Vec}; use core::cmp; use core2::io; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(wid...
{ table: Vec<u16>, eob_symbol: Option<u16>, safely_peek_bitwidth: Option<u8>, max_bitwidth: u8, } impl DecoderBuilder { pub fn new( max_bitwidth: u8, safely_peek_bitwidth: Option<u8>, eob_symbol: Option<u16>, ) -> Self { debug_assert!(max_bitwidth <= MAX_BITWIDTH...
DecoderBuilder
identifier_name
huffman.rs
//! Length-limited Huffman Codes. use crate::bit; use alloc::{vec, vec::Vec}; use core::cmp; use core2::io; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(wid...
EncoderBuilder { table: vec![Code::new(0, 0); symbol_count], } } pub fn from_bitwidthes(bitwidthes: &[u8]) -> io::Result<Encoder> { let symbol_count = bitwidthes .iter() .enumerate() .filter(|e| *e.1 > 0) .last() .ma...
pub struct EncoderBuilder { table: Vec<Code>, } impl EncoderBuilder { pub fn new(symbol_count: usize) -> Self {
random_line_split
huffman.rs
//! Length-limited Huffman Codes. use crate::bit; use alloc::{vec, vec::Vec}; use core::cmp; use core2::io; const MAX_BITWIDTH: u8 = 15; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Code { pub width: u8, pub bits: u16, } impl Code { pub fn new(width: u8, bits: u16) -> Self { debug_assert!(wid...
fn finish(self) -> Self::Instance { Encoder { table: self.table } } } #[derive(Debug, Clone)] pub struct Encoder { table: Vec<Code>, } impl Encoder { #[inline(always)] pub fn encode<W>(&self, writer: &mut bit::BitWriter<W>, symbol: u16) -> io::Result<()> where W: io::Write, ...
{ debug_assert_eq!(self.table[symbol as usize], Code::new(0, 0)); self.table[symbol as usize] = code.inverse_endian(); Ok(()) }
identifier_body
views.py
from django.shortcuts import render,redirect,reverse from django.views.generic import View #导入只接受GET请求和POST请求的装饰器 from django.views.decorators.http import require_GET,require_POST #导入form验证用的表单 from .forms import Alterform,EditAlterform,Reviewform #导入Alter_manage的模型 from Apps.Alter_management.models import Alter_managm...
start=request.GET.get('start') #获取时间控件开始时间 end =request.GET.get('end') #获取时间控件结束时间 cxtj =request.GET.get('cxtj') #获取查询条件录入信息 #request.GET.get(参数,默认值) #这个参数是只有没有传递参数的时候才会使用 #如果传递了,但是是一个空的字符串,也不会使用,那么可以使用 ('ReviewStatus',0) or 0 reviewStatus = int(request.GET.get('R...
# @method_decorator(permission_required('Alter_management.change_alter_managment',login_url='/alter/index/'),name="dispatch") class Alter_manager_newview(View):#变更管理页面,返回数据 def get(self,request): #request.GET.get获取出来的数据都是字符串类型 page = int(request.GET.get('p',1))#获当前页数,并转换成整形,没有传默认为1
random_line_split
views.py
from django.shortcuts import render,redirect,reverse from django.views.generic import View #导入只接受GET请求和POST请求的装饰器 from django.views.decorators.http import require_GET,require_POST #导入form验证用的表单 from .forms import Alterform,EditAlterform,Reviewform #导入Alter_manage的模型 from Apps.Alter_management.models import Alter_managm...
iew):#变更管理页面,返回数据 # def Alter_manager_view (request):#变更管理页面,返回数据 # Alterd_datas=Alter_managment.objects.all() # context={ # 'Alterd_datas':Alterd_datas # } # return render(request,"Alter_management/Alter.html",context=context) # * @函数名: Alter_manager_newview # * @功能描述: 变更...
iew(V
identifier_name
views.py
from django.shortcuts import render,redirect,reverse from django.views.generic import View #导入只接受GET请求和POST请求的装饰器 from django.views.decorators.http import require_GET,require_POST #导入form验证用的表单 from .forms import Alterform,EditAlterform,Reviewform #导入Alter_manage的模型 from Apps.Alter_management.models import Alter_managm...
conditional_block
views.py
from django.shortcuts import render,redirect,reverse from django.views.generic import View #导入只接受GET请求和POST请求的装饰器 from django.views.decorators.http import require_GET,require_POST #导入form验证用的表单 from .forms import Alterform,EditAlterform,Reviewform #导入Alter_manage的模型 from Apps.Alter_management.models import Alter_managm...
AltType_id=form.cleaned_data.get('AltType') AltTypes = Alt_Type.objects.get(pk=AltType_id) AssociatedNumber = form.cleaned_data.get('AssociatedNumber') Database_id = form.cleaned_data.get('Database') Database= Alt_Database.objects.get(pk=Databas...
1:02 # * @最后编辑者: 郭军 @require_POST @Alter_login_required def delete_Alter_manager(request):#变更内容删除用 if request.user.has_perm('Alter_management.change_alter_managment'): id=request.POST.get("id") try: Alter_managment.objects.filter(id=id).delete() Alter_managment_checked.object...
identifier_body
simpletests.py
from pymarketo.client import MarketoClientFactory import os import sys #@UnusedImport import time #@UnusedImport import datetime #@UnusedImport from pprint import pprint #@UnresolvedImport TESTDIR = os.path.split(__file__)[0] PACKAGEDIR = os.path.join(TESTDIR,"..") INIFILE = os.path.join(PACKAGEDIR,"marketo.ini") DATA...
def aLeadKey(email=None,id=None): leadkey = mc.factory.create("LeadKey") if email: leadkey.keyType = "EMAIL" leadkey.keyValue = email elif id: leadkey.keyType = "IDNUM" leadkey.keyValue = id return leadkey def aLeadKeyArray(leads): lka = mc.factory.create("ArrayOfL...
asa = mc.factory.create("ArrayOfString") asa.stringItem = strings return asa
identifier_body
simpletests.py
from pymarketo.client import MarketoClientFactory import os import sys #@UnusedImport import time #@UnusedImport import datetime #@UnusedImport from pprint import pprint #@UnresolvedImport TESTDIR = os.path.split(__file__)[0] PACKAGEDIR = os.path.join(TESTDIR,"..") INIFILE = os.path.join(PACKAGEDIR,"marketo.ini") DATA...
# <xs:enumeration value="OpenEmail"/> # <xs:enumeration value="ClickEmail"/> # <xs:enumeration value="NewLead"/> # <xs:enumeration value="ChangeDataValue"/> # <xs:enumeration value="LeadAssigned"/> # <xs:enumeration value="NewSFDCOpprtnty"/> # <xs:enumeration value="Wait"/> # <xs:enumeration value="RunSubflow"/> # <xs:...
# <xs:enumeration value="AttendEvent"/> # <xs:enumeration value="SendEmail"/> # <xs:enumeration value="EmailDelivered"/> # <xs:enumeration value="EmailBounced"/> # <xs:enumeration value="UnsubscribeEmail"/>
random_line_split
simpletests.py
from pymarketo.client import MarketoClientFactory import os import sys #@UnusedImport import time #@UnusedImport import datetime #@UnusedImport from pprint import pprint #@UnresolvedImport TESTDIR = os.path.split(__file__)[0] PACKAGEDIR = os.path.join(TESTDIR,"..") INIFILE = os.path.join(PACKAGEDIR,"marketo.ini") DATA...
(): print "Testing listOperation" # Require numeric id fields leadkey = aLeadKey(id=1256) # Is member leadkey2 = aLeadKey(id=1) # Is not member result = mc.service.listOperation("ISMEMBEROFLIST",aListKey(LEADLIST), aLeadKeyArray([leadkey,leadkey2]),True) pri...
test_listOperation
identifier_name
simpletests.py
from pymarketo.client import MarketoClientFactory import os import sys #@UnusedImport import time #@UnusedImport import datetime #@UnusedImport from pprint import pprint #@UnresolvedImport TESTDIR = os.path.split(__file__)[0] PACKAGEDIR = os.path.join(TESTDIR,"..") INIFILE = os.path.join(PACKAGEDIR,"marketo.ini") DATA...
print def test_getMultipleLeadsUnsubscribedFlag(): print "Testing getMultipleLeadsUnsubscribedFlag" lastUpdatedAt = datetime.datetime(year=2010,month=1, day=1) attributelist = aStringArray(["Suppressed"]) leads = mc.service.getMultipleLeads(lastUpdatedAt,None,10, attributelist) assert leads.re...
attrs = attrs2dict(lead.leadAttributeList) print "Lead", lead.Id, lead.Email pprint(attrs)
conditional_block
post.rs
//! `post` table parsing and writing. use std::str; use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt}; use crate::binary::write::{WriteBinary, WriteContext}; use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8}; use crate::error::{ParseError, WriteError}; pub struct PostTable<'a> { pub header: Header, ...
"florin", "approxequal", "Delta", "guillemotleft", "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozeng...
"radical",
random_line_split
post.rs
//! `post` table parsing and writing. use std::str; use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt}; use crate::binary::write::{WriteBinary, WriteContext}; use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8}; use crate::error::{ParseError, WriteError}; pub struct PostTable<'a> { pub header: Header, ...
#[test] fn unused_glyph_names() { let post_data = build_post_with_unused_names().expect("unable to build post table"); let post = ReadScope::new(&post_data) .read::<PostTable<'_>>() .expect("unable to parse post table"); let num_glyphs = post.opt_sub_table.as_re...
{ // Build a post table with unused name entries let mut w = WriteBuffer::new(); let header = Header { version: 0x00020000, italic_angle: 0, underline_position: 0, underline_thickness: 0, is_fixed_pitch: 0, min_mem_type_42: ...
identifier_body
post.rs
//! `post` table parsing and writing. use std::str; use crate::binary::read::{ReadArray, ReadBinary, ReadCtxt}; use crate::binary::write::{WriteBinary, WriteContext}; use crate::binary::{I16Be, I32Be, U16Be, U32Be, U8}; use crate::error::{ParseError, WriteError}; pub struct PostTable<'a> { pub header: Header, ...
<C: WriteContext>(ctxt: &mut C, table: &SubTable<'a>) -> Result<(), WriteError> { U16Be::write(ctxt, table.num_glyphs)?; <&ReadArray<'_, _>>::write(ctxt, &table.glyph_name_index)?; for name in &table.names { PascalString::write(ctxt, name)?; } Ok(()) } } impl<'a...
write
identifier_name
viewer.js
"use strict"; var Widget = require('./widget').Widget, util = require('../util'); var $ = util.$, _t = util.gettext; var NS = 'annotator-viewer'; // Private: simple parser for hypermedia link structure // // Examples: // // links = [ // { // rel: 'alternate', // href: 'http://example.com/...
// Public: Creates an element for viewing annotations. var Viewer = exports.Viewer = Widget.extend({ // Public: Creates an instance of the Viewer object. // // options - An Object containing options. // // Examples // // # Creates a new viewer, adds a custom field and displays an annot...
{ cond = $.extend({}, cond, {rel: rel}); var results = []; for (var i = 0, len = data.length; i < len; i++) { var d = data[i], match = true; for (var k in cond) { if (cond.hasOwnProperty(k) && d[k] !== cond[k]) { match = false; break;...
identifier_body
viewer.js
"use strict"; var Widget = require('./widget').Widget, util = require('../util'); var $ = util.$, _t = util.gettext; var NS = 'annotator-viewer'; // Private: simple parser for hypermedia link structure // // Examples: // // links = [ // { // rel: 'alternate', // href: 'http://example.com/...
if (typeof options.permitDelete === 'undefined') { options.permitDelete = function (annotation) { return authz.permits('delete', annotation, ident.who()); }; } widget = new exports.Viewer(options); }, destroy: fun...
{ options.permitEdit = function (annotation) { return authz.permits('update', annotation, ident.who()); }; }
conditional_block
viewer.js
"use strict"; var Widget = require('./widget').Widget, util = require('../util'); var $ = util.$, _t = util.gettext; var NS = 'annotator-viewer'; // Private: simple parser for hypermedia link structure // // Examples: // // links = [ // { // rel: 'alternate', // href: 'http://example.com/...
if (match) { results.push(d); } } return results; } // Public: Creates an element for viewing annotations. var Viewer = exports.Viewer = Widget.extend({ // Public: Creates an instance of the Viewer object. // // options - An Object containing options. // // E...
if (cond.hasOwnProperty(k) && d[k] !== cond[k]) { match = false; break; } }
random_line_split
viewer.js
"use strict"; var Widget = require('./widget').Widget, util = require('../util'); var $ = util.$, _t = util.gettext; var NS = 'annotator-viewer'; // Private: simple parser for hypermedia link structure // // Examples: // // links = [ // { // rel: 'alternate', // href: 'http://example.com/...
(data, rel, cond) { cond = $.extend({}, cond, {rel: rel}); var results = []; for (var i = 0, len = data.length; i < len; i++) { var d = data[i], match = true; for (var k in cond) { if (cond.hasOwnProperty(k) && d[k] !== cond[k]) { match = false; ...
parseLinks
identifier_name
motorhead.go
package main import ( "bytes" "fmt" "github.com/jasonlvhit/gocron" "github.com/nlopes/slack" "github.com/zmb3/spotify" "log" "math/rand" "os" "strings" "time" ) type BotCentral struct { Channel *slack.Channel Event *slack.MessageEvent UserId string } type ReplyChannel struct { Channel *slack.C...
case msg := <-rtm.IncomingEvents: switch ev := msg.Data.(type) { case *slack.ConnectedEvent: fmt.Println("Connection counter:", ev.ConnectionCount) case *slack.MessageEvent: channelInfo, err := api.GetChannelInfo(ev.Channel) if err != nil { log.Println(err) } botCentral := &BotCent...
Loop: for { select {
random_line_split
motorhead.go
package main import ( "bytes" "fmt" "github.com/jasonlvhit/gocron" "github.com/nlopes/slack" "github.com/zmb3/spotify" "log" "math/rand" "os" "strings" "time" ) type BotCentral struct { Channel *slack.Channel Event *slack.MessageEvent UserId string } type ReplyChannel struct { Channel *slack.C...
(c chan ReplyChannel, sc chan StandupChannel) { commands := map[string]string{ "help": "see the available commands", "play": "play some tunes LENNY !", "stop": "pause|stop da music", "next": "next tune LENNY, this ain't any good", "previous": "dat tune was ace, play it again LENNY", "a...
handleCommands
identifier_name
motorhead.go
package main import ( "bytes" "fmt" "github.com/jasonlvhit/gocron" "github.com/nlopes/slack" "github.com/zmb3/spotify" "log" "math/rand" "os" "strings" "time" ) type BotCentral struct { Channel *slack.Channel Event *slack.MessageEvent UserId string } type ReplyChannel struct { Channel *slack.C...
else { for i := 2; i < len(commandArray); i++ { genresSeeds = append(genresSeeds, commandArray[i]) } } case "current": cp, _ := client.PlayerCurrentlyPlaying() attachment := slack.Attachment{ Pretext: cp.Item.Name, Text: cp.Item.Artists[0].Name, Color: "#85929E", } replyC...
{ attachments := make([]slack.Attachment, 0) genres, _ := client.GetAvailableGenreSeeds() for i := 1; i < 5; i++ { rand.Seed(time.Now().UTC().UnixNano()) genre := genres[rand.Intn(len(genres))] attachment := slack.Attachment{ Text: fmt.Sprintf("added genre %s", genre), } atta...
conditional_block
motorhead.go
package main import ( "bytes" "fmt" "github.com/jasonlvhit/gocron" "github.com/nlopes/slack" "github.com/zmb3/spotify" "log" "math/rand" "os" "strings" "time" ) type BotCentral struct { Channel *slack.Channel Event *slack.MessageEvent UserId string } type ReplyChannel struct { Channel *slack.C...
func getTrackId(trackEndpoint string) string { strs := strings.Split(trackEndpoint, "/") return strs[len(strs)-1] } func handleReply() { for { ac := <-replyChannel params := slack.PostMessageParameters{} params.AsUser = true params.Attachments = ac.Attachments params.UnfurlMedia = true fmt.Println("Ch...
{ var replyChannel ReplyChannel for { sc := <-standupChannel replyChannel.Channel = sc.Channel attachment := slack.Attachment{ Pretext: "Set time engaged", Text: fmt.Sprintf("I will blast some tunes at %s", sc.StandupTime.Format("3:04PM")), } setTime := sc.StandupTime.Format("15:04") newcron :...
identifier_body
main.rs
//! Default Compute@Edge template program. use fastly::http::{header, HeaderValue, Method, StatusCode}; use fastly::{mime, Dictionary, Error, Request, Response}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// The name of a backend server associated with this service. /// /// This should be ch...
let modified_pop_status= modified_pop_status_opt.unwrap(); let mut modified_pop_status_map: HashMap<String, u8> = serde_json::from_str(modified_pop_status.as_str()).unwrap(); let query_params: Vec<(String, String)> = req.get_query().unwrap(); println!("...
{ return Ok(Response::from_status(StatusCode::IM_A_TEAPOT) .with_body_text_plain("Problem accessing API\n")); }
conditional_block
main.rs
//! Default Compute@Edge template program. use fastly::http::{header, HeaderValue, Method, StatusCode}; use fastly::{mime, Dictionary, Error, Request, Response}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// The name of a backend server associated with this service. /// /// This should be ch...
{ current_pop: String, pop_status_data: Vec<PopStatusData>, } #[derive(Serialize, Deserialize, Debug)] struct DictionaryInfo { dictionary_id: String, service_id: String, item_key: String, item_value: String, } /// The entry point for your application. /// /// This function is triggered when y...
PopStatusResponse
identifier_name
main.rs
//! Default Compute@Edge template program. use fastly::http::{header, HeaderValue, Method, StatusCode}; use fastly::{mime, Dictionary, Error, Request, Response}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// The name of a backend server associated with this service. /// /// This should be ch...
group: pop.group.to_string(), shield: shield.to_string(), status, } }) .collect(); let pop_status_response: PopStatusResponse = PopStatusResponse { current_pop, ...
latitude: pop.coordinates.latitude, longitude: pop.coordinates.longitude,
random_line_split
1-built-in-function.py
# Python Built-in Function # The Python interpreter has a number of functions that are always available for use. These functions are called built-in functions. For example, print() function prints the given object to the standard output device (screen) or to the text stream file. # !MAP() # ...
# zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. # Let's see it in action in some examples: # Examples # In [1]: # x = [1,2,3] # y = [4,5,6] # # Zip the lists together # list(zip(x,y)) # Out[1]: # [(1, 4), (2, 5), (3, 6)] # Note...
# yield tuple(result)
random_line_split
merge_registry_pr.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
(prompt): result = raw_input("\n%s (y/n): " % prompt) if result.lower() != "y": fail("Okay, exiting") def clean_up(): print("Restoring head pointer to %s" % original_head) run_cmd("git checkout %s" % original_head) branches = run_cmd("git branch").replace(" ", "").split("\n") for bra...
continue_maybe
identifier_name
merge_registry_pr.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
try: run_cmd(['git', 'merge', pr_branch_name, '--squash']) except Exception as e: msg = "Error merging: %s\nWould you like to manually fix-up this merge?" % e continue_maybe(msg) msg = "Okay, please fix any conflicts and 'git add' conflicting files... Finished?" continue_...
had_conflicts = False
random_line_split
merge_registry_pr.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
merge_message_flags += ["-m", close_line] if should_list_commits: merge_message_flags += ["-m", "\n".join(commits)] run_cmd(['git', 'commit', '--author="%s"' % primary_author] + merge_message_flags) result = raw_input("Merge complete (local ref %s). Push to %s? (y/n)" % ...
close_line += " and squashes the following commits:"
conditional_block
merge_registry_pr.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
def run_cmd(cmd): print(cmd) try: if isinstance(cmd, list): return subprocess.check_output(cmd) else: return subprocess.check_output(cmd.split(" ")) except subprocess.CalledProcessError as e: print("CallProcessError occurred. More information for process is...
print(msg) clean_up() sys.exit(-1)
identifier_body
spike_generators.rs
//! This module represents neurons, generalized as "spike generators." To //! support a wider range of abstractions, the input neurons are divided into //! discrete and continuous implementations. /// The general trait encapsulating a spike generator that has an output voltage /// V. pub trait SpikeGenerator<V> { ...
} impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V> where // TODO: alias this as a trait? T: From<si::Second<f64>> + Copy + PartialOrd<T> + std::ops::AddAssign + std::ops::Sub<Output = T> + std::ops::Neg<Output = T>, ...
{ if self.did_spike() { self.spike_voltage.into() } else { (0.0 * si::V).into() } }
identifier_body
spike_generators.rs
//! This module represents neurons, generalized as "spike generators." To //! support a wider range of abstractions, the input neurons are divided into //! discrete and continuous implementations. /// The general trait encapsulating a spike generator that has an output voltage /// V. pub trait SpikeGenerator<V> { ...
<'a>( slot_starts_to_rate: &'a mut Vec<(T, i32)>, ) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> { slot_starts_to_rate.sort_unstable_by(|a, b| { let (t1, r1) = a; let (t2, r2) = b; match t1.partial_cmp(t2) { Option::None |...
rate_fn_of_times
identifier_name
spike_generators.rs
//! This module represents neurons, generalized as "spike generators." To //! support a wider range of abstractions, the input neurons are divided into //! discrete and continuous implementations. /// The general trait encapsulating a spike generator that has an output voltage /// V. pub trait SpikeGenerator<V> { ...
} } impl<T, V> InputSpikeGenerator<V, T> for SpikeAtTimes<T, V> where // TODO: alias this as a trait? T: From<si::Second<f64>> + Copy + PartialOrd<T> + std::ops::AddAssign + std::ops::Sub<Output = T> + std::ops::Neg<Output...
{ (0.0 * si::V).into() }
conditional_block
spike_generators.rs
//! This module represents neurons, generalized as "spike generators." To //! support a wider range of abstractions, the input neurons are divided into //! discrete and continuous implementations. /// The general trait encapsulating a spike generator that has an output voltage /// V. pub trait SpikeGenerator<V> { ...
) -> Box<dyn Fn(T) -> Option<(i32, T)> + 'a> { slot_starts_to_rate.sort_unstable_by(|a, b| { let (t1, r1) = a; let (t2, r2) = b; match t1.partial_cmp(t2) { Option::None | Option::Some(Ordering::Equal) => r1.cmp(r2), ...
slot_starts_to_rate: &'a mut Vec<(T, i32)>,
random_line_split
utils.ts
import crypto from 'crypto' import { writeHeapSnapshot } from 'v8' import { wait } from 'streamr-test-utils' import { providers, Wallet } from 'ethers' import { PublishRequest } from 'streamr-client-protocol' import LeakDetector from 'jest-leak-detector' import { pTimeout, counterId, CounterId, AggregatedError, pLimi...
export function addAfterFn() { const afterFns: any[] = [] afterEach(async () => { const fns = afterFns.slice() afterFns.length = 0 // @ts-expect-error AggregatedError.throwAllSettled(await Promise.allSettled(fns.map((fn) => fn()))) }) return (fn: any) => { afterF...
const addAfter = addAfterFn() return (...args: Parameters<typeof setTimeout>) => { const t = setTimeout(...args) addAfter(() => { clearTimeout(t) }) return t } }
identifier_body
utils.ts
import crypto from 'crypto' import { writeHeapSnapshot } from 'v8' import { wait } from 'streamr-test-utils' import { providers, Wallet } from 'ethers' import { PublishRequest } from 'streamr-client-protocol' import LeakDetector from 'jest-leak-detector' import { pTimeout, counterId, CounterId, AggregatedError, pLimi...
/* eslint-disable no-await-in-loop */ return async (publishRequest: any, opts = {}) => { const { streamId, streamPartition = 0, interval = 500, timeout = 10000, count = 100, messageMatchFn = defaultMessageMatchFn } = validat...
return JSON.stringify(msgGot.content) === JSON.stringify(msgTarget.streamMessage.getParsedContent()) } export function getWaitForStorage(client: StreamrClient, defaultOpts = {}) {
random_line_split
utils.ts
import crypto from 'crypto' import { writeHeapSnapshot } from 'v8' import { wait } from 'streamr-test-utils' import { providers, Wallet } from 'ethers' import { PublishRequest } from 'streamr-client-protocol' import LeakDetector from 'jest-leak-detector' import { pTimeout, counterId, CounterId, AggregatedError, pLimi...
{ const leaks = await this.getLeaks() if (leaks.length) { throw new Error(format('Leaking %d of %d items: %o', leaks.length, this.leakDetectors.size, leaks)) } } clear() { this.leakDetectors.clear() } }
eckNoLeaks()
identifier_name
utils.ts
import crypto from 'crypto' import { writeHeapSnapshot } from 'v8' import { wait } from 'streamr-test-utils' import { providers, Wallet } from 'ethers' import { PublishRequest } from 'streamr-client-protocol' import LeakDetector from 'jest-leak-detector' import { pTimeout, counterId, CounterId, AggregatedError, pLimi...
testDebugRoot('heap snapshot >>') const value = writeHeapSnapshot() testDebugRoot('heap snapshot <<', value) return value } const testUtilsCounter = CounterId('test/utils') export class LeaksDetector { leakDetectors: Map<string, LeakDetector> = new Map() private counter = CounterId(testUtilsCou...
return '' }
conditional_block
ask_plan.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: ask_plan.proto /* Package sonm is a generated protocol buffer package. It is generated from these files: ask_plan.proto benchmarks.proto bigint.proto capabilities.proto container.proto dwh.proto insonmnia.proto marketplace.proto net.proto node.prot...
func (m *AskPlanNetwork) GetOverlay() bool { if m != nil { return m.Overlay } return false } func (m *AskPlanNetwork) GetOutbound() bool { if m != nil { return m.Outbound } return false } func (m *AskPlanNetwork) GetIncoming() bool { if m != nil { return m.Incoming } return false } type AskPlanResour...
return nil }
random_line_split
ask_plan.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: ask_plan.proto /* Package sonm is a generated protocol buffer package. It is generated from these files: ask_plan.proto benchmarks.proto bigint.proto capabilities.proto container.proto dwh.proto insonmnia.proto marketplace.proto net.proto node.prot...
() string { return proto.CompactTextString(m) } func (*AskPlan) ProtoMessage() {} func (*AskPlan) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *AskPlan) GetID() string { if m != nil { return m.ID } return "" } func (m *AskPlan) GetOrderID() *BigInt { if m !=...
String
identifier_name
ask_plan.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: ask_plan.proto /* Package sonm is a generated protocol buffer package. It is generated from these files: ask_plan.proto benchmarks.proto bigint.proto capabilities.proto container.proto dwh.proto insonmnia.proto marketplace.proto net.proto node.prot...
func (*AskPlanStorage) ProtoMessage() {} func (*AskPlanStorage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *AskPlanStorage) GetSize() *DataSize { if m != nil { return m.Size } return nil } type AskPlanNetwork struct { ThroughputIn *DataSizeRate `protobuf:"bytes,1,o...
{ return proto.CompactTextString(m) }
identifier_body
ask_plan.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: ask_plan.proto /* Package sonm is a generated protocol buffer package. It is generated from these files: ask_plan.proto benchmarks.proto bigint.proto capabilities.proto container.proto dwh.proto insonmnia.proto marketplace.proto net.proto node.prot...
return IdentityLevel_ANONYMOUS } func (m *AskPlan) GetTag() []byte { if m != nil { return m.Tag } return nil } func (m *AskPlan) GetResources() *AskPlanResources { if m != nil { return m.Resources } return nil } func (m *AskPlan) GetStatus() AskPlan_Status { if m != nil { return m.Status } return As...
{ return m.Identity }
conditional_block
log.py
# # Copyright (c) 2018 Two Sigma Open Source, LLC # # 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, m...
(self): self._logfile = None self._logfilename = None self._verbose = False self._attrs = None self._verbose_attrs = None @staticmethod def _open_if_needed(filename): if isinstance(filename, (str, bytes)): return open(filename, 'w') else: ...
__init__
identifier_name
log.py
# # Copyright (c) 2018 Two Sigma Open Source, LLC # # 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, m...
@property def logfilename(self): return os.environ.get('MARBLES_LOGFILE', self._logfilename) @property def attrs(self): try: return os.environ['MARBLES_TEST_CASE_ATTRS'].split(',') except KeyError: return self._attrs or () @property def verbose...
if self._logfile: return self._logfile if self.logfilename: self._logfile = self._open_if_needed(self.logfilename) return self._logfile
identifier_body
log.py
# # Copyright (c) 2018 Two Sigma Open Source, LLC # # 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, m...
other attributes of interest specified by the test author. The captured information includes the assertion's args and kwargs, msg, note, local variables (for failed assertions, and also for passing assertions if verbose logging is turned on), and the result of the assertion. Configuration is handled via the environme...
assertion called. If configured, the :data:`marbles.core.log.logger` will log a json object for each assertion and its success or failure, as well as any
random_line_split
log.py
# # Copyright (c) 2018 Two Sigma Open Source, LLC # # 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, m...
else: return verbose or () def _log_assertion(self, case, assertion, args, kwargs, msg, note, *exc_info): if not self.log_enabled: return now = datetime.datetime.now() locals_, module, filename, lineno = _stack.get_stack_info() ...
return verbose_attrs
conditional_block
fs.rs
use rlua::prelude::*; use std::{ sync::Arc, env, fs::{self, OpenOptions}, io::{self, SeekFrom, prelude::*}, path::Path }; use serde_json; use rlua_serde; use crate::bindings::system::LuaMetadata; use regex::Regex; //TODO: Move to having a common interface so IO can share the same binding pub struct...
#[cfg(test)] mod tests { use super::*; #[test] fn lua_fs () { let lua = Lua::new(); init(&lua).unwrap(); lua.exec::<_, ()>(r#" for entry in fs.entries("./") do local md = fs.metadata(entry) print(md.type .. ": " .. entry) en...
{ let path = src.as_ref(); if !src.as_ref().exists() { return Err(io::Error::from(io::ErrorKind::NotFound)); } if !dest.as_ref().exists() { fs::create_dir(&dest)?; } for entry in path.read_dir()? { let src = entry.map(|e| e.path())?; let src_name = match src.file_n...
identifier_body
fs.rs
use rlua::prelude::*; use std::{ sync::Arc, env, fs::{self, OpenOptions}, io::{self, SeekFrom, prelude::*}, path::Path }; use serde_json; use rlua_serde; use crate::bindings::system::LuaMetadata; use regex::Regex; //TODO: Move to having a common interface so IO can share the same binding pub struct...
<A: AsRef<Path>, B: AsRef<Path>>(src: A, dest: B) -> io::Result<()> { let path = src.as_ref(); if !src.as_ref().exists() { return Err(io::Error::from(io::ErrorKind::NotFound)); } if !dest.as_ref().exists() { fs::create_dir(&dest)?; } for entry in path.read_dir()? { let src...
recursive_copy
identifier_name
fs.rs
use rlua::prelude::*; use std::{ sync::Arc, env, fs::{self, OpenOptions}, io::{self, SeekFrom, prelude::*}, path::Path }; use serde_json; use rlua_serde; use crate::bindings::system::LuaMetadata; use regex::Regex; //TODO: Move to having a common interface so IO can share the same binding pub struct...
fs::OpenOptions::new() .write(true) .create(true) .open(&path) .map(|_| ()) .map_err(LuaError::external) })?)?; module.set("copy_file", lua.create_function(|_, (src, dest): (String, String)| { copy_file(src, dest) })?)?; // This binding has ...
//TODO: Rename to something suitable other than touch //Probably deprecate for path:create_file module.set("touch", lua.create_function( |_, path: String| {
random_line_split
centrify_desktopapp.go
package centrify import ( "errors" "github.com/centrify/terraform-provider/cloud-golang-sdk/restapi" ) // DesktopApp - Encapsulates a single Generic DesktopApp type DesktopApp struct { vaultObject TemplateName string `json:"TemplateName,omitempty" schema:"template_name,omitempty"` Deskto...
() (map[string]interface{}, error) { query := "SELECT * FROM Application WHERE 1=1 AND AppType='Desktop'" if o.Name != "" { query += " AND Name='" + o.Name + "'" } return queryVaultObject(o.client, query) } /* Fetch desktop app https://developer.centrify.com/reference#post_saasmanage-getapplication Request bo...
Query
identifier_name
centrify_desktopapp.go
package centrify import ( "errors" "github.com/centrify/terraform-provider/cloud-golang-sdk/restapi" ) // DesktopApp - Encapsulates a single Generic DesktopApp type DesktopApp struct { vaultObject TemplateName string `json:"TemplateName,omitempty" schema:"template_name,omitempty"` Deskto...
"Version": 1, "IndexingVersion": 1 }, "Description": "This template allows you to provide single sign-on to a custom desktop application.", "DesktopAppType": "CommandLine", "AuthRules": { "_UniqueKey": "Condition", "_Value": [], "Enabled": true, "_Type": "RowSet" }, "AppType": ...
"RemoteDesktopUser": "shared_account (demo.lab)", "CertificateSubjectName": "CN=Centrify Customer Application Signing Certificate", "ParentDisplayName": null, "_metadata": {
random_line_split
centrify_desktopapp.go
package centrify import ( "errors" "github.com/centrify/terraform-provider/cloud-golang-sdk/restapi" ) // DesktopApp - Encapsulates a single Generic DesktopApp type DesktopApp struct { vaultObject TemplateName string `json:"TemplateName,omitempty" schema:"template_name,omitempty"` Deskto...
if !resp.Success { return errors.New(resp.Message) } fillWithMap(o, resp.Result) LogD.Printf("Filled object: %+v", o) return nil } // Create function creates a new DesktopApp and returns a map that contains creation result func (o *DesktopApp) Create() (*restapi.SliceResponse, error) { var queryArg = make(...
{ return err }
conditional_block
centrify_desktopapp.go
package centrify import ( "errors" "github.com/centrify/terraform-provider/cloud-golang-sdk/restapi" ) // DesktopApp - Encapsulates a single Generic DesktopApp type DesktopApp struct { vaultObject TemplateName string `json:"TemplateName,omitempty" schema:"template_name,omitempty"` Deskto...
// Read function fetches a DesktopApp from source, including attribute values. Returns error if any func (o *DesktopApp) Read() error { if o.ID == "" { return errors.New("error: ID is empty") } var queryArg = make(map[string]interface{}) queryArg["_RowKey"] = o.ID // Attempt to read from an upstream API resp...
{ s := DesktopApp{} s.client = c s.apiRead = "/SaasManage/GetApplication" s.apiCreate = "/SaasManage/ImportAppFromTemplate" s.apiDelete = "/SaasManage/DeleteApplication" s.apiUpdate = "/SaasManage/UpdateApplicationDE" s.apiPermissions = "/SaasManage/SetApplicationPermissions" return &s }
identifier_body
call.component.ts
import { Component, OnInit, ViewChild, ElementRef, OnDestroy, Output, HostListener, AfterViewInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import Swal from 'sweetalert2'; import { EventEmitter } from '@angular/core'; import { environment } from 'src/environments/environme...
} this.peer.on('connection',(conn)=>{ conn.on('data',async (data)=>{ if(data.action){ this.finLlamadaMedico.emit(); this.finLlamadaPaciente.emit(); this.inCall = false; return; } if(data.cancelCall){ Swal.close({value:false}); ...
// secure:true });
random_line_split
call.component.ts
import { Component, OnInit, ViewChild, ElementRef, OnDestroy, Output, HostListener, AfterViewInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import Swal from 'sweetalert2'; import { EventEmitter } from '@angular/core'; import { environment } from 'src/environments/environme...
async confirm():Promise<boolean>{ let {dismiss} = await Swal.fire({ title:'Seguro desea salir?', text:'Abandonará una llamada', showCancelButton:true, cancelButtonText:'Permanecer aquí', confirmButtonText:'Seguro que quiero salir', }) return !dismiss } enviarMensaje(){...
event.returnValue = true; this.cierreVentana.emit(); this.colgar(); }
identifier_body
call.component.ts
import { Component, OnInit, ViewChild, ElementRef, OnDestroy, Output, HostListener, AfterViewInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import Swal from 'sweetalert2'; import { EventEmitter } from '@angular/core'; import { environment } from 'src/environments/environme...
if(data.call){ const audio = new Audio(); audio.src = "https://notificationsounds.com/notification-sounds/goes-without-saying-608/download/mp3"; audio.play(); audio.onended = ()=>{ if(!this.conn){ audio.currentTime = 0; audio.play(...
{ this.key = data.key; this.markAsConnected.emit(data.csc); this.conn = this.peer.connect(data.key); return; }
conditional_block
call.component.ts
import { Component, OnInit, ViewChild, ElementRef, OnDestroy, Output, HostListener, AfterViewInit, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import Swal from 'sweetalert2'; import { EventEmitter } from '@angular/core'; import { environment } from 'src/environments/environme...
const canvas = document.createElement('canvas'); canvas.width = this.video.nativeElement.videoWidth; canvas.height = this.video.nativeElement.videoHeight; canvas.getContext("2d").drawImage(this.video.nativeElement,0,0); let imgUrl; canvas.toBlob(async (blob)=>{ imgUrl = window.URL.createOb...
eCapture(){
identifier_name
model.py
#!/usr/bin/env python from __future__ import division import sys import math logs = sys.stderr from collections import defaultdict import time from mytime import Mytime import gflags as flags FLAGS=flags.FLAGS flags.DEFINE_string("weights", None, "weights file (feature instances and weights)", short_name="w") flag...
def count_knowns_from_train(self, trainfile, devfile): '''used in training''' print >> logs, "counting word freqs from %s, unktag=%s" % (trainfile, self.unktag) stime = time.time() words = defaultdict(int) for i, line in enumerate(open(trainfile)): for...
self.knowns = set() self.unk = FLAGS.unk self.unktag = FLAGS.unktag self.unkdel = FLAGS.unkdel assert not (self.unkdel and self.unktag), "UNKDEL and UNKTAG can't be both true" if FLAGS.svector: # now it is known global svector try: svector...
identifier_body
model.py
#!/usr/bin/env python from __future__ import division import sys import math logs = sys.stderr from collections import defaultdict import time from mytime import Mytime import gflags as flags FLAGS=flags.FLAGS flags.DEFINE_string("weights", None, "weights file (feature instances and weights)", short_name="w") flag...
return fv @staticmethod def static_eval((q0w, q0t), (q1w, q1t), (s0w, s0t), (s1w, s1t), (s2w, s2t), (s0lct, s0rct), (s1lct, s1rct)): return ["q0t=%s" % (q0t), "q0w-q0t=%s|%s" % (q0w, q0t), "q0w=%s" % (q0w), "s0t-q0t-q1t=%s|%s|%s" % (s0t, q0t, q1t...
del fv[f]
conditional_block
model.py
#!/usr/bin/env python from __future__ import division import sys import math logs = sys.stderr from collections import defaultdict import time from mytime import Mytime import gflags as flags FLAGS=flags.FLAGS flags.DEFINE_string("weights", None, "weights file (feature instances and weights)", short_name="w") flag...
## for freq in sorted(freqs, reverse=True): ## print >> logs, freq, len(freqs[freq]), " ".join(sorted(freqs[freq])) ## print >> logs self.knowns = set() for word, freq in words.items(): if freq > self.unk: self.knowns.add(word) ...
print >> logs, "=0", len(devunk0), " ".join(sorted(devunk0)) ## freqs = defaultdict(list) ## for word, freq in words.items(): ## freqs[freq].append(word)
random_line_split
model.py
#!/usr/bin/env python from __future__ import division import sys import math logs = sys.stderr from collections import defaultdict import time from mytime import Mytime import gflags as flags FLAGS=flags.FLAGS flags.DEFINE_string("weights", None, "weights file (feature instances and weights)", short_name="w") flag...
(self, trainfile, devfile): '''used in training''' print >> logs, "counting word freqs from %s, unktag=%s" % (trainfile, self.unktag) stime = time.time() words = defaultdict(int) for i, line in enumerate(open(trainfile)): for word in line.split(): ...
count_knowns_from_train
identifier_name
resolver.rs
use std::collections::HashMap; use std::rc::Rc; use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut}; use crate::environment::Environment; use crate::error::Reporter; use crate::token::Position; #[derive(Clone, PartialEq)] pub enum FunctionKind { None, Function, // TODO: add more kinds supposedly...
// exit the current scope pub fn end_scope(&mut self) { self.scopes.pop(); } // declare a variable in the current scope pub fn declare(&mut self, ident: &Identifier) { // try to access the top element of the stack match self.scopes.last_mut() { // if empty, do ...
{ self.scopes.push(HashMap::new()); }
identifier_body
resolver.rs
use std::collections::HashMap; use std::rc::Rc; use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut}; use crate::environment::Environment; use crate::error::Reporter; use crate::token::Position; #[derive(Clone, PartialEq)] pub enum FunctionKind { None, Function, // TODO: add more kinds supposedly...
(&mut self, ident: &Identifier) { // try to access the top element of the stack match self.scopes.last_mut() { // if empty, do nothing (don't worry about global vars) None => (), Some(scope) => { // check if this has already been declared ...
declare
identifier_name
resolver.rs
use std::collections::HashMap; use std::rc::Rc; use crate::ast::{Expr, Identifier, Literal, Stmt, VisitorMut}; use crate::environment::Environment; use crate::error::Reporter; use crate::token::Position; #[derive(Clone, PartialEq)] pub enum FunctionKind { None, Function, // TODO: add more kinds supposedly...
// variable binding is split into 2 steps - declaring and defining self.declare(name); self.visit_expr(expr, env)?; self.define(name); } Stmt::While(ref mut condition_expr, ref mut body) => { // resolve the condition...
Stmt::Var(name, ref mut expr) => { // this adds a new entry to the innermost scope
random_line_split
list-view.js
/** * @created 2014-3-12 19:27:29 */ define(['App', 'tpl!app/oms/settle/total-account-detail/list/templates/table-ct.tpl', 'tpl!app/oms/settle/total-account-detail/list/templates/total-account-detail.tpl', 'i18n!app/oms/common/nls/settle', 'jquery.jqGrid', 'jquery.validate', 'bootstrap-datepicker' ], function(A...
} if(valid){ $($(e.target).closest('button')).addClass('disabled').find('span').html("<i class='icon-ok'></i>&nbsp; 正在提交..."); me.ajaxRequest(me.getRequestDateSelect(roleGird), this, roleGird); } } }, { html: "<i class='icon-remove'></i>&nbsp; 取消", "class" : ...
var $form = $('form.form-total-account-detall'); var validator = $form.validate(); var valid = true; if(validator && !validator.form()){ valid = false;
random_line_split
list-view.js
/** * @created 2014-3-12 19:27:29 */ define(['App', 'tpl!app/oms/settle/total-account-detail/list/templates/table-ct.tpl', 'tpl!app/oms/settle/total-account-detail/list/templates/total-account-detail.tpl', 'i18n!app/oms/common/nls/settle', 'jquery.jqGrid', 'jquery.validate', 'bootstrap-datepicker' ], function(A...
end('付款账户'); me.ajaxGetAccount(form, value, $acctSelect); } else if (value === '2') { $acctSelect.attr('name', 'inAcctId'); $caption.empty().append('收款账户'); me.ajaxGetAccount(form, value, $acctSelect); } }); $select.trigger('change')...
me.ajaxGetAccount(form, value, $acctSelect); } else if (value === '1') { $acctSelect.attr('name', 'outAcctId'); $caption.empty().app
conditional_block
list-view.js
/** * @created 2014-3-12 19:27:29 */ define(['App', 'tpl!app/oms/settle/total-account-detail/list/templates/table-ct.tpl', 'tpl!app/oms/settle/total-account-detail/list/templates/total-account-detail.tpl', 'i18n!app/oms/common/nls/settle', 'jquery.jqGrid', 'jquery.validate', 'bootstrap-datepicker' ], function(A...
identifier_body
list-view.js
/** * @created 2014-3-12 19:27:29 */ define(['App', 'tpl!app/oms/settle/total-account-detail/list/templates/table-ct.tpl', 'tpl!app/oms/settle/total-account-detail/list/templates/total-account-detail.tpl', 'i18n!app/oms/common/nls/settle', 'jquery.jqGrid', 'jquery.validate', 'bootstrap-datepicker' ], function(A...
identifier_name
ACPF_ExportMuRaster.py
# SSURGO_ExportMuRaster.py # # Convert MUPOLYGON featureclass to raster for the specified SSURGO geodatabase. # By default any small NoData areas (< 5000 sq meters) will be filled using # the Majority value. # # Input mupolygon featureclass must have a projected coordinate system or it will skip. # Input databas...
(outputRaster): # For no apparent reason, ArcGIS sometimes fails to build statistics. Might work one # time and then the next time it may fail without any error message. # try: #PrintMsg(" \n\tChecking raster statistics", 0) for propType in ['MINIMUM', 'MAXIMUM', 'MEAN', 'STD']: ...
CheckStatistics
identifier_name
ACPF_ExportMuRaster.py
# SSURGO_ExportMuRaster.py # # Convert MUPOLYGON featureclass to raster for the specified SSURGO geodatabase. # By default any small NoData areas (< 5000 sq meters) will be filled using # the Majority value. # # Input mupolygon featureclass must have a projected coordinate system or it will skip. # Input databas...
## =================================================================================== def CheckSpatialReference(muPolygon): # Make sure that the coordinate system is projected and units are meters try: desc = arcpy.Describe(muPolygon) inputSR = desc.spatialReference if input...
try: PrintMsg("\tUpdating metadata...") arcpy.SetProgressor("default", "Updating metadata") # Set metadata translator file dInstall = arcpy.GetInstallInfo() installPath = dInstall["InstallDir"] prod = r"Metadata/Translator/ARCGIS2FGDC.xml" mdTranslator = ...
identifier_body