file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
Payment-temp.js | return new Promise((resolve) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false);
};
document.body.appendChild(script);
});
};
const _DEV_ = document.domain === "localhost";... | (stepIndex, buyerData) {
switch (stepIndex) {
case 0:
return (
<div>
{buyerData && (
<div style={{ background: "#ecf0f1", margin: "auto", width: 630 }}>
<font color="red" style={{ color: "red", fontWieght: "bold" }}>
<b>Delivery Address</b>
... | getStepContent | identifier_name |
Payment-temp.js | return new Promise((resolve) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false);
};
document.body.appendChild(script);
});
};
const _DEV_ = document.domain === "localhost";... |
// const data = await fetch("http://localhost:5000/buyer/checkout", {
// method: "POST",
// }).then((t) => t.json());
// const data = await axios.post(`http://localhost:5000/buyer/checkout`, {
// headers: { "x-access-token": token },
// });
const data = await fetch(`http://localhost:... | {
alert("razorpay sdk failed to load. are u online");
return;
} | conditional_block |
Payment-temp.js | return new Promise((resolve) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false);
};
document.body.appendChild(script);
});
};
const _DEV_ = document.domain === "localhost";... | setActiveStep(0);
};
useEffect(() => {
const getbuyerData = async () => {
const response = await axios.get(`http://localhost:5000/seller/buyer/${buyerId}`, {
headers: { "x-access-token": token },
});
console.log(response);
const data = await response.data;
console.log(... | {
const navigate = useNavigate();
const buyerId = useParams().buyerId;
const [buyerData, setBuyerData] = useState();
const { token } = useAuth();
const [finalMessage, setFinalMessage] = useState(false);
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
const steps = ge... | identifier_body |
ldacgsmulti.py |
word_top = (np.frombuffer(_word_top, dtype=np.float64)
+ np.sum(word_top_ls, axis=0))
top_norms = 1. / (word_top.reshape(_m_words.value, _K.value).sum(axis=0))
_word_top[:] = word_top
_top_norms[:] = top_norms
del word_top, top_norms
... | """
Note
----
Disable reseeding in `update` before running this test and use
sequential mapping
"""
from vsm.util.corpustools import random_corpus
c = random_corpus(100, 5, 4, 20)
m0 = LdaCgsMulti(c, 'random', K=3)
np.random.seed(0)
m0.train(itr=5, n_proc=2)
m0.train(itr... | identifier_body | |
ldacgsmulti.py | .ctx_prior = np.array(ctx_prior,
dtype=np.float64).reshape(_K.value,1)
else:
# Default is a flat prior of .01
self.ctx_prior = np.ones((_K.value,1), dtype=np.float64) * .01
# Topic posterior stored in shared array, initialized to zero
... |
# Store log probability computations
self.log_prob = []
@staticmethod
def _init_word_top(a):
global _word_top
_word_top = mp.Array('d', _m_words.value*_K.value, lock=False)
_word_top[:] = a
@staticmethod
def _init_top_norms(a):
global _top_norms
... | _train = mp.Value('b', 0, lock=False) | random_line_split |
ldacgsmulti.py | .ctx_prior = np.array(ctx_prior,
dtype=np.float64).reshape(_K.value,1)
else:
# Default is a flat prior of .01
self.ctx_prior = np.ones((_K.value,1), dtype=np.float64) * .01
# Topic posterior stored in shared array, initialized to zero
... |
data = zip(ctx_ls, Z_ls, top_ctx_ls)
# For debugging
# results = map(update, data)
results = p.map(update, data)
if verbose:
stdout.write('\rIteration %d: reducing ' % self.iteration)
stdout.flush()
# Unzip res... | stdout.write('\rIteration %d: mapping ' % self.iteration)
stdout.flush() | conditional_block |
ldacgsmulti.py | array, initialized to the
# sums over the topic priors
LdaCgsMulti._init_top_norms(1. / (np.ones(_K.value, dtype=np.float64)
* self.top_prior.sum()))
self.iteration = 0
# The 0-th iteration is an initialization step, not a training step
... | test_LdaCgsMulti_IO | identifier_name | |
app.py | if st.checkbox("Visualize actual vs predicted conflict"):
if st.checkbox("2019: 12 months"):
fig, axes = plt.subplots(ncols=2)
ax = plt.subplots()
ax = cc_actual.plot(column='2019')
axes[0].set_title("Actual")
axes[1].set_title("Predicted")
... | main | identifier_name | |
app.py | = test1.reset_index()
df_evl = df_test.join(y_pred)
df_evl1 = df_evl[['admin1', 'admin2', 'geometry',
'month_year', 'cc_onset_y', 'cc_onset_prediction']]
df_evl1.cc_onset_y = df_evl1.cc_onset_y.astype(int)
cc_onset_actual = df_evl1.pivot(
index=['admin1', 'admin2', 'geometry'], columns='month_yea... | st.write(
f"Note: Currently, the file to be uploaded should have **exactly the same** format with **training dataset** which is **{current.shape[1]}** columns in the following format.",
current.head(2),
)
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
... | conditional_block | |
app.py |
df2 = df.drop(['Unnamed: 0',
'Unnamed: 0.1',
'admin1',
'admin2',
'geometry',
'location',
'year'], axis=1)
end_date = "2021-01"
mask = (df2['month_year'] < end_date)
df2 = df2.loc[mask]
df3 = df2.drop(['month_year'], axis=1)
X ... | st.title("Kimetrica Conflict Forecasting Model: Myanmar Analytical Activity (MAA)")
st.write("")
st.write("")
st.subheader("INTRODUCTION")
st.write("")
st.write(
"An early-warning system that can meaningfully forecast conflict in its various forms is necessary to respond to crises ahead of t... | identifier_body | |
app.py | ")
st.write("")
st.write("* `ethnicty_count`: number of ethnic groups")
st.write("")
st.write("* `fatalities`: number of fatalities due to conflict")
st.write("")
st.write("* `gender_index`: gender index")
st.write("")
st.write("* `infant_mortality`: infan... | cc_prediction.plot(column='2019-01', cmap='OrRd',
legend=True, ax=axes[1])
st.pyplot(fig)
| random_line_split | |
emacs.js | dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
co... | (cm) {
cm.setExtending(false);
cm.setCursor(cm.getCursor());
}
function makePrompt(msg) {
var fragment = document.createDocumentFragment();
var input = document.createElement("input");
input.setAttribute("type", "text");
input.style.width = "10em";
fragment.appendChild(document.createTe... | clearMark | identifier_name |
emacs.js | dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
co... |
function maybeRemovePrefixMap(cm, arg) {
if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
cm.removeKeyMap(prefixMap);
cm.state.emacsPrefixMap = false;
cm.off("keyHandled", maybeRemovePrefixMap);
cm.off("inputRead", maybeRemovePrefixMap);
}
// Utilities
cmds.se... | {
var dup = getPrefix(cm);
if (dup > 1 && event.origin == "+input") {
var one = event.text.join("\n"), txt = "";
for (var i = 1; i < dup; ++i) txt += one;
cm.replaceSelection(txt);
}
} | identifier_body |
emacs.js | dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
co... |
function maybeClearPrefix(cm, arg) {
if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
clearPrefix(cm);
}
function clearPrefix(cm) {
cm.state.emacsPrefix = null;
cm.off("keyHandled", maybeClearPrefix);
cm.off("inputRead", maybeDuplicateInput);
}
function maybe... | random_line_split | |
parse.rs | ;
} else {
return None;
}
}
}
}
fn scan_path(lines: &Lines, p: Point, d: Direction) -> Vec<Point> {
if !lines.at(p).map(|c| can_go(c, d)).unwrap_or(false) {
return vec![];
}
let mut ret = vec![];
let mut it = PathIter::new(&lines, p, d);
while let Some(next) = it.next() {
if ret.contains(&next) {... | {
let b = TBox(Point { row: 1, col: 1 }, Point { row: 3, col: 4 });
use Direction::*;
assert_eq!(
vec![
(Point { row: 0, col: 1 }, Up),
(Point { row: 0, col: 2 }, Up),
(Point { row: 0, col: 3 }, Up),
(Point { row: 0, col: 4 }, Up),
(Point { row: 4, col: 1 }, Dn),
(Point { row: 4, col: 2... | identifier_body | |
parse.rs | ::Formatter) -> std::fmt::Result {
write!(f, "[{:?} {:?}]", self.0, self.1)
}
}
impl TBox {
#[inline]
pub fn contains(&self, p: Point) -> bool {
["hey", "there"].into_iter().flat_map(|s| s.chars());
p.row >= self.0.row && p.row <= self.1.row && p.col >= self.0.col && p.col <= self.1.col
}
#[inline]
pub fn... | (lines: &Lines, mut p: Point, d: Direction) -> Option<(Point, char)> {
while let Some((q, c)) = lines.in_dir(p, d) {
// p
// --* < can't connect
//
if !can_go(c, d.rev()) {
return lines.at(p).map(|c| (p, c));
}
p = q;
// p
// --. < can connect, can't continue
//
if !can_go(c, d) {
return S... | scan_dir | identifier_name |
parse.rs | ::Formatter) -> std::fmt::Result {
write!(f, "[{:?} {:?}]", self.0, self.1)
}
}
impl TBox {
#[inline]
pub fn contains(&self, p: Point) -> bool {
["hey", "there"].into_iter().flat_map(|s| s.chars());
p.row >= self.0.row && p.row <= self.1.row && p.col >= self.0.col && p.col <= self.1.col
}
#[inline]
pub fn... |
}
}
ret
}
fn scan_dir(lines: &Lines, mut p: Point, d: Direction) -> Option<(Point, char)> {
while let Some((q, c)) = lines.in_dir(p, d) {
// p
// --* < can't connect
//
if !can_go(c, d.rev()) {
return lines.at(p).map(|c| (p, c));
}
p = q;
// p
// --. < can connect, can't continue
//
if ... | {
ret.push((p, c));
} | conditional_block |
parse.rs | ::Formatter) -> std::fmt::Result {
write!(f, "[{:?} {:?}]", self.0, self.1)
}
}
impl TBox {
#[inline]
pub fn contains(&self, p: Point) -> bool {
["hey", "there"].into_iter().flat_map(|s| s.chars());
p.row >= self.0.row && p.row <= self.1.row && p.col >= self.0.col && p.col <= self.1.col
}
#[inline]
pub fn... | }
fn scan_path(lines: &Lines, p: Point, d: Direction) -> Vec<Point> {
if !lines.at(p).map(|c| can_go(c, d)).unwrap_or(false) {
return vec![];
}
let mut ret = vec![];
let mut it = PathIter::new(&lines, p, d);
while let Some(next) = it.next() {
if ret.contains(&next) {
return ret;
}
ret.push(next);
}
r... | }
}
} | random_line_split |
client.go | the server to send a greeting message, and then
// requests server capabilities if they weren't included in the greeting. An
// error is returned if either operation fails or does not complete before the
// timeout, which must be positive to have any effect. If an error is returned,
// it is the caller's responsibilit... | (timeout time.Duration) (rsp *Response, err error) {
if c.state == Closed {
return nil, io.EOF
} else if c.rch == nil && (timeout < 0 || c.cch == nil) {
rsp, err = c.next()
} else {
if c.rch == nil {
rch := make(chan *response, 1)
c.cch <- rch
c.rch = rch
runtime.Gosched()
}
var r *response
i... | recv | identifier_name |
client.go | panic.
conn := c.t.conn
conn.SetDeadline(time.Now().Add(timeout))
defer func() {
conn.SetDeadline(time.Time{})
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
err = ErrTimeout
}
}()
}
// Wait for server greeting
rsp, err := c.recv(block)
if err != nil {
return
} else if rsp.Type... | {
mode := poll
if sync {
if err = c.t.Flush(); err != nil {
return
}
mode = block
}
for cmd.InProgress() {
if rsp, err = c.recv(mode); err != nil {
if err == ErrTimeout {
err = nil
}
return
} else if !c.deliver(rsp) {
if rsp.Type == Continue {
if !sync {
err = ResponseError{rsp... | identifier_body | |
client.go | =%s)", c.tag.id)
defer c.Logf(LogGo, "Receiver finished (Tag=%s)", c.tag.id)
for rch := range cch {
rch <- recv()
}
}
// recv returns the next server response, updating the client state beforehand.
func (c *Client) recv(timeout time.Duration) (rsp *Response, err error) {
if c.state == Closed {
return nil, io.... | if caps == "" { | random_line_split | |
client.go | c.rch = nil
rsp, err = r.rsp, r.err
}
if err == nil {
c.update(rsp)
} else if rsp == nil {
defer c.setState(Closed)
if err != io.EOF {
c.close("protocol error")
} else if err = c.close("end of stream"); err == nil {
err = io.EOF
}
}
return
}
// update examines server responses and updates clien... | {
c.Logln(LogConn, "Close error:", err)
} | conditional_block | |
main.ts | Player{
wins: number = 0;
points: number = 100;
constructor(public name:string){
}
}
abstract class Character{
health: number = 100;
position: number;
abstract damage: number;
abstract image: string;
abstract distance: number;
abstract cost: number;
abstract type: CharacterTypes;
constructor(position: nu... | }
if($(this).hasClass("archer")||$(this).hasClass("thrower")){
highlight(2, position);
chose = true;
}
}
$("#field td").click(function(){
if(chose && !$(this).html() && $(this).hasClass("highlighted")){
moveChar(cellFrom, $(this));
chose = false;
$("#field td").each(function(){
... |
chose = true; | random_line_split |
main.ts | Player{
wins: number = 0;
points: number = 100;
constructor(public name:string){
}
}
abstract class Character{
health: number = 100;
position: number;
abstract damage: number;
abstract image: string;
abstract distance: number;
abstract cost: number;
abstract type: CharacterTypes;
constructor(position: nu... |
get resources(): Character[]{
return this._resources;
}
}
class EnemySquad{
wins: number = 0;
private _resources: Character[] = [];
constructor(){}
addMember(value: Character):void{
this._resources.push(value);
}
deleteMember(value: Character):void{
this._resources.splice(this._resources.indexOf(value)... | {
for(let i=0; i<this._resources.length; i++){
if(this._resources[i].position = position){
return this._resources[i];
};
}
} | identifier_body |
main.ts | ;
abstract image: string;
abstract distance: number;
abstract cost: number;
abstract type: CharacterTypes;
constructor(position: number){
this.position = position;
}
showInfo(){
return ("Type: " + CharacterTypes[this.type] + "</br> Distance: " + this.distance + "</br>Cost: " + this.cost);
}
}
class Warri... | highlight | identifier_name | |
image.go | `json:"properties"`
Protected bool `json:"protected"`
Status string `json:"status"`
Size int64 `json:"size"`
VirtualSize *int64 `json:"virtual_size"` // Note: Property exists in OpenStack dev stack payloads but not Hel... |
return reqURL, nil
}
type imagesDetailResponse struct { | random_line_split | |
image.go | DeletedAt *misc.RFC8601DateTime `json:"deleted_at"`
DiskFormat string `json:"disk_format"`
ID string `json:"id"`
IsPublic bool `json:"is_public"`
MinDisk int64 `json:"min_disk"`
MinRAM int64 ... | {
values.Set("limit", fmt.Sprintf("%d", queryParameters.Limit))
} | conditional_block | |
image.go | QueryParameters.
*/
package image
import (
"fmt"
"github.com/xenserverarmy/go-osglance/misc"
"net/http"
"net/url"
"strings"
)
// Service is a client service that can make
// requests against a OpenStack version 1 image service.
// Below is an example on creating an image service and getting images:
// imageSer... | (queryParameters *QueryParameters) ([]Response, error) {
imagesContainer := imagesResponse{}
err := imageService.queryImages(false /*includeDetails*/, &imagesContainer, queryParameters)
if err != nil {
return nil, err
}
return imagesContainer.Images, nil
}
// QueryImagesDetail will issue a get request with the... | QueryImages | identifier_name |
image.go | json:"name"`
Size int64 `json:"size"`
}
// DetailResponse is a structure for all properties of
// an image for a detailed query
type DetailResponse struct {
CheckSum string `json:"checksum"`
ContainerFormat string `json:"container_format"`
CreatedAt misc.RFC86... | {
reqURL, err := url.Parse(imageService.URL)
if err != nil {
return nil, err
}
if queryParameters != nil {
values := url.Values{}
if queryParameters.Name != "" {
values.Set("name", queryParameters.Name)
}
if queryParameters.ContainerFormat != "" {
values.Set("container_format", queryParameters.Cont... | identifier_body | |
thread.rs | create()`], but only start executing
/// when either [`Thread::start()`] or [`Process::start()`] are called. Both syscalls
/// take as an argument the entrypoint of the initial routine to execute.
///
/// The thread passed to [`Process::start()`] should be the first thread to start execution
/// on a process.
///
/// A... | (
self: &Arc<Self>,
entry: usize,
stack: usize,
arg1: usize,
arg2: usize,
) -> ZxResult<()> {
let regs = GeneralRegs::new_fn(entry, stack, arg1, arg2);
self.start_with_regs(regs)
}
/// Start execution with given registers.
pub fn start_with_regs(s... | start | identifier_name |
thread.rs | create()`], but only start executing
/// when either [`Thread::start()`] or [`Process::start()`] are called. Both syscalls
/// take as an argument the entrypoint of the initial routine to execute.
///
/// The thread passed to [`Process::start()`] should be the first thread to start execution
/// on a process.
///
/// A... |
inner.state = Some(state);
}
#[derive(Default)]
struct ThreadInner {
/// HAL thread handle
///
/// Should be `None` before start or after terminated.
hal_thread: Option<kernel_hal::Thread>,
/// Thread state
///
/// Only be `Some` on suspended.
state: Option<&'static mut ThreadStat... | {
state.general = old_state.general;
} | conditional_block |
thread.rs | ::create()`], but only start executing
/// when either [`Thread::start()`] or [`Process::start()`] are called. Both syscalls
/// take as an argument the entrypoint of the initial routine to execute.
///
/// The thread passed to [`Process::start()`] should be the first thread to start execution
/// on a process.
///
///... | thread: self.clone(),
}
}
pub fn resume(&self) {
let mut inner = self.inner.lock();
assert_ne!(inner.suspend_count, 0);
inner.suspend_count -= 1;
if inner.suspend_count == 0 {
if let Some(waker) = inner.waker.take() {
waker.wake();... | }
}
}
RunnableChecker { | random_line_split |
thread.rs | does not terminate execution. The last
/// action of the entrypoint should be to call [`Thread::exit()`].
///
/// Closing the last handle to a thread does not terminate execution. In order to
/// forcefully kill a thread for which there is no available handle, use
/// `KernelObject::get_child()` to obtain a handle to ... | root_job = Job::root();
let proc = Process::create(&root_job, "proc", 0).expect("failed to create process");
let thread = Thread::create(&proc, "thread", 0).expect("failed to create thread");
let thread1 = Thread::create(&proc, "thread1", 0).expect("failed to create thread");
// allocat... | identifier_body | |
lib.rs | https://github.com/Geal/nom) parser combinator
//! framework.
//!
//! It is written in pure Rust, fast, and makes extensive use of zero-copy. A lot of care is taken
//! to ensure security and safety of this crate, including design (recursion limit, defensive
//! programming), tests, and fuzzing. It also aims to be pani... | //! - macros: these are generally previous (historic) versions of parsers, kept for compatibility.
//! They can sometime reduce the amount of code to write, but are hard to debug.
//! Parsers should be preferred when possible.
//!
//! ## Misc Notes | random_line_split | |
lib.rs | (code_byte: u8) -> ResponseCode {
use self::ResponseCode::*;
match code_byte {
x if x == NoDataExpected as u8 => NoDataExpected,
x if x == Pending as u8 => Pending,
x if x == DeviceError as u8 => DeviceError,
x if x == Success as u8 => Success,
_ => UnknownError,
}
}
... | response_code | identifier_name | |
lib.rs | ,
Bps115200 = 115200,
}
impl BpsRate {
/// Returns the `BpsRate` from a `u32` value.
pub fn parse_u32(bps_rate: u32) -> Result<BpsRate, EzoError> {
let bps = match bps_rate {
x if x == BpsRate::Bps300 as u32 => BpsRate::Bps300,
x if x == BpsRate::Bps1200 as u32 => BpsRate::B... | {
assert_eq!(response_code(255), ResponseCode::NoDataExpected);
} | identifier_body | |
lib.rs | => Pending,
x if x == DeviceError as u8 => DeviceError,
x if x == Success as u8 => Success,
_ => UnknownError,
}
}
/// Allowable baudrates used when changing the chip to UART mode.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BpsRate {
Bps300 = 300,
Bps1200 = 1200,
Bps2400 =... | assert_eq!(data, flipped_data);
}
#[test]
fn converts_valid_response_to_string() {
// empty nul-terminated string
assert_eq!(string_from_response_data(&b"\0"[..]).unwrap(), "");
// non-empty nul-terminated string
assert_eq!(string_from_response_data(&b"hello\0"[..])... | #[test]
fn turns_off_high_bits() {
let data: [u8; 11] = [63, 73, 44, 112, 72, 44, 49, 46, 57, 56, 0];
let mut flipped_data: [u8; 11] = [63, 73, 172, 112, 200, 172, 49, 46, 57, 56, 0];
turn_off_high_bits(&mut flipped_data); | random_line_split |
resource.go | _one WHERE state=0`
// index-icon
_indexIconSQL = `SELECT id,type,title,state,link,icon,weight,user_name,sttime,endtime,deltime,ctime,mtime FROM icon WHERE state=1 AND deltime=0 AND (type=1 OR (type=2 AND sttime>0))`
_playIconSQL = `SELECT icon1,hash1,icon2,hash2,stime FROM bar_icon WHERE stime<? AND etime>? AND is... | DefaultBanner | identifier_name | |
resource.go | ,style,style_param,top_margin,state,ctime,mtime FROM cmtbox WHERE state=1`
// update resource assignment etime
_updateResourceAssignmentEtime = `UPDATE resource_assignment SET etime=? WHERE id=?`
// update resource apply status
_updateResourceApplyStatus = `UPDATE resource_apply SET audit_state=? WHERE apply_group_... | err = nil | random_line_split | |
resource.go | , &rsc.Mark, &rsc.CTime, &rsc.MTime, &rsc.Level, &rsc.Type, &rsc.IsAd); err != nil {
log.Error("Resources rows.Scan err (%v)", err)
return
}
rsc.Size = size.String
rscs = append(rscs, rsc)
}
err = rows.Err()
return
}
// Assignment get assigment from db
func (d *Dao) Assignment(c context.Context) (asgs [... | {
var link string
icon := &model.IndexIcon{}
if err = rows.Scan(&icon.ID, &icon.Type, &icon.Title, &icon.State, &link, &icon.Icon,
&icon.Weight, &icon.UserName, &icon.StTime, &icon.EndTime, &icon.DelTime, &icon.CTime, &icon.MTime); err != nil {
log.Error("IndexIcon rows.Scan err (%v)", err)
return
}
... | conditional_block | |
resource.go | _updateResourceAssignmentEtime = `UPDATE resource_assignment SET etime=? WHERE id=?`
// update resource apply status
_updateResourceApplyStatus = `UPDATE resource_apply SET audit_state=? WHERE apply_group_id IN (%s)`
// insert resource logs
_inResourceLogger = `INSERT INTO resource_logger (uname,uid,module,oid,cont... | {
row := d.db.QueryRow(c, _defBannerSQL)
asg = &model.Assignment{}
if err = row.Scan(&asg.ID, &asg.Name, &asg.ContractID, &asg.ResID, &asg.Pic, &asg.LitPic,
&asg.URL, &asg.Rule, &asg.Weight, &asg.Agency, &asg.Price, &asg.Atype, &asg.Username); err != nil {
if err == sql.ErrNoRows {
asg = nil
err = nil
} ... | identifier_body | |
btrfs_tree_h.go | }
type btrfs_extent_inline_ref struct {
type_ uint8
offset uint64
}
/* old style backrefs item */
type btrfs_extent_ref_v0 struct {
root uint64
generation uint64
objectid uint64
count uint32
}
/* dev extents record free space on individual devices. The owner
* field points back to the chunk all... | chunk_to_extended | identifier_name | |
btrfs_tree_h.go | key per qgroup, (0, _BTRFS_QGROUP_INFO_KEY, qgroupid).
*/
/*
* Contains the user configured limits for the qgroup.
* One key per qgroup, (0, _BTRFS_QGROUP_LIMIT_KEY, qgroupid).
*/
/*
* Records the child-parent relationship of qgroups. For
* each relation, 2 keys are present:
* (childid, _BTRFS_QGROUP_RELATION... | last_snapshot uint64 | random_line_split | |
btrfs_tree_h.go | }
type btrfs_inode_ref struct {
index uint64
name_len uint16
}
/* name goes here */
type btrfs_inode_extref struct {
parent_objectid uint64
index uint64
name_len uint16
//name [0]uint8
}
/* name goes here */
type btrfs_timespec struct {
sec uint64
nsec uint32
}
type btrfs_ino... | {
return qgroupid >> uint32(qgroupLevelShift)
} | identifier_body | |
btrfs_tree_h.go |
generation uint64
objectid uint64
count uint32
}
/* dev extents record free space on individual devices. The owner
* field points back to the chunk allocation mapping tree that allocated
* the extent. The chunk tree uuid field is a way to double check the owner
*/
type btrfs_dev_extent struct {
chunk_... | {
flags |= uint64(availAllocBitSingle)
} | conditional_block | |
wordlattice.py | __(self):
return "\t".join([str(self.start_node), str(self.end_node), \
self.word.encode(sys.stdout.encoding), str(self.ac_score), str(self.lm_score)])
class Path:
# Constructs a path given a list of node IDs.
def __init__(self, links = []):
self.__links = links
def __repr__(self):
result = ... |
tokens = new_tokens
new_tokens = []
for path in tokens:
new_tokens.extend(self.expand_path_to_null_links(path))
tokens = new_tokens
print(len(tokens), "tokens @", word)
if tokens == []:
return []
result = []
for path in tokens:
if path.final_node() == self.end_node:
result.append(p... | new_tokens.extend(self.find_extensions(path, word)) | conditional_block |
wordlattice.py | __(self):
return "\t".join([str(self.start_node), str(self.end_node), \
self.word.encode(sys.stdout.encoding), str(self.ac_score), str(self.lm_score)])
class Path:
# Constructs a path given a list of node IDs.
def __init__(self, links = []):
self.__links = links
def __repr__(self):
result = ... | output_file.write("\tW=" + link.word)
output_file.write("\ta=" + str(link.ac_score))
output_file.write("\tv=0")
output_file.write("\tl=" + str(link.lm_score) + "\n")
# Finds a path from start node to end node through given words.
def find_paths(self, words):
tokens = self.expand_path_to_null_links(se... | output_file.write("# Header\n")
output_file.write("VERSION=1.1\n")
output_file.write("base=10\n")
output_file.write("dir=f\n")
output_file.write("lmscale=" + str(self.lm_scale) + "\n")
output_file.write("start=" + str(self.start_node) + "\n")
output_file.write("end=" + str(self.end_node) + "\n")
output_fi... | identifier_body |
wordlattice.py | __(self):
return "\t".join([str(self.start_node), str(self.end_node), \
self.word.encode(sys.stdout.encoding), str(self.ac_score), str(self.lm_score)])
class Path:
# Constructs a path given a list of node IDs.
def __init__(self, links = []):
self.__links = links
def __repr__(self):
result = ... | (self, memo={}):
result = WordLattice()
memo[id(self)] = result
result.__nodes = deepcopy(self.__nodes, memo)
result.__links = deepcopy(self.__links, memo)
result.__start_nodes_of_links = deepcopy(self.__start_nodes_of_links, memo)
result.start_node = self.start_node
result.end_node = self.end_node
resu... | __deepcopy__ | identifier_name |
wordlattice.py | __(self):
return "\t".join([str(self.start_node), str(self.end_node), \
self.word.encode(sys.stdout.encoding), str(self.ac_score), str(self.lm_score)])
class Path:
# Constructs a path given a list of node IDs.
def __init__(self, links = []):
self.__links = links
def __repr__(self):
result = ... | self.links.extend(other.links)
self.nodes.extend(other.nodes)
def __init__(self):
# A regular expression for fields such as E=997788 or W="that is" in an
# SLF file.
self.assignment_re = re.compile(r'(\S+)=(?:"((?:[^\\"]+|\\.)*)"|(\S+))')
def __deepcopy__(self, memo={}):
result = WordLattice()
me... | def __init__(self):
self.links = []
self.nodes = []
def extend(self, other): | random_line_split |
main01.go | ><body><h1>" +
"hello world</h1></body></html>"
w.Write([]byte(str))
}
func writeHeaderExample(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(501)
fmt.Fprintln(w, "No such service, try next door")
}
func headerExample(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "http://baidu.co... | (w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles(mPath + "test02/src/test/tmpl9.html")
t.Execute(w, r.FormValue("comment"))
}
func form(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles(mPath + "test02/src/test/form.html")
t.Execute(w, nil)
}
func process10(w http.Respons... | process9 | identifier_name |
main01.go | "github.com/julienschmidt/httprouter"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"runtime"
"time"
)
type HelloHandler struct {
}
func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello!")
}
type WorldHandler struct {
}
func (h *WorldHandler) ServeHT... | "database/sql"
"encoding/base64"
"fmt"
_ "github.com/go-sql-driver/mysql" | random_line_split | |
main01.go | Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: nil,
}
http.SetCookie(w, &rc)
val, _ := base64.URLEncoding.DecodeString(c.Value)
fmt.Fprintln(w, string(val))
}
}
var mPath = "D:/MyProgram/Go/github/"
//var mPath = "E:/go/project/"
func process2(w http.Response... | {
fmt.Println("err = " + err.Error())
} | conditional_block | |
main01.go | data, err := ioutil.ReadAll(file)
if err == nil {
fmt.Fprintln(w, string(data))
}
}
}
func writeExample(w http.ResponseWriter, r *http.Request) {
str := "<html> <head><title>Go web Programming</title></head><body><h1>" +
"hello world</h1></body></html>"
w.Write([]byte(str))
}
func writeHeaderExample(w ... | {
//r.ParseForm()
//fmt.Fprintln(w, r.Form)
r.ParseMultipartForm(1024)
//fmt.Fprintln(w, "(1)", r.FormValue("hello"))
//fmt.Fprintln(w, "(2)", r.PostFormValue("hello"))
//fmt.Fprintln(w, "(3)", r.PostForm)
//fmt.Fprintln(w, "(4)", r.MultipartForm)
//fileHeader := r.MultipartForm.File["uploaded"][0]
//file, er... | identifier_body | |
mod.rs | InitialSnapshot, RemoteTimestamp};
use self::progress::{LowerFrontier, UpperFrontier};
use self::sink::{EventSink, EventStream};
pub mod sink;
pub mod progress;
type SubscriberId = usize;
enum Event<T, D> {
Timely(TimelyEvent<T, D>),
Accepted((Sender, Receiver)),
Disconnected(SubscriberId),
Error(S... | return Ok(());
}
}
}
}
/// Sends `msg` to all connected subscribers.
fn broadcast(&self, msg: MessageBuf) -> io::Result<()> {
if self.subscribers.len() == 0 {
// nothing to do here
return Ok(());
}
let ... | // all still connected subscribers | random_line_split |
mod.rs |
.map(Event::Timely)
.map_err(|_| unreachable!())
.chain(stream::once(Ok(Event::ShutdownRequested)));
let subscribers = subscribers.map_err(|_| unreachable!());
// all of which we merge into a single stream
let events = listener.select(subscribers).select(time... | lock | identifier_name | |
tof_coincidences_jitters_correct_Paola.py |
### read sensor positions from database
DataSiPM = db.DataSiPMsim_only('petalo', 0)
DataSiPM_idx = DataSiPM.set_index('SensorID')
n_sipms = len(DataSiPM)
first_sipm = DataSiPM_idx.index.min()
### parameters for single photoelectron convolution in SiPM response
tau_sipm = [100, 15000]
time_wind... | parser = argparse.ArgumentParser()
parser.add_argument('first_file' , type = int, help = "first file (inclusive)" )
parser.add_argument('n_files' , type = int, help = "number of files to analize" )
parser.add_argument('thr_r' , type = int, help = "threshold in r coordinate" )
parser.add_arg... | identifier_body | |
tof_coincidences_jitters_correct_Paola.py | = np.arange(0, 5000)
#time = time + (time_bin/2)
spe_resp, norm = tf.apply_spe_dist(time, tau_sipm)
sigma_sipm = 0 #80 #ps
sigma_elec = 0 #30 #ps
#n_pe = 1
arguments = parse_args(sys.argv)
start = arguments.first_file
numb = arguments.n_files
thr_r = arguments.thr_r
thr_phi = arguments... | evt_tof = evt_tof[evt_tof.sensor_id.isin(-ids_over_thr)]
if len(evt_tof) == 0:
boh2 += 1
continue
pos1, pos2, q1, q2, true_pos1, true_pos2, true_t1, true_t2, sns1, sns2 = rf.reconstruct_coincidences(evt_sns, charge_range, DataSiPM_idx, evt_parts, evt_hits)
if l... | random_line_split | |
tof_coincidences_jitters_correct_Paola.py | (args):
parser = argparse.ArgumentParser()
parser.add_argument('first_file' , type = int, help = "first file (inclusive)" )
parser.add_argument('n_files' , type = int, help = "number of files to analize" )
parser.add_argument('thr_r' , type = int, help = "threshold in r coordinate" )
pa... | parse_args | identifier_name | |
tof_coincidences_jitters_correct_Paola.py | = np.arange(0, 5000)
#time = time + (time_bin/2)
spe_resp, norm = tf.apply_spe_dist(time, tau_sipm)
sigma_sipm = 0 #80 #ps
sigma_elec = 0 #30 #ps
#n_pe = 1
arguments = parse_args(sys.argv)
start = arguments.first_file
numb = arguments.n_files
thr_r = arguments.thr_r
thr_phi = arguments... |
pos1_phi = rf.from_cartesian_to_cyl(np.array(pos1r))[:,1]
diff_sign = min(pos1_phi ) < 0 < max(pos1_phi)
if diff_sign & (np.abs(np.min(pos1_phi))>np.pi/2.):
pos1_phi[pos1_phi<0] = np.pi + np.pi + pos1_phi[pos1_phi<0]
mean_phi = np.average(pos1_phi, weights=q1r)
var_... | c1 += 1
continue | conditional_block |
tooltip.directive.ts | material design tooltip to the host element. Animates the showing and
* hiding of a tooltip provided position (defaults to below the element).
*/
@Directive({
selector: '[appTooltip]',
exportAs: 'appTooltip',
host: {
'(longpress)': 'show()',
'(keydown)': '_handleKeydown($event)',
'(touchend)': 'hide(' + TOU... | (): void {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._tooltipInstance = null;
}
/**
* Returns the origin position and a fallback position based on the user's position preference.
* The fallback position is the inverse of the origin (e.g. 'below' -> 'above').... | _disposeTooltip | identifier_name |
tooltip.directive.ts | message = value != null ? `${value}`.trim() : '';
this._updateTooltipMessage();
}
/** Classes to be passed to the tooltip. Supports the same syntax as `ngClass`. */
@Input('appTooltipClass')
get tooltipClass() { return this._tooltipClass; }
set tooltipClass(value: string | string[] | Set<string> | { [key: strin... | {
if (x === 'end') {
x = 'start';
} else if (x === 'start') {
x = 'end';
}
} | conditional_block | |
tooltip.directive.ts | material design tooltip to the host element. Animates the showing and
* hiding of a tooltip provided position (defaults to below the element).
*/
@Directive({
selector: '[appTooltip]',
exportAs: 'appTooltip',
host: {
'(longpress)': 'show()',
'(keydown)': '_handleKeydown($event)',
'(touchend)': 'hide(' + TOU... |
set tooltipClass(value: string | string[] | Set<string> | { [key: string]: any }) {
this._tooltipClass = value;
if (this._tooltipInstance) {
this._setTooltipClass(this._tooltipClass);
}
}
private _enterListener: Function;
private _leaveListener: Function;
constructor (
renderer: Renderer2,
private ... | { return this._tooltipClass; } | identifier_body |
tooltip.directive.ts | material design tooltip to the host element. Animates the showing and
* hiding of a tooltip provided position (defaults to below the element).
*/
@Directive({
selector: '[appTooltip]',
exportAs: 'appTooltip',
host: {
'(longpress)': 'show()',
'(keydown)': '_handleKeydown($event)',
'(touchend)': 'hide(' + TOU... | if (this.position == 'above') {
position = { overlayX: 'center', overlayY: 'bottom' };
} else if (this.position | let position: OverlayConnectionPosition;
| random_line_split |
lib.rs | _queriable_and_has_subresources() -> Result<(), Box<dyn std::error::Error>> {
use crate::runtime::wait::{await_condition, conditions};
use serde_json::json;
let client = Client::try_default().await?;
let ssapply = PatchParams::apply("kube").force();
let crds: Api<CustomResourceD... | {
Api::default_namespaced_with(client.clone(), &ar)
} | conditional_block | |
lib.rs | (10),
//! await_condition(crds, "foos.clux.dev", conditions::is_crd_established())
//! ).await?;
//!
//! // Watch for changes to foos in the configured namespace
//! let foos: Api<Foo> = Api::default_namespaced(client.clone());
//! let wc = watcher::Config::default();
//! let mut apply_strea... | #[cfg(test)]
#[cfg(all(feature = "derive", feature = "client"))]
mod test {
use crate::{
api::{DeleteParams, Patch, PatchParams},
Api, Client, CustomResourceExt, Resource, ResourceExt,
};
use kube_derive::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
... | pub use kube_core as core;
// Tests that require a cluster and the complete feature set
// Can be run with `cargo test -p kube --lib --features=runtime,derive -- --ignored` | random_line_split |
lib.rs | ();
//! let mut apply_stream = watcher(foos, wc).applied_objects().boxed();
//! while let Some(f) = apply_stream.try_next().await? {
//! println!("saw apply to {}", f.name_any());
//! }
//! Ok(())
//! }
//! ```
//!
//! For details, see:
//!
//! - [`CustomResource`](crate::CustomResource) for doc... | ContainerSimple | identifier_name | |
lib.rs | !(o.status.unwrap().replicas, 1, "scale replicas got patched");
let linked_replicas = o.spec.unwrap().replicas.unwrap();
assert_eq!(linked_replicas, 3, "patch_scale updates linked spec.replicas");
}
// cleanup
foos.delete_collection(&DeleteParams::default(), &Default::de... | {
|obj: Option<&Pod>| {
if let Some(o) = obj {
if let Some(s) = &o.status {
if let Some(conds) = &s.conditions {
if let Some(pcond) = conds.iter().find(|c| c.type_ == "ContainersReady") {
... | identifier_body | |
testone.py | "0" or h1str == 0:
h1str = clientlist[i].get_pk()['pk']
print("h1str", h1str)
pk = group_signature.pkGen(h1str)
print("pk---------------\n", pk)
if (group_signature.verifyUsk(usklist[i], vklist[i], pk, GID, UID)):
count = count + 1
else:
... | append(op | conditional_block | |
testone.py | )
b4 = self.group.gen1_0(1)
b5 = self.group.gen1_0(1)
r2 = self.group.random(ZR)
for i in range(k):
b0 = b0 * (usklist[i]['b0'] ** L[i])
b3 = b3 * (usklist[i]['b3'] ** L[i])
b4 = b4 * (usklist[i]['b4'] ** L[i])
b5 = b5 * (usklist[i]['b5']... | random_line_split | ||
testone.py | 389375981104409894060310698729022957801238449570622103067828518416602275957863668289683360250722835022304456841105526036470008237775051984811323, 862537748555943361001122447731987661405436458862545177179548603003392540530328380518694788420155531238391922289886044667763424887444361610972254938158280]"
u4str = "[... | (self, usk, vk, pk, GID, UID):
g = pk['g']
g2 = pk['g2']
u0 = pk['u0']
u1 = pk['u1']
u2 = pk['u2']
u3 = pk['u3']
u4 = pk['u4']
b0 = usk['b0']
b5 | verifyUsk | identifier_name |
testone.py | ID)) ** k
e3 = (pk['n'] ** UID) * (pair(pk['h1'], pk['g2']) ** k)
# 产生pok
f = pk['u0'] * (pk['u1'] ** GID)
gp = pair(pk['h1'], pk['g2'])
k1 = self.group.random(ZR)
k2 = self.group.random(ZR)
k3 = self.group.random(ZR)
r1 = (pk['u2'] ** k1) * (pk['u4'] *... | args=(account, ssiglistone[i], userID, permlinklistone[i], steemd, wallet))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
def mul_annoy_tx(usk, pk, UID):
ssiglist = []
permlinklist = []
threads = | identifier_body | |
app.go | ) User {
session := getSession(r)
uid, ok := session.Values["user_id"]
if !ok || uid == nil {
return User{}
}
u := User{}
err := db.Get(&u, "SELECT * FROM `users` WHERE `id` = ?", uid)
if err != nil {
return User{}
}
return u
}
func getFlash(w http.ResponseWriter, r *http.Request, key string) string {
... | p.StatusOK)
}
func getLogin(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("login.html")),
).Execute(w, struct {
Me User
Flash strin... | teHeader(htt | identifier_name |
app.go | _id` = ?", p.ID)
if err != nil {
return nil, err
}
query := "SELECT * FROM `comments` WHERE `post_id` = ? ORDER BY `created_at` DESC"
if !allComments {
query += " LIMIT 3"
}
var comments []Comment
err = db.Select(&comments, query, p.ID)
if err != nil {
return nil, err
}
for i := 0; i < le... | random_line_split | ||
app.go | notice"] = "アカウント名かパスワードが間違っています"
session.Save(r, w)
http.Redirect(w, r, "/login", http.StatusFound)
}
}
func getRegister(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout... | return
}
mime := ""
if file != nil {
// 投稿のContent-Type | conditional_block | |
app.go | _at` FROM `posts` ORDER BY `created_at` DESC")
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), false)
if err != nil {
log.Print(err)
return
}
fmap := template.FuncMap{
"imageURL": imageURL,
}
template.Must(template.New("layout.html").Funcs(fmap).ParseFiles(... | e)
_, err := w.Write(post.Imgdata)
if err != nil {
log.Print(err)
return
}
return
}
w.WriteHeader(http.StatusNotFound)
}
func postComment(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if r.FormValue... | identifier_body | |
shuffle.py | icarpeta/proyectos/Ejercicios_Pyhton/biblioteca/Seattle_Party.flac"},
"King_Kunta":
{"track-number": 3, "artist": "Kendrick Lamar", "album": "To Pimp A Butterfly", "location": "/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/King_Kunta.mp3"},
"Gorilaz - Clint Eastwoo... |
"""def creadorIndicesRandom(libreria):
assert isinstance(libreria,dict),"no es un diccionario!"
indices=[]
indiceRandom=random.randrange(1,len(libreria)+1)
indices.append(indiceRandom)
while len(indices)!=len(libreria):
while indiceRandom in indices:
indiceRandom=random.randran... | random_line_split | |
shuffle.py | wood.mp3":
{"track-number": 3, "artist": "Kendrick Lamar", "album": "To Pimp A Butterfly", "location": "/home/ulises/Música/gorillaz/Gorilaz - Clint Eastwood.mp3"}
}"""
def checkSeleccionaCancionRandom(cancion, libreria):
assert isinstance(cancion, str)
assert isinstance(libreri... | me]={"location":thePath+'/'+fileName}
| conditional_block | |
shuffle.py | icarpeta/proyectos/Ejercicios_Pyhton/biblioteca/Seattle_Party.flac"},
"King_Kunta":
{"track-number": 3, "artist": "Kendrick Lamar", "album": "To Pimp A Butterfly", "location": "/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/King_Kunta.mp3"},
"Gorilaz - Clint Eastwoo... | reria=dict()
musicaPath="/home/ulises/Música/"
musicaArbol=os.walk(musicaPath)
for path,sub,fileList in musicaArbol:
for grupo in sub:
print(grupo)
break
while True:
print("¿Que quieres escuchar?")
NombreGrupo=input()
if os.path.exists(musicaPath+No... | eriaGrupo():
lib | identifier_name |
shuffle.py | arpeta/proyectos/Ejercicios_Pyhton/biblioteca/Seattle_Party.flac"},
"King_Kunta":
{"track-number": 3, "artist": "Kendrick Lamar", "album": "To Pimp A Butterfly", "location": "/home/ulises/Micarpeta/proyectos/Ejercicios_Pyhton/biblioteca/King_Kunta.mp3"},
"Gorilaz - Clint Eastwood.... | # a la linea de comandos para invocar a VLC
#lineaComandoVLC = lineaComandoVLC + separador + str(rutaAccesoFichero)
lineaComandoVLC.append(str(rutaAccesoFichero))
else:
print("no lo encuentro",os.path.exists(str(rutaAccesoFichero)))
... | bprocess
import shlex
import os
linuxPathVLC = "/usr/bin/vlc"
lineaComandoVLC = [linuxPathVLC]
separador = " "
for numeroCancion in sorted(playList.keys()):
tituloCancion = playList[numeroCancion]
try:
rutaAccesoFichero = getLocalización(libreria,titulo... | identifier_body |
GeneticAlgorithm.py | self.parameters['population_size']
self.edge_domain = self.parameters['edge_domain']
self.tournament_size = self.parameters['tournament_size']
self.parents_per_offspring = self.parameters['parents_per_offspring']
self.mutation_probability = self.parameters['mutation_probability']
... |
return parents
# create the children from the selected parents
def breed(self, parents):
children = []
for breeding_group in range(int(len(parents)/self.parents_per_offspring)):
picked_parents = parents[breeding_group*self.parents_per_offspring:breeding_group*self.parents_p... | print('Error: no appropriate parent selection method selected') | conditional_block |
GeneticAlgorithm.py | self.parameters['population_size']
self.edge_domain = self.parameters['edge_domain']
self.tournament_size = self.parameters['tournament_size']
self.parents_per_offspring = self.parameters['parents_per_offspring']
self.mutation_probability = self.parameters['mutation_probability']
... | return fittest_individual
# perform a tournament to choose the parents that reproduce
def tournament(self, population_fitness, population):
# match up individuals for tournament
reproductive_individuals = []
random.shuffle(self.integer_list) # randomize the integer_list to dete... | self.init_run()
while self.stop_condition():
self.step()
self.record_of_all_fitnesses_each_generation.append(np.ndarray.tolist(self.survived_fitnesses))
#save a record of all fitnesses of all individuals in all generations to a pickle file
pickle_out = open('task_1_GA_' ... | identifier_body |
GeneticAlgorithm.py | = self.parameters['population_size']
self.edge_domain = self.parameters['edge_domain']
self.tournament_size = self.parameters['tournament_size']
self.parents_per_offspring = self.parameters['parents_per_offspring']
self.mutation_probability = self.parameters['mutation_probability']
... | self.fitness_type = 0
self.selection_fitness_score = self.fitness_order[self.fitness_type]
# generate an initial population
self.survived_population = np.random.uniform(self.edge_domain[0], self.edge_domain[1], (self.population_size, edges))
# determine and make an array of the f... | edges = self.env.get_num_sensors() * self.hidden_neurons + 5 * self.hidden_neurons # not sure why this should be the right amount of edges
# set the first fitness type to select on | random_line_split |
GeneticAlgorithm.py | ):
return self.selection_fitness_score != 'STOP' and self.evaluation_nr < self.max_fitness_evaluations
def init_run(self):
# initialize population
# make a list of integers to be able to randomize the order of the population without losing the connectedness of individuals and fitness
... | survivor_selection | identifier_name | |
test_error_reporting.py | in Python 3 return repr()
us = u'\xfc' # bytes(us) fails; str(us) fails in Python 2
be = Exception(bs) # unicode(be) fails
ue = Exception(us) # bytes(ue) fails, str(ue) fails in Python 2;
# unicode(ue) fails in Python < 2.6 (issue2517_)
# .. _issue2517: h... | ocale.setlocale(locale.LC_ALL, oldlocale)
| conditional_block | |
test_error_reporting.py | from io import StringIO, BytesIO
except ImportError: # new in Python 2.6
from StringIO import StringIO
BytesIO = StringIO
import DocutilsTestSupport # must be imported before docutils
from docutils import core, parsers, frontend, utils
from docutils.utils.error_reporting import SafeString, Err... |
import unittest
import sys, os
import codecs
try: # from standard library module `io` | random_line_split | |
test_error_reporting.py |
BytesIO = StringIO
import DocutilsTestSupport # must be imported before docutils
from docutils import core, parsers, frontend, utils
from docutils.utils.error_reporting import SafeString, ErrorString, ErrorOutput
from docutils._compat import b, bytes
oldlocale = None
if sys.version_info < (3,0): # p... |
class ErrorOutputTests(unittest.TestCase):
def test_defaults(self):
e = ErrorOutput()
self.assertEqual(e.stream, sys.stderr)
def test_bbuf(self):
buf = BBuf() # buffer storing byte string
e = ErrorOutput(buf, encoding='ascii')
# write byte-string as-is
e.write(b... | ef write(self, data):
# emulate Python 3 handling of stdout, stderr
if isinstance(data, bytes):
raise TypeError('must be unicode, not bytes')
super(UBuf, self).write(data)
| identifier_body |
test_error_reporting.py |
BytesIO = StringIO
import DocutilsTestSupport # must be imported before docutils
from docutils import core, parsers, frontend, utils
from docutils.utils.error_reporting import SafeString, ErrorString, ErrorOutput
from docutils._compat import b, bytes
oldlocale = None
if sys.version_info < (3,0): # p... | self, data):
if isinstance(data, unicode):
data.encode('ascii', 'strict')
super(BBuf, self).write(data)
# Stub: Buffer expecting unicode string:
class UBuf(StringIO, object): # super class object required by Python <= 2.5
def write(self, data):
# emulate Python 3 handling of std... | rite( | identifier_name |
clustering.go | .New("missing locker type field")
}
func (a *App) leaderKey() string {
return fmt.Sprintf("gnmic/%s/leader", a.Config.Clustering.ClusterName)
}
func (a *App) inCluster() bool {
if a.Config == nil {
return false
}
return !(a.Config.Clustering == nil)
}
func (a *App) apiServiceRegistration() {
addr, port, _ := ... | intf("starting locker type %q", lockerType)
if initializer, ok := lockers.Lockers[lockerType.(string)]; ok {
lock := initializer()
err := lock.Init(a.ctx, a.Config.Clustering.Locker, lockers.WithLogger(a.Logger))
if err != nil {
return err
}
a.locker = lock
return nil
}
return fmt.Errorf("un... | conditional_block | |
clustering.go | .ctx)
defer cancel()
go func() {
go a.watchMembers(ctx)
a.Logger.Printf("leader waiting %s before dispatching targets", a.Config.Clustering.LeaderWaitTimer)
time.Sleep(a.Config.Clustering.LeaderWaitTimer)
a.Logger.Printf("leader done waiting, starting loader and dispatching targets")
go a.startLoader(ctx)
... | if len(load) == 0 { | random_line_split | |
clustering.go | target has no suitable matching services,
// continue to next target without wait
continue
}
}
//a.m.RUnlock()
cancel()
select {
case <-ctx.Done():
return
default:
time.Sleep(a.Config.Clustering.TargetsWatchTimer)
}
}
}
}
func (a *App) dispatchTarget(ctx context.Context, ... | x context.Co | identifier_name | |
clustering.go | .Clustering.InstanceName))
if err != nil {
a.Logger.Printf("failed to acquire leader lock: %v", err)
time.Sleep(retryTimer)
continue
}
if !a.isLeader {
time.Sleep(retryTimer)
continue
}
a.isLeader = true
a.Logger.Printf("%q became the leader", a.Config.Clustering.InstanceName)
break
}
ctx... | err := a.locker.WatchServices(ctx, serviceName, []string{"cluster-name=" + a.Config.Clustering.ClusterName}, membersChan, a.Config.Clustering.ServicesWatchTimer)
if err != nil {
a.Logger.Printf("failed getting services: %v", err)
time.Sleep(retryTimer)
goto START
}
}
}
func (a *App)
updateServices(srv... | := fmt.Sprintf("%s-%s", a.Config.Clustering.ClusterName, apiServiceName)
START:
select {
case <-ctx.Done():
return
default:
membersChan := make(chan []*lockers.Service)
go func() {
for {
select {
case <-ctx.Done():
return
case srvs, ok := <-membersChan:
if !ok {
return
}
... | identifier_body |
views.py | *
from .feeds import EventFeed
import mijnhercules.settings as settings
from .models import Match, Location
from .forms import MatchPresence
from members.models import Team, Player, MembershipHercules, Pass
# from mijnhercules.forms import *
from members.forms import EditPlayerForm, ArrangeSubstitutesForm, importMatc... | (request, match):
u1 = User.objects.get(username=request.user.username)
teampk = u1.get_profile().team_member.pk
try:
m = Match.objects.get(id=match)
except Match.DoesNotExist:
raise Http404
if request.method == 'POST' and m.isTeam(teampk):
form = ArrangeSubstitutesForm(... | editMatch | identifier_name |
views.py | *
from .feeds import EventFeed
import mijnhercules.settings as settings
from .models import Match, Location
from .forms import MatchPresence
from members.models import Team, Player, MembershipHercules, Pass
# from mijnhercules.forms import *
from members.forms import EditPlayerForm, ArrangeSubstitutesForm, importMatc... |
return render(request, 'savematch.html', {'form': form, 'matches': matches})
def viewMyMatches(request):
u1 = User.objects.get(username=request.user.username)
teampk = u1.get_profile().team_member.pk
matches = Match.objects.get_my_matches(teampk)
presentmatches = {}
for m in matches:
i... | form = importMatchesForm() | conditional_block |
views.py | return cal.__call__(request)
@login_required
def viewMatch(request, match):
try:
m = Match.objects.get(id=match)
except Match.DoesNotExist:
raise Http404
teams = m.getHercules()
substituteoptions = False
substitutes = {}
for t in teams:
if m.getSubstitutes(t.pk) !... | match = Match.objects.get(pk=matchpk)
match.removeSubstitute(teampk=teampk, player =Player.objects.get(pk=substitutepk))
# return render(request, 'substitutewilling_cancellation.html')
messages.add_message(request, messages.SUCCESS, 'Je afmelding als mogelijke invaller is doorgegeven.')
# return render(... | identifier_body | |
views.py | import *
from .feeds import EventFeed
import mijnhercules.settings as settings
from .models import Match, Location
from .forms import MatchPresence
from members.models import Team, Player, MembershipHercules, Pass
# from mijnhercules.forms import *
from members.forms import EditPlayerForm, ArrangeSubstitutesForm, imp... | if form.is_valid():
cd = form.cleaned_data
# m.substitutesneeded = cd['substitutesneeded']
m.setSubstitutes(team = teampk, amountsubsneeded = cd['substitutesneeded'])
m.save()
return render(request, 'player/editplayer_complete.html')
else:
... | if request.method == 'POST' and m.isTeam(teampk):
form = ArrangeSubstitutesForm(request.POST) | random_line_split |
hotflip.py | to compute is") and a version
# where the full prefix is discovered by HotFlip without any assistance.
preprefix_ids = [self.tokenizer.bos_token_id] if self.tokenizer.bos_token_id else []
if preprefix:
preprefix_ids.extend(self.tokenizer.encode(preprefix))
self.preprefix_ids... |
def _set_prefix_ids(self, new_ids: torch.Tensor) -> None:
assert new_ids.ndim == 1, "cannot set prefix with more than 1 dim (need list of IDs)"
# Track steps since new prefix to enable early stopping
if (self.prefix_ids is not None) and (self.prefix_ids == new_ids).all():
... | """Allow prefix models to stop early."""
if self.args.early_stopping_steps == -1:
return False
return self._steps_since_new_prefix >= self.args.early_stopping_steps | identifier_body |
hotflip.py | model: transformers.PreTrainedModel,
tokenizer: transformers.PreTrainedTokenizer,
preprefix: str = ''
):
super().__init__(
args=args, loss_func=loss_func, model=model, tokenizer=tokenizer, preprefix=preprefix
)
# HotFlip-specific parameters... | args: argparse.Namespace,
loss_func: PrefixLoss, | random_line_split | |
hotflip.py | to compute is") and a version
# where the full prefix is discovered by HotFlip without any assistance.
preprefix_ids = [self.tokenizer.bos_token_id] if self.tokenizer.bos_token_id else []
if preprefix:
preprefix_ids.extend(self.tokenizer.encode(preprefix))
self.preprefix_ids... |
@property
def _prefix_token_grad(self) -> torch.Tensor:
"""Gradient of the prefix tokens wrt the token embedding matrix."""
return torch.einsum('nd,vd->nv', self.prefix_embedding.grad, self.token_embedding.weight)
def compute_loss_and_call_backward(
self,
x... | print("*" * 30)
print(f"Epoch {epoch}. Closest tokens to '{prefix_str}':")
word_distances = ((self.token_embedding.weight - self.prefix_embedding.reshape(1, emb_dim))**2).sum(1)
assert word_distances.shape == (50_257,)
topk_closest_words = word_distances.topk(k=TOP_K, l... | conditional_block |
hotflip.py | compute is") and a version
# where the full prefix is discovered by HotFlip without any assistance.
preprefix_ids = [self.tokenizer.bos_token_id] if self.tokenizer.bos_token_id else []
if preprefix:
preprefix_ids.extend(self.tokenizer.encode(preprefix))
self.preprefix_ids = ... | (self) -> bool:
"""Allow prefix models to stop early."""
if self.args.early_stopping_steps == -1:
return False
return self._steps_since_new_prefix >= self.args.early_stopping_steps
def _set_prefix_ids(self, new_ids: torch.Tensor) -> None:
assert new_ids.ndim == 1, "c... | check_early_stop | identifier_name |
cartesian.rs | a>(collections: &'a [C]) -> Product<'a, C, T>
where
&'a C: IntoIterator<Item = &'a T>,
{
// We start with fresh iterators and a `next_item` full of `None`s.
let mut iterators = collections.iter().map(<&C>::into_iter).collect::<Vec<_>>();
let next_item = iterators.iter_mut().map(Iterator::next).collect()... | ter | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.