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 |
|---|---|---|---|---|
data.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
#
# 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... |
class BertVocab(object):
"""
While glove_vocab has been used as default. The term glove is misnomer. Glove_vocab represents normal vocab in this file
This function converts individual tokens to their respective word piece tokens
"""
def __init__(self, glove_vocab, bert_vocab_file_path):
self.bert_vocab = co... | """Vocabulary class for mapping between words and ids (integers)"""
def __init__(self, vocab_file, max_size):
"""Creates a vocab of up to max_size words, reading from the vocab_file. If max_size is 0, reads the entire vocab file.
Args:
vocab_file: path to the vocab file, which is assumed to contain "<word> <fr... | identifier_body |
bastion_test.go | // Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the Lice... | else {
return "", fmt.Errorf("not valid IPv4 address")
}
cidr := net.IPNet{
IP: ip,
Mask: mask,
}
full := cidr.String()
_, ipnet, _ := net.ParseCIDR(full)
return ipnet.String(), nil
}
func verifyPort22IsOpen(ctx context.Context, c client.Client, bastion *extensionsv1alpha1.Bastion) {
By("check conn... | {
mask = net.CIDRMask(24, 32) // use a /24 net for IPv4
} | conditional_block |
bastion_test.go | // Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the Lice... |
func verifyDeletion(clientFactory alicloudclient.ClientFactory, options *bastionctrl.Options) {
ecsClient, err := clientFactory.NewECSClient(*region, *accessKeyID, *accessKeySecret)
Expect(err).NotTo(HaveOccurred())
By("bastion instance should be gone")
response, err := ecsClient.GetInstances(options.BastionInst... | {
By("delete bastion")
Expect(client.IgnoreNotFound(c.Delete(ctx, bastion))).To(Succeed())
By("wait until bastion is deleted")
err := extensions.WaitUntilExtensionObjectDeleted(ctx, c, logger, bastion, extensionsv1alpha1.BastionResource, 20*time.Second, 15*time.Minute)
Expect(err).NotTo(HaveOccurred())
} | identifier_body |
bastion_test.go | // Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the Lice... | () (string, error) {
suffix, err := gardenerutils.GenerateRandomStringFromCharset(5, "0123456789abcdefghijklmnopqrstuvwxyz")
if err != nil {
return "", err
}
return suffix, nil
}
func getMyPublicIPWithMask() (string, error) {
resp, err := http.Get("https://api.ipify.org")
if err != nil {
return "", err
}
... | randomString | identifier_name |
bastion_test.go | // Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the Lice... | Shoot: shoot,
CloudProfile: cloudProfile,
}
return extensionscluster, cluster
}
func createInfrastructureConfig() *alicloudv1alpha1.InfrastructureConfig {
return &alicloudv1alpha1.InfrastructureConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: alicloudv1alpha1.SchemeGroupVersion.String(),
Kind: ... | },
}
cluster := &controller.Cluster{
ObjectMeta: metav1.ObjectMeta{Name: name}, | random_line_split |
WarningAlarm.js |
var searchText = $("#searchText").val();
var currentPage = $("#currentPage").html();
var pageIndex = currentPage - 1;
var raPageIndex = 0;
var pageSize = 16;
var totalPage = $("#totalPage").html();
var state = '';
var fKey = '';
var scrollOnoff = true;
$("#pageSize").html(pageSize);
$("#startTime").val(formatDate() +... | $.ajax({
url: '/V_YCJK/SearchAlarm',
data: {
"pumpID": pumpId,
"pumpJZID": jzId,
"pageIndex": raPageIndex,
"pageSize": 5, //搜索是pageSize值无效
"StartDate": '2016-01-01',//startDate
"EndDate": '2017-05-09'//endDate
},
da... | ty();
var str = '';
for (var i = 0; i < realAlarmData.length; i++) {
var tempStr = '<li data-id="' + realAlarmData[i].BaseID + '" data-fKey="' + realAlarmData[i].FKey + '">\
<div class="line1_box .clearfix">\
<p class="real_pumpName" data-id="P... | identifier_body |
WarningAlarm.js |
var searchText = $("#searchText").val();
var currentPage = $("#currentPage").html();
var pageIndex = currentPage - 1;
var raPageIndex = 0;
var pageSize = 16;
var totalPage = $("#totalPage").html();
var state = '';
var fKey = '';
var scrollOnoff = true;
$("#pageSize").html(pageSize);
$("#startTime").val(formatDate() +... | _alarmList").empty();
var str = '';
for (var i = 0; i < realAlarmData.length; i++) {
var tempStr = '<li data-id="' + realAlarmData[i].BaseID + '" data-fKey="' + realAlarmData[i].FKey + '">\
<div class="line1_box .clearfix">\
<p class="real_pump... | {
$(".ul | identifier_name |
WarningAlarm.js |
var searchText = $("#searchText").val();
var currentPage = $("#currentPage").html();
var pageIndex = currentPage - 1;
var raPageIndex = 0;
var pageSize = 16;
var totalPage = $("#totalPage").html();
var state = '';
var fKey = '';
var scrollOnoff = true;
$("#pageSize").html(pageSize);
$("#startTime").val(formatDate() +... | var i = url.indexOf('?');
if (i == -1) { return };
var queryStr = url.substr(i + 1);
var arr1 = queryStr.split('&');
var arr2 = {};
for (j in arr1) {
var tar = arr1[j].split('=');
arr2[tar[0]] = tar[1];
};
return arr2;
}
laydate({
elem: "#startTime",
format: "YYY... | random_line_split | |
WarningAlarm.js |
var searchText = $("#searchText").val();
var currentPage = $("#currentPage").html();
var pageIndex = currentPage - 1;
var raPageIndex = 0;
var pageSize = 16;
var totalPage = $("#totalPage").html();
var state = '';
var fKey = '';
var scrollOnoff = true;
$("#pageSize").html(pageSize);
$("#startTime").val(formatDate() +... | complete: loadingMiss,
error: function (data) {
console.log('错误:' + data.responseText);
}
});
}
function loadingFunction() {
var $div = $('<div class="loading" style="position:absolute;left: 50%;top:50%;margin-left: -150px;margin-top: -70px;width: 300px;color:black;text-alig... | a);
}
scrollOnoff = true;
},
| conditional_block |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... | desc.push_str(&stderr.replace("\n", "\n "));
}
if stack_overflow {
if is_stack_overflow(&output.status, &stderr) {
assert!(
stdout.trim().ends_with(CONFIRM),
"failed to find confirmation in test `{}`\n{}",
name,
desc... | random_line_split | |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... |
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The main thread might overflow or it might be from a fiber stack (SIGSEGV/SIGBUS)
stderr.contains("has overflowed its stack")
|| match status.signal() {
Some(libc::SIGSEGV)... | {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
} | identifier_body |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... |
}
#[cfg(unix)]
fn is_segfault(status: &ExitStatus) -> bool {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
}
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The m... | {
if is_segfault(&output.status) {
assert!(
stdout.trim().ends_with(CONFIRM) && stderr.is_empty(),
"failed to find confirmation in test `{}`\n{}",
name,
desc
);
} else {
panic!("\n\nexpected a segfault on... | conditional_block |
host_segfault.rs | // To handle out-of-bounds reads and writes we use segfaults right now. We only
// want to catch a subset of segfaults, however, rather than all segfaults
// happening everywhere. The purpose of this test is to ensure that we *don't*
// catch segfaults if it happens in a random place in the code, but we instead
// bail... | (ptr: *const ()) {
assert_eq!(ptr as usize, 5);
}
}
fn main() {
if cfg!(miri) {
return;
}
// Skip this tests if it looks like we're in a cross-compiled situation and
// we're emulating this test for a different platform. In that scenario
// emulators (like QEMU) tend to not repo... | drop | identifier_name |
builtins.go | package bot
import (
"fmt"
"log"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/lnxjedi/gopherbot/robot"
"golang.org/x/sys/unix"
)
// Cut off for listing channels after help text
const tooManyChannels = 4
func init() {
RegisterPlugin("builtin-fallback", r... |
if want_specific && !specific {
continue
}
Log(robot.Trace, "Checking help for plugin %s (term: %s)", task.name, term)
if !hasKeyword { // if you ask for help without a term, you just get help for whatever commands are available to you
for _, phelp := range plugin.Help {
for _, helptext := ran... | {
continue
} | conditional_block |
builtins.go | package bot
import (
"fmt"
"log"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/lnxjedi/gopherbot/robot"
"golang.org/x/sys/unix"
)
// Cut off for listing channels after help text
const tooManyChannels = 4
func init() {
RegisterPlugin("builtin-fallback", r... | (m robot.Robot, command string, args ...string) (retval robot.TaskRetVal) {
r := m.(Robot)
switch command {
case "init":
return
case "level":
setLogLevel(logStrToLevel(args[0]))
r.Say("I've adjusted the log level to %s", args[0])
Log(robot.Info, "User %s changed logging level to %s", r.User, args[0])
case ... | logging | identifier_name |
builtins.go | package bot
import (
"fmt"
"log"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/lnxjedi/gopherbot/robot"
"golang.org/x/sys/unix"
)
// Cut off for listing channels after help text
const tooManyChannels = 4
func init() {
RegisterPlugin("builtin-fallback", r... | if args[0] == task.name {
if plugin == nil {
r.Say("Task '%s' is a job, not a plugin", task.name)
return
}
found = true
c, _ := yaml.Marshal(plugin)
r.Fixed().Say("%s", c)
}
}
if !found {
r.Say("Didn't find a plugin named " + args[0])
}
case "listplugins":
joiner := ", "
... | found := false
for _, t := range r.tasks.t[1:] {
task, plugin, _ := getTask(t) | random_line_split |
builtins.go | package bot
import (
"fmt"
"log"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/lnxjedi/gopherbot/robot"
"golang.org/x/sys/unix"
)
// Cut off for listing channels after help text
const tooManyChannels = 4
func init() {
RegisterPlugin("builtin-fallback", r... |
type psList struct {
pslines []string
wids []int
}
func (p *psList) Len() int {
return len(p.pslines)
}
func (p *psList) Swap(i, j int) {
p.pslines[i], p.pslines[j] = p.pslines[j], p.pslines[i]
p.wids[i], p.wids[j] = p.wids[j], p.wids[i]
}
func (p *psList) Less(i, j int) bool {
return p.wids[i] < p.wids[j... | {
r := m.(Robot)
switch command {
case "init":
return
case "level":
setLogLevel(logStrToLevel(args[0]))
r.Say("I've adjusted the log level to %s", args[0])
Log(robot.Info, "User %s changed logging level to %s", r.User, args[0])
case "show":
page := 0
if len(args) == 1 {
page, _ = strconv.Atoi(args[0... | identifier_body |
server.go | package server
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types/volume"
"github.com/danhale-git/craft/internal/files"
"github.com/docker/docker/api/types/mount"
"github.com/danhale-git/craft/internal/logger"
"github.com/docker/docker/api/ty... | () (net.Conn, error) {
waiter, err := s.ContainerAttach(
context.Background(),
s.ContainerID,
docker.ContainerAttachOptions{
Stdin: true,
Stream: true,
},
)
if err != nil {
return nil, err
}
return waiter.Conn, err
}
// LogReader returns a buffer with the stdout and stderr from the running mc se... | CommandWriter | identifier_name |
server.go | package server
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types/volume"
"github.com/danhale-git/craft/internal/files"
"github.com/docker/docker/api/types/mount"
"github.com/danhale-git/craft/internal/logger"
"github.com/docker/docker/api/ty... | logger.Error.Panicf("while stopping %s another error occurred: %s\n", s.ContainerName, err)
}
}
// Command attaches to the container and runs the given arguments separated by spaces.
func (s *Server) Command(args []string) error {
conn, err := s.CommandWriter()
if err != nil {
return err
}
commandString := s... | if err != nil { | random_line_split |
server.go | package server
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types/volume"
"github.com/danhale-git/craft/internal/files"
"github.com/docker/docker/api/types/mount"
"github.com/danhale-git/craft/internal/logger"
"github.com/docker/docker/api/ty... |
// Stop executes a stop command first in the server process cli then on the container itself, stopping the
// server. The server must be saved separately to persist the world and settings.
func (s *Server) Stop() error {
if err := s.Command([]string{"stop"}); err != nil {
return fmt.Errorf("%s: running 'stop' comm... | {
id, err := containerID(containerName, cl)
if err != nil {
return nil, err
}
c := Server{
ContainerAPIClient: cl,
ContainerName: containerName,
ContainerID: id,
}
containerJSON, err := cl.ContainerInspect(context.Background(), c.ContainerID)
if err != nil {
return nil, fmt.Errorf("inspec... | identifier_body |
server.go | package server
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types/volume"
"github.com/danhale-git/craft/internal/files"
"github.com/docker/docker/api/types/mount"
"github.com/danhale-git/craft/internal/logger"
"github.com/docker/docker/api/ty... |
portBinding := nat.PortMap{containerPort: []nat.PortBinding{hostBinding}}
var mounts []mount.Mount
if mountVolume {
volName := fmt.Sprintf("%s-%s", volumeLabel, name)
vol, err := c.VolumeCreate(ctx, volume.VolumeCreateBody{
Name: volName,
})
if err != nil {
return nil, fmt.Errorf("creating vol '%s':... | {
return nil, fmt.Errorf("creating container port: %s", err)
} | conditional_block |
common.js | function $(el){
if (!el) return null;
if (el.htmlElement) return Garbage.collect(el);
if (typeof(document.getElementById(el))=="object") return document.getElementById(el);
var type = $type(el);
if (type == 'string'){
el = document.getElementById(el);
type = (el) ? 'element' : false;
}
if (type != 'element')... | getUrlParam(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{return decodeURIComponent(r[2]);}
else
{return ""; }
}
function Trim(ss)
{
// 用正则表达式将前后空格
// 用空字符串替代。
return ss.replace(/(^\s*)|(\s*$)/g, "... | nction | identifier_name |
common.js | function $(el){
if (!el) return null;
if (el.htmlElement) return Garbage.collect(el);
if (typeof(document.getElementById(el))=="object") return document.getElementById(el);
var type = $type(el);
if (type == 'string'){
el = document.getElementById(el);
type = (el) ? 'element' : false;
}
if (type != 'element')... | rn offset;
}
function getParent(el){
return el.parentNode ? el.parentNode : el.parentElement;
}
//登录情况下从公共平台跳转到会员管理平台,参数tourl 例如:要修改会员信息就传hqenmanger(CompanyInfo/MemberModify.aspx)
//CompanyInfo代表栏目,MemberModify.aspx代表文件
function hqenmanger(tourl)
{
window.open("/Web/Hqen/"+encodeURIComponent(to... | getLeft(e){
var offset=e.offsetLeft;
if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
retu | identifier_body |
common.js | function $(el){
if (!el) return null;
if (el.htmlElement) return Garbage.collect(el);
if (typeof(document.getElementById(el))=="object") return document.getElementById(el);
var type = $type(el);
if (type == 'string'){
el = document.getElementById(el);
type = (el) ? 'element' : false;
}
if (type != 'element')... | if(obj.value!=value){
return false;
}
obj.value="";
obj.className = cname;
}
function g_logout()
{
g_ibs("/Web/Hqen/Logout.aspx", false);
}
function HTMLEnCode(str)
{
var s = "";
if(str.length == 0)
{
return "";
}
s = str.re... | //input去掉默认内容还原编辑样式
function g_on_setvalue(obj,value,cname)
{ | random_line_split |
gateway-sia-cachelayer.go | /*
* (C) 2017 David Gore <dvstate@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 required by applicable law ... |
// Sys returns system interface
func (o SiaFileInfo) Sys() interface{} {
return o.FileSys
}
// newSiaCacheLayer creates a new Sia cache layer
func newSiaCacheLayer(siadAddress string, cacheDir string, dbFile string, debug bool) (*SiaCacheLayer, error) {
cache := &SiaCacheLayer{
SiadAddress: siadAddress,
... | {
return o.FileIsDir
} | identifier_body |
gateway-sia-cachelayer.go | /*
* (C) 2017 David Gore <dvstate@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 required by applicable law ... |
}
tmp = os.Getenv("SIA_BACKGROUND_UPLOAD")
if tmp != "" {
i, err := strconv.ParseInt(tmp, 10, 64)
if err == nil {
if i == 0 {
cache.BackgroundUpload = false
} else {
cache.BackgroundUpload = true
}
}
}
}
| {
cache.MaxCacheSizeBytes = i
} | conditional_block |
gateway-sia-cachelayer.go | /*
* (C) 2017 David Gore <dvstate@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 required by applicable law ... | (siaObj string) *SiaServiceError {
cache.debugmsg("SiaCacheLayer.waitTillSiaUploadCompletes")
complete := false
for !complete {
avail, e := cache.isSiaFileAvailable(siaObj)
if e != nil {
return e
}
if avail {
return nil
}
time.Sleep(time.Duration(cache.UploadCheckFreqMs) * time.Millisecond)
}
r... | waitTillSiaUploadCompletes | identifier_name |
gateway-sia-cachelayer.go | /*
* (C) 2017 David Gore <dvstate@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 required by applicable law ... | UploadCheckFreqMs: 3000,
MaxCacheSizeBytes: 10000000000,
CacheTicker: nil,
Db: nil,
DbMutex: &sync.Mutex{},
}
cache.loadSiaEnv()
return cache, nil
}
// Start will start running the Cache Layer
func (cache *SiaCacheLayer) Start() *SiaServiceError {
cache.debugmsg("SiaCache... | SiadAddress: siadAddress,
CacheDir: cacheDir,
DbFile: dbFile,
DebugMode: debug,
ManagerDelaySec: 30, | random_line_split |
basic_unet.py | import os
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import time
import copy
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets, models
from torchsummary import summary
import torch.optim as optim
from torch.optim import lr_schedul... | for param_group in optimizer.param_groups:
print("LR", param_group['lr'])
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
metrics = defaultdict(float)
... | if phase == 'train': | random_line_split |
basic_unet.py | import os
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import time
import copy
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets, models
from torchsummary import summary
import torch.optim as optim
from torch.optim import lr_schedul... |
# statistics
epoch_samples += inputs.size(0)
print_metrics(metrics, epoch_samples, phase)
epoch_loss = metrics['loss'] / epoch_samples
# collect statistics for figure and take lr step
if phase == 'train':
... | loss.backward()
optimizer.step() | conditional_block |
basic_unet.py | import os
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import time
import copy
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets, models
from torchsummary import summary
import torch.optim as optim
from torch.optim import lr_schedul... | (metrics, epoch_samples, phase):
outputs = []
for k in metrics.keys():
outputs.append("{}: {:4f}".format(k, metrics[k] / epoch_samples))
print("{}: {}".format(phase, ", ".join(outputs)))
###########################################################
# Define training
###################... | print_metrics | identifier_name |
basic_unet.py | import os
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import time
import copy
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, datasets, models
from torchsummary import summary
import torch.optim as optim
from torch.optim import lr_schedul... |
###########################################################
# Test if dataset load works
###########################################################
#ds = ISBI_Dataset(tfms = simulation.get_aug_train())
#dl = DataLoader(ds,batch_size=4)
#imgs,masks = next(iter(dl))
#print(imgs.shape, masks.shape)
#print(imgs.dtype, ... | fname = self.fnames[idx]
img = cv2.imread(os.path.join(DATA,TRAIN,fname), cv2.IMREAD_GRAYSCALE)
mask = cv2.imread(os.path.join(DATA,MASKS,fname),cv2.IMREAD_GRAYSCALE)
if self.tfms is not None:
augmented = self.tfms(image=img,mask=mask)
img,mask = augmented['image'],augme... | identifier_body |
shared.go | package commander
import (
"os"
"os/signal"
"strings"
"sync"
"time"
"log"
"encoding/json"
"io/ioutil"
"strconv"
"syscall"
docker "github.com/fsouza/go-dockerclient"
"github.com/litl/galaxy/commander"
"github.com/litl/galaxy/config"
"github.com/litl/galaxy/discovery"
"github.com/litl/galaxy/log"
"gith... | () {
pools, err := configStore.ListPools(env)
if err != nil {
log.Fatalf("ERROR: Could not check pools: %s", err)
}
if strings.TrimSpace(pool) == "" {
log.Fatalf("ERROR: Need a pool. Use '-pool <pool>'. Existing pools are: %s", strings.Join(pools, ","))
}
}
func pullImageAsync(appCfg config.App, errChan ch... | ensurePool | identifier_name |
shared.go | package commander
import (
"os"
"os/signal"
"strings"
"sync"
"time"
"log"
"encoding/json"
"io/ioutil"
"strconv"
"syscall"
docker "github.com/fsouza/go-dockerclient"
"github.com/litl/galaxy/commander"
"github.com/litl/galaxy/config"
"github.com/litl/galaxy/discovery"
"github.com/litl/galaxy/log"
"gith... |
func ensurePool() {
pools, err := configStore.ListPools(env)
if err != nil {
log.Fatalf("ERROR: Could not check pools: %s", err)
}
if strings.TrimSpace(pool) == "" {
log.Fatalf("ERROR: Need a pool. Use '-pool <pool>'. Existing pools are: %s", strings.Join(pools, ","))
}
}
func pullImageAsync(appCfg confi... | {
envs, err := configStore.ListEnvs()
if err != nil {
log.Fatalf("ERROR: Could not check envs: %s", err)
}
if strings.TrimSpace(env) == "" {
log.Fatalf("ERROR: Need an env. Use '-env <env>'. Existing envs are: %s.", strings.Join(envs, ","))
}
} | identifier_body |
shared.go | package commander
import (
"os"
"os/signal"
"strings"
"sync"
"time"
"log"
"encoding/json"
"io/ioutil"
"strconv"
"syscall"
docker "github.com/fsouza/go-dockerclient"
"github.com/litl/galaxy/commander"
"github.com/litl/galaxy/config"
"github.com/litl/galaxy/discovery"
"github.com/litl/galaxy/log"
"gith... | if err != nil {
log.Fatal(err)
}
for _, pool := range envDump.Pools {
_, err := configStore.CreatePool(env, pool)
if err != nil {
log.Println(err)
}
}
for _, appDef := range envDump.Configs {
_, err := configStore.UpdateApp(&appDef, env)
if err != nil {
log.Println(err)
}
}
for _, hostInfo... | err = json.Unmarshal(js, &envDump) | random_line_split |
shared.go | package commander
import (
"os"
"os/signal"
"strings"
"sync"
"time"
"log"
"encoding/json"
"io/ioutil"
"strconv"
"syscall"
docker "github.com/fsouza/go-dockerclient"
"github.com/litl/galaxy/commander"
"github.com/litl/galaxy/config"
"github.com/litl/galaxy/discovery"
"github.com/litl/galaxy/log"
"gith... |
continue
}
startService(appCfg, logOnce)
}
if cmd == "restart" {
err := serviceRuntime.Stop(appCfg)
if err != nil {
log.Errorf("ERROR: Could not stop %s: %s",
appCfg.Version(), err)
if !loop {
return
}
startService(appCfg, logOnce)
continue
}
}
... | {
return
} | conditional_block |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... |
}
}
/// Performs the same function on `self.climate`, filling in `self.year`.
pub fn get_growth_since(&self, last_updated: f64) -> f64 {
return self
.climate
.get_growth_over_time_range(self.year, last_updated);
}
/// Returns the current growth rate (temper... | {
i += 1;
} | conditional_block |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... | board.maintain_creature_minimum();
return board;
}
/// Maintains the creature minimum by adding random creatures until there are at least `self.creature_minimum` creatures.
///
/// # Processing equivalent
/// This function is the equivalent of *Board.pde/maintainCreatureMinimum* wi... | random_line_split | |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... | (&self) -> f64 {
self.climate.get_growth_rate(self.year)
}
/// Returns the current time, i.e. `self.year`.
pub fn get_time(&self) -> f64 {
return self.year;
}
/// Returns a tuple with the width and height of this `Board`.
///
/// Equivalent to `(board.get_board_width(), boa... | get_current_growth_rate | identifier_name |
board.rs | //! The central part of this crate, uses all modules to load and run our world in memory.
//!
//! The `Board` struct is technically all you need to start your world but then you wouldn't be able to see it!
//! Graphics are provided by the [graphics] module; although you could implement your own.
//!
//! TODO: documenta... |
/// Returns `self.creature_id_up_to`
pub fn get_creature_id_up_to(&self) -> usize {
self.creature_id_up_to
}
/// Gets the size of the current population; i.e. how many creatures are currently alive.
pub fn get_population_size(&self) -> usize {
return self.creatures.len();
... | {
self.creature_minimum
} | identifier_body |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... |
/// Receives bytes from the socket stream.
///
/// # System calls
/// - `read`
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
self.fd.read(buf)
}
/// Receives bytes from the socket stream, making use of [scatter input] for the main data.
///
/// # System calls
... | {
let addr = path.try_to::<sockaddr_un>()?;
let socket = {
let (success, fd) = unsafe {
let result = libc::socket(AF_UNIX, SOCK_STREAM, 0);
(result != -1, result)
};
if success {
fd
} else {
r... | identifier_body |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... | (&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.fd.read_vectored(bufs)
}
/// Receives both bytes and ancillary data from the socket stream.
///
/// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, mutable slices of bytes... | recv_vectored | identifier_name |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... |
};
let success = unsafe {
libc::connect(
socket,
&addr as *const _ as *const _,
size_of::<sockaddr_un>() as u32,
)
} != 1;
if !success {
unsafe { return Err(handle_fd_error(socket)) };
}
... | {
return Err(io::Error::last_os_error());
} | conditional_block |
stream.rs | #[cfg(uds_peercred)]
use super::util::get_peer_ucred;
#[cfg(uds_supported)]
use super::util::raw_shutdown;
#[cfg(unix)]
use super::super::{close_by_error, handle_fd_error};
use super::{
imports::*,
util::{
check_ancillary_unsound, enable_passcred, mk_msghdr_r, mk_msghdr_w, raw_get_nonblocking,
r... | /// conn.read_to_string(&mut string_buffer)?;
/// println!("Server answered: {}", string_buffer);
/// # }
/// # Ok(()) }
/// ```
pub struct UdStream {
fd: FdOps,
}
impl UdStream {
/// Connects to a Unix domain socket server at the specified path.
///
/// See [`ToUdSocketPath`] for an example of using va... | /// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new(); | random_line_split |
services.js | angular.module('starter.services', [])
.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText... |
return null;
}
};
})
.factory('listPesonel',function(){
var listData=[
[{src:"img/1200.png",title:"我的卡卷", count:"6张"},
{src:"img/1005.png",title:"积分商城", count:""},
{src:"img/10067.png",title:"我的积分", count:"110积分"},
{src:"img/1008.png",titl... | {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
} | conditional_block |
services.js | angular.module('starter.services', [])
.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText... | remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
})
.factory('listPesonel',function(){
... | all: function() {
return chats;
}, | random_line_split |
olympics.py | '''
olympics.py
A command line program used to query data from the related olympics database.
Code by Cole Weinstein, 21 October 2021
Credits: Jeff Ondich - psycopg2-sample.py
For use in the "olympics" assignment from Carleton's
CS 257 Software Design class, Fall 2021.
'''
import argparse
import co... | query += item + ', '
# Removes the last comma from the query string
query = query[:-2] + '\n'
query += 'FROM '
for item in tables:
query += item + ', '
# Removes the last comma from the query string
query = query[:-2] + '\n'
query += 'WHERE '
for item in ... | where_statements.append('cast(games.year AS TEXT) LIKE cast(\'{games_year}\' AS TEXT)')
if medal:
where_statements.append('medals.medal NOT LIKE \'NA\'')
for item in fields:
| random_line_split |
olympics.py | '''
olympics.py
A command line program used to query data from the related olympics database.
Code by Cole Weinstein, 21 October 2021
Credits: Jeff Ondich - psycopg2-sample.py
For use in the "olympics" assignment from Carleton's
CS 257 Software Design class, Fall 2021.
'''
import argparse
import co... | ():
'''
Gets arguments from command line.
'''
# Help descriptions for each argument and the argparser.
arg_parse_description = '''Finds information about the athletes registered under a specific NOC (National Olympic Committee), the athletes who have participated in a given event, the athle... | get_parsed_arguments | identifier_name |
olympics.py | '''
olympics.py
A command line program used to query data from the related olympics database.
Code by Cole Weinstein, 21 October 2021
Credits: Jeff Ondich - psycopg2-sample.py
For use in the "olympics" assignment from Carleton's
CS 257 Software Design class, Fall 2021.
'''
import argparse
import co... |
def run_golden_query(cursor, event_name='', games_year=0):
event = False
if event_name != '':
event = True
year = False
if games_year != 0:
year = True
query = form_golden_query(event, year)
try:
cursor.execute(query.format(event_name=event_name, games_... | noc = False
if noc_code != '':
noc = True
event = False
if event_name != '':
event = True
year = False
if games_year != 0:
year = True
query = form_variable_query(noc, event, medal, year)
try:
cursor.execute(query.format(noc_code=noc_code, eve... | identifier_body |
olympics.py | '''
olympics.py
A command line program used to query data from the related olympics database.
Code by Cole Weinstein, 21 October 2021
Credits: Jeff Ondich - psycopg2-sample.py
For use in the "olympics" assignment from Carleton's
CS 257 Software Design class, Fall 2021.
'''
import argparse
import co... |
else:
print(field)
print('=' * 30)
cursor_items = []
line_count = 1
for row in cursor:
if len(row) == 2:
if table == 'noc_regions':
string_to_print = row[0] + ' ' + row[1]
elif ... | print(' Events' + ' ' * (54) + 'Sports')
print('=' * 100) | conditional_block |
dbgap.go | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
id.VisaJWTs = append(id.VisaJWTs, string(v.JWT()))
}
return &id, nil
}
| {
return nil, fmt.Errorf("sign org ClaimAffiliationAndRole claim failed: %s", err)
} | conditional_block |
dbgap.go | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (publicKey, selfIssuer string, signer kms.Signer) (*DbGapTranslator, error) {
if len(selfIssuer) == 0 {
return nil, fmt.Errorf("NewDbGapTranslator failed, selfIssuer or signingPrivateKey is empty")
}
jku := strings.TrimSuffix(selfIssuer, "/") + "/.well-known/jwks.json"
t := &DbGapTranslator{
visaIssuer: selfI... | NewDbGapTranslator | identifier_name |
dbgap.go | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
// TranslateToken implements the ga4gh.Translator interface.
func (s *DbGapTranslator) TranslateToken(ctx context.Context, auth string) (*ga4gh.Identity, error) {
if err := ga4gh.VerifyTokenWithKey(s.publicKey, auth); err != nil {
return nil, fmt.Errorf("verifying user token signature: %v", err)
}
userInfo, err ... | {
if len(selfIssuer) == 0 {
return nil, fmt.Errorf("NewDbGapTranslator failed, selfIssuer or signingPrivateKey is empty")
}
jku := strings.TrimSuffix(selfIssuer, "/") + "/.well-known/jwks.json"
t := &DbGapTranslator{
visaIssuer: selfIssuer,
visaJKU: jku,
signer: signer,
}
block, _ := pem.Decode(... | identifier_body |
dbgap.go | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | }
// TranslateToken implements the ga4gh.Translator interface.
func (s *DbGapTranslator) TranslateToken(ctx context.Context, auth string) (*ga4gh.Identity, error) {
if err := ga4gh.VerifyTokenWithKey(s.publicKey, auth); err != nil {
return nil, fmt.Errorf("verifying user token signature: %v", err)
}
userInfo, err... | t.publicKey = pub
return t, nil | random_line_split |
HandView.py | import pygame
import textwrap
import client.Button as Btn
from client.ClickableImage import ClickableImage as ClickImg
from client.CreateDisplay import CreateDisplay
import client.LiverpoolButtons as RuleSetsButtons_LP
import client.HandAndFootButtons as RuleSetsButtons_HF
import client.HandManagement as HandManagement... |
def discardConfirmation(self, confirmed, wrapped_discards):
""" Confirm a user is sure about a discard and then perform it once confirmed."""
discards = []
for element in wrapped_discards:
discards.append(element.card)
if self.discards != discards:
confirmed... | """ gathers selected cards
in order to take action on selected cards (either discarding them or preparing them)
"""
self.selected_list = []
for element in self.hand_info:
if element.status == 1:
self.selected_list.append(element)
return self.selected_l... | identifier_body |
HandView.py | import pygame
import textwrap
import client.Button as Btn
from client.ClickableImage import ClickableImage as ClickImg
from client.CreateDisplay import CreateDisplay
import client.LiverpoolButtons as RuleSetsButtons_LP
import client.HandAndFootButtons as RuleSetsButtons_HF
import client.HandManagement as HandManagement... | self.Meld_Threshold = controller._state.rules.Meld_Threshold
self.deal_size = controller._state.rules.Deal_Size
self.help_text = controller._state.rules.help_text
if ruleset == 'Liverpool':
self.buttons_per_player = self.Meld_Threshold[0][0] + self.Meld_Threshold[0][1]
... | def __init__(self, controller, display, ruleset):
self.controller = controller
self.display = display
self.ruleset = ruleset | random_line_split |
HandView.py | import pygame
import textwrap
import client.Button as Btn
from client.ClickableImage import ClickableImage as ClickImg
from client.CreateDisplay import CreateDisplay
import client.LiverpoolButtons as RuleSetsButtons_LP
import client.HandAndFootButtons as RuleSetsButtons_HF
import client.HandManagement as HandManagement... | (self, controller, display, ruleset):
self.controller = controller
self.display = display
self.ruleset = ruleset
self.Meld_Threshold = controller._state.rules.Meld_Threshold
self.deal_size = controller._state.rules.Deal_Size
self.help_text = controller._state.rules.help_t... | __init__ | identifier_name |
HandView.py | import pygame
import textwrap
import client.Button as Btn
from client.ClickableImage import ClickableImage as ClickImg
from client.CreateDisplay import CreateDisplay
import client.LiverpoolButtons as RuleSetsButtons_LP
import client.HandAndFootButtons as RuleSetsButtons_HF
import client.HandManagement as HandManagement... |
elif self.event.type == pygame.MOUSEMOTION:
self.RuleSetsButtons.MouseHiLight(self, pos)
HandManagement.MouseHiLight(self.hand_info, pos)
elif self.event.type == pygame.KEYDOWN:
if self.controller._state.rules.Buy_Option:
if s... | self.RuleSetsButtons.ClickedButton(self, pos)
for element in self.hand_info:
# cannot select prepared cards, so not included in logic below.
if element.img_clickable.isOver(pos):
if element.status == 1:
element.s... | conditional_block |
ft_cityscapes.py | import datetime
import os
import random
import argparse
import torch
import numpy as np
import torchvision.transforms as transforms
import torchvision.utils as vutils
from tensorboardX import SummaryWriter
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.backends import cud... |
def parse_args():
parser = argparse.ArgumentParser(description='Games Semantic Segmentation FCN8')
parser.add_argument('--gpu', type=str, default='0,1', help='gpu id')
parser.add_argument('--epochs', type=int, default=50, help='number of rpochs to run')
parser.add_argument('--seed', type=int, default=47, help='s... | torch.nn.init.xavier_uniform_(m.weight.data)
# torch.nn.init.xavier_uniform(m.bias.data, 0)
nn.init.constant_(m.bias, 0) | conditional_block |
ft_cityscapes.py | import datetime
import os
import random
import argparse
import torch
import numpy as np
import torchvision.transforms as transforms
import torchvision.utils as vutils
from tensorboardX import SummaryWriter
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.backends import cud... |
def train(train_loader, net, device, criterion, optimizer, epoch, train_args):
net.train()
train_loss = AverageMeter()
curr_iter = (epoch - 1) * len(train_loader)
targets_all, preds_all = [], []
for i, data in enumerate(train_loader):
inputs, targets = data
assert inputs.size()[2:] == targets.size()[1:]... | torch.backends.cudnn.benchmark = True
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1'
device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu")
# # if args.seed:
# random.seed(args.seed)
# np.random.seed(args.seed)
# torch.manual_seed(args.seed)
# # if args.gpu:
# torch.cuda.manual_seed_all(args.s... | identifier_body |
ft_cityscapes.py | import datetime
import os
import random
import argparse
import torch
import numpy as np
import torchvision.transforms as transforms
import torchvision.utils as vutils
from tensorboardX import SummaryWriter
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.backends import cud... | curr_iter = (epoch - 1) * len(train_loader)
targets_all, preds_all = [], []
for i, data in enumerate(train_loader):
inputs, targets = data
assert inputs.size()[2:] == targets.size()[1:]
N = inputs.size(0)
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = net(inp... | net.train()
train_loss = AverageMeter() | random_line_split |
ft_cityscapes.py | import datetime
import os
import random
import argparse
import torch
import numpy as np
import torchvision.transforms as transforms
import torchvision.utils as vutils
from tensorboardX import SummaryWriter
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.backends import cud... | (train_loader, net, device, criterion, optimizer, epoch, train_args):
net.train()
train_loss = AverageMeter()
curr_iter = (epoch - 1) * len(train_loader)
targets_all, preds_all = [], []
for i, data in enumerate(train_loader):
inputs, targets = data
assert inputs.size()[2:] == targets.size()[1:]
N = input... | train | identifier_name |
load_csv.py | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 11:51:49 2019
@author: Christian Post
"""
# TODO: row index as an attribute of Data?
# make iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace(... | elif head and column_names:
# TODO: check if len of column names is compatible
self.columns = list(column_names)
file_data = file_data[1:]
for col in self.columns:
self.data[col] = []
elif not head and column_names:
self.... | self.data[col] = []
| random_line_split |
load_csv.py | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 11:51:49 2019
@author: Christian Post
"""
# TODO: row index as an attribute of Data?
# make iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace(... |
def read_csv(self, filename, head=True, column_names=[],
decimal=',', parse_dates=[], date_parser=None):
# make an array to store the csv data with shape (rows, columns)
if not os.path.isfile(filename):
print(f'Error: "{filename}" does not exist.')
r... | th open(filename, 'w+', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=sep)
if head:
writer.writerow(self.columns)
for i, row in self.iterrows():
str_row = [str(r).replace('.', decimal) for r in row]
writer.writero... | identifier_body |
load_csv.py | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 11:51:49 2019
@author: Christian Post
"""
# TODO: row index as an attribute of Data?
# make iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace(... | else:
for i in range(len(file_data[0])):
self.columns.append(str(i))
self.data[str(i)] = []
for i, row in enumerate(file_data):
for j, col in enumerate(row):
# check if data is boolean
... | lf.columns = list(column_names)
for col in self.columns:
self.data[col] = []
| conditional_block |
load_csv.py | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 11:51:49 2019
@author: Christian Post
"""
# TODO: row index as an attribute of Data?
# make iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace(... | elf, by=None, reverse=False):
'''
sorts the rows
"by" has to be a column name
'''
#temp_data = list(self.iterrows())
temp_data = [list(row) for i, row in self.iterrows()]
#print(temp_data)
if not by or by not in self.columns:
i = 0
... | rt(s | identifier_name |
client.rs | use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use regex::Regex;
use reqwest::IntoUrl;
use rss::Channel;
use select::document::Document;
use select::predicate::Name;
use crate::torrentLib::client::{BasicAuth, TransClient};
use crate::torrentLib::request::{Id, TorrentAction, TorrentAddArgs};
u... |
pub async fn getUserInfo(&self) -> Result<UserInfo> {
let context = self
.get(format!(
"https://u2.dmhy.org/userdetails.php?id={}",
self.uid
))
.await?;
let username = Document::from(context.as_str())
.find(Name("a"))... | {
let mut torrent = self.getWorkingTorrent().await?;
torrent.torrents.sort_by_key(|x| {
(
x.peers_getting_from_us.unwrap_or(0),
x.added_date.unwrap_or(0),
)
});
Ok(torrent.torrents.into_iter().take(5).collect())
} | identifier_body |
client.rs | use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use regex::Regex;
use reqwest::IntoUrl;
use rss::Channel;
use select::document::Document;
use select::predicate::Name;
use crate::torrentLib::client::{BasicAuth, TransClient};
use crate::torrentLib::request::{Id, TorrentAction, TorrentAddArgs};
u... | .find(|x| match x.attr("class") {
Some(x) => x == "outer",
_ => false,
})
.ok_or("parseHtml:parse failed")?;
for _ in 0..timesOfReduce {
outer = outer
.find(Name("tbody"))
.next()
.ok_... | e("td"))
| identifier_name |
client.rs | use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use regex::Regex;
use reqwest::IntoUrl;
use rss::Channel;
use select::document::Document;
use select::predicate::Name;
use crate::torrentLib::client::{BasicAuth, TransClient};
use crate::torrentLib::request::{Id, TorrentAction, TorrentAddArgs};
u... | .get("https://u2.dmhy.org/index.php")
.send()
.await?;
if x.url().path() == "/index.php" {
let context = x.text().await?;
let uid = Document::from(context.as_str())
.find(Name("a"))
.filter(|x| match x.attr("class") {
... | let x = container | random_line_split |
main.py | #!/usr/bin/env python
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import logging
import os.path
import webapp2
import json
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import ... | self._serve_page(failed)
def _serve_page(self, failed=False):
params = {
'failed': failed
}
self.render_template('tip.html', params)
def serve_profile_page(self):
user = self.user
params = {
'auth_id': user.auth_ids[0],
'first_name': user.name,
'last_name': user.last_name,
... | try:
tip.tip(user, tipReceiver, amount)
except:
failed=True
| random_line_split |
main.py | #!/usr/bin/env python
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import logging
import os.path
import webapp2
import json
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import ... |
user_id = user.get_id()
token = self.user_model.create_signup_token(user_id)
verification_url = self.uri_for('verification', type='p', user_id=user_id,
signup_token=token, _full=True)
msg = 'Send an email to user in order to reset their password. \
They will be able to do so by visit... | logging.info('Could not find any user entry for username %s', username)
self._serve_page(not_found=True)
return | conditional_block |
main.py | #!/usr/bin/env python
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import logging
import os.path
import webapp2
import json
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import ... | (self):
password = self.request.get('password')
old_token = self.request.get('t')
if not password or password != self.request.get('confirm_password'):
self.display_message('passwords do not match')
return
user = self.user
user.set_password(password)
user.put()
# remove signup ... | post | identifier_name |
main.py | #!/usr/bin/env python
from google.appengine.ext.webapp import template
from google.appengine.ext import ndb
import logging
import os.path
import webapp2
import json
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import ... |
class VerificationHandler(BaseHandler):
def get(self, *args, **kwargs):
user = None
user_id = kwargs['user_id']
signup_token = kwargs['signup_token']
verification_type = kwargs['type']
# it should be something more concise like
# self.auth.get_user_by_token(user_id, signup_token)
# unf... | def get(self):
self._serve_page()
def post(self):
username = self.request.get('username')
user = self.user_model.get_by_auth_id(username)
if not user:
logging.info('Could not find any user entry for username %s', username)
self._serve_page(not_found=True)
return
user_id = user... | identifier_body |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... |
pub fn get_chunk(&self, pos: Pos, size: Pos) -> MapChunk {
let (x0, y0, z0) = pos;
let (xlen, ylen, zlen) = size;
let mut tiles = Tiles::new();
for x in x0..(x0 + xlen) {
for y in y0..(y0 + ylen) {
for z in z0..(z0 + zlen) {
let ind... | {
let (x, y, z) = pos;
self.tiles = vec![AIR_TILE; (x * y * z) as usize];
self.xlen = x;
self.ylen = y;
self.zlen = z;
} | identifier_body |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... | let zlen = min(CHUNK_TILES_Z, self.zlen - dz * CHUNK_TILES_Z);
let size = (xlen, ylen, zlen);
chunks.push(self.get_chunk(pos, size))
}
}
}
chunks
}
fn get_num_chunks(map_len: PosUnit, chunk_len: PosUnit) -... | let z = dz * CHUNK_TILES_Z;
let pos = (x, y, z);
let xlen = min(CHUNK_TILES_X, self.xlen - dx * CHUNK_TILES_X);
let ylen = min(CHUNK_TILES_Y, self.ylen - dy * CHUNK_TILES_Y); | random_line_split |
tiles.rs | use std::cmp::min;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Write, BufWriter, Error};
use game::base::*;
use io::base::*;
use map::constants::*;
use map::material::*;
pub type Tiles = Vec<Tile>;
pub type PosUnit = i32;
const CHUNK_TILES_X: PosUnit = 8;
const CHUNK_TILES_Y: PosUnit = 8;
const CHUN... | {
pub tiles: Tiles,
pub pos: Pos,
pub xlen: PosUnit,
pub ylen: PosUnit,
pub zlen: PosUnit,
}
pub fn init_map(root: &Path) -> Map {
info!("Initializing map");
let test_path = root.join("static/inc/maps/smol_map_excel.sfm.csv");
let path_str = test_path
.to_str()
... | MapChunk | identifier_name |
rotas.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DrawingManager, NguiMap, NguiMapComponent } from '@ngui/map';
import { Router} from '@angular/router';
import {Subscription} from 'rxjs';
import { ClienteService } from '../../cliente';
import { Rua, Client... |
var cliLatLng = new google.maps.LatLng(parseFloat(cli.latitude), parseFloat(cli.longitude));
if (google.maps.geometry.poly.containsLocation(cliLatLng, this.selectedOverlay) === true) {
cli.checked = true;
//console.log('qtd clientesSelec ****'+this.clientesSelec.length);
... | random_line_split | |
rotas.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DrawingManager, NguiMap, NguiMapComponent } from '@ngui/map';
import { Router} from '@angular/router';
import {Subscription} from 'rxjs';
import { ClienteService } from '../../cliente';
import { Rua, Client... | now: ['1','3']
return this.clientesSelec
.filter(opt => opt.checked)
.map(opt => opt.id)
}
incluirClientesRota(): void {
console.log('Rota selecionada : ' + this.rotaSelecionada.id);
if (typeof this.rotaSelecionada.id === 'undefined') {
swal("ERRO!", "Selecione uma ROTA para incluir o... | dCli() { // right | identifier_name |
rotas.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DrawingManager, NguiMap, NguiMapComponent } from '@ngui/map';
import { Router} from '@angular/router';
import {Subscription} from 'rxjs';
import { ClienteService } from '../../cliente';
import { Rua, Client... | } else {
var cliLatLng = new google.maps.LatLng(parseFloat(cli.latitude), parseFloat(cli.longitude));
if (google.maps.geometry.poly.containsLocation(cliLatLng, this.selectedOverlay) === true) {
cli.checked = true;
//console.log('qtd clientesSelec ****'+this.client... | cli.checked = true;
//console.log('qtd clientesSelec ****'+this.clientesSelec.length);
var encontrado = false;
//laco for para testar no momento de faze varios poligonos no mapa
//nao sera colocado mais de 1x o cliente na lista
for (let client of this.clientesSe... | conditional_block |
main.js | $(document).ready(function() {
// Devices
const mobile = window.matchMedia('(min-width: 0px) and (max-width: 767px)');
const tablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)');
/* Smooth Scroll function */
// Browsers info
let chromeCheck = /Chrome/.test(navigator.u... |
document.addEventListener('scroll', () => {
startForm();
});
/* Toggle contact methods dropdown */
let connectBtn = $('#contact-methods .contact-methods-container h3');
let connectList = $('#contact-methods .contact-methods-container .contact-methods-list');
connectBtn.on('clic... | {
if(startedForm == 0) {
// $('.contact-content-container').html('<div data-tf-widget="zdz53C" data-tf-opacity="100" data-tf-iframe-props="title=Contact Form Submission" data-tf-transitive-search-params data-tf-medium="snippet" style="width:100%;height:600px;"></div>');
// $('.contact... | identifier_body |
main.js | $(document).ready(function() {
// Devices
const mobile = window.matchMedia('(min-width: 0px) and (max-width: 767px)');
const tablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)');
/* Smooth Scroll function */
// Browsers info
let chromeCheck = /Chrome/.test(navigator.u... | () {
if(startedForm == 0) {
// $('.contact-content-container').html('<div data-tf-widget="zdz53C" data-tf-opacity="100" data-tf-iframe-props="title=Contact Form Submission" data-tf-transitive-search-params data-tf-medium="snippet" style="width:100%;height:600px;"></div>');
// $('.cont... | startForm | identifier_name |
main.js | $(document).ready(function() {
// Devices
const mobile = window.matchMedia('(min-width: 0px) and (max-width: 767px)');
const tablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)');
/* Smooth Scroll function */
// Browsers info
let chromeCheck = /Chrome/.test(navigator.u... | connectBtn.on('click', function() {
if ( $(connectList).css('display') === 'none' ) {
$(connectBtn).addClass('connectListToggled');
$(connectList).css('display', 'inline-block');
} else {
$(connectBtn).removeClass('connectListToggled');
$(connect... | random_line_split | |
main.js | $(document).ready(function() {
// Devices
const mobile = window.matchMedia('(min-width: 0px) and (max-width: 767px)');
const tablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)');
/* Smooth Scroll function */
// Browsers info
let chromeCheck = /Chrome/.test(navigator.u... |
if ( clickCounter >= 35 ) { $('.easter-egg-container p').text('I would get bored at this point but go on champ \u{1f64c}'); }
if ( clickCounter >= 50 ) { $('.easter-egg-container p').text('Meh, continue I guess'); }
if ( clickCounter >= 65 ) { $('.easter-egg-container p').text('The person in... | { $('.easter-egg-container p').text('Does this look fun to you?'); } | conditional_block |
finetuning.py | # -*- coding: utf-8 -*-
"""FINETUNING.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qLYSKyTMeUXpD-uNVPwfJKHBFzgTjjHO
**MODULES**
"""
import torch
import torch.nn as nn
from torch.nn import BCEWithLogitsLoss
import torchvision.transforms as tr... |
def forward(self, x, toExtract=False):
x = self.net(x, toExtract)
return x
@torch.no_grad()
def classify(self,images):
self.net.train(False)
_, preds=torch.max(self.forward(images,False), dim=1)
mapped=[]
for pred in preds:
mapped.append(list(self.dic.keys())[list(self.dic.val... | super(iCaRLNet, self).__init__()
self.net = resnet32()
self.n_classes = 0
self.n_known = 0
self.classes_known=[]
self.new_classes=[]
self.dic={}
self.count_per_dic=0
self.loss=BCEWithLogitsLoss() | identifier_body |
finetuning.py | # -*- coding: utf-8 -*-
"""FINETUNING.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qLYSKyTMeUXpD-uNVPwfJKHBFzgTjjHO
**MODULES**
"""
import torch
import torch.nn as nn
from torch.nn import BCEWithLogitsLoss
import torchvision.transforms as tr... |
test_set = iCIFAR100(root='./data',train=False,classes=lista_tot,download=True,transform=transform_test)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=128,shuffle=False, num_workers=2)
icarl.update_representation(train_set)
icarl.n_known = icarl.n_classes
icarl.net.train(False)
total ... | print(f"In test {lista_tot}")
train_set = iCIFAR100(root='./data',train=True,classes=list_classes[s],download=True,transform=transform_train)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=128,shuffle=True, num_workers=2) | random_line_split |
finetuning.py | # -*- coding: utf-8 -*-
"""FINETUNING.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qLYSKyTMeUXpD-uNVPwfJKHBFzgTjjHO
**MODULES**
"""
import torch
import torch.nn as nn
from torch.nn import BCEWithLogitsLoss
import torchvision.transforms as tr... | (self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
... | forward | identifier_name |
finetuning.py | # -*- coding: utf-8 -*-
"""FINETUNING.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qLYSKyTMeUXpD-uNVPwfJKHBFzgTjjHO
**MODULES**
"""
import torch
import torch.nn as nn
from torch.nn import BCEWithLogitsLoss
import torchvision.transforms as tr... |
return index, img, target
def __len__(self):
return len(self.data)
def get_image_class(self, label):
return self.data[np.array(self.targets) == label]
def append(self, images, labels):
self.data = np.concatenate((self.data, images), axis=0)
self.targets = self.targets + labels
class ... | target = self.target_transform(target) | conditional_block |
produce_evaluation.py | from pathlib import Path
import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from string import Template
import pprint
PRETTY_NAMES = {
"model_ac_opf": "Model → ACOPF",
"model": "Model",
"dcac_opf": "DCOPF → ACOPF",
"dc_opf": "DCOPF",
"ac_opf... |
return np.percentile(x, n)
percentile_.__name__ = 'percentile_%s' % n
return percentile_
def statistical_summary(results, filter_by_solved):
group_by = ["opf_method"]
if filter_by_solved:
results = results[results["solved"] == 1]
grouped_results = results.groupby(group_by)
agg_... | entile_(x): | identifier_name |
produce_evaluation.py | from pathlib import Path
import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from string import Template
import pprint
PRETTY_NAMES = {
"model_ac_opf": "Model → ACOPF",
"model": "Model",
"dcac_opf": "DCOPF → ACOPF",
"dc_opf": "DCOPF",
"ac_opf... | ef main(results_file, base_csv=None, take_from_base=None):
pp = pprint.PrettyPrinter(indent=4)
results = pd.read_csv(results_file)
if base_csv is not None:
added_results = pd.read_csv(base_csv)
for method in take_from_base:
method_results = added_results[added_results["opf_metho... | f_results = results[results.opf_method == "ac_opf"]
model_ac_opf_results = results[results.opf_method == "model_ac_opf"]
dcacopf_results = results[results.opf_method == "dcac_opf"]
for scen in acopf_results.scenario_id.unique():
acopf = acopf_results[acopf_results.scenario_id == scen]
modela... | identifier_body |
produce_evaluation.py | from pathlib import Path
import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from string import Template
import pprint
PRETTY_NAMES = {
"model_ac_opf": "Model → ACOPF",
"model": "Model",
"dcac_opf": "DCOPF → ACOPF",
"dc_opf": "DCOPF",
"ac_opf... | parser.add_argument("-d", "--dataset", required=True)
parser.add_argument("--exp_path", required=True, type=Path)
args = parser.parse_args()
if args.dataset == "ACTIVSg200":
eval_200(args.exp_path)
elif args.dataset == "ACTIVSg2000":
eval_2k(args.exp_path)
if __name__ == '__main__':... | parser = ArgumentParser() | random_line_split |
produce_evaluation.py | from pathlib import Path
import pandas as pd
import datetime
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from string import Template
import pprint
PRETTY_NAMES = {
"model_ac_opf": "Model → ACOPF",
"model": "Model",
"dcac_opf": "DCOPF → ACOPF",
"dc_opf": "DCOPF",
"ac_opf... | fig.savefig("./relative_runtimes.svg", bbox_inches='tight')
fig.savefig("./relative_runtimes.pdf", bbox_inches='tight')
fig.savefig("./relative_runtimes.png", dpi=200, bbox_inches='tight')
return fig
def solved_in_n_seconds(n_seconds, results, filter_by_methods=None):
filter_by_methods = filter_by_met... | .set_fontsize(26)
| conditional_block |
main.rs | extern crate nalgebra_glm as glm;
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::{mem, os::raw::c_void, ptr};
mod shader;
mod util;
use glutin::event::{
DeviceEvent,
ElementState::{Pressed, Released},
Event, KeyboardInput,
VirtualKeyCode::{self, *}... |
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn offset<T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
... | {
&val[0] as *const T as *const c_void
} | identifier_body |
main.rs | extern crate nalgebra_glm as glm;
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::{mem, os::raw::c_void, ptr};
mod shader;
mod util;
use glutin::event::{
DeviceEvent,
ElementState::{Pressed, Released},
Event, KeyboardInput,
VirtualKeyCode::{self, *}... |
}
}
// Get a null pointer (equivalent to an offset of 0)
// ptr::null()
// let p = 0 as *const c_void
// == // Modify and complete the function below for the first task
unsafe fn init_vao(vertices: &Vec<f32>, indices: &Vec<u32>, colors: &Vec<f32>) -> u32 {
// Returns the ID of the newly instantiated vertex a... | {
println!("Error message: {}", error);
std::process::exit(1);
} | conditional_block |
main.rs | extern crate nalgebra_glm as glm;
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::{mem, os::raw::c_void, ptr};
mod shader;
mod util;
use glutin::event::{
DeviceEvent,
ElementState::{Pressed, Released},
Event, KeyboardInput,
VirtualKeyCode::{self, *}... | VirtualKeyCode::Right => {
rot_y += rot_step;
},
_ => {}
}
}
}
// Handle mouse movement. delta contains the x and y movement of the mouse since last frame in p... | VirtualKeyCode::Left => {
rot_y -= rot_step;
}, | random_line_split |
main.rs | extern crate nalgebra_glm as glm;
use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::{mem, os::raw::c_void, ptr};
mod shader;
mod util;
use glutin::event::{
DeviceEvent,
ElementState::{Pressed, Released},
Event, KeyboardInput,
VirtualKeyCode::{self, *}... | <T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
// Takes in an arbitraray amount of trinagles from a file
let mut vertices: Vec<f32>;
match File::open(".\\src\\triangles.txt") {
Ok(mut file) =... | offset | identifier_name |
index.js | let url = "/api/posts"; //이동할 url
/*
* 단위페이지: 하단에 previous나 Next page를 누르면 페이지 번호가 10개 묶음으로 바뀜
* ex) 1 2 3 4 5 6 7 8 9 10 : 한 묶음
* 11 12 13 14 15 16 17 18 19 20 : 한 묶음
* */
$(document).ready(function() {
//page번호 세팅 후 게시물 목록 구성
getPagingAndPostsData(url, 0, 0);
//글쓰기 버튼 누르면 모달로 글... | let total_pages = response["totalPages"].toString(); //총 페이지 수
paging(current_page, result_count, result_length, page_number, total_pages);
selectPage(select_page);
}
});
}
//게시물 데이터 모두 가져와 목록 만들기
function getPosts(url, current_page) {
let url_include_page = "";
... | random_line_split | |
index.js | let url = "/api/posts"; //이동할 url
/*
* 단위페이지: 하단에 previous나 Next page를 누르면 페이지 번호가 10개 묶음으로 바뀜
* ex) 1 2 3 4 5 6 7 8 9 10 : 한 묶음
* 11 12 13 14 15 16 17 18 19 20 : 한 묶음
* */
$(document).ready(function() {
//page번호 세팅 후 게시물 목록 구성
getPagingAndPostsData(url, 0, 0);
//글쓰기 버튼 누르면 모달로 글... | (0,10);
let content = response["content"];
if(created_at_date != modified_at_date) {
$("#date").text("수정일");
}
$("#detail-title").text(title);
$("#detail-name").text(name);
$("#detail-createdate").text(modified_at_date);
... | "name"];
let created_at_date = response["createdAt"].substr(0,10);
let modified_at_date = response["modifiedAt"].substr | identifier_body |
index.js | let url = "/api/posts"; //이동할 url
/*
* 단위페이지: 하단에 previous나 Next page를 누르면 페이지 번호가 10개 묶음으로 바뀜
* ex) 1 2 3 4 5 6 7 8 9 10 : 한 묶음
* 11 12 13 14 15 16 17 18 19 20 : 한 묶음
* */
$(document).ready(function() {
//page번호 세팅 후 게시물 목록 구성
getPagingAndPostsData(url, 0, 0);
//글쓰기 버튼 누르면 모달로 글... | <td onclick="event.cancelBubble=true">
<input id="${id}-checkbox" name="check" type="checkbox" value="${id}">
</td>
<th id="${id}">${id}</th>
<td id="${id}-title">${title}</td>
... | `<tr onclick="showDetail('${id}')">
| conditional_block |
index.js | let url = "/api/posts"; //이동할 url
/*
* 단위페이지: 하단에 previous나 Next page를 누르면 페이지 번호가 10개 묶음으로 바뀜
* ex) 1 2 3 4 5 6 7 8 9 10 : 한 묶음
* 11 12 13 14 15 16 17 18 19 20 : 한 묶음
* */
$(document).ready(function() {
//page번호 세팅 후 게시물 목록 구성
getPagingAndPostsData(url, 0, 0);
//글쓰기 버튼 누르면 모달로 글... | identifier_name | ||
tgsrv.go | package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/url"
"strconv"
"strings"
"sort"
"golang.org/x/net/html"
"golang.org/x/net/publicsuffix"
"github.com/azhinu/Telefeed/httputils"
"github.com/azhinu/Telefeed/params"
"github.com/azhinu/Telefeed/vkapi"
"gith... |
case "twitter.com":
parts := strings.Split(urls.Path, "/")
for _, part := range parts {
if part != "" {
findFeed("https://twitrss.me/twitter_user_to_rss/?user="+part, msg, delete, userid)
}
}
case "instagram.com":
parts := strings.Split(urls.Path, "/")
for _, part := range parts {
i... | {
channelName := "@" + parts[len(parts)-1]
m := tgbotapi.NewMessageToChannel(channelName, "Ok")
m.DisableWebPagePreview = true
reply, err := bot.Send(m)
if err != nil {
s := err.Error()
if strings.Contains(s, "orbidden") {
m := tgbotapi.NewMessage(msg.Chat.ID, "Add @telefeedbot as ad... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.