language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,447 | 3.078125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NthDimension.Procedural.Quest.Actions
{
public class GoTo : QuestAction
{
int x;
int y;
public GoTo()
{
this.name = "GoTo";
generateStartingAction();
generateX();
generateY();
}
public GoTo(QuestObject o)
{
this.name = "GoTo";
this.obj = o;
generateStartingAction();
generateX();
generateY();
}
void generateStartingAction()
{
int next_action = rnd1.Next(0, 3);
if (next_action == 0)
{
this.subActions.Add(new None());
}
else
{
if (next_action == 1)
this.subActions.Add(new Learn(obj));
else
this.subActions.Add(new Explore(obj));
}
}
void generateX()
{
this.x = rnd1.Next(0, 100);
}
void generateY()
{
this.y = rnd1.Next(0, 100);
}
override public void DisplaySingleAction(int indent)
{
DrawIndent(indent);
Console.WriteLine("{0} {1}:{2}", this.name, this.x, this.y);
writeSubActions(indent);
}
};
}
|
Python | UTF-8 | 1,203 | 3.515625 | 4 | [] | no_license | import networkx as nx
import matplotlib.pyplot as plt
graph = [('A', 'B'), ('A', 'F'),
('B', 'C'), ('B', 'I'), ('B', 'G'),
('C', 'D'), ('C', 'I'),
('D', 'E'), ('D', 'H'), ('D', 'G'), ('D', 'I'),
('E', 'F'), ('E', 'H'),
('F', 'A'), ('F', 'G'),
('G', 'B'), ('G', 'D'), ('G', 'H'),
('H', 'D'), ('H', 'E')]
class BFS:
def __init__(self, G=None):
self.G = G if G else self.createGraph()
print('networkx: ', list(nx.bfs_tree(self.G, 'A')))
print('bfs_tree: ', self.bfs_tree('A'))
self.draw()
def createGraph(self):
G = nx.Graph()
G.add_edges_from(graph)
return G
def bfs_tree(self, u):
nodes = []
visited = set()
curQueue = [u]
while len(curQueue) > 0:
n = curQueue.pop(0)
nodes.append(n)
visited.add(n)
for v in self.G[n]:
if v not in visited and v not in curQueue:
curQueue.append(v)
return nodes
def draw(self):
nx.draw(self.G, with_labels=True)
plt.show()
if __name__ == '__main__':
BFS()
|
Python | UTF-8 | 736 | 3.078125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
def f(x):
return x - x**6
# In[3]:
x = np.linspace(0,1,100)
plt.plot(x, f(x))
# In[4]:
z = np.sort(np.random.rand(10))
z[0] = 0
z[-1] = 1
h = np.diff(z)
Ih = np.inner(h, f(z[:-1]))
print(Ih)
# In[5]:
plt.plot(x, f(x))
plt.plot(z, 0*z, 'o', ms=12)
# In[6]:
I = 1/2 - 1/7
print(I)
# In[7]:
for i in range(20):
znew = np.zeros(len(z)*2 - 1)
znew[0::2] = z
znew[1::2] = (z[:-1] + z[1:]) / 2
z = znew
h = np.diff(z)
Ih = np.inner(h, f(z[:-1]))
print(I - Ih)
# In[ ]:
len(z)
# In[ ]:
len(znew[2::2])
# In[ ]:
|
Markdown | UTF-8 | 722 | 2.9375 | 3 | [
"MIT"
] | permissive | <h1>PowerTrack Rule Management</h1>
<h2>Ruby Examples</h2>
<p>The following Ruby snippets demonstrate how to perform the following rule-management operations on the PowerTrack Rules API.
<ul>
<li>
Add a rule to a stream</li>
<li>
Delete a rule from a stream</li>
<li>
Retrieve the list of rules for a stream</li>
</ul>
</p>
<p>Each snippet provides examples of what the stream URL should look like for each type described above, and includes specific lines that may be commented or uncommented depending on the type of stream you are using. The files for adding a rule and retrieving a rule will work for PowerTrack 1.0 and 2.0 while there is a separate file for each version of the script to delete a rule.</p>
|
Java | UTF-8 | 1,859 | 2.34375 | 2 | [] | no_license | package com.example.jpa.example1;
import com.example.jpa.example1.base.BaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString(exclude = "addresses")
public class User extends BaseEntity {// implements Auditable<Integer,Long, Instant> {
private String name;
private String email;
@Enumerated(EnumType.STRING)
private SexEnum sex;
private Integer age;
@OneToMany(mappedBy = "user")
@JsonIgnore
private List<UserAddress> addresses;
private Boolean deleted;
// @CreatedBy
// private Integer createUserId;
// @CreatedDate
// private Instant createTime;
// @LastModifiedBy
// private Integer lastModifiedUserId;
// @LastModifiedDate
// private Instant lastModifiedTime;
// @Override
// public Optional<Integer> getCreatedBy() {
// return Optional.ofNullable(this.createUserId);
// }
// @Override
// public void setCreatedBy(Integer createdBy) {
// this.createUserId = createdBy;
// }
// @Override
// public Optional<Instant> getCreatedDate() {
// return Optional.ofNullable(this.createTime);
// }
// @Override
// public void setCreatedDate(Instant creationDate) {
// this.createTime = creationDate;
// }
// @Override
// public Optional<Integer> getLastModifiedBy() {
// return Optional.ofNullable(this.lastModifiedUserId);
// }
// @Override
// public void setLastModifiedBy(Integer lastModifiedBy) {
// this.lastModifiedUserId = lastModifiedBy;
// }
// @Override
// public void setLastModifiedDate(Instant lastModifiedDate) {
// this.lastModifiedTime = lastModifiedDate;
// }
// @Override
// public Optional<Instant> getLastModifiedDate() {
// return Optional.ofNullable(this.lastModifiedTime);
// }
// @Override
// public boolean isNew() {
// return id==null;
// }
}
enum SexEnum {
BOY,GIRL
}
|
PHP | UTF-8 | 630 | 2.671875 | 3 | [] | no_license | <? echo("<?"); ?>xml version="1.0" encoding="utf-8" <? echo("?>"); ?>
<grammar xmlns="http://www.w3.org/2001/06/grammar" xml:lang="ru-ru" version="1.0" mode="voice" root="root" tag-format="semantics/1.0-literals">
<rule id="root">
<one-of>
<?
$ff = fopen("rab.csv", "r") or die("Ошибка!");
while($dr = fgetcsv($ff, 1000, "\n"))
{
# print_r($dr);
$dt = explode(";", $dr[0]);
$dd = explode(",", $dt[1]);
# print_r($dd);
foreach($dd as $ds)
{
?><item><? echo($ds); ?><tag><? echo($dt[0]); ?></tag></item><? echo("\n");
}
}
fclose($ff);
?>
</one-of>
</rule>
</grammar>
|
Java | UTF-8 | 1,154 | 2.59375 | 3 | [] | no_license | package BeansMetier;
public class Document {
private String libelle_doc;
private String descriptionDoc;
private int idProc;
private int idDoc;
public Document(String libelle_doc, String descriptionDoc,int idProc) {
this.libelle_doc = libelle_doc;
this.descriptionDoc = descriptionDoc;
this.idProc= idProc;
}
public Document() {
}
public String getLibelle_doc() {
return libelle_doc;
}
public void setLibelle_doc(String libelle_doc) {
this.libelle_doc = libelle_doc;
}
public String getDescriptionDoc() {
return descriptionDoc;
}
public void setDescriptionDoc(String descriptionDoc) {
this.descriptionDoc = descriptionDoc;
}
public int getIdProc() {
return idProc;
}
public void setIdProc(int idProc) {
this.idProc = idProc;
}
@Override
public String toString() {
return "Document [libelle_doc=" + libelle_doc + ", descriptionDoc=" + descriptionDoc + ", idProc=" + idProc
+ "]";
}
public int getIdDoc() {
return idDoc;
}
public void setIdDoc(int idDoc) {
this.idDoc = idDoc;
}
}
|
C# | UTF-8 | 1,291 | 2.625 | 3 | [
"MIT"
] | permissive | using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infrastructure.EfDataAccess
{
public class UnitofWorkManager<TContext> : IUnitofWork where TContext : DbContext
{
private readonly TContext context;
public UnitofWorkManager(TContext context)
{
this.context = context;
}
public bool Commit(IDbContextTransaction tran = null)
{
var result = context.SaveChanges() > -1;
if (result && tran != null)
tran.Commit();
return result;
}
public async Task<bool> CommitAsync(IDbContextTransaction tran = null)
{
var result = (await context.SaveChangesAsync()) > -1;
if (result && tran != null)
await tran.CommitAsync();
return result;
}
public IDbContextTransaction BeginTransaction()
{
return context.Database.BeginTransaction();
}
public async Task<IDbContextTransaction> BeginTransactionAsync()
{
return await context.Database.BeginTransactionAsync();
}
}
}
|
Python | UTF-8 | 364 | 3.546875 | 4 | [] | no_license | import datetime
ano = int(input('Digite o ano em que nasceu '))
idade = datetime.datetime.today().year - ano
#print(datetime.datetime.today())
dif = abs(idade - 18)
if idade < 18:
print('Você ainda vai se alistar. Falta(m) {} ano(s)'.format(dif))
elif idade == 18 or 17:
print('Está na hora de se alistar')
else:
print('já passou da hora amigao')
|
Java | UTF-8 | 1,312 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package de.bbcdaas.themehandlerweb.domains;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author Robert Illers
*/
@Entity
public class UserEntity implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String loginName;
private String password;
private Integer userRole;
/**
*
* @return
*/
public String getPassword() {
return password;
}
/**
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
*
* @return
*/
public Integer getID() {
return id;
}
/**
*
* @param userID
*/
public void setID(Integer userID) {
this.id = userID;
}
/**
*
* @return
*/
public String getLoginName() {
return loginName;
}
/**
*
* @param loginName
*/
public void setLoginName(String loginName) {
this.loginName = loginName;
}
/**
*
* @return
*/
public Integer getUserRole() {
return userRole;
}
/**
*
* @param userRole
*/
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
}
|
C++ | UTF-8 | 819 | 2.921875 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <Kernel/VM/PhysicalAddress.h>
#include <Kernel/VM/VMObject.h>
class AnonymousVMObject final : public VMObject {
public:
virtual ~AnonymousVMObject() override;
static NonnullRefPtr<AnonymousVMObject> create_with_size(size_t);
static NonnullRefPtr<AnonymousVMObject> create_for_physical_range(PhysicalAddress, size_t);
virtual NonnullRefPtr<VMObject> clone() override;
private:
explicit AnonymousVMObject(size_t);
explicit AnonymousVMObject(const AnonymousVMObject&);
AnonymousVMObject(PhysicalAddress, size_t);
AnonymousVMObject& operator=(const AnonymousVMObject&) = delete;
AnonymousVMObject& operator=(AnonymousVMObject&&) = delete;
AnonymousVMObject(AnonymousVMObject&&) = delete;
virtual bool is_anonymous() const override { return true; }
};
|
Python | UTF-8 | 3,969 | 3.03125 | 3 | [] | no_license | import numpy as np
import scipy.cluster.hierarchy as sch
import scipy.spatial.distance as dist
import json
from scipy.stats import zscore
from collections import Counter
import networkx as nx
from networkx.readwrite import json_graph
def _linkageMatrix2json(Z, labels):
## function to convert linkage matrix to a json dict through DiGraph object
n = Z.shape[0] + 1
G = nx.DiGraph()
for i, row in enumerate(Z):
cluster = int(n + i)
child0 = int(row[0])
if child0 < n:
child0 = labels[child0]
G.add_node(child0, height=0)
child1 = int(row[1])
if child1 < n:
child1 = labels[child1]
G.add_node(child1, height=0)
G.add_edge(cluster, child0)
G.add_edge(cluster, child1)
G.node[cluster]['height'] = row[2]
root = cluster
json_data = json_graph.tree_data(G,root=root)
return json_data
def clustergram(data=None, row_labels=None, col_labels=None,
row_linkage='average', col_linkage='average',
row_pdist='euclidean', col_pdist='euclidean',
standardize=3, log=False, prefix=None):
"""
A function to output json of a clustergram given input data
Parameters:
----------
data: a numpy array or numpy matrix
row_labels: a list of strings corresponding to the rows in data
col_labels: a list of strings corresponding to the columns in data
cluster: boolean variable specifying whether to perform hierarchical clustering (True) or not (False)
row_linkage: linkage method used for rows
col_linkage: linkage method used for columns
options = ['average','single','complete','weighted','centroid','median','ward']
row_pdist: pdist metric used for rows
col_pdist: pdist metric used for columns
options = ['euclidean','minkowski','cityblock','seuclidean','sqeuclidean',
'cosine','correlation','hamming','jaccard','chebyshev','canberra','braycurtis',
'mahalanobis','wminkowski']
standardize: specifying the dimension for standardizing the values in data
options = {1: 'standardize along the columns of data',
2: 'standardize along the rows of data',
3: 'do not standardize the data'}
log: boolean variable specifying whether to perform log transform for the data
Example:
----------
from clustergram import clustergram
clustergram(data=np.random.randn(3,3),row_labels=['a','b','c'],
col_labels=['1','2','3'], row_groups=['A','A','B'],
col_groups=['group1','group1','group2'])
"""
## preprocess data
if log:
data = np.log2(data + 1.0)
if standardize == 1: # Standardize along the columns of data
data = zscore(data, axis=0)
elif standardize == 2: # Standardize along the rows of data
data = zscore(data, axis=1)
## perform hierarchical clustering for rows and cols
## compute pdist for rows:
d1 = dist.pdist(data, metric=row_pdist)
D1 = dist.squareform(d1)
Y1 = sch.linkage(D1, method=row_linkage, metric=row_pdist)
Z1 = sch.dendrogram(Y1, orientation='right')
idx1 = Z1['leaves']
json_data1 = _linkageMatrix2json(Y1, row_labels)
## compute pdist for cols
d2 = dist.pdist(data.T, metric=col_pdist)
D2 = dist.squareform(d2)
Y2 = sch.linkage(D2, method=col_linkage, metric=col_pdist)
Z2 = sch.dendrogram(Y2)
idx2 = Z2['leaves']
json_data2 = _linkageMatrix2json(Y2, col_labels)
## plot heatmap
data_clustered = data
data_clustered = data_clustered[:,idx2]
data_clustered = data_clustered[idx1,:]
if prefix is None:
return data_clustered, json_data1, json_data2
else:
json.dump(data_clustered.tolist(), open(prefix + '_matrix.json', 'wb'))
json.dump(json_data1, open(prefix + '_dendroRow.json', 'wb'))
json.dump(json_data2, open(prefix + '_dendroCol.json', 'wb'))
return
# data, d1, d2 = clustergram(data=np.random.randn(4,3), row_labels=['a','b','c','d'],col_labels=['1','2','3'])
import os
os.chdir('json')
# clustergram(data=np.random.randn(6,3), row_labels=['a','b','c','d','e','f'],col_labels=['1','2','3'],prefix='testRand')
clustergram(data=np.random.randn(100,10), row_labels=map(str,range(100)),col_labels=map(str,range(10)),prefix='testRand')
|
Python | UTF-8 | 288 | 3.65625 | 4 | [] | no_license | def main():
a = int(input("Please enter the starting height of the hailstone: "))
while a !=1:
print("Hail is currently at height",int(a))
if a %2== 0:
a/=2
else:
a = a*3+1
print("Hail stopped at height 1")
main()
|
PHP | UTF-8 | 6,615 | 2.578125 | 3 | [] | no_license | <?php
/**
* AbstractHandler.php
*
* Licensed under the Apache License, Version 2.0 (the "License"),
* see LICENSE for more details: http://www.apache.org/licenses/LICENSE-2.0.
*
* @author Zhang Yi <loeyae@gmail.com>
* @version 2019-02-25 10:21:17
*/
namespace app\services\handler;
use loeye\service\Handler;
/**
* AbstractHandler
*
* @author Zhang Yi <loeyae@gmail.com>
*/
abstract class AbstractHandler extends Handler
{
const ERR_TOKEN_EXPIRED = 13;
const ERR_TOKEN_INVALID = 14;
const SECRUITY_RULE_DENY = 'deny';
const SECRUITY_RULE_ALLOW = 'allow';
static public $OPENER_ERR_MAPPING = [
self::ERR_TOKEN_EXPIRED => LOEYE_REST_STATUS_DENIED,
self::ERR_TOKEN_INVALID => LOEYE_REST_STATUS_DENIED,
];
static public $OPENER_ERR_MSG = [
self::ERR_TOKEN_EXPIRED => 'Token expired',
self::ERR_TOKEN_INVALID => 'Invalid token',
];
protected $securityBundle = 'security';
protected $oauth = false;
protected $access = false;
/**
* initServer
*
* @return void
*/
abstract protected function initServer();
/**
* operate
*
* @param mixed $req request data
*
* @return mixed
*/
abstract protected function operate($req);
/**
* checkIp
*
* @return true
* @throws \loeye\base\Exception
*/
protected function checkIp()
{
$setting = $this->getSecuritySetting();
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == '::1') {
$ip = '127.0.0.1';
}
$denyRule = !empty($setting[self::SECRUITY_RULE_DENY]) ? (array) $setting[self::SECRUITY_RULE_DENY] : [];
$allowRule = !empty($setting[self::SECRUITY_RULE_ALLOW]) ? (array) $setting[self::SECRUITY_RULE_ALLOW] : [];
if ($denyRule) {
foreach ($denyRule as $rule) {
if ($this->inIpRule($ip, $rule)) {
throw new \loeye\base\Exception(parent::$ERR_MSG[parent::ERR_ACCESS_DENIED], parent::ERR_ACCESS_DENIED);
}
}
}
if ($allowRule) {
foreach ($allowRule as $rule) {
if ($this->inIpRule($ip, $rule)) {
return true;
}
}
throw new \loeye\base\Exception(parent::$ERR_MSG[parent::ERR_ACCESS_DENIED], parent::ERR_ACCESS_DENIED);
}
return true;
}
/**
* is ip in rule
*
* @param string $ip ip string
* @param string $rule rule string
*
* @return boolean
*/
protected function inIpRule($ip, $rule)
{
if (is_string($rule)) {
$mlinepos = mb_stripos($rule, '-');
if ($mlinepos !== false) {
$dotrpos = mb_strripos($rule, '.');
if (mb_substr($rule, 0, $dotrpos) == mb_substr($ip, 0, $dotrpos)) {
$endrule = mb_substr($rule, $dotrpos + 1);
$endip = mb_substr($ip, $dotrpos + 1);
$dotpos = mb_stripos($endip, '.');
if ($dotpos !== false) {
$endip = mb_substr($endip, 0, $dotpos);
}
$endrulearr = explode('-', $endrule);
if (count($endrulearr) == 2 && intval($endip) >= intval($endrulearr[0]) && intval($endip) <= intval($endrulearr[1])) {
return true;
}
}
} else {
$rule = rtrim($rule, '.*');
if (mb_substr($ip, 0, mb_strlen($rule)) == $rule) {
return true;
}
}
}
}
/**
* getSecuritySetting
*
* @return array
*/
protected function getSecuritySetting()
{
$moduleKey = \loeye\base\UrlManager::REWRITE_KEY_PREFIX . \loeye\service\Dispatcher::KEY_MODULE;
$serviceKey = \loeye\base\UrlManager::REWRITE_KEY_PREFIX . \loeye\service\Dispatcher::KEY_SERVICE;
if (isset($_REQUEST[$moduleKey])) {
$property = $_REQUEST[$moduleKey];
} else {
$property = $this->config->getPropertyName();
}
$config = $this->bundleConfig($property, $this->securityBundle);
$globalSetting = $config->get('global');
$currentSetting = [];
if (isset($_REQUEST[$serviceKey])) {
$currentSetting = $config->get($_REQUEST[$serviceKey]);
}
return !empty($currentSetting) ? $currentSetting : $globalSetting;
}
/**
* checkMethod
*
* @return void
* @throws \loeye\base\Exception
*/
protected function checkMethod()
{
$method = $this->context->getRequest()->getMethod();
if (strtolower($method) != strtolower($this->method)) {
throw new \loeye\base\Exception(parent::$ERR_MSG[parent::ERR_NOT_ALLOWD_METHOD], parent::ERR_NOT_ALLOWD_METHOD);
}
}
/**
* oauth
*
* @throws \loeye\base\Exception
*/
protected function oauth()
{
return true;
$tokenServer = new \app\services\server\TokenServer($this->config);
$accessToken = $this->queryParameter['access_token'];
$sourceData = $tokenServer->decodeToken($accessToken);
if ($sourceData === false) {
throw new \loeye\base\Exception(self::$OPENER_ERR_MSG[self::ERR_TOKEN_EXPIRED], self::$OPENER_ERR_MAPPING[self::ERR_TOKEN_EXPIRED]);
}
if (!$sourceData) {
throw new \loeye\base\Exception(self::$OPENER_ERR_MSG[self::ERR_TOKEN_INVALID], self::$OPENER_ERR_MAPPING[self::ERR_TOKEN_INVALID]);
}
if (time() - $sourceData['time'] > self::TOKEN_EXPIRE_TIME) {
throw new \loeye\base\Exception(self::$OPENER_ERR_MSG[self::ERR_TOKEN_EXPIRED], self::$OPENER_ERR_MAPPING[self::ERR_TOKEN_EXPIRED]);
}
$certif = $tokenServer->getCertif($sourceData['appid']);
if (md5($certif->getSecret()) != $sourceData['secret'] || $certif->getRefreshTime() != $sourceData['time']) {
throw new \loeye\base\Exception(self::$OPENER_ERR_MSG[self::ERR_TOKEN_INVALID], self::$OPENER_ERR_MAPPING[self::ERR_TOKEN_INVALID]);
}
}
/**
* process
*
* @param array $req request data
*
* @return mixed
*/
protected function process($req)
{
if ($this->access) {
$this->checkIp();
}
$this->checkMethod();
if ($this->oauth) {
$this->oauth();
}
$this->initServer();
return $this->operate($req);
}
}
|
Markdown | UTF-8 | 9,353 | 3.875 | 4 | [] | no_license |
# Python面向对象编程2
---
## 编程语言的特征:
- 继承
- 封装
- 多态
- 如:C++ / Java / Python / Swift / C#
# inheritance 继承 drived 派生
- 概念:
- **继承**是指从已有的类中衍生出新类,新类具有原类的行为,并能扩展新的行为
- **派生**就是从一个已有的衍生(创建)新类,在新类上可以田间新的属性的行为
- 目的:
- **继承**是延续旧类的功能
- **派生**是为了在旧类的基础上添加新的功能
- 作用:
- 用继承派生机制,可以将一些共有功能加在基类中,实现代码的共享
- 在不改变基类的基础上改变原有功能
- 名词:
- 基类(base class)
- 超类(super class)
- 父类(father class)
- 派生类(derived class)
- 子类(child class)
- 说明:
- 任何类都直接或间接继承自object类
- object类是一切类的超类(祖类)不写相当于def Human(object):...
- **类的```__base__```属性**用来记录此类的基类
```Human.__base__```
## 单继承
- 语法:
```class 类名(基类名):
语句块```
- 说明:
- 单继承是派生类由一个基类衍生出来的类
```python
# 此示例示意继承和派生
class Human:
'''此类用来描述人类的共性行为'''
def say(self, that):
print("说:", that)
def walk(self, distance):
print("走了:", distance, "公里")
print("\n-----人类-----")
h1 = Human()
h1.say("今天天气真热")
h1.walk(5)
class Student(Human):
def study(self, subject):
print("正在学习", subject)
print("\n-----学生-----")
s1 = Student()
s1.say("今天天气真热")
s1.walk(6)
s1.study("Python")
class Teacher(Student):
def teach(self, subject):
print("正在教", subject)
print("\n-----教师-----")
t1 = Teacher()
t1.say("明天就星期六啦")
t1.walk(8)
t1.teach("OOP")
t1.study("Piano")
```
-----人类-----
说: 今天天气真热
走了: 5 公里
-----学生-----
说: 今天天气真热
走了: 6 公里
正在学习 Python
-----教师-----
说: 明天就星期六啦
走了: 8 公里
正在教 OOP
正在学习 Piano
## override 覆盖
- 概念:
- 覆盖是指在有继承关系的子类中,子类中实现了与基类同名的方法,在子类实例调用该方法时,实例调用的是子类中的覆盖版本的方法,这种现象叫做覆盖
- 子类对象显式调用基类方法的方式:
- ```基类名.方法名(实例, 实际调用传参)```
```python
# 此示例示意覆盖的用法
class A:
def work(self):
print("A.work()被调用")
class B(A):
'''B类继承自A类'''
def work(self): # 在这里覆盖了A类的work方法
print("B.work()被调用")
pass
b = B()
b.work()
a = A()
a.work()
b.__class__.__base__.work(b)
```
B.work()被调用
A.work()被调用
A.work()被调用
## super 函数
super(type, obj) 返回绑定超类的实例
super( ) 返回绑定超类的实例,等同于```super(__class__, 实例方法的第一个参数)```(必须在方法内调用)
```python
# 此示例示意super函数来调用父类覆盖的用法
class A:
def work(self):
print("A.work()被调用")
class B(A):
'''B类继承自A类'''
def work(self):
print("B.work()被调用")
def super_work(self):
# self.work() # B.work()被调用
# super(B, self).work() # A.work()被调用
# super(__class__, self).work() # 在类内__class__可以直接用
# super().work()
b = B()
super(B, b).work() # 调用超类
b.super_work()
```
A.work()被调用
A.work()被调用
## 显式调用基类的\_\_init\_\_初始化方法:
- 当子类中实现了`__init__`方法时,基类的`__init__`方法并不会被自动调用,此时需要显式调用
```python
# 此实例示意子类对象用super方法显式调用基类__init__方法
class Human:
def __init__(self, n, a):
'''此方法为人的对象添加,姓名和年龄属性'''
self.name = n
self.age = a
def infos(self):
print("姓名:", self.name)
print("年龄:", self.age)
class Student(Human):
def __init__(self, n, a, s):
super().__init__(n, a)
self.score = s
def infos(self):
super().infos()
print("成绩:", self.score)
h1 = Human("小赵", 20)
h1.infos()
s1 = Student('小张', 18, 100)
s1.infos()
```
姓名: 小赵
年龄: 20
姓名: 小张
年龄: 18
成绩: 100
## issubclass 判断派生子类
- 语法:
```issubclass(cls, class_or_tuple)```
判断一个类是否继承自其他类,如果此类cls是class或tuple中的一个派生子类,则返回True,否则返回False
- 查看内建类的属性:`help(__builtins__)`
```python
class A:
pass
class B(A):
pass
class C(B):
pass
print(issubclass(C, B))
print(issubclass(C, A))
print(issubclass(C, object))
print(issubclass(C, (int, str)))
print(issubclass(C, (int, str, A)))
```
True
True
True
False
True
## enclosure 封装
- 封装是指隐藏类的实现细节,让使用者不用关心这些细节,封装的目的是让使用者尽可能少的实例变量(属性)进行操作
- 私有属性:python类中,以双线划线'\_\_'开头,不以双下划线结尾的标识符为私有成员,以类的外部无法直接访问
```python
# 此示例示意使用私有属性和私有方法:
class A:
def __init__(self):
self.__p1 = 100 # __p1为私有属性,在类的外部不可调用
def test(self):
print(self.__p1)
def __m1(self):
print("我是A类的__m1方法")
a = A()
a.test()
a.__m1() # 在类调用不了__m1方法,访问失败
print(a.__p1) # 在类外看不到__p1属性,访问失败
```
100
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-a71fa418a07d> in <module>
12 a = A()
13 a.test()
---> 14 a.__m1()
15 print(a.__p1) # 在类外看不到__p1属性,访问失败
AttributeError: 'A' object has no attribute '__m1'
## ploymorphic 多态
- 字面意思:“多种状态”
- 多态是指在继承/派生关系的类中,调用基类对象的方法,实际能调用子类的覆盖版本方法的现象叫多态
- 说明:
- 多态调用的方法与对象相关,不与类型相关
- Python的全部对象只有“运行时状态(动态)”,没有“C++/Java”里的编译时状态(静态)
```python
class Shape():
def draw(self):
print("Shape.draw被调用")
class Point(Shape):
def draw(self):
print("正在画一个点")
class Circle(Point):
def draw(self):
print("正在画一个圈")
def my_draw(s):
s.draw() # 此处显示出多态的动态
# def my_draw(Circle s) # 在其他语言中,例如这样就是所谓的静态,在编译阶段规定类
# s.draw()
s1 = Circle()
s2 = Point()
my_draw(s1)
my_draw(s2)
```
正在画一个圈
正在画一个点
## 编程语言的特征:
- 继承
- 封装
- 多态
- 如:C++ / Java / Python / Swift / C#
## multiple inheritance 多继承
- 多继承是指一个子类继承自两个或两个以上的基类
- 只有C++和Python支持多继承
- 语法:
`class 类名(基类名1, 基类名2, ...):
语句块`
- 说明:
- 一个子类同时继承自多个父类,父类中的方法可以同时被继承下来
- 如果两个父类中有同名的方法,而在子类中由没有覆盖此方法时,调用结果难以确定
```python
# 此示例示意多继承的语句和使用
class Car:
def run(self, speed):
print("汽车以", speed, "公里/小时的速度行驶")
class Plane:
def fly(self, height):
print("飞机以海拔", height, "的高度飞行")
class PlaneCar(Car, Plane):
pass
p1 = PlaneCar()
p1.fly(10000)
p1.run(50)
```
飞机以海拔 10000 的高度飞行
汽车以 50 公里/小时的速度行驶
- 缺陷:
- 标识符(名字空间冲突问题)
- 谨慎使用
```python
class A:
def m(self):
print("A.m()被调用")
class B:
def m(self):
print("B.m()被调用")
class AB(A, B):
pass
ab = AB()
ab.m()
```
A.m()被调用
## MRO ( Method Resolution Order) 问题
- 类内的\_\_mro\_\_属性用来记录继承方法的查找顺序
```python
# 此示例示意在多继承方法中的方法查找顺序问题
class A:
def m(self):
print("A.m")
class B(A):
def m(self):
print("B.m")
super().m()
class C(A):
def m(self):
print("C.m")
class D(B, C):
def m(self):
print("D.m")
super().m() ##
d = D()
print(D.__mro__)
d.m()
```
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
D.m
B.m
C.m
|
C++ | UTF-8 | 809 | 2.78125 | 3 | [] | no_license | #pragma once
#include "Headers.h"
namespace Compiler
{
class LocalNode
{
int m_dimension;
int m_line;
SymbolCategory m_category;
std::string m_dataType;
std::string m_scope;
std::string m_name;
void* m_value;
LocalNode* m_nextNode;
public:
LocalNode(int line, std::string name, SymbolCategory category, int dimension, std::string dataType, std::string scope);
int GetDimension();
int GetLine();
SymbolCategory GetCategory();
std::string GetLineStr();
std::string GetDimensionStr();
std::string GetCategoryStr();
std::string GetDataType();
std::string GetScope();
std::string GetName();
void SetNextNode(LocalNode* localNode);
LocalNode* GetNextNode();
bool HasNextNode();
};
}; |
C | UTF-8 | 1,675 | 3.78125 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1000 // I initialize a global variable for the length of the array
int main(){
FILE* fp; // I initialize all the other variables starting from the file pointer pointer
char string[MAX]; // the string
int a = 0, c = 0, g = 0, t = 0; // and all the counters for eatch letter
fp = fopen("rna.txt", "r"); // I open the file
if (fp != NULL){ // I verify if the file vas opened correctly
while (!feof(fp)){ // I cycle until the and of the file
fgets(string, MAX, fp); // I put the entire line in the string
for (int i = 0; i < strlen(string); i++){ // I cycle for every letter and update eatch counter for every time it reconize a letter
if (string[i] == 'a'){
a++;
}
if (string[i] == 'c'){
c++;
}
if (string[i] == 'g'){
g++;
}
if (string[i] == 't'){
t++;
}
}
}
printf("\n\nthe numbers of a are: %d", a); // I print every couter for eatch letter
printf("\n\nthe numbers of c are: %d", c);
printf("\n\nthe numbers of g are: %d", g);
printf("\n\nthe numbers of t are: %d\n\n", t);
}
else{
printf("\n\nerror during opening of file\n\n"); // if the file didn't open correctly the program will print this
}
fclose(fp); // I close the file
return 0;
} |
Markdown | UTF-8 | 2,849 | 2.546875 | 3 | [] | no_license | # Trading Journal
**Version 1.0.0**
<div align="center">
<a href="#usage"><img src="https://tlc.thinkorswim.com/center/main/navigation/01/icon/img-release-notes" width="200px"></a>
<a href="#usage"><img src="https://upload.wikimedia.org/wikipedia/commons/8/86/Microsoft_Excel_2013_logo.svg" width="200px"></a>
<br>
</div>
> An Excel spreadsheet to collect and analyze institutionally traded stock and option data.
This spreadsheet was designed to (1) help track your trades throughout the year, (2) keep track of the market conditions surrounding the successes or failures surrounding your trades, and (3) keep record of the personal trading rules you applied to them to test whether they are effective trading rules or not.
## Build
The easiest way to access this Trading Journal is simply to download the `Trading Journal.xlxm` file from the repository. However, to build the workbook yourself, follow the following steps:
1. Create an Excel Macro-Enabled Worksheet (Trading Journal.xlsm)
1. `Developer` > `Visual Basic` > Right-click `VBAProject (Trading Journal.xlms)` > `Insert` > `Module`
1. Copy and paste the code from `functions.vb` into the created `Module1` module.

