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 |
|---|---|---|---|---|
amap.go | package amap
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/go-resty/resty"
)
// PoiResult PoiResult
type PoiResult struct {
Count string `json:"count"`
Info string `json:"info"`
Infocode string `json:"infocode"`
Pois []Poi `json:"pois"`
Status string... | (mRecs []minRec) (mrp []minRecPage) {
for _, mRec := range mRecs {
mrp = append(mrp, minRecPages(mRec)...)
}
return
}
func recTypePages(rec Rectangle, types string) (mrp []minRecPage) {
cutrec := cutRec(rec, types)
mrp = minRecsPages(cutrec)
return
}
// RecTypePois RecTypePois
func RecTypePois(rec Rectangle, ... | minRecsPages | identifier_name |
models.py | from django.db import models
import uuid
from on.activities.base import Goal, Activity
from on.user import UserInfo, UserTicket, UserRecord, UserSettlement
import django.utils.timezone as timezone
from django.conf import settings
import os
import pytz
import math
from datetime import timedelta, datetime
class Running... | identifier_body | ||
models.py | from django.db import models
import uuid
from on.activities.base import Goal, Activity
from on.user import UserInfo, UserTicket, UserRecord, UserSettlement
import django.utils.timezone as timezone
from django.conf import settings
import os
import pytz
import math
from datetime import timedelta, datetime
class Running... | te(goal=goal, voucher_ref=file_refpath, voucher_store=file_filepath, distance=distance,record_time = punch_record_time,
document=document)
print(555555555555555555555555555555555555555)
# 如果是自由模式, 则计算剩余距离
if not goal.goal_type:
goal.left_distance -= dista... | record = self.crea | identifier_name |
models.py | from django.db import models
import uuid
from on.activities.base import Goal, Activity
from on.user import UserInfo, UserTicket, UserRecord, UserSettlement
import django.utils.timezone as timezone
from django.conf import settings
import os
import pytz
import math
from datetime import timedelta, datetime
class Running... | filter(start_time=start_time).filter(status="PENDING")
# 如果存在的话就删掉
if goal:
goal.first().delete()
goal = self.create(user_id=user_id,
activity_type=RunningGoal.get_activity(),
start_time=start_time,
goal... | 21: 18,
30: 25,
61: 50
}
goal_distance = distance
left_distance = distance
distances = int(distance)
kilos_day = 2 * distances // actual_day_map[goal_day]
# 查询出没有支付的活动
goal = self.filter(user_id=us... | conditional_block |
models.py | from django.db import models
import uuid
from on.activities.base import Goal, Activity
from on.user import UserInfo, UserTicket, UserRecord, UserSettlement
import django.utils.timezone as timezone
from django.conf import settings
import os
import pytz
import math
from datetime import timedelta, datetime
class Running... | start_time = timezone.now() # + timedelta(days=1)
# start_time = datetime.strptime("2018-01-01 00:00:01", "%Y-%m-%d %H:%M:%S")
kilos_day, goal_distance, left_distance = None, None, None
if running_type:
kilos_day = distance
else:
actual_day_map = ... | if settings.DEBUG:
start_time = timezone.now()
else:
# 当天创建活动只有后一天才能参加,所以以后一天为开始日期 | random_line_split |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... | (ix: u32, x: f32, y1: bool, sign: bool) -> f32 {
let z: f64;
let mut s: f64;
let c: f64;
let mut ss: f64;
let mut cc: f64;
s = sinf(x) as f64;
if y1 {
s = -s;
}
c = cosf(x) as f64;
cc = s - c;
if ix < 0x7f000000 {
ss = -s - c;
z = cosf(2.0 * x) as f64... | common | identifier_name |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... |
#[test]
fn test_y1f_2002() {
//allow slightly different result on x87
let res = y1f(2.0000002_f32);
if cfg!(all(target_arch = "x86", not(target_feature = "sse2"))) && (res == -0.10703231_f32)
{
return;
}
assert_eq!(res, -0.10703229_f32);
}
}
| {
// 0x401F3E49
assert_eq!(j1f(2.4881766_f32), 0.49999475_f32);
} | identifier_body |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... | ix = x.to_bits();
sign = (ix >> 31) != 0;
ix &= 0x7fffffff;
if ix >= 0x7f800000 {
return 1.0 / (x * x);
}
if ix >= 0x40000000 {
/* |x| >= 2 */
return common(ix, fabsf(x), false, sign);
}
if ix >= 0x39000000 {
/* |x| >= 2**-13 */
z = x * x;
... | let sign: bool;
| random_line_split |
postgres.go | package postgres
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/cortexproject/cortex/pkg/configs/userconfig"
util_log "github.com/cortexproject/cortex/pkg/util/log"
"github.com/Masterminds/squirrel"
"github.com/go-kit/log/level"
"github.com/golang-migrate/migrate/v4"
... |
// GetAllConfigs gets all of the userconfig.
func (d DB) GetAllConfigs(ctx context.Context) (map[string]userconfig.View, error) {
return d.findConfigs(allConfigs)
}
// GetConfigs gets all of the configs that have changed recently.
func (d DB) GetConfigs(ctx context.Context, since userconfig.ID) (map[string]userconf... | {
if !cfg.RulesConfig.FormatVersion.IsValid() {
return fmt.Errorf("invalid rule format version %v", cfg.RulesConfig.FormatVersion)
}
cfgBytes, err := json.Marshal(cfg)
if err != nil {
return err
}
_, err = d.Insert("configs").
Columns("owner_id", "owner_type", "subsystem", "config").
Values(userID, entit... | identifier_body |
postgres.go | package postgres
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/cortexproject/cortex/pkg/configs/userconfig"
util_log "github.com/cortexproject/cortex/pkg/util/log"
"github.com/Masterminds/squirrel"
"github.com/go-kit/log/level"
"github.com/golang-migrate/migrate/v4"
... |
// RestoreConfig restores configuration.
func (d DB) RestoreConfig(ctx context.Context, userID string) error {
cfg, err := d.GetConfig(ctx, userID)
if err != nil {
return err
}
return d.SetDeletedAtConfig(ctx, userID, pq.NullTime{}, cfg.Config)
}
// Transaction runs the given function in a postgres transaction.... | return err
}
return d.SetDeletedAtConfig(ctx, userID, pq.NullTime{Time: time.Now(), Valid: true}, cfg.Config)
} | random_line_split |
postgres.go | package postgres
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/cortexproject/cortex/pkg/configs/userconfig"
util_log "github.com/cortexproject/cortex/pkg/util/log"
"github.com/Masterminds/squirrel"
"github.com/go-kit/log/level"
"github.com/golang-migrate/migrate/v4"
... |
// Legacy configs don't have a rule format version, in which case this will
// be a zero-length (but non-nil) slice.
if len(rfvBytes) > 0 {
err = json.Unmarshal([]byte(`"`+string(rfvBytes)+`"`), &cfg.Config.FormatVersion)
if err != nil {
return nil, err
}
}
cfg.DeletedAt = deletedAt.Time
cfgs[... | {
return nil, err
} | conditional_block |
postgres.go | package postgres
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/cortexproject/cortex/pkg/configs/userconfig"
util_log "github.com/cortexproject/cortex/pkg/util/log"
"github.com/Masterminds/squirrel"
"github.com/go-kit/log/level"
"github.com/golang-migrate/migrate/v4"
... | (f func(DB) error) error {
if _, ok := d.dbProxy.(*sql.Tx); ok {
// Already in a nested transaction
return f(d)
}
tx, err := d.dbProxy.(*sql.DB).Begin()
if err != nil {
return err
}
err = f(DB{
dbProxy: tx,
StatementBuilderType: statementBuilder(tx),
})
if err != nil {
// Rollback erro... | Transaction | identifier_name |
chroot.go | package shared
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
lxd "github.com/canonical/lxd/shared"
"golang.org/x/sys/unix"
)
// ChrootMount defines mount args.
type ChrootMount struct {
Source string
Target string
FSType string
Flags uintptr
Data string
IsDir bool
}
// ActiveChroots is a m... | if err != nil {
return fmt.Errorf("Failed to mount '%s': %w", mount.Source, err)
}
}
return nil
}
func moveMounts(mounts []ChrootMount) error {
for i, mount := range mounts {
// Source path
tmpSource := filepath.Join("/", ".distrobuilder", fmt.Sprintf("%d", i))
// Resolve symlinks
target := mount.T... |
// Mount to the temporary path
err := unix.Mount(mount.Source, tmpTarget, mount.FSType, mount.Flags, mount.Data) | random_line_split |
chroot.go | package shared
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
lxd "github.com/canonical/lxd/shared"
"golang.org/x/sys/unix"
)
// ChrootMount defines mount args.
type ChrootMount struct {
Source string
Target string
FSType string
Flags uintptr
Data string
IsDir bool
}
// ActiveChroots is a m... |
func populateDev() error {
devs := []struct {
Path string
Major uint32
Minor uint32
Mode uint32
}{
{"/dev/console", 5, 1, unix.S_IFCHR | 0640},
{"/dev/full", 1, 7, unix.S_IFCHR | 0666},
{"/dev/null", 1, 3, unix.S_IFCHR | 0666},
{"/dev/random", 1, 8, unix.S_IFCHR | 0666},
{"/dev/tty", 5, 0, unix.... | {
// Mount the rootfs
err := unix.Mount(rootfs, rootfs, "", unix.MS_BIND, "")
if err != nil {
return nil, fmt.Errorf("Failed to mount '%s': %w", rootfs, err)
}
// Setup all other needed mounts
mounts := []ChrootMount{
{"none", "/proc", "proc", 0, "", true},
{"none", "/sys", "sysfs", 0, "", true},
{"none"... | identifier_body |
chroot.go | package shared
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
lxd "github.com/canonical/lxd/shared"
"golang.org/x/sys/unix"
)
// ChrootMount defines mount args.
type ChrootMount struct {
Source string
Target string
FSType string
Flags uintptr
Data string
IsDir bool
}
// ActiveChroots is a m... | (rootfs string, mounts []ChrootMount) error {
// Create a temporary mount path
err := os.MkdirAll(filepath.Join(rootfs, ".distrobuilder"), 0700)
if err != nil {
return fmt.Errorf("Failed to create directory %q: %w", filepath.Join(rootfs, ".distrobuilder"), err)
}
for i, mount := range mounts {
// Target path
... | setupMounts | identifier_name |
chroot.go | package shared
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
lxd "github.com/canonical/lxd/shared"
"golang.org/x/sys/unix"
)
// ChrootMount defines mount args.
type ChrootMount struct {
Source string
Target string
FSType string
Flags uintptr
Data string
IsDir bool
}
// ActiveChroots is a m... |
}
symlinks := []struct {
Symlink string
Target string
}{
{"/dev/fd", "/proc/self/fd"},
{"/dev/stdin", "/proc/self/fd/0"},
{"/dev/stdout", "/proc/self/fd/1"},
{"/dev/stderr", "/proc/self/fd/2"},
}
for _, l := range symlinks {
err := os.Symlink(l.Target, l.Symlink)
if err != nil {
return fmt.E... | {
return fmt.Errorf("Failed to chmod %q: %w", d.Path, err)
} | conditional_block |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... |
/* POST /questions */
#[derive(FromForm)]
struct PostQuestionForm {
body: String
}
#[derive(Serialize, Debug)]
struct PostQuestionFailedDTO {
reason: String
}
#[post("/questions", data = "<params>")]
fn post_question(repo: web::guard::Repository, client_ip: web::guard::ClientIP, params: request::Form<PostQ... | {
let answer_dtos = repo.search_answers(query.clone())
.into_iter()
.map(|a| AnswerDTO::from(a))
.collect::<Vec<_>>();
let context = SearchDTO {
profile: ProfileDTO {
username: profile.clone().nam... | identifier_body |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | onse::Responder<'r> for RequireLogin {
fn respond_to(self, _req: &Request) -> Result<response::Response<'r>, Status> {
response::Response::build()
.status(Status::Unauthorized)
.header(Header::new("WWW-Authenticate", "Basic realm=\"SECRET AREA\""))
.ok()
}
}
#[catch(... | mpl<'r> resp | identifier_name |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | ,
Err(err) => {
match err {
model::StoreQuestionError::BlankBody => {
let context = PostQuestionFailedDTO { reason: String::from("質問の内容が空です") };
Err(Template::render("question/post_failed", &context))
}
}
}
... | {
let question_id = question.id;
notify::send_email(question);
Ok(response::Redirect::to(format!("/question/{}/after_post", question_id)))
} | conditional_block |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | #[derive(Serialize, Debug)]
struct ShowAnswerDTO {
pub answer: AnswerDTO,
pub next_answer: Option<AnswerDTO>,
pub prev_answer: Option<AnswerDTO>,
}
#[get("/question/<question_id>")]
fn show_question(question_id: i32, repo: web::guard::Repository) -> Result<response::Redirect, status::NotFound<&'static str>... | random_line_split | |
lib.rs | // Copyright (c) 2019, Bayu Aldi Yansyah <bayualdiyansyah@gmail.com>
//
// 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 requ... | //! ```
//!
//! To get started using Crabsformer, read the quickstart tutorial below.
//!
//! # Quickstart Tutorial
//!
//! ## Prerequisites
//! Before reading this quick tutorial you should know a bit of Rust. If you
//! would like to refresh your memory, take a look at the [Rust book].
//!
//! [Rust book]: https://do... | //!
//! and this to your crate root:
//!
//! ```
//! use crabsformer::prelude::*; | random_line_split |
2.1.dl_tf_intermediate_classifications.py | #%% Binary classification On Kaggle data using Tensorflow Multi level
# Restart the Spyder
import pandas as pd
import numpy as np
import tensorflow as tf
import os
from sklearn.metrics import accuracy_score, cohen_kappa_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
from sklearn.... |
if caller_source == 'train':
dataset = dataset.shuffle(len(features)) #if ".repeat()" is added here then add "epochs steps_per_epoch" in fit
dataset = dataset.batch(custom_batch_size)
return dataset
#train in iterable dataset
ds_train = input_fn(training_set[FEATURES], tr... | dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) | conditional_block |
2.1.dl_tf_intermediate_classifications.py | #%% Binary classification On Kaggle data using Tensorflow Multi level
# Restart the Spyder
import pandas as pd
import numpy as np
import tensorflow as tf
import os
from sklearn.metrics import accuracy_score, cohen_kappa_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
from sklearn.... | (features, labels = None, custom_batch_size = batch_size, caller_source = 'train'):
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices(dict(features))
if caller_source != 'test':
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
... | input_fn | identifier_name |
2.1.dl_tf_intermediate_classifications.py | #%% Binary classification On Kaggle data using Tensorflow Multi level
# Restart the Spyder
import pandas as pd
import numpy as np
import tensorflow as tf
import os
from sklearn.metrics import accuracy_score, cohen_kappa_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
from sklearn.... | training_set.shape
training_set.head(2)
len_fea = len(ar_independent_features)
# Build the model
model = tf.keras.models.Sequential() # same as tf.keras.Sequential()
model.add(tf.keras.layers.Dense(2*len_fea, input_shape=(len_fea,), activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(len_fea, activation=t... | random_line_split | |
2.1.dl_tf_intermediate_classifications.py | #%% Binary classification On Kaggle data using Tensorflow Multi level
# Restart the Spyder
import pandas as pd
import numpy as np
import tensorflow as tf
import os
from sklearn.metrics import accuracy_score, cohen_kappa_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt
from sklearn.... |
#train in iterable dataset
ds_train = input_fn(training_set[FEATURES], training_set[LABEL],custom_batch_size = batch_size)
#Create feature columns
feature_cols = []
# numeric cols
for num_col in NUM_FEATURES:
feature_cols.append(tf.feature_column.numeric_column(num_col, dtype=tf.float32))
#bucketized... | dataset = tf.data.Dataset.from_tensor_slices(dict(features))
if caller_source != 'test':
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
if caller_source == 'train':
dataset = dataset.shuffle(len(features)) #if ".repeat()" is added here then add "epochs st... | identifier_body |
ivf_torch.py | import torch
import time
from pykeops.torch import LazyTensor, Genred, KernelSolve, default_dtype
from pykeops.torch.cluster import swap_axes as torch_swap_axes
from pykeops.torch.cluster import cluster_ranges_centroids, from_matrix
# from pykeops.torch.generic.generic_red import GenredLowlevel
def is_on_device(x):
... | elif dtype == int:
return int
elif dtype == list:
return "float32"
else:
raise ValueError(
"[KeOps] {} data type incompatible with KeOps.".format(dtype)
)
@staticmethod
def rand(m, n, dtype=default_dtype, device="cpu"):
... | return "float64"
elif dtype == torch.float16:
return "float16" | random_line_split |
ivf_torch.py | import torch
import time
from pykeops.torch import LazyTensor, Genred, KernelSolve, default_dtype
from pykeops.torch.cluster import swap_axes as torch_swap_axes
from pykeops.torch.cluster import cluster_ranges_centroids, from_matrix
# from pykeops.torch.generic.generic_red import GenredLowlevel
def is_on_device(x):
... |
if k == 1:
return self.tools.view(self.tools.long(d.argmin(dim=1)), -1)
else:
return self.tools.long(d.argKmin(K=k, dim=1))
def __sort_clusters(self, x, lab, store_x=True):
lab, perm = self.tools.sort(self.tools.view(lab, -1))
if store_x:
self._... | d.backend = self.__backend | conditional_block |
ivf_torch.py | import torch
import time
from pykeops.torch import LazyTensor, Genred, KernelSolve, default_dtype
from pykeops.torch.cluster import swap_axes as torch_swap_axes
from pykeops.torch.cluster import cluster_ranges_centroids, from_matrix
# from pykeops.torch.generic.generic_red import GenredLowlevel
def is_on_device(x):
... |
N, D = x.shape
c = x[:K, :].clone()
x_i = LazyTensor(x.view(N, 1, D).to(device))
for i in range(Niter):
c_j = LazyTensor(c.view(1, K, D).to(device))
D_ij = distance(x_i, c_j)
cl = D_ij.argmin(dim=1).long().view(-1)
# updating c: either ... | "Helper function to optimise centroid location"
c = torch.clone(c.detach()).to(device)
c.requires_grad = True
x1 = LazyTensor(x.unsqueeze(0))
op = torch.optim.Adam([c], lr=1 / n)
scaling = 1 / torch.gather(torch.bincount(cl), 0, cl).view(-1, 1)
sca... | identifier_body |
ivf_torch.py | import torch
import time
from pykeops.torch import LazyTensor, Genred, KernelSolve, default_dtype
from pykeops.torch.cluster import swap_axes as torch_swap_axes
from pykeops.torch.cluster import cluster_ranges_centroids, from_matrix
# from pykeops.torch.generic.generic_red import GenredLowlevel
def is_on_device(x):
... | (self):
pass
def __k_argmin(self, x, y, k=1):
x_LT = self.__LazyTensor(
self.tools.to(self.tools.unsqueeze(x, 1), self.__device)
)
y_LT = self.__LazyTensor(
self.tools.to(self.tools.unsqueeze(y, 0), self.__device)
)
d = self.__distance(x_LT, ... | __get_tools | identifier_name |
views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import signUpForm, EventForm, AddMemberForm, AddLocation
import requests
from datetime import datetime, date
from django.http... | (request, note_id):
note= Notes.objects.get(id= note_id)
note.delete()
return JsonResponse({'result' : 'ok'}, status=200)
#add file for event view
@login_required
def add_files(request):
#getting the event to which we want to add file
event_id = request.POST.get('event_id')
event = Event.object... | note_delete | identifier_name |
views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import signUpForm, EventForm, AddMemberForm, AddLocation
import requests
from datetime import datetime, date
from django.http... |
else:
Http404('Wrong credentials')
# If logged in, session variables are cleaned up and user logged out. Otherwise redirected to login page
@login_required
def logoutView(request):
logout(request)
#registration
def signUpView(request):
#checking if methos is POST
if request.method == "POST":... | request.session['username'] = username
request.session['password'] = password
context = {
'username': username,
'password': password,
'loggedin': True
}
response = render(request, 'index.html', context)
# Remember last login in cookie
... | conditional_block |
views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import signUpForm, EventForm, AddMemberForm, AddLocation
import requests
from datetime import datetime, date
from django.http... | note.save()
#returning to ajax like in crete note
return JsonResponse({'note' : model_to_dict(note)}, status=200)
#exercise detail view
@login_required
def healthView(request):
user = CustomUser.objects.get(username= request.user)
#get exercise details if already created
if Exercise.objects.fi... | note.complited = False
elif note.complited == False:
note.complited = True
#saveing new status | random_line_split |
views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import signUpForm, EventForm, AddMemberForm, AddLocation
import requests
from datetime import datetime, date
from django.http... |
#delete location, same process as delete member
@login_required
def location_delete(request, location_id):
location = Locations.objects.get(id = location_id)
location.delete()
return JsonResponse({'result' : 'ok'}, status=200)
#note delte same process as delete member
@login_required
def note_delete(requ... | file = EventFiles.objects.get(id = file_id)
file.delete()
return JsonResponse({'result' : 'ok'}, status=200) | identifier_body |
utils.py | #! /usr/bin/env python
import csv
import itertools
import numpy as np
import nltk
from nltk import word_tokenize
import time
import cPickle
import sys
import operator
import io
import array
from datetime import datetime
from gru_theano import GRUTheano
from keras.datasets.data_utils import get_file
from keras.preproc... |
tokens = word_tokenize(text)
word_freq = nltk.FreqDist(tokens)
if verbose:
print("Found %d unique words tokens." % len(word_freq.items()))
vocab = word_freq.most_common(vocsize-3)
indices_word = [x[0] for x in vocab]
indices_word.append(UNKNOWN_TOKEN)
indices_word.append(S... | print('corpus length:', len(text)) | conditional_block |
utils.py | #! /usr/bin/env python
import csv
import itertools
import numpy as np
import nltk
from nltk import word_tokenize
import time
import cPickle
import sys
import operator
import io
import array
from datetime import datetime
from gru_theano import GRUTheano
from keras.datasets.data_utils import get_file
from keras.preproc... | """
Saves stuff to disk as pickle object
:type stuff: any type
:param stuff: data to be stored
Return: create pickle file at path
"""
if path == None:
# TODO take name from something
output = open('results/i-will-be-overwritten.pkl', 'wb')
else:
output = open(pat... | identifier_body | |
utils.py | #! /usr/bin/env python
import csv
import itertools
import numpy as np
import nltk
from nltk import word_tokenize
import time
import cPickle
import sys
import operator
import io
import array
from datetime import datetime
from gru_theano import GRUTheano
from keras.datasets.data_utils import get_file
from keras.preproc... | (s, index_to_word):
sentence_str = [index_to_word[x] for x in s[1:-1]]
print(" ".join(sentence_str))
sys.stdout.flush()
def generate_sentence(model, index_to_word, word_to_index, min_length=5):
# We start the sentence with the start token
new_sentence = [word_to_index[SENTENCE_START_TOKEN]]
# R... | print_sentence | identifier_name |
utils.py | #! /usr/bin/env python
import csv
import itertools
import numpy as np
import nltk
from nltk import word_tokenize
import time
import cPickle
import sys
import operator
import io
import array
from datetime import datetime
from gru_theano import GRUTheano
from keras.datasets.data_utils import get_file
from keras.preproc... |
return xx, yy, vocab, word_indices, indices_word
def train_with_sgd(model, X_train, y_train, learning_rate=0.001, nepoch=40, startfrom = 0, decay=0.9,
callback_every=10000, callback=None):
for epoch in range(startfrom, nepoch):
num_examples_seen = 0
# For each training examp... |
# Create the training data
xx = np.asarray(tokens[:-1], dtype=np.int32)
yy = np.asarray(tokens[1:], dtype=np.int32) | random_line_split |
Surreal.py | # ----------------------------------------------------------------------------------------------------------------------
#
# Class handling Surreal Dataset (training and testing)
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Hugu... | (stacked_points, stacked_evecs, stacked_evecs_trans,
stacked_evals, stacked_evecs_full, obj_inds, stack_lengths):
"""
From the input point cloud, this function compute all the point clouds at each conv layer, the neighbors
indices, the pooling indices and other use... | tf_map | identifier_name |
Surreal.py | # ----------------------------------------------------------------------------------------------------------------------
#
# Class handling Surreal Dataset (training and testing)
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Hugu... |
return tf_map
| """
From the input point cloud, this function compute all the point clouds at each conv layer, the neighbors
indices, the pooling indices and other useful variables.
:param stacked_points: Tensor with size [None, 3] where None is the total number of points
:param stack_le... | identifier_body |
Surreal.py | # ----------------------------------------------------------------------------------------------------------------------
#
# Class handling Surreal Dataset (training and testing)
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Hugu... |
else:
return cpp_subsampling.compute(points, features=features, classes=labels, sampleDl=sampleDl, verbose=verbose)
# ----------------------------------------------------------------------------------------------------------------------
#
# Class Definition
# \***************/
#
class S... | return cpp_subsampling.compute(points, classes=labels, sampleDl=sampleDl, verbose=verbose) | conditional_block |
Surreal.py | # ----------------------------------------------------------------------------------------------------------------------
#
# Class handling Surreal Dataset (training and testing)
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Hugu... | :param labels: optional (N,) matrix of integer labels
:param sampleDl: parameter defining the size of grid voxels
:param verbose: 1 to display
:return: subsampled points, with features and/or labels depending of the input
"""
if (features is None) and (labels is None):
return cpp_subsam... | :param points: (N, 3) matrix of input points
:param features: optional (N, d) matrix of features (floating number) | random_line_split |
widget.rs | //! Widget controller.
//!
//! The Widget Controller is responsible for querying the language server for information about
//! the node's widget configuration or resolving it from local cache.
mod configuration;
mod response;
use crate::prelude::*;
use crate::controller::visualization::manager::Manager;
use crate:... | buffer
}
} | }
buffer.push(']'); | random_line_split |
widget.rs | //! Widget controller.
//!
//! The Widget Controller is responsible for querying the language server for information about
//! the node's widget configuration or resolving it from local cache.
mod configuration;
mod response;
use crate::prelude::*;
use crate::controller::visualization::manager::Manager;
use crate:... | (&mut self, suggestion: &enso_suggestion_database::Entry, req: &Request) -> bool {
let mut visualization_modified = false;
if self.method_name != suggestion.name {
self.method_name = suggestion.name.clone();
visualization_modified = true;
}
let mut zipped_argume... | update | identifier_name |
argument_parser.py | import argparse
import os
import sys
import textwrap
import configargparse
import locust
version = locust.__version__
DEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']
def _is_package(path):
"""
Is the given path a Python package?
"""
return (
os.path.isdir(path)
and os.path... | (locustfile):
"""
Attempt to locate a locustfile, either explicitly or by searching parent dirs.
"""
# Obtain env value
names = [locustfile]
# Create .py version if necessary
if not names[0].endswith('.py'):
names.append(names[0] + '.py')
# Does the name contain path elements?
... | find_locustfile | identifier_name |
argument_parser.py | import argparse
import os
import sys
import textwrap
import configargparse
import locust
version = locust.__version__
DEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']
def _is_package(path):
"""
Is the given path a Python package?
"""
return (
os.path.isdir(path)
and os.path... | dest='stop_timeout',
default=None,
help="Number of seconds to wait for a simulated user to complete any executing task before exiting. Default is to terminate immediately. This parameter only needs to be specified for the master process when running Locust distributed."
)
locust_cla... | '-s', '--stop-timeout',
action='store',
type=int, | random_line_split |
argument_parser.py | import argparse
import os
import sys
import textwrap
import configargparse
import locust
version = locust.__version__
DEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']
def _is_package(path):
"""
Is the given path a Python package?
"""
return (
os.path.isdir(path)
and os.path... |
if locustfile == "locust.py":
sys.stderr.write("The locustfile must not be named `locust.py`. Please rename the file and try again.\n")
sys.exit(1)
return locustfile
def setup_parser_arguments(parser):
"""
Setup command-line options
Takes a configargparse.Argume... | if options.help or options.version:
# if --help or --version is specified we'll call parse_options which will print the help/version message
parse_options(args=args)
sys.stderr.write("Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.\n")
... | conditional_block |
argument_parser.py | import argparse
import os
import sys
import textwrap
import configargparse
import locust
version = locust.__version__
DEFAULT_CONFIG_FILES = ['~/.locust.conf','locust.conf']
def _is_package(path):
"""
Is the given path a Python package?
"""
return (
os.path.isdir(path)
and os.path... |
def get_parser(default_config_files=DEFAULT_CONFIG_FILES):
# get a parser that is only able to parse the -f argument
parser = get_empty_argument_parser(add_help=True, default_config_files=default_config_files)
# add all the other supported arguments
setup_parser_arguments(parser)
# fire event to p... | """
Setup command-line options
Takes a configargparse.ArgumentParser as argument and calls it's add_argument
for each of the supported arguments
"""
parser._optionals.title = "Common options"
parser.add_argument(
'-H', '--host',
help="Host to load test in the following form... | identifier_body |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... |
}
/// Function that does early processing of the peer's message and decides how it shall be
/// handled. Returns a function so that it may be passed to the `Handler`.
fn processor(
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> + 'static
{
mo... | {
Err(RpcError::MismatchedResponseType.into())
} | conditional_block |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... | (
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> + 'static
{
move |event: TransportEvent| {
let binary_data = match event {
TransportEvent::BinaryMessage(data) => data,
_ => return Disposition::error(UnexpectedTextMe... | processor | identifier_name |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... |
fn write_file(&self, path: &Path, contents: &[u8]) -> StaticBoxFuture<FallibleResult> {
info!("Writing file {} with {} bytes.", path, contents.len());
let payload = ToServerPayload::WriteFile { path, contents };
self.make_request(payload, Self::expect_success)
}
fn read_file(&self... | {
info!("Initializing binary connection as client with id {client_id}.");
let payload = ToServerPayload::InitSession { client_id };
self.make_request(payload, Self::expect_success)
} | identifier_body |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... | // ===============
struct ClientFixture {
transport: MockTransport,
client: Client,
executor: futures::executor::LocalPool,
}
impl ClientFixture {
fn new() -> ClientFixture {
let transport = MockTransport::new();
let client = Client::new(tran... |
// ===============
// === Fixture === | random_line_split |
anlyzPRR.py | '''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest
Created 27 Aug 20
@author: rik@electronicArtifacts.com
'''
from collections import defaultdict
import csv
import datetime
import json
import random
import re
import requests
import sys
import time
import urllib
import re
PRRDateFm... | rptOpenPRR(prr20Recent,openPRRFile)
deptFreqFile = dataDir + 'deptFreq2.csv'
rptDeptFreq(prr20Recent, deptTbl,startDate,deptFreqFile)
createDateFile = dataDir + 'createDate_200831.csv'
anlyzCreateDates(prr20Recent,createDateFile)
clearDateDir = dataDir + 'deptClear_200831/'
anlyzClearDates(prr20Recent,deptT... | random_line_split | |
anlyzPRR.py | '''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest
Created 27 Aug 20
@author: rik@electronicArtifacts.com
'''
from collections import defaultdict
import csv
import datetime
import json
import random
import re
import requests
import sys
import time
import urllib
import re
PRRDateFm... |
def rptOpenPRR(prrTbl,outf):
daysOpen = defaultdict(lambda: defaultdict(list)) # ndays -> OPD/non -> [prrID]
runDate = datetime.datetime.today()
for prrID in prrTbl.keys():
prr = prrTbl[prrID]
opdP = 'Police Department' in prr['dept']
if prr['status'] == 'Open' or prr['status'] == 'Overdue' or prr['stat... | outs = open(outf,'w')
outs.write('Dept,Freq\n')
for dept in sorted(deptTbl.keys()):
nrecent = 0
for prrIdx in deptTbl[dept]:
prr = prrTbl[prrIdx]
if prr['createDate'] >= startDate:
nrecent += 1
outs.write('%s,%d\n' % (dept,nrecent))
outs.close() | identifier_body |
anlyzPRR.py | '''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest
Created 27 Aug 20
@author: rik@electronicArtifacts.com
'''
from collections import defaultdict
import csv
import datetime
import json
import random
import re
import requests
import sys
import time
import urllib
import re
PRRDateFm... | (a,b):
"decreasing order of frequencies"
return b[1] - a[1]
flist = list(tbl.items()) #python3
flist.sort(key=cmp_to_key(cmpd1))
return flist
AllCSVHeader = ['Id', 'Created At', 'Request Text', 'Due Date', 'Point of Contact', 'Request Date',
'Status', 'URL', 'Visibility', 'Closed Date', 'Closure Reasons',... | cmpd1 | identifier_name |
anlyzPRR.py | '''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest
Created 27 Aug 20
@author: rik@electronicArtifacts.com
'''
from collections import defaultdict
import csv
import datetime
import json
import random
import re
import requests
import sys
import time
import urllib
import re
PRRDateFm... |
daysOpen[opdP][dkey].append(prrID)
outs = open(outf,'w')
outs.write('DaysOpen,NOPD,NOther,PRR-OPD,PRR-non\n')
allNDaySet = set(daysOpen[0].keys()).union(set(daysOpen[0].keys()))
allNDay = sorted(list(allNDaySet))
for nday in allNDay:
if nday > 365:
lbl = '> %d year' % (nday-1000)
else:
lbl = '%... | dkey = 1000 + openYears | conditional_block |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... |
} else {
tokio::spawn(new_b.future);
bindings.push((new_b.address, new_b.handle));
}
}
shared.rehash(cfg.state).await;
log::info!("Configuration reloaded");
}
/// Re-read the configuration file and re-generate the bindings.
///
/// See documentation of `reload_bin... | {
// Failure to send the command means either the binding task have dropped the
// command channel, or the binding task doesn't exist anymore. Both possibilities
// shouldn't happen (see doc for `Control.bindings`); but in the opposite case
// let's remov... | conditional_block |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... | (
config_path: String,
shared: State,
stop: mpsc::Sender<SocketAddr>,
) -> Option<(Config, Vec<LoadedBinding<impl Future<Output = ()>>>)> {
let mut cfg = match Config::from_file(&config_path) {
Ok(cfg) => cfg,
Err(err) => {
log::error!("Failed to read {:?}: {}", config_path, ... | reload_config | identifier_name |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... | //!
//! Bindings are identified by their socket address (IP address + TCP port). TLS identities are
//! not kept track of, thus ellidri might reload the same TLS identity for a binding (it is fine to
//! let it do we are not reading thousands for TLS identities here).
use crate::{Config, net, State, tls};
use crate::... | //! - If a binding is present in both configurations, `Control` will keep the binding and send a
//! command to it, either to make it listen for raw TCP connections, or to listen for TLS
//! connections with a given `TlsAcceptor` (see `tokio-tls` doc for that). | random_line_split |
config.rs | use clap::{CommandFactory, Parser};
use pathfinder_common::AllowedOrigins;
use pathfinder_storage::JournalMode;
use reqwest::Url;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use pathfinder_common::consts::VERGEN_GIT_DESCRIBE;
#[derive(Parser)]
#[command... | env = "PATHFINDER_ETHEREUM_API_PASSWORD",
)]
ethereum_password: Option<String>,
#[arg(
long = "ethereum.url",
long_help = r"This should point to the HTTP RPC endpoint of your Ethereum entry-point, typically a local Ethereum client or a hosted gateway service such as Infura or Cloud... |
#[arg(
long = "ethereum.password",
long_help = "The optional password to use for the Ethereum API",
value_name = None, | random_line_split |
config.rs | use clap::{CommandFactory, Parser};
use pathfinder_common::AllowedOrigins;
use pathfinder_storage::JournalMode;
use reqwest::Url;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use pathfinder_common::consts::VERGEN_GIT_DESCRIBE;
#[derive(Parser)]
#[command... | {
#[arg(
long,
value_name = "DIR",
value_hint = clap::ValueHint::DirPath,
long_help = "Directory where the node should store its data",
env = "PATHFINDER_DATA_DIRECTORY",
default_value_os_t = (&std::path::Component::CurDir).into()
)]
data_directory: PathBuf... | Cli | identifier_name |
vacuum.py | """Support for Deebot Vaccums."""
import logging
from typing import Any, Mapping, Optional
import voluptuous as vol
from deebot_client.commands import (
Charge,
Clean,
FanSpeedLevel,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.clean import CleanAc... |
async def on_status(event: StatusEvent) -> None:
self._state = event.state
self.async_write_ha_state()
listeners: list[EventListener] = [
self._vacuum_bot.events.subscribe(BatteryEvent, on_battery),
self._vacuum_bot.events.subscribe(CustomCommandEvent, ... | self._rooms = event.rooms
self.async_write_ha_state() | identifier_body |
vacuum.py | """Support for Deebot Vaccums."""
import logging
from typing import Any, Mapping, Optional
import voluptuous as vol
from deebot_client.commands import (
Charge,
Clean,
FanSpeedLevel,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.clean import CleanAc... | | SUPPORT_RETURN_HOME
| SUPPORT_FAN_SPEED
| SUPPORT_BATTERY
| SUPPORT_SEND_COMMAND
| SUPPORT_LOCATE
| SUPPORT_MAP
| SUPPORT_STATE
| SUPPORT_START
)
# Must be kept in sync with services.yaml
SERVICE_REFRESH = "refresh"
SERVICE_REFRESH_PART = "part"
SERVICE_REFRESH_SCHEMA = {
vol.Requ... | SUPPORT_DEEBOT: int = (
SUPPORT_PAUSE
| SUPPORT_STOP | random_line_split |
vacuum.py | """Support for Deebot Vaccums."""
import logging
from typing import Any, Mapping, Optional
import voluptuous as vol
from deebot_client.commands import (
Charge,
Clean,
FanSpeedLevel,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.clean import CleanAc... |
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_REFRESH,
SERVICE_REFRESH_SCHEMA,
"_service_refresh",
)
class DeebotVacuum(DeebotEntity, StateVacuumEntity): # type: ignore
"""Deebot Vacuum."""
def __init__(self, va... | async_add_entities(new_devices) | conditional_block |
vacuum.py | """Support for Deebot Vaccums."""
import logging
from typing import Any, Mapping, Optional
import voluptuous as vol
from deebot_client.commands import (
Charge,
Clean,
FanSpeedLevel,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.clean import CleanAc... | (event: FanSpeedEvent) -> None:
self._fan_speed = event.speed
self.async_write_ha_state()
async def on_report_stats(event: ReportStatsEvent) -> None:
self.hass.bus.fire(EVENT_CLEANING_JOB, dataclass_to_dict(event))
async def on_rooms(event: RoomsEvent) -> None:
... | on_fan_speed | identifier_name |
lib.rs | //! # OpenID Connect Client
//!
//! There are two ways to interact with this library - the batteries included magic methods, and
//! the slightly more boilerplate fine grained ones. For most users the former is what you want:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! l... | let expected = expected.to_string();
let actual = actual.to_string();
return Err(
Validation::Mismatch(Mismatch::Nonce { expected, actual }).into()
);
}
}
... | if expected != actual { | random_line_split |
lib.rs | //! # OpenID Connect Client
//!
//! There are two ways to interact with this library - the batteries included magic methods, and
//! the slightly more boilerplate fine grained ones. For most users the former is what you want:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! l... | (&self, token: &mut IdToken) -> Result<(), Error> {
// This is an early return if the token is already decoded
if let Compact::Decoded { .. } = *token {
return Ok(());
}
let header = token.unverified_header()?;
// If there is more than one key, the token MUST have a ... | decode_token | identifier_name |
lib.rs | //! # OpenID Connect Client
//!
//! There are two ways to interact with this library - the batteries included magic methods, and
//! the slightly more boilerplate fine grained ones. For most users the former is what you want:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! l... |
if let Some(max) = max_age {
match claims.auth_time {
Some(time) => {
let age = chrono::Duration::seconds(now.timestamp() - time);
if age >= *max {
return Err(error::Validation::Expired(Expiry::MaxAge(age)).into());
... | {
return Err(Validation::Expired(Expiry::Expires(
chrono::naive::NaiveDateTime::from_timestamp(claims.exp, 0),
))
.into());
} | conditional_block |
machine.rs | #[cfg(target_arch = "wasm32")]
use crate::ast::wasm::{LangValueArrayMap, LangValueMap, SourceElement};
use crate::{
ast::{
compiled::Program, Instruction, Label, LangValue, Node, RegisterRef,
SpanNode, StackRef, ValueSource,
},
consts::MAX_CYCLE_COUNT,
debug,
error::{RuntimeError, So... | {
/// An error occurred while trying to execute one of the instructions
RuntimeError,
/// The input buffer wasn't empty upon terminated
RemainingInput,
/// The output buffer didn't match the expected output, as defined by the
/// program spec
IncorrectOutput,
}
| FailureReason | identifier_name |
machine.rs | #[cfg(target_arch = "wasm32")]
use crate::ast::wasm::{LangValueArrayMap, LangValueMap, SourceElement};
use crate::{
ast::{
compiled::Program, Instruction, Label, LangValue, Node, RegisterRef,
SpanNode, StackRef, ValueSource,
},
consts::MAX_CYCLE_COUNT,
debug,
error::{RuntimeError, So... | .into_iter()
.map(|stack_ref| (stack_ref, self.stacks[stack_ref.0].as_slice()))
.collect()
}
/// Get the runtime error that halted execution of this machine. If no error
/// has occurred, return `None`.
pub fn error(&self) -> Option<&WithSource<RuntimeError>> {
... | pub fn stacks(&self) -> HashMap<StackRef, &[LangValue]> {
self.hardware_spec
.all_stack_refs() | random_line_split |
machine.rs | #[cfg(target_arch = "wasm32")]
use crate::ast::wasm::{LangValueArrayMap, LangValueMap, SourceElement};
use crate::{
ast::{
compiled::Program, Instruction, Label, LangValue, Node, RegisterRef,
SpanNode, StackRef, ValueSource,
},
consts::MAX_CYCLE_COUNT,
debug,
error::{RuntimeError, So... |
/// Pops an element off the given stack. If the pop is successful, the
/// popped value is returned. If the stack is empty, an error is returned.
/// If the stack reference is invalid, will panic (should be validated at
/// build time).
fn pop_stack(
&mut self,
stack_ref: &SpanNode... | {
// Have to access this first cause borrow checker
let max_stack_length = self.hardware_spec.max_stack_length;
let stack = &mut self.stacks[stack_ref.value().0];
// If the stack is capacity, make sure we're not over it
if stack.len() >= max_stack_length {
return Err... | identifier_body |
machine.rs | #[cfg(target_arch = "wasm32")]
use crate::ast::wasm::{LangValueArrayMap, LangValueMap, SourceElement};
use crate::{
ast::{
compiled::Program, Instruction, Label, LangValue, Node, RegisterRef,
SpanNode, StackRef, ValueSource,
},
consts::MAX_CYCLE_COUNT,
debug,
error::{RuntimeError, So... |
}
/// Internal function to execute the next instruction. The return value
/// is the same as [Self::execute_next], except the error needs to be
/// wrapped before being handed to the user.
fn execute_next_inner(&mut self) -> Result<bool, (RuntimeError, Span)> {
// We've previously hit an e... | {
Err((RuntimeError::EmptyStack, *stack_ref.metadata()))
} | conditional_block |
rgou.py | #!/usr/bin/env python
# Royal Game of Ur
try:
# python2
import Tkinter as tk
from Tkinter.messagebox import showinfo
except ImportError:
# python3
import tkinter as tk
from tkinter.messagebox import showinfo
import random # for rolls
def | (event):
print("clicked at", event.x, event.y)
coords(event.x,event.y)
# coordss(event.x,event.y)
#frame = Frame(game, width=100, height=100)
#game.mainloop()
game = tk.Tk()
game.title("Royal Game of Ur")
## BG image
#fname = "RGOU.gif"
#fname = "RGOU2.gif"
fname = "RGOU4.gif"
bg_image = tk.PhotoImage... | callback | identifier_name |
rgou.py | #!/usr/bin/env python
# Royal Game of Ur
try:
# python2
import Tkinter as tk
from Tkinter.messagebox import showinfo
except ImportError:
# python3
import tkinter as tk
from tkinter.messagebox import showinfo
import random # for rolls
def callback(event):
print("clicked at", event.x, event.y... |
# score()
def endmove(playagain = False): # True == one more move
global turn,rolled,moved
if turn == 0:
opponent = 2
else:
opponent = 0
if not playagain:
turn = opponent
rolled = False
moved = True
if playagain:
s = roll()
if s == 0:
... | a = tk.messagebox.askokcancel("popup","reset?")
if a:
def_cv_pieces(True)
setup() | identifier_body |
rgou.py | #!/usr/bin/env python
# Royal Game of Ur
try:
# python2
import Tkinter as tk
from Tkinter.messagebox import showinfo
except ImportError:
# python3
import tkinter as tk
from tkinter.messagebox import showinfo
import random # for rolls
def callback(event):
print("clicked at", event.x, event.y... | global cv
global whiterollicon,blackrollicon
whiterollicon = rollicon(0)
blackrollicon = rollicon(2)
if len(rollicons) == 3:
cv.delete(rollicons[0])
cv.delete(rollicons[2])
# w = rollicons[0]
# b = rollicons[2]
# cv[w]["image"] = whiterollicon
# cv[b]["ima... | global w ,b | random_line_split |
rgou.py | #!/usr/bin/env python
# Royal Game of Ur
try:
# python2
import Tkinter as tk
from Tkinter.messagebox import showinfo
except ImportError:
# python3
import tkinter as tk
from tkinter.messagebox import showinfo
import random # for rolls
def callback(event):
print("clicked at", event.x, event.y... |
# show canvas text :p
return
# RUN!
setup()
game.mainloop()
| cv.itemconfig(scoretext[0],font="Times 30 italic bold",text=t) | conditional_block |
lib.rs | //! Embed images in documentation.
//!
//! This crate enables the portable embedding of images in
//! `rustdoc`-generated documentation. Standard
//! web-compatible image formats should be supported. Please [file an issue][issue-tracker]
//! if you have problems. Read on to learn how it works.
//!
//! # Showcase
//!
//... | {
label: String,
path: PathBuf,
}
impl Parse for ImageDescription {
fn parse(input: ParseStream) -> parse::Result<Self> {
let label = input.parse::<syn::LitStr>()?;
input.parse::<syn::Token![,]>()?;
let path = input.parse::<syn::LitStr>()?;
Ok(ImageDescription {
... | ImageDescription | identifier_name |
lib.rs | //! Embed images in documentation.
//!
//! This crate enables the portable embedding of images in
//! `rustdoc`-generated documentation. Standard
//! web-compatible image formats should be supported. Please [file an issue][issue-tracker]
//! if you have problems. Read on to learn how it works.
//!
//! # Showcase
//!
//... | //! around the current limitations of `rustdoc` and enables a practically workable approach to
//! embedding images in a portable manner.
//!
//! # How to embed images in documentation
//!
//! First, you'll need to depend on this crate. In `cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! // Replace x.x with the lat... | //!
//! This crate represents a carefully crafted solution based on procedural macros that works | random_line_split |
orders-alter.js | var order = {};
order.init = function(){
this.page = staticPage;
this.orderType = type;
this.picUrl = picUrl;
this.active();
this.doAction();
// this.all();
// this.unpay();
// this.unship();
// this.alship();
// this.evaluate();
// this.refund();
this.imgBox();
this.loadorderDetail();
this.odialog... | }
order.createGroupLiHtml = function(nowGroup,buttonHtml){
var orderHtmls = "";
var imagesHtmls = "";
var disableHtmls = "";
for(q in nowGroup.orderGoodsImage.pics){
disableHtmls = "";
if(nowGroup.orderGoodsImage.pics[q].disable){
disableHtmls = '<i class="icon-failstate"></i>';
}
imagesHtmls += '<span ... | 'type':'post',
'dataType':'json',
success:func
}); | random_line_split |
rs_handler_user.go | package main
import (
"time"
"gohappy/data"
"gohappy/game/config"
"gohappy/game/handler"
"gohappy/glog"
"gohappy/pb"
"utils"
"github.com/AsynkronIT/protoactor-go/actor"
)
//玩家数据请求处理
func (rs *RoleActor) handlerUser(msg interface{}, ctx actor.Context) {
switch msg.(type) {
case *pb.CPing:
arg := msg.(*pb... | OG_TYPE15))
//充值消息提醒
record1, msg1 := handler.GiveNotice(amount, rs.User.GetUserid(), userid)
if record1 != nil {
rs.loggerPid.Tell(record1)
}
rs.Send(msg1)
} else {
msg.Error = pb.GiveUseridError
}
}
case pb.BankSelect: //查询
msg.Phone = rs.User.BankPhone
case pb.BankOpen: //开通
... | Currency(0, -1*amount, 0, 0, int32(pb.L | conditional_block |
rs_handler_user.go | package main
import (
"time"
"gohappy/data"
"gohappy/game/config"
"gohappy/game/handler"
"gohappy/glog"
"gohappy/pb"
"utils"
"github.com/AsynkronIT/protoactor-go/actor"
)
//玩家数据请求处理
func (rs *RoleActor) handlerUser(msg interface{}, ctx actor.Context) {
switch msg.(type) {
case *pb.CPing:
arg := msg.(*pb... | User.BankPhone == "" {
msg.Error = pb.BankNotOpen
} else if (coin - amount) < data.BANKRUPT {
msg.Error = pb.NotEnoughCoin
} else if amount <= 0 {
msg.Error = pb.DepositNumberError
} else {
rs.addCurrency(0, -1*amount, 0, 0, int32(pb.LOG_TYPE12))
rs.addBank(amount, int32(pb.LOG_TYPE12), "")
}
ca... | rs. | identifier_name |
rs_handler_user.go | package main
import (
"time"
"gohappy/data"
"gohappy/game/config"
"gohappy/game/handler"
"gohappy/glog"
"gohappy/pb"
"utils"
"github.com/AsynkronIT/protoactor-go/actor"
)
//玩家数据请求处理
func (rs *RoleActor) handlerUser(msg interface{}, ctx actor.Context) {
switch msg.(type) {
case *pb.CPing:
arg := msg.(*pb... | rsp := handler.GetCurrency(arg, rs.User)
rs.Send(rsp)
case *pb.CBuy:
arg := msg.(*pb.CBuy)
glog.Debugf("CBuy %#v", arg)
//优化
rsp, diamond, coin := handler.Buy(arg, rs.User)
//同步兑换
rs.addCurrency(diamond, coin, 0, 0, int32(pb.LOG_TYPE18))
//响应
rs.Send(rsp)
record, msg2 := handler.BuyNotice(coin, r... | rs.joinActivity(arg, ctx)
case *pb.CGetCurrency:
arg := msg.(*pb.CGetCurrency)
glog.Debugf("CGetCurrency %#v", arg)
//响应 | random_line_split |
rs_handler_user.go | package main
import (
"time"
"gohappy/data"
"gohappy/game/config"
"gohappy/game/handler"
"gohappy/glog"
"gohappy/pb"
"utils"
"github.com/AsynkronIT/protoactor-go/actor"
)
//玩家数据请求处理
func (rs *RoleActor) handlerUser(msg interface{}, ctx actor.Context) {
switch msg.(type) {
case *pb.CPing:
arg := msg.(*pb... | n); ok {
if response1.Error == pb.OK {
return true
}
glog.Errorf("BankGiven err %#v", response1)
return false
}
return false
}
//银行重置密码, 银行开通
func (rs *RoleActor) bankCheck(arg *pb.CBank) pb.ErrCode {
msg1 := &pb.BankCheck{
Userid: rs.User.GetUserid(),
Phone: arg.GetPhone(),
Password: arg.GetP... | = "" {
msg.Error = pb.BankNotOpen
} else if (coin - amount) < data.BANKRUPT {
msg.Error = pb.NotEnoughCoin
} else if amount <= 0 {
msg.Error = pb.DepositNumberError
} else {
rs.addCurrency(0, -1*amount, 0, 0, int32(pb.LOG_TYPE12))
rs.addBank(amount, int32(pb.LOG_TYPE12), "")
}
case pb.BankDraw: ... | identifier_body |
ppo_trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
import logging
from collections import deque, defaultdict
from typing import D... |
METRICS_BLACKLIST = {"top_down_map", "collisions.is_collision"}
@classmethod
def _extract_scalars_from_info(
cls, info: Dict[str, Any]
) -> Dict[str, float]:
result = {}
for k, v in info.items():
if k in cls.METRICS_BLACKLIST:
continue
... | checkpoints = glob.glob(f"{self.config.CHECKPOINT_FOLDER}/*.pth")
if len(checkpoints) == 0:
count_steps = 0
count_checkpoints = 0
start_update = 0
else:
last_ckpt = sorted(checkpoints, key=lambda x: int(x.split(".")[1]))[-1]
checkpoint_path = l... | identifier_body |
ppo_trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
import logging
from collections import deque, defaultdict
from typing import D... | count=torch.zeros(self.envs.num_envs, 1),
reward=torch.zeros(self.envs.num_envs, 1),
)
window_episode_stats = defaultdict(
lambda: deque(maxlen=ppo_cfg.reward_window_size)
)
t_start = time.time()
env_time = 0
pth_time = 0
count... | random_line_split | |
ppo_trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
import logging
from collections import deque, defaultdict
from typing import D... | (
cls, infos: List[Dict[str, Any]]
) -> Dict[str, List[float]]:
results = defaultdict(list)
for i in range(len(infos)):
for k, v in cls._extract_scalars_from_info(infos[i]).items():
results[k].append(v)
return results
def _collect_rollout_step(
... | _extract_scalars_from_infos | identifier_name |
ppo_trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
import logging
from collections import deque, defaultdict
from typing import D... |
writer.add_scalar("Policy/value_loss", value_loss, count_steps)
writer.add_scalar("Policy/policy_loss", action_loss, count_steps)
writer.add_scalar("Policy/entropy_loss", dist_entropy, count_steps)
writer.add_scalar('Policy/learning_rate', lr_scheduler.g... | for metric, value in metrics.items():
writer.add_scalar(f"Metrics/{metric}", value, count_steps) | conditional_block |
imaging-multibeam.py | #!/usr/bin/env python
import os
import sys
import numpy
import math
import glob
import shutil
import lofar.parameterset
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp
from pyrap.tables import table
from utility import run_process
from utility import t... |
# We source a special build for using the "new" awimager
awim_init = input_parset.getString("awimager.initscript")
# Calculate the threshold for cleaning based on the noise in a dirty map
# We don't use our threadpool here, since awimager is parallelized
noise_parset_name = get_parset_subset(input... | limit_baselines(target_info["output_ms"], target_info["bl_limit_ms"], maxbl)
with time_code("Limiting maximum baseline length"):
pool.map(limit_bl, ms_target.values()) | random_line_split |
imaging-multibeam.py | #!/usr/bin/env python
import os
import sys
import numpy
import math
import glob
import shutil
import lofar.parameterset
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp
from pyrap.tables import table
from utility import run_process
from utility import t... |
with time_code("Limiting maximum baseline length"):
pool.map(limit_bl, ms_target.values())
# We source a special build for using the "new" awimager
awim_init = input_parset.getString("awimager.initscript")
# Calculate the threshold for cleaning based on the noise in a dirty map
# We don't... | target_info["bl_limit_ms"] = mkdtemp(dir=scratch)
limit_baselines(target_info["output_ms"], target_info["bl_limit_ms"], maxbl) | identifier_body |
imaging-multibeam.py | #!/usr/bin/env python
import os
import sys
import numpy
import math
import glob
import shutil
import lofar.parameterset
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp
from pyrap.tables import table
from utility import run_process
from utility import t... | (target_info):
output = os.path.join(mkdtemp(dir=scratch), "combined.MS")
run_ndppp(
get_parset_subset(input_parset, "combine.parset", scratch),
{
"msin": str(target_info["datafiles"]),
"msout": output
}
)
target_info["c... | combine_ms | identifier_name |
imaging-multibeam.py | #!/usr/bin/env python
import os
import sys
import numpy
import math
import glob
import shutil
import lofar.parameterset
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp
from pyrap.tables import table
from utility import run_process
from utility import t... |
except Exception, e:
print "Error in phaseonly with %s" % (target_info["combined_ms"])
print str(e)
raise
# Most Lisa nodes have 24 GB RAM -- we don't want to run out
calpool = ThreadPool(6)
with time_code("Phase-only calibration"):
calpool.map(phaseonly... | shutil.copy(logfile, target_info["output_dir"]) | conditional_block |
bressan_computerscience.py | # -*- coding: utf-8 -*-
"""BRESSAN_ComputerScience
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ueH8-8StvLf_jngtgChgeeIzwrVHLfZW
# "Foundations of Computer Science" course (F9101Q001)
## Final Project
**Matteo Bressan - 765957**
---
The current... | (row):
start_date = row['disburse_time'].tz_localize(None)
end_date = row['planned_expiration_time'].tz_localize(None)
value = row['loan_amount']
# calculating the difference in years considewring leap years
jumps = end_date.year - start_date.year
if jumps != 0:
dayss = []
starting_year = start_d... | divide_value_by_period | identifier_name |
bressan_computerscience.py | # -*- coding: utf-8 -*-
"""BRESSAN_ComputerScience
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ueH8-8StvLf_jngtgChgeeIzwrVHLfZW
# "Foundations of Computer Science" course (F9101Q001)
## Final Project
**Matteo Bressan - 765957**
---
The current... |
"""Now, we can apply the funciton to the dataset, removing rows where one of the 2 dates are missing.
I also apply a check on overall duration, to remove issues (duration <= 0 days)
"""
time_loans = loans_import[loans_import.disburse_time.notnull() & loans_import.planned_expiration_time.notnull()]
time_loans = time_... | start_date = row['disburse_time'].tz_localize(None)
end_date = row['planned_expiration_time'].tz_localize(None)
value = row['loan_amount']
# calculating the difference in years considewring leap years
jumps = end_date.year - start_date.year
if jumps != 0:
dayss = []
starting_year = start_date.year
... | identifier_body |
bressan_computerscience.py | # -*- coding: utf-8 -*-
"""BRESSAN_ComputerScience
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ueH8-8StvLf_jngtgChgeeIzwrVHLfZW
# "Foundations of Computer Science" course (F9101Q001)
## Final Project
**Matteo Bressan - 765957**
---
The current... |
"""Then, I join obtained dataset with the _loans_ dataset by loan ID"""
lender_loan_country_full = pd.merge(
lender_loan_country.drop_duplicates(),
loans_import[['loan_id','loan_amount','country_code']],
left_on= ['loan_id'],
... |
lender_loan_country = lender_loan_country[['loan_id', 'lender_country']]
lender_loan_country.head(5) | random_line_split |
bressan_computerscience.py | # -*- coding: utf-8 -*-
"""BRESSAN_ComputerScience
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ueH8-8StvLf_jngtgChgeeIzwrVHLfZW
# "Foundations of Computer Science" course (F9101Q001)
## Final Project
**Matteo Bressan - 765957**
---
The current... |
else:
return value
"""Now, we can apply the funciton to the dataset, removing rows where one of the 2 dates are missing.
I also apply a check on overall duration, to remove issues (duration <= 0 days)
"""
time_loans = loans_import[loans_import.disburse_time.notnull() & loans_import.planned_expiration_time.notn... | dayss = []
starting_year = start_date.year
for i in range(jumps):
next_year = starting_year + 1
next_year_comp = datetime(next_year, 1, 1)
# get the difference in days
diff = (next_year_comp - start_date).days
dayss.append(diff)
# re-assigning start and end dates
... | conditional_block |
titanic-alpha-attempt.py | #!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
i... | (dataset, age_groups):
for sex in ['male','female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages
tmp['AgeGroup'] = age_groups[sex] # index age group values
dataset = dataset.combine_first(tmp) # uses tmp to fill holes
return dat... | insert_age_group_values | identifier_name |
titanic-alpha-attempt.py | #!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
i... |
# number of males and females by age group
def get_counts(dataset):
return dataset.groupby(['Sex', 'AgeGroup']).size()
# randomly generate a list of age groups based on age group frequency (for each sex separately)
def generate_age_groups(num, freq):
age_groups = {}
for sex in ['male','female']:
... | na_males = dataset[dataset.Sex == 'male'].loc[:,'AgeGroup'].isnull().sum()
na_females = dataset[dataset.Sex == 'female'].loc[:,'AgeGroup'].isnull().sum()
return {'male': na_males, 'female': na_females} | identifier_body |
titanic-alpha-attempt.py | #!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
i... |
# In[ ]:
# split the datasets into matched input and ouput pairs
X_train = train_df.drop("Survived", axis=1) # X = inputs
Y_train = train_df["Survived"] # Y = outputs
X_test = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape
# Model fitting
# ----------
# (Some of this section... | # The methods marked * either discover linear classification boundaries (logistic regression, perceptron, and SVMs if using linear kernels) or assume no relationship between features (naive bayes) and thus are not expected to perform as well (see the section above on the relationship between survival, age group and sex... | random_line_split |
titanic-alpha-attempt.py | #!/usr/bin/env python
# coding: utf-8
# Predicting Surviving the Sinking of the Titanic
# -----------------------------------------------
#
#
# This represents my first attempt at training up some classifiers for the titanic dataset.
# In[ ]:
# data analysis and wrangling
import pandas as pd
import numpy as np
i... |
return age_groups
# insert the new age group values
def insert_age_group_values(dataset, age_groups):
for sex in ['male','female']:
tmp = pd.DataFrame(dataset[(dataset.Sex == sex) & dataset.Age.isnull()]) # filter on sex and null ages
tmp['AgeGroup'] = age_groups[sex] # index age group va... | relfreq = freq[sex] / freq[sex].sum()
age_groups[sex] = np.random.choice(freq[sex].index, size=num[sex], replace=True, p=relfreq) | conditional_block |
contacts-details.component.ts | import { Component, OnInit, Input, forwardRef, ViewChild, OnDestroy, Inject, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { HttpClient, HttpHe... |
handleCancel() {
this.modalOpen = false;
this.inputForm.reset();
this.current = 0;
}
pre() {
this.current -= 1;
}
next() {
this.current += 1;
}
} | this.globalS.sToast('Success', 'Contact Deleted');
this.searchKin(this.user);
});
} | random_line_split |
contacts-details.component.ts | import { Component, OnInit, Input, forwardRef, ViewChild, OnDestroy, Inject, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { HttpClient, HttpHe... |
buildForm(): void {
this.kindetailsGroup = this.formBuilder.group({
listOrder: [''],
type: [''],
name: [''],
email: [''],
address1: [''],
address2: [''],
suburbcode: [''],
suburb: [''],
postcode: [''],
phone1: [''],
phone2: [''],
mobile: ['... | {
this.listS.getdoctorinformation().subscribe(data => {
console.log(data);
this.doctors = data;
})
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.