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 |
|---|---|---|---|---|
zkdevice.py | '''
This script will do auto-check in/out for ZMM100 fingerprint access control
device by ZKSoftware.
At my office, the manager uses an application to load data from the
fingerprint device. After he loads data, log in device's database is cleared.
So in my case, I write this script to automate checking in/out everyday... | (uid, start, end, status, late=False):
start_date = datetime.datetime.strptime(start, '%d/%m/%Y')
end_date = datetime.datetime.strptime(end, '%d/%m/%Y')
day_count = end_date - start_date
day_count = day_count.days + 1
for date in (start_date + datetime.timedelta(i) for i in range(day_count)):
... | add_logs | identifier_name |
zkdevice.py | '''
This script will do auto-check in/out for ZMM100 fingerprint access control
device by ZKSoftware.
At my office, the manager uses an application to load data from the
fingerprint device. After he loads data, log in device's database is cleared.
So in my case, I write this script to automate checking in/out everyday... |
def check_log_row(log_row):
'''
Each day must have exactly 2 logs.
One for checking in, before 8:00:00
One for checking out, after 17:00:00
Return True if satisfies all conditions, else False
'''
in_time = datetime.time(8, 0, 0)
out_time = datetime.time(17, 0, 0)
log_date = datet... | '''
Pretty print a log row
log row format: (ID, User_PIN, Verify_Type, Verify_Time, Status)
'''
id, uid, verify_type, verify_time, status = log_row
if status == 1:
status = 'Check out'
elif status == 0:
status = 'Check in'
print('{}. {} {} at {}'.format(id, uid, status, veri... | identifier_body |
obj.rs | //! Object file builder.
//!
//! Creates ELF image based on `Compilation` information. The ELF contains
//! functions and trampolines in the ".text" section. It also contains all
//! relocation records for the linking stage. If DWARF sections exist, their
//! content will be written as well.
//!
//! The object file has... | ///
/// Returns the symbol associated with the function as well as the range
/// that the function resides within the text section.
pub fn append_func(
&mut self,
name: &str,
compiled_func: &'a CompiledFunction<impl CompiledFuncEnv>,
resolve_reloc_target: impl Fn(FuncInde... | /// within `CompiledFunction` and the return value must be an index where
/// the target will be defined by the `n`th call to `append_func`. | random_line_split |
obj.rs | //! Object file builder.
//!
//! Creates ELF image based on `Compilation` information. The ELF contains
//! functions and trampolines in the ".text" section. It also contains all
//! relocation records for the linking stage. If DWARF sections exist, their
//! content will be written as well.
//!
//! The object file has... |
/// Forces "veneers" to be used for inter-function calls in the text
/// section which means that in-bounds optimized addresses are never used.
///
/// This is only useful for debugging cranelift itself and typically this
/// option is disabled.
pub fn force_veneers(&mut self) {
self.t... | {
let body = compiled_func.buffer.data();
let alignment = compiled_func.alignment;
let body_len = body.len() as u64;
let off = self
.text
.append(true, &body, alignment, &mut self.ctrl_plane);
let symbol_id = self.obj.add_symbol(Symbol {
name:... | identifier_body |
obj.rs | //! Object file builder.
//!
//! Creates ELF image based on `Compilation` information. The ELF contains
//! functions and trampolines in the ".text" section. It also contains all
//! relocation records for the linking stage. If DWARF sections exist, their
//! content will be written as well.
//!
//! The object file has... | (&mut self) {
self.text.force_veneers();
}
/// Appends the specified amount of bytes of padding into the text section.
///
/// This is only useful when fuzzing and/or debugging cranelift itself and
/// for production scenarios `padding` is 0 and this function does nothing.
pub fn append... | force_veneers | identifier_name |
obj.rs | //! Object file builder.
//!
//! Creates ELF image based on `Compilation` information. The ELF contains
//! functions and trampolines in the ".text" section. It also contains all
//! relocation records for the linking stage. If DWARF sections exist, their
//! content will be written as well.
//!
//! The object file has... |
for r in compiled_func.relocations() {
match r.reloc_target {
// Relocations against user-defined functions means that this is
// a relocation against a module-local function, typically a
// call between functions. The `text` field is given priority ... | {
self.unwind_info.push(off, body_len, info);
} | conditional_block |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... | <F: IntoFuture> {
action: F,
inner: Either<F::Future, Delay>,
options: BackoffRetryBuilder,
}
impl<F> Future for BackoffRetry<F>
where
F: IntoFuture + Clone,
{
type Item = F::Item;
type Error = Option<F::Error>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
... | BackoffRetry | identifier_name |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... | if self.interval > 0 {
let s_interval = self.interval as f64 / 1000f64;
info!(self.log, "stats";
"egress" => format!("{:2}", egress / s_interval),
"ingress" => format!("{:2}", ingress / s_interval),
"ingress-m" => format!("{:2}", ingress_m / s_interva... | add_metric!(INGRESS_METRICS, ingress_m, "ingress-metric");
add_metric!(AGG_ERRORS, agr_errors, "agg-error");
add_metric!(PARSE_ERRORS, parse_errors, "parse-error");
add_metric!(PEER_ERRORS, peer_errors, "peer-error");
add_metric!(DROPS, drops, "drop"); | random_line_split |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... |
}
#[cfg(test)]
pub(crate) fn new_test_graphite_name(s: &'static str) -> MetricName {
let mut intermediate = Vec::new();
intermediate.resize(9000, 0u8);
let mode = bioyino_metric::name::TagFormat::Graphite;
MetricName::new(s.into(), mode, &mut intermediate).unwrap()
}
// A future to send own stats. N... | {
let is_leader = IS_LEADER.load(Ordering::SeqCst);
if is_leader != acquired {
warn!(log, "leader state change: {} -> {}", is_leader, acquired);
}
IS_LEADER.store(acquired, Ordering::SeqCst);
} | conditional_block |
util.rs | use libc;
use std::ffi::CStr;
use std::io;
use std::net::SocketAddr;
use std::net::TcpStream as StdTcpStream;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use bytes::{BufMut, BytesMut};
use futures::future::Either;
use futures::sync::mpsc::Sender;
use futures::{Async, Future, IntoFuture, Poll, ... |
}
impl BackoffRetryBuilder {
pub fn spawn<F>(self, action: F) -> BackoffRetry<F>
where
F: IntoFuture + Clone,
{
let inner = Either::A(action.clone().into_future());
BackoffRetry { action, inner, options: self }
}
}
/// TCP client that is able to reconnect with customizable set... | {
Self {
delay: 500,
delay_mul: 2f32,
delay_max: 10000,
retries: 25,
}
} | identifier_body |
listing.rs | use actix_web::http::StatusCode;
use actix_web::{fs, http, Body, FromRequest, HttpRequest, HttpResponse, Query, Result};
use bytesize::ByteSize;
use futures::stream::once;
use htmlescape::encode_minimal as escape_html_entity;
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
use serde::Deserialize;
use s... | (&self) -> bool {
self.entry_type == EntryType::Directory
}
/// Returns whether the entry is a file
pub fn is_file(&self) -> bool {
self.entry_type == EntryType::File
}
/// Returns whether the entry is a symlink
pub fn is_symlink(&self) -> bool {
self.entry_type == Entr... | is_dir | identifier_name |
listing.rs | use actix_web::http::StatusCode;
use actix_web::{fs, http, Body, FromRequest, HttpRequest, HttpResponse, Query, Result};
use bytesize::ByteSize;
use futures::stream::once;
use htmlescape::encode_minimal as escape_html_entity;
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
use serde::Deserialize;
use s... | /// Type of the entry
pub entry_type: EntryType,
/// URL of the entry
pub link: String,
/// Size in byte of the entry. Only available for EntryType::File
pub size: Option<bytesize::ByteSize>,
/// Last modification date
pub last_modification_date: Option<SystemTime>,
}
impl Entry {
... | /// Entry
pub struct Entry {
/// Name of the entry
pub name: String,
| random_line_split |
masking.py | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
return MaskingInfo(mask_labels, labels)
# @masking_registry.register_with_multiple_names("plm", "permutation")
# class PermutationLanguageModeling(MaskSequence):
# pass
#
#
# @masking_registry.register_with_multiple_names("rtd", "replacement")
# class ReplacementLanguageModeling(MaskSequence):
# pas... | if self.eval_on_last_item_seq_only:
last_item_sessions = tf.reduce_sum(non_padded_mask, axis=1) - 1
indices = tf.concat(
[
tf.expand_dims(rows_ids, 1),
tf.cast(tf.expand_dims(last_item_sessions, 1), tf.int64),
... | conditional_block |
masking.py | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | (self, item_ids: tf.Tensor, training=False) -> MaskingInfo:
"""
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
And the attributes of the class `mask_schema` and `masked_targets`
are u... | compute_masked_targets | identifier_name |
masking.py | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
def _compute_masked_targets(self, item_ids: tf.Tensor, training=False) -> MaskingInfo:
"""
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
Parameters
----------
item_ids... | super(MaskSequence, self).__init__(**kwargs)
self.padding_idx = padding_idx
self.eval_on_last_item_seq_only = eval_on_last_item_seq_only
self.mask_schema = None
self.masked_targets = None | identifier_body |
masking.py | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | """
Method to prepare masked labels based on the sequence of item ids.
It returns The true labels of masked positions and the related boolean mask.
Parameters
----------
item_ids: tf.Tensor
The sequence of input item ids used for deriving labels of
... | random_line_split | |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... | match *self {
AppError::RafxError(ref e) => e.fmt(fmt),
AppError::WinitError(ref e) => e.fmt(fmt),
}
}
}
impl From<RafxError> for AppError {
fn from(result: RafxError) -> Self {
AppError::RafxError(result)
}
}
impl From<winit::error::OsError> for AppError {
... | fn fmt(
&self,
fmt: &mut core::fmt::Formatter,
) -> core::fmt::Result { | random_line_split |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... |
}
if app_control.should_terminate_process() {
*control_flow = winit::event_loop::ControlFlow::Exit
}
});
}
}
| {} | conditional_block |
app.rs | //! Contains the main types a user needs to interact with to configure and run a skulpin app
use crate::skia_safe;
use crate::winit;
use super::app_control::AppControl;
use super::input_state::InputState;
use super::time_state::TimeState;
use super::util::PeriodicEvent;
use skulpin_renderer::LogicalSize;
use skulpin... | (result: winit::error::OsError) -> Self {
AppError::WinitError(result)
}
}
pub struct AppUpdateArgs<'a, 'b, 'c> {
pub app_control: &'a mut AppControl,
pub input_state: &'b InputState,
pub time_state: &'c TimeState,
}
pub struct AppDrawArgs<'a, 'b, 'c, 'd> {
pub app_control: &'a AppControl,... | from | identifier_name |
lds.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/api/v2/lds.proto
package envoy_api_v2
import (
context "context"
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
_ "github.com/datawire/ambassador/pkg/api/envoy/annotations"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "g... |
func _ListenerDiscoveryService_DeltaListeners_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(ListenerDiscoveryServiceServer).DeltaListeners(&listenerDiscoveryServiceDeltaListenersServer{stream})
}
type ListenerDiscoveryService_DeltaListenersServer interface {
Send(*DeltaDiscoveryResponse) e... | {
s.RegisterService(&_ListenerDiscoveryService_serviceDesc, srv)
} | identifier_body |
lds.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/api/v2/lds.proto
package envoy_api_v2
import (
context "context"
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
_ "github.com/datawire/ambassador/pkg/api/envoy/annotations"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "g... | l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowLds
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
br... | random_line_split | |
lds.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/api/v2/lds.proto
package envoy_api_v2
import (
context "context"
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
_ "github.com/datawire/ambassador/pkg/api/envoy/annotations"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "g... |
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowLds
}
if iNdEx >= l {
return 0, io.ErrU... | {
return 0, ErrIntOverflowLds
} | conditional_block |
lds.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/api/v2/lds.proto
package envoy_api_v2
import (
context "context"
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
_ "github.com/datawire/ambassador/pkg/api/envoy/annotations"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "g... | (b []byte) error {
return m.Unmarshal(b)
}
func (m *LdsDummy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_LdsDummy.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return... | XXX_Unmarshal | identifier_name |
chat.js | // pages/contact/contact.js
var util = require('../../utils/util.js')
const app = getApp();
var api = require('../../config/api.js');
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var SocketTask;
var ... | /**
* 获取聚焦
*/
focus: function(e) {
keyHeight = e.detail.height;
this.setData({
scrollHeight: (windowHeight - keyHeight) + 'px'
});
this.setData({
toView: 'msg-' + (msgList.length - 1),
inputBottom: keyHeight + 'px'
})
},
//失去聚焦(软键盘消失)
blur: function(e) {
this.s... | },
| random_line_split |
chat.js | // pages/contact/contact.js
var util = require('../../utils/util.js')
const app = getApp();
var api = require('../../config/api.js');
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var SocketTask;
var ... | wx.showToast({
title: "请授权登录后发布",
image: '../../images/hint1.png',
mask: true,
})
setTimeout(function() {
//要延时执行的代码
wx.navigateTo({
url: '../mine/mine',
})
}, 1000)
... | image: '../../images/hint1.png',
mask: true,
})
setTimeout(function () {
//要延时执行的代码
wx.navigateBack({
delta: 1
});
}, 1000)
}
that.setData({
myOpenId:... | conditional_block |
chat.js | // pages/contact/contact.js
var util = require('../../utils/util.js')
const app = getApp();
var api = require('../../config/api.js');
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var SocketTask;
var ... | = true;
msg.time = util.toWeiXinString(new Date(msg.createTime));
}
return msg;
} | ime));
}
} else {
msg.format | identifier_body |
chat.js | // pages/contact/contact.js
var util = require('../../utils/util.js')
const app = getApp();
var api = require('../../config/api.js');
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var SocketTask;
var ... | header: {
"Content-Type": "multipart/form-data",
'Authorization': token // 缓存中token信息
},
success: function (res) {
var data = JSON.parse(res.data);
if(data.status==200){
var msg = {
msgType: 2,
conten... | ile',
| identifier_name |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | {
pub linker_major_version: u8,
pub linker_minor_version: u8,
pub entry_table_offset: u16,
pub entry_table_size: u16,
pub crc: u32,
pub flags: NEFlags,
pub auto_data_segment_index: u16,
pub heap_size: u16,
pub stack_size: ... | NEHeader | identifier_name |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | min_code_swap_size: le_u16 >>
win_version_minor: le_u8 >>
win_version_major: le_u8 >>
(NEHeader {
linker_major_version,
linker_minor_version,
entry_table_offset,
entry_table_size,
crc,
flags: NEFlags::from_bits_truncate(flags),
auto_data_segment_index,
heap_size,
... | segment_thunk_offset: le_u16 >> | random_line_split |
neexe.rs | use bitflags::bitflags;
use byteorder::{ByteOrder, LE};
use custom_error::custom_error;
use crate::util::read_pascal_string;
use enum_primitive::*;
use nom::{apply, count, do_parse, le_u8, le_u16, le_u32, named, named_args, tag, take};
macro_rules! try_parse (
($result: expr, $error: expr) => (match $result {
Ok((_... | else {
NEResourcesIterator {
table: self.raw_header,
index: 0,
table_kind: NEResourceKind::Integer(0xffff),
offset_shift: 0,
block_index: 1,
block_len: 0,
finished: true
}
}
}
pub fn has_resource_table(&self) -> bool {
// In DIRAPI.DLL from Director for Windows, the resource ta... | {
NEResourcesIterator::new(&self.raw_header[self.header.resource_table_offset as usize..])
} | conditional_block |
query-builder-common.js | /**
* Show the tables as tree format at side menu in window,
* here we can Collapse and Expend the tables under "Table" title bar
* @author mahesh
*/
$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr(
'title', 'Collapse this branch');
$('.tree li.parent_li > span').on(
... | deleteTableFromExpressionCombo($(ui.draggable).find(".drag-table-title-bar").attr("tableName"));
$(ui.draggable).hide('scale', {
origin: ["top", "right"]
}, 300, function() {
$(this).remove();
});
}
});
}
/**
* Initialize t... | tolerance : "touch",
accept : ".table-column-list-container",
drop : function(event, ui) { | random_line_split |
query-builder-common.js | /**
* Show the tables as tree format at side menu in window,
* here we can Collapse and Expend the tables under "Table" title bar
* @author mahesh
*/
$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr(
'title', 'Collapse this branch');
$('.tree li.parent_li > span').on(
... | () {
$('#new-link-line').remove();
$(document).unbind('mousemove.link').unbind('click.link').unbind('keydown.link');
}
/**
* Load operators in select box
* @param results
*/
function loadOperatorsInSelectBox(results){
$(".pop-modal-content").find(".operators_select_box").each(function(){
$(this).dds... | endLinkMode | identifier_name |
query-builder-common.js | /**
* Show the tables as tree format at side menu in window,
* here we can Collapse and Expend the tables under "Table" title bar
* @author mahesh
*/
$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr(
'title', 'Collapse this branch');
$('.tree li.parent_li > span').on(
... | else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(
' > i').addClass('fa-minus-square')
.removeClass('fa-plus-square');
}
e.stopPropagation();
});
});
fetchAllTablesAjax(loadTables... | {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(
' > i').addClass('fa-plus-square')
.removeClass('fa-minus-square');
} | conditional_block |
query-builder-common.js | /**
* Show the tables as tree format at side menu in window,
* here we can Collapse and Expend the tables under "Table" title bar
* @author mahesh
*/
$(function() {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr(
'title', 'Collapse this branch');
$('.tree li.parent_li > span').on(
... |
var connections = [];
var connectionsId = [];
//connections.push(new $.connect('#PROD2CAT', '#PRODUKT', {leftLabel : 'Many', rightLabel: 'One'}));
/**
* Here we enable the drag and drop events for drag the tables and drop into drop area with list of columns
*/
function enableDNDEvents() {
var zIndex = 3;
$... | {
$(".pop-modal-content").find(".operators_select_box").each(function(){
$(this).ddslick({
data : results,
width : 170
});
});
} | identifier_body |
http.go | package main
import (
"encoding/json"
"fmt"
m "github.com/log22/MoviesCrawler"
"reflect"
"net/http"
"log"
"github.com/gorilla/mux"
"sync"
"os"
"path/filepath"
"os/exec"
"regexp"
"strings"
"errors" | )
// Request struct for Search POST
type SearchRequest struct {
Services []string
MovieName string
}
// Request struct for get downloads links POST
type DownloadLinksRequest struct {
Service string
Movie m.Movie
}
// Response struct for Search Request
type FoundMovies struct {
Service string
... | "time" | random_line_split |
http.go | package main
import (
"encoding/json"
"fmt"
m "github.com/log22/MoviesCrawler"
"reflect"
"net/http"
"log"
"github.com/gorilla/mux"
"sync"
"os"
"path/filepath"
"os/exec"
"regexp"
"strings"
"errors"
"time"
)
// Request struct for Search POST
type SearchRequest struct {
S... |
func StopTorrent(ip string, ID string) bool {
out, err := exec.Command("/usr/bin/transmission-remote", ip,"-t", ID, "-S").Output()
if err != nil {
log.Fatal(err)
return false
}
if strings.Contains(string(out), "Error") {
return false
} else {
return true
}
}
func ResumeTorrent(ip string, ID string) boo... | {
out, err := exec.Command("/usr/bin/transmission-remote", ip,"-a", magnetLink).Output()
if err != nil {
log.Fatal(err)
return false
}
if strings.Contains(string(out), "Error") {
return false
} else {
return true
}
} | identifier_body |
http.go | package main
import (
"encoding/json"
"fmt"
m "github.com/log22/MoviesCrawler"
"reflect"
"net/http"
"log"
"github.com/gorilla/mux"
"sync"
"os"
"path/filepath"
"os/exec"
"regexp"
"strings"
"errors"
"time"
)
// Request struct for Search POST
type SearchRequest struct {
S... | (w http.ResponseWriter, r *http.Request) {
// Set Header for Options
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
fmt.Printf("[%s] - Requested listServices\n", time.Now().Format("2006-01-02 15:04:05"))
var listServices []string
for key, ... | listServices | identifier_name |
http.go | package main
import (
"encoding/json"
"fmt"
m "github.com/log22/MoviesCrawler"
"reflect"
"net/http"
"log"
"github.com/gorilla/mux"
"sync"
"os"
"path/filepath"
"os/exec"
"regexp"
"strings"
"errors"
"time"
)
// Request struct for Search POST
type SearchRequest struct {
S... |
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
r... | {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
} | conditional_block |
gologs.go | package gologs
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
// DefaultCommandFormat specifies a log format might be more appropriate for a
// infrequently used command line program, where the name of the service is a
// recommended part of the log... |
// SetWarning changes the log level to Warning, which causes all Debug, Verbose,
// and Info events to be ignored, and all Warning, and Error events to be
// logged.
func (b *Logger) SetWarning() *Logger {
atomic.StoreUint32((*uint32)(&b.level), uint32(Warning))
return b
}
// SetError changes the log level to Erro... | {
atomic.StoreUint32((*uint32)(&b.level), uint32(Info))
return b
} | identifier_body |
gologs.go | package gologs
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
// DefaultCommandFormat specifies a log format might be more appropriate for a
// infrequently used command line program, where the name of the service is a
// recommended part of the log... | (e *event) error {
// ??? *If* want to sacrifice a bit of speed, might consider using a
// pre-allocated byte slice to format the output. The pre-allocated slice
// can be protected with the lock already being used to serialize output, or
// even better, its own lock so one thread can be formatting an event while
... | log | identifier_name |
gologs.go | package gologs
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
// DefaultCommandFormat specifies a log format might be more appropriate for a
// infrequently used command line program, where the name of the service is a
// recommended part of the log... |
return buf[:1] // all newline characters, so just return the first one
}
type logger interface {
log(*event) error
}
// Logger provides methods to create events to be logged. Logger instances are
// created to emit events to their parent Logger instance, which may themselves
// either filter events based on a con... | {
if buf[i] != '\n' {
if i+1 < l && buf[i+1] == '\n' {
return buf[:i+2]
}
return append(buf[:i+1], '\n')
}
} | conditional_block |
gologs.go | package gologs
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
// DefaultCommandFormat specifies a log format might be more appropriate for a
// infrequently used command line program, where the name of the service is a
// recommended part of the log... | if b.prefix != "" {
e.prefix = append([]string{b.prefix}, e.prefix...)
}
return b.parent.log(e)
}
// SetLevel allows changing the log level. Events must have the same log level
// or higher for events to be logged.
func (b *Logger) SetLevel(level Level) *Logger {
atomic.StoreUint32((*uint32)(&b.level), uint32(le... | random_line_split | |
gui_LMI.py | from __future__ import division
import clr
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtGui import QPixmap,QImage,QStandardItem
from PyQt5.QtCore import QThread , pyqtSignal
from PyQt5.QtWidgets import QFileDialog ,QTableWidgetItem
import time
import inspect
import sqlite3
import pandas
import collections
... | dictPara['tLDip']=self.tLDip.toPlainText()
dictPara['tRUip']=self.tRUip.toPlainText()
dictPara['tRDip']=self.tRDip.toPlainText()
dictPara['tC1ip']=self.tC1ip.toPlainText()
dictPara['tC2ip']=self.tC2ip.toPlainText()
dictPara['tSpeed']=self.tSpeed.t... | dictPara['tBadRate']=self.tBadRate.toPlainText()
dictPara['tFail']=self.tFail.toPlainText()
dictPara['tLUip']=self.tLUip.toPlainText() | random_line_split |
gui_LMI.py | from __future__ import division
import clr
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtGui import QPixmap,QImage,QStandardItem
from PyQt5.QtCore import QThread , pyqtSignal
from PyQt5.QtWidgets import QFileDialog ,QTableWidgetItem
import time
import inspect
import sqlite3
import pandas
import collections
... |
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(self,thread):
self._async_raise(thread.ident, SystemExit)
#---F程序跟踪功能
def outDebug(self,text):
global fd
# fd = os.open( "debug.txt", os.O_RDWR|os.O_APPEND|os.O_CREAT )
# # Writ... | raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
pythonapi.PyThreadState_SetAsyncExc(tid, None) | identifier_body |
gui_LMI.py | from __future__ import division
import clr
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtGui import QPixmap,QImage,QStandardItem
from PyQt5.QtCore import QThread , pyqtSignal
from PyQt5.QtWidgets import QFileDialog ,QTableWidgetItem
import time
import inspect
import sqlite3
import pandas
import collections
... | "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWindow = MyApp()
# visionWindow=Vison()
# windowConn()
# mainWindow.show()
app.setActiveWindow(mainWindow)
mainWindow.showMaximized()
# mainWindow.showFullScreen()
sys.exit(app.exec_())
| time.sleep(1)
if __name__ == | conditional_block |
gui_LMI.py | from __future__ import division
import clr
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtGui import QPixmap,QImage,QStandardItem
from PyQt5.QtCore import QThread , pyqtSignal
from PyQt5.QtWidgets import QFileDialog ,QTableWidgetItem
import time
import inspect
import sqlite3
import pandas
import collections
... | def _async_raise(self,tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = pythonapi.PyThreadState_SetAsyncExc(tid, py_object(exctype))
if res == 0:
... | 程功能
| identifier_name |
mgmt.py | # import pythoncom
# import win32serviceutil
# import win32service
# import win32event
# import servicemanager
# import socket
# import time
# import datetime
# import sys
# import os
# import logging
# import random
# # from win32com.shell import shell, shellcon
# import ntsecuritycon
# import win32security
# import w... | "function": LockScreen.show_lock_screen_widget,
"help": "Launch the lock screen widget which shoes current state of syncing/updates/etc..."
},
"refresh_lock_screen_widget": {
"function": LockScreen.refresh_lock_screen_widget,
"help": "Update the lockscreen widget with the latest ... | "show_lock_screen_widget": { | random_line_split |
mgmt.py | # import pythoncom
# import win32serviceutil
# import win32service
# import win32event
# import servicemanager
# import socket
# import time
# import datetime
# import sys
# import os
# import logging
# import random
# # from win32com.shell import shell, shellcon
# import ntsecuritycon
# import win32security
# import w... |
valid_commands = {
"help": {
"function": show_help,
"help": "Display help information for the specified command (e.g. mgmt.exe help set_log_level)",
},
### SETTINGS ###
# Add self to system path
"add_mgmt_to_system_path": {
"function": RegistrySettings.add_mgmt_utility... | global LOGGER, valid_commands
# Find the help key for this command
cmd = util.get_param(1).lower()
param1 = util.get_param(2).lower()
if cmd == "" or param1 == "":
# Missing required parameters!
p("}}rnMissing Required Parameters! " + cmd + " - " + param1 + "}}xx", log_level=1)
... | identifier_body |
mgmt.py | # import pythoncom
# import win32serviceutil
# import win32service
# import win32event
# import servicemanager
# import socket
# import time
# import datetime
# import sys
# import os
# import logging
# import random
# # from win32com.shell import shell, shellcon
# import ntsecuritycon
# import win32security
# import w... | ():
ver = CredentialProcess.get_mgmt_version()
p("}}gbVersion: " + str(ver) + "}}xx")
return True
def show_help():
global LOGGER, valid_commands
# Find the help key for this command
cmd = util.get_param(1).lower()
param1 = util.get_param(2).lower()
if cmd == "" or param1 == "":
... | show_version | identifier_name |
mgmt.py | # import pythoncom
# import win32serviceutil
# import win32service
# import win32event
# import servicemanager
# import socket
# import time
# import datetime
# import sys
# import os
# import logging
# import random
# # from win32com.shell import shell, shellcon
# import ntsecuritycon
# import win32security
# import w... |
cmd_requires_admin = util.get_dict_value(cmd_parts, "require_admin", True)
if cmd_requires_admin is True and is_admin[1] is not True:
# Command requires elevation and this user doesn't have it!
if is_admin[0] is not True:
# User is NOT in the administrators group
... | p("}}rnERROR - Command not avaialable " + cmd + " - coming soon...}}xx", log_level=1)
sys.exit(1) | conditional_block |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | rt default withRouter(ClientMobileApp);
/*
{loading
? (
<LoadingThreeDots color="white" />
) : (
)}
*/
/*
<div className="my-3 container-center">
<img src="/img/official-logo.jpg" alt="logo" width={300} height="auto"/>
</div>
*/ | {
const userScoreRef = useRef(null);
// const [showMoreBtn, setShowMoreBtn] = useState(false);
const [showPercentage, setShowPercentage] = useState(false);
let { isUserAuth, role, loyaltyScores, userName } = useStoreState(state => ({
isUserAuth: state.authReducer.cases.isUserAuthenticat... | identifier_body |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | {loading
? (
<LoadingThreeDots color="white" />
) : (
)}
*/
/*
<div className="my-3 container-center">
<img src="/img/official-logo.jpg" alt="logo" width={300} height="auto"/>
</div>
*/ | }
export default withRouter(ClientMobileApp);
/*
| random_line_split |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... | ({ history }) {
const userScoreRef = useRef(null);
// const [showMoreBtn, setShowMoreBtn] = useState(false);
const [showPercentage, setShowPercentage] = useState(false);
let { isUserAuth, role, loyaltyScores, userName } = useStoreState(state => ({
isUserAuth: state.authReducer.cases.isU... | ClientMobileApp | identifier_name |
ClientMobileApp.js | import React, { Fragment, useRef, useEffect, useState } from 'react';
import { Link, withRouter } from 'react-router-dom';
import Tilt from 'react-tilt'
import RatingStars from './RatingStars';
import { useStoreState, useStoreDispatch } from 'easy-peasy';
import { logout } from '../../redux/actions/authActions';
... |
}, [role, isUserAuth])
const playBeep = () => {
// Not working
const elem = document.querySelector("#appBtn");
elem.play();
}
const showLogin = () => (
<div className="my-5">
<div className="mb-3 text-white text-em-2-5 text-center text-default">
... | {
animateNumber(
userScoreRef.current,
0,
userScore,
3000,
setShowPercentage
);
} | conditional_block |
DanXuanCiHui.js | export default [
{
question: `I have been looking forward to from my parents. `,
options: [`hear `, `being heared `, `be heared `, `hearing`],
answer: "D"
},
{
question: `The manager will not us to use his car. `,
options: [`have `, `let `, `agree `, `allow`],
... | answer: "C"
},
{
question: `-He is not seriously ill, only a headache. `,
options: [
`obvious `,
`delicate `,
`slight `,
`temporary`
],
answer: "C"
},
{
question: `The boy is not happy at the new school. He has... | `who `,
`whose `,
`what`
], | random_line_split |
trans_dist_mmei_v1_batch.py | py_name = 'trans_dist_mmei_v1_batch.py'
# Leo Vo, Feb 2019
# For measuring distance between end of protospacer to TN7 flanks for NGS reads from an MmeI NGS library
# Reads in FastQ files outputed from GENEIOUS Prime Software, which have transposon flank sequences removed
# and are reverse complemented from the or... | (code, psl, description, filename, direction, refseq, spacer, date, excel, plot, plot_overlap): # main analysis function
# map spacer to refseq and determine query window
query_length = 500
if refseq.find(spacer) >= 0:
spacer_end = refseq.find(spacer) + 32
query = refseq[spacer_end-90:... | dist_find | identifier_name |
trans_dist_mmei_v1_batch.py | py_name = 'trans_dist_mmei_v1_batch.py'
# Leo Vo, Feb 2019
# For measuring distance between end of protospacer to TN7 flanks for NGS reads from an MmeI NGS library
# Reads in FastQ files outputed from GENEIOUS Prime Software, which have transposon flank sequences removed
# and are reverse complemented from the or... |
if excel:
log.close() | print("WARNING - File Not Found For {}".format(code)) | conditional_block |
trans_dist_mmei_v1_batch.py | py_name = 'trans_dist_mmei_v1_batch.py'
# Leo Vo, Feb 2019
# For measuring distance between end of protospacer to TN7 flanks for NGS reads from an MmeI NGS library
# Reads in FastQ files outputed from GENEIOUS Prime Software, which have transposon flank sequences removed
# and are reverse complemented from the or... |
# analyze all input files back-to-back using a master input .csv file
with open('input_spacers.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader, None)
for row in reader:
code = row[0]
filename = 'none'
for i in os.listdir('.'):
... | query_length = 500
if refseq.find(spacer) >= 0:
spacer_end = refseq.find(spacer) + 32
query = refseq[spacer_end-90:spacer_end+query_length] # '-99' accounts for the -50bp of the on-target later
query_rc = query.reverse_complement()
spacer_end = 90 # resets spacer end index to ... | identifier_body |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... |
}
fn push_merge(&mut self, other1: (&Self::Trie, usize, usize), other2: (&Self::Trie, usize, usize)) -> usize {
// just rebinding names to clarify code.
let (trie1, mut lower1, upper1) = other1;
let (trie2, mut lower2, upper2) = other2;
debug_assert!(upper1 <= trie1.keys.len());
debug_assert!(upper2 <... | {
let other_basis = other.lower(lower); // from where in `other` the offsets do start.
let self_basis = self.vals.boundary(); // from where in `self` the offsets must start.
for index in lower .. upper {
let other_entry = &other.keys[index];
let new_entry = if other_entry.is_some() {
Entry::new(
... | conditional_block |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... |
#[inline]
fn push_tuple(&mut self, (key, val): (K, L::Item)) {
// we build up self.temp, and rely on self.boundary() to drain self.temp.
let temp_len = self.temp.len();
if temp_len == 0 || self.temp[temp_len-1].key != key {
if temp_len > 0 { debug_assert!(self.temp[temp_len-1].key < key); }
let boundary... | {
HashedBuilder {
temp: Vec::with_capacity(cap),
keys: Vec::with_capacity(cap),
vals: L::with_capacity(cap),
}
} | identifier_body |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... | (other1: &Self::Trie, other2: &Self::Trie) -> Self {
HashedBuilder {
temp: Vec::new(),
keys: Vec::with_capacity(other1.keys() + other2.keys()),
vals: L::with_capacity(&other1.vals, &other2.vals),
}
}
/// Copies fully formed ranges (note plural) of keys from another trie.
///
/// While the ranges are fu... | with_capacity | identifier_name |
hashed.rs | //! Implementation using ordered keys with hashes and robin hood hashing.
use std::default::Default;
use timely_sort::Unsigned;
use ::hashable::{Hashable, HashOrdered};
use super::{Trie, Cursor, Builder, MergeBuilder, TupleBuilder};
const MINIMUM_SHIFT : usize = 4;
const BLOAT_FACTOR : f64 = 1.1;
// I would like t... | else {
self.pos = self.bounds.1;
}
}
#[inline(never)]
fn seek(&mut self, storage: &HashedLayer<K, L>, key: &Self::Key) {
// leap to where the key *should* be, or at least be soon after.
// let key_hash = key.hashed();
// only update position if shift is large. otherwise leave it alone.
if self.shif... | } | random_line_split |
views.py | from django.shortcuts import render,redirect,HttpResponse
from seller import models
import os
"""用来加密的函数,要调用它"""
import hashlib
def pwd_jm(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
"""3中校验方式,1.表单校验 2.装饰器校验 3.中间件校验"""
"""form表单校验register,归根到底算是... |
"""第三步主页"""
import datetime
#过滤器不能直接过滤时间戳
#给主页加一个装饰器
# @login_decorator
def index(request):
# 1.获取当前登录时间
times = datetime.datetime.now()
# 2. 获取头像
seller_id = request.session.get('seller_id')
seller_obj = models.Seller.objects.get(id=seller_id)
# models.Seller.objects.get(name=request.ses... | return redirect('/seller/login/')
return inner
| random_line_split |
views.py | from django.shortcuts import render,redirect,HttpResponse
from seller import models
import os
"""用来加密的函数,要调用它"""
import hashlib
def pwd_jm(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
"""3中校验方式,1.表单校验 2.装饰器校验 3.中间件校验"""
"""form表单校验register,归根到底算是... | username = data.get('username')
nickname = data.get('nickname')
password = data.get('password')
#picture=data.get('picture')如果这样获取的是图片名称
picture = request.FILES.get('picture')#获取的是图片对象
time_temp = time.time()#获取当前时间戳
#2.保存图片
path =... | identifier_name | |
views.py | from django.shortcuts import render,redirect,HttpResponse
from seller import models
import os
"""用来加密的函数,要调用它"""
import hashlib
def pwd_jm(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
"""3中校验方式,1.表单校验 2.装饰器校验 3.中间件校验"""
"""form表单校验register,归根到底算是... | identifier_body | ||
views.py | from django.shortcuts import render,redirect,HttpResponse
from seller import models
import os
"""用来加密的函数,要调用它"""
import hashlib
def pwd_jm(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
"""3中校验方式,1.表单校验 2.装饰器校验 3.中间件校验"""
"""form表单校验register,归根到底算是... | conditional_block | ||
pan2mqtt.py | #!/usr/bin/python
# -*- coding:utf-8 -*-
#dependence: paho-mqtt (pip install paho-mqtt)
# XBee (pip install XBee)
# PyYAML (pip install PyYaml)
# pyserial (pip install pyserial)
import os
import sys
import time
import logging
import yaml
from serial import Serial
from factory import *... |
print "topic list:" + str_topic_holder
self.mqtt_client.publish(dst_topic, str_topic_holder, 2)
###
def on_mqtt_connect (self, client, userdata, flags, rc):
if rc == 0:
self.__log(logging.INFO, "Connected to MQTT brok... | for mac,mac_obj in self.config['pan']['nodes'].items():
for topic,topic_content in mac_obj.items():
topic = topic.format(client_id=self.client_id)
if topic_content['dir'] == "uplink" and topic_content['type'] != "listening":
str_topic_holde... | conditional_block |
pan2mqtt.py | #!/usr/bin/python
# -*- coding:utf-8 -*-
#dependence: paho-mqtt (pip install paho-mqtt)
# XBee (pip install XBee)
# PyYAML (pip install PyYaml)
# pyserial (pip install pyserial)
import os
import sys
import time
import logging
import yaml
from serial import Serial
from factory import *... | (self):
self.downlink_topics = {}
self.uplink_topics = {}
if self.config['pan']['nodes']:
for mac,mac_obj in self.config['pan']['nodes'].items():
for topic,topic_content in mac_obj.items():
topic = topic.format(client_id=self.client_id)
... | __parse_nodes | identifier_name |
pan2mqtt.py | #!/usr/bin/python
# -*- coding:utf-8 -*-
#dependence: paho-mqtt (pip install paho-mqtt)
# XBee (pip install XBee)
# PyYAML (pip install PyYaml)
# pyserial (pip install pyserial)
import os
import sys
import time
import logging
import yaml
from serial import Serial
from factory import *... |
def on_mqtt_log (self, client, userdata, level, buf):
self.__log(logging.DEBUG, buf)
def on_message_from_pan (self, mac, key, value, type):
self.__log(logging.INFO, "Received message from PAN: %s, %s:%s" % (mac, key, value))
#walk over plugins and determin whether to drop
'''... | topic = self.mqtt_subcriptions.get(mid, "Unknown")
self.__log(logging.INFO, "Sub to topic %s confirmed"%topic) | identifier_body |
pan2mqtt.py | #!/usr/bin/python
# -*- coding:utf-8 -*-
#dependence: paho-mqtt (pip install paho-mqtt)
# XBee (pip install XBee)
# PyYAML (pip install PyYaml)
# pyserial (pip install pyserial)
import os
import sys
import time
import logging
import yaml
from serial import Serial
from factory import *... | self.__log(logging.INFO, "Sub to topic %s confirmed"%topic)
def on_mqtt_log (self, client, userdata, level, buf):
self.__log(logging.DEBUG, buf)
def on_message_from_pan (self, mac, key, value, type):
self.__log(logging.INFO, "Received message from PAN: %s, %s:%s" % (mac, key, value))
... | random_line_split | |
install_dotfiles.py | #!/usr/bin/env python
"""
hopefully doesn't mess anything up too badly
Significant inspiration was taken from:
https://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py
Steps:
- Ensure dependencies (git)
- Download repository
- Run dotdrop from the repo... | get_pip_file = self.CACHE_DIR / "get_pip.py"
get_pip_file.touch()
with get_pip_file.open(mode="wb") as file:
with urlopen("https://bootstrap.pypa.io/get-pip.py") as request:
while request.peek(1):
file.write(request.read(8192))
# NO... | # >> ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
self.shell("iwr -useb https://bootstrap.pypa.io")
# https://pip.pypa.io/en/stable/installation/#get-pip-py
| random_line_split |
install_dotfiles.py | #!/usr/bin/env python
"""
hopefully doesn't mess anything up too badly
Significant inspiration was taken from:
https://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py
Steps:
- Ensure dependencies (git)
- Download repository
- Run dotdrop from the repo... |
class Installer:
SHELL: Optional[Path] = None
PYTHON_EXECUTABLE: str = sys.executable
UPDATED_ENVIRONMENT: Dict[str, str] = {}
_SCOOP_INSTALLED: bool = False
PROCESS_TYPES: Dict[str, str] = {
"cmd": "{0!r}",
"shell": '"{0}"',
"pip": "{0}",
"scoop": "{0}... | if not self._PIP_INSTALLED:
self.bootstrap_pip()
# NOTE: pip forces the --user flag on Microsoft Store Pythons:
# https://stackoverflow.com/q/63783587
self.cmd([self.PYTHON_EXECUTABLE, "-m", "pip", *args, "--no-user"]) | identifier_body |
install_dotfiles.py | #!/usr/bin/env python
"""
hopefully doesn't mess anything up too badly
Significant inspiration was taken from:
https://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py
Steps:
- Ensure dependencies (git)
- Download repository
- Run dotdrop from the repo... |
assert venv_modules.is_dir(), f"missing directory '{venv_modules}'"
self.PYTHON_EXECUTABLE = str(venv_python)
sys.path.insert(0, str(venv_modules))
# Install trio
self.pip(["install", "trio"])
import trio as trio_module # isort:skip
global trio
... | raise Exception(
f"could not find a virtual environment python at '{venv_python}'"
) | conditional_block |
install_dotfiles.py | #!/usr/bin/env python
"""
hopefully doesn't mess anything up too badly
Significant inspiration was taken from:
https://github.com/python-poetry/poetry/blob/c967a4a5abc6a0edd29c57eca307894f6e1c4f16/install-poetry.py
Steps:
- Ensure dependencies (git)
- Download repository
- Run dotdrop from the repo... | (name: str) -> Optional[str]:
if not WINDOWS:
raise NotImplementedError(
"can only update environment variables on Windows for now"
)
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:
with winreg.OpenKey(root, "Environment", 0, winreg.KEY_ALL_ACCESS... | win_get_user_env | identifier_name |
64112.user.js | // ==UserScript==
// @name Google Preferences Without Cookies
// @version 1.1
// @date 2009-12-12
// @description Allows setting some Google preferences without having cookies enabled.
// @namespace http://www.theworldofstuff.com/greasemonkey/
// @copyright Copyright 2009 Jordon Kali... |
}
// if on a search page
if (/[?#](.*&)?q=/i.test(location.href)) {
var queryString = location.href.substring(location.href.indexOf('?'));
var origQueryString = queryString;
// change the query string if necessary
// if hl (interface language) is specified, change it because it is only specified from the ... | {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, otherwise the new page will be blank
... | conditional_block |
64112.user.js | // ==UserScript==
// @name Google Preferences Without Cookies
// @version 1.1
// @date 2009-12-12
// @description Allows setting some Google preferences without having cookies enabled.
// @namespace http://www.theworldofstuff.com/greasemonkey/
// @copyright Copyright 2009 Jordon Kali... |
// if on a search page
if (/[?#](.*&)?q=/i.test(location.href)) {
var queryString = location.href.substring(location.href.indexOf('?'));
var origQueryString = queryString;
// change the query string if necessary
// if hl (interface language) is specified, change it because it is only specified from the pr... | {
if (reg.test(location.href)) {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, otherwis... | identifier_body |
64112.user.js | // ==UserScript==
// @name Google Preferences Without Cookies
// @version 1.1
// @date 2009-12-12
// @description Allows setting some Google preferences without having cookies enabled.
// @namespace http://www.theworldofstuff.com/greasemonkey/
// @copyright Copyright 2009 Jordon Kali... | "zu": "Zulu"
}
pageBody += '<p><label>Display Google tips and messages in: <select id="GPWOC_hl">';
for (var i in interfaceLanguages) {
pageBody += '<option value="' + i + '"' + ((interfaceLanguage==i)?' selected="selected"':'') + '>' + interfaceLanguages[i] + '</option>';
}
pageBody += '</sele... | "xh": "Xhosa",
"yi": "Yiddish",
"yo": "Yoruba", | random_line_split |
64112.user.js | // ==UserScript==
// @name Google Preferences Without Cookies
// @version 1.1
// @date 2009-12-12
// @description Allows setting some Google preferences without having cookies enabled.
// @namespace http://www.theworldofstuff.com/greasemonkey/
// @copyright Copyright 2009 Jordon Kali... | () {
if (reg.test(location.href)) {
document.removeEventListener('DOMNodeInserted', checkURL, true); // we need to remove the event listener or we might cause an infinite loop
var newURL = location.href.replace(reg, '$1search?$5');
newURL = newURL.replace(/&fp=[^&]*/i, ''); // remove fp also, other... | checkURL | identifier_name |
api_op_Search.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package resourceexplorer2
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"
... | {
return stack.Serialize.Insert(&opSearchResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | identifier_body | |
api_op_Search.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package resourceexplorer2
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"
... | (ctx context.Context, optFns ...func(*Options)) (*SearchOutput, error) {
if !p.HasMorePages() {
return nil, fmt.Errorf("no more pages available")
}
params := *p.params
params.NextToken = p.nextToken
var limit *int32
if p.options.Limit > 0 {
limit = &p.options.Limit
}
params.MaxResults = limit
result, er... | NextPage | identifier_name |
api_op_Search.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package resourceexplorer2
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"
... |
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); er... | {
return err
} | conditional_block |
api_op_Search.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package resourceexplorer2
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"
... | UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | random_line_split | |
imap.go | package Pinger
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"github.com/nachocove/Pinger/Utils"
"github.com/nachocove/Pinger/Utils/Logging"
"math/rand"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// IMAP Commands
const (
IMAP_EXISTS string = "EXISTS"
... | () {
imap.mutex.Lock()
imap.cancelled = true
if imap.tlsConn != nil {
imap.cancelIDLE()
imap.tlsConn.Close()
imap.tlsConn = nil
}
imap.mutex.Unlock()
}
func (imap *IMAPClient) Cleanup() {
imap.Debug("Cleaning up")
imap.cancel()
imap.pi.cleanup()
imap.pi = nil
}
| cancel | identifier_name |
imap.go | package Pinger
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"github.com/nachocove/Pinger/Utils"
"github.com/nachocove/Pinger/Utils/Logging"
"math/rand"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// IMAP Commands
const (
IMAP_EXISTS string = "EXISTS"
... | imap.Info("Saving starting EXISTS count|IMAPEXISTSCount=%d||msgCode=IMAP_STARTING_EXISTS_COUNT", count)
imap.pi.IMAPEXISTSCount = count
} else if token == IMAP_UIDNEXT {
imap.Info("Setting starting IMAPUIDNEXT|IMAPUIDNEXT=%d", count)
imap.pi.IMAPUIDNEXT = count
}
case "STATUS":
imap.Debug("Processing... | count, token := imap.parseEXAMINEResponse(response)
if token == IMAP_EXISTS { | random_line_split |
imap.go | package Pinger
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"github.com/nachocove/Pinger/Utils"
"github.com/nachocove/Pinger/Utils/Logging"
"math/rand"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// IMAP Commands
const (
IMAP_EXISTS string = "EXISTS"
... |
if err != nil {
if imap.isIdling {
imap.isIdling = false
}
imap.Info("Request/Response Error: %s", err)
nerr, ok := err.(net.Error)
if ok && nerr.Timeout() {
responseErrCh <- IOTimeoutError;
} else {
responseErrCh <- fmt.Errorf("Request/Response Error: %s", err)
}
return
}
responseCh <- res... | {
imap.Info("IMAP Request cancelled. Exiting|msgCode=IMAP_REQ_CANCELLED")
return
} | conditional_block |
imap.go | package Pinger
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"github.com/nachocove/Pinger/Utils"
"github.com/nachocove/Pinger/Utils/Logging"
"math/rand"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// IMAP Commands
const (
IMAP_EXISTS string = "EXISTS"
... |
func (t *cmdTag) String() string {
return fmt.Sprintf("%s%d", t.id, t.seq)
}
func (imap *IMAPClient) setupScanner() {
imap.scanner = bufio.NewScanner(imap.tlsConn)
imap.scanner.Split(bufio.ScanLines)
}
func (imap *IMAPClient) isContinueResponse(response string) bool {
if len(response) > 0 && response[0] == '+' ... | {
t.seq++
return string(strconv.AppendUint(t.id, t.seq, 10))
} | identifier_body |
singer.go | package singer
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/jitsucom/jitsu/server/drivers/base"
"github.com/jitsucom/jitsu/server/logging"
"github.com/jitsucom/jitsu/server/safego"
"github.com/jitsucom/jitsu/server/singer"
"github.com/jitsucom/jitsu/serve... | () {
base.RegisterDriver(base.SingerType, NewSinger)
base.RegisterTestConnectionFunc(base.SingerType, TestSinger)
}
//NewSinger returns Singer driver and
//1. writes json files (config, catalog, properties, state) if string/raw json was provided
//2. runs discover and collects catalog.json
//2. creates venv
//3. in ... | init | identifier_name |
singer.go | package singer
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/jitsucom/jitsu/server/drivers/base"
"github.com/jitsucom/jitsu/server/logging"
"github.com/jitsucom/jitsu/server/safego"
"github.com/jitsucom/jitsu/server/singer"
"github.com/jitsucom/jitsu/serve... | {
catalogBytes, err := ioutil.ReadFile(catalogPath)
if err != nil {
return nil, fmt.Errorf("Error reading catalog file: %v", err)
}
catalog := &SingerCatalog{}
err = json.Unmarshal(catalogBytes, catalog)
if err != nil {
return nil, err
}
streamTableNamesMapping := map[string]string{}
for _, stream := ra... | identifier_body | |
singer.go | package singer
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/jitsucom/jitsu/server/drivers/base"
"github.com/jitsucom/jitsu/server/logging"
"github.com/jitsucom/jitsu/server/safego"
"github.com/jitsucom/jitsu/server/singer"
"github.com/jitsucom/jitsu/serve... | s.catalogPath = catalogPath
s.propertiesPath = propertiesPath
s.catalogDiscovered.Store(true)
return
}
}
//GetTableNamePrefix returns stream table name prefix or sourceID_
func (s *Singer) GetTableNamePrefix() string {
//put as prefix + stream if prefix exist
if s.tableNamePrefix != "" {
return s.tableNa... | continue
}
| random_line_split |
singer.go | package singer
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/jitsucom/jitsu/server/drivers/base"
"github.com/jitsucom/jitsu/server/logging"
"github.com/jitsucom/jitsu/server/safego"
"github.com/jitsucom/jitsu/server/singer"
"github.com/jitsucom/jitsu/serve... |
if s.catalogDiscovered.Load() {
break
}
if !singer.Instance.IsTapReady(s.tap) {
time.Sleep(time.Second)
continue
}
catalogPath, propertiesPath, err := doDiscover(s.sourceID, s.tap, s.pathToConfigs, s.configPath)
if err != nil {
logging.Errorf("[%s] Error configuring Singer: %v", s.sourceID, ... | {
break
} | conditional_block |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... | let hits_b = b.score.total_hits();
let ratio_a = a.score.statistics.count_miss as f32 / hits_a as f32;
let ratio_b = b.score.statistics.count_miss as f32 / hits_b as f32;
ratio_b
.partial_cmp(&ratio_a)
... | .count_miss
.cmp(&a.score.statistics.count_miss)
.then_with(|| {
let hits_a = a.score.total_hits(); | random_line_split |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... | (ctx: Arc<Context>, msg: &Message, args: Args<'_>) -> Result<()> {
match Mapper::args(Some(GameModeOption::Taiko), args, None) {
Ok(args) => mapper(ctx, msg.into(), args).await,
Err(content) => {
msg.error(&ctx, content).await?;
Ok(())
}
}
}
#[command]
#[desc("H... | prefix_mappertaiko | identifier_name |
mapper.rs | use std::{
borrow::Cow,
cmp::{Ordering, Reverse},
collections::HashMap,
sync::Arc,
};
use bathbot_macros::{command, HasName, SlashCommand};
use bathbot_model::ScoreSlim;
use bathbot_psql::model::configs::{ListSize, MinimizedPp};
use bathbot_util::{
constants::{GENERAL_ISSUE, OSU_API_ISSUE},
mat... |
async fn process_scores(
ctx: &Context,
scores: Vec<Score>,
mapper_id: u32,
sort: Option<ScoreOrder>,
) -> Result<Vec<TopEntry>> {
let mut entries = Vec::new();
let maps_id_checksum = scores
.iter()
.filter_map(|score| score.map.as_ref())
.filter(|map| map.creator_id =... | {
let msg_owner = orig.user_id()?;
let mut config = match ctx.user_config().with_osu_id(msg_owner).await {
Ok(config) => config,
Err(err) => {
let _ = orig.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
let mode = args
.mode
.ma... | identifier_body |
linked-data-provider.service.ts | import { Injectable, Inject } from '@angular/core';
import { ISchemaAgent, IRelatableSchemaAgent, IdentityValue, SchemaNavigator, JsonSchema, ExtendedFieldDescriptor } from 'json-schema-services';
import { FieldContextProvider } from './field-context-provider.service';
import { FormField } from './models/form-field';
... | return pointer.get(item, this.field.meta.field.data['pointer'] || '/');
}
catch (e) {
debug(`[warn] unable to get the data for pointer "${this.field.meta.field.data['pointer']}"`);
... | .then(item => {
try { | random_line_split |
linked-data-provider.service.ts | import { Injectable, Inject } from '@angular/core';
import { ISchemaAgent, IRelatableSchemaAgent, IdentityValue, SchemaNavigator, JsonSchema, ExtendedFieldDescriptor } from 'json-schema-services';
import { FieldContextProvider } from './field-context-provider.service';
import { FormField } from './models/form-field';
... |
if (a.order > b.order) {
return 1;
}
return -1;
}));
}
/**
* Chooses between the ambient context and the one given, and returns the correct one (eventually).
*/
private chooseAppropriateContext(context?: any): Promis... | {
return String(a.name).localeCompare(String(b.name));
} | conditional_block |
linked-data-provider.service.ts | import { Injectable, Inject } from '@angular/core';
import { ISchemaAgent, IRelatableSchemaAgent, IdentityValue, SchemaNavigator, JsonSchema, ExtendedFieldDescriptor } from 'json-schema-services';
import { FieldContextProvider } from './field-context-provider.service';
import { FormField } from './models/form-field';
... |
/**
* Convert the given list of simplified values to a list of the actual linked objects.
*
* @param items The simplified linked resource items.
*/
public getLinkedDataFromSimplifiedLinkedData(items: SimplifiedLinkedResource[]): Promise<any | IdentityValue[]> {
if (typeof this.fiel... | {
return this.chooseAppropriateContext(context).then(ctx =>
this.mapMultipleChoice(items, ctx, forceReload, includeOriginal));
} | identifier_body |
linked-data-provider.service.ts | import { Injectable, Inject } from '@angular/core';
import { ISchemaAgent, IRelatableSchemaAgent, IdentityValue, SchemaNavigator, JsonSchema, ExtendedFieldDescriptor } from 'json-schema-services';
import { FieldContextProvider } from './field-context-provider.service';
import { FormField } from './models/form-field';
... | ield: ExtendedFieldDescriptor, item: any): IdentityValue {
if (field.field.data == null || field.field.data.parent == null) {
return item['parent'];
}
return item[field.field.data.parent];
}
function startsWith(str: string, target: string) {
return String(str).slice(0, target.length) == String(... | tParentValue(f | identifier_name |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | } else {
grid[i][j] += grid[i-1][j].max(grid[i][j-1]);
}
}
}
return grid[row-1][col-1];
}
// https://leetcode-cn.com/problems/triangle/solution/di-gui-ji-yi-hua-dp-bi-xu-miao-dong-by-sweetiee/
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
let n = tri... | dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
} else {
// 遇到障碍了,但一开始我们就是初始化为0的,所以这里其实可以不写
dp[i][j] = 0;
}
}
}
return dp[row-1][col-1];
}
// https://leetcode-cn.com/problems/re-space-lcci/
pub fn respace(dictionary: Vec<String>,... | identifier_body |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | st[r-1][c];
} else {
cost[r][c] = grid[r][c] + min(cost[r-1][c], cost[r][c-1]);
}
}
}
return cost[row-1][col-1];
}
// https://leetcode-cn.com/problems/generate-parentheses/solution/
pub fn generate_parenthesis(n: i32) -> Vec<String> {
if n == 0 {
ret... | d[r][c] + co | identifier_name |
dp.rs | // 我们开始学习动态规划吧
use std::cmp::min;
// https://leetcode-cn.com/problems/maximum-subarray
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = nums[0];
let mut ans = nums[0];
for i in 1..nums.len() {
if sum > 0 {
// add positive sum means larger
... | +1]) + triangle[i][j];
}
}
return dp[0];
}
// https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof/solution/
pub fn two_sum(n: i32) -> Vec<f64> {
let mut res = vec![1./6.;6];
for i in 1..n as usize {
let mut temp = vec![0.0; 5 * i + 6];
for j in 0..res.len() {
... | ("i, j = {}, {}", i, j);
dp[j] = dp[j].min(dp[j | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.