Access the Scrum project management on [Azure Boards](https://dev.azure.com/ethanromans58/Trading%20Journal/_boards/board/t/Trading%20Journal%20Team/Stories)
Trading rules and formulas can be found in this [Quizlet collection](https://quizlet.com/kingmelchizedek/folders/investing/sets).
## Enable function intellisense
Take the following steps to get function tooltips to top up as you're writing them.
1. Download and open the [`ExcelDna.IntelliSense64.xll`](https://github.com/Excel-DNA/IntelliSense/releases/download/v1.1.0/ExcelDna.IntelliSense64.xll) add-in from the Excel-DNA IntelliSense [Releases](https://github.com/Excel-DNA/IntelliSense/releases) page (under "Assets"). (Note: use `ExcelDna.IntelliSense.xll` if your Excel version is 32-bit. Check at `File` > `Account` > `About Excel`.)
1. Open Excel and navigate to `Developer` > `Excel Add-ins` > `Browse` and select ExcelDna.IntelliSense64.xll from the Windows Explorer.

3. Create a new Worksheet with the name "\_IntelliSense_", and fill in function descriptions as instructed on the [Getting Started](https://github.com/Excel-DNA/IntelliSense/wiki/Getting-Started) page.

(Note: Excel must be restarted before changes made to function descriptions will take effect. Be sure to check out the [VBASamples](https://github.com/Excel-DNA/IntelliSense/tree/master/VBASamples) page if you get stuck.) |
JavaScript | UTF-8 | 886 | 3.25 | 3 | [] | no_license | // import de express
const express = require("express");
// definition de notre app
const app = express();
// le port d'écoute de notre serveur
const PORT = 3000;
// définition d'une route '/', la route par défaut.
// lorsqu'un client effectuera une requête sur ce endpoint
// on lui retournera le texte 'Hello World!' via la callback/
// Cette callback est aussi appellée 'handler function'
app.get("/", (req, res) => {
res.send("Hello World!");
});
// a route with parameters userId & BookId
// GET /users/11/books/13
app.get("/users/:userId/books/:bookId", (req, res) => {
res.send(
`Book with id ${req.params.bookId} for user with id ${req.params.userId}`
);
});
// démarrage de notre serveur sur le port 3000
app.listen(PORT, () => {
//exécution d'un affichage au lacement du serveur.
console.log(`Example app listening at http://localhost:${PORT}`);
});
|
Java | UTF-8 | 505 | 2.8125 | 3 | [] | no_license | package lexer;
public class StringLexer extends BaseLexer {
private String source;
private int curr;
public StringLexer(String source) {
super(5);
this.source = source;
fillBuffer(buffers[0]);
}
protected void fillBuffer(char[] buffer) {
int j=0;
for (; curr<source.length()&&j<k; curr++,j++) {
buffer[j] = source.charAt(curr);
}
if (curr==source.length() && j<k) {
buffer[j]=EOF;
}
}
}
|
C | UTF-8 | 1,214 | 2.984375 | 3 | [] | no_license | /*
* Tapis.c
*
* Created on: Feb 16, 2020
* Author: zahrof
*/
#include "Tapis.h"
void mktapis(size_t maxsize, tapis * t, ft_event_t * cv, char * str){
t->nom=newcopy(str);
t->allocsize= maxsize;
t->begin=0;
t->sz=0;
t->cv=cv;
t->tab=malloc(maxsize*sizeof(paquet));
}
int empty(tapis * t){ return (t->sz==0); }
int full(tapis * t){ return (t->sz ==t->allocsize); }
size_t size(tapis * t){
size_t res = t->sz;
return res;
}
paquet * defiler(char * str, tapis * t){
while(empty(t)){
ft_thread_await(*t->cv);
ft_thread_cooperate();
}
if(full(t))ft_thread_generate(*t->cv);
paquet * p = t->tab[t->begin];
t->sz--;
t->begin=(t->begin+1)%t->allocsize;
return p;
}
void enfiler(char * str, tapis *t, paquet * p){
while(full(t)){
ft_thread_await(*t->cv);
ft_thread_cooperate();
}
if(empty(t)) ft_scheduler_broadcast(*t->cv);
t->tab[(t->begin+t->sz)%t->allocsize]=p;
t->sz++;
}
void printTapis(tapis *t){
if(t->sz==0)printf("Le tapis est vide\n");
if(t->begin==t->sz) printf("%zueme élément du tapis: %s\n",t->begin, t->tab[t->begin]->nom);
else{
for (int i=t->begin; i<t->sz; i++)
printf("%deme élément du tapis: %s\n",i, t->tab[i]->nom);
}
printf("\n");
}
|
Python | UTF-8 | 557 | 4.3125 | 4 | [] | no_license | """
Your task is to make two functions, max and min (maximum and minimum in PHP and Python) that take a(n) array/vector of integers list as input and outputs, respectively, the largest and lowest number in that array/vector.
#Examples
maximun([4,6,2,1,9,63,-134,566]) returns 566
minimun([-52, 56, 30, 29, -54, 0, -110]) returns -110
maximun([5]) returns 5
minimun([42, 54, 65, 87, 0]) returns 0
#Notes
You may consider that there will not be any empty arrays/vectors.
"""
def minimun(arr):
return min(arr)
def maximun(arr):
return max(arr)
|
PHP | UTF-8 | 770 | 2.53125 | 3 | [] | no_license | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Acelle\Model\Language;
class AddJapaneseLanguage extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Language::where('code', 'ja')->exists()) {
$japanese = new Language();
$japanese->name = '日本語 (Japanese)';
$japanese->code = 'ja';
$japanese->region_code = 'ja';
$japanese->status = Language::STATUS_ACTIVE;
$japanese->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
|
Markdown | UTF-8 | 9,689 | 2.875 | 3 | [] | no_license | ---
title: Working for US companies as a resident in Europe
date: 2022-06-05
---
The goal of this blog post is to prepare EU- and EFTA remote prospective employees in talks with US
employers.
With an increase in the number of companies willing to support remote work there are new
complexities around payroll. When everyone is in the same country salaries are negotiated and
comparable apples-to-apples, employers have a single payroll with consolidated insurances, worker
rights and days off, be it calendar holidays or earned days off. Companies are incorporated in a
specific jurisdiction and layer on top their own staff policies for additional benefits. With remote
workers local labor laws and tax regulations are vastly different between countries.
The first thing someone might notice is that quoted salaries are completely different. The US
commonly quotes annual salaries but in many European countries it’s monthly, and of course in local
currency. In Iceland quoted salaries will have significant non-voluntary pension payments which go
from the employer directly to the pension fund. Federal taxes are also transferred directly from the
employer, and on and on.
Sizzling employee benefits like “paid time off”, “401k/pension contributions” and “medical
insurance” can be ambiguous and meaningless for someone that will be working out of a country where
these are mandatory, don’t apply or are simply state provided regardless of employement as is the
case in many European countries, but even within Europe the situation with healthcare and pensions
varies considerably.
## Option 1: US company sets up a branch/subsidiary
A startup is unlikely to set up a branch subsidiary in a country they have no previous experience
with or presence in. They don’t know how to navigate the environment, find accountants and lawyers
that are used to dealing with US companies etc. — and they probably want to focus on their own
business, not the most recent union contracts in a European country. For prospect headcounts of 2+
in a particular branch it starts to make more sense however, and talent often knows other talent so
startups might find it a good tactic to not cast too wide a net, but drill strategically into local
markets, certain cities that are attractive (either because of weather or family welfare).
## Option 2: Direct employment
A US company agrees to employ you in your local state without a local branch and with you being a
direct employee. Companies will have to ensure they comply with local labor law and pay salaries
correctly. This probably requires outsourcing the payroll and employment contract to a specialized
party unless the company hires an accountant with a local presence in the jurisdiction of salary
payment. There is no way to spend an afternoon to “get everything correct” in such a contract
without prior knowledge. There are services that help:
- [Deel](https://www.letsdeel.com/)
- [Pilot](https://pilot.co)
- [Velocity Global](https://velocityglobal.com)
These are services the company opts into at a cost, usually as part of an effort to be “remote
friendly”.
Behind these employments are what the US company considers
[international employment contracts](https://www.letsdeel.com/blog/international-employment-contracts).
Beware of currency risk if you go with this option. You might not want to burden that if your
employer is expecting to negotiate in USD. If you do, consider looking at historical swings and add
some risk buffers to your salary request.
A "twist" on this Option 2 is going through a recruiting platform that becomes the employer of
record:
- [Remote.com](https://remote.com)
## Option 3: Worker incorporates locally and sets up as an independent contractor
The simplest way, I found, was for the employee to set up as an independent contractor with a sole
ownership (limited) company. This way your employer is not really an employer but an importer of
vendor services. You export these services by simply issuing invoices from your company. If you are
engaging a small startup they might be open to adding someone remote in the EU, but that doesn’t
mean they are ready and setup with these services – nor are they likely to have the bandwidth to
deal with setting up a branch. For these companies this is your best bet.
This option will require you to set up a company of your own. The complexity, time and cost of this
step is very different between countries. In the UK and Iceland, two places I have experience with
incorporating, this is simple, fast and relatively cheap. It is advisable to talk to a local
accountant and have them guide you through the setup. This will reduce the risk of you doing
anything wrong.
You should still get setup with a contractor agreement between your company and theirs that
outlines:
- Time length and contract termination clauses
- Your working hours and holidays
- Intellectual property rights of what you produce
The company you deal with should be the one to set this up with the help of a lawyer though you
should always get your own representation to ensure the contract is in your best interest, not just
the companies.
There is nothing stopping a company from also granting a stock option agreement alongside this,
which should then be to you as a person. There may be language in there about “continuous services”.
Clarify that this relates to the contract in question and that the continuous employment covers or
pauses-then-resumes for any paternal leaves or shorter breaks in the contract. You should get
absolute transparency on a
[number of facts](https://www.holloway.com/g/equity-compensation/sections/questions-candidates-can-ask)
if you are interested in receiving a mixed compensation including options.
Is it legal to set up as a full time independent contractor? It depends on your jurisdiction. In
Germany there are provisions in the law to ensure that solo contractors cannot be left outside the
labor law when working for foreign entities, which I guess is meant to bring those companies close
to German law by setting up as branch subsidiaries, which are easier to monitor by unions. In other
countries contracting on behalf of your own company is extremely common and completely legal.
The invoiced amount will need to cover all expenses related to your work. If your remote work
includes offsite or onsite travel to sync with your team you’ll want to make it crystal clear who
covers those irregular expenses. If you rent a desk or office space ensure this cost is covered by
your contract fee. Same goes for any hardware, equipment, both laptops and remote conferencing stuff
and also internet connectivity. In some countries you can make your company support you as an
employee with green commuting stipends and fitness activities. Again, talk to your accountant about
all these claims to ensure you are as tax efficient as other employers.
Some sole proprietors go crazy with expenses, letting it creep into their personal lifestyle. In
Europe it makes a huge difference in total cost since there are VAT refunds and high taxes on
income. With the help of your accountant you should ensure you are fully compliant with local laws.
Another common way independent contractors reduce taxes is to suppress salary income and book a high
annual profit which can be paid out at a lower tax in some European countries. Talk to your
accountant about the industry salaries and what you both feel comfortable with as a salary. Building
up a buffer of cash is fine as long as your salary is not below industry standard.
### Invoiced fee vs. Salary
In many countries there is a significant cost of paying salaries both for employer and employee. In
Iceland there is a [handy calculator](https://virtus.is/reiknivel) that breaks down what is paid
from which party. You enter in what is colloquially known as “the salary” and then you get an
employer cost salary and the final transferred amount. When you negotiate you should be focusing on
the total cost, as you’ll need to bear the “employee cost” of the salary.
Again, your accountant can help you calculate numbers. Point being; negotiating a salary is not the
same as negotiating a contractor fee.
The contractor fee should include
- Your monthly salary base
- \+ payroll taxes …
- \+ health insurance (if applicable) …
- \+ pension or other savings payments …
- \+ office, equipment, hardware …
- \+ accounting and legal services …
- \+ any other business expenses that are considered required for you to do your job
### Bonus: Tips for remote workers
- Set up expectations about national holidays, daily syncs and annual visits.
- Find a space where you are productive and set up with a good conference call setup. I recommend
[Shure MV7-S](https://www.amazon.de/-/en/gp/product/B08G7JN6J7/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&th=1)
and
[SAMD5 desktop stand](https://www.amazon.co.uk/Samson-SAMD5-Desktop-Microphone-Stand/dp/B000MYIIRG).
I find external camera's overkill if you have an LG UltraFine, MacBook Pro M1 or similar built in
camera. Builtin camers are finally getting a bit better.
- Use [Raycast](./tools) shortcuts to quickly log into scheduled meetings and create meeting links
to jump on calls. Live and die by the calendar invites.
- Align on the notification culture - are people expected to answer outside of local work hours?
Probably not. Agree on how to elevate super important things.
- Get your employer company to accept and process an invoice 1-2 business days before the last
business day of the month. That way a wire transfer will clear before you have to pay bills.
|
Java | UTF-8 | 2,189 | 2.5625 | 3 | [] | no_license | package mlab.dataviz.entities;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import mlab.dataviz.util.Formatters;
public class DatastoreTest {
private static SimpleDateFormat dtf = new SimpleDateFormat(Formatters.TIMESTAMP);
private static BQPipelineRunDatastore dbq;
private static BTPipelineRunDatastore dbt;
public static void main(String[] args) throws IOException, GeneralSecurityException {
dbq = new BQPipelineRunDatastore();
dbt = new BTPipelineRunDatastore();
try {
// bq tests
long id = createBQ();
BQPipelineRun vpr = getlast();
System.out.println(vpr.toString());
// bt tests
long id2 = createBT();
updateBT(id2);
BTPipelineRun bt = getBT(id2);
System.out.println(bt.toString());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static long createBQ() throws SQLException {
Calendar c = Calendar.getInstance();
c.set(2017, 01, 15);
Date start = c.getTime();
c.set(2017, 01, 20);
Date end = c.getTime();
BQPipelineRun vpr = new BQPipelineRun.Builder()
.data_start_date(dtf.format(start))
.data_end_date(dtf.format(end))
.type("test")
.status(BQPipelineRun.STATUS_RUNNING)
.build();
return dbq.createBQPipelineRunEntity(vpr);
}
public static long createBT() throws SQLException {
Calendar c = Calendar.getInstance();
c.set(2017, 01, 15);
Date start = c.getTime();
c.set(2017, 01, 20);
Date end = c.getTime();
BTPipelineRun bpr = new BTPipelineRun.Builder()
.run_start_date(dtf.format(start))
.run_end_date(dtf.format(end))
.status(BTPipelineRun.STATUS_RUNNING)
.build();
return dbt.createBTPipelineRunEntity(bpr);
}
public static void updateBT(long id) throws SQLException {
dbt.markBTPipelineRunComplete(id);
}
public static BTPipelineRun getBT(long id) throws SQLException {
return dbt.getBTPipelineRunEntity(id);
}
public static BQPipelineRun getlast() throws SQLException {
return dbq.getLastBQPipelineRun("test");
}
}
|
PHP | UTF-8 | 855 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace Yoast\PHPUnitPolyfills\Tests\Polyfills;
use PHPUnit\Framework\TestCase;
use Yoast\PHPUnitPolyfills\Polyfills\AssertNumericType;
/**
* Availability test for the functions polyfilled by the AssertNumericType trait.
*
* @covers \Yoast\PHPUnitPolyfills\Polyfills\AssertNumericType
*/
class AssertNumericTypeTest extends TestCase {
use AssertNumericType;
/**
* Verify availability of the assertFinite() method.
*
* @return void
*/
public function testAssertFinite() {
$this->assertFinite( 1 );
}
/**
* Verify availability of the assertInfinite() method.
*
* @return void
*/
public function testAssertInfinite() {
$this->assertInfinite( \log( 0 ) );
}
/**
* Verify availability of the assertNan() method.
*
* @return void
*/
public function testAssertNan() {
self::assertNan( \acos( 8 ) );
}
}
|
Python | UTF-8 | 316 | 3.640625 | 4 | [] | no_license | #https://leetcode.com/problems/reverse-words-in-a-string/
"""
Inp: " the sky is blue "
Out: "blue is sky the"
"""
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
ans = s.split()[::-1]
return ' '.join(ans)
|
Markdown | UTF-8 | 475 | 3 | 3 | [
"MIT"
] | permissive | # A* Path Planner
This is the implementation of the popular A* path planner for the grid-map
context
## Conventions
As this is intended for a gridmap, we exploit the following conventions:
1. maps are represented my `numpy.array`s
2. because of this, data is organized in `[row, col]` order, _not_ `[x,y]` order
- [rows, cols] start at the top left and continue to bottom right
3. gridmap cells are floats [0,1], with 0.0 == open space and 1.0 == fully closed obstacle |
C# | UTF-8 | 717 | 3.15625 | 3 | [] | no_license | public static void BindEnumToCombobox<T>(this ComboBox comboBox, T defaultSelection)
{
var list = Enum.GetValues(typeof(T))
.Cast<T>()
.Select(value => new
{
(Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
value
})
.OrderBy(item => item.value.ToString())
.ToList();
comboBox.DataSource = list;
comboBox.DisplayMember = "Description";
comboBox.ValueMember = "value";
foreach (var opts in list)
{
if (opts.value.ToString() == defaultSelection.ToString())
{
comboBox.SelectedItem = opts;
}
}
}
|
Java | UTF-8 | 1,168 | 2.265625 | 2 | [] | no_license | package com.eclubprague.cardashboard.core.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.eclubprague.cardashboard.core.R;
import com.eclubprague.cardashboard.core.model.resources.StringResource;
/**
* Created by Michael on 09.09.2015.
*/
public class TextListItemView extends RelativeLayout {
private TextView textView;
public TextListItemView(Context context) {
super(context);
}
public TextListItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextListItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TextListItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public TextListItemView setText(StringResource textResource) {
if (textView == null) {
textView = (TextView) findViewById(R.id.item_text);
}
textResource.setInView(textView);
return this;
}
}
|
Java | UTF-8 | 1,692 | 3.75 | 4 | [] | no_license | /**
*
*/
package com.example.colllection.workingDemo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author govindaraju.v
*
*/
public class ArrayListWorkingFlow {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(10);
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
nums.add(6);
nums.add(7);
nums.add(8);
nums.add(9);
nums.add(10);
/*
* if addition of new element cannot be fit into the internal transient
* Object[] elementData; // non-private to simplify nested class access
*
* size is increase oldSize * 2/3 +1 ; 10 *( 3/2 ) + 1 = 16 is new size
* array elementData = Arrays.copyOf(elementData, newCapacity);
*
* in Java 7+ size new size is int newCapacity = oldCapacity +
* (oldCapacity >> 1); thus increase capaity by 50 %
*
*/
// insert element in middle start,position
// requires lot of shifting..
nums.add(2, 20);
nums.forEach(ele -> System.out.print(" " + ele));
// similarly deleting from middle,/start poition also shifting happens
nums.remove(2);
/* Bad for Insertion / Deletion.
* if insertion/removal from the middle of the collection ArrayList is
* bad choice System.out.println(""); nums.forEach(ele ->
* System.out.print(" " + ele));
*/
/*
* Good for retrieving : ArrayList is good for retrieval because it implements RandomAccess interface.
* Retrieving the element from position. time is
* always same irrespective of size and position because arrayList
* implements RandomAccess Marker interface.
*/
System.out.println("\n number at positon 1 : " + nums.get(1));
}
}
|
Java | UTF-8 | 366 | 1.96875 | 2 | [] | no_license | package com.example.memberapp.repository;
import com.example.memberapp.model.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MemberRepository extends JpaRepository<Member, Long> {
Member findByEmail(String email);
Member findByUsername(String username);
} |
Markdown | UTF-8 | 12,208 | 3.078125 | 3 | [] | no_license | # 06 | 嗨,别忘了UDP这个小兄弟
如果说 TCP 是网络协议的“大哥”,那么 UDP 可以说是“小兄弟”。这个小兄弟和大哥比,有什么差异呢?
**首先,UDP 是一种“数据报”协议,而 TCP 是一种面向连接的“数据流”协议。**
TCP 可以用日常生活中打电话的场景打比方,前面也多次用到了这样的例子。在这个例子中,拨打号码,接通电话,开始交流,分别对应了 TCP 的三次握手和报文传送。一旦双方的连接建立,那么双方对话时,一定知道彼此是谁。这个时候我们就说,这种对话是有上下文的。
同样的,我们也可以给 UDP 找一个类似的例子,这个例子就是邮寄明信片。在这个例子中,发信方在明信片中填上了接收方的地址和邮编,投递到邮局的邮筒之后,就可以不管了。发信方也可以给这个接收方再邮寄第二张、第三张,甚至是第四张明信片,但是这几张明信片之间是没有任何关系的,**他们的到达顺序也是不保证的**,有可能最后寄出的第四张明信片最先到达接收者的手中,因为没有序号,接收者也不知道这是第四张寄出的明信片;而且,即使接收方没有收到明信片,也没有办法重新邮寄一遍该明信片。
这两个简单的例子,道出了 UDP 和 TCP 之间最大的区别。
**TCP 是一个面向连接的协议,TCP 在 IP 报文的基础上,增加了诸如重传、确认、有序传输、拥塞控制等能力,通信的双方是在一个确定的上下文中工作的。**
而 UDP 则不同,**UDP 没有这样一个确定的上下文**,它是**一个不可靠的通信协议,没有重传和确认,没有有序控制,也没有拥塞控制**。我们可以简单地理解为,**在 IP 报文的基础上,UDP 增加的能力有限**。
**UDP 不保证报文的有效传递,不保证报文的有序,也就是说使用 UDP 的时候,我们需要做好丢包、重传、报文组装等工作。**
既然如此,为什么我们还要使用 UDP 协议呢?
**答案很简单,因为 UDP 比较简单,适合的场景还是比较多的,我们常见的 DNS 服务,SNMP 服务都是基于 UDP 协议的,这些场景对时延、丢包都不是特别敏感。另外多人通信的场景,如聊天室、多人游戏等,也都会使用到 UDP 协议。**
### UDP 编程
UDP 和 TCP 编程非常不同,下面这张图是 UDP 程序设计时的主要过程。
<img src="image\UDP程序设计模型.png" style="zoom:50%;" />
我们看到服务器端创建 UDP 套接字之后,**绑定到本地端口**,调用 **recvfrom 函数等待客户端的报文发**送;客户端创建套接字之后,**调用 sendto 函数往目标地址和端口发送 UDP 报文**,然后客户端和服务器端进入互相应答过程。
recvfrom 和 sendto 是 UDP 用来接收和发送报文的两个主要函数:
~~~c
#include <sys/socket.h>
ssize_t recvfrom(int sockfd, void *buff, size_t nbytes, int flags,
struct sockaddr *from, socklen_t *addrlen);
ssize_t sendto(int sockfd, const void *buff, size_t nbytes, int flags,
const struct sockaddr *to, socklen_t addrlen);
~~~
我们先来看一下 recvfrom 函数。
sockfd、buff 和 nbytes 是前三个参数。sockfd 是本地创建的套接字描述符,buff 指向本地的缓存,nbytes 表示最大接收数据字节。
第四个参数 flags 是和 I/O 相关的参数,这里我们还用不到,设置为 0。
后面两个参数 from 和 addrlen,**实际上是返回对端发送方的地址和端口等信息**,这和 TCP 非常不一样,**TCP 是通过 accept 函数拿到的描述字信息来决定对端的信息**。另外 **UDP 报文每次接收都会获取对端的信息**,也就是说**报文和报文之间是没有上下文**的。
函数的返回值告诉我们实际接收的字节数。
接下来看一下 sendto 函数。
sendto 函数中的前三个参数为 sockfd、buff 和 nbytes。sockfd 是本地创建的套接字描述符,buff 指向发送的缓存,nbytes 表示发送字节数。第四个参数 flags 依旧设置为 0
后面两个参数 to 和 addrlen,表示发送的对端地址和端口等信息。
函数的返回值告诉我们实际接收的字节数。
我们知道, TCP 的发送和接收每次都是在一个上下文中,类似这样的过程:
A 连接上: 接收→发送→接收→发送→…
B 连接上: 接收→发送→接收→发送→ …
而 UDP 的每次接收和发送都是一个独立的上下文,类似这样:
接收 A→发送 A→接收 B→发送 B →接收 C→发送 C→ …
### UDP 服务端例子
我们先来看一个 UDP 服务器端的例子:
~~~c
#include "lib/common.h"
static int count;
static void recvfrom_int(int signo) {
printf("\nreceived %d datagrams\n", count);
exit(0);
}
int main(int argc, char **argv) {
int socket_fd;
socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(SERV_PORT);
bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
socklen_t client_len;
char message[MAXLINE];
count = 0;
signal(SIGINT, recvfrom_int);
struct sockaddr_in client_addr;
client_len = sizeof(client_addr);
for (;;) {
int n = recvfrom(socket_fd, message, MAXLINE, 0, (struct sockaddr *) &client_addr, &client_len);
message[n] = 0;
printf("received %d bytes: %s\n", n, message);
char send_line[MAXLINE];
sprintf(send_line, "Hi, %s", message);
sendto(socket_fd, send_line, strlen(send_line), 0, (struct sockaddr *) &client_addr, client_len);
count++;
}
}
~~~
程序的 12~13 行,首先创建一个套接字,注意这里的套接字类型是“SOCK_DGRAM”,表示的是 UDP 数据报。
15~21 行和 TCP 服务器端类似,绑定数据报套接字到本地的一个端口上。
27 行为该服务器创建了一个信号处理函数,以便在响应“Ctrl+C”退出时,打印出收到的报文总数。
31~42 行是该服务器端的主体,通过调用 recvfrom 函数获取客户端发送的报文,之后我们对收到的报文进行重新改造,加上“Hi”的前缀,再通过 sendto 函数发送给客户端对端。
### UDP 客户端例子
接下来我们再来构建一个对应的 UDP 客户端。在这个例子中,从标准输入中读取输入的字符串后,发送给服务端,并且把服务端经过处理的报文打印到标准输出上。
~~~c
#include "lib/common.h"
# define MAXLINE 4096
int main(int argc, char **argv) {
if (argc != 2) {
error(1, 0, "usage: udpclient <IPaddress>");
}
int socket_fd;
socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
socklen_t server_len = sizeof(server_addr);
struct sockaddr *reply_addr;
reply_addr = malloc(server_len);
char send_line[MAXLINE], recv_line[MAXLINE + 1];
socklen_t len;
int n;
while (fgets(send_line, MAXLINE, stdin) != NULL) {
int i = strlen(send_line);
if (send_line[i - 1] == '\n') {
send_line[i - 1] = 0;
}
printf("now sending %s\n", send_line);
size_t rt = sendto(socket_fd, send_line, strlen(send_line), 0, (struct sockaddr *) &server_addr, server_len);
if (rt < 0) {
error(1, errno, "send failed ");
}
printf("send bytes: %zu \n", rt);
len = 0;
n = recvfrom(socket_fd, recv_line, MAXLINE, 0, reply_addr, &len);
if (n < 0)
error(1, errno, "recvfrom failed");
recv_line[n] = 0;
fputs(recv_line, stdout);
fputs("\n", stdout);
}
exit(0);
}
~~~
10~11 行创建一个类型为“SOCK_DGRAM”的套接字。
13~17 行,初始化目标服务器的地址和端口。
28~51 行为程序主体,从标准输入中读取的字符进行处理后,调用 sendto 函数发送给目标服务器端,然后再次调用 recvfrom 函数接收目标服务器发送过来的新报文,并将其打印到标准输出上。
为了让你更好地理解 UDP 和 TCP 之间的差别,我们模拟一下 UDP 的三种运行场景,你不妨思考一下这三种场景的结果和 TCP 的到底有什么不同?
### 场景一:只运行客户端
如果我们只运行客户端,程序会一直阻塞在 recvfrom 上。
~~~c
$ ./udpclient 127.0.0.1
1
now sending g1
send bytes: 2
<阻塞在这里>
~~~
**还记得 TCP 程序吗?如果不开启服务端,TCP 客户端的 connect 函数会直接返回“Connection refused”报错信息。而在 UDP 程序里,则会一直阻塞在这里。**
### 场景二:先开启服务端,再开启客户端
在这个场景里,我们先开启服务端在端口侦听,然后再开启客户端:
~~~c
$./udpserver
received 2 bytes: g1
received 2 bytes: g2
~~~
~~~c
$./udpclient 127.0.0.1
g1
now sending g1
send bytes: 2
Hi, g1
g2
now sending g2
send bytes: 2
Hi, g2
~~~
我们在客户端一次输入 g1、g2,服务器端在屏幕上打印出收到的字符,并且可以看到,我们的客户端也收到了服务端的回应:“Hi, g1”和“Hi,g2”。
### 场景三: 开启服务端,再一次开启两个客户端
这个实验中,在服务端开启之后,依次开启两个客户端,并发送报文。
服务端:
~~~c
$./udpserver
received 2 bytes: g1
received 2 bytes: g2
received 2 bytes: g3
received 2 bytes: g4
~~~
第一个客户端:
~~~c
$./udpclient 127.0.0.1
now sending g1
send bytes: 2
Hi, g1
g3
now sending g3
send bytes: 2
Hi, g3
~~~
第二个客户端:
~~~c
$./udpclient 127.0.0.1
now sending g2
send bytes: 2
Hi, g2
g4
now sending g4
send bytes: 2
Hi, g4
~~~
我们看到,两个客户端发送的报文,依次都被服务端收到,并且客户端也可以收到服务端处理之后的报文。
如果我们**此时把服务器端进程杀死**,就可以看到**信号函数在进程退出之前,打印出服务器端接收到的报文个数**。
~~~c
$ ./udpserver
received 2 bytes: g1
received 2 bytes: g2
received 2 bytes: g3
received 2 bytes: g4
^C
received 4 datagrams
~~~
之后,我们**再重启服务器端进程**,并使用客户端 1 和客户端 2 继续发送新的报文,我们可以看到和 TCP 非常不同的结果。
以下就是服务器端的输出,**服务器端重启后可以继续收到客户端的报文,这在 TCP 里是不可以的,TCP 断联之后必须重新连接才可以发送报文信息。但是 UDP 报文的”无连接“的特点,可以在 UDP 服务器重启之后,继续进行报文的发送,这就是 UDP 报文“无上下文”的最好说明。**
~~~c
$ ./udpserver
received 2 bytes: g1
received 2 bytes: g2
received 2 bytes: g3
received 2 bytes: g4
^C
received 4 datagrams
$ ./udpserver
received 2 bytes: g5
received 2 bytes: g6
~~~
第一个客户端:
~~~c
$./udpclient 127.0.0.1
now sending g1
send bytes: 2
Hi, g1
g3
now sending g3
send bytes: 2
Hi, g3
g5
now sending g5
send bytes: 2
Hi, g5
~~~
第二个客户端:
~~~c
$./udpclient 127.0.0.1
now sending g2
send bytes: 2
Hi, g2
g4
now sending g4
send bytes: 2
Hi, g4
g6
now sending g6
send bytes: 2
Hi, g6
~~~
### 总结
1. **UDP 是无连接的数据报程序,和 TCP 不同,不需要三次握手建立一条连接。**
2. **UDP 程序通过 recvfrom 和 sendto 函数直接收发数据报报文。**
### 思考题
在第一个场景中,recvfrom 一直处于阻塞状态中,这是非常不合理的,你觉得这种情形应该怎么处理呢?另外,既然 UDP 是请求 - 应答模式的,那么请求中的 UDP 报文最大可以是多大呢? |
Java | UTF-8 | 976 | 2.078125 | 2 | [] | no_license | package project.restapi.service;
import project.restapi.domain.models.api.request.CourseAvailableStudentsRequest;
import project.restapi.domain.models.api.request.StudentAddRequest;
import project.restapi.domain.models.api.request.StudentAddToCourseRequest;
import project.restapi.domain.models.api.response.*;
import java.util.List;
public interface StudentService {
StudentAddResponse add(StudentAddRequest studentAddRequest);
StudentAddToCourseResponse addToCourse(StudentAddToCourseRequest studentAddToCourseRequest);
List<CourseAllOrderedResponse> getAllInCoursesAscByAverageGradeAsc();
Double getTotalAverageGrade(String studentId);
Double getTotalAverageGradeStudentSelf(Long studentId);
StudentProfileResponse getProfileData(String name);
List<StudentAvailableResponse> getStudentsNotInCourse(CourseAvailableStudentsRequest courseAvailableStudentsRequest);
StudentProfileResponse getById(Long id);
void seedStudents();
}
|
C# | UTF-8 | 430 | 3.609375 | 4 | [
"MIT"
] | permissive | using System;
using System.Linq;
class Program
{
static void Main() // 100/100
{
int[] arrays = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
bool same = true;
for (int i = 0; i < arrays.Length - 1; i++)
{
if (arrays[i] == arrays[i + 1])
{
same = false;
}
}
Console.WriteLine(same ? "No" : "Yes");
}
} |
Markdown | UTF-8 | 1,469 | 2.96875 | 3 | [] | no_license | ### 安装方法
1、npm 安装
执行命令:`npm install vuedemo-npm-practice`
2、yarn 安装
执行命令:`yarn add vuedemo-npm-practice`
3、使用 vuedemo-npm-practice.js
### 使用方法
1、组件内部使用
html:
```javascript
<vuedemoNpmPractice :propData="initData"></vuedemoNpmPractice>
```
js:
```javascript
import vuedemoNpmPractice from "vuedemo-npm-practice";
export default {
name: "app",
components: {
vuedemoNpmPractice
},
data() {
return {
initData: "Welcome to Your Vue.js App"
};
}
};
```
2、 main.js 全局安装:
```
import vuedemoNpmPractice from "vuedemo-npm-practice";
Vue.use(vuedemoNpmPractice);
```
然后在其他.vue 文件里面,直接使用组件 <vuedemoNpmPractice/> 即可
3、直接引用打包后的 vuedemo-npm-practice.js
这种方式就不需要 webpack 这类的构建工具,跟 jquery 的方式差不多,可以直接页面引用,使用方法示例如下:
#### HTML 代码 HTML codes
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<vuedemoNpmPractice :propData="propData"></vuedemoNpmPractice>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="./dist/vuedemo-npm-practice.js"></script>
<script>
new Vue({
el: '#app',
data: function() {
return {
propData: '11111111111111111111'
}
},
methods: {
}
})
</script>
</body>
</html>
```
|
PHP | UTF-8 | 418 | 2.96875 | 3 | [] | no_license | <?php
function checkEmail($email){
$regex='/^[A-Za-z0-9]+[A-Za-z0-9]*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)$/';
if(preg_match($regex,$email)){
echo "Valid";
}else{
echo "Invalid";
}
}
checkEmail('a@gmail.com');
echo "<br>";
checkEmail('ab@yahoo.com');
echo "<br>";
checkEmail('abc@hotmail.com');
echo "<br>";
checkEmail('@gmail.com');
echo "<br>";
checkEmail('ab@gmail.');
echo "<br>";
checkEmail('@#abc@gmail.com'); |
PHP | UTF-8 | 552 | 2.640625 | 3 | [] | no_license | <?php
require_once("facebook-sdk/facebook.php");
$config = array(
'appId' => '552609414832678',
'secret' => 'f2c42a5725aa8950eb242c789e47a1d9',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
// get the user id, returns 0 if not loggged in
//$facebook->getUser();
$myMessage = 'Post to Arine';
if ($facebook->api('ArinResidence/feed', 'post', array('message' => $myMessage))) {
echo "Message posted";
} else {
echo "Error occured";
}; |
C# | UTF-8 | 1,586 | 3.90625 | 4 | [] | no_license | using DS.BinaryTree;
using System;
using System.Collections.Generic;
using System.Text;
namespace Algorithms.BinaryTree
{
public class Height
{
public static int MaxDepth(TreeNode root)
{
if (root == null || root.value == -1)
{
return 0;
}
int left = MaxDepth(root.left);
int right = MaxDepth(root.right);
return Math.Max(left, right) + 1;
}
/*
* "The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node."
The term "leaf node" is defined as a node with no children; therefore, root node cannot be a leaf node. There is only one leaf node, "2", and the path is the number of nodes along the path from root to that node, which is 2.
Edit for clarification: in this particular case, where there are 2 nodes, the root node cannot be a leaf node. That was not a general statement. A single node tree's root node would of course also be a leaf node, and the depth would be calculated as 1.
*/
public static int MinDepth(TreeNode root)
{
if (root == null || root.value == -1)
{
return 0;
}
int left = MinDepth(root.left);
int right = MinDepth(root.right);
if (left > 0 && right > 0)
{
return 1 + Math.Min(left, right);
}
else
{
return 1 + Math.Max(left, right);
}
}
}
}
|
Swift | UTF-8 | 663 | 2.890625 | 3 | [] | no_license | //
// CountryListDetailWorker.swift
// CountryList
//
// Created by Z64me on 16/10/2562 BE.
// Copyright (c) 2562 Z64me. All rights reserved.
//
import UIKit
protocol CountryListDetailStoreProtocol {
func getDataCity(sent city_name:String ,_ completion: @escaping (Result<DataCity,Error>) -> Void)
}
class CountryListDetailWorker {
var store: CountryListDetailStoreProtocol
init(store: CountryListDetailStoreProtocol) {
self.store = store
}
// MARK: - Business Logic
func getStore(sent city_name: String,_ completion: @escaping (Result<DataCity,Error>) -> Void) {
store.getDataCity(sent: city_name) {
completion($0)
}
}
}
|
Swift | UTF-8 | 9,107 | 3.03125 | 3 | [] | no_license | //
// ContentView.swift
// SwiftUICode
//
// Created by HuangSenhui on 2020/5/4.
// Copyright © 2020 H.Senhui. All rights reserved.
// 1. 卡片动画:
// 通过isShowCard属性,控制背景的偏移、旋转、缩放、动画时间
import SwiftUI
struct ContentView: View {
@State var isShowCard = false
@State var viewState = CGSize.zero
@State var isShowBottomCard = false
@State var bottomState = CGSize.zero
@State var isShowFull = false
var body: some View {
ZStack {
TitleView()
.blur(radius: isShowCard ? 20 : 0)
.opacity(isShowBottomCard ? 0.4 : 1)
.offset(y: isShowBottomCard ? -200 : 0)
.animation(
Animation
.default
.delay(0.1)
.speed(2) // 速度、重复
)
BackCardView()
.frame(width: isShowBottomCard ? 300 : 340, height: 220)
.background(Color.red)
.cornerRadius(20)
.shadow(radius: 20)
.offset(x: 0, y: isShowCard ? -400 : -40)
.offset(x: viewState.width, y: viewState.height) // 显示卡遍, 响应拖动手势
.offset(y: isShowBottomCard ? -180 : 0)
.scaleEffect(isShowBottomCard ? 1 : 0.9)
.rotationEffect(Angle(degrees: isShowCard ? 0 : 10)) // 旋转
.rotationEffect(Angle(degrees: isShowBottomCard ? -10 : 0))
.rotation3DEffect(Angle(degrees: isShowBottomCard ? 0 : 10), axis: (x: 10.0, y: 0.0, z: 0.0)) // 3D
.blendMode(.hardLight) // 混合模式
.animation(.easeIn(duration: 0.5))
BackCardView()
.frame(width: 340, height: 220)
.background(Color.blue)
.cornerRadius(20)
.shadow(radius: 20)
.offset(x: 0, y: isShowCard ? -200 : -20)
.offset(x: viewState.width, y: viewState.height)
.offset(y: isShowBottomCard ? -140 : 0)
.scaleEffect(isShowBottomCard ? 1 : 0.95)
.rotationEffect(Angle(degrees: isShowCard ? 0 : 5))
.rotationEffect(Angle(degrees: isShowBottomCard ? -5 : 0))
.rotation3DEffect(Angle(degrees: isShowBottomCard ? 0 : 5), axis: (x: 10.0, y: 0.0, z: 0.0))
.blendMode(.hardLight)
.animation(.easeIn(duration: 0.3))
CardView()
.frame(width: isShowBottomCard ? 375 : 340, height: 220)
.background(Color.black)
// .cornerRadius(20)
.clipShape(RoundedRectangle(cornerRadius: isShowBottomCard ? 30 : 20, style: .continuous))
.shadow(radius: 20)
.offset(x: viewState.width, y: viewState.height)
.offset(y: isShowBottomCard ? -100 : 0)
//.blendMode(.hardLight)
.animation(.spring(
response: 0.1,
dampingFraction: 0.6,
blendDuration: 0))
.onTapGesture {
self.isShowBottomCard.toggle()
}
.gesture(
DragGesture().onChanged { value in
if value.translation.height > 10 {
self.isShowBottomCard = false
}
self.viewState = value.translation
self.isShowCard = true
}
.onEnded { value in
self.viewState = .zero
self.isShowCard = false
}
)
// 显示拖拽偏移数据
// Text("\(bottomState.height)").offset(y:-300)
BottomCardView(isShow: $isShowBottomCard)
.offset(x:0, y: isShowBottomCard ? 360 : 1000)
.offset(y: bottomState.height)
.blur(radius: isShowCard ? 20 : 0)
.animation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.8)) // 时间曲线
.gesture(
// 分段滑动
DragGesture().onChanged { value in
self.bottomState = value.translation
if self.isShowFull {
self.bottomState.height += -300
}
if self.bottomState.height < -300 {
self.bottomState.height = -300 // 处理视图边框
}
}
.onEnded { value in
if self.bottomState.height > 50 {
self.isShowBottomCard = false
}
if (self.bottomState.height < -100 && !self.isShowFull) ||
(self.bottomState.height < -250 && self.isShowFull) {
self.bottomState.height = -300
self.isShowFull = true
} else {
self.bottomState = .zero
self.isShowFull = false
}
}
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// 将模块导出,将需要做动画的modifier放到主View
struct CardView: View {
var body: some View {
VStack {
HStack {
VStack(alignment: .leading) {
Text("UI Design")
.font(.title)
.fontWeight(.semibold)
.foregroundColor(Color.white)
Text("SwiftUI 教程")
.foregroundColor(Color.gray)
}
Spacer()
Image("swiftui_logo")
.resizable()
.frame(width:36, height: 36)
.cornerRadius(18)
}
.padding(.horizontal, 20)
.padding(.top, 20)
Spacer()
Image("huoying_post1")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 130, alignment: .top)
}
}
}
struct BackCardView: View {
var body: some View {
VStack {
Spacer()
}
}
}
struct TitleView: View {
var body: some View {
VStack {
HStack {
VStack {
Text("凭证")
.font(.largeTitle)
.fontWeight(.bold)
}
.padding(.leading)
Spacer()
}
Image("huoying_post1")
.resizable()
.frame(width: 370, height: 200)
Spacer()
}
}
}
struct BottomCardView: View {
@Binding var isShow: Bool
var body: some View {
VStack(spacing: 20.0) {
Rectangle()
.frame(width: 40, height: 6)
.cornerRadius(3)
.opacity(0.1)
Text("这是一个信息面板,介绍凭证。这是一个信息面板,介绍凭证。这是一个信息面板,介绍凭证。这是一个信息面板,介绍凭证")
.multilineTextAlignment(.center)
.lineSpacing(4)
.font(.subheadline)
HStack(spacing: 20.0) {
RingView(color1: #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1),
color2: #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1),
width: 88,
height: 88,
percent: 80,
isShow: $isShow)
.animation(Animation.easeInOut.delay(0.3))
VStack(alignment: .leading, spacing: 8.0) {
Text("SwiftUI")
.fontWeight(.bold)
Text("SwiftUI 修炼进度:布局、动画、数据流...")
.font(.footnote)
.foregroundColor(.gray)
.lineSpacing(4)
}
.padding(20)
.background(Color(.tertiarySystemBackground))
.cornerRadius(20)
.shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 10)
}
Spacer()
}
.padding(.top, 8)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity) // 与屏幕等宽
.background(BlurView(style: .systemUltraThinMaterial))
.cornerRadius(30)
.shadow(radius: 20)
}
}
|
TypeScript | UTF-8 | 1,270 | 2.890625 | 3 | [] | no_license | input.onButtonPressed(Button.A, function () {
WantToPass = 1
})
function ResetLight () {
pins.digitalWritePin(DigitalPin.P2, 0)
pins.digitalWritePin(DigitalPin.P1, 0)
pins.digitalWritePin(DigitalPin.P0, 0)
pins.digitalWritePin(DigitalPin.P8, 0)
pins.digitalWritePin(DigitalPin.P16, 0)
}
function Yellow () {
pins.digitalWritePin(DigitalPin.P1, 1)
}
function Pass () {
pins.digitalWritePin(DigitalPin.P16, 1)
}
function Wait () {
pins.digitalWritePin(DigitalPin.P8, 1)
basic.pause(200)
pins.digitalWritePin(DigitalPin.P8, 0)
basic.pause(200)
}
function Green () {
pins.digitalWritePin(DigitalPin.P0, 1)
}
function Red () {
pins.digitalWritePin(DigitalPin.P2, 1)
}
let Pieton = 0
let WantToPass = 0
let Time = 0
basic.forever(function () {
Time += 0.025
ResetLight()
if (Time < 5) {
Red()
if (Pieton == 1) {
if (Time < 4.75) {
Pass()
} else {
Wait()
}
}
} else if (Time < 8) {
Green()
} else if (Time < 10) {
Yellow()
} else {
Time = 0
if (WantToPass == 1) {
Pieton = 1
WantToPass = 0
} else {
Pieton = 0
}
}
})
|
Java | UTF-8 | 283 | 2.609375 | 3 | [] | no_license | package expression.exceptions;
public class UnexpectedVariableNameException extends IllegalExpressionException {
public UnexpectedVariableNameException(String variableName, int pos) {
super("Unexpected variable name \"" + variableName + "\" at position " + pos);
}
}
|
JavaScript | UTF-8 | 868 | 2.9375 | 3 | [] | no_license | class Space {
constructor(args) {
let currArgs = args || {};
this._id = currArgs._id || null;
this.rows = currArgs.rows || new Range({start:1, end: 50});
this.columns = currArgs.columns || new Range({start:1, end: 50});
this.filled = currArgs.filled || [];
}
toObject() {
let obj = Object.assign({}, this)
obj.rows = Object.assign({}, obj.rows )
obj.columns = Object.assign({}, obj.columns )
return obj;
}
static fromObject(obj){
let space = new Space();
space._id = obj._id;
space.rows = new Range(obj.rows);
space.columns = new Range(obj.columns);
space.filled = obj.filled;
return space
}
}
class Range {
constructor(args) {
let currArgs = args || {};
this.start = currArgs.start;
this.end = currArgs.end;
}
}
module.exports = Space; |
Java | UTF-8 | 5,087 | 2.1875 | 2 | [
"BSD-3-Clause"
] | permissive | package gov.nih.nci.evs.restapi.util;
import gov.nih.nci.evs.restapi.bean.*;
import gov.nih.nci.evs.restapi.common.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.*;
public class TreeTraversalUtils {
OWLSPARQLUtils owlSPARQLUtils = null;
HierarchyHelper hh = null;
Vector main_types = null;
String named_graph = null;
public TreeTraversalUtils(Vector parent_child_vec, Vector main_types) {
this.main_types = main_types;
this.hh = new HierarchyHelper(parent_child_vec);
}
public TreeTraversalUtils(String serviceUrl, String named_graph, String username, String password, Vector parent_child_vec, Vector main_types) {
this.main_types = main_types;
this.hh = new HierarchyHelper(parent_child_vec);
this.named_graph = named_graph;
owlSPARQLUtils = new OWLSPARQLUtils(serviceUrl, username, password);
if (named_graph != null) {
owlSPARQLUtils.set_named_graph(named_graph);
}
}
public Vector formatRoles(String label, String code, Vector roles, boolean outbound) {
Vector v = new Vector();
for (int i=0; i<roles.size(); i++) {
String line = (String) roles.elementAt(i);
if (outbound) {
line = label + "|" + code + "|" + line;
} else {
//Stage I Choroidal and Ciliary Body Melanoma AJCC v8|C140660|Disease_Has_Primary_Anatomic_Site
//System.out.println(line);
line = line + "|" + label + "|" + code;
}
line = StringUtils.formatAssociation(line);
v.add(line);
}
return new SortUtils().quickSort(v);
}
public Vector getRolesByCode(String code) {
String label = hh.getLabel(code);
Vector w = new Vector();
boolean outbound = true;
Vector v = owlSPARQLUtils.getInboundRolesByCode(named_graph, code);
v = new ParserUtils().getResponseValues(v);
if (v != null && v.size() > 0) {
v = formatRoles(label, code, v, false);
v = new SortUtils().quickSort(v);
w.addAll(v);
}
v = owlSPARQLUtils.getOutboundRolesByCode(named_graph, code);
v = new ParserUtils().getResponseValues(v);
if (v != null && v.size() > 0) {
v = formatRoles(label, code, v, true);
v = new SortUtils().quickSort(v);
w.addAll(v);
}
return w;
}
public void dumpVector(String indentation, Vector v) {
for (int i=0; i<v.size(); i++) {
String t = (String) v.elementAt(i);
t = indentation + t;
System.out.println(t);
}
}
public String getIndentation(int level) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<level; i++) {
buf.append("\t");
}
return buf.toString();
}
/*
public Vector getLocality(String code) {
Vector w = new Vector();
boolean outbound = true;
Vector v = owlSPARQLUtils.getAssociatedConcepts(named_graph, code, null, outbound);
v = new ParserUtils().getResponseValues(v);
if (v != null && v.size() > 0) {
w.addAll(v);
}
outbound = false;
v = owlSPARQLUtils.getAssociatedConcepts(named_graph, code, null, outbound);
v = new ParserUtils().getResponseValues(v);
if (v != null && v.size() > 0) {
w.addAll(v);
}
return w;
}
*/
public void run(String root) {
run(root, false);
}
public void run(String root, boolean show_locality) {
Stack stack = new Stack();
int level = 0;
stack.push(root + "|" + level);
while (!stack.isEmpty()) {
String line = (String) stack.pop();
Vector u = StringUtils.parseData(line, '|');
String code = (String) u.elementAt(0);
String level_str = (String) u.elementAt(1);
int next_level = Integer.parseInt(level_str);
String label = hh.getLabel(code);
String indentation = getIndentation(next_level);
if (main_types != null && main_types.contains(code)) {
System.out.println(indentation + label + " (" + code + ") (*)");
} else {
System.out.println(indentation + label + " (" + code + ")");
}
if (show_locality) {
Vector v = getRolesByCode(code);
dumpVector(indentation, v);
}
next_level = next_level + 1;
Vector superclass_codes = hh.getSuperclassCodes(code);
if (superclass_codes != null) {
for (int k=0; k<superclass_codes.size(); k++) {
String child_code = (String) superclass_codes.elementAt(k);
stack.push(child_code + "|" + next_level);
}
}
}
}
public static void main(String[] args) {
long ms = System.currentTimeMillis();
String serviceUrl = args[0];
String named_graph = args[1];
String username = args[2];
String password = args[3];
String parent_child_file = args[4];
Vector main_types = null;
String code = args[5];
Vector parent_child_vec = Utils.readFile(parent_child_file);
//Vector main_types = Utils.readFile("main_types.txt");
new TreeTraversalUtils(serviceUrl, named_graph, username, password, parent_child_vec, main_types).run(code, true);
System.out.println("Total run time (ms): " + (System.currentTimeMillis() - ms));
}
}
|
JavaScript | UTF-8 | 459 | 3.390625 | 3 | [
"BSD-2-Clause"
] | permissive | (function () {
'use strict';
let testString = 'this is a test string';
console.log(testString.length);
let strArr = testString.split(' ');
console.log(strArr);
console.log(testString.indexOf('is'));
console.log(testString.lastIndexOf('is'));
console.log(testString.toUpperCase());
console.log(testString.substring(8, 9));
console.log(testString.slice(-6));
console.log(' test '.trim());
})();
|
Rust | UTF-8 | 1,464 | 2.671875 | 3 | [
"MIT"
] | permissive | use std::error;
use clap;
use crate::config;
use super::executer::{Executer, ExecuterOptions};
pub struct Command<'c> {
config: &'c config::command::Config,
name: &'c str,
no_wait: bool,
}
impl<'c> Command<'c> {
pub fn from_args(config: &'c config::command::Config, args: &'c clap::ArgMatches<'c>) -> Self {
trace!("command::run_task::Command::from_args");
Command {
config: config,
name: args.value_of("NAME").unwrap(),
no_wait: args.is_present("NO_WAIT"),
}
}
pub fn new(config: &'c config::command::Config, name: &'c str, no_wait: bool) -> Self {
trace!("command::run_task::Command::new");
Command {
config: config,
name: name,
no_wait: no_wait,
}
}
pub async fn run(&self) -> Result<(), Box<dyn error::Error>> {
trace!("command::run_task::Command::run");
if let Some(run_task_config_group) = self.config.run_task.as_ref() {
for run_task_config in run_task_config_group {
if run_task_config.name != self.name {
continue;
}
let options = ExecuterOptions {
no_wait: self.no_wait,
};
let ecs_run_task_cmd = Executer::from_config(&run_task_config, &options);
ecs_run_task_cmd.run().await?;
}
}
Ok(())
}
}
|
Swift | UTF-8 | 437 | 2.703125 | 3 | [] | no_license | //
// SupportedCurrenciesEntityList.swift
// Currency Conversion App
//
// Created by kitaharamugirou on 2019/05/25.
// Copyright © 2019 kitaharamugirou. All rights reserved.
//
import Foundation
struct SupportedCurrencyViewModel {
var threeLetter : String //e.g. USD
var countryName : String //e.g. United States of America
func displayName() -> String {
return threeLetter + " - " + countryName
}
}
|
PHP | UTF-8 | 18,929 | 3.15625 | 3 | [] | no_license | <?php
/**
* Clase NoticiaSeccion
*
* Esta clase hace referencia a la entidad noticia_seccion de la base de datos
* @author aocampo
* @version 1.0
* @since 2017-05-29 09:35:22
*/
Class NoticiaSeccion
{
//Atributos de la clase
private $conexion;
private $auditoria_tabla;
private $nts_id;
private $nts_id_tipo;
private $nts_nombre;
private $nts_nombre_tipo;
private $nts_activo;
private $nts_activo_tipo;
/**
* Constructor de la clase
*/
public function __construct()
{
}
public function crear()
{
return new NoticiaSeccion();
}
/**
* Metodo para obtener una conexion a la base de datos desde la clase Factory.
* @param string $opcion_bd nombre del tipo de la conexion deseada
* @return $conexion
*/
public function crearBD($opcion_bd)
{
//Instanciamos la clase Factory
$factory=new FactoryBaseDatos();
//Obtenemos la conexion del tipo recibido
$this -> conexion = $factory -> crearBD($opcion_bd);
//retornamos la conexion
return $this -> conexion;
}
/**
* Metodo para hacer consultas a la entidad noticia_seccion
* @param string $where condicion para obtener los resultados
* @param integer $cantidad cantidad de registros deseados
* @param integer $inicio inicio de los registros deseados
* @param string $sql sql personalizado
* @return NoticiaSeccion $objetos arreglo de objetos
*/
public function consultar($where = '', $cantidad = 0, $inicio = 0, $sql = '')
{
//Definimos el arreglo que vamos a devolver
$objetos=array();
//Evaluamos si la cadena SQL viene vacia
$sql=trim($sql);
//Si la cadena SQL esta vacia entonces definimos el SQL predeterminado
if(empty($sql))
{
$sql="SELECT principal.* FROM noticia_seccion AS principal ";
//Si el where no esta vacio entonces lo concatenamos al SQL
$sql.=(!empty($where)) ? $where : "";
}
//Si viene una cantidad definida y un inicio definido entonces ejecuto un metodo del ADOdb
if($cantidad and $inicio)
$rs = $this -> getConexion() -> SelectLimit($sql, $cantidad, $inicio);
else
//Si solo viene la cantidad
if($cantidad)
$rs = $this -> getConexion() -> SelectLimit($sql, $cantidad);
//Sino ejecuto el metodo predeterminado
else
$rs = $this -> getConexion() -> Execute($sql);
//Si es un result set valido entonces hago la asignacion correspondiente
if($rs)
{
//Recorro el result set
while ($row = $rs->FetchRow())
{
$noticia_seccion=$this -> crear();
$noticia_seccion -> setConexion($this -> getConexion());
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_id", $row))
$noticia_seccion -> setNtsId($row["nts_id"]);
else
$noticia_seccion -> setNtsId(null);
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_nombre", $row))
$noticia_seccion -> setNtsNombre($row["nts_nombre"]);
else
$noticia_seccion -> setNtsNombre(null);
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_activo", $row))
$noticia_seccion -> setNtsActivo($row["nts_activo"]);
else
$noticia_seccion -> setNtsActivo(null);
//Asigno una posicion con el objeto asignado
$objetos[]=$noticia_seccion;
}
//Cierro la conexion
$rs -> Close();
}
//Si se genero un error entonces lo imprimo
else
echo $this -> getConexion() -> ErrorMsg()." <strong>SQL: ".$sql."<br/>En la linea ".__LINE__."<br/></strong>";
return $objetos;
}
/**
* Metodo para hacer consultas a la entidad noticia_seccion por codigo de la llave primaria
* @param integer $id codigo de la llave primaria
* @return boolean bandera de ejecucion
*/
public function consultarId($id)
{
$noticia_seccion=false;
$sql="SELECT principal.* FROM noticia_seccion AS principal WHERE nts_id = ".$id;
$rs = $this -> getConexion() -> Execute($sql);
if($rs)
{
while ($row = $rs->FetchRow())
{
$noticia_seccion=$this -> crear();
$noticia_seccion -> setConexion($this -> getConexion());
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_id", $row))
$noticia_seccion -> setNtsId($row["nts_id"]);
else
$noticia_seccion -> setNtsId(null);
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_nombre", $row))
$noticia_seccion -> setNtsNombre($row["nts_nombre"]);
else
$noticia_seccion -> setNtsNombre(null);
//Si el campo viene el recurso entonces lo asigno con el valor. De lo contrario le asigno un null
if(array_key_exists("nts_activo", $row))
$noticia_seccion -> setNtsActivo($row["nts_activo"]);
else
$noticia_seccion -> setNtsActivo(null);
}
$rs -> Close();
return $noticia_seccion;
}
else
echo $this -> getConexion() -> ErrorMsg()." <strong>SQL: ".$sql."<br/>En la linea ".__LINE__."<br/></strong>";
return false;
}
/**
* Metodo para hacer inserciones a la entidad noticia_seccion.
* Esto depende de los valores de los atributos del objeto
*
* @return integer $insert_id registro ingresado
*/
public function insertar()
{
$ultimo_id = 0;
//Defino el arreglo de campos a insertar
$sql_campos_insert=array();
//Defino el arreglo de valores a insertar
$sql_valores_insert=array();
//Descripcion para la auditoria
$descripcion=array();
//Si el campo ha sido asignado y es diferente a null entonces lo agrego al SQL
if(isset($this -> nts_nombre) and !is_null($this -> nts_nombre))
{
//Lo agrego a los campos a insertar
$sql_campos_insert[]="nts_nombre";
//Si el tipo del campo ha sido definido evaluo su tipo
if(isset($this -> nts_nombre_tipo) and !empty($this -> nts_nombre_tipo))
{
switch($this -> nts_nombre_tipo)
{
//Si es de tipo SQL lo agrego tal cual viene porque es una instruccion SQL
case "sql":
$sql_valores_insert[]= $this -> nts_nombre;
break;
}
}
//Sino ha sido definido le agrego comillas para que el insert sea efectivo
else
$sql_valores_insert[]= "'".$this -> nts_nombre."'";
}
//Si el campo ha sido asignado y es diferente a null entonces lo agrego al SQL
if(isset($this -> nts_activo) and !is_null($this -> nts_activo))
{
//Lo agrego a los campos a insertar
$sql_campos_insert[]="nts_activo";
//Si el tipo del campo ha sido definido evaluo su tipo
if(isset($this -> nts_activo_tipo) and !empty($this -> nts_activo_tipo))
{
switch($this -> nts_activo_tipo)
{
//Si es de tipo SQL lo agrego tal cual viene porque es una instruccion SQL
case "sql":
$sql_valores_insert[]= $this -> nts_activo;
break;
}
}
//Sino ha sido definido le agrego comillas para que el insert sea efectivo
else
$sql_valores_insert[]= "'".$this -> nts_activo."'";
}
//Si el arreglo de campos tiene posiciones
if(sizeof($sql_campos_insert))
{
//Armo el SQL para ejecutar el Insert
$sql="INSERT INTO noticia_seccion(".implode($sql_campos_insert, ", ").")
VALUES(".implode($sql_valores_insert, ", ").")";
//Si la ejecucion es exitosa entonces devuelvo el codigo del registro insertado
if($this -> getConexion() -> Execute($sql))
{
//Esto NO funciona para postgreSQL
$ultimo_id=$this -> getConexion() -> Insert_ID();
$this -> setNtsId($ultimo_id);
//Si se encuentra habilitado el log entonces registro la auditoria
if(isset($this -> auditoria_tabla) and $this -> auditoria_tabla and $ultimo_id)
{
//Consulto la informacion que se inserto
$noticia_seccion = $this -> consultarId($ultimo_id);
$descripcion[]="nts_id = ".$noticia_seccion -> getNtsId();
$descripcion[]="nts_nombre = ".$noticia_seccion -> getNtsNombre();
$descripcion[]="nts_activo = ".$noticia_seccion -> getNtsActivo();
/**
* instanciacion de la clase auditoria_tabla para la creacion de un nuevo registro
*/
$objAuditoriaTabla = new AuditoriaTabla();
$objAuditoriaTabla->crearBD("sisgot_adodb");
$objAuditoriaTabla->setAutTabla("noticia_seccion");
$objAuditoriaTabla->setAutTablaId($ultimo_id);
$objAuditoriaTabla->setAutUsuId($objAuditoriaTabla -> obtenerUsuarioActual());
$objAuditoriaTabla->setAutFecha("NOW()", "sql");
$objAuditoriaTabla->setAutTransaccion("INSERTAR");
$objAuditoriaTabla->setAutDescripcionNueva(implode(", ", $descripcion));
$aut_id=$objAuditoriaTabla->insertar();
if(!$aut_id)
{
echo "<b>Error al almacenar informacion en la tabla de auditoria_tabla</b><br/>";
}
}
//return $ultimo_id;
/*
$sql="SELECT MAX(nts_id) AS insert_id FROM noticia_seccion";
$rs = $this -> getConexion() -> Execute($sql);
$row = $rs->FetchRow();
//return $row["insert_id"];
*/
}
//Sino imprimo el error generado
else
{
echo $this -> getConexion() -> ErrorMsg()." <strong>SQL: ".$sql."<br/>En la linea ".__LINE__."<br/></strong>";
$ultimo_id = false;
}
}
return $ultimo_id;
}
/**
* Metodo para hacer actualizaciones a la entidad noticia_seccion.
* @return integer registros afectados
*/
public function actualizar()
{
$registros_afectados = 0;
//Defino el arreglo de los valores a actualizar
$sql_update=array();
//Descripcion para la auditoria
$descripcion=array();
$descripcion_antigua="";//Descripcion antigua
$descripcion_nueva="";//Descripcion nueva
//Si el campo ha sido asignado y es diferente a null entonces lo agrego al SQL
if(isset($this -> nts_id) and !is_null($this -> nts_id))
{
//Lo agrego a los campos a actualizar
if(isset($this -> nts_id_tipo) and !empty($this -> nts_id_tipo))
{
//Si el tipo del campo ha sido definido evaluo su tipo
switch($this -> nts_id_tipo)
{
//Si es de tipo SQL lo agrego tal cual viene porque es una instruccion SQL
case "sql":
$sql_update[]="nts_id = ".$this -> nts_id;
break;
}
}
//Sino ha sido definido le agrego comillas para que el update sea efectivo
else
$sql_update[]="nts_id = '".$this -> nts_id."'";
}
//Si el campo ha sido asignado y es diferente a null entonces lo agrego al SQL
if(isset($this -> nts_nombre) and !is_null($this -> nts_nombre))
{
//Lo agrego a los campos a actualizar
if(isset($this -> nts_nombre_tipo) and !empty($this -> nts_nombre_tipo))
{
//Si el tipo del campo ha sido definido evaluo su tipo
switch($this -> nts_nombre_tipo)
{
//Si es de tipo SQL lo agrego tal cual viene porque es una instruccion SQL
case "sql":
$sql_update[]="nts_nombre = ".$this -> nts_nombre;
break;
}
}
//Sino ha sido definido le agrego comillas para que el update sea efectivo
else
$sql_update[]="nts_nombre = '".$this -> nts_nombre."'";
}
//Si el campo ha sido asignado y es diferente a null entonces lo agrego al SQL
if(isset($this -> nts_activo) and !is_null($this -> nts_activo))
{
//Lo agrego a los campos a actualizar
if(isset($this -> nts_activo_tipo) and !empty($this -> nts_activo_tipo))
{
//Si el tipo del campo ha sido definido evaluo su tipo
switch($this -> nts_activo_tipo)
{
//Si es de tipo SQL lo agrego tal cual viene porque es una instruccion SQL
case "sql":
$sql_update[]="nts_activo = ".$this -> nts_activo;
break;
}
}
//Sino ha sido definido le agrego comillas para que el update sea efectivo
else
$sql_update[]="nts_activo = '".$this -> nts_activo."'";
}
//Si el arreglo tiene posiciones
if(sizeof($sql_update))
{
//Si se encuentra habilitado el log entonces registro la auditoria
if(isset($this -> auditoria_tabla) and $this -> auditoria_tabla)
{
//Consulto la informacion actual antes de la actualizacion
$noticia_seccion = $this -> consultarId($this -> getNtsId());
$descripcion[]="nts_id = ".$noticia_seccion -> getNtsId();
$descripcion[]="nts_nombre = ".$noticia_seccion -> getNtsNombre();
$descripcion[]="nts_activo = ".$noticia_seccion -> getNtsActivo();
$descripcion_antigua = implode(", ", $descripcion);
}
//Armo el SQL para actualizar
$sql="UPDATE noticia_seccion SET ".implode($sql_update, ", ")." WHERE nts_id = ".$this -> getNtsId();
//Si la ejecucion es exitosa entonces devuelvo el numero de registros afectados
if($this -> getConexion() -> Execute($sql))
{
$registros_afectados=$this -> getConexion() -> Affected_Rows();
//Si se actualizaron registros de la tabla
if(isset($this -> auditoria_tabla) and $this -> auditoria_tabla and $registros_afectados)
{
//Consulto la informacion que se registro luego de la actualizacion
$descripcion=array();
$noticia_seccion = $this -> consultarId($this -> getNtsId());
$descripcion[]="nts_id = ".$noticia_seccion -> getNtsId();
$descripcion[]="nts_nombre = ".$noticia_seccion -> getNtsNombre();
$descripcion[]="nts_activo = ".$noticia_seccion -> getNtsActivo();
$descripcion_nueva = implode(", ", $descripcion);
/**
* instanciacion de la clase auditoria_tabla para la creacion de un nuevo registro
*/
$objAuditoriaTabla = new AuditoriaTabla();
$objAuditoriaTabla->crearBD("sisgot_adodb");
$objAuditoriaTabla->setAutTabla("noticia_seccion");
$objAuditoriaTabla->setAutTablaId($this -> getNtsId());
$objAuditoriaTabla->setAutUsuId($objAuditoriaTabla -> obtenerUsuarioActual());
$objAuditoriaTabla->setAutFecha("NOW()", "sql");
$objAuditoriaTabla->setAutDescripcionAntigua($descripcion_antigua);
$objAuditoriaTabla->setAutDescripcionNueva($descripcion_nueva);
$objAuditoriaTabla->setAutTransaccion("ACTUALIZAR");
$aut_id=$objAuditoriaTabla->insertar();
if(!$aut_id)
{
echo "<b>Error al almacenar informacion en la tabla de auditoria_tabla</b><br/>";
}
}
//return $registros_afectados;
}
//Sino imprimo el mensaje de error
else
{
echo $this -> getConexion() -> ErrorMsg()." <strong>SQL: ".$sql."<br/>En la linea ".__LINE__."<br/></strong>";
$registros_afectados = false;
}
}
return $registros_afectados;
}
/**
* Metodo para hacer eliminaciones a la entidad noticia_seccion.
* @return integer registros borrados
*/
public function eliminar()
{
$descripcion=array(); //array para almacenar la informacion de la entidad
//Concateno el where para eliminar los registros de la entidad
$sql="DELETE FROM noticia_seccion WHERE nts_id = ".$this -> getNtsId();
if(isset($this -> auditoria_tabla) and $this -> auditoria_tabla)
{
//Consulto la informacion que se registro luego de la actualizacion
$noticia_seccion = $this -> consultarId($this -> getNtsId());
$descripcion[]="nts_id = ".$noticia_seccion -> getNtsId();
$descripcion[]="nts_nombre = ".$noticia_seccion -> getNtsNombre();
$descripcion[]="nts_activo = ".$noticia_seccion -> getNtsActivo();
$descripcion_antigua = implode(", ", $descripcion);
}
//Si la ejecucion es exitosa entonces devuelvo el numero de registros borrados
if($this -> getConexion() -> Execute($sql))
{
$registros_eliminados=$this -> getConexion() -> Affected_Rows();
//Si se pudo eliminar el registro entonces registro la auditoria sobre la tabla
if(isset($this -> auditoria_tabla) and $this -> auditoria_tabla and $registros_eliminados)
{
/**
* instanciacion de la clase auditoria_tabla para la eliminacion de un registro
*/
$objAuditoriaTabla = new AuditoriaTabla();
$objAuditoriaTabla->crearBD("sisgot_adodb");
$objAuditoriaTabla->setAutTabla("noticia_seccion");
$objAuditoriaTabla->setAutTablaId($this -> getNtsId());
$objAuditoriaTabla->setAutUsuId($objAuditoriaTabla -> obtenerUsuarioActual());
$objAuditoriaTabla->setAutFecha("NOW()", "sql");
$objAuditoriaTabla->setAutDescripcionAntigua($descripcion_antigua);
$objAuditoriaTabla->setAutDescripcionNueva("");
$objAuditoriaTabla->setAutTransaccion("ELIMINAR");
$aut_id=$objAuditoriaTabla->insertar();
if(!$aut_id)
{
echo "<b>Error al almacenar informacion en la tabla de auditoria_tabla</b><br/>";
}
}
return $registros_eliminados;
}
//Sino imprimo el mensaje de error
else
echo $this -> getConexion() -> ErrorMsg()." <strong>SQL: ".$sql."<br/>En la linea ".__LINE__."<br/></strong>";
return 0;
}
/**
* Metodo para asignar el valor al atributo nts_id.
* @param string $valor valor para el atributo nts_id
* @param string $tipo tipo de valor que llevara el campo (sql)
*/
public function setNtsId($valor, $tipo = "")
{
$this -> nts_id = $valor;
if(!empty($tipo))
{
$this -> nts_id_tipo = $tipo;
}
}
/**
* Metodo para obtener el valor del atributo nts_id.
* @return valor
*/
public function getNtsId()
{
return $this -> nts_id;
}
/**
* Metodo para asignar el valor al atributo nts_nombre.
* @param string $valor valor para el atributo nts_nombre
* @param string $tipo tipo de valor que llevara el campo (sql)
*/
public function setNtsNombre($valor, $tipo = "")
{
$this -> nts_nombre = $valor;
if(!empty($tipo))
{
$this -> nts_nombre_tipo = $tipo;
}
}
/**
* Metodo para obtener el valor del atributo nts_nombre.
* @return valor
*/
public function getNtsNombre()
{
return $this -> nts_nombre;
}
/**
* Metodo para asignar el valor al atributo nts_activo.
* @param string $valor valor para el atributo nts_activo
* @param string $tipo tipo de valor que llevara el campo (sql)
*/
public function setNtsActivo($valor, $tipo = "")
{
$this -> nts_activo = $valor;
if(!empty($tipo))
{
$this -> nts_activo_tipo = $tipo;
}
}
/**
* Metodo para obtener el valor del atributo nts_activo.
* @return valor
*/
public function getNtsActivo()
{
return $this -> nts_activo;
}
/**
* Metodo para asignar el valor al atributo auditoria_tabla.
* @param bool $valor valor para el atributo auditoria_tabla
*/
public function setAuditoriaTabla($valor)
{
$this -> auditoria_tabla = $valor;
}
/**
* Metodo para obtener el valor del atributo auditoria_tabla.
* @return valor
*/
public function getAuditoriaTabla()
{
return $this -> auditoria_tabla;
}
/**
* Metodo para asignar el valor al atributo conexion.
* @param string $valor valor para el atributo conexion
*/
public function setConexion($valor)
{
$this -> conexion = $valor;
}
/**
* Metodo para obtener el valor del atributo conexion.
* @return valor
*/
public function getConexion()
{
return $this -> conexion;
}
}
?> |
Ruby | UTF-8 | 413 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | class << Time
# MIN = Time.at(0) # 1969-12-31 00:00:00 UTC
MIN = Time.at(-30610224000) # 1000-01-01 00:00:00 UTC
MAX = Time.at(253402300799) # 9999-12-31 23:59:59 UTC
def random(options = {}, m = Propr::Random)
min = (options[:min] || MIN).to_f
max = (options[:max] || MAX).to_f
m.bind(Float.random(options.merge(min: min, max: max))) do |ms|
m.unit(at(ms))
end
end
end
|
Python | UTF-8 | 3,053 | 2.6875 | 3 | [] | no_license | # encoding=utf-8
"""
Created on 16:47 2017/3/17
@author: Jindong Wang
"""
from sklearn.pipeline import Pipeline
from sklearn import preprocessing
import numpy as np
from sklearn.pipeline import FeatureUnion
import pandas as pd
def gene_feature(data_pd):
# numeric columns
col_binary = ['holiday', 'workingday']
index_binary = np.asarray([(col in col_binary) for col in data_pd.columns], dtype=bool)
# cate columns
col_cate = ['season', 'weather']
index_cate = np.asarray([(col in col_cate) for col in data_pd.columns], dtype=bool)
# numeric columns
col_num = ['temp', 'atemp', 'humidity', 'windspeed']
index_num = np.asarray([(col in col_num) for col in data_pd.columns], dtype=bool)
# normal value
col_normal = ['month', 'day', 'hour']
normal_num = np.asarray([(col in col_normal) for col in data_pd.columns], dtype=bool)
feature_trans_list = [
('binary_value', Pipeline(steps=[
('select', preprocessing.FunctionTransformer(lambda x: x[:, index_binary])),
('transform', preprocessing.OneHotEncoder())
])),
('cate_value', Pipeline(steps=[
('select', preprocessing.FunctionTransformer(lambda x: x[:, index_cate])),
('transform', preprocessing.OneHotEncoder())
])),
('numeric_value', Pipeline(steps=[
('select', preprocessing.FunctionTransformer(lambda x: x[:, index_num])),
('transform', preprocessing.StandardScaler(with_mean=0))
])),
('normal_value', Pipeline(steps=[
('select', preprocessing.FunctionTransformer(lambda x: x[:, normal_num]))
]))
]
feature_union = FeatureUnion(feature_trans_list)
feature_set = feature_union.fit_transform(data_pd).toarray()
return feature_set
def process_rawdata():
data_train = pd.read_csv('../data/train.csv')
data_test = pd.read_csv('../data/test.csv')
data_train['month'] = data_train['datetime'].apply(lambda x: int(x.split('-')[1]))
data_train['day'] = data_train['datetime'].apply(lambda x: int(x.split('-')[2].split(' ')[0]))
data_train['hour'] = data_train['datetime'].apply(lambda x: int(x.split(' ')[1].split(':')[0]))
data_test['month'] = data_test['datetime'].apply(lambda x: int(x.split('-')[1]))
data_test['day'] = data_test['datetime'].apply(lambda x: int(x.split('-')[2].split(' ')[0]))
data_test['hour'] = data_test['datetime'].apply(lambda x: int(x.split(' ')[1].split(':')[0]))
y = data_train['count'].values
X = gene_feature(data_train.drop(['datetime', 'casual', 'registered', 'count'], axis=1))
label_col = np.asarray(data_train['count'].values)
label_col = label_col.reshape((len(label_col), 1))
X = np.hstack((X, label_col))
np.savetxt('../result/train.csv', X, fmt='%.4f', delimiter=',')
data_pred = pd.DataFrame(data=data_test['datetime'].values, columns=['datetime'])
X_test = gene_feature(data_test.drop('datetime', axis=1))
np.savetxt('../result/test.csv', X_test, fmt='%.4f', delimiter=',')
|
Markdown | UTF-8 | 1,924 | 2.859375 | 3 | [] | no_license | A team of six developers are developing a Ruby on Rails application and their source code is being hosted on the company's own GitLab server. The application will be hosted on Heroku. They have set up a GitLab pipeline for rails (a GitLab runner), which includes three stages:
- build
- test
- deploy
In the build stage, the code is checked whether it meets the current coding standards and that there aren't any errors when compiling. The second phase tests the application in many different ways, by doing security tests on the application, security tests on the packages, unit tests etc. The third step deploys the application to Heroku depending on the target environment.
They currently have two Heroku applications / environments. One for testing (test environment) and one for production. They also have three permanent branches on GitLab, a test branch, a staging branch and a master branch. When a commit is merged into the test branch and pushed to the versioning control server, the test pipeline is automatically run and the change is deployed to the Heroku test environment (if the pipeline succeeds). When a new feature or a bug fix is developed, a new branch is created for this. When the job on that is done, it is tested in the test environment, a merge request to the staging branch is created, the request is reviewed by some of the other developers on the team, and when the review passes, the branch is merged into the staging branch. Unlike the test branch, a merge to the staging branch does not cause an automatic deployment to the production environment. When the production deployment is needed, a merge request from staging to the master branch is created. When the branch is merged, a production pipeline starts, and if all succeeds, the production environment is updated with the changes in the master branch. The master branch should always have the same status as the production environment. |
Java | UTF-8 | 277 | 2.265625 | 2 | [] | no_license | package com.demoFunction.command.receiver;
/**
* 命令模式_具体执行者
*
* @author popkidorc
*
*/
public class MyCommandSaveReceiver {
private int count = 0;
public void count() {
count++;
System.out.println("==count==" + count);
}
}
|
Python | UTF-8 | 3,869 | 4.34375 | 4 | [] | no_license | # -*- coding: UTF-8 -*-
class SingleNode(object):
"""单链表节点"""
def __init__(self, item):
# elem存放数据元素
self.elem = item
# next存放下一个节点的标识
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self, node=None):
# 初始化单链表,默认值为None,便于创建空链表
self.__head = node
def is_empty(self):
"""判断单链表是否为空"""
return self.__head is None
def length(self):
"""返回链表长度"""
# 游标cur 刚开始和 __head一样,都指向链表中的第一个节点
cur = self.__head
count = 0
# 需要考虑空链表的情况
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
# 需要考虑空链表的情况
while cur is not None:
print(cur.elem, end=" ")
cur = cur.next
print("") # 换行
def add(self, item):
"""在链表头部添加元素,头插法。时间复杂度O(1)"""
node = SingleNode(item)
node.next = self.__head
self.__head = node
def append(self, item):
"""在链表尾部添加元素,尾插法。时间复杂度O(n)"""
node = SingleNode(item)
# 考虑空链表的情况,空链表没有next属性
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素。时间复杂度O(n)
:param pos 从0开始,0代表头结点,原来的pos位置节点向后移
"""
# 等价于头插法
if pos <= 0:
self.add(item)
# 等价于尾插法
elif pos >= self.length():
self.append(item)
# 在链表中间插入节点
else:
count = 0
pre = self.__head
# count == pos-1的时候,跳出循环,游标pre在pos-1的位置插入后一个节点,原来的pos位置节点向后移
while count < (pos - 1):
count += 1
pre = pre.next
node = SingleNode(item)
node.next = pre.next
pre.next = node
def remove(self, item):
"""删除节点。若链表中存在多个等于item的节点,则只删除第一个"""
cur = self.__head
pre = None
# 如果最后也没找到item,则不做任何操作
while cur is not None:
if cur.elem == item:
# 如果待删除节点为头结点
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
cur.next = None
return
else:
pre = cur
cur = cur.next
def search(self, item):
"""查找节点是否存在。时间复杂度O(n)"""
cur = self.__head
while cur is not None:
if cur.elem == item:
print("yes,it's in")
return True
cur = cur.next
print("sorry,not in")
return False
if __name__ == '__main__':
sll = SingleLinkList()
print(sll.is_empty())
print(sll.length())
sll.append(2)
sll.append(5)
sll.add(9)
sll.append(8)
sll.travel()
sll.insert(-1, -1)
sll.travel()
sll.insert(sll.length(), sll.length() + 1)
sll.travel()
print(sll.search(5))
sll.insert(-100,8)
sll.travel()
sll.remove(8)
sll.travel()
sll.remove(8)
sll.travel()
|
Python | UTF-8 | 317 | 2.546875 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("./data/fuel_consumption.csv")
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("FUELCONSUMPTION_COMB")
plt.ylabel("Emission")
plt.show() |
Go | UTF-8 | 2,607 | 2.53125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | package client
import (
"net/http"
"os"
"testing"
"github.com/isfonzar/pagarme-go/internal/transactions"
)
func TestPagarmeClient_CreateTransaction(t *testing.T) {
address := transactions.Address{
Street: "Avenida Brigadeiro Faria Lima",
StreetNumber: "1811",
Neighborhood: "Jardim Paulistano",
Zipcode: "01451001",
Country: "br",
State: "sp",
City: "Sao Paulo",
Complementary: "Quinto andar",
}
params := transactions.CreateTransactionParams{
Amount: 100,
CardHolderName: "Morpheus Fishburne",
CardExpirationDate: "1220",
CardNumber: "4242424242424242",
CardCVV: "123",
PostbackURL: "http://requestb.in/pkt7pgpk",
Installments: "1",
Billing: transactions.Billing{
Name: "Morpheus Fishburne",
Address: address,
},
Shipping: transactions.Shipping{
Name: "Neo Reeves",
DeliveryDate: "2000-12-21",
Address: address,
},
Items: []transactions.Item{
{
Id: "r123",
Title: "Red Pill",
UnitPrice: 10000,
Quantity: 1,
Category: "Pills",
Venue: "Matrix",
Date: "2000-12-21",
},
{
Id: "b123",
Title: "Blue Pill",
UnitPrice: 10000,
Quantity: 1,
Category: "Pills",
Venue: "Matrix",
Date: "2000-12-21",
},
},
Customer: transactions.Customer{
ExternalID: "#3311",
Type: "individual",
Name: "Morpheus Fishburne",
Country: "br",
Email: "mopheus@nabucodonozor.com",
Documents: []transactions.Document{
{
Number: "30621143049",
Type: "cpf",
},
},
PhoneNumbers: []string{
"+5511999998888",
"+5511888889999",
},
},
}
cli := NewClient(http.Client{}, os.Getenv("PAGARME_API_KEY"), nil)
_, _, err := cli.CreateTransaction(params)
if err != nil {
t.Errorf("Error when sending create transaction request got: %s", err.Error())
}
}
func TestPagarmeClient_CaptureTransaction(t *testing.T) {
params := transactions.CaptureTransactionParams{
Amount: 100,
}
cli := NewClient(http.Client{}, os.Getenv("PAGARME_API_KEY"), nil)
_, _, err := cli.CaptureTransaction(12345, params)
if err != nil {
t.Errorf("Error when sending capture transaction request got: %s", err.Error())
}
}
func TestPagarmeClient_RefundTransaction(t *testing.T) {
params := transactions.NewRefundTransactionParams()
cli := NewClient(http.Client{}, os.Getenv("PAGARME_API_KEY"), nil)
_, _, err := cli.RefundTransaction(12345, params)
if err != nil {
t.Errorf("Error when sending refund transaction request got: %s", err.Error())
}
}
|
JavaScript | UTF-8 | 501 | 2.625 | 3 | [] | no_license | var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/set/:url', function(req, res) {
res.send("Adding URL: " + req.param.url)
});
app.get('*', function(req, res){
//res.send(req.path);
res.redirect("http://google.com");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
}); |
C++ | UTF-8 | 6,364 | 3.265625 | 3 | [] | no_license | #ifndef __WUP__TOPK
#define __WUP__TOPK
#include <exception>
#include <iostream>
#include <cstring>
using std::ostream;
using std::istream;
namespace wup {
template <typename W, typename T>
class TopK {
public:
class TopKException : public std::exception {
public:
TopKException(const char * const msg) : _msg(msg) { }
virtual const char * what() const throw() { return _msg; }
const char * _msg;
};
class Node {
public:
Node() { }
Node(const W w, const T d) : weight(w), data(d) { }
void dumpTo(ostream &file_out)
{
file_out << " " << weight;
file_out << " " << data;
}
void loadFrom(istream &file_in)
{
file_in >> weight;
file_in >> data;
}
bool operator != (const Node &other) const
{
return !((*this) == other);
}
bool operator == (const Node &other) const
{
if (weight != other.weight) return false;
if (data != other.data) return false;
return true;
}
public:
W weight;
T data;
};
class iterator {
public:
iterator(const Node * const mem, const int pos)
: _mem(mem), _pos(pos) { }
const T operator*() const
{
return _mem[_pos].data;
}
void operator++()
{
++_pos;
}
bool operator!=(const iterator &other) const
{
return _pos != other._pos;
}
private:
const Node * const _mem;
int _pos;
};
public:
TopK(istream &file_in)
{
file_in >> _k;
file_in >> _eltos;
_mem = new Node[_k];
for (int i=0;i<_eltos;++i)
_mem[i].loadFrom(file_in);
}
TopK(const int k) : _k(k), _eltos(0), _mem(new Node[k])
{
}
TopK(const TopK &other) : _k(other._k), _eltos(other._eltos), _mem(new Node[_k])
{
memcpy(_mem, other._mem, _eltos * sizeof(Node));
}
~TopK()
{
delete [] _mem;
}
void push(const W &weight, const T &data)
{
if (_eltos == _k) {
if (_mem[0].weight < weight) {
_mem[0] = Node(weight, data);
goDown(0);
}
} else {
_mem[_eltos] = Node(weight, data);
goUp(_eltos++);
}
}
T pop()
{
W tmp;
return pop(tmp);
}
T pop(W &weight)
{
if (_eltos == 0)
throw TopKException("TopK is empty.");
weight = _mem[0].weight;
T temp = _mem[0].data;
_mem[0] = _mem[_eltos-1];
_eltos--;
goDown(0);
return temp;
}
int size() const
{
return _eltos;
}
bool hasAny() const
{
return _eltos != 0;
}
bool isFull() const
{
return _eltos == _k;
}
int k() const
{
return _k;
}
void clear()
{
_eltos = 0;
}
W & base_weight() const
{
if (_eltos == 0)
throw TopKException("TopK is empty.");
return _mem[0].weight;
}
T & base_data() const
{
if (_eltos == 0)
throw TopKException("TopK is empty.");
return _mem[0].data;
}
Node &
base() const
{
return _mem[0];
}
void dumpTo(ostream &file_out)
{
file_out << " " << _k;
file_out << " " << _eltos;
for (int i=0;i<_eltos;++i)
_mem[i].dumpTo(file_out);
}
bool operator != (const TopK<W, T> &other) const
{
return !((*this) == other);
}
bool operator == (const TopK<W, T> &other) const
{
if (_k != other._k) return false;
if (_eltos != other._eltos) return false;
for (int i=0;i<_eltos;++i)
if (_mem[i] != other._mem[i])
return false;
return true;
}
iterator begin() const
{
return iterator(_mem, 0);
}
iterator end() const
{
return iterator(_mem, _eltos);
}
private:
void goUp(int i)
{
Node temp;
int parentId = parent(i);
while(i != 0 && _mem[parentId].weight > _mem[i].weight) {
temp = _mem[parentId];
_mem[parentId] = _mem[i];
_mem[i] = temp;
i = parentId;
parentId = parent(i);
}
}
void goDown(int i)
{
Node temp;
for (;;) {
Node ¤t = _mem[i];
if (hasRight(i)) {
Node &leftSon = _mem[left(i)];
Node &rightSon = _mem[right(i)];
if (leftSon.weight < rightSon.weight) {
if (leftSon.weight < current.weight) {
temp = current;
current = leftSon;
leftSon = temp;
i = left(i);
} else break;
} else {
if (rightSon.weight < current.weight) {
temp = current;
current = rightSon;
rightSon = temp;
i = right(i);
} else break;
}
} else if (hasLeft(i)) {
Node &leftSon = _mem[left(i)];
if (leftSon.weight < current.weight) {
temp = current;
current = leftSon;
leftSon = temp;
i = left(i);
} else break;
} else break;
}
}
int parent(const int i) const
{
return (i-1)/2;
}
int left(const int i) const
{
return i*2+1;
}
int right(const int i) const
{
return i*2+2;
}
bool hasLeft(const int i) const
{
return left(i) < _eltos;
}
bool hasRight(const int i) const
{
return right(i) < _eltos;
}
private:
int _k;
int _eltos;
Node *_mem;
};
} /* wup */
#endif
|
Python | UTF-8 | 2,076 | 2.859375 | 3 | [] | no_license | import gym
from gym import spaces
from QLearning.GridWorld.state import State
TRAP_REWARD = -1
GOAL_REWARD = +1
TIMESTEP_REWARD = -0.1
class GridEnv(gym.Env):
def __init__(self, layout_id=0):
super().__init__()
self.state = State(layout_id=layout_id)
self.time = 0
self.end_time = 20
max_state = 10 * self.state.shape[0] + self.state.shape[1]
self.observation_space = spaces.Discrete(max_state)
self.action_space = spaces.Discrete(5)
def reset(self):
self.state.reset()
self.time = 0
return self.get_obs()
def apply_action(self, action):
if action == 1:
self.state.move(dy=-1)
elif action == 2:
self.state.move(dx=-1)
elif action == 3:
self.state.move(dy=+1)
elif action == 4:
self.state.move(dx=+1)
elif action == 0:
pass
else:
raise ValueError("Unknown action {}".format(action))
def get_obs(self):
x, y = self.state.get_player_pos()
obs = 10 * x + y
return obs
def step(self, action):
done = False
self.apply_action(action)
reward = self.compute_reward()
obs = self.get_obs()
self.time += 1
x, y = self.state.get_player_pos()
if self.state.get_state(x, y) == 2:
done = True
if self.state.get_state(x, y) == 3:
done = True
# if self.time >= self.end_time:
# done = True
# done = False
return obs, reward, done, {}
def compute_reward(self):
x, y = self.state.get_player_pos()
cell_value = self.state.get_state(x, y)
reward = 0
if cell_value == 2:
reward += TRAP_REWARD
elif cell_value == 3:
reward += GOAL_REWARD
else:
reward += TIMESTEP_REWARD
return reward
def get_state(self):
return self.state
# def render(self, mode='txt'):
# for
#
# self.state.render()
|
Markdown | UTF-8 | 7,026 | 3.5625 | 4 | [] | no_license | # 1.2 - Clock App
This next time app we're going to make is going to tell us what time it is! So a little bit more complex than a simple timer, but still utilizing many of the same lifestyle methods.
## Component Starter
To start we need to create a `ClockApp.js` file inside of our timer-apps folder. Your timer-apps should look like the following.
```text
└── src
└── assets
└── components
└── apps
└── timer-apps
└── TimePiecesApp.js
└── TimerApp.js
└── ClockApp.js
```
Let's go ahead and get our `ClockApp` file started with the following code:
```javascript
import React, { Component } from 'react';
export default class ClockApp extends Component {
render() {
return (
<div>
<h1 className="section-title">React Clock</h1>
</div>
);
}
}
```
Next, to get this to display, we need to change our parent component, TimePiecesApp to no longer have CloakApp commented out, so go ahead and make sure that your TimePiecesApp file looks like this.
```javascript
import React from 'react';
import TimerApp from './TimerApp';
import ClockApp from './ClockApp';
// import StopWatchApp from './StopWatchApp'
const TimePiecesApp = () => {
return (
<div className="main">
<div className="mainDiv">
<TimerApp />
<hr />
<ClockApp />
{/* <hr />
<StopWatchApp /> */}
</div>
</div>
)
}
export default TimePiecesApp;
```
Now you should see your Clock App h1, to know you've correctly gotten your component to display!
## State Set up
For this app, our goal is to display the current time. To do this, we need to set up our state in this component to be the current time, and then have that time be displayed in our render.
So, the first thing we can do is set up our state to have our current time. As usual, to initiate state, we can do this inside of our constructor. Remember to include `super(props)` inside of your constructor as well. Type the following code at the top of your ClockApp class.
```javascript
constructor(props) {
super(props);
var date = this.getTimeString();
this.state = {
time: date
}
}
```
We also need to define our `getTimeString()`, so underneath our constructor we're going to create a method to get the current time. We can use build in javascript Date, see [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) for more info on Date. Put our `getTimeString()` method underneath the constructor.
```javascript
getTimeString() {
const date = new Date(Date.now()).toLocaleTimeString();
return date;
}
```
So now our state should reflect the current time. But we haven't rendered this to the screen yet, so let's go ahead and add it to our render. See if you can figured out how to add it without looking at the below code. Remember to use this, when needed.
Did you add it successfully? Either way, check out the below code for our render\(\) function, to compare to yours.
```javascript
render() {
return (
<div>
<h1 className="section-title">React Clock</h1>
<hr className="explanation" />
<p>{this.state.time}</p>
</div>
);
}
```
## Time Check
Now that we have it rendering the time, do you think this will update to the new time? If you're unsure, watch and see what happens, are the seconds moving?
Why isn't it updating with the time? Think back to our timer app, and remember what we had to do to get the seconds to update every single second. We'll need to do something similar here, to get our clock to update every single second. Just like the simple timer app, we'll need to use `componentDidMount()` to set our interval, and `componentWillUnmount()` to stop the interval when we navigate away or the component is no longer needed.
## componentDidMount
In our `componentDidMount` we need some way to update our time part of our state every second with the current updated time. In the below code, we are ensuring that this happens every one second.
```javascript
componentDidMount() {
const _this = this;
this.timer = setInterval(function () {
var date = _this.getTimeString();
_this.setState({
time: date
})
}, 1000)
}
```
Notice the first line of `ComponentDidMount()`, why are we creating a new const \_this? Try commenting out the `const _this = this` and using `this` instead of `_this` in the rest of this block of code. It throws an error, and says that `this.getTimeString() is not a function`.
Why does it do this? This is due to scoping in JavaScript. Where we set \_this = this, `this` is in the global scope, but inside of the function\(\), we now have a local scope, so if we try to use regular `this` inside of the function, it is pointing to the local scope of the function, which is not what we want.
So, to prevent this issue, we set `const _this = this` first, so that we are then able to use the correctly scoped `this` when we need to. See [here](https://javascriptplayground.com/javascript-variable-scope-this/) for another explanation that uses examples in vanilla JS and jQuery, or [here](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) for an extremely in depth explanation.
## Check the clock
Now that we have our setInterval with our date, we are correctly able to see a clock that updates!! Now, just like our simple timer app, we need to make sure that when we leave the page, whent the component unmounts, that the setInterval is not still going. So again, we're going to clearInterval in componentWillUnmount.
```javascript
componentWillUnmount() {
clearInterval(this.timer);
}
```
And that takes care of our clock app! Hopefully you have a better understanding of some of the lifestyle methods in react, and some more information on this scoping JS. Check your final code against the code below, to ensure that it's all correct. Next up is a stop watch app!
```javascript
import React, { Component } from 'react';
export default class ClockApp extends Component {
constructor(props) {
super(props);
var date = this.getTimeString();
this.state = {
time: date
}
}
getTimeString() {
const date = new Date(Date.now()).toLocaleTimeString();
return date;
}
componentDidMount() {
const _this = this;
this.timer = setInterval(function () {
var date = _this.getTimeString();
_this.setState({
time: date
})
}, 1000)
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<div>
<h1 className="section-title">React Clock</h1>
<hr className="explanation" />
<p>{this.state.time}</p>
</div>
);
}
}
```
[Stopwatch App Setup](1.3-stop-watch-app.md)
|
JavaScript | UTF-8 | 1,700 | 3.03125 | 3 | [] | no_license | import { patch, createVNode } from "./vdom.js";
/*
const createVButton = props => {
const { text, onclick } = props;
return createVNode("button", { onclick }, [text]);
};
const createVApp = store => {
const { count } = store.state;
return createVNode("div", { class: "container", "data-count": count }, [
createVNode("h1", {}, ["Hello, Virtual DOM"]),
createVNode("div", {}, [`Count: ${count}`]),
"Text node without tags",
createVNode("img", { src: "https://i.ibb.co/M6LdN5m/2.png", width: 200 }),
createVNode("div", {}, [
createVButton({
text: "-1",
onclick: () => store.setState({ count: store.state.count - 1 })
}),
" ",
createVButton({
text: "+1",
onclick: () => store.setState({ count: store.state.count + 1 })
})
])
]);
};
*/
const createVApp = store => {
const { count } = store.state;
const decrement = () => store.setState({ count: store.state.count - 1 });
const increment = () => store.setState({ count: store.state.count + 1 });
return (
<div {...{ class: "container", "data-count": String(count) }}>
<h1>Hello, Virtual DOM</h1>
<div>Count: {String(count)}</div>
Text node without tags
<img src="https://i.ibb.co/M6LdN5m/2.png" width="200" />
<button onclick={decrement}>-1</button>
<button onclick={increment}>+1</button>
</div>
);
};
const store = {
state: { count: 0 },
onStateChanged: () => {},
setState(nextState) {
this.state = nextState;
this.onStateChanged();
}
};
let app = patch(createVApp(store), document.getElementById("app"));
store.onStateChanged = () => {
app = patch(createVApp(store), app);
};
|
Markdown | UTF-8 | 347 | 2.953125 | 3 | [] | no_license | # Data-Wrangling
Data Wrangling is also known as 'data munging', is the process of transforming and mapping data from one "raw" data form into another format with the intent of making it more appropriate and valuable for a variety of downstream purposes such as analytics. A data wrangler is a person who performs these transformation operations.
|
C | UTF-8 | 1,703 | 2.515625 | 3 | [] | no_license | /*
* gpio.c
*
* Created on: Oct 27, 2017
* Author: user
*/
/*
uint32_t *gpioGMode = (uint32_t*)(GPIOG_BASE+GPIOG_MODE);
uint32_t *gpioGOSPEED = (uint32_t*)(GPIOG_BASE+GPIOG_OSPEED);
uint32_t *gpioGOPupd = (uint32_t*)(GPIOG_BASE+GPIOG_PUPD);
uint32_t *gpioGOType = (uint32_t*)(GPIOG_BASE+GPIOG_OUT_TYPE);
uint32_t *gpioGOD = (uint32_t*)(GPIOG_BASE+GPIOG_OD);
*/
#include "gpio.h"
/*
void gpioGConfig(int pin,int mode, int outDriveType, int pullType, int speed)
{
*gpioGMode &= ~(3<<(pin*2)); //clear pin mode to zero
*gpioGMode |= mode<<(pin*2);
*gpioGOSPEED &= ~(3<<(pin*2));
*gpioGOSPEED |= speed<<(pin*2);
*gpioGOSPEED &= ~(3<<(pin*2));
*gpioGOPupd |= pullType<<(pin*2);
*gpioGOType &= ~(1<<pin);
*gpioGOType |= outDriveType<<pin;
}
*/
void gpio_config(gpio_setting *gpio,int pin,int mode, int outDriveType, int pullType, int speed)
{
gpio->mode_register &=~(3<<(pin*2));
gpio->mode_register |= mode<<(pin*2);
gpio->output_type_register &= ~(1<<pin);
gpio->output_type_register |= outDriveType<<pin;
gpio->output_speed_register &=~(3<<(pin*2));
gpio->output_speed_register |= mode<<(pin*2);
gpio->pull_up_pull_down_register &=~(3<<(pin*2));
gpio->pull_up_pull_down_register |= mode<<(pin*2);
}
void gpio_bit_set_reset_register(gpio_setting *gpio,int pin,int set_reset)
{
if(set_reset==1)
{
gpio->bit_set_reset_register=(1<<pin);
}
else
{
gpio->bit_set_reset_register=(1<<16+pin);
}
}
void gpio_write(gpio_setting *gpio,int pin, int state)
{
if(state==1)
{
gpio->output_data_register |=1<<pin;
}
else
{
gpio->output_data_register &= ~(1<<pin);
}
}
int gpio_read(gpio_setting *gpio,int pin)
{
return (gpio->input_data_register)&(1<<pin);
}
|
Java | UTF-8 | 1,806 | 1.976563 | 2 | [] | no_license | package com.avito.android.messenger.di;
import com.avito.android.analytics.screens.ScreenFlowTrackerProvider;
import com.avito.android.analytics.screens.TimerFactory;
import com.avito.android.analytics.screens.tracker.ScreenTrackerFactory;
import dagger.internal.Factory;
import dagger.internal.Preconditions;
import javax.inject.Provider;
public final class ChannelFragmentModule_ProvidesScreenFlowTrackerProviderFactory implements Factory<ScreenFlowTrackerProvider> {
public final ChannelFragmentModule a;
public final Provider<ScreenTrackerFactory> b;
public final Provider<TimerFactory> c;
public ChannelFragmentModule_ProvidesScreenFlowTrackerProviderFactory(ChannelFragmentModule channelFragmentModule, Provider<ScreenTrackerFactory> provider, Provider<TimerFactory> provider2) {
this.a = channelFragmentModule;
this.b = provider;
this.c = provider2;
}
public static ChannelFragmentModule_ProvidesScreenFlowTrackerProviderFactory create(ChannelFragmentModule channelFragmentModule, Provider<ScreenTrackerFactory> provider, Provider<TimerFactory> provider2) {
return new ChannelFragmentModule_ProvidesScreenFlowTrackerProviderFactory(channelFragmentModule, provider, provider2);
}
public static ScreenFlowTrackerProvider providesScreenFlowTrackerProvider(ChannelFragmentModule channelFragmentModule, ScreenTrackerFactory screenTrackerFactory, TimerFactory timerFactory) {
return (ScreenFlowTrackerProvider) Preconditions.checkNotNullFromProvides(channelFragmentModule.providesScreenFlowTrackerProvider(screenTrackerFactory, timerFactory));
}
@Override // javax.inject.Provider
public ScreenFlowTrackerProvider get() {
return providesScreenFlowTrackerProvider(this.a, this.b.get(), this.c.get());
}
}
|
SQL | UTF-8 | 2,671 | 3.546875 | 4 | [] | no_license | --SpoiledBeans table setup
--CREATE TABLE users (
--
-- id serial,
-- username varchar(25) UNIQUE NOT NULL,
-- password varchar(256) NOT NULL,
-- email varchar(256) UNIQUE NOT NULL,
-- firstname varchar(25),
-- lastname varchar(25),
-- bio varchar(256),
--
-- CONSTRAINT user_id
-- PRIMARY KEY (id)
--
--
--);
create table user_roles(
id serial,
name varchar(25),
constraint id
primary key (id)
);
CREATE TABLE users (
id serial,
username varchar(25) UNIQUE NOT NULL,
password varchar(256) NOT NULL,
email varchar(256) UNIQUE NOT NULL,
firstname varchar(25),
lastname varchar(25),
bio varchar(256),
user_role int,
CONSTRAINT user_id
PRIMARY KEY (id),
FOREIGN KEY (user_role) REFERENCES user_roles (id)
);
--CREATE TABLE movies (
--
-- id serial,
-- name varchar(180),
-- director varchar(51),
-- genre varchar(25),
-- synopsis varchar(25),
--
-- CONSTRAINT movie_id
-- PRIMARY KEY (id)
--
--);
CREATE TABLE movies (
id serial,
name varchar(180),
director varchar(51),
genre varchar(25),
synopsis text,
release_date int not null,
CONSTRAINT movie_id
PRIMARY KEY (id)
);
--CREATE TABLE review (
--
-- id serial,
-- rating numeric(2,1) NOT NULL,
-- review varchar(256),
--
-- CONSTRAINT review_id
-- PRIMARY KEY (id)
--
--);
CREATE TABLE review (
id serial,
rating numeric(2,1) NOT NULL,
review varchar(256),
review_time timestamp not null,
CONSTRAINT review_id
PRIMARY KEY (id)
);
CREATE TABLE user_reviews (
review_id int,
user_id int,
PRIMARY KEY (review_id, user_id),
FOREIGN KEY (review_id) REFERENCES review (id),
FOREIGN KEY (user_id) REFERENCES users (id)
);
CREATE TABLE movie_review (
review_id int,
movie_id int,
PRIMARY KEY (review_id, movie_id),
FOREIGN KEY (review_id) REFERENCES review (id),
FOREIGN KEY (movie_id) REFERENCES movies (id)
);
CREATE TABLE favorites (
user_id int,
movie_id int,
PRIMARY KEY (user_id, movie_id),
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (movie_id) REFERENCES movies (id)
);
--insert into movies ("name",release_date)
-- values('dummyMovieTheSequel',2003);
--insert into movies ("name",director,genre,synopsis,release_date)
-- values('dummy the Third', 'Kalyb Levesque', 'comedy', 'a funny conclusion ', 2005);
--select * from movies;
--select * from users;
--select * from review;
--select * from user_reviews;
--select * from movie_review;
-- these drops should be in order to delete everything for recreation
--drop table user_reviews;
--drop table favorites;
--drop table users;
--drop table user_roles;
--drop table movie_review;
--drop table movies;
--drop table review;
|
Markdown | UTF-8 | 1,982 | 2.9375 | 3 | [] | no_license | ---
title: Java线程状态
category: 编程开发
tags: [Java]
---

### NEW
尚未启动的线程的线程状态。
```java
Thread thread = new Thread();
```
### RUNNABLE
已启动,等待CPU调度运行的线程状态。
```java
thread.start();
```
### BLOCKED
线程阻塞等待监视器锁的线程状态。等待进入synchronized同步代码块或方法。
```java
synchronized (this) {
// ...
}
```
### WAITING
线程获得锁,处于等待状态,需要其它线程唤醒。
```java
synchronized (this) {
this.wait();
}
```
### TIMED_WAITING
线程获得锁,处于等待状态,需要其它线程唤醒,也可以在等待时间结束后自动唤醒。
```java
synchronized (this) {
this.wait(1000);
}
```
### TERMINATED
线程执行完成。
### BLOCKED与WAITING的区别
* 每个对象都有一个监视器锁,同一时刻仅允许一个线程进入,多个线程同时获取锁资源时,就会有线程需要排队等待,等待在`EntryList`同步队列上。等待监视器资源的现在就是BLOCKED状态。
* 当线程调用某个对象的`wait`方法时,当前线程会释放对象锁(因此wait一定要在synchronized同步方法/块中调用),进入等待状态(`WaitSet`)。等待 `notify` 唤醒,或者等待时间结束后自动唤醒。
### sleep和wait的区别
* sleep是线程中的方法,但是wait是Object中的方法。
* sleep方法不会释放lock,但是wait会释放,而且会加入到等待队列中。
* sleep方法不依赖于同步器synchronized,但是wait需要依赖synchronized关键字。
* sleep不需要被唤醒(休眠之后推出阻塞),但是wait需要(不指定时间需要被别人中断)。
### 需要关注的状态
使用jstack、jvisualvm等工具查看线程状态时,重点关注 `WAITING`、`BLOCKED` 状态的线程,尤其是 `dead lock`。
|
SQL | UTF-8 | 1,566 | 4.03125 | 4 | [] | no_license | -- Load data into table
LOAD DATA INPATH '/user/w205/hospital_compare/effective_care/effective_care.csv' OVERWRITE INTO TABLE effective_care_raw;
-- Create a temporary table to hold the maximum value of the scores for each measure_id. Some of the scores are above 100
-- or are on different scales, so I want to normalize these into a field Score_Relative in the subsequent query.
DROP TABLE measure_score_ranges;
CREATE TEMPORARY TABLE measure_score_ranges AS
SELECT Measure_ID, MIN(Score) AS Score_Min, Max(Score) AS Score_Max
FROM (SELECT Measure_ID, CAST(CASE WHEN Score = 'Not Available' THEN NULL
WHEN Score LIKE 'Low %' THEN 1
WHEN Score LIKE 'Medium %' THEN 2
WHEN Score LIKE 'High %' THEN 3
WHEN Score LIKE 'Very High %' THEN 4
ELSE Score END AS INT) AS Score
FROM effective_care_raw) tbl
GROUP BY Measure_ID;
-- Create effective_care table that is ready for later analysis. It includes the score_relative field, which
-- looks up to the temporary table created above to find the relative score for that measure_id.
DROP TABLE effective_care;
CREATE TABLE effective_care AS
SELECT Provider_ID, Condition, a.Measure_ID, Measure_name, Score, Score / Score_Max as Score_Relative,
CAST(CASE WHEN Sample LIKE '%[a-z]%' THEN NULL ELSE Sample END AS INT) AS Sample
FROM effective_care_raw a
INNER JOIN measure_score_ranges b
ON a.measure_id = b.measure_id;
|
C | UTF-8 | 3,900 | 3.71875 | 4 | [] | no_license | #include "tree.h"
void insertTree(struct nodeAuthor* ptrAuthor, struct book* aBook) {
int lenght = strlen(aBook->author);
for (int i = 0; i < lenght; i++) {
char c = aBook->author[i];
int position = charToIndex(c);
if(position < 0 || position > ALPHA_SIZE)
position = getCustomPos(c);
if(ptrAuthor->letters[position] == NULL){
ptrAuthor->letters[position] = createNodeAuthor();
ptrAuthor->letters[position]->letter = c;
}
ptrAuthor = ptrAuthor->letters[position];
}
ptrAuthor->isAuthor = true;
ptrAuthor->books = addBookInList(ptrAuthor->books, aBook);
}
int getCustomPos(char c){
if(c == ' '){
return 26;
}else if(c == '\''){
return 27;
}else if(c == '-'){
return 28;
}
}
struct listBook* findByAuthor(char* name, struct nodeAuthor* tree){
struct listBook* books = createEmptyListBook();
recursiviteAuthor(tree, books, name);
if(books->book == NULL){
printf("None book found with the author %s\n", name);
}
return books;
}
struct listBook* getAllBooks(struct nodeAuthor* tree){
struct listBook* books = createEmptyListBook();
recursiviteAll(tree, books);
return books;
}
struct listBook* findByName(char* name, struct nodeAuthor* tree){
struct listBook* books = createEmptyListBook();
recursiviteName(tree, books, name);
if(books->book == NULL){
printf("None book found with the name %s\n", name);
}
return books;
}
struct nodeAuthor* createNodeAuthor() {
struct nodeAuthor* ptrAuthor = (struct nodeAuthor*) malloc(sizeof(struct nodeAuthor));
for (int i = 0; i < ALPHA_SIZE; i++) {
ptrAuthor->letters[i]=NULL;
}
ptrAuthor->isAuthor = false;
return ptrAuthor;
}
void recursiviteAuthor(struct nodeAuthor* node, struct listBook* books, char* name){
if(node == NULL)
return;
for(int i = 0; i < ALPHA_SIZE; i++){
struct nodeAuthor* next = node->letters[i];
if(next != NULL){
recursiviteAuthor(next, books, name);
}
}
if(node->isAuthor){
struct listBook* aBooks = node->books;
while(aBooks != NULL){
if(strAreEquals(name, aBooks->book->author)){
addBookInList(books, aBooks->book);
}
aBooks = aBooks->next;
}
}
}
void recursiviteName(struct nodeAuthor* node, struct listBook* books, char* name){
if(node == NULL)
return;
for(int i = 0; i < ALPHA_SIZE; i++){
struct nodeAuthor* next = node->letters[i];
if(next != NULL){
recursiviteName(next, books, name);
}
}
if(node->isAuthor){
struct listBook* aBooks = node->books;
while(aBooks != NULL){
if(strAreEquals(name, aBooks->book->name)){
addBookInList(books, aBooks->book);
}
aBooks = aBooks->next;
}
}
}
void recursiviteAll(struct nodeAuthor* node, struct listBook* books){
if(node == NULL)
return;
for(int i = 0; i < ALPHA_SIZE; i++){
struct nodeAuthor* next = node->letters[i];
if(next != NULL){
recursiviteAll(next, books);
}
}
if(node->isAuthor){
struct listBook* aBooks = node->books;
while(aBooks != NULL){
addBookInList(books, aBooks->book);
aBooks = aBooks->next;
}
}
}
bool strAreEquals(char* str1, char* str2){
int lenght1 = strlen(str1);
int lenght2 = strlen(str2);
if(lenght1 > lenght2)
return false;
for(int i = 0; i < lenght1; i++){
char c1 = str1[i];
char c2 = str2[i];
if(tolower(c1) != tolower(c2)){
return false;
}
}
return true;
}
int charToIndex(char c){
if((int)c <= 90)
c+= 32;
return ((int)(c - 'a'));
}
|
Java | UTF-8 | 1,575 | 2.375 | 2 | [] | no_license | package uk.co.jaspalsvoice.jv.models;
import android.content.ContentValues;
import uk.co.jaspalsvoice.jv.db.DbOpenHelper;
/**
* Created by Ana on 3/21/2016.
*/
public class Medicine {
private String uuid;
private String id;
private String name;
private String dosage;
private String reason;
private String frequency;
public ContentValues toContentValues() {
ContentValues cv = new ContentValues();
cv.put(DbOpenHelper.COLUMN_M_UUID, getUuid());
cv.put(DbOpenHelper.COLUMN_M_ID, getId());
cv.put(DbOpenHelper.COLUMN_M_NAME, getName());
cv.put(DbOpenHelper.COLUMN_M_DOSAGE, getDosage());
cv.put(DbOpenHelper.COLUMN_M_FREQUENCY, getFrequency());
return cv;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDosage() {
return dosage;
}
public void setDosage(String dosage) {
this.dosage = dosage;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getFrequency() {
return frequency;
}
public void setFrequency(String frequency) {
this.frequency = frequency;
}
}
|
C# | UTF-8 | 5,346 | 2.828125 | 3 | [] | no_license | using PuntuarCombateMarvel_DAL.Connections;
using PuntuarCombateMarvelUWP_Entities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PuntuarCombateMarvelUWP_DAL.Lists
{
public class clsListadosLuchadoresDAL
{
/*TODO:
* ObservableCollecion<clsLuchador> getListadoLuchadoresOrdenados()
* ObservableCollecion<clsLuchador> getListadoLuchadores()
* */
/// <summary>
/// Método que obtiene el listado de todos los luchadores de la BBDD
/// </summary>
/// <returns>ObservableCollection<clsLuchador> listadoLuchadores, con todos los luchadores</returns>
public ObservableCollection<clsLuchador> getListadoLuchadores()
{
clsMyConnection objConnection = new clsMyConnection();
SqlConnection connection = null;
SqlCommand command = new SqlCommand();
SqlDataReader reader= null;
ObservableCollection<clsLuchador> listadoLuchadores = new ObservableCollection<clsLuchador>();
clsLuchador objLuchador = null;
try
{
connection = objConnection.getConnection();
command.Connection = connection;
command.CommandText = "SELECT * FROM SH_Luchadores";
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//Creo objeto clsLuchador
objLuchador = new clsLuchador();
//Paso los datos obtenidos al objeto clsLuchador
objLuchador.IdLuchador = (int)reader["idLuchador"];
objLuchador.NombreLuchador = reader.IsDBNull(reader.GetOrdinal("nombreLuchador")) ? "null" : (string)reader["nombreLuchador"];
objLuchador.FotoLuchador = reader.IsDBNull(reader.GetOrdinal("fotoLuchador")) ? new byte[0] : (byte[])reader["fotoLuchador"];
//Añado el nuevo objeto al listado
listadoLuchadores.Add(objLuchador);
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (connection != null)
{
objConnection.closeConnection(ref connection);
}
}
return listadoLuchadores;
}
/// <summary>
/// Método que obtiene el listado de todos los luchadores de la BBDD ordenados por el total de sus rating en todos los combates que han participado
/// </summary>
/// <returns>ObservableCollection<clsLuchador> listadoLuchadores, con todos los luchadores</returns>
public ObservableCollection<clsLuchador> getListadoLuchadoresOrdenados()
{
clsMyConnection objConnection = new clsMyConnection();
SqlConnection connection = null;
SqlCommand command = new SqlCommand();
SqlDataReader reader = null;
ObservableCollection<clsLuchador> listadoLuchadores = new ObservableCollection<clsLuchador>();
clsLuchador objLuchador = null;
try
{
connection = objConnection.getConnection();
command.Connection = connection;
command.CommandText = " SELECT lu.idLuchador, lu.nombreLuchador, lu.fotoLuchador, SUM(lc.puntuacionLuchador) AS totalPuntuacionLuchador " +
"FROM SH_LuchadoresCombates AS lc, SH_Luchadores AS lu " +
"WHERE lu.idLuchador = lc.idLuchador " +
"GROUP BY lu.idLuchador, lu.nombreLuchador, lu.fotoLuchador "+
"ORDER BY SUM(lc.puntuacionLuchador) DESC";
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//Creo objeto clsLuchador
objLuchador = new clsLuchador();
//Paso los datos obtenidos al objeto clsLuchador
objLuchador.IdLuchador = (int)reader["idLuchador"];
objLuchador.NombreLuchador = reader.IsDBNull(reader.GetOrdinal("nombreLuchador")) ? "null" : (string)reader["nombreLuchador"];
objLuchador.FotoLuchador = reader.IsDBNull(reader.GetOrdinal("fotoLuchador")) ? new byte[0] : (byte[])reader["fotoLuchador"];
//Añado el nuevo objeto al listado
listadoLuchadores.Add(objLuchador);
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (connection != null)
{
objConnection.closeConnection(ref connection);
}
}
return listadoLuchadores;
}
}
}
|
Ruby | UTF-8 | 2,081 | 2.515625 | 3 | [
"MIT"
] | permissive | class Message < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
UNLIMITED_FORM_AT = Time.zone.parse("1970-01-01 00:00:00")
UNLIMITED_TO_AT = Time.zone.parse("2101-01-01 00:00:00")
belongs_to :twitter_account
belongs_to :category
validates :from_at, presence: true
validates :to_at, presence: true
with_options if: :category_is_week? do
validates :post_weekday, presence: true
validates :post_time, presence: true
end
# 有効かどうかは 10 分ごとの値でなくリアルタイムの現在時刻をベースにする。
scope :valid, ->(now) { where("from_at <= :now AND :now < to_at", { now: now }) }
scope :valid_category_id, ->(now, category_id) { valid(now).where(category_id: category_id) }
def category_is_week?
self.category == 1
end
# 表示用のモデルに変更
# - 終了日時を前の日の 00:00 にする
def to_view!
if self.from_at == UNLIMITED_FORM_AT
self.from_at = nil
end
if self.to_at == UNLIMITED_TO_AT
self.to_at = nil
else
self.to_at = self.to_at.yesterday
end
end
# 表示用のモデルから実際のモデルに戻す
# - 終了日時を次の日の 00:00 にする
def from_view!
if self.from_at.nil?
self.from_at = UNLIMITED_FORM_AT
end
if self.to_at.nil?
self.to_at = UNLIMITED_TO_AT
else
self.to_at = self.to_at.tomorrow
end
end
# カテゴリが曜日とランダム用
def modify_for_weekday_and_random!
if self.category_id == 2
self.post_weekday = nil
self.post_time = nil
end
end
# 期間を無制限に
def set_at_unlimited!
self.from_at = UNLIMITED_FORM_AT
self.to_at = UNLIMITED_TO_AT
end
#
# Twitter 投稿
#
def post
account = self.twitter_account
#TwitterUtil.post(self.text,
TwitterUtil.post_v2(self.text,
account.consumer_key,
account.consumer_secret,
account.access_token,
account.access_token_secret)
end
end
|
Markdown | UTF-8 | 1,992 | 2.8125 | 3 | [] | no_license | ---
layout: post
title: Template Support | Toolbar | ASP.NET | Syncfusion
description: template support
platform: aspnet
control: Toolbar
documentation: ug
---
# Template Support
Templates allows you to insert custom or ASP.NET controls inside the toolbar items. You can also design simple dropdown buttons listing the items and radio button inside the Toolbar.
Set the list for DropDown control inside a list tag and define this tag as a Toolbar item. You can use all simple controls as a ToolBar item. The following code example explains how to add RadioButton and DropDownList to the Toolbar.
Add the following code example to the corresponding ASPX page to render the Toolbar Control.
{% highlight html %}
<ej:Toolbar ID="toolbarTemplate" Width="250px" Height="28px" runat="server">
<Items>
<ej:ToolbarItem>
<Template>
<div class="ctrlradio">
<ej:RadioButton ID="RadioButton1" Name="small" runat="server">option</ej:RadioButton>
</div>
<ej:DropDownList ID="selectcar" runat="server" SelectedItemIndex="0" Width="100px" Height="23px">
<Items>
<ej:DropDownListItem Text="Audi A4" Value="Audi A4"></ej:DropDownListItem>
<ej:DropDownListItem Text="Audi A5" Value="Audi A5"></ej:DropDownListItem>
<ej:DropDownListItem Text="Audi A6" Value="Audi A6"></ej:DropDownListItem>
<ej:DropDownListItem Text="Audi A7" Value="Audi A7"></ej:DropDownListItem>
<ej:DropDownListItem Text="Audi A8" Value="Audi A8"></ej:DropDownListItem>
</Items>
</ej:DropDownList>
</Template>
</ej:ToolbarItem>
</Items>
</ej:Toolbar>
{% endhighlight %}
The following screenshot displays the Toolbar output with the embedded controls.

|
Java | UTF-8 | 752 | 2.265625 | 2 | [] | no_license | package com.github.cache.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
/**
* 功能描述: 删除缓存
* @author: qinxuewu
* @date: 2019/11/13 16:26
* @since 1.0.0
*/
public class UpdateProductInfoCommand extends HystrixCommand<Boolean> {
private Long productId;
public UpdateProductInfoCommand(Long productId) {
super(HystrixCommandGroupKey.Factory.asKey("UpdateProductInfoGroup"));
this.productId = productId;
}
@Override
protected Boolean run() throws Exception {
// 这里执行一次商品信息的更新
// ...
// 然后清空缓存
GetProductInfoCommand.flushCache(productId);
return true;
}
}
|
C++ | UTF-8 | 253 | 2.640625 | 3 | [] | no_license | #pragma once
#include <iostream>
class Quest
{
public:
Quest(const std::string question,const std::string answer);
const std::string& getQuestion() const;
const std::string& getAnswer() const;
private:
std::string question;
std::string answer;
};
|
TypeScript | UTF-8 | 2,379 | 2.515625 | 3 | [] | no_license | import { Component, Input, OnInit, Output } from '@angular/core';
import { Pokemon } from '../fight/models/Pokemon';
import { FightService, FightState, Log } from '../fight/fight.service';
import { Observable } from 'rxjs';
import { PokemonService } from '../pokemon/pokemon.service';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'combat-component',
templateUrl: './combat.component.html',
styleUrls: ['./combat.component.css'],
})
export class CombatComponent implements OnInit {
@Input() firstPokemon?: Pokemon;
@Input() secondPokemon?: Pokemon;
@Output() logs: Log[] = [];
@Output() winner?: Pokemon;
source!: Observable<Log | undefined>;
isStarted = false;
isEnd = false;
constructor(
public fightService: FightService,
private pokemonService: PokemonService,
private router: Router,
private route: ActivatedRoute,
) {}
async ngOnInit(): Promise<void> {
const firstPokemonName = this.route.snapshot.queryParamMap.get(
'firstPokemon',
);
const secondPokemonName = this.route.snapshot.queryParamMap.get(
'secondPokemon',
);
if (!firstPokemonName || !secondPokemonName) {
await this.router.navigate(['']);
} else {
this.firstPokemon = await this.pokemonService.getPokemon(
firstPokemonName,
);
this.secondPokemon = await this.pokemonService.getPokemon(
secondPokemonName,
);
}
}
async start(): Promise<void> {
if (!this.firstPokemon || !this.secondPokemon) {
return;
}
this.isStarted = true;
this.source = this.fightService.init(
this.firstPokemon,
this.secondPokemon,
500,
);
const subscription = this.source.subscribe((log: Log | undefined) => {
if (!log) {
return; // when game is paused per example
}
this.logs.push(log);
if (log.type === 'end') {
subscription.unsubscribe();
this.hideLoser(log.looser);
this.isEnd = true;
}
});
}
private hideLoser(loser: Pokemon): void {
if (!this.firstPokemon || !this.secondPokemon) {
return;
}
loser.name === this.firstPokemon.name
? (this.firstPokemon.isLoser = true)
: (this.secondPokemon.isLoser = true);
}
handlePlay(fightState: FightState): void {
this.fightService.state = fightState;
}
}
|
Python | UTF-8 | 540 | 3.328125 | 3 | [
"MIT"
] | permissive | # Allowed symbols
SYMBOLS = '⇒⇔¬∧∨⊕()' # TODO?: '∀∃⊢'
class Var:
'''
Variable token: A way to differentiate variables from symbols
'''
def __init__(self, s):
self.s = s
def __repr__(self):
return self.s
def __str__(self):
return self.s
def __eq__(self, other):
if type(self) == type(other):
return self.s == other.s
def __hash__(self):
return self.s.__hash__()
# Absolute values
ABSOLUTES = {Var('⊤'): True, Var('⊥'): False}
|
TypeScript | UTF-8 | 752 | 2.703125 | 3 | [
"MIT"
] | permissive | import { BaseMetric } from '../base';
import { Recall } from './recall';
import { Specificity } from './specificity';
export class PrevalenceThreshold extends BaseMetric {
name = 'prevalence threshold';
static range: [number, number] = [0, 1];
formula =
'\\frac{\\sqrt{true\\:positive\\:rate \\cdot (1 - true\\:negative\\:rate)} + true\\:negative\\:rate - 1}{true\\:positive\\:rate + true\\:negative\\:rate - 1}';
get value(): number {
const truePositiveRate = new Recall(this.matrix).value;
const trueNegativeRate = new Specificity(this.matrix).value;
return (
(Math.sqrt(truePositiveRate * (-trueNegativeRate + 1)) +
trueNegativeRate -
1) /
(truePositiveRate + trueNegativeRate - 1)
);
}
}
|
Markdown | UTF-8 | 1,634 | 3 | 3 | [] | no_license | # Simple Blog
A simple blog.
This project utilizes the latest JavaScript syntax available in NodeJS.
[Live Demo](https://simple-blog-bccpqpmxki.now.sh)
> Note: Deployment is not scaled and database is a free sandbox might take a while to fire up!
## Concepts Covered
- [x] REST API Architecture.
- [x] Promises using `async/await` syntax.
- [x] Dry code by creating middlewares.
- [x] noSQL Database (`mongodb`)
- [x] `ejs` templating
## REST API Architecture
Name | Endpoint | Verb | Description |
-------|----------------------|---------|-------------------------------------------------------------------|
INDEX | / | GET | Redirect to `/posts`. |
NEW | /posts | GET | Render view for *all* posts. |
GET | /posts/new | GET | Render view for adding new post. |
CREATE | /posts | POST | Add a post to the database. |
SHOW | /posts/:id | GET | Render view for *single* post. |
EDIT | /posts/:id/edit | GET | Render view for editing a post. |
UPDATE | /posts/:id | PUT | Render view *after* updating a post with updated post. |
REMOVE | /posts/:id | DELETE | Render view *after* removing a post with list of remaining posts. |
## TODO
- [ ] Clean up Styling
- [ ] Handle error cases better.
|
JavaScript | UTF-8 | 3,161 | 2.8125 | 3 | [] | no_license | window.addEventListener('hashchange', function(){
navlinks.style.display = 'none';
setTimeout(function(){
nav.classList.remove('expanded');
}, 50)
isNavbarOpen = false;
});
// navbar feature
var nav = document.querySelector('nav');
var menuBtn = document.querySelector('#menuBtn');
var navlinks = document.querySelector('#navlinks');
var isNavbarOpen = false;
menuBtn.addEventListener('click', function(){
if(isNavbarOpen){
navlinks.style.display = 'none';
setTimeout(function(){
nav.classList.remove('expanded');
}, 50)
isNavbarOpen = false;
}
else{
nav.classList.add('expanded');
setTimeout(function(){
navlinks.style.display = 'flex';
}, 50)
isNavbarOpen = true;
}
});
window.addEventListener('scroll', function () {
var scrolledHeight = window.scrollY;
checkForNavbar(scrolledHeight);
})
function checkForNavbar(scrolled) {
if (scrolled > 150) {
nav.classList.add('heightedNav');
}
else {
nav.classList.remove('heightedNav');
}
}
// TWEEN MAX AND ANIMATIONS PART
var controller = new ScrollMagic.Controller();
var tl = new TimelineMax();
tl.to('#image', 10, {
width: '100%',
ease: Power3.easeInOut
})
// create a scene
new ScrollMagic.Scene({
triggerElement: '#scrolledSection',
duration: '100%', // the scene should last for a scroll distance of 100px
triggerHook: 0,
offset: '0'
})
.setTween(tl)
.setPin('#scrolledSection') // pins the element for the the scene's duration
.addTo(controller);
var tl2 = new TimelineMax();
tl2.fromTo('#breaker h1', 10, {
y: 100,
opacity: 0,
ease: Power3.easeInOut
}, {
y: 0,
opacity: 1,
ease: Power3.easeInOut
})
// create a scene
new ScrollMagic.Scene({
triggerElement: '#hero',
duration: '50%', // the scene should last for a scroll distance of 100px
triggerHook: 0,
offset: '100'
})
.setTween(tl2)
// .setPin('#breaker') // pins the element for the the scene's duration
.addTo(controller);
var tl3 = new TimelineMax();
tl3.fromTo('#feature1', 10, {
y: 50,
opacity: 0,
ease: Power3.easeInOut
}, {
y: 0,
opacity: 1,
ease: Power3.easeInOut
})
// create a scene
new ScrollMagic.Scene({
triggerElement: '#breaker',
duration: '300', // the scene should last for a scroll distance of 100px
triggerHook: 0,
offset: '-200'
})
.setTween(tl3)
// .setPin('#breaker') // pins the element for the the scene's duration
.addTo(controller);
var tl4 = new TimelineMax();
tl4.fromTo('#feature2', 10, {
y: 50,
opacity: 0,
ease: Power3.easeInOut
}, {
y: 0,
opacity: 1,
ease: Power3.easeInOut
})
// create a scene
new ScrollMagic.Scene({
triggerElement: '#feature1',
duration: '300', // the scene should last for a scroll distance of 100px
triggerHook: 0,
offset: '-100'
})
.setTween(tl4)
// .setPin('#breaker') // pins the element for the the scene's duration
.addTo(controller);
|
C# | UTF-8 | 346 | 2.609375 | 3 | [] | no_license | using System.Collections;
public class GainCoinsResolver : IResolvable {
public delegate int Count();
private Player player;
private Count count;
public GainCoinsResolver(Player player, Count count) {
this.player = player;
this.count = count;
}
public IEnumerator Resolve() {
yield return player.GainCoins(count.Invoke());
}
}
|
C++ | UTF-8 | 886 | 2.578125 | 3 | [] | no_license | // islands in graph
#include<bits/stdc++.h>
using namespace std;
#define R 5
#define C 5
vector<pair<int,int>>pp={{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
void dfs(int x,int y,int mat[R][C],int visited[R][C])
{
visited[x][y]=1;
for(int i=0;i<8;i++)
{
int newx=x+pp[i].first;
int newy=y+pp[i].second;
if(newx>=0&&newx<R&&newy>=0&&newy<C&&visited[newx][newy]==0&&mat[newx][newy]==1)
{
dfs(newx,newy,mat,visited);
}
}
}
int main()
{
int matrix[R][C]={{1,1,0,0,0},{0,1,0,0,1},{1,0,0,1,1},{0,0,0,0,0},{1,0,1,0,1}};
int visited[R][C];
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
{
visited[i][j]=0;
}
}
int cc=0;
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
{
if(matrix[i][j]&&visited[i][j]==0)
{
dfs(i,j,matrix,visited);
cc++;
}
}
}
cout<<"Number of connected components.."<<cc;
}
|
Shell | UTF-8 | 1,248 | 3.421875 | 3 | [] | no_license | #!/bin/sh
#
## builds CentOS-7-x86_64-autoinst.iso in ~
## expects ./ks.cfg present
## mucks around a bit; meant to be run in its own VM.
## dependencies
yum install genisoimage isomd5sum syslinux wget
## if not present, grab original centos iso
if [ ! -e CentOS-7-x86_64-Minimal-1804.iso ]
then
wget http://mirrordenver.fdcservers.net/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1804.iso
fi
## mount original
mkdir /tmp/bootiso
mount -o loop ./CentOS-7-x86_64-Minimal-1804.iso /tmp/bootiso
## make new path, copy OS
mkdir /tmp/bootisoks
cp -rv /tmp/bootiso/* /tmp/bootisoks/
chmod -R u+w /tmp/bootisoks
## copy our kickstart into new iso and edit bootloader
cp ./ks.cfg /tmp/bootisoks/isolinux/ks.cfg
sed -i 's/append\ initrd\=initrd.img/append initrd=initrd.img\ ks\=cdrom:\/ks.cfg/' /tmp/bootisoks/isolinux/isolinux.cfg
## build the new ISO9660
cd /tmp/bootisoks
mkisofs -o /tmp/boot.iso -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -V "CentOS 7 x86_64" -R -J -v -T isolinux/. .
isohybrid /tmp/boot.iso
implantisomd5 /tmp/boot.iso
## go home, save new iso, clean up
cd
mv /tmp/boot.iso ~/CentOS-7-x86_64-autoinst.iso
umount /tmp/bootiso
rm -rf /tmp/boot.iso
rm -rf /tmp/bootiso
rm -rf /tmp/bootisoks
|
Python | UTF-8 | 5,891 | 3.25 | 3 | [] | no_license | class Controller:
filename="./"
def __init__(self, filename):
self.filename = filename
def select(self, id):
f = open(self.filename, "r")
records = f.readlines()
toReturn = []
if(id == ""):
for record in records:
toReturn.append(record.rstrip().split(", "))
return toReturn
for record in records:
toReturn = record.rstrip().split(", ")
current_id = toReturn[0]
if(current_id == id):
return toReturn
return []
def insert(self, toWrite):
text = ', '.join(str(value) for value in toWrite)
f = open(self.filename, "a")
f.write(text + "\n")
def delete(self, id):
f = open(self.filename, "r")
records = f.readlines()
f = open(self.filename, "w")
for record in records:
currentId = record.rstrip().split(", ")[0]
if(currentId != id):
f.write(record)
def update(self, id, content):
self.delete(id)
self.insert(content)
class Store(Controller):
id = 0
name = ""
address = ""
filename = "stores.txt"
def __init__(self, id = 0, name = "", address = ""):
super().__init__(self.filename)
self.id = id
self.name = name
self.address = address
def select(self, id):
result = super().select(id)
if(id == ""):
toReturn = []
for value in result:
toReturn.append(Store(value[0], value[1], value[2]))
else:
toReturn = Store(result[0], result[1], result[2])
return toReturn
def __str__(self):
return f"ID: {self.id}, Nombre: {self.name}, Dirección: {self.address}"
class Product(Controller):
id = 0
store = 0
name = ""
price = 0.0
filename = "products.txt"
def __init__(self, id = 0, store = 0, name = "", price = 0.0):
super().__init__(self.filename)
self.id = id
self.store = store
self.name = name
self.price = price
def select(self, id, store):
result = super().select(id)
if(id == ""):
toReturn = []
for value in result:
toReturn.append(Product(value[0], value[1], value[2], value [3]))
toReturn = self.filter(toReturn, store)
else:
if(result[1] == store):
toReturn = Product(result[0], result[1], result[2], result[3])
return toReturn
def filter(self, products_list, store):
toReturn = []
for product in products_list:
if(product.store == store):
toReturn. append(product)
return toReturn
def __str__(self):
return f"ID: {self.id}, Tienda: {self.store}, Nombre: {self.name}, Precio: {self.price}"
#consola
def max_id(items):
max_value = 0
for item in items:
if(int(item.id) > max_value):
max_value = int(item.id)
return max_value
option = 0
stores_list = Store().select("")
while(option != "5"):
print("Bienvenido al sistema")
print("1. Administrar tienda")
print("2. Ingresar tienda")
print("3. Eliminar tienda")
print("4. Mostrar tiendas")
print("5. Salir")
option = input("Seleccione una opción: ")
if(option == "1"):
store_option = 0
store_id = input("Ingrese el ID de la tienda: ")
products_list = Product().select("", store_id)
while(store_option != "7"):
print("1. Editar tienda")
print("2. Ver productos")
print("3. Eliminar producto")
print("4. Buscar producto")
print("5. Insertar producto")
print("6. Editar producto")
print("7. Atras")
store_option = input("Seleccione una opción: ")
if(store_option == "1"):
name = input("Ingrese el nuevo nombre de la tienda: ")
address = input("Ingrese la nueva dirección: ")
stores_list[0].update(store_id, [store_id, name, address])
elif(store_option == "2"):
products_list = Product().select("", store_id)
for product in products_list:
print(product)
elif(store_option == "3"):
to_delete = input("Ingrese el ID del producto: ")
products_list[0].delete(to_delete)
elif(store_option == "4"):
to_select = input("Ingrese el ID del producto: ")
product = products_list[0].select(to_select, store_id)
print(product)
elif(store_option == "5"):
new_id = str(max_id(products_list) + 1)
name = input("Ingrese el nombre del nuevo producto: ")
price = input("Ingrese el precio del nuevo producto: ")
Product().insert([new_id, store_id, name, price])
elif(store_option == "6"):
product_id = input("Ingrese el ID del producto: ")
name = input("Ingrese el nuevo nombre del producto: ")
price = input("Ingrese el nuevo precio del producto: ")
products_list[0].update(product_id, [product_id, store_id, name, price])
elif(option == "2"):
store_id = str(max_id(stores_list) + 1)
name = input("Ingrese el nombre de la nueva tienda: ")
address = input("Ingrese la dirección: ")
stores_list[0].insert([store_id, name, address])
stores_list = stores_list[0].select("")
elif(option == "3"):
store_id = input("Ingrese el ID de la tienda: ")
stores_list[0].delete(store_id)
stores_list = stores_list[0].select("")
elif(option == "4"):
for store in stores_list:
print(store)
|
JavaScript | UTF-8 | 322 | 3.546875 | 4 | [] | no_license | function circleArea(input) {
let type = typeof input;
if (type === `number`) {
let r = Number(input);
let S = Math.PI * r * r;
console.log(S.toFixed(2));
} else {
console.log(
`We can not calculate the circle area, because we receive a ${type}.`
);
}
}
circleArea(5);
circleArea("name");
|
Java | UTF-8 | 1,621 | 2.21875 | 2 | [] | no_license | package logging;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
/**
* Created by Sergio on 12/9/18.
*/
public class ResponseLoginExample {
String consumerKey = "zHf4fbp8PDrkyKacgYJg6Dvdd";
String consumerSecret ="990MJOBaYyWs2lcXQqHOeBLl4HY7GyZsU2ZCxrcc9hoLgQjNHT";
String accessToken ="3730041076-Ioop8ETaPHaRFJBKPIOUFwjxGEjeg8YNJD06HNA";
String tokenSecret ="KVb3EciXKOA7eKGbFIlT61gXTdD6s09qMoopB9E3dIx6Y";
@BeforeClass
public void setup(){
RestAssured.baseURI="https://api.twitter.com";
RestAssured.basePath ="/1.1/statuses";
}
@Test
public void testMethod(){
given()
.auth()
.oauth(consumerKey,consumerSecret,accessToken,tokenSecret)
.queryParam("status","My first twit from API8")
.when()
.post("/update.json")
.then()
.log()
//.body()
//.headers()
//.all()
//.ifValidationFails()
.ifError()
.statusCode(201);
}
@Test (enabled = false)
public void getResponseBody(){
Response response =
given()
.param("key","t2rgYt7VdtMZnzCA0Q08yqgWs5s3RZMx")
.param("boundingBox","39.95,-105.25,39.52,-104.71")
.param("filters","incidents")
.param("outFormat","json")
.when()
.get("/incidents");
System.out.println(response.body().prettyPrint());
}
}
|
Java | UTF-8 | 1,564 | 2.140625 | 2 | [] | no_license | package com.wisdom.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wisdom.service.StaffService;
@Controller
@RequestMapping("/staff")
@ResponseBody
public class StaffController {
@Autowired
private StaffService staffService;
// 增加
@RequestMapping("/add")
public Map<String, Object> add(String staffName, String staffType, String staffPhone, String staffStatus) {
return staffService.add(staffName, staffType, staffPhone, staffStatus);
}
// 编辑
@RequestMapping("/edit")
public Map<String, Object> edit(String field, String value, String staffId) {
return staffService.edit(field, value, staffId);
}
// 查询
@RequestMapping("/search")
public Map<String, Object> search(String staffName, String staffType, String staffStatus, String staffPhone,
Integer page, Integer limit) {
return staffService.search(staffName, staffType, staffStatus, staffPhone, page, limit);
}
@RequestMapping("/refresh")
public Map<String, Object> refresh(Integer page, Integer limit) {
return staffService.refresh(page, limit);
}
@RequestMapping("/delete")
public Map<String, Object> delete(String ids) {
return staffService.delete(ids);
}
// 根据工种查询
public Map<String, Object> searchStaffByType(String staffStatus) {
return null;
}
}
|
C# | UTF-8 | 1,161 | 2.765625 | 3 | [] | no_license | using UnityEngine;
namespace Assets.Scripts.Units
{
public class InputController : IBehaviourController
{
private readonly Quaternion _forwardDirection;
public bool IsActive => true;
public InputController(Vector3 forwardDirection)
{
_forwardDirection = Quaternion.Euler(forwardDirection);
}
public void Update(Unit unit)
{
if (TryGetInputDirection(out var inputDirection))
{
var movementDirection = _forwardDirection * inputDirection;
unit.Direction = movementDirection.normalized;
unit.CurrentSpeed = unit.Stats.MoveSpeed;
}
else
{
unit.CurrentSpeed = 0;
}
}
private static bool TryGetInputDirection(out Vector3 direction)
{
direction = Vector3.zero;
bool hasInput = false;
if (Input.GetKey(KeyCode.W))
{
direction += Vector3.forward;
hasInput = true;
}
if (Input.GetKey(KeyCode.A))
{
direction += Vector3.left;
hasInput = true;
}
if (Input.GetKey(KeyCode.S))
{
direction += Vector3.back;
hasInput = true;
}
if (Input.GetKey(KeyCode.D))
{
direction += Vector3.right;
hasInput = true;
}
return hasInput;
}
}
} |
Markdown | UTF-8 | 421 | 2.9375 | 3 | [] | no_license | [Divide Two Integers - LeetCode](https://leetcode.com/problems/divide-two-integers/)
# V1
bit 操作 plus加倍法,
不用数学符号完成除操作,本质还是一个一个减被除数,看减了多少次,但是直接减算法效率明显不高O(n),
那么可以使用加倍法快速确定边界(数组扩容也用的这个原理)
提升效率到O(logn);
注意判断负数和被除数是0的情况。
|
Python | UTF-8 | 523 | 3.640625 | 4 | [] | no_license | '''Дано число A (> 1). Вывести наибольшее из целых чисел K, для которых сумма 1 + 1/2 + … + 1/K будет меньше A, и саму эту сумму. '''
def S(A):
if A == 0: return 0
return S(A-1) + 1/A
def f(I, S, K):
s=S
k=K
if i == 1:
return 1.0, 1
if s >= 0:
while s < I:
k += 1
s += 1/k
return s, k
s = 0
k = 1
k_old = 0
for i in range(1,16):
k_old = k
s, k = f(i, s, k)
print(k, s - 1/k)
print(f"e = {k/k_old}")
|
PHP | UTF-8 | 1,006 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
/**
* FuelIgniter
*
* @author Kenji Suzuki https://github.com/kenjis
* @copyright 2012 Kenji Suzuki
* @license MIT License http://opensource.org/licenses/MIT
* @link https://github.com/kenjis/FuelIgniter
*/
class CI_DB
{
private $db = null;
public function get($table = '', $limit = null, $offset = null)
{
if (is_null($this->db))
{
$this->db = DB::select();
}
return $this->db->from($table)->execute();
}
public function insert($table = '', $set = null)
{
if (is_null($this->db))
{
$this->db = DB::insert($table);
}
return $this->db->set($set)->execute();
}
public function get_where($table = '', $where = null, $limit = null, $offset = null)
{
foreach ($where as $column => $val)
{
$this->where($column, '=', $val);
}
return $this->db->from($table)->execute();
}
public function where($column, $op = null, $value = null)
{
if (is_null($this->db))
{
$this->db = DB::select();
}
$this->db->where($column, $op, $value);
}
}
|
Java | UTF-8 | 722 | 2.234375 | 2 | [] | no_license | package javasScriptExecutor;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class JsDemoClick {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
RemoteWebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement findElement = driver.findElement(By.xpath("(//input[@class='RNmpXc'])[2]"));
js.executeScript("arguments[0].click()", findElement);
}
}
|
Java | UTF-8 | 4,202 | 3.15625 | 3 | [] | no_license | package com.rsanchezg.business.logic;
import com.rsanchezg.business.domain.RomanNumber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author raasanch
*/
@Service
public class ProcessQueries {
private Conversions conversions;
@Autowired
public ProcessQueries(Conversions conversions) {
this.conversions = conversions;
}
private Map<String, RomanNumber> romanNumbersMap = new HashMap<>();
private Map<String, Double> scalarMap = new HashMap<>();
/**
* Process each line of the file
*
* @param lines File's lines
* @return Output of lines processed
*/
public List<String> processLines(List<String> lines) {
List<String> output = new ArrayList<>();
for (String line : lines) {
String[] arg = line.trim().split("\\s+");
String result;
if (arg.length == 3) {
result = assignRomanValue(arg);
if (result != null) {
output.add(result);
}
} else if (line.endsWith(" Credits")) {
result = assignValueToMissingElements(line);
if (result != null) {
output.add(result);
}
} else {
if (line.length() > 0) {
output.add(query(line));
}
}
}
return output;
}
/**
* Process lines which have 3 params as assignation
*
* @param arg Line splited in an array
* @return Return null if nothing bad happend
*/
private String assignRomanValue(String[] arg) {
RomanNumber romanNumber = RomanNumber.valueOf(arg[2]);
if (!arg[1].equalsIgnoreCase("is")) {
return "Invalid assignment operator in roman numbers!! (" + arg[1] + ")";
}
romanNumbersMap.put(arg[0], romanNumber);
return null;
}
/**
* Assign a possible value to missing elements
*
* @param line Line splited in an array
* @return Return null if nothing bad happend
*/
private String assignValueToMissingElements(String line) {
String params = line.substring(0, line.indexOf(" is "));
String[] arg = params.trim().split("\\s+");
RomanNumber[] romanNumber = new RomanNumber[arg.length - 1];
for (int i = 0; i < arg.length - 1; i++) {
romanNumber[i] = romanNumbersMap.get(arg[i]);
}
int value = conversions.decodeRoman(romanNumber);
if (value == -1) {
return "Assign value to missing elements invalid!!";
}
params = line.substring(line.indexOf(" is ") + 3, line.indexOf(" Credits"));
try {
Double credits = Double.parseDouble(params.trim());
scalarMap.put(arg[arg.length - 1], credits / value);
} catch (NumberFormatException e) {
return "Assign value to missing elements invalid!!";
}
return null;
}
/**
* Process lines which could be queries
*
* @param line Line to be processed
* @return Output of process
*/
private String query(String line) {
if (line.startsWith("how much is") && line.endsWith("?")) {
String params = line.trim().substring(11, line.indexOf('?')).trim();
String[] arg = params.split("\\s+");
RomanNumber[] romanNumber = new RomanNumber[arg.length];
for (int i = 0; i < arg.length; i++) {
romanNumber[i] = romanNumbersMap.get(arg[i]);
}
return params + " is " + conversions.decodeRoman(romanNumber);
} else if (line.startsWith("how many Credits is") && line.endsWith("?")) {
String params = line.trim().substring(19, line.indexOf('?')).trim();
String[] arg = params.split("\\s+");
RomanNumber[] romanNumber = new RomanNumber[arg.length - 1];
for (int i = 0; i < arg.length - 1; i++) {
romanNumber[i] = romanNumbersMap.get(arg[i]);
}
Double missingElement = scalarMap.get(arg[arg.length - 1]);
if (missingElement != null) {
return params + " is " + (int) (conversions.decodeRoman(romanNumber) * missingElement)
+ " Credits";
} else {
return "Missing element value: (" + arg[arg.length - 1] + ")";
}
} else {
return "I have no idea what you are talking about";
}
}
}
|
Java | UTF-8 | 1,619 | 1.773438 | 2 | [] | no_license | package tp.pr5.lang;
public class CmdDic {
public static final String dropHelp = "Usage: DROP | SOLTAR <id>";
public static final String[] dropCommand = {"DROP", "SOLTAR"};
public static final String helpHelp = "Usage: HELP | AYUDA";
public static final String[] helpCommand = {"HELP", "AYUDA"};
public static final String moveHelp = "Usage: MOVE | MOVER";
public static final String[] moveCommand = {"MOVE", "MOVER"};
public static final String operateHelp = "Usage: OPERATE | OPERAR <id>";
public static final String[] operateCommand = {"OPERATE", "OPERAR"};
public static final String pickHelp = "Usage: PICK | COGER <id>";
public static final String[] pickCommand = {"PICK", "COGER"};
public static final String quitHelp = "Usage: QUIT | SALIR";
public static final String[] quitCommand = {"QUIT", "SALIR"};
public static final String radarHelp = "Usage: RADAR";
public static final String[] radarCommand = {"RADAR"};
public static final String scanHelp = "Usage: SCAN | ESCANEAR [ <id> ]";
public static final String[] scanCommand = {"SCAN", "ESCANEAR"};
public static final String turnHelp = "Usage: TURN | GIRAR LEFT | RIGHT";
public static final String[] turnCommand = {"TURN", "GIRAR"};
public static final String turnRightCommand = "RIGHT";
public static final String turnLeftCommand = "LEFT";
public static final String[] undoCommand = {"UNDO", "DESHACER"};
public static final String undoHelp = "Usage: UNDO";
public static final String[] redoCommand = {"REDO", "REHACER"};
public static final String redoHelp = "Usage: REDO";
//MAIN commands
}
|
Markdown | UTF-8 | 4,591 | 3.296875 | 3 | [] | no_license | # APS360
Artificial Intelligence Fundamentals
<br>
<h3>Pneumonia Detetction (Course Project)</h3>
<p>The purpose of this project is to automate the classification of pneumonia given an image of a chest X-ray and detecting the presence of lung opacities. The dataset consists of chest X-rays of children aged 1–5 years from Guangzhou Women and Children’s Medical Center found on Kaggle. The chest X-rays were originally classified into three categories: normal, bacterial pneumonia and viral pneumonia. </p>
<p>The automation is accomplished through the use of transfer learning. By combining the convolutional layers of a pre-trained AlexNet model with a fully-connected ANN, we are able to achieve classification accuracies of 96.61% on 412 never-seen-before images in approximately 1.15s. Comparatively, a linear SVC chosen as the baseline model was only able to achieve an accuracy of 93.0% on the same test dataset. </p>
<h3>Labs</h3>
* *Lab 1 PyTorch and ANNs* > This introductory lab introduced **Deep Learning frameworks, such as PyTorch**, while reviewing the basics of **Python and relevant Python libraries**. It also involved designing a simple **ANN** to classify whether a given handwritten digit was less than or greater than 3, training the neural network using the MNIST dataset.
* *Lab 2 Cats vs Dogs Using a CNN* > This lab provided the experience required to work with **images and large datasets**, such as CIFAR-10. Inputs with spatially-related features perform much better with a CNN compared to an MLP, and the purpose of this lab was to classify an image into one of two classes ("cat" or "dog") using a **CNN**. Following the parameter-training, I had the opportunity to experience the process of **hyperparameter optimization using learning curves** for the training and validation datasets.
* *Lab 3 Gesture Recognition Using a CNN* > Similar to Lab 2, this lab also focused on working with images, placing a greater emphasis on **creating our own datasets** for various hand gestures from the sign language. This process involved generating the data as well as overcoming the challenges involved during the data cleaning process. The second part of the lab involved a multi-class classification problem, which was first solved by using a **CNN** of my own design and later, using **transfer learning** (AlexNet) to improve the initial model.
* *Lab 4 Data Imputation Using an Autoencoder* > Moving away from classification problems, this lab introduced the concepts of **unsupervised learning** and using Deep Learning to generate data. Using the census records in the Adult Data Set provided by the UCI Machine Learning Repository, this lab used a denoising **linear autoencoder** to perform the task of generating missing values in the records. The data cleaning process allowed me to gain experience with textual data, including **one-hot encoding**, as well as using baseline models to interpret model performance.
* *Lab 5 Spam Detection using an RNN* > Similar to Lab4, this lab also focused on working with textual data using the concepts of **tokenization** and **batching for RNNs**. Text from emails were inputted into a **character-level RNN** to classify whether an email was "spam" or "not-spam". This lab also provided an opportunity to study how various models, such as **GRUs** and **LSTMs**, performed, while analyzing specific aspects of model performance, such as false positives and false negatives.
<h3>Tutorials</h3>
* *Tutorials 1-5* > These tutorials cover concepts very similar to Labs 1-5 using different problems.
* *Tutorial 6 Trump Tweet Generator Using a Generative RNN* > This tutorial highlighted the differences between **prediction and generative RNNs**. A **word-level generative RNN** took tokenized tweets from a collection of Donald Trump's tweets in 2018 and used concepts of **teacher-forcing, sampling and temperature** to generate a wide range of tweets given an input sequence.
* *Tutorial 7 GANs and Adversarial Attacks* > This tutorial reused the MNIST dataset to train a **GAN** that could generate new handwritten digits. It also provided an insight into how difficult it is to train the discriminator and generator given the shapes of their respective training curves. The second part of the tutorial demonstrated the ease with which adversarial examples could be created to fool a GAN. By adding noise, which had been tuned using an optimizer, to an input image, a **targetted adversarial attack** was executed and resulted in the network misclassifying handwritten digits with certainties of 70-90%.
|
C++ | UTF-8 | 1,753 | 3.375 | 3 | [
"MIT"
] | permissive | #include "storage_manager.hpp"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "utils/assert.hpp"
namespace opossum {
StorageManager& StorageManager::get() {
static StorageManager _instance;
return _instance;
}
void StorageManager::add_table(const std::string& name, std::shared_ptr<Table> table) {
const auto insertion_result = _tables.insert({name, table});
Assert(insertion_result.second,
"Table could not be inserted because there was an existing table with the same name.");
}
void StorageManager::drop_table(const std::string& name) {
const auto dropped_table_count = _tables.erase(name);
Assert(dropped_table_count == 1, "Table could not be removed because it was not found.");
}
std::shared_ptr<Table> StorageManager::get_table(const std::string& name) const { return _tables.at(name); }
bool StorageManager::has_table(const std::string& name) const { return _tables.contains(name); }
std::vector<std::string> StorageManager::table_names() const {
auto table_names = std::vector<std::string>{};
table_names.reserve(_tables.size());
for (const auto& [table_name, _] : _tables) {
table_names.emplace_back(table_name);
}
return table_names;
}
void StorageManager::print(std::ostream& out) const {
out << _tables.size() << " tables available:" << std::endl;
for (const auto& [table_name, table_value] : _tables) {
out << " - \"" << table_name << "\" ["
<< "column_count=" << table_value->column_count() << ","
<< " row_count=" << table_value->row_count() << ","
<< " chunk_count=" << table_value->chunk_count() << "]\n";
}
}
void StorageManager::reset() {
// clear all registered tables
_tables.clear();
}
} // namespace opossum
|
SQL | UTF-8 | 16,609 | 3.203125 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 20, 2019 at 09:48 AM
-- Server version: 10.3.15-MariaDB
-- PHP Version: 7.3.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `point_of_sale`
--
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`father_name` varchar(100) NOT NULL,
`cnic` varchar(15) NOT NULL,
`phone_no` varchar(18) NOT NULL,
`address` varchar(100) NOT NULL,
`created_at` datetime NOT NULL,
`created_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `customers`
--
INSERT INTO `customers` (`id`, `name`, `father_name`, `cnic`, `phone_no`, `address`, `created_at`, `created_by`) VALUES
(1, 'saif rehman ', 'Arshad', '31304-2076970-8', '+92(308)-3152046', 'Chack no 145 P Adam Sahabah Rahim Yar khan', '2019-06-28 13:28:28', 1),
(4, 'Nauman', 'Hashmi', '34567-8900987-6', '+65(789)-0876546', 'Rahim Yar khan', '2019-07-27 08:57:44', 1);
-- --------------------------------------------------------
--
-- Table structure for table `distributer`
--
CREATE TABLE `distributer` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`father_name` varchar(100) NOT NULL,
`cnic` varchar(15) NOT NULL,
`phone_no` varchar(18) NOT NULL,
`address` varchar(100) NOT NULL,
`created_at` datetime NOT NULL,
`created_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `distributer`
--
INSERT INTO `distributer` (`id`, `name`, `father_name`, `cnic`, `phone_no`, `address`, `created_at`, `created_by`) VALUES
(3, 'saif', 'rehman', '31311-3131331-3', '+61(321)-31613__', 'chack no 145 ', '2019-06-29 03:30:38', 1),
(4, 'Nauman', 'Hashmi', '65435-6754324-5', '+33(234)-5345643', '32456432456', '2019-07-27 08:59:25', 1),
(5, 'saif rehman ', 'Arshad Iqbal', '3130420769710', '03083152045', 'Chack No 145 P Adam Sahaba', '2019-11-19 11:12:53', 1);
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`product_name` varchar(55) NOT NULL,
`manufacturer` varchar(55) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `product_name`, `manufacturer`) VALUES
(1, 'Samsung On 5', 'SAMSUNG'),
(4, 'Hivaway', 'Chinasdfs'),
(6, 'C5', 'Samasung');
-- --------------------------------------------------------
--
-- Table structure for table `products_per_purchase_invoice`
--
CREATE TABLE `products_per_purchase_invoice` (
`id` int(11) NOT NULL,
`purchase_invoice_id` int(255) NOT NULL,
`product_id` int(255) NOT NULL,
`expiry_starting_date` date NOT NULL,
`expiry_ending_date` date NOT NULL,
`original_price` int(255) NOT NULL,
`discount_per_item` int(255) NOT NULL,
`purchase_price` int(11) NOT NULL,
`sale_price` int(11) NOT NULL,
`status` enum('available','sold') NOT NULL,
`imei` varchar(45) NOT NULL,
`created_by` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products_per_purchase_invoice`
--
INSERT INTO `products_per_purchase_invoice` (`id`, `purchase_invoice_id`, `product_id`, `expiry_starting_date`, `expiry_ending_date`, `original_price`, `discount_per_item`, `purchase_price`, `sale_price`, `status`, `imei`, `created_by`, `created_at`) VALUES
(73, 35, 4, '2019-11-14', '2019-11-14', 25000, 200, 24800, 28000, 'sold', '321', 1, '2019-11-14 04:12:21'),
(74, 35, 4, '2019-11-14', '2019-11-14', 25000, 200, 24800, 28000, 'available', '123', 1, '2019-11-14 04:12:21'),
(75, 35, 1, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '321', 1, '2019-11-14 04:14:26'),
(76, 35, 1, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'sold', '987', 1, '2019-11-14 04:14:26'),
(77, 35, 1, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '789', 1, '2019-11-14 04:14:26'),
(78, 35, 1, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'sold', '654', 1, '2019-11-14 04:14:26'),
(79, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '963', 1, '2019-11-14 04:14:26'),
(80, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '852', 1, '2019-11-14 04:14:26'),
(81, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '741', 1, '2019-11-14 04:14:26'),
(82, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '258', 1, '2019-11-14 04:14:26'),
(83, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '369', 1, '2019-11-14 04:14:26'),
(84, 35, 6, '2019-11-14', '2020-04-17', 25000, 2000, 23000, 30000, 'available', '471', 1, '2019-11-14 04:14:26'),
(85, 36, 1, '2019-11-14', '2020-02-28', 15000, 1000, 14000, 25000, 'available', '345', 1, '2019-11-14 07:03:14');
-- --------------------------------------------------------
--
-- Table structure for table `purchase_invoice`
--
CREATE TABLE `purchase_invoice` (
`id` int(11) NOT NULL,
`distributer_id` int(11) NOT NULL,
`date` date NOT NULL,
`comment` text NOT NULL,
`product_discount` int(11) NOT NULL,
`net_total_of_discount` int(11) NOT NULL,
`discount_of_invoice` int(11) NOT NULL,
`amount_paid` int(11) NOT NULL,
`amount_payable` int(11) NOT NULL,
`created_by` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `purchase_invoice`
--
INSERT INTO `purchase_invoice` (`id`, `distributer_id`, `date`, `comment`, `product_discount`, `net_total_of_discount`, `discount_of_invoice`, `amount_paid`, `amount_payable`, `created_by`, `created_at`) VALUES
(35, 4, '2019-11-14', 'This invoice is of the distributer Nauman Hashmi', 20400, 20400, 0, 279600, 0, 1, '2019-11-14 04:11:07'),
(36, 3, '2019-11-14', 'Nothing to show here something ', 1000, 1000, 0, 14000, 0, 1, '2019-11-14 06:59:55');
-- --------------------------------------------------------
--
-- Table structure for table `sale_invoice`
--
CREATE TABLE `sale_invoice` (
`sale_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`invoice_date` date NOT NULL,
`total_amount` int(11) NOT NULL,
`discount` double NOT NULL,
`net_total` double NOT NULL,
`amount_paid` double NOT NULL,
`remaining` double NOT NULL,
`status` enum('Unpaid','Partially','Paid') NOT NULL,
`created_by` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sale_invoice`
--
INSERT INTO `sale_invoice` (`sale_id`, `customer_id`, `invoice_date`, `total_amount`, `discount`, `net_total`, `amount_paid`, `remaining`, `status`, `created_by`, `created_at`) VALUES
(77, 1, '2019-11-18', 28000, 1000, 28000, 0, 27000, 'Unpaid', 1, '2019-11-18 04:15:11'),
(78, 1, '2019-11-18', 24000, 2000, 22000, 10000, 12000, 'Partially', 1, '2019-11-18 04:24:59'),
(79, 1, '2019-11-18', 27000, 1000, 26000, 2000, 24000, 'Partially', 1, '2019-11-18 04:26:56'),
(80, 1, '2019-11-18', 29000, 25000, 4000, 2000, 2000, 'Partially', 1, '2019-11-18 04:34:22'),
(81, 4, '2019-11-18', 29000, 0, 29000, 2000, 29000, 'Partially', 1, '2019-11-18 04:39:28'),
(82, 1, '2019-11-19', 30000, 3000, 27000, 27000, 0, 'Paid', 1, '2019-11-19 06:10:29'),
(83, 1, '2019-11-19', 88300, 4415, 83885, 83885, 0, 'Paid', 1, '2019-11-19 06:21:47'),
(84, 1, '2019-11-19', 56500, 1000, 55500, 55500, 0, 'Paid', 1, '2019-11-19 11:36:58'),
(85, 1, '2019-11-20', 30000, 1500, 28500, 28500, 0, 'Paid', 3, '2019-11-20 05:37:21');
-- --------------------------------------------------------
--
-- Table structure for table `sale_invoice_product_details`
--
CREATE TABLE `sale_invoice_product_details` (
`sale_invoice_detail_id` int(11) NOT NULL,
`sale_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`sale_price` double NOT NULL,
`imei` int(11) NOT NULL,
`discount_per_item` int(11) NOT NULL,
`created_by` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sale_invoice_product_details`
--
INSERT INTO `sale_invoice_product_details` (`sale_invoice_detail_id`, `sale_id`, `product_id`, `sale_price`, `imei`, `discount_per_item`, `created_by`, `created_at`) VALUES
(97, 77, 4, 28000, 123, 0, 1, '2019-11-18 04:15:11'),
(98, 78, 1, 25000, 345, 1000, 1, '2019-11-18 04:24:59'),
(99, 79, 4, 28000, 321, 1000, 1, '2019-11-18 04:26:56'),
(100, 80, 1, 30000, 789, 1000, 1, '2019-11-18 04:34:22'),
(101, 81, 1, 30000, 987, 1000, 1, '2019-11-18 04:39:28'),
(102, 82, 1, 30000, 321, 0, 1, '2019-11-19 06:10:29'),
(103, 83, 6, 30000, 963, 200, 1, '2019-11-19 06:21:47'),
(104, 83, 6, 30000, 852, 500, 1, '2019-11-19 06:21:47'),
(105, 83, 1, 30000, 654, 1000, 1, '2019-11-19 06:21:47'),
(106, 84, 4, 28000, 321, 500, 1, '2019-11-19 11:36:58'),
(107, 84, 1, 30000, 654, 1000, 1, '2019-11-19 11:36:58'),
(108, 85, 1, 30000, 987, 0, 3, '2019-11-20 05:37:21');
-- --------------------------------------------------------
--
-- Table structure for table `transection_details`
--
CREATE TABLE `transection_details` (
`id` int(11) NOT NULL,
`type` enum('sale','purchase') NOT NULL,
`transection_date` date NOT NULL,
`invoice_id` int(11) NOT NULL,
`paid_amount` double NOT NULL,
`status` enum('Unpaid','Partially','Paid') NOT NULL,
`created_by` int(11) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `transection_details`
--
INSERT INTO `transection_details` (`id`, `type`, `transection_date`, `invoice_id`, `paid_amount`, `status`, `created_by`, `created_at`) VALUES
(14, 'sale', '2019-11-18', 77, 0, 'Unpaid', 1, '2019-11-18 04:15:11'),
(15, 'sale', '2019-11-18', 77, 14000, 'Partially', 1, '2019-11-18 04:15:59'),
(16, 'sale', '2019-11-18', 77, 12000, 'Partially', 1, '2019-11-18 04:16:32'),
(17, 'sale', '2019-11-18', 78, 0, 'Unpaid', 1, '2019-11-18 04:24:59'),
(18, 'sale', '2019-11-18', 78, 10000, 'Partially', 1, '2019-11-18 04:25:30'),
(19, 'sale', '2019-11-18', 79, 2000, 'Partially', 1, '2019-11-18 04:26:56'),
(20, 'sale', '2019-11-18', 80, 2000, 'Partially', 1, '2019-11-18 04:34:22'),
(21, 'sale', '2019-11-18', 80, 2000, 'Partially', 1, '2019-11-18 04:36:00'),
(22, 'sale', '2019-11-18', 81, 2000, 'Partially', 1, '2019-11-18 04:39:28'),
(23, 'sale', '2019-11-19', 82, 0, 'Unpaid', 1, '2019-11-19 06:10:29'),
(24, 'sale', '2019-11-19', 82, 2000, 'Partially', 1, '2019-11-19 06:10:59'),
(25, 'sale', '2019-11-19', 82, 10000, 'Partially', 1, '2019-11-19 06:11:32'),
(26, 'sale', '2019-11-19', 82, 10000, 'Partially', 1, '2019-11-19 06:11:50'),
(27, 'sale', '2019-11-19', 82, 5000, 'Paid', 1, '2019-11-19 06:12:01'),
(28, 'sale', '2019-11-19', 83, 5000, 'Partially', 1, '2019-11-19 06:21:47'),
(29, 'sale', '2019-11-19', 83, 20000, 'Partially', 1, '2019-11-19 06:23:08'),
(30, 'sale', '2019-11-19', 83, 30000, 'Partially', 1, '2019-11-19 06:23:19'),
(31, 'sale', '2019-11-19', 83, 28885, 'Paid', 1, '2019-11-19 06:23:31'),
(32, 'sale', '2019-11-19', 84, 20000, 'Partially', 1, '2019-11-19 11:36:58'),
(33, 'sale', '2019-11-19', 84, 10000, 'Partially', 1, '2019-11-19 11:37:27'),
(34, 'sale', '2019-11-19', 84, 25500, 'Paid', 1, '2019-11-19 11:37:37'),
(35, 'sale', '2019-11-20', 85, 0, 'Unpaid', 3, '2019-11-20 05:37:21'),
(36, 'sale', '2019-11-20', 85, 10000, 'Partially', 3, '2019-11-20 05:37:48'),
(37, 'sale', '2019-11-20', 85, 18500, 'Paid', 3, '2019-11-20 05:38:04');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(60) NOT NULL,
`password` varchar(30) NOT NULL,
`email` varchar(40) NOT NULL,
`address` varchar(100) NOT NULL,
`image` varchar(150) NOT NULL,
`created_at` datetime NOT NULL,
`created_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `email`, `address`, `image`, `created_at`, `created_by`) VALUES
(1, 'saifrehman', 'saif', 'saifrehman.6987@gmail.com', 'army public school', 'uploads/Anas Shafqat_emp_photo.jpg', '2019-06-28 09:00:00', 1),
(2, 'saif', 'saif', 'saifrehman.6987@gmail.com', 'Chack no 145', 'uploads/pp.jpg', '2019-10-24 06:53:32', 1),
(3, 'sadaqat', 'admin', 'sadaqat@gmail.com', 'abc', 'uploads/Capture.PNG', '2019-11-11 05:42:13', 2),
(5, 'adeel', 'adeel', 'adeel@gmail.com', 'ryk', 'uploads/PicsArt_05-31-01.15.19.jpg', '2019-11-20 05:34:16', 3);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
ADD PRIMARY KEY (`id`),
ADD KEY `created_by` (`created_by`);
--
-- Indexes for table `distributer`
--
ALTER TABLE `distributer`
ADD PRIMARY KEY (`id`),
ADD KEY `created_by` (`created_by`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `products_per_purchase_invoice`
--
ALTER TABLE `products_per_purchase_invoice`
ADD PRIMARY KEY (`id`),
ADD KEY `product_id` (`product_id`),
ADD KEY `purchase_invoice_id` (`purchase_invoice_id`);
--
-- Indexes for table `purchase_invoice`
--
ALTER TABLE `purchase_invoice`
ADD PRIMARY KEY (`id`),
ADD KEY `distributer_id` (`distributer_id`);
--
-- Indexes for table `sale_invoice`
--
ALTER TABLE `sale_invoice`
ADD PRIMARY KEY (`sale_id`);
--
-- Indexes for table `sale_invoice_product_details`
--
ALTER TABLE `sale_invoice_product_details`
ADD PRIMARY KEY (`sale_invoice_detail_id`);
--
-- Indexes for table `transection_details`
--
ALTER TABLE `transection_details`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `distributer`
--
ALTER TABLE `distributer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `products_per_purchase_invoice`
--
ALTER TABLE `products_per_purchase_invoice`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=86;
--
-- AUTO_INCREMENT for table `purchase_invoice`
--
ALTER TABLE `purchase_invoice`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
--
-- AUTO_INCREMENT for table `sale_invoice`
--
ALTER TABLE `sale_invoice`
MODIFY `sale_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=86;
--
-- AUTO_INCREMENT for table `sale_invoice_product_details`
--
ALTER TABLE `sale_invoice_product_details`
MODIFY `sale_invoice_detail_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=109;
--
-- AUTO_INCREMENT for table `transection_details`
--
ALTER TABLE `transection_details`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `customers`
--
ALTER TABLE `customers`
ADD CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);
--
-- Constraints for table `distributer`
--
ALTER TABLE `distributer`
ADD CONSTRAINT `distributer_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);
--
-- Constraints for table `products_per_purchase_invoice`
--
ALTER TABLE `products_per_purchase_invoice`
ADD CONSTRAINT `products_per_purchase_invoice_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`),
ADD CONSTRAINT `products_per_purchase_invoice_ibfk_2` FOREIGN KEY (`purchase_invoice_id`) REFERENCES `purchase_invoice` (`id`);
--
-- Constraints for table `purchase_invoice`
--
ALTER TABLE `purchase_invoice`
ADD CONSTRAINT `purchase_invoice_ibfk_1` FOREIGN KEY (`distributer_id`) REFERENCES `distributer` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Python | UTF-8 | 3,732 | 3.265625 | 3 | [
"MIT"
] | permissive | # Python 3.5.2 |Anaconda 4.2.0 (64-bit)|
# -*- coding: utf-8 -*-
"""
Last edited: 2017-09-13
Author: Jeremias Knoblauch (J.Knoblauch@warwick.ac.uk)
Forked by: Luke Shirley (L.Shirley@warwick.ac.uk)
Description: Implements class CpModel, the Changepoint model used by the
Bayesian Online CP detection. The objects of this class store the prior
information on the number of CPs as well as the prior distribution on the
location of the CPs.
Traditionally, both are contained in a single prior run-length
distribution that implicitly specifies them, see Adams & MacKay (2007)
"""
from scipy import stats
class CpModel:
"""A model for location and number of the CPs in a (spatio-)temporal model.
See Adams & MacKay (2007), or Fearnhead & Liu (2007) for details.
The implemented model here is the geometric distribution
Attributes:
intensity: float >0; specifying the CP intensity rate
Later additions:
boundary: (optional) boolean; specifying if we want steady state
probability (True) or if we assume that there is a CP at
0 (False), with the latter being the default
g: generic pmf (not necessarily geometric distribution) for CP
g_0: generic pmf corresponding to boundary condition
EPS: (static), with which precision we want to calculate the
resulting cdfs G and G_0 from g, g_0
"""
def __init__(self, intensity):
"""Initialize the CP object by specifying intensity and indicating if
you wish to use the steady state/advanced boundary conditions"""
self.intensity = intensity
self.cp_pmf = self.create_distribution()
def create_distribution(self):
"""Creates the CP distribution using the object properties.
NOTE: At this point, it just operates with the geometric distribution.
Once g and g_0 are allowed as input, this function handles the more
general case, too."""
return stats.geom(self.intensity)
def pmf(self, k):
"""Returns the changepoint pmf for having k time periods passing
between two CPs.
NOTE: At this point, it just operates with the geometric distribution.
Once g and g_0 are allowed as input, this function handles the more
general case, too."""
return self.cp_pmf.pmf(k)
def pmf_0(self, k):
"""Returns the cp pmf for the very first CP (i.e., we do not assume
that there is a CP at time point 0 with probability one)
NOTE: At this point, it just operates with the geometric distribution.
Once g and g_0 are allowed as input, this function handles the more
general case, too."""
if k ==0:
return 1
else:
return 0
def hazard(self, k):
"""Returns the changepoint hazard for r_t = k|r_{t-1} = k-1.
NOTE: At this point, it just operates with the geometric distribution.
Once g and g_0 are allowed as input, this function handles the more
general case, too."""
return 1.0/self.intensity #memorylessness of geometric distribution
def hazard_vector(self, k, m):
"""Returns the changepoint hazard for for r_t = l|r_{t-1} = l-1,
with l = k, k+1, k+2, ... m between two CPs. In the geometric case,
the hazard will be the same for all l.
NOTE: At this point, it just operates with the geometric distribution.
Once g and g_0 are allowed as input, this function handles the more
general case, too."""
return 1.0/self.intensity #memorylessness of geometric distribution
|
Python | UTF-8 | 1,140 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | import yaml
import argparse
from rf_client import *
# read config
with open("cfg/config.yaml", 'r') as yaml_file:
config = yaml.load(yaml_file)
# rfclient init
rfclient = RFClient(config)
rfclient.datasource = {"id": "6d03b24d-5a29-4004-a27f-3dda48e2eedb"}
rfclient.bands = [{
"number": 0,
"name": "Red",
"wavelength": [0, 100]
},
{
"number": 1,
"name": "Green",
"wavelength": [0, 100]
},
{
"number": 2,
"name": "Blue",
"wavelength": [0, 100]
}
]
def main(scene_id, url):
scene = rfclient.create_scene(scene_id, url)
print(scene.id)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Generate new TMS links for each image')
parser.add_argument('--scene_id', help='The scene id of the image')
parser.add_argument('--url', help='The url of the image')
args = parser.parse_args()
main(args.scene_id, args.url)
|
Python | UTF-8 | 478 | 2.9375 | 3 | [] | no_license | import sys
from operator import itemgetter
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().split())
def lmi(): return list(map(int, input().split()))
def lmif(n): return [list(map(int, input().split())) for _ in range(n)]
def ss(): return input().split()
def main():
a, b = ss()
sa = a*int(b)
sb = b*int(a)
if sa <= sb:
print(sa)
else:
print(sb)
return
main()
|
C# | UTF-8 | 1,694 | 2.515625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
// VARIABLES
public float zoomSpeed = 4.0f;
public float moveSpeed = 4.0f;
private float verMoveSpeed = 0.0f;
private float horMoveSpeed = 0.0f;
private float zoom = -10.0f;
private float zoomMin = -10.0f;
private float zoomMax = -40.0f;
private float xMin = 0.0f;
private float xMax = 0.0f;
private float yMin = 0.0f;
private float yMax = 0.0f;
private BoardGenerator map;
// EXECUTION METHODS
private void Start()
{
map = FindObjectOfType<BoardGenerator> ();
xMin = -(map.collumns / 2 - 5);
xMax = map.collumns / 2 - 5;
yMin = -(map.rows / 2 - 5);
yMax = map.rows / 2 - 5;
this.transform.position = map.tiles [map.collumns / 2, map.rows / 2].transform.position;
}
private void Update()
{
ZoomHandler ();
PositionHandler ();
}
// METHODS
private void ZoomHandler()
{
// Zoom in based on mouse wheel
zoom += Input.GetAxis ("Mouse ScrollWheel") * zoomSpeed;
// Clamp the zoom
zoom = Mathf.Clamp (zoom, zoomMax, zoomMin);
// Update the camera location based on the zoom
this.transform.localPosition = new Vector3 (this.transform.localPosition.x, this.transform.localPosition.y, zoom);
}
private void PositionHandler()
{
horMoveSpeed += Input.GetAxisRaw ("Horizontal") * Time.deltaTime * moveSpeed;
verMoveSpeed += Input.GetAxisRaw ("Vertical") * Time.deltaTime * moveSpeed;
horMoveSpeed = Mathf.Clamp (horMoveSpeed, xMin, xMax);
verMoveSpeed = Mathf.Clamp (verMoveSpeed, yMin, yMax);
this.transform.position = new Vector3 (horMoveSpeed, verMoveSpeed, this.transform.position.z);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.