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 |
|---|---|---|---|---|
downloadtaskmgr.go | package downloadtaskmgr
import (
"errors"
"io"
"math"
"net"
"net/http"
"os"
"path"
"sort"
"strings"
"sync"
"time"
"github.com/daqnext/meson-common/common/logger"
)
type DownloadInfo struct {
TargetUrl string
BindName string
FileName string
Continent string
Country string
Area ... | .NewTicker(spaceTime)
//lastWtn := int64(0)
count := 0
for {
count++
if stop {
break
}
select {
case <-ticker.C:
if task.Status == Task_Break {
srcWithCloser.Close()
}
task.DownloadedSize = written
useTime := count * 1000
speed := float64(written) / float64(useTime)
task.SpeedKBs ... | {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
//fmt.Println(ew.Error())
if task.Status == Task_Break &&
(strings.Contains(err.Error(), "http: read on closed response body") ||
strings.Contains(err.Error(), "use of closed ne... | conditional_block |
main.go | package runjson
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/seerx/runjson/internal/util"
"github.com/seerx/runjson/internal/runner"
"github.com/seerx/runjson/pkg/graph"
"github.com/seerx/runjson/pkg/context"
"github.com/seerx/runjson/internal/runner/arguments/request"
"gith... | lt of [%s] not found", jr.Name)
}
return rsp, nil
}
// New 新建 Runner
func New() *Runner {
//log := logrus.Logger{
// Level: logrus.WarnLevel,
// Formatter: &logrus.TextFormatter{},
//}
return &Runner{
APIInfo: &graph.APIInfo{
Groups: nil,
Request: map[string]*graph.ObjectInfo{},
Response: map[... | l, fmt.Errorf("resu | identifier_body |
main.go | package runjson
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/seerx/runjson/internal/util"
"github.com/seerx/runjson/internal/runner"
"github.com/seerx/runjson/pkg/graph"
"github.com/seerx/runjson/pkg/context"
"github.com/seerx/runjson/internal/runner/arguments/request"
"gith... | Description
svcInfo.Deprecated = info.Deprecated
svcInfo.History = info.History
svcInfo.InputIsRequire = info.InputIsRequire
svc.SetRequestArgRequire(svcInfo.InputIsRequire)
}
grp.AddService(svcInfo)
//grp. = append(grp.Funcs, fn)
r.service.Add(svc)
}
}
}
return nil
}
| loaderTyp, method.Name)
if info != nil {
svcInfo.Description = info. | conditional_block |
main.go | package runjson
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/seerx/runjson/internal/util"
"github.com/seerx/runjson/internal/runner"
"github.com/seerx/runjson/pkg/graph"
"github.com/seerx/runjson/pkg/context"
"github.com/seerx/runjson/internal/runner/arguments/request"
"gith... | oaders: nil,
service: runner.New(),
injector: inject.NewManager(),
requestObjectManager: request.NewRequestObjectManager(),
}
}
// Register 注册功能
func (r *Runner) Register(loaders ...rj.Loader) {
r.loaders = append(r.loaders, loaders...)
}
// RegisterProvider 注册注入函数
func (... | l | identifier_name |
main.go | package runjson
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/seerx/runjson/internal/util"
"github.com/seerx/runjson/internal/runner"
"github.com/seerx/runjson/pkg/graph"
"github.com/seerx/runjson/pkg/context"
"github.com/seerx/runjson/internal/runner/arguments/request"
"gith... | r.afterExecute = fn
return r
}
type results struct {
response rj.Response
run *Runner
count int
index int
}
// CallCount 调用个数
func (r *results) CallCount() int {
return r.count
}
// CallIndex 调用次序
func (r *results) CallIndex() int {
return r.index
}
func (r *results) Get(method interface{}) ([]*r... |
// AfterExecute 在单个任务执行后拦截
func (r *Runner) AfterExecute(fn AfterExecute) *Runner { | random_line_split |
sync.go | package cmd
import (
"context"
"fmt"
"os"
runtimevar "github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/runtime"
"github.com/loft-sh/devspace/pkg/devspace/config/localcache"
"github.com/loft-sh/devspace/pkg/devspace/config/versions"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/contex... |
if cmd.DownloadOnInitialSync {
syncConfig.InitialSync = latest.InitialSyncStrategyPreferLocal
} else {
syncConfig.InitialSync = latest.InitialSyncStrategyMirrorLocal
}
if cmd.InitialSync != "" {
if !versions.ValidInitialSyncStrategy(latest.InitialSyncStrategy(cmd.InitialSync)) {
return options, errors.E... | {
options = options.WithNamespace(cmd.Namespace)
} | conditional_block |
sync.go | package cmd
import (
"context"
"fmt"
"os"
runtimevar "github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/runtime"
"github.com/loft-sh/devspace/pkg/devspace/config/localcache"
"github.com/loft-sh/devspace/pkg/devspace/config/versions"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/contex... | }
syncConfig.InitialSync = latest.InitialSyncStrategy(cmd.InitialSync)
}
if cmd.Polling {
syncConfig.Polling = cmd.Polling
}
return options, nil
} | random_line_split | |
sync.go | package cmd
import (
"context"
"fmt"
"os"
runtimevar "github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/runtime"
"github.com/loft-sh/devspace/pkg/devspace/config/localcache"
"github.com/loft-sh/devspace/pkg/devspace/config/versions"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/contex... |
type nameConfig struct {
name string
devPod *latest.DevPod
containerName string
syncConfig *latest.SyncConfig
}
// Run executes the command logic
func (cmd *SyncCmd) Run(f factory.Factory) error {
if cmd.Ctx == nil {
var cancelFn context.CancelFunc
cmd.Ctx, cancelFn = context.WithCancel(c... | {
cmd := &SyncCmd{GlobalFlags: globalFlags}
syncCmd := &cobra.Command{
Use: "sync",
Short: "Starts a bi-directional sync between the target container and the local path",
Long: `
#############################################################################
################### devspace sync ##################... | identifier_body |
sync.go | package cmd
import (
"context"
"fmt"
"os"
runtimevar "github.com/loft-sh/devspace/pkg/devspace/config/loader/variable/runtime"
"github.com/loft-sh/devspace/pkg/devspace/config/localcache"
"github.com/loft-sh/devspace/pkg/devspace/config/versions"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/contex... | (f factory.Factory) error {
if cmd.Ctx == nil {
var cancelFn context.CancelFunc
cmd.Ctx, cancelFn = context.WithCancel(context.Background())
defer cancelFn()
}
// Switch working directory
if cmd.ConfigPath != "" {
_, err := os.Stat(cmd.ConfigPath)
if err != nil {
return errors.Errorf("--config is spec... | Run | identifier_name |
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... |
ReadPoolHandle::Yatp {
remote,
running_tasks,
max_tasks,
..
} => {
let running_tasks = running_tasks.clone();
// Note that the running task number limit is not strict.
// If several t... | {
let pool = match priority {
CommandPri::High => read_pool_high,
CommandPri::Normal => read_pool_normal,
CommandPri::Low => read_pool_low,
};
pool.spawn(f)?;
} | conditional_block |
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... | remote: pool.remote().clone(),
running_tasks: running_tasks.clone(),
max_tasks: *max_tasks,
pool_size: *pool_size,
},
}
}
}
#[derive(Clone)]
pub enum ReadPoolHandle {
FuturePools {
read_pool_high: FuturePool,
re... | pool,
running_tasks,
max_tasks,
pool_size,
} => ReadPoolHandle::Yatp { | random_line_split |
read_pool.rs | // Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0.
use futures::channel::oneshot;
use futures::future::TryFutureExt;
use prometheus::IntGauge;
use std::future::Future;
use std::sync::{Arc, Mutex};
use thiserror::Error;
use yatp::pool::Remote;
use yatp::queue::Extras;
use yatp::task::future::Task... | (
max_concurrent_reads: usize,
remote: Remote,
extras: Extras,
pending_reads_gauge: IntGauge,
) -> Self {
let pool = yatp::pool::Pool::new(
max_concurrent_reads,
remote,
extras,
);
Self {
pool,
pendin... | new | identifier_name |
main.js | jQuery(function($) {'use strict';
// Navigation Scroll
$(window).scroll(function(event) {
//Scroll();
});
$('.navbar-collapse ul li a').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 5}, 1000);
return false;
});
/* User define function
function Scroll() {
va... |
}
});
});
};
$('.animated-number').bind('inview', function(event, visible, visiblePartX, visiblePartY) {
var $this = $(this);
if (visible) {
$this.animateNumbers($this.data('digit'), false, $this.data('duration'));
$this.unbind('inview');
}
});
});
// Contact form
/*var form = ... | {
$this.text(stop);
if (commas) { $this.text($this.text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")); }
} | conditional_block |
main.js | jQuery(function($) {'use strict';
// Navigation Scroll
$(window).scroll(function(event) {
//Scroll();
});
$('.navbar-collapse ul li a').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 5}, 1000);
return false;
});
/* User define function
function Scroll() {
va... | $portfolio.isotope({
itemSelector : '.portfolio-item',
layoutMode : 'fitRows'
});
$portfolio_selectors.on('click', function(){
$portfolio_selectors.removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
$portfolio.isotope({ filter: selector });
retur... | random_line_split | |
operator.go | package workflowrun
import (
"context"
stderr "errors"
"fmt"
"os"
"reflect"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record... |
if status.Pod == nil {
log.WithField("wfr", o.wfr.Name).
WithField("stg", stg).
Warn("Pod information is missing, can't clean the pod.")
continue
}
err := o.clusterClient.CoreV1().Pods(status.Pod.Namespace).Delete(context.TODO(), status.Pod.Name, metav1.DeleteOptions{})
if err != nil {
// If ... | {
o.UpdateStageStatus(stg, &v1alpha1.Status{
Phase: v1alpha1.StatusCancelled,
Reason: "GC",
LastTransitionTime: metav1.Time{Time: time.Now()},
})
} | conditional_block |
operator.go | package workflowrun
import (
"context"
stderr "errors"
"fmt"
"os"
"reflect"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record... |
// UpdateStageStatus updates status of a stage in WorkflowRun status part.
func (o *operator) UpdateStageStatus(stage string, status *v1alpha1.Status) {
if o.wfr.Status.Stages == nil {
o.wfr.Status.Stages = make(map[string]*v1alpha1.StageStatus)
}
if _, ok := o.wfr.Status.Stages[stage]; !ok {
o.wfr.Status.Sta... | {
if o.wfr == nil {
return nil
}
// Update WorkflowRun status with retry.
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Get latest WorkflowRun.
latest, err := o.client.CycloneV1alpha1().WorkflowRuns(o.wfr.Namespace).Get(context.TODO(), o.wfr.Name, metav1.GetOptions{})
if err != nil {
... | identifier_body |
operator.go | package workflowrun
import (
"context"
stderr "errors"
"fmt"
"os"
"reflect"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record... | (clusterClient kubernetes.Interface, client k8s.Interface, wfr, namespace string) (Operator, error) {
w, err := client.CycloneV1alpha1().WorkflowRuns(namespace).Get(context.TODO(), wfr, metav1.GetOptions{})
if err != nil {
return nil, err
}
return &operator{
clusterClient: clusterClient,
client: clien... | newFromName | identifier_name |
operator.go | package workflowrun
import (
"context"
stderr "errors"
"fmt"
"os"
"reflect"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record... | o.wfr.Spec.GlobalVariables = append(o.wfr.Spec.GlobalVariables, appendVariables...)
if len(appendVariables) > 0 {
log.WithField("variables", appendVariables).Info("Append variables from wf to wfr")
}
} | }
| random_line_split |
flatdb.go | // Copyright (c) 2020, Gary Rong <garyrong0905@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package flatdb
import (
"encoding/binary"
"errors"
"io"
"os"
"path/filepath"
"sync"
)
const (
temporaryName = "tmp.db"
s... | if n != len(db.buff) {
return ErrWriteFailure
}
db.buff = db.buff[:0]
db.items = 0
// Step two, flush chunk offset
var local [8]byte
binary.BigEndian.PutUint64(local[:], db.offset)
n, err = db.index.Write(local[:])
if err != nil {
return err
}
if n != 8 {
return ErrWriteFailure
}
return nil
}
func ... | n, err := db.data.Write(db.buff)
if err != nil {
return err
} | random_line_split |
flatdb.go | // Copyright (c) 2020, Gary Rong <garyrong0905@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package flatdb
import (
"encoding/binary"
"errors"
"io"
"os"
"path/filepath"
"sync"
)
const (
temporaryName = "tmp.db"
s... |
// Value returns the value of the current key/value pair, or nil if done. The
// caller should not modify the contents of the returned slice, and its contents
// may change on the next call to Next.
func (iter *FlatIterator) Value() []byte {
return iter.val
}
// Release releases associated resources. Release should... | {
return iter.key
} | identifier_body |
flatdb.go | // Copyright (c) 2020, Gary Rong <garyrong0905@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package flatdb
import (
"encoding/binary"
"errors"
"io"
"os"
"path/filepath"
"sync"
)
const (
temporaryName = "tmp.db"
s... |
key := iter.db.buff[offset : offset+int(x)]
offset += int(x)
x, n = binary.Uvarint(iter.db.buff[offset:])
offset += n
if n <= 0 {
return false
}
val := iter.db.buff[offset : offset+int(x)]
offset += int(x)
iter.key = key
iter.val = val
iter.db.buff = iter.db.buff[offset:]
return true
}
// Error returns... | {
return false
} | conditional_block |
flatdb.go | // Copyright (c) 2020, Gary Rong <garyrong0905@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package flatdb
import (
"encoding/binary"
"errors"
"io"
"os"
"path/filepath"
"sync"
)
const (
temporaryName = "tmp.db"
s... | () {
fb.lock.Lock()
defer fb.lock.Unlock()
fb.keysize, fb.valsize = 0, 0
fb.keys = fb.keys[:0]
fb.vals = fb.vals[:0]
}
// NewIterator creates a iterator over the **whole** database with first-in-first-out
// order. The passed `prefix` and `start` is useless, just only to follow the interface.
//
// If there alre... | Reset | identifier_name |
write.rs | use crate::read::ReadHandle;
use crate::Absorb;
use crate::sync::{fence, Arc, AtomicUsize, MutexGuard, Ordering};
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::ptr::NonNull;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use std::{fmt, thread};
/// A writer handle to ... | else {
self.oplog.extend(ops);
}
}
}
/// `WriteHandle` can be sent across thread boundaries:
///
/// ```
/// use left_right::WriteHandle;
///
/// struct Data;
/// impl left_right::Absorb<()> for Data {
/// fn absorb_first(&mut self, _: &mut (), _: &Self) {}
/// fn sync_with(&mut self, ... | {
// Safety: we know there are no outstanding w_handle readers, since we haven't
// refreshed ever before, so we can modify it directly!
let mut w_inner = self.raw_write_handle();
let w_inner = unsafe { w_inner.as_mut() };
let r_handle = self.enter().expect("m... | conditional_block |
write.rs | use crate::read::ReadHandle;
use crate::Absorb;
use crate::sync::{fence, Arc, AtomicUsize, MutexGuard, Ordering};
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::ptr::NonNull;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use std::{fmt, thread};
/// A writer handle to ... |
}
| {
let (mut w, _) = crate::new::<i32, _>();
// Until we refresh, writes are written directly instead of going to the
// oplog (because there can't be any readers on the w_handle table).
assert!(!w.has_pending_operations());
w.publish();
assert!(!w.has_pending_operations()... | identifier_body |
write.rs | use crate::read::ReadHandle;
use crate::Absorb;
use crate::sync::{fence, Arc, AtomicUsize, MutexGuard, Ordering};
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::ptr::NonNull;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use std::{fmt, thread};
/// A writer handle to ... | #[test]
fn take_test() {
// publish twice then take with no pending operations
let (mut w, _r) = crate::new_from_empty::<i32, _>(2);
w.append(CounterAddOp(1));
w.publish();
w.append(CounterAddOp(1));
w.publish();
assert_eq!(*w.take(), 4);
// publi... | assert_eq!(w.oplog.len(), 2);
}
| random_line_split |
write.rs | use crate::read::ReadHandle;
use crate::Absorb;
use crate::sync::{fence, Arc, AtomicUsize, MutexGuard, Ordering};
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::ptr::NonNull;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use std::{fmt, thread};
/// A writer handle to ... | <T, O>
where
T: Absorb<O>,
{
epochs: crate::Epochs,
w_handle: NonNull<T>,
oplog: VecDeque<O>,
swap_index: usize,
r_handle: ReadHandle<T>,
last_epochs: Vec<usize>,
#[cfg(test)]
refreshes: usize,
#[cfg(test)]
is_waiting: Arc<AtomicBool>,
/// Write directly to the write hand... | WriteHandle | identifier_name |
moveit_grasp.py | #!/usr/bin/env python
## working on virturalenv: N/A, but better using Python2.7 (compatible with MoveIt!)
#### Author: Miaoding Dai (m.dai AT u.northwestern.edu DOT com)
#### Reference: http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html
im... |
self.group.stop()
self.group.clear_pose_targets()
## approach -> close gripper -> retreive -> go home
if plan:
# self.clear_octomap()
# self.open_gripper()
self.approach_eef(pose_grasp)
self.close_gripper()
self.retrie... | rospy.logerr("****** mico_arm pregrasp || plan failed ******") | conditional_block |
moveit_grasp.py | #!/usr/bin/env python
## working on virturalenv: N/A, but better using Python2.7 (compatible with MoveIt!)
#### Author: Miaoding Dai (m.dai AT u.northwestern.edu DOT com)
#### Reference: http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html
im... | (self, config=0):
current_joint_values = self.group.get_current_joint_values()
if config == 0:
## home config 0 - prefered home joint values
current_joint_values[0] = -0.5024237154549698
current_joint_values[1] = -0.0461999859584763
current_joint_values[2... | set_home_joint_values | identifier_name |
moveit_grasp.py | #!/usr/bin/env python
## working on virturalenv: N/A, but better using Python2.7 (compatible with MoveIt!)
#### Author: Miaoding Dai (m.dai AT u.northwestern.edu DOT com)
#### Reference: http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html
im... |
def clear_octomap(self):
rospy.loginfo("Clearing Octomap...")
rospy.wait_for_service("/clear_octomap")
try:
client = rospy.ServiceProxy("/clear_octomap", Empty)
client()
except rospy.ServiceException as e:
print ("Service call failed: %s"%e)
... | '''
transform grasp pose from grasp_frame to mdworld_frame
'''
## tf transform
tf_buffer = tf2_ros.Buffer(rospy.Duration(10.0)) # tf buffer length
tf_listener = tf2_ros.TransformListener(tf_buffer)
# try:
transform_grasp_world = tf_buffer.lookup_transform(
... | identifier_body |
moveit_grasp.py | #!/usr/bin/env python
## working on virturalenv: N/A, but better using Python2.7 (compatible with MoveIt!)
#### Author: Miaoding Dai (m.dai AT u.northwestern.edu DOT com)
#### Reference: http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/move_group_python_interface/move_group_python_interface_tutorial.html
im... | # self.go_home(config=1)
self.go_home(config=0)
self.open_gripper()
if self.is_clear_octomap:
self.clear_octomap()
def open_gripper(self):
gripper_goal = self.group_gripper.get_current_joint_values()
gripper_goal[0] = 0.2
gripper_goal[1] = 0.2... | random_line_split | |
Form.py | #
# -*- coding: latin1 -*-
'''
Form - Formulario de MCWidgets
'''
from MCWidgets.Escape import html_escape
class WidgetError(Exception): pass
class WidgetNotFound(WidgetError): pass
class WidgetTypeNotValid(WidgetError): pass
class WidgetDuplicated(WidgetError): pass
class WidgetInvalidArgs(WidgetError): pass
cla... | e(self):
return (self.__form.get_name())
| rm.render_widget(wid)
except:
import traceback, sys
traceback.print_exc(file = sys.stderr)
raise
return self.__cache[wid]
def get_nam | conditional_block |
Form.py | #
# -*- coding: latin1 -*-
'''
Form - Formulario de MCWidgets
'''
from MCWidgets.Escape import html_escape
class WidgetError(Exception): pass
class WidgetNotFound(WidgetError): pass
class WidgetTypeNotValid(WidgetError): pass
class WidgetDuplicated(WidgetError): pass
class WidgetInvalidArgs(WidgetError): pass
cla... | s(self):
'''_get_url_static_files() -> str
Devuelve la url donde están los ficheros estáticos para,
los widgets, como CSS, JavaScript, imágenes, etc'''
return self._args.get('url_static_files', '/staticmcw/')
def _make_var_name(self, widget, varname):
'''_make_var_name (wi... | Devuelve el nombre del formulario'''
return self._form_name
def _get_url_static_file | identifier_body |
Form.py | #
# -*- coding: latin1 -*-
'''
Form - Formulario de MCWidgets
'''
from MCWidgets.Escape import html_escape
class WidgetError(Exception): pass
class WidgetNotFound(WidgetError): pass
class WidgetTypeNotValid(WidgetError): pass
class WidgetDuplicated(WidgetError): pass
class WidgetInvalidArgs(WidgetError): pass
cla... |
def _type_initialized(self, typename):
'''_type_initialized (type) -> bool
Devuelve True si el tipo de widget indicado ya está
inicializado'''
return typename in self._initialized_types
def _type_mark_initialized(self, typename):
'''_type_mark_initialized (typename)
... | ellos.'''
# damos por hecho de que el nombre de la variables
# no contiene caracteres problemáticos
return '_'.join([self._form_name, widget, varname]) | random_line_split |
Form.py | #
# -*- coding: latin1 -*-
'''
Form - Formulario de MCWidgets
'''
from MCWidgets.Escape import html_escape
class WidgetError(Exception): pass
class WidgetNotFound(WidgetError): pass
class WidgetTypeNotValid(WidgetError): pass
class WidgetDuplicated(WidgetError): pass
class WidgetInvalidArgs(WidgetError): pass
cla... | ict_attrs
return html_dict_attrs(self.__form.get_form_attrs())
def __getattr__(self, wid):
if not self.__cache.has_key(wid):
try:
self.__cache[wid] = self.__form.render_widget(wid)
except:
import traceback, sys
traceback.print_... | s import html_d | identifier_name |
customdomain_utils.go | package managed
import (
"context"
"fmt"
"math/rand"
"regexp"
"github.com/go-logr/logr"
compare "github.com/hashicorp/go-version"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
customdomainv1alpha1 "github.com/openshift/custom-domains-operator/api/v1alpha1"
"... | else {
reqLogger.Info(fmt.Sprintf("Secret %s did not have proper labels, skipping.", ingressSecret.Name))
}
}
// get and delete the custom ingresscontroller
customIngress := &operatorv1.IngressController{}
err = r.Client.Get(context.TODO(), types.NamespacedName{
Namespace: ingressOperatorNamespace,
Name:... | {
err = r.Client.Delete(context.TODO(), ingressSecret)
if err != nil {
reqLogger.Error(err, fmt.Sprintf("Failed to delete %s secret", instance.Name))
return err
}
} | conditional_block |
customdomain_utils.go | package managed
import (
"context"
"fmt"
"math/rand"
"regexp"
"github.com/go-logr/logr"
compare "github.com/hashicorp/go-version"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
customdomainv1alpha1 "github.com/openshift/custom-domains-operator/api/v1alpha1"
"... | // contains is a helper function for finding a string in an array
func contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// remove is a helper function for finalizer
func remove(list []string, s string) []string {
for i, v := range list {
if v == ... | }
| random_line_split |
customdomain_utils.go | package managed
import (
"context"
"fmt"
"math/rand"
"regexp"
"github.com/go-logr/logr"
compare "github.com/hashicorp/go-version"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
customdomainv1alpha1 "github.com/openshift/custom-domains-operator/api/v1alpha1"
"... |
// remove is a helper function for finalizer
func remove(list []string, s string) []string {
for i, v := range list {
if v == s {
list = append(list[:i], list[i+1:]...)
}
}
return list
}
// letters used by randSeq
var letters = []rune("abcdefghijklmnopqrstuvwxyz")
// randSeq is a function to generate a fi... | {
for _, v := range list {
if v == s {
return true
}
}
return false
} | identifier_body |
customdomain_utils.go | package managed
import (
"context"
"fmt"
"math/rand"
"regexp"
"github.com/go-logr/logr"
compare "github.com/hashicorp/go-version"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
customdomainv1alpha1 "github.com/openshift/custom-domains-operator/api/v1alpha1"
"... | (kclient client.Client, reqLogger logr.Logger) (bool, error) {
reqLogger.Info("Fetching labels from namespace", "namespace", config.OperatorNamespace)
ns := corev1.Namespace{}
if err := kclient.Get(context.TODO(), client.ObjectKey{Name: config.OperatorNamespace}, &ns); err != nil {
return false, err
}
labels :=... | isUsingNewManagedIngressFeature | identifier_name |
codec.rs | // vim: tw=80
// This module contains methods that haven't yet been integrated into vdev_raid
#![allow(unused)]
use crate::types::SGList;
use fixedbitset::FixedBitSet;
use std::borrow::BorrowMut;
use super::sgcursor::*;
/// An encoder/decoder for Reed-Solomon Erasure coding in GF(2^8), oriented
/// towards RAID appl... | /// `f` parity columns, where one or more columns is missing, reconstruct
/// the data from the missing columns. Takes as a parameter exactly `k`
/// surviving columns, even if more than `k` columns survive. These *must*
/// be the lowest `k` surviving columns. For example, in a 5+3 array where
/... |
/// Reconstruct missing data from partial surviving columns
///
/// Given a `Codec` with `m` total columns composed of `k` data columns and | random_line_split |
codec.rs | // vim: tw=80
// This module contains methods that haven't yet been integrated into vdev_raid
#![allow(unused)]
use crate::types::SGList;
use fixedbitset::FixedBitSet;
use std::borrow::BorrowMut;
use super::sgcursor::*;
/// An encoder/decoder for Reed-Solomon Erasure coding in GF(2^8), oriented
/// towards RAID appl... |
for j in 0..k {
dec_rows[k * i + j] =
dec_matrix[k * r + j];
}
}
// Finally generate the fast encoding tables
isa_l::ec_init_tables(k as u32, errs as u32, &dec_rows, &mut dec_tables);
dec_tables
}
/// Return the degre... | {
break; // Exclude missing parity columns
} | conditional_block |
codec.rs | // vim: tw=80
// This module contains methods that haven't yet been integrated into vdev_raid
#![allow(unused)]
use crate::types::SGList;
use fixedbitset::FixedBitSet;
use std::borrow::BorrowMut;
use super::sgcursor::*;
/// An encoder/decoder for Reed-Solomon Erasure coding in GF(2^8), oriented
/// towards RAID appl... | (&self, _len: usize, _data: &[*const u8],
_parity: &[*const u8]) -> FixedBitSet {
panic!("Unimplemented");
}
/// Reconstruct missing data from partial surviving columns
///
/// Given a `Codec` with `m` total columns composed of `k` data columns and
/// `f` parity columns, w... | check | identifier_name |
codec.rs | // vim: tw=80
// This module contains methods that haven't yet been integrated into vdev_raid
#![allow(unused)]
use crate::types::SGList;
use fixedbitset::FixedBitSet;
use std::borrow::BorrowMut;
use super::sgcursor::*;
/// An encoder/decoder for Reed-Solomon Erasure coding in GF(2^8), oriented
/// towards RAID appl... |
// Test basic RAID functionality using a small chunksize
#[test]
pub fn encode_decode() {
let len = 8;
let codec = Codec::new(3, 1);
let mut rng = rand::thread_rng();
// First, encode
let mut d0 = vec![0u8;len];
let mut d1 = vec![0u8;len];
let mut p... | {
let cfgs = [
(3, 1), (9, 1),
(4, 2), (10, 2),
(6, 3), (19, 3),
(8, 4), (20, 4)
];
let len = 64;
let maxdata = 28;
let maxparity = 4;
let mut rng = rand::thread_rng();
let mut data = Vec::<Vec<u8>>::new();
... | identifier_body |
treerunner.js | var TreeRunner = Fiber.extend(function() {
/**
* Perform a function on the next-tick, faster than setTimeout
* Taken from stagas / public domain
* By using window.postMessage, we can immediately queue a function
* to run on the event stack once the current JS thread has completed.
* For browsers that d... | // -- in a next-tick, create a new TreeDownloader at the new child (async)
// -- -- on complete, decrement children count by 1
// -- -- when children count hits 0, call downloadComplete()
if (rootParent) {
rootData.resolvedId = this.env.rulesEngine.resolveModule(rootData.originalId, root... | // -- transform the contents (rules)
// -- assign file to child
// -- extract requires
// -- for each child, create children, up the children count by 1 | random_line_split |
treerunner.js | var TreeRunner = Fiber.extend(function() {
/**
* Perform a function on the next-tick, faster than setTimeout
* Taken from stagas / public domain
* By using window.postMessage, we can immediately queue a function
* to run on the event stack once the current JS thread has completed.
* For browsers that d... |
function nextTick (fn) {
queue.push(fn);
if (dirty) return;
dirty = true;
trigger();
}
if (hasPostMessage) {
trigger = function () { window.postMessage(messageName, '*'); };
processQueue = function (event) {
if (event.source == window && event.data === mess... | {
var lQueue = queue;
queue = [];
dirty = false;
fn = lQueue.shift();
while (fn) {
fn();
fn = lQueue.shift();
}
} | identifier_body |
treerunner.js | var TreeRunner = Fiber.extend(function() {
/**
* Perform a function on the next-tick, faster than setTimeout
* Taken from stagas / public domain
* By using window.postMessage, we can immediately queue a function
* to run on the event stack once the current JS thread has completed.
* For browsers that d... | (err) {
next(err, contents);
}
try {
fn(onData, contents, commFlowResolver, commFlowCommunicator, {
moduleId: nodeData.originalId,
parentId: (parentData) ? parentData.originalId : '',
parentUrl: (parentData... | onError | identifier_name |
credit_pipe.py |
import numpy as np
import pdb
import itertools as it
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from sklearn.metrics import f1_score
import pandas as pd
import os
import sys
import datetime
import glob
import re
import graphviz
import seaborn as sns
import numpy as np
from scip... |
#converts a string that is camelCase into snake_case
#https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
def camel_case(column_name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', column_name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
#Give data ... | return pd.read_csv(csv_file,nrows=nrows) | identifier_body |
credit_pipe.py |
import numpy as np
import pdb
import itertools as it
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from sklearn.metrics import f1_score
import pandas as pd
import os
import sys
import datetime
import glob
import re
import graphviz
import seaborn as sns
import numpy as np
from scip... | (data_frame, var_scale):
data_scaled = StandardScaler().fit_transform(data_frame[var_scale][:,np.newaxis]);
low_range = data_scaled[data_scaled[:,0].argsort()][:10]
high_range= data_scaled[data_scaled[:,0].argsort()][-10:]
print('outer range (low) of the distribution:')
print(low_range)
print('\... | scale | identifier_name |
credit_pipe.py | import numpy as np
import pdb
import itertools as it
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from sklearn.metrics import f1_score
import pandas as pd
import os
import sys
import datetime
import glob
import re
import graphviz
import seaborn as sns
import numpy as np
from scipy... |
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
#start_time_date = datetime.strptime(start_time, '%Y-%m-%d')
#end_time_date = datetime.strptime(end_time, '%Y-%m-%d')
for prediction_window in prediction_windows:
print(start_time_date,end_time... | update_window = 12 | random_line_split |
credit_pipe.py |
import numpy as np
import pdb
import itertools as it
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from sklearn.metrics import f1_score
import pandas as pd
import os
import sys
import datetime
import glob
import re
import graphviz
import seaborn as sns
import numpy as np
from scip... |
def kfold_eval(df, target, features):
models_params = {
RandomForestClassifier:{'n_estimators':[100] , 'criterion':['gini','entropy'], 'max_features':['sqrt','log2'] , 'max_depth':[5,10],'n_jobs':[4], 'min_samples_leaf':[10,50,100]},
LogisticRegression: {'C':[10**-1,10**-2,10**-3],'penalty':['l1','l2']},
... | test_start_time = test_end_time - relativedelta(months=+prediction_window)
train_end_time = test_start_time - relativedelta(days=+1) # minus 1 day
train_start_time = train_end_time - relativedelta(months=+prediction_window)
while (train_start_time >= start_time_date ):
... | conditional_block |
blockchain.go | package blockchainPackage
import (
"crypto/sha256"
"time"
"strconv"
"encoding/hex"
"fmt"
"strings"
"math/rand"
"sync"
"encoding/json"
"io/ioutil"
)
var BLOCK_TIME int64 = 120
var BLOCK_ADJUSTMENT int = 720
var NUM_OUTLIERS int = 60
var JSONCHAIN string = "chain_storage.json"
/... |
// a->f
if val > 96 {
val -= 96-9
} else {
val -= 48
}
if carry {
val -=1
carry = false
}
if (val+1) == 0 {
val = 15
carry = true
}
if val >= 10 {
r[i] = val+96-9
... | {
r[i] = val
continue
} | conditional_block |
blockchain.go | package blockchainPackage
import (
"crypto/sha256"
"time"
"strconv"
"encoding/hex"
"fmt"
"strings"
"math/rand"
"sync"
"encoding/json"
"io/ioutil"
)
var BLOCK_TIME int64 = 120
var BLOCK_ADJUSTMENT int = 720
var NUM_OUTLIERS int = 60
var JSONCHAIN string = "chain_storage.json"
/... |
// add a function to the blockchain struct to create a hash
func (bc *Blockchain) HashBlock(block Block) string {
var hash = sha256.New()
hash.Write([]byte(strconv.Itoa(block.Index) +
time.Unix(block.Timestamp, 0).Format(time.UnixDate) +
strconv.Itoa(block.Proof) +
... | {
newBlock := new(Block)
newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork()
//newBlock.Timestamp = time.Now().Unix()
newBlock.Index = len(bc.Chain)
newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1])
newBlock.Difficulty = bc.AdjustDifficulty()
bc.BlockMutex.Lock()
bc.Ch... | identifier_body |
blockchain.go | package blockchainPackage
import (
"crypto/sha256"
"time"
"strconv"
"encoding/hex"
"fmt"
"strings"
"math/rand"
"sync"
"encoding/json"
"io/ioutil"
)
var BLOCK_TIME int64 = 120
var BLOCK_ADJUSTMENT int = 720
var NUM_OUTLIERS int = 60
var JSONCHAIN string = "chain_storage.json"
/... | () {
newBlock := new(Block)
newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork()
//newBlock.Timestamp = time.Now().Unix()
newBlock.Index = len(bc.Chain)
newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1])
newBlock.Difficulty = bc.AdjustDifficulty()
bc.BlockMutex.Lock()
bc... | AddBlock | identifier_name |
blockchain.go | package blockchainPackage
import (
"crypto/sha256"
"time"
"strconv"
"encoding/hex"
"fmt"
"strings"
"math/rand"
"sync"
"encoding/json"
"io/ioutil"
)
var BLOCK_TIME int64 = 120
var BLOCK_ADJUSTMENT int = 720
var NUM_OUTLIERS int = 60
var JSONCHAIN string = "chain_storage.json"
/... | fmt.Println(block)
return false
}
//verify proof
if strings.Compare(proof_hash, prev_block.Difficulty) != -1 {
fmt.Println("the new block did not reach the difficulty target")
fmt.Println(block)
return false
}
if bc.HashBlock(prev_block) != block.PreviousHash {
... | return false
}
//verify time stamp
if block.Timestamp < prev_block.Timestamp {
fmt.Println("the new block had a bad timestamp") | random_line_split |
daal_pca_test.py | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | train"""
with self.assertRaisesRegexp(Exception, "k must be less than or equal to number of observation columns"):
self.context.daaltk.models.dimreduction.pca.train(self.frame,
["X1", "X2", "X3", "X4", "X5",
"X6", "X7", "X8", "X9", "... | 2], 6)),
abs(round(self.expected_R_singular_vec[ind][ind2], 6)))
def test_daal_pca_bad_no_of_k(self):
"""Test invalid k value in | conditional_block |
daal_pca_test.py | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | xception, "columns must be a list of strings"):
self.context.daaltk.models.dimreduction.pca.train(self.frame, 10, k=10)
if __name__ == '__main__':
unittest.main()
| identifier_body | |
daal_pca_test.py | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | pca_train_out = self.context.daaltk.models.dimreduction.pca.train(self.frame,
["X1", "X2", "X3", "X4", "X5",
"X6", "X7", "X8", "X9", "X10"],
True, 10)
# actual right-singular vectors
a... | ctionality with mean centering"""
| identifier_name |
daal_pca_test.py | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | actual_R_singular_vec = pca_train_out.right_singular_vectors
# actual singular values
actual_singular_val = pca_train_out.singular_values
expected_actual = zip(self.expected_singular_val, actual_singular_val)
for expected, actual in expected_actual:
self.assertAlmos... | "X6", "X7", "X8", "X9", "X10"],
False, 10)
# actual right-singular vectors | random_line_split |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... |
fn update_collisions(&mut self, world: &mut World) {
let mut collide_world = world.specs_world.write_resource::<nc::world::CollisionWorld<f32, specs::Entity>>();
collide_world.update();
let mut motions = world.specs_world.write_storage::<c::Motion>();
// gameworld.collide_world.... | {
let builder = specs::DispatcherBuilder::new()
.with(MovementSystem, "sys_movement", &[])
.with(CollisionSystem, "sys_collision", &[]);
// builder.add_thread_local(RenderSystem);
builder.build()
} | identifier_body |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... |
ncollide2d::pipeline::narrow_phase::ContactEvent::Stopped(handle1, handle2) =>
{
println!("contact ended");
let obj1 = collide_world.collision_object(*handle1).expect("missing coll obj1");
// look up entity
... | {
println!("contact started!");
// look up collision object
let obj1 = collide_world.collision_object(*handle1).expect("missing coll obj1");
// look up entity
let entity1: &specs::Entity = obj1.data(... | conditional_block |
level.rs | use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::u... | fn update(&mut self, gameworld: &mut World, _ctx: &mut ggez::Context) -> scenes::Switch {
self.dispatcher.dispatch(&mut gameworld.specs_world.res);
self.update_collisions(gameworld);
if self.done {
scene::SceneSwitch::Pop
} else {
scene::SceneSwitch::None
... | // fn camera_draw(ctx: &mut ggez::Context, drawable: &graphics::Drawable, params: graphics::DrawParam) -> ggez::GameResult<()> {
// Ok(())
// }
impl scene::Scene<World, input::Event> for LevelScene { | random_line_split |
level.rs |
use ggez;
use ggez::graphics;
use ggez_goodies::scene;
use ggez_goodies::tilemap::tiled as tiled;
use ggez_goodies::tilemap::Map as Map;
use log::*;
use specs::{self, Join};
use specs::world::Builder;
use warmy;
// use std::path;
use ggez::nalgebra as na;
use ncollide2d as nc;
use crate::components as c;
use crate::... | () -> specs::Dispatcher<'static, 'static> {
let builder = specs::DispatcherBuilder::new()
.with(MovementSystem, "sys_movement", &[])
.with(CollisionSystem, "sys_collision", &[]);
// builder.add_thread_local(RenderSystem);
builder.build()
}
fn update_collisions(&... | register_systems | identifier_name |
lib.rs | #![deny(warnings)]
extern crate unicode_width;
extern crate svg;
use unicode_width::UnicodeWidthStr;
use unicode_width::UnicodeWidthChar;
use svg::node::element::Circle as SvgCircle;
use svg::node::element::Text as SvgText;
use svg::Node;
use svg::node::element::SVG;
use svg::node::element::Style;
use svg::node::Text... |
}
y += 1;
}
(svg_elements, relines, get_styles())
}
/// parse the memes and return the svg together with the unmatched strings
fn line_to_svg_with_excess_str(y: usize, s: &str, settings:&Settings) -> Option<(Vec<Box<Node>>, String)>{
let body = parse_memes(s);
if body.has_memes(){
... | {
relines.push_str(line);
relines.push('\n');
} | conditional_block |
lib.rs | #![deny(warnings)]
extern crate unicode_width;
extern crate svg;
use unicode_width::UnicodeWidthStr;
use unicode_width::UnicodeWidthChar;
use svg::node::element::Circle as SvgCircle;
use svg::node::element::Text as SvgText;
use svg::Node;
use svg::node::element::SVG;
use svg::node::element::Style;
use svg::node::Text... | (s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
to_svg_text_pixel_escaped(&escape_str(s), x, y, settings, anchor)
}
fn to_svg_text_pixel_escaped(s: &str, x: f32, y: f32, settings: &Settings, anchor: Anchor) -> SvgText {
let (offsetx, offsety) = settings.offset();
let sx = x + of... | to_svg_text_pixel | identifier_name |
lib.rs | #![deny(warnings)]
extern crate unicode_width;
extern crate svg;
use unicode_width::UnicodeWidthStr;
use unicode_width::UnicodeWidthChar;
use svg::node::element::Circle as SvgCircle;
use svg::node::element::Text as SvgText;
use svg::Node;
use svg::node::element::SVG;
use svg::node::element::Style;
use svg::node::Text... | let mut new_group = vec![];
//println!("regrouping text..");
for &(start,ref rest) in rest_text{
if new_group.is_empty(){
new_group.push((start, rest.clone()));
}else{
if let Some((lastx, last_rest)) = new_group.pop(){
if lastx + last_rest.width() == st... | }
}
fn regroup_rest_text(rest_text: &Vec<(usize, String)>)->Vec<(usize, String)>{ | random_line_split |
utils.py | import random
import glob
import paddle
import numpy as np
import xml.etree.ElementTree as ET
def iou(bbox, priors):
"""
计算一个真实框与 k个先验框(priors) 的交并比(IOU)值。
bbox: 真实框的宽高,数据为(宽,高),其中宽与高都是归一化后的相对值。
priors: 生成的先验框,数据形状为(k,2),其中k是先验框priors的个数
"""
x = np.minimum(priors[:, 0], bbox[0])
... |
target_indexs = np.where(gt_bboxs[:, :, 3] != 0) # 宽不为0的目标框(真实目标)的索引值, [batch][num]
i_float = gt_center_y * h
i = np.floor(i_float).astype(np.int32) # 在第几行 shape = (batchsize, nums,)
i = i[target_indexs] # 取出对应i
j_float = gt_center_x * w # shape = (batchsize, nums,)
j = np.floor(j_fl... | gt_h = gt_bboxs[:, :, 4]
gtx_min = gt_center_x - gt_w / 2.0
gtx_max = gt_center_x + gt_w / 2.0
gty_min = gt_center_y - gt_h / 2.0
gty_max = gt_center_y + gt_h / 2.0
| random_line_split |
utils.py |
import random
import glob
import paddle
import numpy as np
import xml.etree.ElementTree as ET
def iou(bbox, priors):
"""
计算一个真实框与 k个先验框(priors) 的交并比(IOU)值。
bbox: 真实框的宽高,数据为(宽,高),其中宽与高都是归一化后的相对值。
priors: 生成的先验框,数据形状为(k,2),其中k是先验框priors的个数
"""
x = np.minimum(priors[:, 0], bbox[0])... | 85, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828],
表示有5个锚框,第一个锚框大小[w, h]是[0.57273, 0.677385],第5个锚框大小是[9.77052, 9.16828]
锚框的大小都是表示在特征图13x13中的大小
num_classes:类别数
返回预测框pred_box, 最终输出数据保存在pred_box中,其形状是[N, num_anchors, 4, H, W,],4表示4个位置坐标
"""
num_rows... | 6773 | conditional_block |
utils.py |
import random
import glob
import paddle
import numpy as np
import xml.etree.ElementTree as ET
def iou(bbox, priors):
"""
计算一个真实框与 k个先验框(priors) 的交并比(IOU)值。
bbox: 真实框的宽高,数据为(宽,高),其中宽与高都是归一化后的相对值。
priors: 生成的先验框,数据形状为(k,2),其中k是先验框priors的个数
"""
x = np.minimum(priors[:, 0], bbox[0])... | ss_confidence = np.zeros(shape=(batchsize, h, w, num_anchors), dtype='float32')
label_location = np.zeros(shape=(batchsize, h, w, num_anchors, 4), dtype='float32')
label_classification = np.zeros(shape=(batchsize, h, w, num_anchors, num_classes), dtype='float32')
scale_location = 0.01 * np.ones((batchsiz... | anchors_this.append([anchors[ind * 2], anchors[ind * 2 + 1]])
# anchors_this = np.array(anchors_this).astype('float32')
anchors_this = paddle.to_tensor(anchors_this)
pred_box = paddle.zeros(pred_location.shape)
# for b in range(batchsize):
for i in range(num_rows):
for j in ra... | identifier_body |
utils.py |
import random
import glob
import paddle
import numpy as np
import xml.etree.ElementTree as ET
def iou(bbox, priors):
"""
计算一个真实框与 k个先验框(priors) 的交并比(IOU)值。
bbox: 真实框的宽高,数据为(宽,高),其中宽与高都是归一化后的相对值。
priors: 生成的先验框,数据形状为(k,2),其中k是先验框priors的个数
"""
x = np.minimum(priors[:, 0], bbox[0])... | max = np.float64(xmax)
ymax = np.float64(ymax)
if xmax == xmin or ymax == ymin:
print(xml_file)
dataset.append([xmax - xmin, ymax - ymin]) # 宽与高的相对值
return np.array(dataset) # 转为numpy数组
def bbox2tensor(bbox,max_num=30):
'''
bbox:标签信息。信息格式为[cl... | x | identifier_name |
td_learning.py | The Reproducing Temporal Difference Learning from Sutton (1988)
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
# Set parameters for experiments_______________________________________________________________
# Switches for choosing which figure to generate ... | um_steps, start_step, seq_per_set, num_sets, seed=-1):
"""
Create a list of lists of training sequences for random walks.
:param num_steps: The number of steps in the random walk
:param start_step: The starting step of the sequences. -1 for random
:param seq_per_set: Number of training sequences in ... | ke_a_walk(n | identifier_name |
td_learning.py | The Reproducing Temporal Difference Learning from Sutton (1988)
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
# Set parameters for experiments_______________________________________________________________
# Switches for choosing which figure to generate ... | else: # Non-terminal state
delta_p = np.dot(p, training[step + 1, :]) - np.dot(p, training[step, :])
if verbose: print('delta_p =', delta_p)
delta_w += alpha * delta_p * np.sum(these_steps * lambda_seq[:, None], axis=0)
if verbose: print('delta_w =', delta_w)
lambda_se... | verbose: print("z =", z)
delta_p = z - np.dot(p, training[-1, :])
| conditional_block |
td_learning.py | The Reproducing Temporal Difference Learning from Sutton (1988)
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
# Set parameters for experiments_______________________________________________________________
# Switches for choosing which figure to generate ... | this_sequence[step] = 1
# Add this step to the sequence
sequence = np.vstack((sequence, this_sequence))
# Assign the sequence to its position in the training data
training[this_set][seq] = sequence
return training
#----------------------------... | # Generate the vector representing this step
this_sequence = np.zeros(num_steps).astype(int)
# Set the appropriate element to 1 | random_line_split |
td_learning.py | The Reproducing Temporal Difference Learning from Sutton (1988)
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
# Set parameters for experiments_______________________________________________________________
# Switches for choosing which figure to generate ... | #-----------------------------------------------------------------------------------------------
def learn_game(t_seq, lambda_val, alpha, z_vals, p, verbose=False):
"""
Given a set of training data, perform repeated weight updates as in eq 4 in Sutton (1988)
:param t_seq: The input training sequence
:pa... | "
Create a list of lists of training sequences for random walks.
:param num_steps: The number of steps in the random walk
:param start_step: The starting step of the sequences. -1 for random
:param seq_per_set: Number of training sequences in each training set
:param num_sets: Number of training set... | identifier_body |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... |
}
impl IsError for UnsupportedMessageType<'_> {
fn error_id(&self) -> Id {
Self::ERROR_ID
}
fn error_level(&self) -> Level {
Self::ERROR_LEVEL
}
}
impl fmt::Display for UnsupportedMessageType<'_> {
fn fmt(&self, f: &mut fmt::Formatter) ... | {
UnsupportedMessageType {
sender,
message_type,
}
} | identifier_body |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... | }
}
fn log_config() -> oysterpack_log::LogConfig {
oysterpack_log::config::LogConfigBuilder::new(oysterpack_log::Level::Info).build()
}
const MESSAGE_SERVICE: actor::arbiters::Name = actor::arbiters::Name("MESSAGE_SERVICE");
#[test]
fn message_service() {
let (client_p... | actix::MessageResult(Ok(req.0)) | random_line_split |
service.rs | /*
* Copyright 2019 OysterPack Inc.
*
* 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 applicabl... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: mailbox delivery error for message type: {} : {}",
self.sender, self.message_type, self.err,
)
}
}
}
#[allow(warnings)]
#[cfg(test)]
mod tests {
use crate::actor;
... | fmt | identifier_name |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... | fn path2bytes(p: &Path) -> &[u8] {
p.as_os_str()
.to_str()
.expect("we should only have unicode compatible bytes even on windows")
.as_bytes()
} | random_line_split | |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... |
fn new_default_header() -> tar::Header {
let mut header = tar::Header::new_gnu();
header.set_mtime(0);
header.set_uid(0);
header.set_gid(0);
header
}
fn new_long_filename_header() -> tar::Header {
let mut long_filename_header = tar::Header::new_gnu();
... | {
let bytes = BytesMut::with_capacity(n);
// these are 512 a piece
let header = Self::new_default_header();
let long_filename_header = Self::new_long_filename_header();
let mut zeroes = BytesMut::with_capacity(512);
for _ in 0..(512 / 8) {
zeroes.put_u64(0);
... | identifier_body |
tar_helper.rs | ///! Tar helper is internal to `/get` implementation. It uses some private parts of the `tar-rs`
///! crate to provide a `BytesMut` writing implementation instead of one using `std::io` interfaces.
///!
///! Code was originally taken and modified from the dependency version of `tar-rs`. The most
///! important copied p... | (
&mut self,
path: &Path,
metadata: &Metadata,
total_size: u64,
) -> Result<[Option<Bytes>; 3], GetError> {
let mut ret: [Option<Bytes>; 3] = Default::default();
if let Err(e) = self.header.set_path(path) {
let data =
prepare_long_header(&... | apply_file | identifier_name |
chip8.go | package chip8
//Struct for the Main Chip8 System
import (
"fmt"
"golang.org/x/mobile/asset"
"io/ioutil"
"math/rand"
)
var Chip8_fontset = [80]byte{
0xF0, 0x90, 0x90, 0x90, 0xF0, //0
0x20, 0x60, 0x20, 0x20, 0x70, //1
0xF0, 0x10, 0xF0, 0x80, 0xF0, //2
0xF0, 0x10, 0xF0, 0x10, 0xF0, //3
0x90, 0x90, 0xF0, 0x10, 0... |
//Read file in curent dir into Memory
func (self *Chip8) LoadGame(filename string) {
// rom, _ := ioutil.ReadFile(filename)
filename = self.Games[self.GameIndex]
fmt.Printf("Loading Game %s", filename)
f, _ := asset.Open(filename)
rom, _ := ioutil.ReadAll(f)
rom_length := len(rom)
if rom_length > 0 {
// fmt.... | {
self.Pc = 0x200 // Program counter starts at 0x200, the Space of Memory after the interpreter
self.Opcode = 0 // Reset current Opcode
self.Index = 0 // Reset index register
self.Sp = 0 // Reset stack pointer
for x := 0; x < 16; x++ {
self.V[x] = 0
}
//
for i := 0; i < 80; i++ {
self.Memory[i] = Chi... | identifier_body |
chip8.go | package chip8
//Struct for the Main Chip8 System
import (
"fmt"
"golang.org/x/mobile/asset"
"io/ioutil"
"math/rand"
)
var Chip8_fontset = [80]byte{
0xF0, 0x90, 0x90, 0x90, 0xF0, //0
0x20, 0x60, 0x20, 0x20, 0x70, //1
0xF0, 0x10, 0xF0, 0x80, 0xF0, //2
0xF0, 0x10, 0xF0, 0x10, 0xF0, //3
0x90, 0x90, 0xF0, 0x10, 0... | ex += x + 1
self.Pc += 2
break
case 0x065: // FX55 Fills V0 to VX (including VX) with values from memory starting at address I.[4]
for i := 0; i < int(x); i++ {
self.V[i] = self.Memory[int(self.Index)+i]
}
self.Index += x + 1
self.Pc += 2
break
default:
fmt.Printf("Unknown opcode [0xF000... | emory[self.Index+uint16(i)] = self.V[i]
}
self.Ind | conditional_block |
chip8.go | package chip8
//Struct for the Main Chip8 System
import (
"fmt"
"golang.org/x/mobile/asset"
"io/ioutil"
"math/rand"
)
var Chip8_fontset = [80]byte{
0xF0, 0x90, 0x90, 0x90, 0xF0, //0
0x20, 0x60, 0x20, 0x20, 0x70, //1
0xF0, 0x10, 0xF0, 0x80, 0xF0, //2
0xF0, 0x10, 0xF0, 0x10, 0xF0, //3
0x90, 0x90, 0xF0, 0x10, 0... | self.V[x] += NN
self.Pc += 2
break
//0X8000 - 8 CASES
/*
8XY0 Sets VX to the value of VY.
8XY1 Sets VX to VX or VY.
8XY2 Sets VX to VX and VY.
8XY3 Sets VX to VX xor VY.
8XY4 Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't.
*/
case 0x8000:
switch self.Opcode... | self.Pc += 2
break
case 0x7000: //0x7XNN Adds NN to VX.
x := (self.Opcode & 0xF00) >> 8
NN := byte(self.Opcode & 0x00FF) | random_line_split |
chip8.go | package chip8
//Struct for the Main Chip8 System
import (
"fmt"
"golang.org/x/mobile/asset"
"io/ioutil"
"math/rand"
)
var Chip8_fontset = [80]byte{
0xF0, 0x90, 0x90, 0x90, 0xF0, //0
0x20, 0x60, 0x20, 0x20, 0x70, //1
0xF0, 0x10, 0xF0, 0x80, 0xF0, //2
0xF0, 0x10, 0xF0, 0x10, 0xF0, //3
0x90, 0x90, 0xF0, 0x10, 0... | (filename string) {
// rom, _ := ioutil.ReadFile(filename)
filename = self.Games[self.GameIndex]
fmt.Printf("Loading Game %s", filename)
f, _ := asset.Open(filename)
rom, _ := ioutil.ReadAll(f)
rom_length := len(rom)
if rom_length > 0 {
// fmt.Printf("Rom Length = %d\n", rom_length)
}
//If room to store ROM... | LoadGame | identifier_name |
final.go | package hwy
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
)
const (
majorSep = ";"
minorSep = ","
)
// Conversion multipiers.
const (
// Meters in 1 mile.
MilesToMeters = 1609.344
// Miles in 1 meter.
MetersToMiles = 1 / MilesToMeters
)
// Place is an 'origin' or 'destination' city, gi... |
}
}
// Places provides a slice of unique Places in the graph.
// Use `ByState` or `ByCity` with pkg `sort` to sort the slice.
func (g Graph) Places() []Place {
places := make([]Place, 0, len(g))
for k := range g {
places = append(places, k)
}
return places
}
// Edge gets the Weight (edge data) for the connect... | {
fmt.Fprintf(w, "\t%-16s%3s%7.1fmi%10s\n", kk.City, kk.State, vv.Distance*MetersToMiles, vv.TravelTime)
} | conditional_block |
final.go | package hwy
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
)
const (
majorSep = ";"
minorSep = ","
)
// Conversion multipiers.
const (
// Meters in 1 mile.
MilesToMeters = 1609.344
// Miles in 1 meter.
MetersToMiles = 1 / MilesToMeters
)
// Place is an 'origin' or 'destination' city, gi... | = p[j], p[i]
}
| identifier_body | |
final.go | package hwy
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
)
const (
majorSep = ";"
minorSep = ","
)
// Conversion multipiers.
const (
// Meters in 1 mile.
MilesToMeters = 1609.344
// Miles in 1 meter.
MetersToMiles = 1 / MilesToMeters
)
// Place is an 'origin' or 'destination' city, gi... | (origin Place, predicate MinMax, by Accessor) (most Place, ok bool) {
dm, ok := g[origin]
if !ok {
return most, false
}
var cur *Weight
for k, v := range dm {
// start by setting the first value to the current best
if cur == nil {
most = k
*cur = v
continue
}
// get the mostest
bestval := pr... | Most | identifier_name |
final.go | package hwy
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
)
const (
majorSep = ";"
minorSep = ","
)
// Conversion multipiers.
const (
// Meters in 1 mile.
MilesToMeters = 1609.344
// Miles in 1 meter.
MetersToMiles = 1 / MilesToMeters
)
// Place is an 'origin' or 'destination' city, gi... |
//
//
// parsing Graph and Place
//
//
// ParseGraph parses input from r, successively turning each line into a new
// entry in the graph. Lines beginning with "#" are ignored ascomments, and
// blank lines are skipped. Line format is:
// `<place:city,state,lat,lon>;<place>,<weight:distance,time>;<place>,<weight>;...... | }
return nodes
} | random_line_split |
nrml04.py | """
Module containing NRML 0.4 constants and utility methods.
"""
from lxml import etree
import gml
import numpy
NRML04_NS = 'http://openquake.org/xmlns/nrml/0.4'
NRML04 = "{%s}" % NRML04_NS
NRML04_ROOT_TAG = '%snrml' % NRML04
NRML04_SOURCE_MODEL = etree.QName(NRML04_NS,'sourceModel')
NRML04_AREA_SOURCE = etree.QName(... |
def _append_truncated_gr_mfd(element, mfd):
"""
Append NRML 0.4 truncated GR MFD.
mfd is an instance of TruncatedGutenbergRichterMfdNrml03.
"""
attrib = {'aValue': str(mfd.a_val),
'bValue': str(mfd.b_val),
'minMag': str(mfd.min_mag),
'maxMag': str(mfd.max_m... | element.append(incremental_mfd) | random_line_split |
nrml04.py | """
Module containing NRML 0.4 constants and utility methods.
"""
from lxml import etree
import gml
import numpy
NRML04_NS = 'http://openquake.org/xmlns/nrml/0.4'
NRML04 = "{%s}" % NRML04_NS
NRML04_ROOT_TAG = '%snrml' % NRML04
NRML04_SOURCE_MODEL = etree.QName(NRML04_NS,'sourceModel')
NRML04_AREA_SOURCE = etree.QName(... | (element, mag_scale_rel):
"""
Append NRML 0.4 magnitude scaling relationship element.
"""
msr = etree.Element(NRML04_MAG_SCALE_REL)
msr.text = mag_scale_rel
element.append(msr)
def _append_rupt_aspect_ratio(element, rupt_aspect_ratio):
"""
Append NRML 0.4 rupture aspect ratio.
"""
... | _append_mag_scaling_rel | identifier_name |
nrml04.py | """
Module containing NRML 0.4 constants and utility methods.
"""
from lxml import etree
import gml
import numpy
NRML04_NS = 'http://openquake.org/xmlns/nrml/0.4'
NRML04 = "{%s}" % NRML04_NS
NRML04_ROOT_TAG = '%snrml' % NRML04
NRML04_SOURCE_MODEL = etree.QName(NRML04_NS,'sourceModel')
NRML04_AREA_SOURCE = etree.QName(... |
def _append_id_name_tect_reg(element, NRML04_SOURCE, ID, name, tect_reg):
"""
Append id, name, tectonic region type for the given NRML 0.4 source
typology.
Returns the source element.
"""
attrib = {'id': ID, 'name': name, 'tectonicRegion': tect_reg}
source = etree.Element(NRML04_SOURCE, a... | """
Append and return NRML 0.4 source model element.
"""
attrib = {'name': name}
source_model = etree.Element(NRML04_SOURCE_MODEL,attrib=attrib)
element.append(source_model)
return source_model | identifier_body |
nrml04.py | """
Module containing NRML 0.4 constants and utility methods.
"""
from lxml import etree
import gml
import numpy
NRML04_NS = 'http://openquake.org/xmlns/nrml/0.4'
NRML04 = "{%s}" % NRML04_NS
NRML04_ROOT_TAG = '%snrml' % NRML04
NRML04_SOURCE_MODEL = etree.QName(NRML04_NS,'sourceModel')
NRML04_AREA_SOURCE = etree.QName(... |
else:
raise ValueError('MFD element nor recognized.')
def _create_nrml():
"""
Create and return NRML 0.4 root element.
"""
return etree.Element(NRML04_ROOT_TAG, nsmap=NSMAP)
def _append_source_model(element, name):
"""
Append and return NRML 0.4 source model element.
"""
a... | min_mag = float(mfd.attrib['minMag'])
bin_width = float(mfd.attrib['binWidth'])
occur_rates = numpy.array(mfd.find(NRML04_OCCUR_RATES.text).
text.split(), dtype=float)
return IncrementalMfdNRML04(min_mag, bin_width, occur_rates) | conditional_block |
code.go | /* code.go
* This file is part of pygoas
*
* This is probably going to be a simple Mini-Python to NASM-assembly compiler
* written by Sebastian Kind 2nd Janury -- 20th May 2016
*/
package main
import (
"fmt"
"strconv"
)
// programCode is the essential struct (comparable to a class in
// python) which contains... |
func (pc *programCode) createForCheck(loopVar string) {
code := "\n\tmov rax, [" + loopVar + "] \t; for-loop\n"
code += "\tdec rax\n\tmov [" + loopVar + "], rax\n"
forJmpBackLabel := pc.popLastLabel()
code += "\tcmp rax, 0\n\tjle " + forJmpBackLabel + "\t; if zero close loop\n\t \n" // Fixed this line
pc.appendC... |
// This is the code snipped checking the condition inside an assembly loop. | random_line_split |
code.go | /* code.go
* This file is part of pygoas
*
* This is probably going to be a simple Mini-Python to NASM-assembly compiler
* written by Sebastian Kind 2nd Janury -- 20th May 2016
*/
package main
import (
"fmt"
"strconv"
)
// programCode is the essential struct (comparable to a class in
// python) which contains... |
pc.appendCode(code)
}
// createCall allows the label passed as string argument to be
// called.
//"call" executes a function inside assembly. It cleanes used
// registers before and after the function did its job. -> amd64 Sys V
// abi
// FIXME: 'jmp vs. call'?
func (pc *programCode) createCall(name string) {
code... | {
if _, err := strconv.Atoi(argSlice[i]); err == nil {
code += "\tmov " + registerSlice[i] + argSlice[i] + "\n"
} else {
code += "\tmov " + registerSlice[i] + "[" + argSlice[i] + "]\n"
}
} | conditional_block |
code.go | /* code.go
* This file is part of pygoas
*
* This is probably going to be a simple Mini-Python to NASM-assembly compiler
* written by Sebastian Kind 2nd Janury -- 20th May 2016
*/
package main
import (
"fmt"
"strconv"
)
// programCode is the essential struct (comparable to a class in
// python) which contains... | (name string) {
code := ""
code += "\n" + name + ":\n"
pc.funcSlice = append(pc.funcSlice, name)
pc.indentLevel += 1 // dive deeper -> next buffer.
// Please have a look to FIXME: Where can I find what?
pc.appendCode(code)
}
// createReturn leaves the innermost function/indent buffer by
// decrementing the pc.i... | createLabel | identifier_name |
code.go | /* code.go
* This file is part of pygoas
*
* This is probably going to be a simple Mini-Python to NASM-assembly compiler
* written by Sebastian Kind 2nd Janury -- 20th May 2016
*/
package main
import (
"fmt"
"strconv"
)
// programCode is the essential struct (comparable to a class in
// python) which contains... |
/*
mov eax, [var1]
add eax, [var2]
mov [var3], eax
*/
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+//
// Mathsnippets The following code templates are appended to the
// output program to do ugly numbercrunshing work The following
// functions' parameters are names of va... | {
len := (int64)(len(pc.stringMap[sname])) - 2
// FIXME: WTF int64. Why not use int and strconv.Atoi(var string)
// and stringcon.Itoa(var int)
strlen := strconv.FormatInt(len, 10)
code := "\tmov rax, 1\t;print String" + sname + "\n\tmov rdi, 1\n\tmov rdx, " + strlen + "\n\tmov rsi, " + sname + "\n\tsyscall\n"
... | identifier_body |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... | (
res: &SystemRes,
thr: &Thrs,
exti5: &ExtiDrv<Exti5, thr::Exti95>,
gpio_pins: &GpioPins,
hclk: u32,
) -> Event {
println!("Enter listen, hclk={}", hclk);
// Attach a listener that will notify us on user button pressed.
let mut button_stream = exti5.create_saturating_stream();
// At... | listen | identifier_name |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... |
}
}
}
Event::Push
}
| {
doubleclick_protection = 0;
println!("++");
} | conditional_block |
root.rs | //! The root task.
use crate::consts::HSI_CLK;
use crate::{
drv::{
exti::{ExtiDrv, ExtiSetup},
flash::Flash,
gpio::GpioHead,
hsi::Hsi,
lse::Lse,
pll::Pll,
rcc::Rcc,
},
drv_gpio_pins,
sys::{gpio_pins::GpioPins, system::System},
thr,
thr::{T... |
'user_button_pressed: loop {
// Reset the clock control registers to their default.
System::reset_rcc(&res);
// Apply the current clock tree configuration.
System::apply_clock_config(&res);
// Calculate the configured clock speed.
let hclk = System::calculate_hclk(... | falling: false, // trigger the interrupt on a falling edge.
rising: true, // don't trigger the interrupt on a rising edge.
}); | random_line_split |
wait_cell.rs | //! An atomically registered [`Waker`], for waking a single task.
//!
//! See the documentation for the [`WaitCell`] type for details.
use super::Closed;
use crate::loom::{
cell::UnsafeCell,
sync::atomic::{
AtomicUsize,
Ordering::{self, *},
},
};
use core::{
future::Future,
ops,
... | <'a> {
/// The [`WaitCell`] being waited on.
cell: &'a WaitCell,
}
#[derive(Eq, PartialEq, Copy, Clone)]
struct State(usize);
// === impl WaitCell ===
impl WaitCell {
loom_const_fn! {
/// Returns a new `WaitCell`, with no [`Waker`] stored in it.
#[must_use]
pub fn new() -> Self {
... | Subscribe | identifier_name |
wait_cell.rs | //! An atomically registered [`Waker`], for waking a single task.
//!
//! See the documentation for the [`WaitCell`] type for details.
use super::Closed;
use crate::loom::{
cell::UnsafeCell,
sync::atomic::{
AtomicUsize,
Ordering::{self, *},
},
};
use core::{
future::Future,
ops,
... |
Ok(())
}
}
#[cfg(all(feature = "alloc", not(loom), test))]
mod tests {
use super::*;
use crate::scheduler::Scheduler;
use alloc::sync::Arc;
use tokio_test::{assert_pending, assert_ready, assert_ready_ok, task};
#[test]
fn wait_smoke() {
static COMPLETED: AtomicUsize = At... | {
if *self == Self::WAITING {
return f.write_str("WAITING");
}
f.debug_tuple("UnknownState")
.field(&format_args!("{:#b}", self.0))
.finish()?;
} | conditional_block |
wait_cell.rs | //! An atomically registered [`Waker`], for waking a single task.
//!
//! See the documentation for the [`WaitCell`] type for details.
use super::Closed;
use crate::loom::{
cell::UnsafeCell,
sync::atomic::{
AtomicUsize,
Ordering::{self, *},
},
};
use core::{
future::Future,
ops,
... | Poll::Ready(Err(PollWaitError::Busy)) => {
// Someone else is in the process of registering. Yield now so we
// can wait until that task is done, and then try again.
cx.waker().wake_by_ref();
return Poll::Pending;
}
Poll... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.