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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 18,852 | 3.1875 | 3 |
[] |
no_license
|
# 1 监视集群组件状态
## 1.1 概述
一旦你有一个可以运行的集群之后,你就可以在集群里执行一些命令来监控集群中的健康状态、对进群进行一些运维操作等。Ceph中提供了一个核心命令ceph,通常默认会被安装在\/usr\/bin\/目录下。Ceph中所有组件的操作,都通过它提供的子命令完成。同时,它也提供两种访问模式,交互模式和普通命令行模式,如下所示:
ceph> health
```
EALTH_OK
ceph> status
cluster 8b9a9a32-c11b-4719-95fd-8c9aa4730cc9
health HEALTH_OK
monmap e5: 3 mons at {ceph-01=192.168.0.5:6789/0,ceph-02=192.168.0.6:6789/0,ceph-03=192.168.0.7:6789/0}
election epoch 32, quorum 0,1,2 ceph-01,ceph-02,ceph-03
osdmap e42: 3 osds: 3 up, 3 in
pgmap v70: 64 pgs, 1 pools, 0 bytes data, 0 objects
103 MB used, 79726 MB / 79829 MB avail
64 active+clean
ceph> mon_status
{"name":"ceph-02","rank":1,"state":"peon","election_epoch":32,"quorum":[0,1,2],"outside_quorum":[],"extra_probe_peers":[],"sync_provider":[],"monmap":{"epoch":5,"fsid":"8b9a9a32-c11b-4719-95fd-8c9aa4730cc9","modified":"2016-06-22 11:21:01.792270","created":"0.000000","mons":[{"rank":0,"name":"ceph-01","addr":"192.168.0.5:6789\/0"},{"rank":1,"name":"ceph-02","addr":"192.168.0.6:6789\/0"},{"rank":2,"name":"ceph-03","addr":"192.168.0.7:6789\/0"}]}}
```
一般交互模式的命令,在普通命令行下都能完成。并且普通命令行支持不同的format,可以使得输出结果更加的便于阅读,比如上面执行的mon\_status子命令,通过普通命令行能够显示的更加优雅。
```
# ceph mon_status
-f json-pretty
{
"name": "ceph-03",
"rank": 2,
"state": "peon",
"election_epoch": 32,
"quorum": [
0,
1,
2
],
"outside_quorum": [],
"extra_probe_peers": [],
"sync_provider": [],
"monmap": {
"epoch": 5,
"fsid": "8b9a9a32-c11b-4719-95fd-8c9aa4730cc9",
"modified": "2016-06-22 11:21:01.792270",
"created": "0.000000",
"mons": [
{
"rank": 0,
"name": "ceph-01",
"addr": "192.168.0.5:6789\/0"
},
{
"rank": 1,
"name": "ceph-02",
"addr": "192.168.0.6:6789\/0"
},
{
"rank": 2,
"name": "ceph-03",
"addr": "192.168.0.7:6789\/0"
}
]
}
}
```
目前ceph的命令输出支持以下几种格式:
\# ceph --help\|grep format
-f {json,json-pretty,xml,xml-pretty,plain}, --format {json,json-pretty,xml,xml-pretty,plain}
以下将以普通命令行的方式,介绍集群中常用的命令。
## 1.2 集群状态检查
基本的集群是由Monitor和OSD组成的,如果您使用了对象存储服务那么集群中还有RGW服务的存在,如果您使用了文件服务则还需要注意MDS的状态。在使用集群提供的存储服务之前,要确保集群的整体状态是正常的,具体可以通过以下命令完成:
```
# ceph health
HEALTH_OK
```
当然,如果集群当前状态不是OK的,可以通过以下命令显示较为详细的信息。
```
# ceph health detail
```
如果您在安装时,修改了配置文件或者密钥的路径,那么在执行命令时需要指定现在的路径。
```
# ceph -c /path/to/conf -k /path/to/keyring health
```
如果要观察集群中当前发生的事件,可以通过以下命令查看
```
# ceph -w
cluster 8b9a9a32-c11b-4719-95fd-8c9aa4730cc9
health HEALTH_OK
monmap e5: 3 mons at
{ceph-01=192.168.0.5:6789/0,ceph-02=192.168.0.6:6789/0,ceph-03=192.168.0.7:6789/0}
election epoch 32, quorum 0,1,2 ceph-01,ceph-02,ceph-03
osdmap e46: 3 osds: 3 up, 3 in
pgmap v86: 64 pgs, 1 pools, 24 bytes data, 3 objects
104 MB used, 79725 MB / 79829 MB avail
64 active+clean
2016-06-22 15:47:55.718646 mon.0 [INF] pgmap v86: 64 pgs: 64 active+clean; 24 bytes data,
104 MB used, 79725 MB / 79829 MB avail
2016-06-22 15:48:15.164651 mon.0 [INF] pgmap v87: 64 pgs: 64 active+clean; 277 MB data, 104 MB used, 79725
MB / 79829 MB avail; 39 B/s rd, 5694 B/s wr, 2 op/s
2016-06-22 15:48:16.230646 mon.0 [INF] pgmap v88: 64 pgs: 64 active+clean; 669 MB data,
115 MB used, 79714 MB / 79829 MB avail; 199 B/s rd, 68381 B/s wr, 33 op/s
2016-06-22 15:48:20.167758 mon.0 [INF] pgmap v89: 64 pgs: 64 active+clean; 1085 MB data,
128 MB used, 79701 MB / 79829 MB avail; 3890 B/s rd, 338 kB/s wr, 173 op/s
2016-06-22 15:48:21.241525 mon.0 [INF] pgmap v90: 64 pgs: 64 active+clean; 1398 MB data,
137 MB used, 79692 MB / 79829 MB avail; 3887 B/s rd, 340 kB/s wr, 174 op/s
```
输出的信息里包括:
* 集群唯一标识符
* 集群健康状况
* monitor视图版本、monitor个数以及每个monitor的信息、monitor法定小组选举版本以及当前法定小组成员
* osd视图版本、当前osd个数以及状态
* pg视图版本、pg个数、存储池个数以及当前存储池中的数据和对象数量的统计。
* pg的状态信息
如果集群的健康状况是HEALTH\_OK,则集群的状态一定是正常的,接下来介绍monitor、osd、pg的视图状态。
### **1.2.1 Monitor状态检查**
Monitor作为集群的管理者维护了整个集群的状态信息,并保证在某一时刻集群中所有信息大家都是达成一致的,所以在生产的集群中monitor一般会通过设置多个来避免单点故障问题。如果您的集群中有超过1个的monitor时,那么多个monitor会形成一个法定小组,当小组内的成员必须超过monitor个数的一半时,整个集群才能对外提供服务。
要检查当前集群中的monitor,可以通过以下命令中的任意一个完成:
```
# ceph mon stat
# ceph -s
# ceph status
```
以上命令也包含了monitor法定小组的基本信息,如果需要获得更为详细的法定小组的信息,可以通过以下命令:
```
# ceph
quorum_status -f json-pretty
{
"election_epoch": 32,
"quorum": [
0,
1,
2
],
"quorum_names": [
"ceph-01",
"ceph-02",
"ceph-03"
],
"quorum_leader_name": "ceph-01",
"monmap": {
"epoch": 5,
"fsid": "8b9a9a32-c11b-4719-95fd-8c9aa4730cc9",
"modified": "2016-06-22 11:21:01.792270",
"created": "0.000000",
"mons": [
{
"rank": 0,
"name": "ceph-01",
"addr": "192.168.0.5:6789\/0"
},
{
"rank": 1,
"name": "ceph-02",
"addr": "192.168.0.6:6789\/0"
},
{
"rank": 2,
"name": "ceph-03",
"addr": "192.168.0.7:6789\/0"
}
]
}
}
```
### **1.2.2 OSD的状态检查**
OSD作为集群数据的存储者,它的状态分为两个维度。可以是活着且在运行(up)或挂了且不在运行(down)也可以是在集群内(in)或集群外(out)、也。如果一个OSD活着,它也可以是in(可以读写数据)或者 out 集群。如果它以前是in但最近out了,Ceph 会把其归置组迁移到其他 OSD 。如果一个OSD out 了, CRUSH 就不会再分配归置组给它。如果它挂了(down)并且在规定的时间内没有恢复成up,其状态也会被置为out 。

OSD的状态可以通过以下命令获得:
```
# ceph osd stat
# ceph -s
# ceph status
```
当一个集群正常工作是,它的in的OSD个数应该是等于up的OSD个数。如果in的OSD个数大于up的OSD个数,说明有OSD的状态为down,那么你可以通过service ceph start osd.\[instance\]的命令启动它.
另外,通过以下命令也可以显示OSD的状态:
```
# ceph osd tree
ID WEIGHT TYPE NAME UP/DOWN REWEIGHT PRIMARY-AFFINITY
-1 0.07999 root default
-2 0.01999 host ceph-02
0 0.01999 osd.0 up 1.00000 1.00000
-3 0.03000 host ceph-01
3 0.03000 osd.3 up 1.00000 1.00000
-4 0.03000 host ceph-03
4 0.03000 osd.4 up 1.00000 1.00000
```
其中reweight列的值表示了OUT\/IN的状态。如果你精心设计了CRUSH分级结构(后面会介绍如何管理CRUSH分级结构),那么当OSD出现故障的时候从这里你能快速找到OSD的物理位置,加快排查。
### **1.2.3 PG的状态检查**
当你在检查集群状态时,发现集群不处于HEALTH\_OK状态,并且所有的Monitor和OSD的状态都是正常时,你还需要确认PG的状态。
PG是Ceph数据存储的最小管理单元,在创建资源池时需要指定资源池包含的PG的个数。当向资源池中写入数据时,首先这些数据会被切分成一个或者多个Object,然后Object会通过Hash映射到一个或者多个PG上。PG经过CRUSH算法就会对应到一组OSD上,也就是PG中包含的Object最终会存储在这些OSD上。
可以通过以下命令查看,集群中所有PG的状态:
```
# ceph pg stat
v121: 64 pgs: 64 active+clean; 1398 MB data, 129 MB used, 79700 MB / 79829 MB avail
```
其中如果PG的状态均为active+clean,表示集群状态正常,如果包含以下几种状态,则说明集群正在恢复或者处于异常状态。
通过以下命令可以dump出集群中所有PG的详细信息:
```
# ceph pg dump
dumped all in format plain
version 127
stamp 2016-06-22 23:03:30.468568
last_osdmap_epoch 46
last_pg_scan 1
full_ratio 0.95
nearfull_ratio 0.85
pg_stat objects mip degr misp unf bytes log disklog state state_stamp v reported up up_primary acting acting_primary last_scrub scrub_stamp last_deep_scrub deep_scrub_stamp
0.22 14 0 0 0 0 31178752 17 17 active+clean 2016-06-22 15:43:51.085300 46'17 46:54 [4,3,0] 4 [4,3,0] 4 0'0 2016-06-21 23:29:16.926924 0'0 2016-06-21 23:29:16.926924
0.21 8 0 0 0 0 19513344 9 9 active+clean 2016-06-22 15:43:50.956897 46'9 46:35 [3,4,0] 3 [3,4,0] 3 0'0 2016-06-21 23:29:16.926923 0'0 2016-06-21
23:29:16.926923
0.20 12 0 0 0 0 28377088 14 14 active+clean 2016-06-22 15:43:50.956691 46'14 46:40 [3,0,4] 3 [3,0,4] 3 0'0 2016-06-21 23:29:16.926923 0'0 2016-06-21 23:29:16.926923
0.1f 9 0 0 0 0 24100864 9 9 active+clean 2016-06-22 15:43:51.085185 46'9 46:38 [4,0,3] 4 [4,0,3] 4 0'0 2016-06-21 23:29:16.926922 0'0 2016-06-21 23:29:16.926922
......
```
以上的输出结果比较难以阅读,一般我们会关注如下几列:
* pg\_stat,PG的唯一标识,以{poolid}.{pgid}的形式存在。通过ceph osd lspools可以查看pool以及poolid信息,pgid是一个16进制的数字。
* objects,当前PG中包含的object个数。
* state,PG当前的状态,如上例中active+clean,表示正常。
* v,PG的版本信息
* up\/acting , up\_primary\/acting\_primary,表示PG映射到的对应的up set 和acting set OSD集合, 而up\_primary和acting\_primary分别指的是up set和acting set中的primary OSD。通常情况下,up set和acting set是相同的。up set中的OSD是PG通过CRUSH算法算出来的集合,而当up\_primary因为缺少数据而需要进行数据同步时,monitor会临时调整Primary OSD,从所有有数据的OSD中选择一个作为临时的Primary OSD,而这个临时的OSD set就叫做acting set,临时的Primary OSD就是acting\_primary。
如果想让输出结果可读性更高,可以使用json-pretty这种输出格式。
\# ceph pg dump -o {filename} -f json-pretty
另外,可以通过以下命令查看某个PG各阶段的具体状态。
```
# ceph pg 0.23 query
{
"state": "active+clean",
"snap_trimq": "[]",
"epoch": 46,
"up": [
3,
4,
0
],
"acting": [
3,
4,
0
],
"actingbackfill": [
"0",
"3",
"4"
],
"info": {
"pgid": "0.23",
"last_update": "46'11",
"last_complete": "46'11",
...
"history": {
"epoch_created": 1,
"last_epoch_started": 44,
...
"last_deep_scrub_stamp": "2016-06-21 23:29:16.926924",
"last_clean_scrub_stamp": "0.000000"
},
"stats": {
"version": "46'11",
"reported_seq": "37",
"reported_epoch": "46",
"state": "active+clean",
...
"stats_invalid": "0",
"stat_sum": {
"num_bytes": 19570688,
"num_objects": 8,
...
"num_bytes_hit_set_archive": 0
},
"up": [
3,
4,
0
],
"acting": [
3,
4,
0
],
"blocked_by": [],
"up_primary": 3,
"acting_primary": 3
},
"empty": 0,
...
"hit_set_history": {
"current_last_update": "0'0",
...
"history": []
}
},
"peer_info": [
{
"peer": "0",
"pgid": "0.23",
"last_update": "46'11",
"last_complete": "46'11",
"log_tail": "0'0",
...
}
],
...
}
```
以上的输出结果相比于ceph pg dump的输出又多了几项:
* info,纪录了主PG的详细信息,包括PG上次处于数据完成同步的版本号(last\_complete)和上次已经完成本地更新的版本号(last\_update),这两个主要用于PG之间数据一致性的协商。还有PG的一些历史信息以及统计信息。
* peer\_info,如果采用副本机制,这部分会纪录所有peer的信息,其内容和主PG的内容类似。
* recovery\_state,纪录了recovery过程中进行recovery和backfill的进程以及参与者信息,同时还包含PG进行scrub的信息。每个PG都会维护一个pg\_log,用于纪录该PG上所产生的更新操作(写、删除、更新)等,如果recovery过程,能够通过比对所有peer的pg\_log达成一致进行恢复,那么就进行recovery操作,如果peer之间数据差异较大,无法通过pg\_log计算出数据差异,则主PG会主导缺失数据的PG进行backfill操作。
这里再介绍一下peer,在采用3副本机制的集群中,写入数据时,PG必须处于active、而且应该是clean状态。为了确保所有副本之间的数据是一致的,一般PG的主OSD,也就是PG对应的acting set中的第一个OSD,会进行协调管理的工作,和第二、第三个OSD(即上面提到的peer)建立连接,并且保证这三个OSD上的PG的当前状态达成一致。
在检查PG的状态时,并不是一直处于active+clean的状态,当集群异常时,你也会看到其他的一些状态。
这里介绍一下常见的状态:
* creating,当你创建存储池时,会创建存储池对应的PG。Ceph在创建PG时,对应的PG会进入creating状态。PG会在的acting set中所有的OSD上都进行创建。
* peering,一旦所有PG都创建成功之后,主OSD将会和它的peer进行同步,即进入peering状态。peering过程主要是保证所有PG中的数据能够协商一致,生成一份权威数据,并且按照这个权威数据进行数据同步。peering过程结束之后,PG的状态会被设置为active。
* active,说明PG中的数据已经比对出来了,如果主OSD上的PG和peer上的PG的数据一致,则这个PG将会进入clean状态。如果有数据不一致,主OSD上的PG知道哪些peer上有数据缺失,它会主导其他peer的数据恢复,这时PG可能会进入recovery或者backfill状态。
* recovery,如果主OSD上的PG能够通过pg\_log进行恢复,则PG会进入recovery状态。
* backfill,如果主OSD上的PG不能通过pg\_log进行恢复,则PG会进入backfill状态,主PG会依次比对所有PG的数据,如果不一致,则peer会进行全量数据恢复。
* degraded,如果存放PG数据的OSD出现Down的状态时,对应的PG会进入degraded状态。
* undersized,该状态和degraded的类似,唯一的区别是处于degraded的PG,存放它的数据的OSD可以在整个集群中找到副本个,而处于undersized状态的PG,则找不到。
* remapped,负责某一个PG的acting set变更时,数据要从旧的OSD set迁移到新的OSD set中去。新的主OSD还需要一段时间完成数据同步之后,才能提供服务,所以老的主OSD还要持续提供服务,这时PG会处于remapped状态。
* stale,当存储PG的所有OSD都处于Down状态时,PG会进入该状态。
* down+peering,PG在peering过程无法获取所有PG的信息。
* incomplete,PG无法在peering过程中获取权威log信息。
### **1.2.4 MDS的状态检查**
如果您开启了CephFS的服务,那么您还需要检查MDS的服务状态。MDS维护了CephFS文件系统中的层级结构以及文件的一些访问权限等信息。可以通过如下命令查看集群MDS的信息。
```
# ceph -s
# ceph mds stat
```
注意,如果您只是启动了MDS服务,但没有创建任何文件系统时,mds是不工作的,即不处于active状态。所以这个时候,您在ceph -s的输出看不到mds的信息,在ceph mds stat的输出中会看到没有up的mds。
```
# ceph mds stat
e9: 0/0/0 up
```
当您执行如下命令创建了一个文件系统之后,您会发现mds的状态变为up:active了。
```
# ceph osd pool create cephfs_data 64 64
# ceph osd pool create cephfs_metadata 64 64
# ceph fs new cephfs cephfs_metadata cephfs_data
# ceph mds stat
e13: 1/1/1 up {0=ceph-03=up:active}
```
当然您也可以通过如下命令查看所有mds的详细信息。
```
# ceph mds dump
dumped mdsmap epoch 13
epoch 13
flags 0
created 2016-06-23 19:06:14.132631
modified 2016-06-23 19:06:16.326815
tableserver 0
root 0
session_timeout 60
session_autoclose 300
max_file_size 1099511627776
last_failure 0
last_failure_osd_epoch 0
compat compat={},rocompat={},incompat={1=base v0.20,2=client writeable ranges,3=default file layouts on dirs,4=dir inode in separate object,5=mds uses versioned encoding,6=dirfrag is stored in omap,8=no anchor table}
max_mds 1
in 0
up {0=74594}
failed
stopped
data_pools 2
metadata_pool 3
inline_data disabled
74594: 192.168.0.7:6804/3779 'ceph-03' mds.0.2 up:active seq 75
```
这里介绍一下MDS常见的几种状态:
* up:active,正常状态。
* up:active\(laggy or crashed\),有MDS进程挂掉了。
* failed
* slave
|
TypeScript
|
UTF-8
| 591 | 3.828125 | 4 |
[] |
no_license
|
// enum类型是对JavaScript标准数据类型的一个补充,使用枚举类型可以为一组数值赋予友好的名字
enum Color { // 默认情况下,从0开始为元素编号。 你也可以手动的指定成员的数值
Red,
Blue,
Green
}
/* 枚举ts会编译成一个对象
var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Blue"] = 1] = "Blue";
Color[Color["Green"] = 2] = "Green";
})(Color || (Color = {}));
*/
let c: Color = Color.Green;
console.log(c)
enum promiseType {
Pendding = 1,
Resolved,
Rejected
}
|
Python
|
UTF-8
| 9,500 | 3.34375 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
""" audio.py: Utilities for dealing with audio files
"""
from pathlib import Path
import io
import librosa
import soundfile
import numpy as np
import pandas as pd
import warnings
class OpsoLoadAudioInputError(Exception):
""" Custom exception indicating we can't load input
"""
pass
class OpsoLoadAudioInputTooLong(Exception):
""" Custom exception indicating length of audio is too long
"""
pass
class Audio:
""" Container for audio samples
"""
__slots__ = ("samples", "sample_rate")
def __init__(self, samples, sample_rate):
# Do not move these lines; it will break Pytorch training
self.samples = samples
self.sample_rate = sample_rate
samples_error = None
if not isinstance(self.samples, np.ndarray):
samples_error = (
"Initializing an Audio object requires samples to be a numpy array"
)
try:
self.sample_rate = int(self.sample_rate)
except ValueError:
sample_rate_error = f"Initializing an Audio object requires an integer sample_rate, got `{sample_rate}`"
if samples_error:
raise ValueError(
f"Audio initialization failed with:\n{samples_error}\n{sample_rate_error}"
)
raise ValueError(f"Audio initialization failed with:\n{sample_rate_error}")
if samples_error:
raise ValueError(f"Audio initialization failed with:\n{samples_error}")
@classmethod
def from_file(
cls, path, sample_rate=None, max_duration=None, resample_type="kaiser_fast"
):
""" Load audio from files
Deal with the various possible input types to load an audio
file and generate a spectrogram
Args:
path (str, Path): path to an audio file
sample_rate (int, None): resample audio with value and resample_type,
if None use source sample_rate (default: None)
resample_type: method used to resample_type (default: kaiser_fast)
max_duration: the maximum length of an input file,
None is no maximum (default: None)
Returns:
Audio: attributes samples and sample_rate
"""
if max_duration:
if librosa.get_duration(filename=path) > max_duration:
raise OpsoLoadAudioInputTooLong()
warnings.filterwarnings("ignore")
samples, sr = librosa.load(
path, sr=sample_rate, res_type=resample_type, mono=True
)
warnings.resetwarnings()
return cls(samples=samples, sample_rate=sr)
@classmethod
def from_bytesio(cls, bytesio, sample_rate=None, resample_type="kaiser_fast"):
"""...
"""
samples, sr = soundfile.read(bytesio)
if sample_rate:
samples = librosa.resample(samples, sr, sample_rate, res_type=resample_type)
sr = sample_rate
return cls(samples, sr)
def __repr__(self):
return f"<Audio(samples={self.samples.shape}, sample_rate={self.sample_rate})>"
def trim(self, start_time, end_time):
""" trim Audio object in time
Args:
start_time: time in seconds for start of extracted clip
end_time: time in seconds for end of extracted clip
Returns:
a new Audio object containing samples from start_time to end_time
"""
start_sample = self.time_to_sample(start_time)
end_sample = self.time_to_sample(end_time)
samples_trimmed = self.samples[start_sample:end_sample]
return Audio(samples_trimmed, self.sample_rate)
def extend(self, length):
""" Extend audio file by looping it
Args:
length: the final length in seconds of the extended file
Returns:
a new Audio object of the desired length
"""
total_samples_needed = round(length * self.sample_rate)
samples_extended = np.resize(self.samples, total_samples_needed)
return Audio(samples_extended, self.sample_rate)
def time_to_sample(self, time):
""" Given a time, convert it to the corresponding sample
Args:
time: The time to multiply with the sample_rate
Returns:
sample: The rounded sample
"""
return round(time * self.sample_rate)
def bandpass(self, low_f, high_f, order=9):
""" bandpass audio signal frequencies
uses a phase-preserving algorithm (scipy.signal's butter and solfiltfilt)
Args:
low_f: low frequency cutoff (-3 dB) in Hz of bandpass filter
high_f: high frequency cutoff (-3 dB) in Hz of bandpass filter
order: butterworth filter order (integer) ~= steepness of cutoff
"""
from opensoundscape.audio_tools import bandpass_filter
if low_f <= 0:
raise ValueError("low_f must be greater than zero")
if high_f >= self.sample_rate / 2:
raise ValueError("high_f must be less than sample_rate/2")
filtered_samples = bandpass_filter(
self.samples, low_f, high_f, self.sample_rate, order=9
)
return Audio(filtered_samples, self.sample_rate)
# can act on an audio file and be moved into Audio class
def spectrum(self):
"""create frequency spectrum from an Audio object using fft
Args:
self
Returns:
fft, frequencies
"""
from scipy.fftpack import fft
from scipy.fft import fftfreq
# Compute the fft (fast fourier transform) of the selected clip
N = len(self.samples)
T = 1 / self.sample_rate
fft = fft(self.samples)
freq = fftfreq(N, d=T) # the frequencies corresponding to fft bins
# remove negative frequencies and scale magnitude by 2.0/N:
fft = 2.0 / N * fft[0 : int(N / 2)]
frequencies = freq[0 : int(N / 2)]
fft = np.abs(fft)
return fft, frequencies
def save(self, path):
"""save Audio to file
Args:
path: destination for output
"""
from soundfile import write
write(path, self.samples, self.sample_rate)
def duration(self):
""" Return duration of Audio
Output:
duration (float): The duration of the Audio
"""
return len(self.samples) / self.sample_rate
def split_and_save(
self,
clip_length,
destination,
name,
create_log=True,
final_clip=None, # None, "short", "full"
dry=False,
):
""" Split audio into clips and save to disk
Splits the current audio object into constant-length clips and saves each one to a .wav file.
Args:
clip_length: length of resulting clips, in seconds
destination: a path to a directory where .wav clips will be saved
name: the name of the audio file (start and end times will be appended)
create_log: if True, a .csv file with the name, start time, and end time of each clip is created in destination
final_clip: how to treat the end of the file when less than clip_length remains
- None (default): discard audio
- "short": save whatever audio is left as a clip
- "full": save a clip of length clip_length that ends at the end of the file (duplicating some data)
dry: if True, do not save .wav files, but do create a log file (default: False)
Returns:
clip_df: dataframe containing clip names, start times, and end times
Effects:
writes a .wav file for each clip
writes a log file (.csv) with clip start and end times if create_log is True
"""
clip_df = pd.DataFrame(columns=["start_time", "end_time"])
clip_df.index.name = "file"
total_length = self.duration()
destination = Path(destination)
# number of full clips can we make without re-using audio
nsplits = int(total_length / clip_length)
if nsplits < 1:
warnings.warn(
f"clip_length {clip_length} was longer than total length {total_length}"
)
# extract and save full clips
for i in range(nsplits):
start_t = i * clip_length
end_t = (i + 1) * clip_length
clip_name = f"{name}_{start_t}s-{end_t}s.wav"
if not dry:
self.trim(start_t, end_t).save(destination.joinpath(clip_name))
clip_df.at[clip_name] = [start_t, end_t]
# possibly extract one more clip at the end of the file
last_full_clip_end_t = nsplits * clip_length
if last_full_clip_end_t < total_length and final_clip is not None:
# there was extra audio left?
end_t = total_length
if final_clip == "short":
start_t = last_full_clip_end_t
elif final_clip == "full":
start_t = end_t - clip_length
clip_name = f"{name}_{start_t}s-{end_t}s.wav"
if not dry:
self.trim(start_t, end_t).save(destination.joinpath(clip_name))
clip_df.at[clip_name] = [start_t, end_t]
if create_log:
clip_df.to_csv(destination.joinpath(f"{name}_clip_log.csv"))
return clip_df
|
C++
|
UTF-8
| 719 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#pragma once
namespace recipe_4_02
{
#define MAKE_STR2(x) #x
#define MAKE_STR(x) MAKE_STR2(x)
#define MERGE2(x, y) x##y
#define MERGE(x, y) MERGE2(x, y)
#define DECL_MAKE(x) DECL_MAKE2(x)
#define DECL_MAKE2(x) x* make##_##x() { return new x(); }
#define NUMBER 42
struct bar {};
struct foo {};
DECL_MAKE(foo)
DECL_MAKE(bar)
void execute()
{
std::string s1 { MAKE_STR(sample) }; // s1 = "sample"
std::string s2 { MAKE_STR2(sample) }; // s2 = "sample"
std::string s3{ MAKE_STR(NUMBER) }; // s3 = "42"
std::string s4{ MAKE_STR2(NUMBER) }; // s4 = "NUMBER"
auto f = make_foo(); // f is a foo*
auto b = make_bar(); // b is a bar*
}
}
|
Java
|
UTF-8
| 1,917 | 1.851563 | 2 |
[] |
no_license
|
package com.serviceindeed.yike.yikemo.mapper;
import com.serviceindeed.yike.yikemo.domain.User;
import com.serviceindeed.yike.yikemo.domain.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int deleteByPrimaryKey(Long userId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int insertSelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
User selectByPrimaryKey(Long userId);
User selectByIfkCode(String ifkCode);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_user
*
* @mbg.generated
*/
int updateByPrimaryKey(User record);
List<User> getAllUsers(User user);
/**
* 根据用户Id查询用户信息
* @param userId
* @return
*/
User selectUserInfoById(@Param(value="userId")Long userId);
/**
* 查询平台用户主要信息
* @param userId
* @return
*/
UserInfo queryPlatformUserInfo(@Param(value="userId")Long userId);
}
|
Python
|
UTF-8
| 6,267 | 2.796875 | 3 |
[] |
no_license
|
from requests.auth import _basic_auth_str
from termcolor import colored
import unittest
import requests
class SecurityTests(unittest.TestCase):
def setUp(self):
self.PORT = 5000
self.API_URL = f"http://127.0.0.1:{self.PORT}/"
self.customers = [
{'username': 'applicant1', 'password': 'applicant1'},
{'username': 'applicant2', 'password': 'applicant2'},
{'username': 'applicant3', 'password': 'applicant3'}
]
self.customer_access_tokens = []
def test_9_new_loan_without_token(self):
test_name = "Requesting New Loan without authorized Token"
try:
# Making a call to a endpoint without a authorized token
resp = requests.post("{}/{}".format(self.API_URL, "new-loan"))
self.assertEqual(resp.status_code, 401)
self.assertTrue(b'Missing token' in resp.content)
print(colored(f"\u2713 Test 9: {test_name} Passed", "green"))
except:
print(colored(f"\u2717 Test 9: {test_name} Failed", "red"))
def test_10_new_loan_with_invalid_token(self):
test_name = "Requesting New Loan with invalid Token"
try:
# Making a call to a endpoint with a invalid token
resp = requests.post("{}/{}".format(self.API_URL, "new-loan"),
headers={'x-access-token': 'random_string_as_token'})
self.assertEqual(resp.status_code, 401)
self.assertTrue(b'Invalid token' in resp.content)
print(colored(f"\u2713 Test 10: {test_name} Passed", "green"))
except:
print(colored(f"\u2717 Test 10: {test_name} Failed", "red"))
def test_11_customer_access_admin(self):
test_name = "Customer trying to access Admin endpoints"
try:
# Accessing unauthorised endpoints
for customer in self.customers:
resp = requests.post("{}/{}".format(self.API_URL, "login"),
headers={"Authorization": _basic_auth_str(customer['username'], customer['password'])})
data = resp.json()
self.customer_access_tokens.append(data['token'])
resp = requests.get("{}/{}".format(self.API_URL, "/show-users"),
headers={
"x-access-token": self.customer_access_tokens[0]},
params={"user_type": "all"})
self.assertEqual(resp.status_code, 401)
self.assertTrue(
b"You are not authorized to open this page" in resp.content)
print(colored(f"\u2713 Test 11: {test_name} Passed", "green"))
except:
print(colored(f"\u2717 Test 11: {test_name} Failed", "red"))
def test_12_agent_access_admin(self):
test_name = "Agent trying to access Admin endpoints"
try:
resp = requests.post("{}/{}".format(self.API_URL, "login"),
headers={"Authorization": _basic_auth_str("agent1", "agent1")})
token = resp.json()['token']
resp = requests.get(
"{}/{}".format(self.API_URL, "/approve-loan/3"),
headers={"x-access-token": token})
self.assertEqual(resp.status_code, 401)
print(colored(f"\u2713 Test 12: {test_name} Passed", "green"))
except Exception as e:
print(e)
print(colored(f"\u2717 Test 12: {test_name} Failed", "red"))
def test_13_customer_can_only_view_his_loans(self):
test_name = "Customer can only views his own loans"
loans_by_applicant_2 = [
{"loan_amount": 10000, "duration": 12, "loan_type": "HOME"},
{"loan_amount": 20000, "duration": 24, "loan_type": "CAR"},
{"loan_amount": 30000, "duration": 36, "loan_type": "PERSONAL"}
]
loans_by_applicant_3 = [
{"loan_amount": 10000, "duration": 12, "loan_type": "PERSONAL"},
{"loan_amount": 20000, "duration": 24, "loan_type": "CAR"},
]
for customer in self.customers:
resp = requests.post("{}/{}".format(self.API_URL, "login"),
headers={"Authorization": _basic_auth_str(customer['username'], customer['password'])})
data = resp.json()
self.customer_access_tokens.append(data['token'])
try:
for loan in loans_by_applicant_2:
resp = requests.post("{}/{}".format(self.API_URL, "new-loan"),
headers={
"x-access-token": self.customer_access_tokens[1]},
json=loan)
for loan in loans_by_applicant_3:
resp = requests.post("{}/{}".format(self.API_URL, "new-loan"),
headers={
"x-access-token": self.customer_access_tokens[2]},
json=loan)
loans_by_applicant_2 = requests.get("{}/{}".format(self.API_URL, "show-loans"),
headers={"x-access-token": self.customer_access_tokens[1]})
loans_by_applicant_3 = requests.get("{}/{}".format(self.API_URL, "show-loans"),
headers={"x-access-token": self.customer_access_tokens[2]})
self.assertEqual(loans_by_applicant_2.status_code, 200)
self.assertEqual(loans_by_applicant_3.status_code, 200)
# Checking number of loan application by applicants
# After adding these loans, applicant2 has total 4 loans and
# applicant3 has 3 loans
self.assertEqual(len(loans_by_applicant_2.json()['Loans']), 4)
self.assertEqual(len(loans_by_applicant_3.json()['Loans']), 3)
print(colored(f"\u2713 Test 13: {test_name} Passed", "green"))
except Exception as e:
print(e)
print(colored(f"\u2717 Test 13: {test_name} Failed", "red"))
if __name__ == '__main__':
unittest.main()
|
Swift
|
UTF-8
| 968 | 2.671875 | 3 |
[] |
no_license
|
//
// UIViewControllerExtension.swift
// Tribe
//
// Created by Vahagn Gevorgyan on 13/10/2018.
// Copyright © 2018 Vahagn Gevorgyan. All rights reserved.
//
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc private func dismissKeyboard() {
view.endEditing(true)
}
func alert(title: String, message: String? = nil, action: (() -> ())? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (UIAlertAction) in
action?()
}
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
|
Java
|
UTF-8
| 2,602 | 2.53125 | 3 |
[] |
no_license
|
package br.cnpem.gef.palette;
import org.eclipse.gef.palette.CombinedTemplateCreationEntry;
import org.eclipse.gef.palette.ConnectionCreationToolEntry;
import org.eclipse.gef.palette.CreationToolEntry;
import org.eclipse.gef.palette.PaletteGroup;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.SelectionToolEntry;
import br.cnpem.gef.golpe.CnpemPlugin;
import br.cnpem.gef.model.BBBFactory;
import br.cnpem.gef.model.BBGFactory;
import br.cnpem.gef.model.ConnectionFactory;
import br.cnpem.gef.model.HostFactory;
import br.cnpem.gef.model.NetworkInterfaceFactory;
import br.cnpem.gef.model.PVItemFactory;
import br.cnpem.gef.model.SwitchFactory;
public class EditorPalette extends PaletteRoot {
private PaletteGroup _group;
public EditorPalette (){
addGroup();
_group.setVisible(true);
addSelectionTool();
addHostTool();
ConnectionCreationToolEntry entry = new ConnectionCreationToolEntry("Link", "Creates a new link", new ConnectionFactory(), null, null);
_group.add(entry);
}
private void addSelectionTool() {
SelectionToolEntry entry = new SelectionToolEntry();
_group.add(entry);
setDefaultEntry(entry);
}
private void addGroup() {
_group = new PaletteGroup("New hosts");
add(_group);
}
private void addHostTool() {
CreationToolEntry entry_bbb = new CombinedTemplateCreationEntry("BeagleBone Black ", "Create a new BBB", new BBBFactory(), CnpemPlugin.getDefault().getImageRegistry().getDescriptor(CnpemPlugin.BBB_ICON_ID), null),
entry_bbg = new CombinedTemplateCreationEntry("BeagleBone Green ", "Create a new BBG", new BBGFactory(), CnpemPlugin.getDefault().getImageRegistry().getDescriptor(CnpemPlugin.BBG_ICON_ID), null),
entry_generic = new CombinedTemplateCreationEntry("Generic device", "Create a new device", new HostFactory(), CnpemPlugin.getDefault().getImageRegistry().getDescriptor(CnpemPlugin.GENERIC_ICON_ID), null),
entry_switch = new CombinedTemplateCreationEntry("Switch", "Create a new switch", new SwitchFactory(), CnpemPlugin.getDefault().getImageRegistry().getDescriptor(CnpemPlugin.SWITCH_ICON_ID), null),
entry_network_interface = new CombinedTemplateCreationEntry("Network Interface", "Create a new network interface", new NetworkInterfaceFactory(), null, null),
entry_pv = new CombinedTemplateCreationEntry("PV", "Create a new PV", new PVItemFactory(), null, null);
_group.add(entry_bbb);
_group.add(entry_bbg);
_group.add(entry_generic);
_group.add(entry_switch);
_group.add(entry_network_interface);
_group.add(entry_pv);
}
}
|
Java
|
UTF-8
| 5,970 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bbd;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author James Gamber
*/
public class BBDBeanAPITest extends BBDUnitTestCase {
private BBDBeanAPI instance =
new BBDBeanAPI("db","api","sql",BBDBeanAPITest.class,
new BBDAPIPrincipal("testuser", "testpw"));
/**
*
*/
public BBDBeanAPITest() {
}
/**
* Test of getStoredProcedureName method, of class BBDBeanAPI.
*/
@Test
public void getStoredProcedureName() {
System.out.println("getStoredProcedureName");
setTestMethod();
String expResult = "api";
String result = instance.getStoredProcedureName();
assertEquals(expResult, result);
}
/**
* Test of setStoredProcedureName method, of class BBDBeanAPI.
*/
@Test
public void setStoredProcedureName() {
System.out.println("setStoredProcedureName");
setTestMethod();
String storedProcedureName = "test99";
instance.setStoredProcedureName(storedProcedureName);
assertEquals(instance.getStoredProcedureName(), storedProcedureName);
}
/**
* Test of getDatabaseUsed method, of class BBDBeanAPI.
*/
@Test
public void getDatabaseUsed() {
System.out.println("getDatabaseUsed");
setTestMethod();
String expResult = "db";
String result = instance.getDatabaseUsed();
assertEquals(expResult, result);
}
/**
* Test of setDatabaseUsed method, of class BBDBeanAPI.
*/
@Test
public void setDatabaseUsed() {
System.out.println("setDatabaseUsed");
setTestMethod();
String databaseUsed = "db22";
instance.setDatabaseUsed(databaseUsed);
assertEquals(instance.getDatabaseUsed(), databaseUsed);
}
/**
* Test of getSQL method, of class BBDBeanAPI.
*/
@Test
public void getSQL() {
System.out.println("getSQL");
setTestMethod();
String expResult = "sql";
String result = instance.getSQL();
assertEquals(expResult, result);
}
/**
* Test of setSQL method, of class BBDBeanAPI.
*/
@Test
public void setSQL() {
System.out.println("setSQL");
setTestMethod();
String SQL = "sql99";
instance.setSQL(SQL);
assertEquals(instance.getSQL(), SQL);
}
/**
* Test of isDeprecated method, of class BBDBeanAPI.
*/
@Test
public void isDeprecated() {
System.out.println("isDeprecated");
setTestMethod();
boolean expResult = false;
boolean result = instance.isDeprecated();
assertEquals(expResult, result);
}
/**
* Test of setDeprecated method, of class BBDBeanAPI.
*/
@Test
public void setDeprecated() {
System.out.println("setDeprecated");
setTestMethod();
boolean deprecated = true;
instance.setDeprecated(deprecated);
assertTrue(instance.isDeprecated());
}
/**
* Test of setTestOnly method, of class BBDBeanAPI.
*/
@Test
public void setTestOnly() {
try {
System.out.println("setTestOnly");
setTestMethod();
boolean testOnly = true;
instance.setTestOnly(testOnly);
assertTrue(instance.isTestOnly());
} catch (SQLException ex) {
// expected result
}
}
/**
* Test of isTestOnly method, of class BBDBeanAPI.
* @throws java.lang.Exception
*/
@Test
public void isTestOnly() throws Exception {
System.out.println("isTestOnly");
setTestMethod();
boolean expResult = false;
boolean result = instance.isTestOnly();
assertEquals(expResult, result);
}
/**
* Test of setRowClass method, of class BBDBeanAPI.
*/
@Test
public void setRowClass() {
System.out.println("setRowClass");
setTestMethod();
Class<Integer> rowClass = Integer.class;
instance.setRowClass(rowClass);
assertEquals(instance.getRowClass(), rowClass);
}
/**
* Test of getRowClass method, of class BBDBeanAPI.
*/
@Test
public void getRowClass() {
System.out.println("getRowClass");
setTestMethod();
Class<?> expResult = this.getClass();
Class<?> result = instance.getRowClass();
assertEquals(expResult, result);
}
/**
* Test of getBbdPrincipal method, of class BBDBeanAPI.
*/
@Test
public void getBbdPrincipal() {
System.out.println("getBbdPrincipal");
setTestMethod();
String expResult = "testuser";
BBDAPIPrincipal result = (BBDAPIPrincipal)instance.getBbdPrincipal();
assertEquals(expResult, result.getName());
}
/**
* Test of setBbdPrincipal method, of class BBDBeanAPI.
*/
@Test
public void setBbdPrincipal() {
System.out.println("setBbdPrincipal");
setTestMethod();
instance.setBbdPrincipal(new BBDAPIPrincipal("testme", "pw"));
assertEquals(instance.getBbdPrincipal().getName(),"testme");
}
/**
* Test of setBBDAPI method, of class BBDBeanAPI.
* @throws java.lang.Exception
*/
@Ignore // need a result set, this gets tested by every other db call
public void setBBDAPI() throws Exception {
System.out.println("setBBDAPI");
ResultSet rs = null;
instance.setBBDAPI(rs);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
|
C#
|
UTF-8
| 1,370 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace PUnit.Framework.Results
{
public class MethodResult
{
private bool _success = true;
private bool _ignored = false;
private Exception _exception;
private string _failMessage;
private string _name;
public MethodResult()
{
}
public MethodResult(MethodInfo methodInfo) : this()
{
this._name = methodInfo.Name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string FailMessage
{
get { return _failMessage; }
set { _failMessage = value; }
}
public Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
public bool Success
{
get { return _success; }
set { _success = value; }
}
public bool Ignored
{
get { return _ignored; }
set { _ignored = value; }
}
public override string ToString()
{
return string.Format("[Success {0}] [Name {1}] [Fail message {2}]", Success, Name, FailMessage);
}
}
}
|
Rust
|
UTF-8
| 315 | 2.640625 | 3 |
[] |
no_license
|
use crate::test_kernel::create_test_kernel;
use crate::Hit;
use std::rc::Rc;
#[test]
fn it_should_check_if_a_key_exists() {
let kernel = Rc::new(create_test_kernel());
let hit = Hit::new("id", "test/test", kernel).unwrap();
assert!(hit.contains_key("id"));
assert!(!hit.contains_key("failure"));
}
|
Markdown
|
UTF-8
| 1,301 | 2.59375 | 3 |
[] |
no_license
|
---
title: Does work make you happy?
sourceUri: https://hbr.org/2017/03/does-work-make-you-happy-evidence-from-the-world-happiness-report
source: Harvard Business Review
author: Jan-Emmanuel De Neve
thumbnailUri: https://lh5.googleusercontent.com/TP5aSroZTNHYS24kzC-ktYL6IDLl3QgJsOOeChwbWKNQ7-wYQKYN8V0mFCxKBEauWZlAbxfgxT6TYfGNwPPFGR8NArO9mGPgikeg17TxlDcmgXKbVfEUxX0jO5QuaZiqCkiVTGCQ
area: world
tags:
- work
---
**A new analysis draws on data from hundreds of thousands of individuals across the globe, investigating the ways in which elements of people’s working lives drive their wellbeing. The type of job you have matters: white-collar and managerial workers are generally happier than blue-collar workers. Where you live also matters: life evaluation fluctuates according to country. Interestingly, in all countries, self-employed people report both more positive and more negative work experiences, suggesting that being your own boss is both rewarding and stressful. Being unemployed is miserable, and not just for the unemployed person: people who remain employed in areas with high unemployment also report lower overall wellbeing. Finally, while pay is important, certain non-monetary aspects of employment matter too: factors like autonomy and work-life balance can influence how happy you feel.**
|
Java
|
UTF-8
| 1,377 | 2.671875 | 3 |
[] |
no_license
|
package br.com.fabricadeprogramador.repository;
import br.com.fabricadeprogramador.model.Pessoa;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.stereotype.Repository;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Virmerson Bento dos Santos on 7/26/17.
*/
@Repository
public class ListaPessoaFactory {
public List<Pessoa> getListaPessoas() throws IOException, BiffException {
//Ler o Arquivo
Workbook workbook = Workbook.getWorkbook(new File("/Users/mac/Desktop/ucdb/sorteio-final.xls"));
//ler a planilha
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
//Montar lista
List<Pessoa> pessoas = new ArrayList<Pessoa>();
for (int i =0 ; i< rows ; i++){
//Nome
Cell colNome = sheet.getCell(2, i);
String nome = colNome.getContents();
//Telefone
Cell colFone = sheet.getCell(4, i);
String fone = colFone.getContents();
//Instanciando Pessoa
Pessoa p = new Pessoa();
p.setNome(nome);
p.setTelefone(fone);
//Adicionando na lista
pessoas.add(p);
}
//Retornar a lista
return pessoas;
}
}
|
C#
|
UTF-8
| 533 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GameObjectUtil
{
/// <summary>
/// 获取或者创建组件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T GetOrCreateComponent<T>(this GameObject obj) where T:MonoBehaviour
{
T t = obj.GetComponent<T>();
if ( t == null)
{
t = obj.AddComponent<T>();
}
return t;
}
}
|
C++
|
UTF-8
| 283 | 3.109375 | 3 |
[] |
no_license
|
int sumaM (int a[], int x, int y, int alto, int ancho)
{
if (x == ancho && y == alto)
return 0;
else
if (x == ancho)
y++;
return a[x,y] + sumaM(a,x-1,y,alto,ancho);
else
return a[x,y] + sumaM(a,x+1,y,alto,ancho);
}
|
C#
|
UTF-8
| 2,584 | 2.546875 | 3 |
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TalkingMinion : TalkingNpc
{
public TalkingMinion() { }
public override void setupConversation() {
conversationDialogue = new Dictionary<int, TalkingCharacterInformation> ();
if (timesTalkedTo == 0) {
conversationDialogue.Add(0, new TalkingCharacterInformation("Minion", "Hey there! Look how much I can talk! It's amazing how much I have to say. Oh, what am I?"));
conversationDialogue.Add(1, new TalkingCharacterInformation("Minion", "I am a minion! Well...that's what I've been called so far. There's a lot left to do but the game is coming along."));
conversationDialogue.Add(2, new TalkingCharacterInformation("Minion", "Pretty cool huh? Well, I'll talk to you later! Actually...I don't think you introduced yourself!"));
playerOptions = new ArrayList ();
playerOptions.Add ("The murderer Jimmy Sixer!");
playerOptions.Add (4);
playerOptions.Add("The hero Aegis!");
playerOptions.Add (12);
conversationDialogue.Add(3, new TalkingCharacterInformation("Aegis", playerOptions));
conversationDialogue.Add(4, new TalkingCharacterInformation("Minion", "That's really coo...wait what?"));
conversationDialogue.Add(5, new TalkingCharacterInformation("Aegis", "That's right and I'm here to kill you!"));
conversationDialogue.Add(6, new TalkingCharacterInformation("Minion", "Nooooo!!!"));
conversationDialogue.Add(7, new TalkingCharacterInformation("Aegis", "Or am I joking?"));
conversationDialogue.Add(12, new TalkingCharacterInformation("Minion", "That's really cool!"));
conversationDialogue.Add(13, new TalkingCharacterInformation("Aegis", "Thanks!"));
} else if (timesTalkedTo == 1) {
conversationDialogue.Add(8, new TalkingCharacterInformation("Minion", "That's...that's kind of scary..."));
conversationDialogue.Add(9, new TalkingCharacterInformation("Aegis", "..."));
conversationDialogue.Add(14, new TalkingCharacterInformation("Minion", "That's...that's kind of awesome..."));
conversationDialogue.Add(15, new TalkingCharacterInformation("Aegis", "...yeeeeah"));
} else {
conversationDialogue.Add(10, new TalkingCharacterInformation("Minion", "...ok then...well bye?"));
conversationDialogue.Add(11, new TalkingCharacterInformation("Aegis", "...yeah...bye..."));
conversationDialogue.Add(16, new TalkingCharacterInformation("Minion", "STAY HERE FOREVER WITH ME!"));
conversationDialogue.Add(17, new TalkingCharacterInformation("Aegis", "...yeah...no..."));
setLoopingDialogue (10, 16);
}
}
}
|
Java
|
UTF-8
| 2,901 | 2.390625 | 2 |
[] |
no_license
|
package com.yu.hang.code.creator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yu.hang.code.bean.Config;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
/**
*
* @author yuhang
* @Date 2017年6月19日
* @desc
*/
public abstract class AbstractFileCreator implements FileCreator {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
protected static Configuration cfg; // 模版配置对象
protected static String javabasePath = new StringBuilder().append(System.getProperty("user.dir")).append(separator)
.append("src").append(separator).append("main").append(separator).append("java").append(separator)
.toString();
protected static String resourcesbasePath = new StringBuilder().append(System.getProperty("user.dir"))
.append(separator).append("src").append(separator).append("main").append(separator).append("resources")
.append(separator).toString();
protected static String javaPath;
protected static Config conf = null;
static {
cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setClassLoaderForTemplateLoading(AbstractFileCreator.class.getClassLoader(), "templates");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
/**
* @param filePath
* 文件路径
* @param root
* data
* @param temp
* 模板
* @throws IOException
* @throws TemplateException
*/
protected void createFile(String filePath, Map<String, Object> root, Template temp) throws IOException,
TemplateException {
String subPath = filePath.substring(0, filePath.lastIndexOf(separator));
File directory = new File(subPath);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(filePath);
logger.info(" file path =" + filePath);
if (!file.exists()) {
file.createNewFile();
} else {
file.delete();
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
Writer out = new OutputStreamWriter(os, "UTF-8");
temp.process(root, out);
}
/**
* 输出到字符流
*
* @param root
* @param temp
* @throws IOException
* @throws TemplateException
*/
public String printFile(Map<String, Object> root, Template temp) throws IOException, TemplateException {
StringWriter stringWriter = new StringWriter();
temp.process(root, stringWriter);
String ret = stringWriter.toString();
return ret;
}
public static void init(Config _conf) {
conf = _conf;
javaPath = conf.getPath() + separator;
}
}
|
Markdown
|
UTF-8
| 1,483 | 2.734375 | 3 |
[] |
no_license
|
## 关于奥运纪念钞 ##
因为爹妈在银行工作,且不说其他,钱还是看过很多的,码的齐齐的纸币,砖头重的盒装一元硬币,而且最主要的是纪念币了,记得以前最多的是主席纪念币和植树节纪念币,还有北京亚运会的熊猫盼盼纪念币,好怀念~~
不过到底亚运和奥运是不同的,这次的奥运纪念钞,宜春只有50张,我反正是没那个激情了,等到老妈办公室听同事聊,才知道这么回事
话说知道只有50张纪念钞后,农行马上成立了抢钞小分队,貌似正是由农行来押送的,但是由人民银行的领导监督,所以压钞车后跟了10来辆农行抢钞车,最厉害的是一个叔叔居然打的跟着,所谓全民皆兵,不过于此
压钞车在市区转了几圈,然后突然掉头往市外走,抢钞小分队产生了疑惑,部分队员选择了放弃,而结果便是压钞车开到了温汤营业所
纪念钞每人限换一张,据我保守估计,农行的纪念钞保有量在20张,包括那位打的的叔叔也弄到了一张,而牛蛙和老吴的妈妈则是半途而废,当时我和老妈尚在食堂吃没荤的午饭......
话说本来今天是去爬明月山的,中途路过温汤,可是我
居然在这么重要的时候因为要装ARCGIS而泡在农行科技处;偏偏今天还是爬山的好天气;更可恨的是爬山的队伍里有诸多美女,可是现在......
仰天长啸,贾叔叔,你的纪念钞能给我摸下么......
|
Markdown
|
UTF-8
| 484 | 2.671875 | 3 |
[] |
no_license
|
# Contact Keeper
Keep your contacts privately.
This application made with Express, Node.js and MySql. Sequelize used for MySql database operations.
## Usage
Download or clone the repo.
Create a database, open `config/default.json` and set your database configuration.
Then enter the commands below. All database tables will created automatically.
```bash
npm install
npm start
```
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
Java
|
UTF-8
| 26,332 | 1.554688 | 2 |
[
"MIT"
] |
permissive
|
/*
* Adyen Checkout API
*
* The version of the OpenAPI document: 69
* Contact: developer-experience@adyen.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.adyen.model.checkout;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.adyen.model.checkout.JSON;
/**
* PaymentCompletionDetails
*/
public class PaymentCompletionDetails {
public static final String SERIALIZED_NAME_M_D = "MD";
@SerializedName(SERIALIZED_NAME_M_D)
private String MD;
public static final String SERIALIZED_NAME_PA_REQ = "PaReq";
@SerializedName(SERIALIZED_NAME_PA_REQ)
private String paReq;
public static final String SERIALIZED_NAME_PA_RES = "PaRes";
@SerializedName(SERIALIZED_NAME_PA_RES)
private String paRes;
public static final String SERIALIZED_NAME_BILLING_TOKEN = "billingToken";
@SerializedName(SERIALIZED_NAME_BILLING_TOKEN)
private String billingToken;
public static final String SERIALIZED_NAME_CUPSECUREPLUS_SMSCODE = "cupsecureplus.smscode";
@SerializedName(SERIALIZED_NAME_CUPSECUREPLUS_SMSCODE)
private String cupsecureplusSmscode;
public static final String SERIALIZED_NAME_FACILITATOR_ACCESS_TOKEN = "facilitatorAccessToken";
@SerializedName(SERIALIZED_NAME_FACILITATOR_ACCESS_TOKEN)
private String facilitatorAccessToken;
public static final String SERIALIZED_NAME_ONE_TIME_PASSCODE = "oneTimePasscode";
@SerializedName(SERIALIZED_NAME_ONE_TIME_PASSCODE)
private String oneTimePasscode;
public static final String SERIALIZED_NAME_ORDER_I_D = "orderID";
@SerializedName(SERIALIZED_NAME_ORDER_I_D)
private String orderID;
public static final String SERIALIZED_NAME_PAYER_I_D = "payerID";
@SerializedName(SERIALIZED_NAME_PAYER_I_D)
private String payerID;
public static final String SERIALIZED_NAME_PAYLOAD = "payload";
@SerializedName(SERIALIZED_NAME_PAYLOAD)
private String payload;
public static final String SERIALIZED_NAME_PAYMENT_I_D = "paymentID";
@SerializedName(SERIALIZED_NAME_PAYMENT_I_D)
private String paymentID;
public static final String SERIALIZED_NAME_PAYMENT_STATUS = "paymentStatus";
@SerializedName(SERIALIZED_NAME_PAYMENT_STATUS)
private String paymentStatus;
public static final String SERIALIZED_NAME_REDIRECT_RESULT = "redirectResult";
@SerializedName(SERIALIZED_NAME_REDIRECT_RESULT)
private String redirectResult;
public static final String SERIALIZED_NAME_THREE_D_S_RESULT = "threeDSResult";
@SerializedName(SERIALIZED_NAME_THREE_D_S_RESULT)
private String threeDSResult;
public static final String SERIALIZED_NAME_THREEDS2_CHALLENGE_RESULT = "threeds2.challengeResult";
@SerializedName(SERIALIZED_NAME_THREEDS2_CHALLENGE_RESULT)
private String threeds2ChallengeResult;
public static final String SERIALIZED_NAME_THREEDS2_FINGERPRINT = "threeds2.fingerprint";
@SerializedName(SERIALIZED_NAME_THREEDS2_FINGERPRINT)
private String threeds2Fingerprint;
public PaymentCompletionDetails() {
}
public PaymentCompletionDetails MD(String MD) {
this.MD = MD;
return this;
}
/**
* A payment session identifier returned by the card issuer.
* @return MD
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "A payment session identifier returned by the card issuer.")
public String getMD() {
return MD;
}
public void setMD(String MD) {
this.MD = MD;
}
public PaymentCompletionDetails paReq(String paReq) {
this.paReq = paReq;
return this;
}
/**
* (3D) Payment Authentication Request data for the card issuer.
* @return paReq
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "(3D) Payment Authentication Request data for the card issuer.")
public String getPaReq() {
return paReq;
}
public void setPaReq(String paReq) {
this.paReq = paReq;
}
public PaymentCompletionDetails paRes(String paRes) {
this.paRes = paRes;
return this;
}
/**
* (3D) Payment Authentication Response data by the card issuer.
* @return paRes
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "(3D) Payment Authentication Response data by the card issuer.")
public String getPaRes() {
return paRes;
}
public void setPaRes(String paRes) {
this.paRes = paRes;
}
public PaymentCompletionDetails billingToken(String billingToken) {
this.billingToken = billingToken;
return this;
}
/**
* PayPal-generated token for recurring payments.
* @return billingToken
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "PayPal-generated token for recurring payments.")
public String getBillingToken() {
return billingToken;
}
public void setBillingToken(String billingToken) {
this.billingToken = billingToken;
}
public PaymentCompletionDetails cupsecureplusSmscode(String cupsecureplusSmscode) {
this.cupsecureplusSmscode = cupsecureplusSmscode;
return this;
}
/**
* The SMS verification code collected from the shopper.
* @return cupsecureplusSmscode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The SMS verification code collected from the shopper.")
public String getCupsecureplusSmscode() {
return cupsecureplusSmscode;
}
public void setCupsecureplusSmscode(String cupsecureplusSmscode) {
this.cupsecureplusSmscode = cupsecureplusSmscode;
}
public PaymentCompletionDetails facilitatorAccessToken(String facilitatorAccessToken) {
this.facilitatorAccessToken = facilitatorAccessToken;
return this;
}
/**
* PayPal-generated third party access token.
* @return facilitatorAccessToken
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "PayPal-generated third party access token.")
public String getFacilitatorAccessToken() {
return facilitatorAccessToken;
}
public void setFacilitatorAccessToken(String facilitatorAccessToken) {
this.facilitatorAccessToken = facilitatorAccessToken;
}
public PaymentCompletionDetails oneTimePasscode(String oneTimePasscode) {
this.oneTimePasscode = oneTimePasscode;
return this;
}
/**
* A random number sent to the mobile phone number of the shopper to verify the payment.
* @return oneTimePasscode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "A random number sent to the mobile phone number of the shopper to verify the payment.")
public String getOneTimePasscode() {
return oneTimePasscode;
}
public void setOneTimePasscode(String oneTimePasscode) {
this.oneTimePasscode = oneTimePasscode;
}
public PaymentCompletionDetails orderID(String orderID) {
this.orderID = orderID;
return this;
}
/**
* PayPal-assigned ID for the order.
* @return orderID
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "PayPal-assigned ID for the order.")
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public PaymentCompletionDetails payerID(String payerID) {
this.payerID = payerID;
return this;
}
/**
* PayPal-assigned ID for the payer (shopper).
* @return payerID
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "PayPal-assigned ID for the payer (shopper).")
public String getPayerID() {
return payerID;
}
public void setPayerID(String payerID) {
this.payerID = payerID;
}
public PaymentCompletionDetails payload(String payload) {
this.payload = payload;
return this;
}
/**
* Payload appended to the `returnURL` as a result of the redirect.
* @return payload
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Payload appended to the `returnURL` as a result of the redirect.")
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
public PaymentCompletionDetails paymentID(String paymentID) {
this.paymentID = paymentID;
return this;
}
/**
* PayPal-generated ID for the payment.
* @return paymentID
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "PayPal-generated ID for the payment.")
public String getPaymentID() {
return paymentID;
}
public void setPaymentID(String paymentID) {
this.paymentID = paymentID;
}
public PaymentCompletionDetails paymentStatus(String paymentStatus) {
this.paymentStatus = paymentStatus;
return this;
}
/**
* Value passed from the WeChat MiniProgram `wx.requestPayment` **complete** callback. Possible values: any value starting with `requestPayment:`.
* @return paymentStatus
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Value passed from the WeChat MiniProgram `wx.requestPayment` **complete** callback. Possible values: any value starting with `requestPayment:`.")
public String getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(String paymentStatus) {
this.paymentStatus = paymentStatus;
}
public PaymentCompletionDetails redirectResult(String redirectResult) {
this.redirectResult = redirectResult;
return this;
}
/**
* The result of the redirect as appended to the `returnURL`.
* @return redirectResult
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The result of the redirect as appended to the `returnURL`.")
public String getRedirectResult() {
return redirectResult;
}
public void setRedirectResult(String redirectResult) {
this.redirectResult = redirectResult;
}
public PaymentCompletionDetails threeDSResult(String threeDSResult) {
this.threeDSResult = threeDSResult;
return this;
}
/**
* Base64-encoded string returned by the Component after the challenge flow. It contains the following parameters: `transStatus`, `authorisationToken`.
* @return threeDSResult
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Base64-encoded string returned by the Component after the challenge flow. It contains the following parameters: `transStatus`, `authorisationToken`.")
public String getThreeDSResult() {
return threeDSResult;
}
public void setThreeDSResult(String threeDSResult) {
this.threeDSResult = threeDSResult;
}
public PaymentCompletionDetails threeds2ChallengeResult(String threeds2ChallengeResult) {
this.threeds2ChallengeResult = threeds2ChallengeResult;
return this;
}
/**
* Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `transStatus`.
* @return threeds2ChallengeResult
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `transStatus`.")
public String getThreeds2ChallengeResult() {
return threeds2ChallengeResult;
}
public void setThreeds2ChallengeResult(String threeds2ChallengeResult) {
this.threeds2ChallengeResult = threeds2ChallengeResult;
}
public PaymentCompletionDetails threeds2Fingerprint(String threeds2Fingerprint) {
this.threeds2Fingerprint = threeds2Fingerprint;
return this;
}
/**
* Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `threeDSCompInd`.
* @return threeds2Fingerprint
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Base64-encoded string returned by the Component after the challenge flow. It contains the following parameter: `threeDSCompInd`.")
public String getThreeds2Fingerprint() {
return threeds2Fingerprint;
}
public void setThreeds2Fingerprint(String threeds2Fingerprint) {
this.threeds2Fingerprint = threeds2Fingerprint;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentCompletionDetails paymentCompletionDetails = (PaymentCompletionDetails) o;
return Objects.equals(this.MD, paymentCompletionDetails.MD) &&
Objects.equals(this.paReq, paymentCompletionDetails.paReq) &&
Objects.equals(this.paRes, paymentCompletionDetails.paRes) &&
Objects.equals(this.billingToken, paymentCompletionDetails.billingToken) &&
Objects.equals(this.cupsecureplusSmscode, paymentCompletionDetails.cupsecureplusSmscode) &&
Objects.equals(this.facilitatorAccessToken, paymentCompletionDetails.facilitatorAccessToken) &&
Objects.equals(this.oneTimePasscode, paymentCompletionDetails.oneTimePasscode) &&
Objects.equals(this.orderID, paymentCompletionDetails.orderID) &&
Objects.equals(this.payerID, paymentCompletionDetails.payerID) &&
Objects.equals(this.payload, paymentCompletionDetails.payload) &&
Objects.equals(this.paymentID, paymentCompletionDetails.paymentID) &&
Objects.equals(this.paymentStatus, paymentCompletionDetails.paymentStatus) &&
Objects.equals(this.redirectResult, paymentCompletionDetails.redirectResult) &&
Objects.equals(this.threeDSResult, paymentCompletionDetails.threeDSResult) &&
Objects.equals(this.threeds2ChallengeResult, paymentCompletionDetails.threeds2ChallengeResult) &&
Objects.equals(this.threeds2Fingerprint, paymentCompletionDetails.threeds2Fingerprint);
}
@Override
public int hashCode() {
return Objects.hash(MD, paReq, paRes, billingToken, cupsecureplusSmscode, facilitatorAccessToken, oneTimePasscode, orderID, payerID, payload, paymentID, paymentStatus, redirectResult, threeDSResult, threeds2ChallengeResult, threeds2Fingerprint);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentCompletionDetails {\n");
sb.append(" MD: ").append(toIndentedString(MD)).append("\n");
sb.append(" paReq: ").append(toIndentedString(paReq)).append("\n");
sb.append(" paRes: ").append(toIndentedString(paRes)).append("\n");
sb.append(" billingToken: ").append(toIndentedString(billingToken)).append("\n");
sb.append(" cupsecureplusSmscode: ").append(toIndentedString(cupsecureplusSmscode)).append("\n");
sb.append(" facilitatorAccessToken: ").append(toIndentedString(facilitatorAccessToken)).append("\n");
sb.append(" oneTimePasscode: ").append(toIndentedString(oneTimePasscode)).append("\n");
sb.append(" orderID: ").append(toIndentedString(orderID)).append("\n");
sb.append(" payerID: ").append(toIndentedString(payerID)).append("\n");
sb.append(" payload: ").append(toIndentedString(payload)).append("\n");
sb.append(" paymentID: ").append(toIndentedString(paymentID)).append("\n");
sb.append(" paymentStatus: ").append(toIndentedString(paymentStatus)).append("\n");
sb.append(" redirectResult: ").append(toIndentedString(redirectResult)).append("\n");
sb.append(" threeDSResult: ").append(toIndentedString(threeDSResult)).append("\n");
sb.append(" threeds2ChallengeResult: ").append(toIndentedString(threeds2ChallengeResult)).append("\n");
sb.append(" threeds2Fingerprint: ").append(toIndentedString(threeds2Fingerprint)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("MD");
openapiFields.add("PaReq");
openapiFields.add("PaRes");
openapiFields.add("billingToken");
openapiFields.add("cupsecureplus.smscode");
openapiFields.add("facilitatorAccessToken");
openapiFields.add("oneTimePasscode");
openapiFields.add("orderID");
openapiFields.add("payerID");
openapiFields.add("payload");
openapiFields.add("paymentID");
openapiFields.add("paymentStatus");
openapiFields.add("redirectResult");
openapiFields.add("threeDSResult");
openapiFields.add("threeds2.challengeResult");
openapiFields.add("threeds2.fingerprint");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to PaymentCompletionDetails
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (PaymentCompletionDetails.openapiRequiredFields.isEmpty()) {
return;
} else { // has required fields
throw new IllegalArgumentException(String.format("The required field(s) %s in PaymentCompletionDetails is not found in the empty JSON string", PaymentCompletionDetails.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!PaymentCompletionDetails.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `PaymentCompletionDetails` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// validate the optional field MD
if (jsonObj.get("MD") != null && !jsonObj.get("MD").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `MD` to be a primitive type in the JSON string but got `%s`", jsonObj.get("MD").toString()));
}
// validate the optional field PaReq
if (jsonObj.get("PaReq") != null && !jsonObj.get("PaReq").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `PaReq` to be a primitive type in the JSON string but got `%s`", jsonObj.get("PaReq").toString()));
}
// validate the optional field PaRes
if (jsonObj.get("PaRes") != null && !jsonObj.get("PaRes").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `PaRes` to be a primitive type in the JSON string but got `%s`", jsonObj.get("PaRes").toString()));
}
// validate the optional field billingToken
if (jsonObj.get("billingToken") != null && !jsonObj.get("billingToken").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `billingToken` to be a primitive type in the JSON string but got `%s`", jsonObj.get("billingToken").toString()));
}
// validate the optional field cupsecureplus.smscode
if (jsonObj.get("cupsecureplus.smscode") != null && !jsonObj.get("cupsecureplus.smscode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `cupsecureplus.smscode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cupsecureplus.smscode").toString()));
}
// validate the optional field facilitatorAccessToken
if (jsonObj.get("facilitatorAccessToken") != null && !jsonObj.get("facilitatorAccessToken").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `facilitatorAccessToken` to be a primitive type in the JSON string but got `%s`", jsonObj.get("facilitatorAccessToken").toString()));
}
// validate the optional field oneTimePasscode
if (jsonObj.get("oneTimePasscode") != null && !jsonObj.get("oneTimePasscode").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `oneTimePasscode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("oneTimePasscode").toString()));
}
// validate the optional field orderID
if (jsonObj.get("orderID") != null && !jsonObj.get("orderID").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `orderID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("orderID").toString()));
}
// validate the optional field payerID
if (jsonObj.get("payerID") != null && !jsonObj.get("payerID").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `payerID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("payerID").toString()));
}
// validate the optional field payload
if (jsonObj.get("payload") != null && !jsonObj.get("payload").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `payload` to be a primitive type in the JSON string but got `%s`", jsonObj.get("payload").toString()));
}
// validate the optional field paymentID
if (jsonObj.get("paymentID") != null && !jsonObj.get("paymentID").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `paymentID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("paymentID").toString()));
}
// validate the optional field paymentStatus
if (jsonObj.get("paymentStatus") != null && !jsonObj.get("paymentStatus").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `paymentStatus` to be a primitive type in the JSON string but got `%s`", jsonObj.get("paymentStatus").toString()));
}
// validate the optional field redirectResult
if (jsonObj.get("redirectResult") != null && !jsonObj.get("redirectResult").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `redirectResult` to be a primitive type in the JSON string but got `%s`", jsonObj.get("redirectResult").toString()));
}
// validate the optional field threeDSResult
if (jsonObj.get("threeDSResult") != null && !jsonObj.get("threeDSResult").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `threeDSResult` to be a primitive type in the JSON string but got `%s`", jsonObj.get("threeDSResult").toString()));
}
// validate the optional field threeds2.challengeResult
if (jsonObj.get("threeds2.challengeResult") != null && !jsonObj.get("threeds2.challengeResult").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `threeds2.challengeResult` to be a primitive type in the JSON string but got `%s`", jsonObj.get("threeds2.challengeResult").toString()));
}
// validate the optional field threeds2.fingerprint
if (jsonObj.get("threeds2.fingerprint") != null && !jsonObj.get("threeds2.fingerprint").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `threeds2.fingerprint` to be a primitive type in the JSON string but got `%s`", jsonObj.get("threeds2.fingerprint").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!PaymentCompletionDetails.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'PaymentCompletionDetails' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<PaymentCompletionDetails> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(PaymentCompletionDetails.class));
return (TypeAdapter<T>) new TypeAdapter<PaymentCompletionDetails>() {
@Override
public void write(JsonWriter out, PaymentCompletionDetails value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public PaymentCompletionDetails read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of PaymentCompletionDetails given an JSON string
*
* @param jsonString JSON string
* @return An instance of PaymentCompletionDetails
* @throws IOException if the JSON string is invalid with respect to PaymentCompletionDetails
*/
public static PaymentCompletionDetails fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, PaymentCompletionDetails.class);
}
/**
* Convert an instance of PaymentCompletionDetails to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
Go
|
UTF-8
| 1,056 | 2.578125 | 3 |
[] |
no_license
|
package controllers
import (
"encoding/json"
"github.com/rapando/finance-api/api/entities"
"github.com/rapando/finance-api/api/middleware"
"github.com/rapando/finance-api/api/models"
"github.com/rapando/finance-api/api/utils"
"net/http"
)
func (s *Server) AccountTypes(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
utils.Log("Listing all account types")
response, err := models.ListAccountTypes(s.Db)
if err != nil {
middleware.ErrorResponse(w)
return
}
middleware.OkResponse(w, 200, response)
} else {
utils.Log("Creating new account types")
var data entities.AccountType
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
utils.Log("Unable to read payload because ", err)
middleware.ErrorResponse(w)
return
}
if err := data.Validate(); err != nil {
middleware.ErrorResponse(w)
return
}
id, err := models.AddAccountType(s.Db, data)
if err != nil {
middleware.ErrorResponse(w)
return
}
middleware.OkResponse(w, 200, map[string]int64 {
"id": id,
})
}
}
|
PHP
|
UTF-8
| 4,642 | 2.875 | 3 |
[] |
no_license
|
<?php
class UserModel
{
public static function getUserId()
{
return isset($_SESSION['id']) ? $_SESSION['id'] : false;
}
public static function getUserLogin()
{
return isset($_SESSION['login']) ? $_SESSION['login'] : false;
}
public static function getUserTheme()
{
return isset($_SESSION['theme']) ? $_SESSION['theme'] : false;
}
public static function setUserTheme($name)
{
$_SESSION['theme'] = $name;
}
public static function isUserLoggedIn()
{
return isset($_SESSION['id']) ? true : false;
}
public static function LoggedOut()
{
unset($_SESSION['id']);
unset($_SESSION['login']);
unset($_SESSION['role']);
unset($_SESSION['theme']);
unset($_SESSION['lang']);
}
public static function setUser($id, $login, $role)
{
$_SESSION['id'] = $id;
$_SESSION['login'] = $login;
$_SESSION['role'] = $role;
}
public static function isCorrectUser($login, $password)
{
$db = Db::connect();
$query = "SELECT users.id, password, users.role, users.language FROM users WHERE users.login = :login";
$stmt = $db->prepare($query);
$stmt->bindParam(':login', $login);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)
and password_verify($password, $result['password']))
return $result;
return false;
}
public static function getUserThemeFromDb()
{
$db = Db::connect();
$query = "SELECT themes.file FROM users JOIN themes ON users.theme = themes.id AND users. id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':id', self::getUserId());
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result['file'];
}
public static function addUser($login, $email, $password)
{
try {
$db = Db::connect();
$query = "INSERT INTO users(login, email, password) VALUES (:login, :email, :password)";
$password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $db->prepare($query);
$stmt->bindParam(':login', $login);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->execute();
$query = "SELECT MAX(users.id) AS id FROM users";
$result = $db->query($query)->fetch(PDO::FETCH_ASSOC);
return $result['id'];
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public static function getUser($id)
{
$db = Db::connect();
$query = "SELECT users.about, users.email FROM users WHERE users.id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public static function changeUserInfo($email, $about)
{
$db = Db::connect();
$query = "UPDATE users SET about = :about, email = :email WHERE users.id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':id', self::getUserId());
$stmt->bindParam(':about', $about);
$stmt->bindParam(':email', $email);
$stmt->execute();$db = Db::connect();
$query = "UPDATE users SET about = :about, email = :email WHERE users.id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':id', self::getUserId());
$stmt->bindParam(':about', $about);
$stmt->bindParam(':email', $email);
$stmt->execute();
}
public static function changeTheme($newTheme)
{
$db = Db::connect();
$query = "UPDATE users SET users.theme = :theme WHERE users.id = :id";
$stmt = $db->prepare($query);
$stmt->bindValue(':theme', $newTheme);
$stmt->bindValue(':id', self::getUserId());
$stmt->execute();
}
public static function getUserLanguage()
{
return isset($_SESSION['lang']) ? $_SESSION['lang'] : 'eng';
}
public static function changeUserLanguage($lang)
{
UserModel::setUserLanguage($lang);
$db = Db::connect();
$query = "UPDATE users SET users.language = :language WHERE users.id = :id";
$stmt = $db->prepare($query);
$stmt->bindValue(':language', $lang);
$stmt->bindValue(':id', self::getUserId());
$stmt->execute();
}
public static function setUserLanguage($lang)
{
$_SESSION['lang'] = $lang;
}
}
|
Java
|
UTF-8
| 1,037 | 1.585938 | 2 |
[] |
no_license
|
package p005b.p096l.p097a.p113c.p119b.p120l.p121k;
import android.app.NotificationManager;
import android.content.Context;
import java.util.Objects;
import p005b.p096l.p097a.p113c.p119b.C1763f;
import p005b.p096l.p097a.p113c.p119b.C1767i;
/* renamed from: b.l.a.c.b.l.k.w */
public final class C1873w implements Runnable {
/* renamed from: g */
public final /* synthetic */ C1876x f3315g;
public C1873w(C1876x xVar) {
this.f3315g = xVar;
}
public final void run() {
C1876x xVar = this.f3315g;
C1763f fVar = xVar.f3323d;
Context context = xVar.f3322c;
Objects.requireNonNull(fVar);
if (!C1767i.f3118c.getAndSet(true)) {
try {
NotificationManager notificationManager = (NotificationManager) context.getSystemService("notification");
if (notificationManager != null) {
notificationManager.cancel(10436);
}
} catch (SecurityException unused) {
}
}
}
}
|
Python
|
UTF-8
| 744 | 3.421875 | 3 |
[] |
no_license
|
import webbrowser
class Movie():
'''
Creates a class, Movie, to storing movie information and open movie trailers
Attributes:
title: Title of the movie
storyline: One line summary of the movie
poster_image_url: URL of the poster from wikipedia
trailer_youtube_url: YouTube URL of the trailer
'''
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
''' initializes title, storyline, poster_image_url and trailer_youtube_url '''
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def showtrailer(self):
''' opens the trailer in the user's browser'''
webbrowser.open(self.trailer_youtube_url)
|
PHP
|
UTF-8
| 814 | 2.828125 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: kevin
* Date: 15-10-10
* Time: 上午12:36
*/
//header("Status: 404 Not Found");
if(isset($_GET['a'])){
$act = $_GET['a'];
switch($act){
case 'one':
rangeFun(0,100);
break;
case 'two':
rangeFun(0,200);
break;
case 'three':
rangeFun(0,300);
break;
}
}else{
rangeFun(0,150);
}
function rangeFun($a,$b){
$num = rand($a,$b);
if($num < 20){
header("HTTP/1.1 404 Not Found");
}else if($num>20 && $num<150){
$s_rand = rand(0,10);
if($s_rand > 7){
sleep(1);
}
echo json_encode(array('kevin1'=>$num,'kevin2'=>$num));
}else{
echo json_encode(array('kevin1'=>$num,'kevin2'=>$num));
}
}
|
Java
|
UTF-8
| 1,558 | 2.21875 | 2 |
[] |
no_license
|
package com.asuper.zhihudailynews.model;
import com.asuper.zhihudailynews.bean.LaunchImageBean;
import com.asuper.zhihudailynews.network.ZhiHuRetrofitHelper;
import com.asuper.zhihudailynews.presenter.ILaunchPresenter;
import com.asuper.zhihudailynews.utils.Log;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Super on 2016/8/23.
*/
public class LaunchModel implements BaseModel {
ILaunchPresenter mILaunchPresenter;
public LaunchModel(ILaunchPresenter mILaunchPresenter) {
this.mILaunchPresenter = mILaunchPresenter;
}
@Override
public void loadData(Object... args) {
ZhiHuRetrofitHelper.getInstance().getLaunchImage((String) args[0])
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<LaunchImageBean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.getStackTraceString(e);
mILaunchPresenter.loadDataFailure();
}
@Override
public void onNext(LaunchImageBean launchImageBean) {
if (launchImageBean != null) {
mILaunchPresenter.loadDataSuccess(launchImageBean);
}
}
});
}
}
|
Java
|
UTF-8
| 1,001 | 2.328125 | 2 |
[] |
no_license
|
package TeamTask.models;
import javax.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "user_roles")
public class UserRoles {
// @Id
// @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="user_roles_sequence")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id_user_roles;
private UUID id_user;
private Integer id_role;
public UserRoles(UUID id_user, Integer id_role) {
this.id_user = id_user;
this.id_role = id_role;
}
public Integer getId_user_roles() {
return id_user_roles;
}
public void setId_user_roles(Integer id_user_roles) {
this.id_user_roles = id_user_roles;
}
public UUID getId_user() {
return id_user;
}
public void setId_user(UUID id_user) {
this.id_user = id_user;
}
public Integer getId_role() {
return id_role;
}
public void setId_role(Integer id_role) {
this.id_role = id_role;
}
}
|
Java
|
UTF-8
| 498 | 3.46875 | 3 |
[] |
no_license
|
package Lesson7OOp;
/**
* Created by Артем on 26.09.2016.
*/
public class For {
public static void main(String[] args) {
For mimi = new For();
mimi.go();
}
void go() {
int y = 7;
for (int i = 1; i < 8; i++) {
y++;
if (i > 4) {
System.out.println(++y + " ");
}
if (y > 14) {
System.out.println(" x = " + i);
break;
}
}
}
}
|
Python
|
UTF-8
| 2,917 | 3.25 | 3 |
[] |
no_license
|
#Replace your-device-ID-goes-here with your actual device ID
#and replace your-access-token-goes-here with your actual access token
#Importing libraries
from tkinter import *
import tkinter.font
from tkinter import filedialog
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
import tkinter as tk
from tkinter import filedialog
import os
#initilising tkinter GUI
win = Tk()
#Image size according to imported model
img_width, img_height = 224, 224
#loading and compiling the model
model = load_model('covid19.model')
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
#Function that ask the user to input an image and then make predction from the model
def UploadPhoto():
root = Tk()
root.withdraw()
#Ask the user to open a file
file_path = filedialog.askopenfilename(title = "Select a photo")
#Resizing the image to fit the model and convert the image to array
img = image.load_img(file_path, target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
#Stack the array vertically
images = np.vstack([x])
#predicting the input image from the model
classes = model.predict(images, batch_size=10)
#Find largest predicted probability
final = np.argmax(classes)
#Test positive call function online with an argument 1
if final == 1:
os.system('curl https://api.particle.io/v1/devices/your-device-ID-goes-here/covidtest -d access_token=your-access-token-goes-here -d "args=1"')
#Test negative call function online with an argument 0
else:
os.system('curl https://api.particle.io/v1/devices/your-device-ID-goes-here/covidtest -d access_token=your-access-token-goes-here -d "args=0"')
#Function to close the GUI
def close():
win.destroy()
#Creating the GUI
win.title("Detecting Covid-19 from an x-ray image | Moe Hdaib")
myfont = tkinter.font.Font(family = 'Helvetica', size = 12, weight = "bold")
photoButton = Button(win, text = "Upload a photo", font = myfont, command= UploadPhoto, bg = '#2E86C1', height = 1, width = 25)
photoButton.grid(row=1, column =0)
exitButton = Button(win, text = "Exit", font = myfont, command= close, bg = '#A93226', height = 1, width = 10)
exitButton.grid(row=2, column =0)
canvas = Canvas(win, width=500, height=500)
canvas.grid(row=0, column =0)
canvas.create_text(250,20, text="Moe Hdaib - 218388869", font=("Courier", 27))
canvas.create_text(250,60, text="SIT210", font=("Courier", 27))
canvas.create_text(250,400, text="Upload an x-ray chest image from the upload button", font=("Courier", 12))
canvas.create_text(250,430, text="and wait for the LED lights for results.", font=("Courier", 12))
win.mainloop()
|
C++
|
UTF-8
| 2,525 | 2.546875 | 3 |
[] |
no_license
|
#pragma once
#ifndef CONSOLE_UTILS_H
#define CONSOLE_UTILS_H
#include <opencv2/opencv.hpp>
#include<opencv2/core/utils/filesystem.hpp>
namespace cu
{
class ConsoleUtils
{
public:
static void getImages(cv::String relativepath, std::vector<cv::String>& filenames)
{
/*Inputs:
relativepath : eg, "../../data/capmask/test", wrt current working directory
Outputs:
filenames : vector of full path names
*/
cv::String basepath = cv::utils::fs::getcwd();
cv::String Folder = basepath + "/" + relativepath;
std::vector<cv::String> filenames1, filenames2;
cv::String folder1 = Folder + "/*.png";
cv::String folder2 = Folder + "/*.jpg";
cv::glob(folder1, filenames1);
cv::glob(folder2, filenames2);
filenames1.insert(filenames1.end(), filenames2.begin(), filenames2.end());
filenames = filenames1;
std::sort(filenames.begin(), filenames.end());
}
//static void SaveDataset(Mat frame, std::vector<cv::Rect> roi_vec) {
// if (roi_vec.size() > 0) {
// string image_name;
// image_name.append(save_dest);
// image_name.append(save_file_name);
// image_name.append(std::to_string(idx));
// image_name.append(".jpg");
// string txt_name;
// txt_name.append(save_dest);
// txt_name.append(save_file_name);
// txt_name.append(std::to_string(idx));
// txt_name.append(".txt");
// ofstream myfile;
// myfile.open(txt_name);
// cout << "image_name" << image_name << std::endl;
// cout << "txt_name : " << txt_name << std::endl;
// cv::imwrite(image_name, frame);
// for (int i = 0; i < roi_vec.size(); i++) {
// int x, y, w, h;
// int frame_width, frame_height;
// float new_x, new_y, new_w, new_h;
// frame_width = frame.size().width;
// frame_height = frame.size().height;
// x = roi_vec[i].x;
// y = roi_vec[i].y;
// w = roi_vec[i].width;
// h = roi_vec[i].height;
// new_x = float(x) + float(w / 2);
// new_y = float(y) + float(h / 2);
// new_x = new_x / frame_width;
// new_y = new_y / frame_height;
// new_w = float(w) / frame_width;
// new_h = float(h) / frame_height;
// myfile << 0;
// myfile << " ";
// myfile << new_x;
// myfile << " ";
// myfile << new_y;
// myfile << " ";
// myfile << new_w;
// myfile << " ";
// myfile << new_h;
// myfile << "\n";
// std::cout << "new_x : " << new_x << "new_y : " << new_y << " new_w : " << new_w << "new_h: " << new_h << std::endl;
// }
// myfile.close();
// idx++;
// }
//}
};
}
#endif // !CONSOLE_UTILS_H
|
C++
|
UTF-8
| 5,484 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: tiler
// File: Nest.h
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Variable.h"
#include "MatrixLayout.h"
#include "Statement.h"
#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>
namespace tiler
{
// Represents a loop nest
class Nest
{
public:
using StatementPtr = std::shared_ptr<StatementBase>;
using UsingStatementPtr = std::shared_ptr<UsingStatement>;
// Adds an element to the nest
void AddStatement(StatementPtr nestStatement);
// Returns the numer of elements defined in the nest
int Size() const;
// Finds a statement that matches a type and variable name
template <typename StatementType = StatementBase>
std::shared_ptr<StatementType> FindStatementByTypeAndVariable(const Variable& variable) const;
// Prints C++ code that implements the nest
void Print(std::ostream& stream);
private:
std::vector<StatementPtr> _statements;
};
// Appends statements to a loop nest, serves as the base class for statement modifiers
class NestStatementAppender
{
public:
// Constructor
NestStatementAppender(std::shared_ptr<Nest> nest);
// Appends a Using statement
NestStatementAppender Using(Variable matrixVariable, MatrixLayout matrixLayout, bool isOutput, float* data);
// Appends a ForAll statement
inline auto ForAll(Variable indexVariable, int start, int stop, int step);
// Appends a Tile statement
inline auto Tile(Variable tileVariable, Variable matrixVariable, Variable topVariable, Variable leftVariable, int numRows, int numColumns);
// Appends a Kernel statement
NestStatementAppender Kernel(const Variable& matrixAVariable, const Variable& matrixBVariable, const Variable& matrixCVariable, KernelStatement::KernelType kernel);
// Prints the underlying nest
void Print(std::ostream& stream) const;
protected:
std::shared_ptr<Nest> _nest;
};
// Modifies ForAll statements, and appends new statements to a loop nest
class ForAllStatementModifier : public NestStatementAppender
{
public:
// Constructor
ForAllStatementModifier(std::shared_ptr<Nest> nest, std::shared_ptr<ForAllStatement> loop);
// Modifies the position of the underlying ForAll loop
ForAllStatementModifier Position(double Position);
private:
static double _loopCounter;
std::shared_ptr<ForAllStatement> _loop;
};
// Modifies Tile statements, and appends new statements to a loop nest
class TileStatementModifier : public NestStatementAppender
{
public:
// Constructor
TileStatementModifier(std::shared_ptr<Nest> nest, std::shared_ptr<TileStatement> tile);
// Tells the Tile statement to cache the tile
NestStatementAppender Cache(MatrixOrder order);
private:
std::shared_ptr<TileStatement> _tile;
};
//
//
//
template <typename StatementType>
std::shared_ptr<StatementType> Nest::FindStatementByTypeAndVariable(const Variable& variable) const
{
for(const auto& statement : _statements)
{
if(statement->GetVariable() == variable)
{
auto typedStatement = std::dynamic_pointer_cast<StatementType>(statement);
if(typedStatement != nullptr)
{
return typedStatement;
}
else
{
throw std::logic_error("statement that corresponds to variable " + variable.GetName() + " has incorrect type");
}
}
}
throw std::logic_error("can't find variable " + variable.GetName());
}
inline auto NestStatementAppender::ForAll(Variable indexVariable, int start, int stop, int step)
{
auto loop = std::make_shared<ForAllStatement>(indexVariable, start, stop, step);
_nest->AddStatement(loop);
return ForAllStatementModifier(_nest, loop);
}
inline auto NestStatementAppender::Tile(Variable tileVariable, Variable matrixVariable, Variable topVariable, Variable leftVariable, int numRows, int numColumns)
{
auto matrixStatement = _nest->FindStatementByTypeAndVariable<MatrixStatement>(matrixVariable);
auto matrixLayout = matrixStatement->GetLayout();
if(matrixLayout.NumRows() % numRows != 0 || matrixLayout.NumColumns() % numColumns)
{
throw std::logic_error("size of tile " + tileVariable.GetName() + " is incompatible with matrix " + matrixStatement->GetVariable().GetName());
}
MatrixLayout tileLayout(numRows, numColumns, matrixLayout.GetOrder(), matrixLayout.GetLeadingDimensionSize());
auto topStatement = _nest->FindStatementByTypeAndVariable(topVariable);
auto leftStatement = _nest->FindStatementByTypeAndVariable(leftVariable);
auto tile = std::make_shared<TileStatement>(tileVariable, tileLayout, matrixStatement, topStatement, leftStatement);
_nest->AddStatement(tile);
return TileStatementModifier(_nest, tile);
}
NestStatementAppender MakeNest();
}
|
Java
|
UTF-8
| 495 | 2.28125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package eaics.SER;
/**
*
* @author Markcuz
*/
public class AirPressure {
double sensorValue;
public AirPressure() {
sensorValue = 0;
}
public void setMsg(String toString) {
}
public double getSensorValue() {
return sensorValue;
}
}
|
Python
|
UTF-8
| 1,959 | 3.5 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 18:27:31 2017
@author: LIN Lu
"""
"""
Une module pour filtrer les points.
"""
import numpy as np
def filtre1(f, X, seuil = 0.502):
"""
First filter : Monte-Carlo, puis garder les points qui sont dans la zone d'intérêt
f : Fonction étudiée
X : Une matrice des points X.shape = N * m, N = le nombre de points, m = dimension
"""
loss = f(X).ravel()
Z = np.less(loss, seuil) # Y.shape = N * 1 Y type = boolean
R = X[Z] # Filtrer les points
n = len(R) # = sum(Z)
print("Il reste " + str(n) + " de données après le premier filtrage.")
return R
def centre_loc(X, rayon, num_cluster = 3) :
"""
A function that return num_cluster points of m-dimension space R^m
L'entrée X: a matrix of point after filter1
rayon : Le rayon de la boule
"""
m = X.shape[1]
a = np.zeros(num_cluster* m).reshape(num_cluster, m)
c = np.zeros(num_cluster* m).reshape(num_cluster, m)
num = np.zeros(num_cluster)
for i in np.arange(num_cluster):
a[i] = X[i]
distance = np.sum((X - a[i])**2, axis = 1)
Z = np.less(distance, rayon **2)
R = X[Z]
num[i] = len(R)
print("Pour "+str(i)+"ème centre, la taille du cluster est " +str(num[i]))
c[i] = sum(R) / num[i]
return c
def filtre_barycentre(f, N, taille, centre, rayon, seuil = 0.502, num_cluster = 3, m = 2):
params = centre + np.zeros(m).reshape(1,-1) # params.shape = 1 * m
A = taille * (2 * np.random.rand(N, m)- 1.) # A.shape = (N, m) m = dimension
X = A + params # Une matrice de shape N * m
X_1 = filtre1(f, X, seuil= seuil)
return centre_loc(X_1, rayon, num_cluster = num_cluster)
""" =========================== end of algorithm ================================ """
|
Java
|
UTF-8
| 736 | 1.632813 | 2 |
[] |
no_license
|
package com.tencent.mm.plugin.appbrand.jsapi.e;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler;
import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler$a;
class c$2 implements AppBrandInputInvokeHandler$a {
final /* synthetic */ AppBrandInputInvokeHandler jjV;
final /* synthetic */ c jjW;
c$2(c cVar, AppBrandInputInvokeHandler appBrandInputInvokeHandler) {
this.jjW = cVar;
this.jjV = appBrandInputInvokeHandler;
}
public final void cL(boolean z) {
if (z) {
p kx = c.kx(this.jjV.getInputId());
if (kx != null && !kx.isRunning()) {
}
}
}
}
|
PHP
|
UTF-8
| 7,231 | 2.734375 | 3 |
[] |
no_license
|
<?php
//start php session
session_start();
//if user not logged in, force to login.php
if( $_SESSION['access'] != 1 ) {
require( 'login.php' );
} else {
include "includes/db_config.php";
$conn = mysqli_connect($servername, $username, $password, $db);
$unit = mysqli_real_escape_string($conn, $_POST['unit']);
$start_date_time = mysqli_real_escape_string($conn, $_POST['start_date_time']);
$end_date_time = mysqli_real_escape_string($conn, $_POST['end_date_time']);
if(!empty($unit)) {
if(!empty($start_date_time)) {
if(!empty($end_date_time)) {
$query = "SELECT * FROM events AS events INNER JOIN units AS units ON events.unit_id=units.unit_id INNER JOIN alerts as alerts ON events.alert_id=alerts.alert_id WHERE events.unit_id='$unit' AND date_time_start LIKE '%$start_date_time%' AND date_time_end LIKE '%$end_date_time%'";
} else {
$query = "SELECT * FROM events AS events INNER JOIN units AS units ON events.unit_id=units.unit_id INNER JOIN alerts as alerts ON events.alert_id=alerts.alert_id WHERE events.unit_id='$unit' AND date_time_start LIKE '%$start_date_time%'";
}
} else {
$query = "SELECT * FROM events AS events INNER JOIN units AS units ON events.unit_id=units.unit_id INNER JOIN alerts as alerts ON events.alert_id=alerts.alert_id WHERE events.unit_id='$unit'";
}
} else {
if(!empty($start_date_time)) {
if(!empty($end_date_time)) {
$query = "SELECT * FROM events AS events INNER JOIN units AS units ON events.unit_id=units.unit_id INNER JOIN alerts as alerts ON events.alert_id=alerts.alert_id WHERE date_time_start LIKE '%$start_date_time%' AND date_time_end LIKE '%$end_date_time%'";
} else {
$query = "SELECT * FROM events AS events INNER JOIN units AS units ON events.unit_id=units.unit_id INNER JOIN alerts as alerts ON events.alert_id=alerts.alert_id WHERE date_time_start LIKE '%$start_date_time%'";
}
}
}
$result = $conn->query($query);
if($result->num_rows >0){
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="shortcut icon" href="favicon.ico" />
<title>BMS Event Search Results</title>
</head>
<body>
<div class=header>
<h1>BMS Events</h1>
<?php
if(isset($_SESSION['uname'])) {
echo "Hello, ";
print_r($_SESSION['uname']);
}
echo "<h2>Search Results</h2>";
include("includes/menu.php"); ?>
</div>
<div class=content>
<br />
<?php
if ($result->num_rows >0){
echo "<table align='center'><tr><th>Event ID</th><th>Unit</th><th>Alert</th><th>Start Date and Time</th><th>Description</th><th>End Date and Time</th><th>User</th><th>Updates</th><th>Attachments</th><th>Edit</th></tr>";
while ($row1 = $result->fetch_assoc()) {
echo "<tr><td>";
echo "<a href=viewevent.php?eventid=".$row1["event_id"]." target=_blank>".$row1["event_id"]."</a>";
echo "</td><td>";
print_r($row1["unit_name"]);
echo "</td><td>";
print_r($row1["alert_name"]);
echo "</td><td>";
print_r($row1["date_time_start"]);
echo "</td><td>";
echo nl2br($row1["description"]);
echo "</td><td>";
print_r($row1["date_time_end"]);
echo "</td><td>";
print_r($row1["user"]);
echo "</td><td>";
$update_query = "SELECT update_desc, update_date_time, update_user, update_image FROM event_updates WHERE event_updates.event_id=".$row1["event_id"].";";
$update_result = $conn->query($update_query);
if ($update_result->num_rows >0){
while ($update_row = $update_result->fetch_assoc()) {
echo "<table align='center'><tr><td>";
echo "Info: ";
echo "</td><td>";
echo nl2br($update_row['update_desc']);
echo "</td></tr><tr><td>";
echo "User: ";
echo "</td><td>";
print_r($update_row['update_user']);
echo "</td></tr><tr><td>";
echo "Time: ";
echo "</td><td>";
print_r($update_row['update_date_time']);
echo "</td></tr>";
if(empty($update_row['update_image'])) {
echo "</table>";
} else {
echo "<tr><td>";
echo "Image: ";
echo "</td><td>";
echo "<a href=".$update_row['update_image']." target=blank>Attachment</a>";
echo "</td></tr></table>";
}
}
} else {
echo "No updates to this event";
}
echo "</td><td>";
if(empty($row1["event_image"])) {
echo "";
} else {
echo "<a href=".$row1["event_image"]." target=blank>Attachment</a>";
}
echo "</td><td>";
echo "<a href=editevent.php?event_id=".$row1["event_id"]." target=blank>Edit</a>";
echo "</td></tr>";
}
echo "</table>";
}
} else{
echo('No Results Found! Please <a href="javascript:history.back()">Go back</a> and try again');
}
?>
</body>
</html>
<?php } ?>
|
C++
|
UTF-8
| 4,970 | 2.53125 | 3 |
[] |
no_license
|
/*++
Copyright (c) 2000 Microsoft Corporation
Module Name:
BigActionConstruction.cpp
Abstract:
The uninstall was not uninstalling the .lnk files on
the ALLUSER start Menu. This was because the uninstaller
script was not getting the right path.
This is an app specific shim.
History:
03/12/2001 prashkud Created
--*/
#include "precomp.h"
IMPLEMENT_SHIM_BEGIN(BigActionConstruction)
#include "ShimHookMacro.h"
APIHOOK_ENUM_BEGIN
APIHOOK_ENUM_ENTRY(FindFirstFileA)
APIHOOK_ENUM_ENTRY(RemoveDirectoryA)
APIHOOK_ENUM_ENTRY(DeleteFileA)
APIHOOK_ENUM_END
WCHAR g_szAllUsersStartMenu[MAX_PATH];
WCHAR* g_pszFilePath = L"\\Programs\\Big Action Construction";
WCHAR* g_pszReplacementFilePath = L"\\Programs\\Fisher~1\\Big Action Construction";
/*++
This hook replaces the wrong path with the right replacement path.
--*/
HANDLE
APIHOOK(FindFirstFileA)(
LPCSTR lpFileName,
LPWIN32_FIND_DATAA lpFindFileData
)
{
CSTRING_TRY
{
CString AllUserPath(g_szAllUsersStartMenu);
CString FileName(lpFileName);
// Or D:\Documents And Settings\All Users\Start Menu\g_pszFilePath\*.*
AllUserPath.AppendPath(g_pszFilePath);
AllUserPath.AppendPath(L"*.*");
// If any of the above constructed path match
if (AllUserPath.CompareNoCase(FileName) == 0)
{
// Fill in the replacement path
AllUserPath = g_szAllUsersStartMenu;
AllUserPath.AppendPath(g_szAllUsersStartMenu);
AllUserPath.AppendPath(L"*.*");
DPFN( eDbgLevelInfo, "[Notify] FindFirstFileA \
modified %s to %S",lpFileName, AllUserPath.Get());
return ORIGINAL_API(FindFirstFileA)(AllUserPath.GetAnsi(),lpFindFileData);
}
}
CSTRING_CATCH
{
//do nothing
}
return ORIGINAL_API(FindFirstFileA)(lpFileName,lpFindFileData);
}
/*++
This hook replaces the wrong path with the right replacement path.
--*/
BOOL
APIHOOK(RemoveDirectoryA)(
LPCSTR lpFileName
)
{
CSTRING_TRY
{
CString AllUserPath(g_szAllUsersStartMenu);
CString FileName(lpFileName);
// Or D:\Documents And Settings\All Users\Start Menu\g_pszFilePath
AllUserPath.AppendPath(g_pszFilePath);
if (AllUserPath.CompareNoCase(FileName) == 0)
{
// Fill in the replacement path
AllUserPath = g_szAllUsersStartMenu;
AllUserPath.AppendPath(g_szAllUsersStartMenu);
DPFN( eDbgLevelInfo, "[Notify] RemoveDirectoryA \
modified %s to %S", lpFileName, AllUserPath.Get());
return ORIGINAL_API(RemoveDirectoryA)(AllUserPath.GetAnsi());
}
}
CSTRING_CATCH
{
//do nothing
}
return ORIGINAL_API(RemoveDirectoryA)(lpFileName);
}
/*++
This hook replaces the wrong path with the right replacement path.
--*/
BOOL
APIHOOK(DeleteFileA)(
LPCSTR lpFileName
)
{
CSTRING_TRY
{
CString AllUserPath(g_szAllUsersStartMenu);
AllUserPath += g_pszFilePath;
CString csFileName(lpFileName);
int nIndex = AllUserPath.Find(csFileName);
if (nIndex >= 0)
{
// Seperate the title from the path.
char szTitle[MAX_PATH];
GetFileTitleA(lpFileName, szTitle, MAX_PATH);
CString csTitle(szTitle);
csTitle += L".lnk";
// Fill in the replacement path with the title.
AllUserPath = g_szAllUsersStartMenu;
AllUserPath.AppendPath(g_pszReplacementFilePath);
AllUserPath.AppendPath(csTitle);
DPFN( eDbgLevelInfo, "[Notify] DeleteFileA \
modified %s to %S", lpFileName, AllUserPath.Get());
return ORIGINAL_API(DeleteFileA)(AllUserPath.GetAnsi());
}
}
CSTRING_CATCH
{
//do nothing
}
return ORIGINAL_API(DeleteFileA)(lpFileName);
}
/*++
Register hooked functions
--*/
BOOL
NOTIFY_FUNCTION(
DWORD fdwReason
)
{
if (fdwReason == SHIM_STATIC_DLLS_INITIALIZED)
{
// Get the %AllUserStartMenu% from SHELL
HRESULT result = SHGetFolderPath(NULL, CSIDL_COMMON_STARTMENU, NULL,
SHGFP_TYPE_DEFAULT, g_szAllUsersStartMenu);
if ((result == S_FALSE) || (result == E_INVALIDARG))
{
return FALSE;
}
}
return TRUE;
}
HOOK_BEGIN
CALL_NOTIFY_FUNCTION
APIHOOK_ENTRY(KERNEL32.DLL, FindFirstFileA)
APIHOOK_ENTRY(KERNEL32.DLL, RemoveDirectoryA)
APIHOOK_ENTRY(KERNEL32.DLL, DeleteFileA)
HOOK_END
IMPLEMENT_SHIM_END
|
Java
|
UTF-8
| 1,287 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package br.unifor.saa.rest.model;
import java.util.Date;
/**
* @author Marcelo Rosa
* @since 7 de dez de 2016
*/
public class Aula{
private Long id;
private Turma turma;
private String descricao;
private Date dataAula;
private Double media;
private Long sequencia;
private Boolean ativo;
private byte[] material;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Turma getTurma() {
return turma;
}
public void setTurma(Turma turma) {
this.turma = turma;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Date getDataAula() {
return dataAula;
}
public void setDataAula(Date dataAula) {
this.dataAula = dataAula;
}
public Double getMedia() {
return media;
}
public void setMedia(Double media) {
this.media = media;
}
public Long getSequencia() {
return sequencia;
}
public void setSequencia(Long sequencia) {
this.sequencia = sequencia;
}
public Boolean getAtivo() {
return ativo;
}
public void setAtivo(Boolean ativo) {
this.ativo = ativo;
}
public byte[] getMaterial() {
return material;
}
public void setMaterial(byte[] material) {
this.material = material;
}
}
|
Ruby
|
UTF-8
| 557 | 4.03125 | 4 |
[] |
no_license
|
# 20時から翌朝7時までにオウムに喋られると問題があるのでその場合は「NG」、
# それ以外は「OK」と出力するメソッドを作成します。
# オウムが喋る時をture、喋らない時をfalseと入力することにし、時刻も同時に入力します。
def parrot_trouble(talking, hour)
talking && (7 > hour || 20 <= hour) ? (puts "NG") : (puts "OK")
end
parrot_trouble(true, 6)
parrot_trouble(true, 7)
parrot_trouble(false, 6)
parrot_trouble(false, 7)
parrot_trouble(true, 10)
parrot_trouble(true, 20)
|
SQL
|
UTF-8
| 1,061 | 3.328125 | 3 |
[] |
no_license
|
USE [SnackOverflowDB]
GO
IF EXISTS(SELECT * FROM sys.objects WHERE type = 'P' AND name = 'sp_create_product_order')
BEGIN
DROP PROCEDURE sp_create_product_order
Print '' print ' *** dropping procedure sp_create_product_order'
End
GO
Print '' print ' *** creating procedure sp_create_product_order'
GO
Create PROCEDURE sp_create_product_order
(
@CUSTOMER_ID[INT],
@EMPLOYEE_ID[INT],
@ORDER_TYPE_ID[NVARCHAR](250),
@ADDRESS_TYPE[NVARCHAR],
@DELIVERY_TYPE_ID[NVARCHAR](50),
@AMOUNT[DECIMAL](6,2),
@ORDER_DATE[DATETIME],
@DATE_EXPECTED[DATETIME],
@DISCOUNT[DECIMAL](5,2),
@ORDER_STATUS_ID[NVARCHAR](50),
@USER_ADDRESS_ID[INT],
@HAS_ARRIVED[BIT]
)
AS
BEGIN
INSERT INTO PRODUCT_ORDER (CUSTOMER_ID, EMPLOYEE_ID, ORDER_TYPE_ID, ADDRESS_TYPE, DELIVERY_TYPE_ID, AMOUNT, ORDER_DATE, DATE_EXPECTED, DISCOUNT, ORDER_STATUS_ID, USER_ADDRESS_ID, HAS_ARRIVED)
VALUES
(@CUSTOMER_ID, @EMPLOYEE_ID, @ORDER_TYPE_ID, @ADDRESS_TYPE, @DELIVERY_TYPE_ID, @AMOUNT, @ORDER_DATE, @DATE_EXPECTED, @DISCOUNT, @ORDER_STATUS_ID, @USER_ADDRESS_ID, @HAS_ARRIVED)
SELECT SCOPE_IDENTITY()
END
|
JavaScript
|
UTF-8
| 2,148 | 3.09375 | 3 |
[] |
no_license
|
/*
** DOM Navigate:
** find_ancestor_class: find first ancestor by classname
** find_ancestor_tag: find first ancestor by tagname
** find_1stDescendant_with: find first descendant by tag and then class
**
** Event control (IE fallback):
** getTriggerEle
** preventLinkAction
** stopBubbling
** addEvent
**
** Other:
** encodeForPost: encode data into utf-8 and the form data type
**
*/
function find_ancestor_class(element, classname){
let targetEle = element;
do{
targetEle = targetEle.parentNode;
}while(!targetEle.className.match(classname));
return targetEle;
}
function find_ancestor_tag(element, tagname){
let targetEle = element;
do{
targetEle = targetEle.parentNode;
var checkTagName = targetEle.tagName.toLowerCase();
}while( checkTagName != tagname && checkTagName != 'body');
return targetEle;
}
function find_1stDescendant_with(element, tagname, classname){
let tagElements = element.getElementsByTagName(tagname);
let i;
for(i=0;i<tagElements.length;i++){
if(tagElements[i].className.match(classname))
break;
}
if(i<tagElements.length){
return tagElements[i];
}else{
return null;
}
}
function getTriggerEle(e){
if(!e){
e = window.event;
}
element = e.target || e.srcElement;
return element;
}
function preventLinkAction(e){
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
function stopBubbling(e){
if(e.stopPropogation){
e.stopPropogation();
}else{
e.cancelBubble = true;
}
}
function addEvent(el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function () {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
// modify the code in MDN document about 'encodeURIComponent'
function encodeForPost(str) {
return encodeURIComponent(str).replace('%20','+').replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
|
Java
|
UTF-8
| 679 | 1.9375 | 2 |
[] |
no_license
|
package ee.bcs.valiit.controller;
import java.math.BigInteger;
public class CreateAccountRequest {
private Integer accountNr;
private BigInteger balance;
private BigInteger clientId;
public Integer getAccountNr() {
return accountNr;
}
public void setAccountNr(Integer accountNr) {
this.accountNr = accountNr;
}
public BigInteger getBalance() {
return balance;
}
public void setBalance(BigInteger balance) {
this.balance = balance;
}
public BigInteger getClientId() {
return clientId;
}
public void setClientId(BigInteger clientId) {
this.clientId = clientId;
}
}
|
Markdown
|
UTF-8
| 7,946 | 3.265625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<!--Title: Glossary-->
There are some terms that reoccur throughout the documentation and show up in the StructureMap API. Understanding these terms and how they relate to StructureMap isn't a prerequisite to using StructureMap, but it helps.
## Container
Tools like StructureMap are generally known as *Inversion of Control (IoC) Containers* or *Dependency Injection (DI) Containers*. In the Java world they are also known as *Lightweight Containers* to differentiate them from the older *EJB Containers*.
A container is a tool that can help you composing object graphs and managing their scope (lifecycle). Altough you can do Inversion of Control and Dependecy Injection manually, using tools like StructureMap makes you far more productive and succesfull in doing so.
Obviously there is more to a container then resolving services and managing their scope, but in the core that's just what it is. Before you can do so you need to tell StructureMap, the container, how it must compose those objects graphs and what their lifecycle is. This is called registration and can be done in various mixed ways. The strongly recommend way would be using the <[linkto:registration/registry-dsl]>. In your registration you're basically mapping abstractions to concrete types and defining their lifecycle.
A simple example of a container using the <[linkto:registration/registry-dsl]>:
<[sample:foobar-registry]>
<[sample:glossary-container]>
Because we didn't specify the lifecycle for both registrations, the default `Transient` lifecycle will be used. This will instruct the container to create a new instance for every request for a plugin type `IFoo` or `IBar`.
More advanced features that the container can do are things like: Interception, Auto-Wiring, Forwarding Types.
## Nested Container
A nested container is used to mark the scope of short lived transactions or web requests and track and clean up objects implementing the `IDisposable` interface for that operation.
You can ask an existing container to create a nested container for you like in the following example:
<[sample:glossary-nested-container]>
For more detailed information about nested containers and their special properties you can read the <[linkto:the-container/nested-containers]> topic.
## PluginType and PluggedType
The term plugin type is used throughout the code and documentation to mean the type that you want to register or resolve. More generally this type is known as the service type. This type can be a concrete class or in most cases, it will be a form of abstraction like an abstract class or interface.
The term plugged type means the actual concrete type that you get when you request the plugin type. This type must obviously implement the plugin type contract.
In your registration you could have something like this:
<[sample:foo-registry]>
<[sample:glossary-pluggintype-and-plugged-type]>
If you request an object of `IFoo`, you'll get an instance of the `Foo` class. In this case, `IFoo` is the plugin type (what you're asking for) and `Foo` is the plugged type (the concrete class you'll get that fulfills, implements the plugin type contract).
## PluginFamily
This term you will not see so often because it's mostly used by StructureMap itself. A `PluginFamily` represents a [CLR](http://en.wikipedia.org/wiki/Common_Language_Runtime) type (the plugin type) that StructureMap can build, and all of the possible plugged types that implement the [CLR](http://en.wikipedia.org/wiki/Common_Language_Runtime) type.
In the following code StructureMap internally creates one `PluginFamily` of the plugin type `IFoo` with two instances `Foo` and `SomeOtherFoo`, where `Foo` is the default instance because it's registered through `For<PLUGIN_TYPE>().Use<PLUGGED_TYPE>()`.
<[sample:glossary-pluginfamily]>
Before StructureMap 3.0 you have probably seen the term used in an exception message when you request a plugin type that doesn't have a default instance defined.
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily [plugin type]
This specific exception message is gone in 3.0 because the exception messages were modernized.
## Plugin Graph
A `PluginGraph` is the configuration model of the runtime configuration of a StructureMap container. The `PluginGraph` model can be manipulated directly in StructureMap 3.0 for
any kind of special convention that doesn't fit into the existing conventional support.
## Instance
In StructureMap terms, an "Instance" is a configured and named strategy to build or locate a named object instance for a requested Plugin Type. An "Instance" does not automatically equate to a concrete type. For example, let's say that we're building a system to automate a warehouse. Our system might consume an interface called IShippingService that acts as a Gateway to various ways of shipping boxes out of our warehouse.
<[sample:IShippingService]>
Our warehouse system might have to interact with three types of shipping: domestic, international, and intra-company or internal shipments. The internal shipping service runs in process with the warehouse application, but domestic and international shipping is done by invoking external web services. The registration of the IShippingService Instances might look like this:
<[sample:ShippingRegistry]>
In the registration code above, there are three "Instances." You can access the various IShippingService Instance's by name:
<[sample:getting-ishippingservice]>
Asking for the "International" or the "Domestic" instance of IShippingService will both return an object of type ShippingWebService, but the two objects will be differently configured with unique Url's.
There is an actual class in StructureMap that represents an "[Instance](https://github.com/structuremap/structuremap/blob/master/src/StructureMap/Pipeline/Instance.cs)."
When you call `Container.GetInstance<T>("the instance that I want")` or `Container.GetInstance<T>()`, the internal `Container` object is locating the correct Instance object and then using the Instance's internal _build plan_ to resolve or construct the actual object.
A StructureMap "Instance" is a close analogue for what many other IoC tools call a "Component."
## Lifecycle (or Scope)
The power of an IoC container isn't just in building object graphs for you, it's also about _scoping_ an object graph to what StructureMap calls a _lifecycle_. Think of it this way:
when you ask StructureMap for a service or (much more commonly) when StructureMap is filling a dependency behind the scenes, do you want:
* A brand new, unique object each time?
* The exact same object as the rest of the graph is using?
* The exact same object every single time throughout the application?
## Registry
A `Registry` or a sub class of `Registry` is a class that let's you create reusable configuration for StructureMap containers.
## Profile
StructureMap 3.0 features a complete rewrite of the ancient _Profile_ functionality where you can create your base Container configuration with additional _Profile_
configuration that overrides one or more of the parent Container defaults. The _Profile_ functionality was originally meant to handle differences between
development, testing, and production environments but has been more commonly used for multi-tenancy situations. Think of a _Profile_ as an application or tenant mode.
## Auto wiring
You'd never get anything done if you had to tell StructureMap how to build each and every constructor or setter dependency on every concrete class. Fortunately, StructureMap like
most IoC container tools, supports the concept of _auto-wiring_ -- meaning that StructureMap can happily infer dependency requirements from constructor functions and setter
rules and fill those dependencies with the default configuration for the declared dependency type.
Let's just see it in action:
<[sample:auto-wiring-sample]>
|
JavaScript
|
UTF-8
| 1,160 | 2.578125 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
( function( $ ) {
"use strict";
$.extend( {
openCageGeocode: function(options) {
options = $.extend( {
place: "",
apikey: "",
success: function(_geoData) {},
error: function(_message) {}
}, options );
var errorMsg = "Could not geocode this location.";
function geocodeURL() {
var baseURL = "https://api.opencagedata.com/geocode/v1/json?q=";
var apiKey = "&key=" + options.apikey;
return encodeURI(baseURL + options.place + apiKey);
}
$.getJSON(
geocodeURL(),
function( data ) {
if( data !== null && data.results.length ) {
var geoData = {};
var firstResult = data.results[0];
geoData.placeName = firstResult.formatted
geoData.placeURL = firstResult.annotations.OSM.url
geoData.latitude = firstResult.geometry.lat
geoData.longitude = firstResult.geometry.lng
options.success( geoData )
} else { options.error(errorMsg); }
}
).fail(function(){ options.error(errorMsg); });
return this;
}
} );
} )( jQuery );
|
JavaScript
|
UTF-8
| 1,222 | 3.0625 | 3 |
[] |
no_license
|
import React from 'react';
import HitPoint from './HitPoint.js'
const HPBar = (props) => {
const {HP} = props;
let displayArr = [];
const fillSlots = () => {
//Fill array with 1 until reaching the HP in props
for(let i = 0; i < HP; i++ ){
displayArr.push(1)
}
//Subtract HP passed in props from 10 to push 0's into the array until the total length is 10
for(let i = 0; i < 10 - HP; i++){
displayArr.push(0)
}
}
fillSlots()
const playerColor = () => {
//For styling purposes, if p1 is passed in as props, create a p1 health bar, otherwise create a p2 health bar
if (props.p1){
return (
<div className="p1_health_bar">
{displayArr.reverse().map((hitPoint) => <HitPoint hitPoint={hitPoint}/>)}
</div>
)
} else {
return (
<div className="p2_health_bar">
{displayArr.map((hitPoint) => <HitPoint hitPoint={hitPoint}/>)}
</div>
)
}
}
return(
<>
{playerColor()}
</>
)
}
export default HPBar
|
Java
|
UTF-8
| 3,357 | 2.46875 | 2 |
[] |
no_license
|
package com.muye.kl.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport
{
/**
* 自定义生成key的规则
* @return
*/
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
//格式化缓存key字符串
StringBuilder sb = new StringBuilder();
//追加类名
sb.append(o.getClass().getName());
//追加方法名
sb.append(method.getName());
//遍历参数并且追加
for (Object obj : objects) {
sb.append(obj.toString());
}
System.out.println("调用Redis缓存Key : " + sb.toString());
return sb.toString();
}
};
}
/**
* 采用RedisCacheManager作为缓存管理器
* @param objectMapper
* @param redisConnectionFactory
* @return
*/
//缓存管理器
@Bean(name = "cacheManager")
@Primary
public CacheManager cacheManager(ObjectMapper objectMapper, RedisConnectionFactory redisConnectionFactory) {
//设置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues()
// .computePrefixWith(cacheName -> "yourAppName".concat(":").concat(cacheName).concat(":"))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
}
}
|
C#
|
UTF-8
| 545 | 2.546875 | 3 |
[] |
no_license
|
using(SqlConnection con = new SqlConnection("your conn"))
{
con.Open();
string sql = "SELECT MA_BO_CAU_HOI FROM R_NGUOICHOI_BOCAUHOI where MA_NGUOI_CHOI=@Param1";
DataTable data = new DataTable();
using(SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@Param1", cbbten.SelectedIndex);
adapter.SelectCommand = cmd;
adapter.Fill(data);
}
}
|
Java
|
UTF-8
| 984 | 3.65625 | 4 |
[] |
no_license
|
package LeetCode;
import java.util.Arrays;
public class Q53MaxSubArray {
//有滑窗的感觉,但不需要用左右指针
//用sum记录当前连续子数组的值,如果这个值大于0,那sum就更新为当前值加sum。
//如果这个值小于0,说明到目前为止的子数组对后面是副作用,就直接丢掉,子数组从当前位置开始。
public static int maxSubArray(int[] nums) {
int res = nums[0];
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (sum > 0) {
sum = sum + nums[i];
} else {
sum = nums[i];
}
res = Math.max(res,sum);
}
res = Math.max(res, sum);
return res;
}
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
Arrays.stream(nums).forEach(num-> System.out.println(num));
System.out.println(maxSubArray(nums));
}
}
|
Markdown
|
UTF-8
| 2,516 | 3.109375 | 3 |
[] |
no_license
|
---
layout: post
title: GM History page
date: 2020-08-20
tags:
- post
- New Feature
---
Back in [the old days](https://basketball-gm.com/old/), there was no way to switch your team in Basketball GM. If you got fired from your job, it was game over. Try again a new league. In part that was just because I hadn't gotten around to adding that feature yet. But also I thought it might be a good way to ensure a league database never grows too large, because at some point you were bound to get fired.
This turned out to not be a very popular feature. People found it too harsh to be forced to quit playing their league. So eventually I made it so you could switch to a new team after getting fired, and also added the ability to switch at any time in God Mode.
This introduced another problem. The game wasn't really designed to support switching teams, so there was no way to easily view your performance was across all the teams you managed in league history. But today there is!
Now you can go to Teams > GM History to view a summary of your overall performance as a GM, tracking all the seasons for all the different teams you managed. Here's what it looks like:
<!--more-->
<figure><a href="/files/gm-history.png"><img src="/files/gm-history.png" class="img-fluid"></a></figure>
One caveat with this. Previously, your past teams were not tracked at all. So for seasons simulated prior to this update, the GM History page will assume that you managed your current team since the beginning of the league. Only future team switches will be tracked. If you want to change that, see [the "Change GM History teams" section on this page](/basketball/manual/worker-console/).
There's also another new feature! Like I mentioned above, the original ways to change your team were either to get fired or use God Mode. There of course is another way that real GMs switch teams - they do a really good job and get hired by another team. No, this is how it happens in Basketball GM too:
<figure><img src="/files/job-offers.png" class="img-fluid"></figure>
It's based on the score you see in your annual performance evaluation. The higher your score, the better your odds of getting offers from other teams, up to 50% for a perfect score.
One other edge case is switching your team in God Mode, because that allows you to switch teams at any time, including multiple times during the same season. If you do that, the team logged in the GM History page will be whatever team you controlled at the end of the season.
|
Markdown
|
UTF-8
| 78,101 | 2.6875 | 3 |
[] |
no_license
|
# 谷歌Python代码风格指南 中文翻译
Update: 2020.01.31
Translator: [shendeguize@github](
https://github.com/shendeguize)
Link: [
https://github.com/shendeguize/GooglePythonStyleGuideCN](
https://github.com/shendeguize/GooglePythonStyleGuideCN)
本翻译囿于水平,可能有不准确的地方,欢迎指出,谢谢大家
*如有引用,请注明出处*
## 0 目录
- - [谷歌Python代码风格指南 中文翻译](#谷歌python代码风格指南-中文翻译)
- [0 目录](#0-目录)
- [1 背景](#1-背景)
- [2 Python语言规则](#2-python语言规则)
- [2.1 Lint](#21-lint)
- [2.1.1Definition(以下都译为定义)](#211definition以下都译为定义)
- [2.1.2 Pros](#212-pros)
- [2.1.3 Cons](#213-cons)
- [2.1.4 Decision(以下都译为建议)](#214-decision以下都译为建议)
- [2.2 Imports](#22-imports)
- [2.2.1 定义](#221-定义)
- [2.2.2 Pros](#222-pros)
- [2.2.3 Cons](#223-cons)
- [2.2.4 建议](#224-建议)
- [2.3 包](#23-包)
- [2.3.1 Pros](#231-pros)
- [2.3.2 Cons](#232-cons)
- [2.3.3 建议](#233-建议)
- [2.4 异常](#24-异常)
- [2.4.1 定义](#241-定义)
- [2.4.2 Pros](#242-pros)
- [2.4.3 Cons](#243-cons)
- [2.4.4 建议](#244-建议)
- [2.5 全局变量](#25-全局变量)
- [2.5.1 定义](#251-定义)
- [2.5.2 Pros](#252-pros)
- [2.5.3 Cons](#253-cons)
- [2.5.4 建议](#254-建议)
- [2.6 内嵌/局部/内部 类和函数](#26-内嵌局部内部-类和函数)
- [2.6.1 定义](#261-定义)
- [2.6.2 Pros](#262-pros)
- [2.6.3 Cons](#263-cons)
- [2.6.4 建议](#264-建议)
- [2.7 列表推导和生成器表达式](#27-列表推导和生成器表达式)
- [2.7.1 定义](#271-定义)
- [2.7.2 Pros](#272-pros)
- [2.7.3 Cons](#273-cons)
- [2.7.4 建议](#274-建议)
- [2.8 默认迭代器和运算符](#28-默认迭代器和运算符)
- [2.8.1 定义](#281-定义)
- [Pros](#pros)
- [Cons](#cons)
- [建议](#建议)
- [2.9 生成器](#29-生成器)
- [2.9.1 定义](#291-定义)
- [2.9.2 Pros](#292-pros)
- [2.9.3 Cons](#293-cons)
- [2.9.4 建议](#294-建议)
- [2.10 Lambda表达式](#210-lambda表达式)
- [2.10.1 定义](#2101-定义)
- [2.10.2 Pros](#2102-pros)
- [2.10.3 Cons](#2103-cons)
- [2.10.4 建议](#2104-建议)
- [2.11 条件表达式](#211-条件表达式)
- [2.11.1 定义](#2111-定义)
- [2.11.2 Pros](#2112-pros)
- [2.11.3 Cons](#2113-cons)
- [2.11.4 建议](#2114-建议)
- [2.12 默认参数值](#212-默认参数值)
- [2.12.1 定义](#2121-定义)
- [2.12.2 Pros](#2122-pros)
- [2.12.3 Cons](#2123-cons)
- [2.12.4 建议](#2124-建议)
- [2.13 属性](#213-属性)
- [2.13.1 定义](#2131-定义)
- [2.13.2 Pros](#2132-pros)
- [2.13.3 Cons](#2133-cons)
- [2.13.4 建议](#2134-建议)
- [2.14 True/False表达式](#214-truefalse表达式)
- [2.14.1 定义](#2141-定义)
- [2.14.2 Pros](#2142-pros)
- [2.14.3 Cons](#2143-cons)
- [建议](#建议-1)
- [2.15 弃用的语言特性](#215-弃用的语言特性)
- [2.15.1 定义](#2151-定义)
- [2.15.2 建议](#2152-建议)
- [2.16 词法作用域](#216-词法作用域)
- [2.16.1 定义](#2161-定义)
- [2.16.2 Pros](#2162-pros)
- [2.16.3 Cons](#2163-cons)
- [2.16.4 建议](#2164-建议)
- [2.17 函数和方法装饰器](#217-函数和方法装饰器)
- [2.17.1 定义](#2171-定义)
- [2.17.2 Pros](#2172-pros)
- [2.17.3 Cons](#2173-cons)
- [2.17.4 建议](#2174-建议)
- [2.18 线程](#218-线程)
- [2.19 过于强大的特性](#219-过于强大的特性)
- [2.19.1 定义](#2191-定义)
- [2.19.2 Pros](#2192-pros)
- [2.19.3 Cons](#2193-cons)
- [2.19.4 定义](#2194-定义)
- [2.20 新版本Python: Python3 和从`__future__`import](#220-新版本python-python3-和从__future__import)
- [2.20.1 定义](#2201-定义)
- [2.20.2 Pros](#2202-pros)
- [2.20.3 Cons](#2203-cons)
- [2.20.4 建议](#2204-建议)
- [2.21 带有类型注释的代码](#221-带有类型注释的代码)
- [2.21.1 定义](#2211-定义)
- [2.21.2 Pros](#2212-pros)
- [2.21.3 Cons](#2213-cons)
- [2.21.4 建议](#2214-建议)
- [3 Python代码风格规范](#3-python代码风格规范)
- [3.1 分号](#31-分号)
- [3.2 行长度](#32-行长度)
- [3.3 括号](#33-括号)
- [3.4 缩进](#34-缩进)
- [3.4.1 关于尾后逗号](#341-关于尾后逗号)
- [3.5 空行](#35-空行)
- [3.6 空格](#36-空格)
- [3.7 Shebang](#37-shebang)
- [3.8 注释和文档字符串](#38-注释和文档字符串)
- [3.8.1 文档字符串](#381-文档字符串)
- [3.8.2 模块](#382-模块)
- [3.8.3 函数和方法](#383-函数和方法)
- [3.8.4 类](#384-类)
- [3.8.5 块注释和行注释](#385-块注释和行注释)
- [3.8.6 标点,拼写和语法](#386-标点拼写和语法)
- [3.9 类](#39-类)
- [3.10 字符串](#310-字符串)
- [3.11 文件和socket](#311-文件和socket)
- [3.12 TODO注释](#312--todo注释)
- [3.13 import格式](#313-import格式)
- [3.14 语句](#314-语句)
- [3.15 访问](#315-访问)
- [3.16 命名](#316-命名)
- [3.16.1 要避免的名字:](#3161-要避免的名字)
- [3.16.4 命名约定](#3164-命名约定)
- [3.16.3 文件名](#3163-文件名)
- [3.16.4 Guido的指导建议](#3164-guido的指导建议)
- [3.17 Main](#317-main)
- [3.18 函数长度](#318-函数长度)
- [3.19 类型注释](#319-类型注释)
- [3.19.1 基本规则](#3191-基本规则)
- [3.19.2 分行](#3192-分行)
- [3.19.3 前置声明](#3193-前置声明)
- [3.19.4 默认值](#3194-默认值)
- [3.19.5 NoneType](#3195-nonetype)
- [3.19.6 类型别名](#3196-类型别名)
- [3.19.7 忽略类型检查](#3197-忽略类型检查)
- [3.19.8 对变量注释类型](#3198-对变量注释类型)
- [3.19.9 元组和列表](#3199-元组和列表)
- [3.19.10 TypeVars](#31910-typevars)
- [3.19.11 字符串类型](#31911-字符串类型)
- [3.19.12 typing的import](#31912-typing的import)
- [3.19.13 条件import](#31913-条件import)
- [3.19.14 循环依赖](#31914-循环依赖)
- [3.19.15 泛型](#31915--泛型)
- [4 最后的话](#4-最后的话)
## 1 背景
Python是谷歌主要是用的动态语言,本风格指导列举了使用Python编程时应该做和不该做的事项(dos & don'ts)
为了帮助你正确地组织代码,我们编写了一个[Vim的设置文件](https://google.github.io/styleguide/google_python_style.vim).对于Emacs,默认设置即可.
许多团队使用[yapf](https://github.com/google/yapf/)自动格式工具来避免格式争议
## 2 Python语言规则
### 2.1 Lint
对代码使用`pylint`
#### 2.1.1Definition(以下都译为定义)
`pylint`是一个用于在Python代码中发现bug和代码风格问题的工具,,`pylint`查找那些常在非动态语言(例如C或C++)编译器中捕获的问题.由于Python是动态语言,一些警告可能不正确,不过应该非常少有错误警告.
#### 2.1.2 Pros
能够发现一些易被遗漏的错误,类似拼写错误,调用早于声明等等.
#### 2.1.3 Cons
`pylint`并不完美,为了更好的利用工具,我们有时候需要
a. Write around it(适配上下文风格)
b. 压制一些警告
c. 优化工具
#### 2.1.4 Decision(以下都译为建议)
确保对代码应用`pylint`
如果一些警告是不合适的,就抑制这些警告,这是为了让其他警告不会被隐藏.为了压制警告,可以设置行级别的注释:
```Python
dict = 'something awful' # Bad Idea... pylint: disable=redefined-builtin
```
`pylint`警告包含标识名(`empty-docstring`),谷歌专有的警告以`g-`开头.
如果抑制警告的原因在标识名称中表述不够清晰,请额外添加注解.
用这种方式来抑制警告的优点是我们能够简单地找到抑制的警告并且重新访问这些警告.
可以通过下述方式来获得`pylint`警告列表:
```bash
pylint --list-msgs
```
用下述方式来获取某个特定消息的更多具体信息:
```bash
pylint --help-msg=C6409
```
优先使用`pylint: disable`而非旧方法(`pylint: disable-msg`)
如果要抑制由于参数未使用的警告,可以在函数开头del,并注释为什么要删除这些未使用参数,仅仅一句"unused"是不够的:
```Python
def viking_cafe_order(spam, beans, eggs=None):
del beans, eggs # Unused by vikings.
return spam + spam + spa
```
其他可以用来抑制警告的方式包括用`'_'`作为未使用参数的标识,在参数名前增加`'unused_'`,或者分配这些参数到`'_'`.这些方式是可以的,但是已经不鼓励继续使用.前两种方式会影响到通过参数名传参的调用方式,而最后一种并不能保证参数确实未被使用.
### 2.2 Imports
只在import包和模块的时候使用`import`,而不要应用在单独的类或函数.(这一条对于[typing_module](https://google.github.io/styleguide/pyguide.html#typing-imports)有特别的意外)
#### 2.2.1 定义
一个模块到另一个模块之间共享代码的复用性机制
#### 2.2.2 Pros
命名空间管理约定简单,每个标识的源都一致性地被指明了.例如`x.Obj`表示`Obj`是在模块`x`中定义的
#### 2.2.3 Cons
模块名可能会有冲突,一些模块名可能很长,比较不方便
#### 2.2.4 建议
* ` import x`(当`x`是包或模块)
* `from x import y` (当`x`是包前缀,`y`是不带前缀的模块名)
* `from x import y as z` (当有重复模块名`y`或`y`过长不利于引用的时候)
* `import y as z` (仅在非常通用的简写的时候使用例如`import numpy as np`)
以`sound.effects.echo`为例:
```Python
from sound.effects import echo...echo.EchoFilter(input, output, delay=0.7, atten=4)
```
不要使用相对引用,即便在同一包内,也使用完整包名import,这有助于避免无意重复import包.
从[typing module](https://google.github.io/styleguide/pyguide.html#typing-imports)和[six.moves module](https://six.readthedocs.io/#module-six.moves) import不适用上述规则
### 2.3 包
每一模块都要从完整路径import
#### 2.3.1 Pros
能够避免模块名冲突以及由于模块搜索路径与作者预期不符而造成的错误引用.让查找模块更简单.
#### 2.3.2 Cons
让部署代码时有些困难,因为包架构也需要赋值,不过对于现在的部署机制而言,这其实不是问题.
#### 2.3.3 建议
所有的新代码都要从完整包名来import模块
import示例应该像这样:
**Yes:**
```Python
# Reference absl.flags in code with the complete name (verbose).
# 在代码中使用完整路径调用absl.flags
import absl.flagsfrom doctor.who import jodie
FLAGS = absl.flags.FLAGS
```
``` Python
# Reference flags in code with just the module name (common).
# 在代码中只用包名来调用flags
from absl import flagsfrom doctor.who import jodie
FLAGS = flags.FLAGS
```
**No:**(假设文件在`doctor/who`中,`jodie.py`也在这里)
```Python
# Unclear what module the author wanted and what will be imported. The actual
# import behavior depends on external factors controlling sys.path.
# Which possible jodie module did the author intend to import?
# 不清楚作者想要哪个包以及最终import的是哪个包,
# 实际的import操作依赖于受到外部参数控制的sys.path
# 那么哪一个可能的jodie模块是作者希望import的呢?
import jodie
```
不应该假设主代码所在路径被包含在`sys.path`中,即使有些时候可以work.在上一例代码中,我们应该认为`import jodie`指的是import一个叫做`jodie`的第三方包或者顶级目录中的`jodie`,而非一个当前路径的`jodie.py`
### 2.4 异常
异常处理是允许使用的,但使用务必谨慎
#### 2.4.1 定义
异常是一种从正常代码段控制流中跳出以处理错误或者其他异常条件的手段.
#### 2.4.2 Pros
正常代码的控制流时不会被错误处理代码影响的.异常处理同样允许在某些情况下,控制流跳过多段代码,例如在某一步从N个嵌入函数返回结果而非强行延续错误代码.
#### 2.4.3 Cons
可能会让控制流变的难于理解,也比较容易错过调用库函数的报错.
#### 2.4.4 建议
异常必定遵循特定条件:
* 使用`raise MyError('Error message')`或者`raise MyError()`,不要使用两段`raise MyError, 'Error message'`
* 当内置异常类合理的时候,尽量使用内置异常.例如:抛出`ValueError`来表示一个像是违反预设前提(例如传参了一个负数给要求正数的情况)的程序错误发生.
不要使用`assert`来片段公共结构参数值.`assert`是用来确认内部计算正确性也不是用来表示一些预期外的事件发生的.如果异常是后续处理要求的,用`raise`语句来处理,例如:
**Yes:**
```Python
def connect_to_next_port(self, minimum):
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
# Note that this raising of ValueError is not mentioned in the doc
# string's "Raises:" section because it is not appropriate to
# guarantee this specific behavioral reaction to API misuse.
# 注意抛出ValueError这件事是不在docstring中的Raises中提及, 因为这样并适合保障对于API误用的特殊反馈
raise ValueError('Minimum port must be at least 1024, not %d.' % (minimum,))
port = self._find_next_open_port(minimum)
if not port:
raise ConnectionError('Could not connect to service on %d or higher.' % (minimum,))
assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port, minimum)
return port
```
**No:**
```Python
def connect_to_next_port(self, minimum):
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
"""
assert minimum >= 1024, 'Minimum port must be at least 1024.'
port = self._find_next_open_port(minimum)
assert port is not None
return port
```
* 库或者包可能会定义各自的异常.当这样做的时候,必须要继承一个已经存在的异常类,异常类的名字应该以`Error`结尾,并且不应该引入重复(`foo.FooError`)
* 永远不要用捕获全部异常的`except:`语句,或者捕获`Exception`或者`StandardError`除非:
* 再次抛出这个异常
* 在程序中异常不会继续但是会被记录以及消除(例如通过保护最外层的方式保护线程不会崩溃)的地方创造一个孤立点.
Python在这个方面容忍度很高,并且`except:`语句会捕获包括拼写错误,sys.exit(),Ctrl+C终止,单元测试失败和和所有你并没有想到捕获的其他异常.
* 最精简`try/except`表达式内部的代码量,`try`代码块里的代码体量越大,月可能会在你不希望抛出异常的代码中抛出异常,进而在这种情况下,`try/except`掩盖了一个真实的异常
* 使用finally来执行代码,这些代码无论是否有异常在`try`代码块被抛出都会被执行.这在清理(即关闭文件)时非常有用.
* 当捕获了异常时,用as而不是逗号分段.
```Python
try:
raise Error()
except Error as error:
pass
```
### 2.5 全局变量
避免全局变量
#### 2.5.1 定义
在模块级别或者作为类属性声明的变量
#### 2.5.2 Pros
有些时候有用
#### 2.5.3 Cons
在import的过程中,有可能改变模块行为,因为在模块首次被引入的过程中,全局变量就已经被声明
#### 2.5.4 建议
避免全局变量
作为技术变量,模块级别的常量是允许并鼓励使用的.例如`MAX_HOLY_HANDGRENADE_COUNT = 3`, 常量必须由大写字母和下划线组成,参见下方[命名规则](https://google.github.io/styleguide/pyguide.html#s3.16-naming)
如果需要,全局变量需要在模块级别声明,并且通过在变量名前加`_`来使其对模块内私有化.外部对模块全局变量的访问必须通过公共模块级别函数,参见下方[命名规则](https://google.github.io/styleguide/pyguide.html#s3.16-naming)
### 2.6 内嵌/局部/内部 类和函数
内嵌局部函数或类在关闭局部变量时是可以的.内部类意识可用的.(译注:这里我的理解是当内嵌局部函数或类是和局部变量在同一个封闭作用域内是可以的.)
#### 2.6.1 定义
类可以在方法,函数,类内定义.函数可以在方法或函数内定义.内嵌函数对封闭作用域的变量具有只读访问权限.
#### 2.6.2 Pros
允许定义只在非常有限作用域内可用的工具类或工具函数.Very ADT-y(??符合抽象数据类型要求???),通常用于实现装饰器
#### 2.6.3 Cons
内嵌或局部类的实例是不能被pickle的,内嵌函数或类是不能被直接测试的.嵌套会让外部函数更长并且更难读懂.
#### 2.6.4 建议
除了一些特别声明,这些内嵌/局部/内部类和函数都是可以的.
避免内嵌函数或类除了需要关闭一个局部值的时候.(译者理解可能是除了将局部变量封闭在同一个作用域的情况以外).不要把一个函数转为内嵌指示为了避免访问.在这种情况下,把函数置于模块级别并在函数名前加`_`以保证测试是可以访问该函数的.
### 2.7 列表推导和生成器表达式
在简单情况下是可用的
#### 2.7.1 定义
List, Dict和Set推导生成式以及生成器表达式提供了一个简明有效的方式来生成容器和迭代器而不需要传统的循环,`map()`,`filter()`或者`lambda表达式`
#### 2.7.2 Pros
简单地推导表达比其他的字典,列表或集合生成方法更加简明清晰.生成器表达式可以很有效率,因为完全避免了生成列表.
#### 2.7.3 Cons
负载的推导表达式或生成器表达式很难读懂
#### 2.7.4 建议
简单情况下使用时可以的.每个部分(mapping表达式,filter表达式等)都应该在一行内完成.多个for条款或者filter表达式是不允许的.当情况变得很复杂的适合就使用循环.
**Yes:**
```Python
result = [mapping_expr for value in iterable if filter_expr]
result = [{'key': value} for value in iterable
if a_long_filter_expression(value)]
result = [complicated_transform(x)
for x in iterable if predicate(x)]
descriptive_name = [
transform({'key': key, 'value': value}, color='black')
for key, value in generate_iterable(some_input)
if complicated_condition_is_met(key, value)
]
result = []
for x in range(10):
for y in range(5):
if x * y > 10:
result.append((x, y))
return {x: complicated_transform(x)
for x in long_generator_function(parameter)
if x is not None}
squares_generator = (x**2 for x in range(10))
unique_names = {user.name for user in users if user is not None}
eat(jelly_bean for jelly_bean in jelly_beans
if jelly_bean.color == 'black')
```
**No:**
```Python
result = [complicated_transform(
x, some_argument=x+1)
for x in iterable if predicate(x)]
result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
return ((x, y, z)
for x in range(5)
for y in range(5)
if x != y
for z in range(5)
if y != z)
```
### 2.8 默认迭代器和运算符
对支持默认迭代器和云算法的类型例如列表,字典和文件等使用它们
#### 2.8.1 定义
容器类型(例如字典,列表等)定义了的默认的迭代器和成员检查运算符.
#### Pros
默认迭代器和操作符是简单有效的,能够直接不需额外调用方法地表达操作.使用默认操作符的函数是通用的.能被用于任何支持这些操作的类型.
#### Cons
不能通过方法名来分辨类型,例如`has_key()`意味着字典,当然这也是一种优势.
#### 建议
对于支持的类型诸如列表,字典和文件,使用默认迭代器和操作符.内置类型同样定义了迭代器方法.优先使用这些方法而非那些返回列表的方法.除非能够确定在遍历容器的过程中不会改变容器.不要使用Python 2专有迭代方法除非必要.
**Yes:**
```Python
for key in adict: ...
if key not in adict: ...
if obj in alist: ...
for line in afile: ...
for k, v in adict.items(): ...
for k, v in six.iteritems(adict): ...
```
**No:**
```Python
for key in adict.keys(): ...
if not adict.has_key(key): ...
for line in afile.readlines(): ...
for k, v in dict.iteritems(): ...
```
### 2.9 生成器
需要时使用生成器
#### 2.9.1 定义
生成器函数返回一个迭代器,每次执行`yield`语句的时候生成一个值.在生成一个值之后,生成器函数的运行被挂起直到需要下一个值.
#### 2.9.2 Pros
简化代码,因为局部变量和控制流在每次调用时被保留,生成器相比于一次性生成整个一个列表值要更节省内存.
#### 2.9.3 Cons
无
#### 2.9.4 建议
建议使用.在生成器函数的文档字符串中使用"Yields:"而非"Returns:"
### 2.10 Lambda表达式
单行代码时是可以的
#### 2.10.1 定义
lambda在一个表达式内定义了匿名函数,而不在语句里.lambda表达式常被用于定义高阶函数(例如`map()`和`filter()`)使用的回调函数或者操作符.
#### 2.10.2 Pros
方便
#### 2.10.3 Cons
比局部函数更难读懂和debug,匿名意味着堆栈跟踪更难懂.表达性受限因为lambda函数只包含一个表达式
#### 2.10.4 建议
对于单行代码而言,可以使用lambda表达式.如果`lambda`表达式内的代码超过60-80个字符,最好定义成为常规的内嵌函数.
对于一般的操作诸如乘法,使用`operator`模块内置函数而非重新定义匿名函数,例如使用`operator.mul`而非`lambda x,y: x * y`
### 2.11 条件表达式
简单情况下可以使用.
#### 2.11.1 定义
条件表达式(也称为三元运算符)是一种更短替代if语句的机制.例如`x = 1 if cond else 2`
#### 2.11.2 Pros
相对于if语句更短也更方便
#### 2.11.3 Cons
比if语句可能更难读懂,当表达式很长的时候条件部分可能很难定位.
#### 2.11.4 建议
简单情况可以使用.每个部分(真值表达式,if表达式,else表达式)必须在一行内完成.如果使用条件表达式很富的时候使用完整的if语句.
**Yes:**
```Python
one_line = 'yes' if predicate(value) else 'no'
slightly_split = ('yes' if predicate(value)
else 'no, nein, nyet')
the_longest_ternary_style_that_can_be_done = (
'yes, true, affirmative, confirmed, correct'
if predicate(value)
else 'no, false, negative, nay')
```
**No:**
```Python
bad_line_breaking = ('yes' if predicate(value) else
'no')portion_too_long = ('yes'
if some_long_module.some_long_predicate_function(
really_long_variable_name)
else 'no, false, negative, nay')
```
### 2.12 默认参数值
大多数情况下都OK
#### 2.12.1 定义
在函数参数列表的最后可以为变量设定值,例如`def foo(a, b=0):`.如果`foo`在调用时只传入一个参数,那么`b`变量就被设定为0,如果调用时传入两个参数,那么`b`就被赋予第二个参数值.
#### 2.12.2 Pros
通常一个函数可能会有大量默认值,但是很少会有需要修改这些默认值的时候.默认值就提供了一个很简单满足上述情况的方式,而不需要为这些少见的情况重新定义很多函数.因为Python不支持重载方法或函数,默认参数是一个很简单的方式来"假重载"行为.
#### 2.12.3 Cons
默认参数在模块加载时就被复制.这在参数是可变对象(例如列表或字典)时引发问题.如果函数修改了这些可变对象(例如向列表尾添加元素).默认值就被改变了.
#### 2.12.4 建议
使用时请注意以下警告----在函数或方法定义时不要将可变对象作为默认值.
**Yes:**
```Python
def foo(a, b=None):
if b is None:
b = []
def foo(a, b: Optional[Sequence] = None):
if b is None:
b = []
def foo(a, b: Sequence = ()): # Empty tuple OK since tuples are immutable 空元组是也不可变的
...
```
**No:**
```Python
def foo(a, b=[]):
...
def foo(a, b=time.time()): # The time the module was loaded??? 模块被加载的时间???
...
def foo(a, b=FLAGS.my_thing): # sys.argv has not yet been parsed... sys.argv还未被解析
...
def foo(a, b: Mapping = {}): # Could still get passed to unchecked code 仍可传入未检查的代码(此处翻译可能有误)
...
```
### 2.13 属性
使用属性可以通过简单而轻量级的访问器和设定器方法来访问或设定数据.
#### 2.13.1 定义
一种装饰器调用来在计算比较轻量级时作为标准的属性访问来获取和设定一个属性的方式
#### 2.13.2 Pros
对于简单的属性访问,减少显式的get和set方法能够提升可读性.允许惰性计算.被认为是一种Python化的方式来维护类接口.在表现上,当直接对变量的访问更合理时,允许属性绕过所需的琐碎的访问方法.
#### 2.13.3 Cons
在Python2中必须继承于`object`,可能会隐藏像是操作符重载之类的副作用.对于子类而言,属性可能有些迷惑性.
#### 2.13.4 建议
在通常会有简单而且轻量级的访问和设定方法的新代码里使用属性来访问或设定数据.属性在创建时被`@property`装饰,参加[装饰器](https://google.github.io/styleguide/pyguide.html#s2.17-function-and-method-decorators)
如果属性本身未被重写,带有属性的继承可能不够明晰,因而必须确保访问方法是被间接访问的,来确保子类的方法重载是被属性调用的(使用Template Method DP,译者:应是模板方法设计模式).
**Yes:**
```Python
class Square(object):
"""A square with two properties: a writable area and a read-only perimeter.
To use:
>>> sq = Square(3)
>>> sq.area
9
>>> sq.perimeter
12
>>> sq.area = 16
>>> sq.side
4
>>> sq.perimeter
16
"""
def __init__(self, side):
self.side = side
@property
def area(self):
"""Area of the square."""
return self._get_area()
@area.setter
def area(self, area):
return self._set_area(area)
def _get_area(self):
"""Indirect accessor to calculate the 'area' property."""
return self.side ** 2
def _set_area(self, area):
"""Indirect setter to set the 'area' property."""
self.side = math.sqrt(area)
@property
def perimeter(self):
return self.side * 4
```
### 2.14 True/False表达式
只要可能,就使用隐式False的if语句
#### 2.14.1 定义
在布尔环境下,Python对某些值判定为False,一个快速的经验规律是所有"空"值都被认为是False,所以`0, None, [], {}, ''`的布尔值都是False
#### 2.14.2 Pros
使用Python布尔类型的条件语句可读性更好而且更难出错,大多数情况下,这种方式也更快.
#### 2.14.3 Cons
对于C/C++开发者而言可能有些奇怪
#### 建议
如果可能的话,使用隐式False.例如使用`if foo:`而非`if foo != []:`下面列举了一些你应该牢记的警告:
* 使用`if foo is None`(或者`if foo is not None`)来检查`None`.例如在检查一个默认值是`None`的变量或者参数是否被赋予了其他值的时候,被赋予的其他值的布尔值可能为False.
* 不要用`==`来和布尔值为`False`的变量比较,使用`if not x`,如果需要区别`False`和`None`,那么使用链式的表达式如`if not x and x is not None`
* 对于序列(如字符串,列表,元组),利用空序列为`False`的事实,故而相应地使用`if seq:`和`if not seq:`而非`if len(seq)`或`if not len(seq):`.
* 在处理整数时,隐式的False可能会引入更多风险(例如意外地将`None`和0进行了相同的处理)你可以用一个已知是整形(并且不是`len()`的结果)的值和整数0比较.
**Yes:**
```Python
if not users:
print('no users')
if foo == 0:
self.handle_zero()
if i % 10 == 0:
self.handle_multiple_of_ten()
def f(x=None):
if x is None:
x = []
```
**No:**
```Python
if len(users) == 0:
print('no users')
if foo is not None and not foo:
self.handle_zero()
if not i % 10:
self.handle_multiple_of_ten()
def f(x=None):
x = x or []
```
### 2.15 弃用的语言特性
尽可能利用字符串方法而非`string`模块.使用函数调用语法而非`apply`.在函数参数本就是一个行内匿名函数的时候,使用列表推导表达式和for循环而非`filter`和`map`
#### 2.15.1 定义
当前Python版本提供了人们普遍更倾向的构建方式.
#### 2.15.2 建议
我们不使用任何不支持这些特性的Python版本,因而没有理由不使用新方式.
**Yes:**
```Python
words = foo.split(':')
[x[1] for x in my_list if x[2] == 5]
map(math.sqrt, data) # Ok. No inlined lambda expression. 可以,没有行内的lambda表达式
fn(*args, **kwargs)
```
**No:**
```Python
words = string.split(foo, ':')
map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
apply(fn, args, kwargs)
```
### 2.16 词法作用域
可以使用
#### 2.16.1 定义
一个内嵌Python函数可以引用在闭包命名空间内定义的变量,但是不能对其复制.变量绑定是解析到使用词法作用域的,即基于静态程序文本.任何对块内命名的赋值都会让Python将对于这个命名的引用都作为局部变量,即使在使用先于赋值的情况下也是.如果有全局声明,这个命名就会被认为是全局变量.
一个使用这个特性的例子是:
```Python
def get_adder(summand1):
"""Returns a function that adds numbers to a given number."""
def adder(summand2):
return summand1 + summand2
return adder
```
#### 2.16.2 Pros
经常可以让代码更简明优雅,尤其会让有经验的Lisp和Scheme(以及Haskell和ML还有其他)的程序要很舒服.
#### 2.16.3 Cons
可能会导致令人迷惑的bug例如这个基于[PEP-0227](http://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0227/)的例子.
```Python
i = 4
def foo(x):
def bar():
print(i, end='')
# ...
# A bunch of code here
# ...
for i in x: # Ah, i *is* local to foo, so this is what bar sees i对于foo来说是局部变量,所以在这里就是bar函数所获取的值
print(i, end='')
bar()
```
所以`foo([1, 2, 3])`会打印`1 2 3 3`而非`1 2 3 4`.
#### 2.16.4 建议
可以使用
### 2.17 函数和方法装饰器
在明显有好处时,谨慎明智的使用,避免`@staticmethod`,控制使用`@classmethod`
#### 2.17.1 定义
[函数和方法装饰器](https://docs.python.org/3/glossary.html#term-decorator)(也就是`@`记号).一个常见的装饰器是`@property`,用于将普通方法转换成动态计算属性.然而装饰器语法也允许用户定义装饰器,尤其对于一些函数`my_decorator`如下:
```Python
class C(object):
@my_decorator
def method(self):
# method body ...
```
是等效于
```Python
class C(object):
def method(self):
# method body ...
method = my_decorator(method)
```
#### 2.17.2 Pros
能够优雅的对方法进行某种转换,而该转换可能减少一些重复代码并保持不变性等等.
#### 2.17.3 Cons
装饰器可以对函数的参数和返回值任意操作,导致非常隐形的操作行为.此外,装饰器在import的时候就被执行,装饰器代码的实效可能非常难恢复.
#### 2.17.4 建议
在有明显好处的地方谨慎地使用装饰器.装饰器应该和函数遵守相同的import和命名指导规则.装饰器的文档应该清晰地声明该函数为装饰器函数.并且要为装饰器函数编写单元测试.
避免装饰器自身对外部的依赖,(如不要依赖于文件,socket,数据库连接等等),这是由于在装饰器运行的时候(在import时,可能从`pydoc`或其他工具中)这些外部依赖可能不可用.一个被传入有效参数并调用的装饰器应该(尽可能)保证在任何情况下都可用.
装饰器是一种特殊的"顶级代码",参见[main](https://google.github.io/styleguide/pyguide.html#s3.17-main)
永远不要使用`@staticmethod`,除非不得不整合一个API到一个已有的库,应该写一个模块等级的函数.
只在写一个命名的构造器或者一个类特定的,修改必要的全局状态(例如进程缓存等)的流程时使用`@classmethod`.
### 2.18 线程
不要依赖于内建类型的原子性
尽管Python内置数据类型例如字典等似乎有原子性操作,仍有一些罕见情况下,他们是非原子的(比如,如果`__hash__`或者`__eq__`被实现为Python方法),就不应该依赖于这些类型的原子性.也不应该依赖于原子变量赋值(因为这依赖于字典)
优先使用Queue模块的`Queue`类来作为线程之间通讯数据的方式.此外,要是用threading模块和其locking primitives(锁原语).了解条件变量的合理用法以便于使用`threading.Condition`而非使用更低级的锁.
### 2.19 过于强大的特性
尽量避免使用
#### 2.19.1 定义
Python是一种非常灵活的语言并且提供了很多新奇的特性,诸如定制元类,访问字节码,动态编译,动态继承,对象父类重定义,import hacks,反射(例如一些对于`getattr()`的应用),系统内置的修改等等.
#### 2.19.2 Pros
这些是非常强大的语言特性,可以让程序更紧凑
#### 2.19.3 Cons
使用这些新特性是很诱人的.但是并不绝对必要,它们很难读很难理解.也很难debug那些在底层使用了不常见的特性的代码.对于原作者而言可能不是这样,但是再次看代码的时候,可能比更长但是更直接的代码要难.
#### 2.19.4 定义
避免在代码中使用这些特性.
内部使用这些特性的标准库和类是可以使用的(例如`abc.ABCMeta`,`collections.namedtuple`,和`enum`)
### 2.20 新版本Python: Python3 和从`__future__`import
Python3已经可用了(译者:目前Python2已经不受支持了),尽管不是每个项目都准备好使用Python3,所有的代码应该兼容Python3并且在可能的情况下在Python3的环境下测试.
#### 2.20.1 定义
Python3是Python的重大改变,尽管现有代码通常是Python2.7写成的,但可以做一些简单的事情来让代码更加明确地表达其意图,从而可以让代码更好地在Python3下运行而不用调整.
#### 2.20.2 Pros
在考虑Python3编写的代码更清晰明确,一旦所有依赖已就绪,就可以更容易在Python3环境下运行.
#### 2.20.3 Cons
一些人会认为默认样板有些丑,import实际不需要的特性到模块中是不常见的.
#### 2.20.4 建议
**from __future__ imports**
鼓励使用`from __future__ import`语句.所有新代码都应该包含下述代码,而现有代码应该被更新以尽可能兼容:
```Python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
```
如果你不太熟悉这些,详细阅读这些:[绝对import](https://www.python.org/dev/peps/pep-0328/),[新的`/`除法行为](https://www.python.org/dev/peps/pep-0238/),和[`print`函数](https://www.python.org/dev/peps/pep-3105/)
请勿省略或移除这些import,即使在模块中他们没有在使用,除非代码只用于Python3.最好总是在所有的文档中都有从future的import,来保证不会在有人使用在后续编辑时遗忘.
有其他的`from __future__`import语句,看喜好使用.我们的建议中不包含`unicode_literals`因为其并无明显优势,这是由于隐式默认的编码转换导致其在Python2.7内很多地方被引入了,必要时,大多数代码最好显式的使用`b''`和`u''`btyes和unicode字符串表示.(译者:这段翻译可能不准确)
**The six, future, or past libraries**
当项目需要支持Python2和3时,根据需求使用[six](https://pypi.org/project/six/),[future](https://pypi.org/project/future/)和[past](https://pypi.org/project/past/).
### 2.21 带有类型注释的代码
可以根据[PEP-484](https://www.python.org/dev/peps/pep-0484/)对Python3代码进行类型注释,并且在build时用类型检查工具例如[pytype](https://github.com/google/pytype)进行类型检查.
类型注释可以在源码中或[stub pyi file](https://www.python.org/dev/peps/pep-0484/#stub-files)中.只要可能,注释就应写在源代码中.对于第三方或拓展模块使用pyi文件.
#### 2.21.1 定义
类型注释(也称为"类型提示")是用于函数或方法参数和返回值的:
```Python
def func(a: int) -> List[int]:
```
你也可以声明用一个单独的注释来声明变量的类型:
```Python
a = SomeFunc() # type: SomeType
```
#### 2.21.2 Pros
类型注释提升代码的可读性和可维护性,类型检查会将很多运行错误转化为构建错误,也减少了使用[过于强力特性](https://google.github.io/styleguide/pyguide.html#power-features)的能力.
#### 2.21.3 Cons
需要不断更新类型声明,对于认为有效的代码可能会报类型错误,使用[类型检查](https://github.com/google/pytype)可能减少使用[过于强力特性](https://google.github.io/styleguide/pyguide.html#power-features)的能力.
#### 2.21.4 建议
强烈鼓励在更新代码的时候进行Python类型分析.在对公共API进行补充和修改时,包括python类型声明并通过构建系统中的pytype进行检查.对Python来说静态类型检查比较新,我们承认,一些意料外的副作用(例如错误推断的类型)可能拒绝一些项目的使用.这种情况下,鼓励作者适当地增加一个带有TODO或到bug描述当前不接搜的类型注释的链接到BUILD文件或者在代码内.
## 3 Python代码风格规范
### 3.1 分号
不要在行尾加分号,也不要用分号把两行语句合并到一行
### 3.2 行长度
最大行长度是*80个字符*
超出80字符的明确例外:
* 长import
* 注释中的:URL,路径,flags等
* 不包含空格不方便分行的模块级别的长字符串常量
* pylint的diable注释使用(如`# pylint: disable=invalid-name`)
不要使用反斜杠连接,除非对于需要三层或以上的上下文管理器`with`语句
利用Python的[implicit line joining inside parentheses, brackets and braces](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining)(隐式行连接方法--括号连接,包括`(), [], {}`).如果必要的话,也可在表达式外面额外添加一对括号.
**Yes:**
```Pyhon
foo_bar(self, width, height, color='black', design=None, x='foo',
emphasis=None, highlight=0)
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong'):
```
当字符串不能在一行内完成时,使用括号来隐式连接行:
```Python
x = ('This will build a very long long '
'long long long long long long string')
```
在注释内,如有必要,将长URL放在其本行内:
**Yes:**
```Python
# See details at
# http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
```
**No:**
```Python
# See details at
# http://www.example.com/us/developer/documentation/api/content/\
# v2.0/csv_file_name_extension_full_specification.html
```
在定义一个表达式超过三行或更多的`with`语句时,可以使用反斜杠来分行.对于两行表达式,使用嵌套`with`语句:
**Yes:**
```Python
with very_long_first_expression_function() as spam, \
very_long_second_expression_function() as beans, \
third_thing() as eggs:
place_order(eggs, beans, spam, beans)
with very_long_first_expression_function() as spam:
with very_long_second_expression_function() as beans:
place_order(beans, spam)
```
**No:**
```Python
with VeryLongFirstExpressionFunction() as spam, \
VeryLongSecondExpressionFunction() as beans:
PlaceOrder(eggs, beans, spam, beans)
```
注意上述例子中的缩进,具体参看[缩进](https://google.github.io/styleguide/pyguide.html#s3.4-indentation)
在其他一行超过80字符的情况下,而且[yapf](https://github.com/google/yapf/)自动格式工具也不能使分行符合要求时,允许超过80字符限制.
### 3.3 括号
括号合理使用
尽管不必要,但是可以在元组外加括号.再返回语句或者条件语句中不要使用括号,除非是用于隐式的连接行或者指示元组.
**Yes:**
```Python
if foo:
bar()
while x:
x = bar()
if x and y:
bar()
if not x:
bar()
# For a 1 item tuple the ()s are more visually obvious than the comma.
onesie = (foo,)
return foo
return spam, beans
return (spam, beans)
for (x, y) in dict.items(): ...
```
**No:**
```Python
if (x):
bar()
if not(x):
bar()
return (foo)
```
### 3.4 缩进
缩进用4个空格
缩进代码段不要使用制表符,或者混用制表符和空格.如果连接多行,多行应垂直对齐,或者再次4空格缩进(这个情况下首行括号后应该不包含代码).
**Yes:**
```Python
# Aligned with opening delimiter
# 和opening delimiter对齐(译者理解是分隔符的入口,例如三种括号,字符串引号等)
foo = long_function_name(var_one, var_two,
var_three, var_four)
meal = (spam,
beans)
# Aligned with opening delimiter in a dictionary
foo = {
long_dictionary_key: value1 +
value2,
...
}
# 4-space hanging indent; nothing on first line
# 缩进4个空格,首行括号后无内容
foo = long_function_name(
var_one, var_two, var_three,
var_four)
meal = (
spam,
beans)
# 4-space hanging indent in a dictionary
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
```
**No:**
```Python
# Stuff on first line forbidden
# 首行不允许有内容
foo = long_function_name(var_one, var_two,
var_three, var_four)
meal = (spam,
beans)
# 2-space hanging indent forbidden
foo = long_function_name(
var_one, var_two, var_three,
var_four)
# No hanging indent in a dictionary
foo = {
long_dictionary_key:
long_dictionary_value,
...
}
```
#### 3.4.1 关于尾后逗号
关于在一序列元素中的尾号逗号,只推荐在容器结束符号`]`,`)`或者`}`和最后元素不在同一行时使用.尾后逗号的存在也被用作我们Python代码自动格式化工具[yapf](https://github.com/google/yapf/)的提示,在`,`最后元素之后出现的时候来自动调整容器元素到每行一个元素.
**Yes:**
```Python
golomb3 = [0, 1, 3]
golomb4 = [
0,
1,
4,
6,
]
```
**No:**
```Python
golomb4 = [
0,
1,
4,
6
]
```
### 3.5 空行
在顶级定义(函数或类)之间要间隔两行.在方法定义之间以及`class`所在行与第一个方法之间要空一行,`def`行后无空行,在函数或方法内你认为合适地方可以使用单空行.
### 3.6 空格
遵守标准的空格和标点排版规则.
括号`()`,`[]`,`{}`内部不要多余的空格.
**Yes:**
```Python
spam(ham[1], {eggs: 2}, [])
```
**No:**
```Python
spam( ham[ 1 ], { eggs: 2 }, [ ] )
```
逗号、分号、冒号前不要空格,但是在后面要加空格,除非是在行尾.
**Yes:**
```Python
if x == 4:
print(x, y)
x, y = y, x
```
**No:**
```Python
if x == 4 :
print(x , y)
x , y = y , x
```
在函数调用括号的前,索引切片括号前都不加空格.
**Yes:**
```Python
spam(1)
dict['key'] = list[index]
```
**No:**
```Python
spam (1)
dict ['key'] = list [index]
```
行尾不要加空格.
在赋值(`=`),比较(`==`,`<`,`>`,`!=`,`<>`,`<=`,`>=`,`in`,`not in`,`is`,`is not`),布尔符号(`and`,`or`,`not`)前后都加空格.视情况在算术运算符(`+`,`-`,`*`,`/`,`//`,`%`,`**`,`@`),前后加空格
**Yes:**
```Python
x == 1
```
**No:**
```Python
x<1
```
在关键字名参数传递或定义默认参数值的时候不要在`=`前后加空格,只有一个例外:[当类型注释存在时](https://google.github.io/styleguide/pyguide.html#typing-default-values)在定义默认参数值时`=`前后加空格
**Yes:**
```Python
def complex(real, imag=0.0): return Magic(r=real, i=imag)
def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)
```
**No:**
```Python
def complex(real, imag = 0.0): return Magic(r = real, i = imag)
def complex(real, imag: float=0.0): return Magic(r = real, i = imag)
```
不要用空格来做无必要的对齐,因为这会在维护时带来不必要的负担(对于`:`.`#`,`=`等等).
**Yes:**
```Python
foo = 1000 # comment
long_name = 2 # comment that should not be aligned
dictionary = {
'foo': 1,
'long_name': 2,
}
```
**No:**
```Python
foo = 1000 # comment
long_name = 2 # comment that should not be aligned
dictionary = {
'foo' : 1,
'long_name': 2,
}
```
### 3.7 Shebang
大部分`.py`文件不需要从`#!`行来开始.根据[PEP-394](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0394/),程序的主文件应该以`#!/usr/bin/python2`或`#!/usr/bin/python3`起始
这行被用于帮助内核找到Python解释器,但是在导入模块时会被Python忽略/只在会被直接运行的文件里有必要写.
### 3.8 注释和文档字符串
确保使用正确的模块,函数,方法的文档字符串和行内注释.
#### 3.8.1 文档字符串
Python使用*文档字符串*来为代码生成文档.文档字符串是包,模块,类或函数的首个语句.这些字符串能够自动被`__doc__`成员方法提取并且被`pydoc`使用.(尝试在你的模块上运行`pydoc`来看看具体是什么).文档字符串使用三重双引号`"""`(根据[PEP-257](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0257/)).文档字符串应该这样组织:一行总结(或整个文档字符串只有一行)并以句号,问好或感叹号结尾.随后是一行空行,随后是文档字符串,并与第一行的首个引号位置相对齐.更多具体格式规范如下.
#### 3.8.2 模块
每个文件都应包含许可模板.选择合适的许可模板用于项目(例如
Apache 2.0,BSD,LGPL,GPL)
文档应该以文档字符串开头,并描述模块的内容和使用方法.
```Python
"""A one line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.FunctionBar()
"""
```
#### 3.8.3 函数和方法
在本节,"函数"所指包括方法,函数或者生成器.
函数应有文档字符串,除非符合以下所有条件:
* 外部不可见
* 非常短
* 简明
文档字符串应该包含足够的信息以在无需阅读函数代码的情况下调用函数.文档字符串应该是叙事体(`"""Fetches rows from a Bigtable."""`)的而非命令式的(`"""Fetch rows from a Bigtable."""`),除了`@property`(应与[attribute](https://google.github.io/styleguide/pyguide.html#384-classes)使用同样的风格).文档字符串应描述函数的调用语法和其意义,而非实现.对比较有技巧的地方,在代码中使用注释更合适.
覆写了基类的方法可有简单的文档字符串向读者指示被覆写方法的文档字符串例如`"""See base class."""`.这是因为没必要在很多地方重复已经在基类的文档字符串中存在的文档.不过如果覆写的方法行为实际上与被覆写方法不一致,或者需要提供细节(例如文档中表明额外的副作用),覆写方法的文档字符串至少要提供这些差别.
一个函数的不同方面应该在特定对应的分节里写入文档,这些分节如下.每一节都由以冒号结尾的一行开始, 每一节除了首行外,都应该以2或4个空格缩进并在整个文档内保持一致(译者建议4个空格以维持整体一致).如果函数名和签名足够给出足够信息并且能够刚好被一行文档字符串所描述,那么可以忽略这些节.
[*Args:*](https://google.github.io/styleguide/pyguide.html#doc-function-args)
列出每个参数的名字.名字后应有为冒号和空格,后跟描述.如果描述太长不能够在80字符的单行内完成.那么分行并缩进2或4个空格且与全文档一致(译者同样建议4个空格)
描述应该包含参数所要求的类型,如果代码不包含类型注释的话.如果函数容许`*foo`(不定长度参数列表)或`**bar`(任意关键字参数).那么就应该在文档字符串中列举为`*foo`和`**bar`.
[*Returns:(或对于生成器是Yields:)*](https://google.github.io/styleguide/pyguide.html#doc-function-returns)
描述返回值的类型和含义.如果函数至少返回None,这一小节不需要.如果文档字符串以Returns或者Yields开头(例如`"""Returns row from Bigtable as a tuple of strings."""`)或首句足够描述返回值的情况下这一节可忽略.
[*Raises:*](https://google.github.io/styleguide/pyguide.html#doc-function-returns)
列出所有和接口相关的异常.对于违反文档要求而抛出的异常不应列出.(因为这会矛盾地使得违反接口要求的行为成为接口的一部分)
```Python
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtable Table instance.
keys: A sequence of strings representing the key of each table row
to fetch.
other_silly_variable: Another optional variable, that has a much
longer name than the other args, and which does nothing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{'Serak': ('Rigel VII', 'Preparer'),
'Zim': ('Irk', 'Invader'),
'Lrrr': ('Omicron Persei 8', 'Emperor')}
If a key from the keys argument is missing from the dictionary,
then that row was not found in the table.
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
```
#### 3.8.4 类
类定义下一行应为描述这个类的文档字符串.如果类有公共属性,应该在文档字符串中的`Attributes`节中注明,并且和[函数的`Args`](https://google.github.io/styleguide/pyguide.html#doc-function-args)一节风格统一.
```Python
class SampleClass(object):
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
```
#### 3.8.5 块注释和行注释
最后要在代码中注释的地方是代码技巧性的部分.如果你将要在下次[code review](http://en.wikipedia.org/wiki/Code_review)中揭示代码.应该现在就添加注释.在复杂操作开始前,注释几行.对于不够明晰的代码在行尾注释.
```Python
# We use a weighted dictionary search to find out where i is in
# the array. We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.
if i & (i-1) == 0: # True if i is 0 or a power of 2.
```
为了提升易读性,行注释应该至少在代码2个空格后,并以`#`后接至少1个空格开始注释部分.
另外,不要描述代码,假定阅读代码的人比你更精通Python(他只是不知道你试图做什么).
#### 3.8.6 标点,拼写和语法
注意标点,拼写和语法,写得好的注释要比写得差的好读.
注释应当是和叙事性文本一样可读,并具有合适的大小写和标点.在许多情况下,完整的句子要比破碎的句子更可读.更简短的注释如行尾的注释有时会不太正式,但是应该全篇保持风格一致.
尽管被代码审核人员指出在应该使用分号的地方使用了逗号是很令人沮丧的,将源代码维护在高度清楚可读的程度是很重要的.合适的标点,拼写和语法能够帮助达到这个目标.
### 3.9 类
如果类并非从其他基类继承而来,那么就要明确是从`object`继承而来,即便内嵌类也是如此.
**Yes:**
```Python
class SampleClass(object):
pass
class OuterClass(object):
class InnerClass(object):
pass
class ChildClass(ParentClass):
"""Explicitly inherits from another class already."""
```
**No:**
```Python
class SampleClass:
pass
class OuterClass:
class InnerClass:
pass
```
从`object`类继承保证了属性能够在Python2正确运行并且保护代码在Python3下出现潜在的不兼容.这样也定义了object包括`__new__`,`__init__`,`__delattr__`,`__getattribute__`,`__setattr__`,`__hash__`,`__repr__`,和`__str__`等默认特殊方法的实现.
### 3.10 字符串
使用`format`或`%`来格式化字符串,即使参数都是字符串对象,也要考虑使用`+`还是`%`及`format`.
**Yes:**
```Python
x = a + b
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}'.format(first, second)
x = 'name: %s; score: %d' % (name, n)
x = 'name: {}; score: {}'.format(name, n)
x = f'name: {name}; score: {n}' # Python 3.6+
```
**No:**
```Python
employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'
```
避免使用`+`和`+=`操作符来在循环内累加字符串,因为字符串是不可变对象.这会造成不必要的临时变量导致运行时间以四次方增长而非线性增长.应将每个字符串都记入一个列表并使用`''.join`来将列表在循环结束后连接(或将每个子字符串写入`io.BytesIO`缓存)
**Yes:**
```Python
items = ['<table>']
for last_name, first_name in employee_list:
items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
items.append('</table>')
employee_table = ''.join(items)
```
**No:**
```Python
employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'
```
在同一个文件内,字符串引号要一致,选择`''`或者`""`并且不要改变.对于需要避免`\\`转义的时候,可以更改.
**Yes:**
```Python
Python('Why are you hiding your eyes?')
Gollum("I'm scared of lint errors.")
Narrator('"Good!" thought a happy Python reviewer.')
```
**No:**
```Python
Python("Why are you hiding your eyes?")
Gollum('The lint. It burns. It burns us.')
Gollum("Always the great lint. Watching. Watching.")
```
多行字符串多行字符串优先使用"""而非`'''`,当且只当对所有非文档字符串的多行字符串都是用`'''`而且对正常字符串都使用`'`时才可使用三单引号.docstring不论如何必须使用`"""`
多行字符串和其余代码的缩进方式不一致.如果需要避免在字符串中插入额外的空格,要么使用单行字符串连接或者带有[`textwarp.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent)的多行字符串来移除每行的起始空格.
**No:**
```Python
long_string = """This is pretty ugly.
Don't do this.
"""
```
**Yes:**
```Python
long_string = """This is fine if your use case can accept
extraneous leading spaces."""
long_string = ("And this is fine if you can not accept\n" +
"extraneous leading spaces.")
long_string = ("And this too is fine if you can not accept\n"
"extraneous leading spaces.")
import textwrap
long_string = textwrap.dedent("""\
This is also fine, because textwrap.dedent()
will collapse common leading spaces in each line.""")
```
### 3.11 文件和socket
当使用结束后显式地关闭文件或socket.
不必要地打开文件,socket或其他类似文件的对象有很多弊端:
* 他们可能会消耗有限的系统资源,例如文件描述符.如果在使用没有即使归还系统,处理很多这样对象的代码可能会浪费掉很多不应浪费的资源.
* 保持一个文件可能会阻止其他操作诸如移动或删除.
* 被程序共享的文件和socket可能会无意中在逻辑上已被关闭的情况下仍被读写.如果实际上已经关闭,试图读写的操作会抛出异常,这样就可以立即发现问题.
此外,当文件或socket在文件对象被销毁的同时被自动关闭的时候,是不可能将文件的生命周期和文件状态绑定的:
* 不能保证何时会真正将文件对象销毁.不同的Python解释器使用的内存管理技术不同,例如延时垃圾处理可能会让对象的生命周期被无限期延长.
* 可能导致意料之外地对文件对象的引用,例如在全局变量或者异常回溯中,可能会让文件对象比预计的生命周期更长.
推荐使用[with语句](http://docs.python.org/reference/compound_stmts.html#the-with-statement)管理文件:
```Python
with open("hello.txt") as hello_file:
for line in hello_file:
print(line)
```
对于类似文件的对象,如果不支持with语句的可以使用`contextlib.closing()`:
```Python
import contextlib
with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
for line in front_page:
print(line)
```
### 3.12 TODO注释
对于下述情况使用`TODO`注释:临时的,短期的解决方案或者足够好但是不完美的解决方案.
`TODO`注释以全部大写的字符串`TODO`开头,并带有写入括号内的姓名,email地址,或其他可以标识负责人或者包含关于问题最佳描述的issue.随后是这里做什么的说明.
有统一风格的`TODO`的目的是为了方便搜索并了解如何获取更多相关细节.`TODO`并不是保证被提及者会修复问题.因此在创建`TODO`注释的时候,基本上都是给出你的名字.
```Python
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.
```
如果`TODO`注释形式为"未来某个时间点会做什么事"的格式,确保要么给出一个非常具体的时间点(例如"将于2009年11月前修复")或者给出一个非常具体的事件(例如"当所有客户端都能够处理XML响应时就移除此代码").
### 3.13 import格式
imports应该在不同行.例如:
**Yes:**
```Python
import os
import sys
```
**No:**
```Python
import os, sys
```
import应集中放在文件顶部,在模块注释和docstring后面,模块globals和常量前面.应按照从最通用到最不通用的顺序排列分组:
1. Python未来版本import语句,例如:
> ```Python
> from __future__ import absolute_import
> from __future__ import division
> from __future__ import print_function
> ```
> 更多信息参看[上文](https://google.github.io/styleguide/pyguide.html#from-future-imports)
2. Python标准基础库import,例如:
> ```Python
> import sys
> ```
3. 第三方库或包的import,例如:
> ```Python
> import tensorflow as tf
> ```
4. 代码库内子包import,例如:
> ```Python
> from otherproject.ai import mind
> ```
5. **此条已弃用**:和当前文件是同一顶级子包专用的import,例如:
> ```Python
> from myproject.backend.hgwells import time_machine
> ```
在旧版本的谷歌Python代码风格指南中实际上是这样做的.但是现在不再需要了.**新的代码风格不再受此困扰.**简单的将专用的子包import和其他子包import同一对待即可.
在每个组内按照每个模块的完整包路径的字典序忽略大小写排序.可以根据情况在每个节质检增加空行.
```Python
import collectionsimport queueimport sys
from absl import appfrom absl import flagsimport bs4import cryptographyimport tensorflow as tf
from book.genres import scififrom myproject.backend.hgwells import time_machinefrom myproject.backend.state_machine import main_loopfrom otherproject.ai import bodyfrom otherproject.ai import mindfrom otherproject.ai import soul
# Older style code may have these imports down here instead:
# 旧版本代码风格可能会采用下述import方式
# from myproject.backend.hgwells import time_machine
# from myproject.backend.state_machine import main_loop
```
### 3.14 语句
每行只有一条语句.
不过如果测试语句和结果能够在一行内放下,就可以放在一行内.但是不允许将`try`/`except`语句和对应内容放于一行,因为`try`或者`except`都不能在一行内完成.对于没有else的if语句可以将`if`和对应内容合并到一行.
**Yes:**
```Python
if foo: bar(foo)
```
**No:**
```Python
if foo: bar(foo)
else: baz(foo)
try: bar(foo)
except ValueError: baz(foo)
try:
bar(foo)
except ValueError: baz(foo)
```
### 3.15 访问
对于琐碎又不太重要的访问函数,应用公共变量来替代访问函数,以避免额外的程序调用消耗,当添加了更多函数功能时,使用`property`来保持连续性
此外,如果访问过于复杂,或者访问变量的消耗过大,应该使用诸如`get_foo()`和`set_foo()`之类的函数式访问(参考[命名](https://google.github.io/styleguide/pyguide.html#s3.16-naming)指南).如果过去的访问方式是通过属性,新访问函数不要绑定到property上,这样使用property的旧方式就会失效,使用者就会知道函数有变化.
### 3.16 命名
`module_name`,`package_name`,`ClassName`,`method_name`,`ExceptionName`,`function_name`,`GLOBAL_CONSTANT_NAME`,`global_var_name`,`instance_var_name`,`function_parameter_name`,`local_var_name`.
命名函数名,变量名,文件名应该是描述性的,避免缩写,尤其避免模糊或对读者不熟悉的缩写.并且不要通过删减单词内的字母来缩短.
使用`.py`作为文件拓展名,不要使用横线.
#### 3.16.1 要避免的名字:
* 单字符名字,除非是计数或迭代元素,e可以作为Exception捕获识别名来使用..
* `-`横线,不应出现在任何包名或模块名内
* `__double_leading_and_trailing_underscore__`首尾都双下划线的名字,这种名字是python的内置保留名字
#### 3.16.4 命名约定
* internal表示仅模块内可用、或者类内保护的或者私有的
* 单下划线(`_`)开头表示是被保护的(`from module import *`不会import).双下划线(`__`也就是"dunder")开头的实例变量或者方法表示类内私有(使用命名修饰).我们不鼓励使用,因为这会对可读性和可测试性有削弱二期`并非真正`的私有.
* 相关的类和顶级函数放在同一个模块内,不必像是Java一样要一个类放在一个模块里.
* 对类名使用大写字母(如CapWords)开头的单词,命名,模块名应该使用小写加下划线的方式.尽管有一些旧的模块命名方式是大写字母的(如CapWords.py),现在不鼓励这样做了,因为在模块刚好是从某个类命名出发的时候可能会令人迷惑(例如是选择`import StringIO`还是`from StringIO import StringIO`?)
* 在*unittest*方法中可能是`test`开头来分割名字的组成部分,即使这些组成部分是使用大写字母驼峰式的.这种方式是可以的: `test<MethodUnderTest>_<state>`例如`testPop_EmptyStack`,对于命名测试方法没有明确的正确方法.
#### 3.16.3 文件名
文件拓展名必须为`.py`,不可以包含`-`.这保证了能够被正常import和单元测试.如果希望一个可执行文件不需要拓展名就可以被调用,那么建立一个软连接或者一个简单的bash打包脚本包括`exec "$0.py" "$@"`.
#### 3.16.4 Guido的指导建议
| **类型** | **公共** | **内部** |
| --- | --- | --- |
| 包 | `lower_with_under` | |
| 模块 | `lower_with_under` | `_lower_with_under` |
| 类 | `CapWords` | `_CapWords` |
| 异常 | `CapWords` | |
| 函数 | `lower_with_under()` | `_lower_with_under()` |
| 全局/类常量 | `CAPS_WITH_UNDER` | `_CAPS_WITH_UNDER` |
| 全局/类变量 | `lower_with_under` | `_lower_with_under` |
| 实例变量 | `lower_with_under` | `_lower_with_under`(受保护) |
| 方法名 | `lower_with_under()` | `_lower_with_under()`(受保护) |
| 函数/方法参数 | `lower_with_under` | |
| 局部变量 | `lower_with_under` | |
尽管Python支持通过双下划线`__`(即"dunder")来私有化.不鼓励这样做.优先使用单下划线.单下划线更易于打出来、易读、易于小的单元测试调用.Lint的警告关注受保护成员的无效访问.
### 3.17 Main
即便是一个用做脚本的py文件也应该是可以被import的,而只用于import时,也不应有执行了主函数的副作用.主函数的功能应该被放在`main()`里.
在Python中,`pydoc`和单元测试要求模块是可import的.所以代码在主程序执行前应进行`if __name__ == '__main__':`检查,以防止模块在import时被执行.
```Python
def main():
...
if __name__ == '__main__':
main()
```
所有顶级代码在模块被import时执行.因而要小心不要调用函数,创建对象或者执行其他在执行`pydoc`时不应该被执行的操作.
### 3.18 函数长度
优先写小而专一的函数.
长函数有时候是合适的,故而函数长度没有固定的限制.但是超过40行的时候就要考虑是否要在不影响程序结构的前提下分解函数.
尽管长函数现在运行的很好,但是在之后的时间里其他人修改函数并增加新功能的时候可能会引入新的难以发现的bug,保持函数的简短,这样有利于其他人读懂和修改代码.
在处理一些代码时,可能会发现有些函数长而且复杂.不要畏惧调整现有代码,如果处理这个函数非常困难,如难以对报错debug或者希望在几个不同的上下文中使用它,那么请将函数拆解成若干个更小更可控的片段.
### 3.19 类型注释
#### 3.19.1 基本规则
* 熟悉[PEP-484](https://www.python.org/dev/peps/pep-0484/)
* 在方法中,只在必要时给`self`或者`cls`增加合适的类型信息.例如`@classmethod def create(cls: Type[T]) -> T: return cls()`
* 如果其他变量或返回类型不定,使用`Any`
* 不需要注释每个函数
* 至少需要注明公共接口
* 使用类型检查来在安全性和声明清晰性以及灵活性之间平衡
* 标注容易因类型相关而抛出异常的代码(previous bugs or complexity,此处译者认为是与上一条一致,平衡安全性和复杂性)
* 标注难理解的代码
* 标注类型稳定的代码,成熟稳定的代码可以都进行标注而不会影响其灵活性
#### 3.19.2 分行
遵循现有的[缩进](https://google.github.io/styleguide/pyguide.html#indentation)规范
标注类型后,函数签名多数都要是"每行一个参数".
```Python
def my_method(self,
first_var: int,
second_var: Foo,
third_var: Optional[Bar]) -> int:
...
```
优先在变量之间换行,而非其他地方(如变量名和类型注释之间).如果都能放在一行内,就放在一行.
```Python
def my_method(self, first_var: int) -> int:
...
```
如果函数名,一直到最后的参数以及返回类型注释放在一行过长,那么分行并缩进4个空格.
```Python
def my_method(
self, first_var: int) -> Tuple[MyLongType1, MyLongType1]:
...
```
当返回值类型不能和最后一个参数放入同一行,比较好的处理方式是将参数分行并缩进4个空格,右括号和返回值类型换行并和`def`对齐.
```Python
def my_method(
self, other_arg: Optional[MyLongType]
) -> Dict[OtherLongType, MyLongType]:
...
```
pylint允许您将右括号移动到新行并与左括号对齐,但这不太容易理解.
**No:**
```
def my_method(self,
other_arg: Optional[MyLongType]
) -> Dict[OtherLongType, MyLongType]:
...
```
就像上面的例子一样,尽量不要分割类型注释,不过有时类型注释太长无法放入一行,(那就尽量让子注释不要被分割).
```Python
def my_method(
self,
first_var: Tuple[List[MyLongType1],
List[MyLongType2]],
second_var: List[Dict[
MyLongType3, MyLongType4]]) -> None:
...
```
如果某个命名和类型太长了,考虑使用别名.如果没有其他解决方案,在冒号后分行缩进4个空格.
**Yes:**
```Python
def my_function(
long_variable_name:
long_module_name.LongTypeName,
) -> None:
...
```
**No:**
```Python
def my_function(
long_variable_name: long_module_name.
LongTypeName,) -> None:
...
```
#### 3.19.3 前置声明
如果需要同一模块内还未定义的类名,例如需要类声明内部的类,或者需要在后续代码中定义的类,那么使用类名的字符串来代替.
```Python
class MyClass(object):
def __init__(self,
stack: List["MyClass"]) -> None:
```
#### 3.19.4 默认值
参考[PEP-008](https://www.python.org/dev/peps/pep-0008/#other-recommendations),只有在同时需要类型注释和默认值的时候在`=`前后都加空格
**Yes:**
```Python
def func(a: int = 0) -> int:
...
```
**No:**
```Python
def func(a:int=0) -> int:
...
```
#### 3.19.5 NoneType
在Python系统中`NoneType`是一等类型,为了方便输入,`None`是`NoneType`的别名.如果一个参数可以是`None`,那么就需要声明!可以使用`Union`,但如果只有一个其他类型,那么使用`Optional`.
显式地使用`Optional`而非隐式地.PEP 484的早期版本容许`a: Text = None`被解释为`a: Optional[Text] = None`.但现在已经不推荐这样使用了.
**Yes:**
```Python
def func(a: Optional[Text], b: Optional[Text] = None) -> Text:
...
def multiple_nullable_union(a: Union[None, Text, int]) -> Text
...
```
**No:**
```Python
def nullable_union(a: Union[None, Text]) -> Text:
...
def implicit_optional(a: Text = None) -> Text:
...
```
#### 3.19.6 类型别名
可以对复杂类型声明别名,别名的名称应为CapWorded,如果只用于当前模块,应加下划线私有化.
例如,如果带有模块名的类型名过长:
```Python
_ShortName = module_with_long_name.TypeWithLongName
ComplexMap = Mapping[Text, List[Tuple[int, int]]]
```
其他示例是复杂的嵌套类型和一个函数的多个返回变量(作为元组).
#### 3.19.7 忽略类型检查
可以通过增加特殊行注释`# type: ignore`来禁止类型检查.
`pytype`对于明确的报错有关闭选项(类似于lint):
```Python
# pytype: disable=attribute-error
```
#### 3.19.8 对变量注释类型
对变量标注类型如果内部变量很难或者不可能指向,可以使用下述方式:
[*类型注释*](https://google.github.io/styleguide/pyguide.html#type-comments):
在行尾增加以`# type`开头的注释
```Python
a = SomeUndecoratedFunction() # type: Foo
```
[*注释绑定*](https://google.github.io/styleguide/pyguide.html#annotated-assignments):
在变量名和赋值之间用冒号和类型注明,和函数参数一致.
```Python
a: Foo = SomeUndecoratedFunction()
```
#### 3.19.9 元组和列表
不像是列表只能包含单一类型,元组可以既只有一种重复类型或者一组不同类型的元素,后者常用于函数返回.
```Python
a = [1, 2, 3] # type: List[int]
b = (1, 2, 3) # type: Tuple[int, ...]
c = (1, "2", 3.5) # type: Tuple[int, Text, float]
```
#### 3.19.10 TypeVars
Python是有[泛型](https://www.python.org/dev/peps/pep-0484/#generics)的,工厂函数`TypeVar`是通用的使用方式.
例子:
```Python
from typing import List, TypeVar
T = TypeVar("T")
...
def next(l: List[T]) -> T:
return l.pop()
```
TypeVar可以约束类型:
```Python
AddableType = TypeVar("AddableType", int, float, Text)
def add(a: AddableType, b: AddableType) -> AddableType:
return a + b
```
在`typing`模块预定义好的类型变量是`AnyStr`,用于针对字符串可以是`bytes`也可为`unicode`并且保持一致的多个类型注释.
```
from typing import AnyStr
def check_length(x: AnyStr) -> AnyStr:
if len(x) <= 42:
return x
raise ValueError()
```
#### 3.19.11 字符串类型
注释字符串的合适类型是基于Python版本的.
对于只有Python3的代码,使用`str`,`Text`可以用但是在选择上保持一致.
对于Python2兼容的代码,用`Text`,在一些很罕见的情况下,`str`可能可用.当在不同Python版本之间返回值类型不同的时候通常是为了照顾兼容性.避免使用`unicode`,因为Python3中不存在.
**No:**
```Python
def py2_code(x: str) -> unicode:
...
```
对于处理二进制数据的代码,请使用`bytes`.
**Yes:**
```Python
def deals_with_binary_data(x: bytes) -> bytes:
...
```
对于Python2兼容,处理文本数据(Python中`str`或`unicode`,Python3中`str`)的代码,使用`Text`.对于只有Python3的代码,优先使用`str`.
```Python
from typing import Text
...
def py2_compatible(x: Text) -> Text:
...
def py3_only(x: str) -> str:
...
```
如果既可以是byte也可以是文本,那么使用`Union`和合适的文本类型.
```Python
from typing import Text, Union
...
def py2_compatible(x: Union[bytes, Text]) -> Union[bytes, Text]:
...
def py3_only(x: Union[bytes, str]) -> Union[bytes, str]:
...
```
如果一个函数中所有的字符串类型始终一致,例如前文例子中返回值类型和参数类型是一致的,那么使用[`AnyStr`](https://google.github.io/styleguide/pyguide.html#typing-type-var)
像这样写能够简化代码向Python3的迁移过程.
#### 3.19.12 typing的import
对于从`typing`模块import的类,要import类本身.明确的允许在一行内从`typing`模块import多个特定的类,如
```Python
from typing import Any, Dict, Optional
```
这种从`typing`模块import的方式会向命名空间内增加额外项,`typing`中的任何命名都应该和关键字同等对待并且不在你的Python代码中定义,typed or not(译者推测文无论是否引入).如果和已有的命名冲突,使用`import x as y`来import.
```Python
from typing import Any as AnyType
```
#### 3.19.13 条件import
只在运行时一定要避免进行类型检查的情况下使用条件import.不鼓励使用这种模式.鼓励使用其他替代方式诸如重构代码以容许顶级import.
只用于类型注释的import可以被归于`if TYPE_CHECKING:`代码块中.
* 条件import的类型应被视为字符串引用,以和Python3.6兼容(在Python3.6中,注释表达式实际上被赋值的).
* 只有单独用于类型注释的实例才能在这里定义,包括了别名.否则将会报运行错误因为在运行时这些模块不会被引用.
* 代码块应该紧跟在正常import后面.
* 在类型import后不应有空行
* 按照正常import顺序对这一块代码进行排序
```Python
import typing
if typing.TYPE_CHECKING:
import sketch
def f(x: "sketch.Sketch"): ...
```
#### 3.19.14 循环依赖
由于类型检查引发的循环依赖是一种code smell([代码异味](https://zh.wikipedia.org/zh-hans/%E4%BB%A3%E7%A0%81%E5%BC%82%E5%91%B3)),这样的代码应当被重构.尽管技术上是可以保留循环引用的.[build system](https://google.github.io/styleguide/pyguide.html#typing-build-deps)(系统)不允许这样做因为每个模块都要依赖于其他模块.
将造成循环依赖的模块替换为`Any`并赋予一个有意义的[别名](https://google.github.io/styleguide/pyguide.html#typing-aliases)并使用从这个模块导入的真实类名(因为任何`Any`的属性都是`Any`).别名的定义用和最后一行import用一行空行分隔.
```Python
from typing import Any
some_mod = Any # some_mod.py imports this module.
...
def my_method(self, var: some_mod.SomeType) -> None:
...
```
#### 3.19.15 泛型
当注释的时候,优先泛型类型专有类型参数,否则[泛型的参数会被认为是`Any`](https://www.python.org/dev/peps/pep-0484/#the-any-type).
```Python
def get_names(employee_ids: List[int]) -> Dict[int, Any]:
...
```
```Python
# These are both interpreted as get_names(employee_ids: List[Any]) -> Dict[Any, Any]
def get_names(employee_ids: list) -> Dict:
...
def get_names(employee_ids: List) -> Dict:
...
```
如果泛型最佳的参数类型是`Any`也将其显式地表示出来.但是在很多情况下[`TypeVar`](https://google.github.io/styleguide/pyguide.html#typing-type-var)可能更合适.
```Python
def get_names(employee_ids: List[Any]) -> Dict[Any, Text]:
"""Returns a mapping from employee ID to employee name for given IDs."""
```
```Python
T = TypeVar('T')
def get_names(employee_ids: List[T]) -> Dict[T, Text]:
"""Returns a mapping from employee ID to employee name for given IDs."""
```
## 4 最后的话
***保持一致***
如果你在编辑代码,花几分钟看看现有代码然后决定好要使用哪种风格.如果现有代码在所有算术运算符两侧都加了空格,那么你也应该如此.如果现有的注释用井号组成了包围框,那么你的注释也应如此.
有代码风格指南的目的是有一个编程的共识,这样人们能够集中在内容而非形式上.我们将通用的代码风格指南公布于此这样人们就能了解这个共识(译者:有巴别塔的意味.)但是各自的代码风格也很重要.如果你添加的代码与原有代码看起来完全不一致,就会打乱读者的阅读节奏.避免这样.
|
Shell
|
UTF-8
| 156 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
status_code=`curl -LI $1 -o /dev/null -w "%{http_code}" -s`
if [ "$status_code" != 200 ]; then
zenity --error --text "$1 is down."
exit
fi
|
Python
|
UTF-8
| 2,477 | 3.296875 | 3 |
[] |
no_license
|
import math
class ComplexNumber:
def __init__(self, r, i):
self.r = r
self.i = i
def add(self, liczba):
return ComplexNumber(self.r + liczba.r, self.i + liczba.i)
def subtrack(self, liczba):
return ComplexNumber(self.r - liczba.r, self.i - liczba.i)
def multiply(self, liczba):
tempReal = self.r * liczba.r + -(self.i * liczba.i)
tempImagine = (self.r * liczba.i) + (self.i * liczba.r)
return ComplexNumber(tempReal, tempImagine)
def divide(self, liczba):
liczbaZobruconymZnakiem = liczba.conjugate()
tempLicznik = self.multiply(liczbaZobruconymZnakiem)
tempMianownik = liczba.multiply(liczbaZobruconymZnakiem)
return ComplexNumber(tempLicznik.r / tempMianownik.r, tempLicznik.i / tempMianownik.r)
def conjugate(self):
return ComplexNumber(self.r, -self.i)
def module(self):
return ComplexNumber(math.sqrt(self.r ** 2 + self.i ** 2), 0)
def __repr__(self):
format = ''
if self.r != 0:
format += f'{self.r}'
if self.i != 0:
format += ' + '
if self.i == 1:
format += 'i'
elif self.i != 0:
format += f'{self.i}i'
return format
class Vector:
@staticmethod
def add(v1, v2):
wynik = []
for idx, liczba in enumerate(v1):
wynik.append(liczba.add(v2[idx]))
return wynik
@staticmethod
def subtrack(v1, v2):
wynik = []
for idx, liczba in enumerate(v1):
wynik.append(liczba.subtrack(v2[idx]))
return wynik
@staticmethod
def scalar_multiply(scalar, v):
wynik = []
for idx, liczba in enumerate(v):
wynik.append(liczba.multiply(scalar))
return wynik
@staticmethod
def multiply(v1, v2):
stack_to_sum = []
for idx, zLiczba in enumerate(v1):
stack_to_sum.append(zLiczba.multiply(v2[idx].conjugate()))
sum = stack_to_sum[0]
for idx, liczba in enumerate(stack_to_sum[1:]):
sum = sum.add(liczba)
return sum
@staticmethod
def norma(v1):
stack_to_sum = []
for idx, zLiczba in enumerate(v1):
stack_to_sum.append(zLiczba.multiply(zLiczba.conjugate()))
sum = stack_to_sum[0]
for idx, liczba in enumerate(stack_to_sum[1:]):
sum = sum.add(liczba)
return '√{}'.format(sum)
|
Java
|
UTF-8
| 855 | 2.546875 | 3 |
[] |
no_license
|
package com.example.cachedemo.service;
import com.example.cachedemo.controllers.DemoController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class NumberService {
private static final Logger logger = LoggerFactory.getLogger(NumberService.class);
//using this annotation spring will handing caching
//We need to provide the name of the cache to use and optionally the key.
//We can also add a condition to restrict what is cached:
@Cacheable(
value = "squareCache",
key = "#number")//,
// condition = "#number>10")
public Integer getValue(Integer number) {
logger.info("getValue method started. number:{}", number);
return number*number;
}
}
|
Go
|
UTF-8
| 3,684 | 2.671875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
package conveyor
import (
"testing"
"golang.org/x/net/context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/remind101/conveyor/builder"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestBuildQueue(t *testing.T) {
q := &buildQueue{
queue: make(chan BuildContext, 1),
}
background := context.Background()
options := builder.BuildOptions{}
err := q.Push(background, options)
assert.NoError(t, err)
ch := make(chan BuildContext)
go q.Subscribe(ch)
req := <-ch
assert.Equal(t, req.BuildOptions, options)
assert.Equal(t, req.Ctx, background)
}
func TestSQSBuildQueue_Push(t *testing.T) {
c := new(mockSQSClient)
q := &SQSBuildQueue{
sqs: c,
}
c.On("SendMessage", &sqs.SendMessageInput{
MessageBody: aws.String(`{"ID":"01234567-89ab-cdef-0123-456789abcdef","Repository":"remind101/acme-inc","Sha":"abcd","Branch":"master","NoCache":false}`),
QueueUrl: aws.String(""),
}).Return(&sqs.SendMessageOutput{}, nil)
background := context.Background()
options := builder.BuildOptions{
ID: fakeUUID,
Repository: "remind101/acme-inc",
Branch: "master",
Sha: "abcd",
}
err := q.Push(background, options)
assert.NoError(t, err)
}
func TestSQSBuildQueue_Subscribe(t *testing.T) {
c := new(mockSQSClient)
q := &SQSBuildQueue{
sqs: c,
}
c.On("ReceiveMessage", &sqs.ReceiveMessageInput{
QueueUrl: aws.String(""),
}).Return(&sqs.ReceiveMessageOutput{
Messages: []*sqs.Message{
{
ReceiptHandle: aws.String("a"),
Body: aws.String(`{"Repository":"remind101/acme-inc-1","Sha":"abcd","Branch":"master","NoCache":false}`),
},
{
ReceiptHandle: aws.String("b"),
Body: aws.String(`{"Repository":"remind101/acme-inc-2","Sha":"abcd","Branch":"master","NoCache":false}`),
},
},
}, nil)
c.On("DeleteMessageBatch", &sqs.DeleteMessageBatchInput{
Entries: []*sqs.DeleteMessageBatchRequestEntry{
{Id: aws.String("0"), ReceiptHandle: aws.String("a")},
{Id: aws.String("1"), ReceiptHandle: aws.String("b")},
},
QueueUrl: aws.String(""),
}).Return(&sqs.DeleteMessageBatchOutput{}, nil)
ch := make(chan BuildContext, 1)
q.Subscribe(ch)
assert.Equal(t, builder.BuildOptions{
Repository: "remind101/acme-inc-1",
Branch: "master",
Sha: "abcd",
}, (<-ch).BuildOptions)
assert.Equal(t, builder.BuildOptions{
Repository: "remind101/acme-inc-2",
Branch: "master",
Sha: "abcd",
}, (<-ch).BuildOptions)
}
func TestSQSBuildQueue_Subscribe_Panic(t *testing.T) {
called := make(chan error)
c := new(mockSQSClient)
q := &SQSBuildQueue{
sqs: c,
ErrHandler: func(err error) {
called <- err
},
}
c.On("ReceiveMessage", &sqs.ReceiveMessageInput{
QueueUrl: aws.String(""),
}).Run(func(args mock.Arguments) {
panic("boom")
})
ch := make(chan BuildContext, 1)
q.Subscribe(ch)
err := <-called
assert.EqualError(t, err, "panic: boom")
}
// mockSQSClient is an implementation of the sqsClient interface for testing.
type mockSQSClient struct {
mock.Mock
}
func (c *mockSQSClient) SendMessage(input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) {
args := c.Called(input)
return args.Get(0).(*sqs.SendMessageOutput), args.Error(1)
}
func (c *mockSQSClient) ReceiveMessage(input *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) {
args := c.Called(input)
return args.Get(0).(*sqs.ReceiveMessageOutput), args.Error(1)
}
func (c *mockSQSClient) DeleteMessageBatch(input *sqs.DeleteMessageBatchInput) (*sqs.DeleteMessageBatchOutput, error) {
args := c.Called(input)
return args.Get(0).(*sqs.DeleteMessageBatchOutput), args.Error(1)
}
|
Ruby
|
UTF-8
| 5,199 | 4.0625 | 4 |
[] |
no_license
|
###############################################################
# Ejercicio 1: Sintaxis
###############################################################
# Corregir los errores para poder ejecutar ambos métodos
class MiClase
def de_instancia
puts 'Método de instancia!'
end
def self.de_clase
puts 'Método de clase!'
end
end
MiClase.new.de_instancia
MiClase.de_clase
###############################################################
# Ejercicio 2: Sintaxis
###############################################################
# Corregir los errores de sintaxis para que las últimas cuatro líneas se ejecuten de manera correcta.
class MiClase
attr_writer :name
attr_reader :name
def initialize(name)
@name = name
end
def self.saludar
"Hola! Soy la clase #{self}"
end
end
c = MiClase.new('Clase Uno')
puts c.name
c.name = 'Nombre Nuevo'
puts MiClase.saludar
###############################################################
# Ejercicio 3: Herencia
###############################################################
# Se tiene la clase Vehicle que recibe como argumento un modelo y un año. El método engine_start enciende el vehículo
class Vehicle
def initialize(model, year)
@model = model
@year = year
@start = false
end
def engine_start
@start = true
end
end
# Se pide:
# Crear una clase Car que herede de Vehicle
# El constructor de Car, además de heredar las propiedades de Vehicle, debe incluir un contador de instancias de Car.
# Crear un método de clase en Car que devuelva la cantidad de instancias.
# El método engine_start heredado debe además imprimir 'El motor se ha encendido!'.
# Instanciar 10 Cars.
# Consultar la cantidad de instancias generadas de Car mediante el método de clase creado
class Car < Vehicle
@@contador_instacia = 0
def initialize(model,year)
super
@@contador_instacia += 1
end
def self.instancias
@@contador_instacia
end
def engine_start
super
puts 'El motor de ha encendido'
end
end
clases_arr = []
modelos = ['model1','model2','model3']
year = [2015,2016,2017]
10.times do
clases_arr << Car.new(modelos.sample,year.sample)
end
puts "La cantidad de instancias son: #{Car.instancias}"
###############################################################
# Ejercicio 4: Método de clase
###############################################################
# El archivo notas.txt contiene las notas de 4 alumnos
#La clase Alumno posee un constructor que recibe el nombre del alumno junto a sus cuatro notas
# Crear un método de clase llamado read_file que reciba como argumento el nombre del archivo (por defecto debe ser 'notas.txt') y devuelva la colección de objetos.
# El método debe alojar las instrucciones que se encuentran después de la clase.
# Finalmente imprimir la colección de objetos generada.
# Hint: Debes reemplazar el argumento de File.open con el nombre del argumento del método read_file
class Alumno
def initialize(nombre, nota1, nota2, nota3, nota4)
@nombre = nombre
@nota1 = nota1
@nota2 = nota2
@nota3 = nota3
@nota4 = nota4
end
def self.read_file(file)
alumnos = []
data = []
File.open(file, 'r') { |file| data = file.readlines }
data.each do |alumno|
alumnos << Alumno.new(*alumno.split(', '))
end
alumnos
end
end
print Alumno.read_file('notas.txt')
print
###############################################################
# Ejercicio 5
###############################################################
# Se tienen las clases Rectangulo y Cuadrado cuyos constructores reciben las medidas de los lados correspondientes.
# Se pide:
# Agregar un método de instancia llámado lados en ambas clases. El método debe imprimir un string conlas medidas de los lados.
# Crear un método llamado perimetro que reciba dos argumentos (lados) y devuelva el perímetro.
# Crear un método llamado area que reciba dos argumentos (lados) y devuelva el área.
# Instanciar un Rectangulo y un Cuadrado.
# Imprimir el área y perímetro de los objetos instanciados utilizando los métodos implementado
# NOTA: Donde dice:
# --> "Crear un método llamado perimetro que reciba dos argumentos (lados) y devuelva el perímetro."
# --> "Crear un método llamado area que reciba dos argumentos (lados) y devuelva el área.""
# No corresponde volver a pasar a los paremtros ya que al momento de crear el objeto se declaran y se asignan
class Rectangulo
def initialize(largo, ancho)
@largo = largo
@ancho = ancho
end
def lados
puts "El ancho es: #{@ancho}, el largo es:#{@lado}"
end
def area
@largo * @ancho
end
def perimetro
(@largo * 2) + (@ancho * 2)
end
end
class Cuadrado
def initialize(lado)
@lado = lado
end
def lados
puts "El lado del cuadrado es: #{@lado}"
end
def area
@lado * @lado
end
def perimetro
(@lado * 4)
end
end
cuadrado = Cuadrado.new(2)
rectangulo = Rectangulo.new(2,3)
puts "\n\n"
puts "El area del cuadrado es: #{cuadrado.area} y su perimetro #{cuadrado.perimetro}"
puts "El area del rectangulo es: #{rectangulo .area} y su perimetro #{rectangulo .perimetro}"
|
TypeScript
|
UTF-8
| 888 | 3 | 3 |
[
"MIT"
] |
permissive
|
import { Point3 } from "../vec/point3";
import { Vec3 } from "../vec";
import { Ray } from "../ray";
import { Material, IMaterial } from "../material";
interface IHitRecord {
p: Point3;
normal: Vec3;
material: Material;
t: number;
fontFace: boolean;
setFaceNormal: (r: Ray, outwardNormal: Vec3) => void;
}
export class HitRecord implements IHitRecord {
p: Point3;
normal: Vec3;
// @ts-ignore
material: Material;
t: number = 0;
fontFace: boolean = false;
constructor() {
this.p = new Point3();
this.normal = new Vec3();
}
setFaceNormal(r: Ray, outwardNormal: Vec3) {
this.fontFace = Vec3.dot(r.direction, outwardNormal) < 0;
this.normal = this.fontFace
? outwardNormal
: Vec3.multiply(outwardNormal, -1);
}
}
export abstract class Hittable {
abstract hit(r: Ray, t_min: number, t_max: number, rec: HitRecord): boolean;
}
|
C#
|
UTF-8
| 960 | 2.84375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
public static class DailyAchievementDictionary
{
// Key : DB_DailyAchieveList.Index
// Value :
// [IMPLEMENT]
// int -> enum
private static readonly Dictionary<int, Type> s_AchvCompDict = new Dictionary<int, Type>();
static DailyAchievementDictionary()
{
this[1] = typeof(DailyAchieveCompleteDailyAchieve); // 일일 업적 완료
this[2] = typeof(DailyAchieveChestOpen); // 상자 열기
this[3] = typeof(DailyAchieveGoldCollect); // 골드 획득
this[4] = typeof(DailyAchievePvPComplete); // 매칭 클리어 (승/패 상관X)
this[5] = typeof(DailyAchievePvEComplete); // 모험 클리어 (승/패 상관x)
this[6] = typeof(DailyAchieveCardCollect); // 카드 획득
}
public static bool TryGetValue(int achvIndex, out Type achvComp)
{
return s_AchvCompDict.TryGetValue(achvIndex, out achvComp);
}
}
|
JavaScript
|
UTF-8
| 242 | 3.25 | 3 |
[] |
no_license
|
function mostrar()
{
var numeroIngresado;
for(var i=0; numeroIngresado!=9; i++)
{
numeroIngresado = prompt("Ingrese un numero");
numeroIngresado = parseInt(numeroIngresado);
}
alert("Usted ingreso el numero 9, fin del ciclo");
}
|
Java
|
UTF-8
| 483 | 1.84375 | 2 |
[] |
no_license
|
package com.facebook.compactdiskmodule;
import com.facebook.common.init.INeedInit;
import com.facebook.compactdisk.LazyDispatcher;
import javax.inject.Inject;
/* compiled from: max_impressions */
public class LazyDispatcherInit implements INeedInit {
private final LazyDispatcher f8194a;
@Inject
public LazyDispatcherInit(LazyDispatcher lazyDispatcher) {
this.f8194a = lazyDispatcher;
}
public void init() {
this.f8194a.dispatchNow();
}
}
|
TypeScript
|
UTF-8
| 478 | 3.125 | 3 |
[
"MIT",
"JSON"
] |
permissive
|
import { ArgumentException } from './argument-exception'
export class ArgumentNullException extends ArgumentException {
/* istanbul ignore next */
public constructor(paramName?: string, message?: string) {
super(paramName, composite(paramName, message))
}
}
function composite(paramName?: string, message?: string): string {
if (message) {
return message
}
if (paramName) {
return `参数 ${paramName} 不可为空`
}
return '参数不可为空'
}
|
C++
|
UTF-8
| 585 | 2.8125 | 3 |
[] |
no_license
|
#ifndef DEFAULT_RANDOM_ENGINE_HPP
#define DEFAULT_RANDOM_ENGINE_HPP
/*!
@file default_random_engine.hpp
@brief グローバルの乱数生成エンジン
*/
#include <random>
/*!
@namespace estd
@brief extended std
*/
namespace estd
{
using DefaultRandomEngineType = std::mt19937;
inline DefaultRandomEngineType& GetDefaultRandomEngine()
{
static thread_local DefaultRandomEngineType engine;
return engine;
}
inline void Reseed(const DefaultRandomEngineType::result_type seed)
{
GetDefaultRandomEngine().seed(seed);
}
}
#endif
|
Markdown
|
UTF-8
| 2,756 | 4.25 | 4 |
[
"MIT"
] |
permissive
|
---
title: C++ 运算符重载
key: 2015-10-31-operator
date: 2015-10-31 10:50
categories: C++
tags: [C++]
---
本例为实现复数运算,定义一个复数类,其中私有成员变量有两个,实数部real和虚数部image,通过运算符重载实现复数的直接相加减。
```cpp
#include<iostream>
using namespace std;
class Complex { //复数类
private: //定义私有成员变量
double real; //定义实数部
double image; //定义虚数部
public:
Complex(void):real(0),image(0) {} //定义参数为空的构造函数
Complex(double rp):real(rp),image(0) {} //定义只有实数部的构造函数
Complex(double rp,double ip):real(rp),image(ip) {} //定义参数同时制定实数和虚数的构造函数
~Complex() {} //定义析构函数(无特定操作可不写)
Complex operator+(const Complex &x) const; //声明重载运算符+
Complex operator-(const Complex &x) const; //声明重载运算符-
Complex operator*(const Complex &x) const; //声明重载运算符*
Complex operator/(const Complex &x) const; //声明重载运算符/
bool operator==(const Complex &x) const; //声明重载运算符==
Complex& operator+=(const Complex &x); //声明重载运算符+=
void Print(void) const; //定义类成员输出函数
};
inline Complex Complex::operator+(const Complex &x) const { //重载运算符的实际函数体
return Complex(real + x.real,image + x.image);
}
inline Complex Complex::operator-(const Complex &x) const {
return Complex(real - x.real,image - x.image);
}
inline Complex Complex::operator*(const Complex &x) const {
return Complex(real * x.real - image * x.image,real * x.image + image * x.real);
}
Complex Complex::operator/(const Complex &x) const {
double m;
m = x.real * x.real + x.image * x.image;
return Complex((real * x.real + image * x.image) / m, (image * x.real - real * x.image) / m);
}
inline bool Complex::operator==(const Complex &x) const { //运算符==判断是否相等,应返回bool类型的值
return bool(real == x.real && image == x.image);
}
Complex& Complex::operator+=(const Complex &x) { //因为+=的结果是将被加数加在自己的成员函数上,所以返回自身的指针
real += x.real;
image += x.image;
return *this;
}
void Complex::Print(void) const { //输出函数
cout<<"("<<real<<","<<image<<"i)"<<endl;
}
int main(void) { //测试函数
Complex a(3, 5), b(2, 3), c;
c = a + b * a / b - b;
c.Print();
a += b;
a.Print();
if(a == c) cout<<"对象a等于对象c"<<endl;
else cout<<"对象a不等于对象c"<<endl;
return 0;
}
```
|
C
|
UTF-8
| 2,677 | 2.9375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24
struct Natal{
char pais[50];
char saudacao[50];
};
typedef struct Natal natal;
int main() {
char p[50];
natal * trad = NULL;
int i, aux;
trad = calloc(N, sizeof(natal));
sprintf(trad[0].pais,"brasil");
sprintf(trad[1].pais,"alemanha");
sprintf(trad[2].pais,"austria");
sprintf(trad[3].pais,"coreia");
sprintf(trad[4].pais,"espanha");
sprintf(trad[5].pais,"grecia");
sprintf(trad[6].pais,"estados-unidos");
sprintf(trad[7].pais,"inglaterra");
sprintf(trad[8].pais,"australia");
sprintf(trad[9].pais,"portugal");
sprintf(trad[10].pais,"suecia");
sprintf(trad[11].pais,"turquia");
sprintf(trad[12].pais,"argentina");
sprintf(trad[13].pais,"chile");
sprintf(trad[14].pais,"mexico");
sprintf(trad[15].pais,"antardida");
sprintf(trad[16].pais,"canada");
sprintf(trad[17].pais,"irlanda");
sprintf(trad[18].pais,"belgica");
sprintf(trad[19].pais,"italia");
sprintf(trad[20].pais,"libia");
sprintf(trad[21].pais,"siria");
sprintf(trad[22].pais,"marrocos");
sprintf(trad[23].pais,"japao");
sprintf(trad[0].saudacao,"Feliz Natal!");
sprintf(trad[1].saudacao,"Frohliche Weihnachten!");
sprintf(trad[2].saudacao,"Frohe Weihnacht!");
sprintf(trad[3].saudacao,"Chuk Sung Tan!");
sprintf(trad[4].saudacao,"Feliz Navidad!");
sprintf(trad[5].saudacao,"Kala Christougena!");
sprintf(trad[6].saudacao,"Merry Christmas!");
sprintf(trad[7].saudacao,"Merry Christmas!");
sprintf(trad[8].saudacao,"Merry Christmas!");
sprintf(trad[9].saudacao,"Feliz Natal!");
sprintf(trad[10].saudacao,"God Jul!");
sprintf(trad[11].saudacao,"Mutlu Noeller");
sprintf(trad[12].saudacao,"Feliz Navidad!");
sprintf(trad[13].saudacao,"Feliz Navidad!");
sprintf(trad[14].saudacao,"Feliz Navidad!");
sprintf(trad[15].saudacao,"Merry Christmas!");
sprintf(trad[16].saudacao,"Merry Christmas!");
sprintf(trad[17].saudacao,"Nollaig Shona Dhuit!");
sprintf(trad[18].saudacao,"Zalig Kerstfeest!");
sprintf(trad[19].saudacao,"Buon Natale!");
sprintf(trad[20].saudacao,"Buon Natale!");
sprintf(trad[21].saudacao,"Milad Mubarak!");
sprintf(trad[22].saudacao,"Milad Mubarak!");
sprintf(trad[23].saudacao,"Merii Kurisumasu!");
while(scanf("%[^\n]%*c", p) != EOF){
aux=0;
for(i=0;i<N;i++){
if(strcmp(p,trad[i].pais)==0){
printf("%s\n", trad[i].saudacao);
aux=1;
}
}
if(aux==0) printf("-- NOT FOUND --\n");
}
free(trad);
return 0;
}
|
Python
|
UTF-8
| 1,786 | 3.359375 | 3 |
[] |
no_license
|
#
# @lc app=leetcode.cn id=124 lang=python3
#
# [124] 二叉树中的最大路径和
#
# https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/description/
#
# algorithms
# Hard (44.67%)
# Likes: 1389
# Dislikes: 0
# Total Accepted: 184.7K
# Total Submissions: 413.4K
# Testcase Example: '[1,2,3]'
#
# 路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个
# 节点,且不一定经过根节点。
#
# 路径和 是路径中各节点值的总和。
#
# 给你一个二叉树的根节点 root ,返回其 最大路径和 。
#
#
#
# 示例 1:
#
#
# 输入:root = [1,2,3]
# 输出:6
# 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
#
# 示例 2:
#
#
# 输入:root = [-10,9,20,null,null,15,7]
# 输出:42
# 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
#
#
#
#
# 提示:
#
#
# 树中节点数目范围是 [1, 3 * 10^4]
# -1000
#
#
#
from typing import Optional
from commons.Tree import TreeNode
# @lc code=start
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
result = float('-inf')
def helper(node: Optional[TreeNode]):
if not node:
return 0
left = helper(node.left)
right = helper(node.right)
max_single = max(left + node.val, right + node.val, node.val)
nonlocal result
result = max(max_single, result, left + right + node.val)
return max_single
helper(root)
return result
# @lc code=end
s = Solution()
print(s.maxPathSum(TreeNode.deserialize([-10,9,20,None,None,15,7])))
|
PHP
|
UTF-8
| 2,077 | 3.6875 | 4 |
[] |
no_license
|
<?php
#2020.7.9 三数之和
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function threeSum($nums)
{
$threeArray = [];
$count = count($nums);
sort($nums);
for ($i = 0; $i < $count - 2; ++$i) {
if ($nums[$i] > 0) break;
if ($i > 0 && $nums[$i] === $nums[$i - 1]) continue;
$first = $i + 1;
$last = $count - 1;
while ($first < $last) {
$tSum = $nums[$first] + $nums[$last] + $nums[$i];
if ($tSum === 0) {
$threeArray[] = [$nums[$i], $nums[$first], $nums[$last]];
while ($first < $last && $nums[$last] == $nums[--$last]) {
};
while ($first < $last && $nums[$first] == $nums[++$first]) {
};
} else
if ($tSum > 0) {
$last--;
} else if ($tSum < 0) {
$first++;
}
}
}
return $threeArray;
}
#2020.7.9 两数之和 1遍hash
function twoSum($nums, $target)
{
$count = count($nums);
$map = [];
for ($i = 0; $i < $count; $i++) {
$value = $target - $nums[$i];
if (isset($map[$value])) {
return [$map[$value], $i];
}
$map[$nums[$i]] = $i;
}
return [];
}
#2020.7.9 删除排序数组中的重复项 双指针
function removeDuplicates(&$nums)
{
$i = 0;
$count = count($nums);
for ($j = 1; $j < $count; $j++) {
if ($nums[$i] != $nums[$j]) {
$i++;
$nums[$i] = $nums[$j];
}
}
return $i + 1;
}
#2020.7.9 旋转数组 翻转三次
function rotate(&$nums, $k)
{
$len = count($nums);
$k = $k % $len;
if ($len < 2) {
return $nums;
}
reverse($nums, 0, $len - 1);
reverse($nums, 0, $k - 1);
reverse($nums, $k, $len - 1);
return $nums;
}
function reverse(&$nums, $start, $end)
{
while ($start < $end) {
$temp = $nums[$start];
$nums[$start] = $nums[$end];
$nums[$end] = $temp;
$start++;
$end--;
}
}
|
Markdown
|
UTF-8
| 2,967 | 3.140625 | 3 |
[] |
no_license
|
# YouTube iFrame API Wrapper
A convenient way to add custom functionality and styles to YouTube's video player using the iFrame API
provided by YouTube.
> ***Warning*** Bug in IE9. Player carrys on playing after the preload play/pause/seek cycle.
### Basic Usage
Add the template wherever you want the video to appear on your page, padding in the video id wherever it
is needed. This example used a YouTube video id of `ShUyfk4QB-8`.
```html
<div class="video-container" id="ShUyfk4QB-8">
<div class="embed-responsive embed-responsive-16by9">
<div class="embed-responsive-item">
<div class="mask"></div>
<img src="assets/img/preload.gif" class="preload">
<div class="play">
<i class="play-icon glyphicon glyphicon-play-circle"></i>
</div>
<div class="mute">
<i class="mute-icon notMuted glyphicon glyphicon-volume-up"></i>
<i class="mute-icon isMuted glyphicon glyphicon-volume-off"></i>
</div>
<img class="thumb" src="http://img.youtube.com/vi/ShUyfk4QB-8/maxresdefault.jpg">
<div class="iframe" id="video-ShUyfk4QB-8"></div>
</div>
</div>
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
</div>
</div>
```
Include YouTube's iFrame API and the Player class.
```html
<script src="//www.youtube.com/iframe_api"></script>
<script src="path/to/Player.js"></script>
```
Add the onYouTubeIframeAPIReady that the iFrame API will call when it's loaded. Then instantiate the
Player class and call the init method, passing in the YouTube video id and any method callbacks you want
(See Method Callbacks section for more information).
```js
function onYouTubeIframeAPIReady() {
(new Player).init({id: 'ShUyfk4QB-8'});
}
```
### Method Callbacks
There are 10 method callbacks that will get called on specific events. You can use these to hoot into
these events and execute your own code.
```js
(new Player).init({
id: 'ShUyfk4QB-8',
onLoaded: function(player) {},
onPlay: function(player) {},
onPlaying: function(player) {},
onPause: function(player) {},
onMute: function(player) {},
onUnMute: function(player) {},
onEnd: function(player) {},
onSeekStart: function(player) {},
onSeeking: function(player) {},
onSeekEnd: function(player) {}
});
```
Here is an example. When the video is played, after 5 seconds the video is paused and the current time
is alerted.
```js
(new Player).init({
id: 'ShUyfk4QB-8',
onPlay: function(player) {
setTimeout(function() {
player.pause();
alert(player.time());
}, 5000);
}
});
```
### Example Player Theme


|
Swift
|
UTF-8
| 3,497 | 3.28125 | 3 |
[] |
no_license
|
//
// TextSettingAttribute.swift
// SwiftUIPractice
//
// Created by 灵 Q on 2020/4/13.
// Copyright © 2020 灵 Q. All rights reserved.
//
import SwiftUI
struct TextSettingAttribute: View {
var body: some View {
VStack {
//设置字体之间的间隙
Text("Hello, World!,哈哈哈,")
.tracking(10.0)
Text("Hello, World!,哈哈哈,")
.kerning(10.0)
//设置字体模糊效果 radius模糊半径
Text("Hello, World!,哈哈哈哈哈哈哈哈哈")
.blur(radius: 1.0)
//设置字体间距与行间距,并不限制行数
Text("这是设置字体的h行间距,这是设置字体的h行间距,这是设置字体的h行间距,这是设置字体的h行间距,这是设置字体的h行间距,这是设置字体的h行间距,这是设置字体的h行间距")
.tracking(5.0)
.lineSpacing(10.0)
.lineLimit(nil)
//设置字体偏移量
Text("Hello, World!")
.offset(x: 40, y: 0.0)
.background(Color.red)
Divider()
Text("Hello, World!")
//横线
.strikethrough(true, color: Color.blue)
//下划线
.underline(true, color: Color.black)
//斜体
.italic()
//字体大小
.font(.system(size: 25))
//设置粗体样式
.fontWeight(.bold)
//字体颜色
.foregroundColor(.yellow)
//圆角
.cornerRadius(30)
.background(Color.red)
// 如果要设置文字的背景阴影, 一般还是要包裹起来
.shadow(color: Color.green, radius: 10)
//添加单击手势
.onTapGesture {
print("...点击了....")
}
//添加长按手势
.onLongPressGesture(minimumDuration: 2, maximumDistance: 4, pressing: { (result) in
print("\(result ? "开始按压" : "按压结束")")
}) {
print("触发长按")
}
// 添加其他手势
.gesture(
// 比如这里添加一个拖动手势
DragGesture()
// 拖动改变了
.onChanged({ (value) in
print(value)
})
// 拖动结束
.onEnded({ (value) in
print(value)
})
)
VStack {
Divider()
Text("Hello, World!")
//注意:会使对齐属性失效
.position(CGPoint(x: 40, y: 10))
.frame(width: 200, height: 50, alignment: .bottomTrailing)
.background(Color.red)
//设置多行对齐方式
Text("Hello, World!\n这是\nthis\n哈哈哈哈哈哈")
.multilineTextAlignment(.trailing)
}
Spacer()
}
.navigationBarTitle("Text")
}
}
struct TextSettingAttribute_Previews: PreviewProvider {
static var previews: some View {
TextSettingAttribute()
}
}
|
Swift
|
UTF-8
| 6,542 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// Actions
//
// Created by Infraestructura on 6/14/19.
// Copyright © 2019 Daniel Rosales. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController, UITextFieldDelegate {
@IBAction func unwindToHome(_ unwindSegue: UIStoryboardSegue) {
//let sourceViewController = unwindSegue.source
// Use data from the view controller which initiated the unwind segue
}
@IBOutlet weak var ResizeY: NSLayoutConstraint!
@IBAction func btnEnter(_ sender: Any) {
//var mensaje:String
var mensaje = "" //Inferencia
let correo = txtCorreo.text!
let password = txtPass.text!
if correo.isEmpty{
mensaje = "Escribe tu correo"
}
else{
let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let correoValido = NSPredicate(format: "SELF MATCHES %@", regex)
if !correoValido.evaluate(with: correo){
mensaje = "No lo sé Rick...parece falso"
}
else{
let urlSTR = "http://janzelaznog.com/DDAM/iOS/WS/login.php"
guard let cypherPass = base64Encoded(password) else {
let actionController = UIAlertController(title: "Error pass cypher", message: mensaje, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
actionController.addAction(alertAction)
self.present(actionController, animated: true, completion: nil)
return
}
let params:Parameters = ["username": correo, "password":cypherPass]
Alamofire.request(urlSTR, method:.post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON{ (responseData) in
print("Hola" + responseData.description)
if let data = responseData.data{
do {
//Alamofire.request(urlSTR, method: post, parameters: params, encoding: JSONEncoding.default, headers: HTTPHeaders?) //Para darle formato en json
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
if let code = jsonResponse["code"] as? String{
if code == "200" {
UserDefaults.standard.set(Date(), forKey: "inicioSesion")
self.performSegue(withIdentifier: "LoginOK", sender: nil)
}
else {
let actionController = UIAlertController(title: "Error", message: jsonResponse["message"] as! String, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
actionController.addAction(alertAction)
self.present(actionController, animated: true, completion: nil)
}
}
}
catch {
let actionController = UIAlertController(title: "Error catch", message: error.localizedDescription, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
actionController.addAction(alertAction)
self.present(actionController, animated: true, completion: nil)
}
}
}
}
}
/* if mensaje != ""{
let actionController = UIAlertController(title: "Error", message: mensaje, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
actionController.addAction(alertAction)
self.present(actionController, animated: true, completion: nil)
}
else{
//Navega a la siguiente vista
/* txtCorreo.text = ""*/
//Guardar el timestamp del inicio de sesión
/* UserDefaults.standard.set(Date(), forKey: "inicioSesion")
self.performSegue(withIdentifier: "LoginOK", sender: nil)
*/
}*/
}
func base64Encoded(_ string:String) -> String? {
if let data = string.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
@IBOutlet weak var txtCorreo: UITextField!
@IBOutlet weak var txtPass: UITextField!
@IBAction func TapInView(_ sender: Any) {
print("tap")
txtCorreo.resignFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(subeTeclado(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
//TODO suscribirse a la notificacion keybordWillHideNotification invocando un metodo que se llame "bajaTeclado"
NotificationCenter.default.addObserver(self, selector: #selector(bajaTeclado(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
//txtCorreo.text = ""
}
@objc func subeTeclado(_ notificacion:Notification){
print("sube Teclado")
ResizeY.constant = -50.0
}
@objc func bajaTeclado(_ notificacion:Notification){
print("baja Teclado")
ResizeY.constant = 0.0
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self ,action:#selector(TapInView(_:)))
self.view.addGestureRecognizer(tapGestureRecognizer)
txtCorreo.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
// called when 'return' key pressed. return NO to ignore.
btnEnter(self) //selector para invocar btnEnter
return true
}
}
|
C
|
UTF-8
| 787 | 2.609375 | 3 |
[] |
no_license
|
#include "screenster.h"
typedef struct {
draw_state_t draw_state;
} saved_graphics_state_t;
#define GRAPHICS_STACK_SIZE 32
static saved_graphics_state_t graphics_stack[GRAPHICS_STACK_SIZE];
static int graphics_stack_count = 0;
void reset_graphics_state() {
graphics_stack_count = 0;
draw_state.flags = DRAW_PEN_ON | DRAW_FILL_ON;
draw_state.pen_color = al_map_rgb(255, 255, 255);
draw_state.fill_color = al_map_rgb(0, 0, 0);
draw_state.x = 0.0f;
draw_state.y = 0.0f;
}
void save_graphics_state() {
graphics_stack[graphics_stack_count].draw_state = draw_state;
graphics_stack_count++;
}
void restore_graphics_state() {
graphics_stack_count--;
draw_state = graphics_stack[graphics_stack_count].draw_state;
}
|
Python
|
UTF-8
| 561 | 3.75 | 4 |
[] |
no_license
|
# Given the head of a singly linked list, return the middle node of the linked list.
# If there are two middle nodes, return the second middle node.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
l,r=head,head
while r and r.next:
l = l.next
r = r.next.next
return l
|
Markdown
|
UTF-8
| 608 | 2.875 | 3 |
[] |
no_license
|
# using-mixpanel
This sample website explains how you can use mixpanel to track user activities on your website
# Steps
These will be the steps
1. Create an account on mixpanel.
2. You will get an installation script for every language, I am using JavaScript here.
3. Add that script just above your closing head code.
<br><br>
Now its installed, for documentations, visit: <a href="https://developer.mixpanel.com/docs/javascript">Official Docs</a>
<br>
# Adding code synetex to track events
Adding a few in my code
1. Track website loading `function onload(){
mixpanel.track("Website Loaded")
}`
2.
|
JavaScript
|
UTF-8
| 1,231 | 2.59375 | 3 |
[] |
no_license
|
const jwt = require("jsonwebtoken");
const authMiddleware = {};
authMiddleware.loginRequired = async (req, res, next) => {
try {
// 1. Get the token from request
const tokenString = req.headers.authorization;
if (!tokenString) {
throw new Error("Token not found");
}
const token = tokenString.replace("Bearer ", "");
// 2. Check the token is exist
jwt.verify(token, process.env.JWT_SECRET_KEY, (error, payload) => {
if (error) {
if (error.name === "TokenExpiredError") {
throw new Error("Token expired");
} else {
throw new Error("Token is invalid");
}
}
req.userId = payload._id;
});
// 3. Go to the next step
next();
} catch (error) {
res.status(400).json({
success: false,
error: error.message,
});
}
};
authMiddleware.adminRequired = async (req, res, next) => {
try {
const userId = req.userId;
const currentUser = await User.findById(userId);
const isAdmin = currentUser.role === "admin";
if (!isAdmin) return next(new Error("401- Admin required"));
req.isAdmin = isAdmin;
next();
} catch (error) {
next(error);
}
};
module.exports = authMiddleware;
|
Java
|
UTF-8
| 1,069 | 2 | 2 |
[] |
no_license
|
package com.siliconlabs.bluetoothmesh.App;
import com.siliconlabs.bluetoothmesh.App.Fragments.NetworkList.NetworkListFragment;
import com.siliconlabs.bluetoothmesh.App.Fragments.NetworkList.NetworkListModule;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.AndroidInjector;
import dagger.multibindings.ClassKey;
import dagger.multibindings.IntoMap;
@Module(
subcomponents = ActivityBuilder_BindNetworkListFragment.NetworkListFragmentSubcomponent.class
)
public abstract class ActivityBuilder_BindNetworkListFragment {
private ActivityBuilder_BindNetworkListFragment() {}
@Binds
@IntoMap
@ClassKey(NetworkListFragment.class)
abstract AndroidInjector.Factory<?> bindAndroidInjectorFactory(
NetworkListFragmentSubcomponent.Builder builder);
@Subcomponent(modules = NetworkListModule.class)
public interface NetworkListFragmentSubcomponent extends AndroidInjector<NetworkListFragment> {
@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<NetworkListFragment> {}
}
}
|
Markdown
|
UTF-8
| 776 | 3.21875 | 3 |
[] |
no_license
|
#React Native and Redux
<hr>
This application was a tutorial to work with react native and redux. The app takes some dummy JSON objects displaying different library names such as "Webpack", "React", etc and displays them in a list view. Then as the user taps through the different names, an action creater to update the selectedId in the redux store which then triggers a displayed textbox with info about that library
Things learned:
- Though I had already learned how to work with redux, I learned how to incorporate it into a React Native project.
- Listviews in React Native and how they work under the hood
- Animation basics in React Native with _LayoutAnimation_ along with _Touchables_ for user interaction
<img src="./src/assets/tut3.gif" height=600 width=300/>
|
JavaScript
|
UTF-8
| 2,688 | 2.640625 | 3 |
[] |
no_license
|
var doctors = require('./data/doctors.json')
var restaurants = require('./data/restaurants.json')
var users = require('./data/users.json')
var tips = require('./data/tips.json')
module.exports = function(app) {
app.get('/search', function(req, res) {
res.render('search')
})
app.get('/search/restaurants/name/has/:keyword', function(req, res) {
var keyword = req.params.keyword
// TODO: lookup restaurants whose names contain the given keyword
var rs = [restaurants[6], restaurants[10]] // hardcoded for 'Pizza'
res.render('listRestaurants.jade', {
restaurants: rs
})
})
app.get('/search/restaurants/good/for/:x', function(req, res) {
var x = req.params.x
// TODO: lookup restaurants good for :x
var rs = [restaurants[1], restaurants[2], restaurants[3]] // hardcoded fake results
res.render('listRestaurants.jade', {
restaurants: rs
})
})
app.get('/search/restaurants/ambience/is/:x', function(req, res) {
var x = req.params.x
// TODO: lookup restaurants has ambience of :x
var rs = [restaurants[1], restaurants[2], restaurants[3]] // hardcoded fake results
res.render('listRestaurants.jade', {
restaurants: rs
})
})
app.get('/search/restaurants/category/is/:x', function(req, res) {
var x = req.params.x
// TODO: lookup restaurants belonging to category :x
var rs = [restaurants[1], restaurants[2], restaurants[3]] // hardcoded fake results
res.render('listRestaurants.jade', {
restaurants: rs
})
})
app.get('/search/restaurants/stars/:relationship/:number', function(req, res) {
var number = req.params.number
var relationship = req.params.relationship
// TODO: lookup restaurants with starts higher or lower than :number
var rs = [restaurants[1], restaurants[2], restaurants[3]] // hardcoded fake results
res.render('listRestaurants.jade', {
restaurants: rs
})
})
app.get('/search/restaurants/q', function(req, res) {
var name = req.query.name
var minStars = req.query.minStars
var category = req.query.category
var ambience = req.query.ambience
console.log('req.query: ', req.query)
// // TODO: lookup restaurants with the given query parameters
var rs = [restaurants[1], restaurants[2], restaurants[3]] // hardcoded fake results
res.render('listRestaurants.jade', {
restaurants: rs
})
})
}
|
Markdown
|
UTF-8
| 664 | 3.078125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Simple node app
A pretty simple node application to show how to create and use a docker container. It can be used for creating simple one off services that exit after running.
## For Building the container
```
docker build -t my-node-app .
```
## For Running the container
```
docker run my-node-app
```
## Resources
* [Creating a Docker container for a NodeJs application - Tutorial - Video](https://youtu.be/piGUsH6p1IE)
* [Creating a Docker container for a NodeJs application - Tutorial - Post](https://www.dlighthouse.co/2017/09/docker-node-express-mongo.html)
* [Dockerizing a Node.js web app](https://nodejs.org/en/docs/guides/nodejs-docker-webapp/)
|
Java
|
UTF-8
| 1,376 | 2.046875 | 2 |
[] |
no_license
|
package project.club.p002.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import project.club.p002.dao.ClubP002_d002DAO;
import project.club.vo.ClubMemberVO;
@Service
public class ClubP002_d002ServiceImpl implements ClubP002_d002Service{
@Autowired
private ClubP002_d002DAO clubP002_d002DAO;
@Override
public List<ClubMemberVO> waitMemberList(Map<String, Object> searchMap) {
List<ClubMemberVO> waitMemberList = clubP002_d002DAO.waitMemberList(searchMap);
return waitMemberList;
}
@Override
public void permitMember(Map<String, Object> updateMap) {
clubP002_d002DAO.permitMember(updateMap);
}
@Override
public void denyMember(Map<String, Object> deleteMap) {
clubP002_d002DAO.denyMember(deleteMap);
}
@Override
public List<ClubMemberVO> getClubMemberList(Map<String, Object> searchMap) {
List<ClubMemberVO> list = clubP002_d002DAO.clubMemberList(searchMap);
return list;
}
@Override
public void qualifyMember(Map<String, Object> searchMap) {
clubP002_d002DAO.qualifyMember(searchMap);
}
@Override
public void kickMember(Map<String, Object> searchMap) {
clubP002_d002DAO.kickMember(searchMap);
}
@Override
public void usurpMember(Map<String, Object> searchMap) {
clubP002_d002DAO.usurpMember(searchMap);
}
}
|
Python
|
UTF-8
| 913 | 3.1875 | 3 |
[] |
no_license
|
#!/bin/env python3
import glob
import os, sys
def main(dovedir):
"""This is the main commandline function (list_unique_dates.py)
It reads the SR image files in a directory and lists the unique dates in standard output
"""
imglist = glob.glob(dovedir+'/2*_SR.tif')
print("Number of images: %d" % (len(imglist)))
if (len(imglist) == 0):
print("No images found that match.")
sys.exit(0)
newlist = [ os.path.basename(img) for img in imglist ]
thedates = [ img[0:8] for img in newlist ]
uniqdates = sorted(list(set(thedates)))
for thisdate in uniqdates:
print("%s" % (thisdate))
if __name__ == "__main__":
if len( sys.argv ) != 2:
print("[ ERROR ] you must supply 1 arguments: list_unique_dates.py dovedir")
print(" dovedir = directory containing the Dove images (*_SR.tif) to get search for unique dates.")
print("")
sys.exit( 0 )
main(sys.argv[1])
|
Python
|
UTF-8
| 51 | 3.140625 | 3 |
[] |
no_license
|
nombre = input ("ingrese su nombre")
print(nombre)
|
JavaScript
|
UTF-8
| 1,012 | 2.78125 | 3 |
[] |
no_license
|
const Sequelize = require('sequelize');
const sequelize = new Sequelize('clase_4', 'root', '', {
host: 'localhost',
dialect: 'mariadb'
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
/* crea una tabla */
class Cars extends Sequelize.Model {}
Cars.init({
movieName: Sequelize.STRING,
director:Sequelize.STRING,
year:Sequelize.STRING
}, { sequelize, modelName: 'movies' }); /*define nombre de la tabla */
const Model = Sequelize.Model;
class User extends Model {}
User.init({
movieName: {
type: Sequelize.STRING,
allowNull: false
},
director: {
type: Sequelize.STRING
},
year: {
type: Sequelize.STRING
}
}, {
sequelize,
modelName: 'movies'
});
//elimina usuario con id =1 (se espera que se elimine star wars 1)
User.destroy({
where: {
id: 1
}
}).then(() => {
console.log("Elimine Registro");
});
|
Java
|
UTF-8
| 1,517 | 3.59375 | 4 |
[] |
no_license
|
import java.util.Stack;
/*
* @Author: Scarlett Chen
* @date: 12/27/2014 Sat 11:42 PM
* LeetCode 156 Largest Rectangle in Histogram
* 1. o(n^2) + 剪枝可过
* 2. 线段树,维护线段之中的最小值 + 分治 recursive 可过 http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/
* 3. 用栈 保持递增序列
* 这个讲得特别好:http://blog.csdn.net/doc_sgl/article/details/11805519
*/
public class LargestRectangleArea {
public int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int n = height.length;
if (n<1) return 0;
int largest = height[0];
for (int i=0; i<=n; i++) {
int curHeight = i==n? 0: height[i];
while (!stack.isEmpty() && height[stack.peek()] > curHeight) {
int index = stack.pop();
/*
* 拿 0 3 2 5 举例
* 之所以要i-stack.peek()-1
* 是因为在入栈时,2<3,所以3被踢掉了。但在算2为高度的最大面积时
* 就要算从栈内的 0 后面一位直到i:这距离就是 i-stack.peek()【就是0 +1
*/
int curArea = height[index] * (stack.isEmpty()? i:i-stack.peek()-1);
largest = Math.max(largest, curArea);
}
stack.push(i);
}
return largest;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
Python
|
UTF-8
| 1,897 | 2.5625 | 3 |
[] |
no_license
|
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
from object_detection_dataset import DataTransform
from object_detection_SSD import SSD
def main():
voc_classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
'horse', 'motorbike', 'person', 'pottedplant', 'sheep',
'sofa', 'train', 'tvmonitor']
# --------------
# Network load
ssd_cfg = {
'num_classes': 21,
'input_size': 300,
'bbox_aspect_num': [4, 6, 6, 6, 4, 4],
'feature_maps': [38, 19, 10, 5, 3, 1],
'steps': [8, 16, 32, 64, 100, 300],
'min_sizes': [30, 60, 111, 162, 213, 264],
'max_sizes': [60, 111, 162, 213, 264, 315],
'aspect_ratios': [[2], [2, 3], [2, 3], [2, 3], [2], [2]],
}
net = SSD(phase="inference", cfg=ssd_cfg)
net_weights = torch.load('./weights/ssd300_2.pth',
map_location={'cuda:0': 'cpu'})
net.load_state_dict(net_weights)
print("Weight loaded; network complete.")
# --------------
# Image load
image_file_path = "./data/cowboy-757575_640.jpg"
img = cv2.imread(image_file_path)
height, width, channels = img.shape
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
color_mean = (104, 117, 123)
input_size = 300
transform = DataTransform(input_size, color_mean)
phase = "val"
img_transformed, boxes, labels = transform(img, phase, "", "")
img = torch.from_numpy(img_transformed[:, :, (2, 1, 0)]).permute(2, 0, 1)
# --------------
# Inference
net.eval()
x = img.unsqueeze(0)
detections = net(x)
print(detections.shape)
print(detections)
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 1,658 | 3.140625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 18:19:51 2019
@author: ashleshashinde
"""
import csv
import pandas as pd
feedback_dict={}
new_dict={}
column_list = ['title', 'artist', 'lyrics','genre', 'mood']
def max_voting(feedback_dict):
for key in feedback_dict:
value=feedback_dict[key]
happy=0
sad=0
for feedback in value:
mood=feedback[3]
genre=feedback[4]
score=feedback[5]
if mood=="happy" and score == '0':
happy+=1
elif mood=="happy" and score == '1':
sad+=1
elif mood=="sad" and score == '1':
happy+=1
elif mood=="sad" and score == '0':
sad+=1
print( key ,sad,happy)
if happy > sad:
new_dict[key]=(feedback[0],feedback[1],feedback[2],feedback[4],"happy")
else:
new_dict[key]=(feedback[0],feedback[1],feedback[2],feedback[4],"sad")
return(new_dict)
with open('feedback.csv','r') as file:
reader = csv.reader(file)
for rows in reader:
key= rows[1]+" "+rows[2]
if key in feedback_dict:
feedback_dict[key].append((rows[1],rows[2],rows[3],rows[4],rows[5],rows[7]))
# print(rows[7])
else:
feedback_dict[key] = [(rows[1],rows[2],rows[3],rows[4],rows[5],rows[7])]
new_dict=max_voting(feedback_dict)
new_df = pd.DataFrame.from_dict(new_dict, orient = 'index',columns=column_list)
# mydict = {rows[1]+" "+rows[2]:(rows[4],rows[6]) for rows in reader}
|
Java
|
UTF-8
| 3,138 | 2.640625 | 3 |
[] |
no_license
|
package ourneighborschild;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class StoplightPanel extends JPanel implements ActionListener, DatabaseListener
{
/**
* This class implements a stop light that the user can click and set the color and
* add a message as a tool tip. All objects that have stop lights in the ONC application
* are derived from ONCEntity. This class listens to data base changes. If change objects
* are derived from type ONCEntity, the the stop light is updated.
*/
private static final long serialVersionUID = 1L;
private JRadioButton rb;
private ONCDatabase db;
private ONCEntity e;
private GlobalVariablesDB gvs;
private JFrame frame;
StoplightPanel(JFrame frame, ONCDatabase db)
{
this.frame = frame;
this.db = db;
e = null;
gvs = GlobalVariablesDB.getInstance();
rb = new JRadioButton(gvs.getImageIcon(8));
rb.setEnabled(false);
rb.addActionListener(this);
db.addDatabaseListener(this);
this.add(rb);
}
void setEntity(ONCEntity e)
{
this.e = e;
if(e != null)
{
this.set(e.getStoplightPos(), e.getStoplightMssg() + ": " + e.getStoplightChangedBy() );
rb.setEnabled(true);
}
else
rb.setEnabled(false);
}
void set(int pos, String mssg)
{
// System.out.println(String.format("Stoplight.set: pos= %d, mssg= %s", pos, mssg));
if(pos >= 0 && pos < 4)
rb.setIcon(gvs.getImageIcon(pos+5));
else
rb.setIcon(gvs.getImageIcon(8));
rb.setToolTipText(mssg);
}
void clear()
{
rb.setIcon(gvs.getImageIcon(8));
rb.setToolTipText("");
rb.setEnabled(false);
}
boolean showStoplightDialog()
{
StoplightDialog slDlg = new StoplightDialog(frame, "Stoplight");
slDlg.setData(e.getStoplightPos(), e.getStoplightMssg(), e.getStoplightChangedBy());
slDlg.setLocationRelativeTo(this);
slDlg.setVisible(true);
if(slDlg.getStoplightPos() != e.getStoplightPos() ||
!slDlg.getStoplightMssg().equals(e.getStoplightMssg()))
{
//user changed stop light, update ONCEntity
e.setStoplightPos(slDlg.getStoplightPos());
e.setStoplightMssg(slDlg.getStoplightMssg());
e.setStoplightChangedBy(UserDB.getInstance().getUserLNFI());
//notify data base of update
db.update(this, e);
//change the radio button to reflect the dialog user changes
set(e.getStoplightPos(), e.getStoplightMssg() + ": " + e.getStoplightChangedBy());
return true;
}
else
return false; //Data didn't change
}
@Override
public void actionPerformed(ActionEvent ae)
{
showStoplightDialog();
}
@Override
public void dataChanged(DatabaseEvent dbe)
{
if(dbe.getSource() != this && dbe.getObject1() != null &&
ONCEntity.class.isAssignableFrom(dbe.getObject1().getClass()))
{
//didn't originate the change and is an ONCEntity subclass so it has a stop light
ONCEntity ue = (ONCEntity) dbe.getObject1();
if(e != null && ue.getID() == e.getID())
set(ue.getStoplightPos(), ue.getStoplightMssg() + ": " + ue.getStoplightChangedBy());
}
}
}
|
Rust
|
UTF-8
| 906 | 3.90625 | 4 |
[] |
no_license
|
// Complete this function to return the factorial of a given number
pub fn factorial(num: u64) -> u64 {}
fn main() {
println!("The factorial of 0 = {}", factorial(0));
println!("The factorial of 1 = {}", factorial(1));
println!("The factorial of 5 = {}", factorial(5));
println!("The factorial of 10 = {}", factorial(10));
println!("The factorial of 19 = {}", factorial(19));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn factorial_of_1() {
assert_eq!(1, factorial(0));
assert_eq!(1, factorial(1));
assert_eq!(120, factorial(5));
assert_eq!(40320, factorial(8));
assert_eq!(3628800, factorial(10));
assert_eq!(87178291200, factorial(14));
assert_eq!(6402373705728000, factorial(18));
assert_eq!(121645100408832000, factorial(19));
assert_eq!(2432902008176640000, factorial(20));
}
}
|
C++
|
UTF-8
| 514 | 3.3125 | 3 |
[] |
no_license
|
#include <iostream>
#include <time.h>
/*there is few comment present */
using namespace std;
int main()
{
int numbers[10];
srand(time(NULL));
for (int i = 0; i < 10; i++) {
numbers[i] = rand() % 41 - 20; // -20 ... 20
}
for (int i = 0; i < 10; i++) {
cout << numbers[i] << " ";
}
if (numbers[0] > 0) {
cout << "fisrt number is positive" << endl;
}
if (numbers[0] < 0) {
cout << "fisrt number is negative" << endl;
}
if (numbers[0] == 0) {
cout << "fisrt number is zero" << endl;
}
}
|
Python
|
UTF-8
| 1,326 | 2.921875 | 3 |
[] |
no_license
|
# Testing the things in the funcs.py file.
# Most of the underlying functions point directly to
# numpy funcs so no need to test those ones.
import inspect
import numpy as np
from src.funcs import get_funcs, create_args
def test_create_args():
"""
Test the creat_args function which creates
random parameters for functions which require them
"""
all_func_names = get_funcs('names')
for fname in all_func_names:
f = get_funcs(fname)
arg_dict = create_args(f)
expected_args = dict(inspect.signature(f).parameters)
del expected_args['z'] # We don't create an argument for the input vector
for a in expected_args:
assert a in arg_dict
def test_mod():
"""
Test the new thresholded mod function.
"""
f = get_funcs('mod')
arg_dict = create_args(f)
in_vec = np.arange(-10, 10, 0.2)
out_vec = f(in_vec, **arg_dict)
expected = (np.mod(in_vec, arg_dict['divisor']) < arg_dict['thresh']).astype(float)
assert np.all(out_vec == expected)
def test_round():
"""
Test the round function
"""
f = get_funcs('round')
arg_dict = create_args(f)
in_vec = np.arange(-10, 10, 0.2)
out_vec = f(in_vec, **arg_dict)
expected = np.round(in_vec, arg_dict['decimals'])
assert np.all(out_vec == expected)
|
Markdown
|
UTF-8
| 3,344 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
# Get an undergraduate internship
I'm writing this repo to keep track of everything I have done and continue to do in order to get an internship at basically any company I want. I messed up, it's already March of my Junior year. My very first piece of advice is to do this stuff earlier. Start your Sophomore year, even your Freshman year. If you aren't in college, start now. This will include resources to reference that help you learn the fundamentals for the interview process. I'm assuming you know data structures and algorithms. Good luck!
## Step 1: Build a schedule, make it work
- Spend 3 hours a day on preparing for an interview
- 2 hours should be used to work on leetcode problems
- 1 hours should be dedicated to applying to internships
## Step 2: Learn & Review the fundamentals
- Data Structures and Algorithms are your friend
- Watch YouTube videos on algorithms, not lectures
- Do LeetCode and Hackerrank problems, Easy/Medium
- Read 'Cracking the Coding Interview
- Invest in LeetCode Premium and _use it_
## Step 3: Mentally Prepare for the Technical and Behavioral Interview
- Replace LeetCode and Hackerrank time with mock interviews
- Put yourself in uncomfortable positions where someone watches you code
- Read and judge other people's code
- Continue to apply to new jobs
- Your school's Career Development (or equivalent) office may offer interviewing practices
## Step 4: Revise Your Resume
- If you are not getting as many call backs as desired, you need to fix your resume
- Increase your number of projects
- Try to make your projects impressive, using relevant enterprise technologies
- Get rid of irrelevant work experience, highlight your tech experience
- In your bullet points, each should describe 'what, how, why'
- be very specific and use plenty of keywords that reference the technologies you utilized
- if you can't fit it all, change your format so you _can_
- get rid of irrelevant achievements
- do not list any skills that you barely have. If you list a language that you are not familiar with, you run the risk of your interviewer asking you to use it for your technical interview
- Order things by how much experience you have with them. first in the list indicates your best technology, and the end of the list indicates you are least familiar with it
## Step 5: Study What They Give You
- Companies may send you a very general 'study guide' for your interview
- Study the hell out of anything that could be on that interview
- Interviews are usually scheduled within 2 weeks of being offered, so you have little time
- Any preparation before this point is vital, this can be easy if you did enough LeetCode and Hackerrank
- Prepare questions for the company by researching their industry, mission statement, company culture, etc., these questions show you have genuine interest in working for them
## Miscellaneous:
- If you think this is easy, it isn't. I've spent my entire college career trying to simplify CS in every way I can. There is no escaping this part of the grind. If there was, I would have found it and shared it
- Don't waste any time, start now
- Modify your resume for different positions
- Make sure to have several languages that you are familiar with and can use to code during a technical interview
- Practice LeetCode and Hackerrank problems in multiple languages
|
Java
|
UTF-8
| 4,060 | 2.421875 | 2 |
[] |
no_license
|
package com.example.zickler.projete4.controleur;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.zickler.projete4.R;
import com.example.zickler.projete4.modele.Praticien;
import com.example.zickler.projete4.modele.Visite;
import com.example.zickler.projete4.modele.VisiteDAO;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPracticien = (Button) findViewById(R.id.buttonPrat);
Button buttonDernieresVisites = (Button) findViewById(R.id.buttonVisites);
Button buttonPratAVis = (Button) findViewById(R.id.buttonAnciennesVisites);
final EditText txtDateDeb = (EditText) findViewById(R.id.dateDeb);
final EditText txtDateFin = (EditText) findViewById(R.id.dateFin);
final EditText txtDateMax = (EditText) findViewById(R.id.dateMax);
View.OnClickListener onClickLister = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonVisites:
Toast.makeText(getApplicationContext(), "ouverture fenêtre dernières visites !", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, ListVisitesBetween.class);
intent.putExtra("dateDebut",txtDateDeb.getText().toString());
intent.putExtra("dateFin",txtDateFin.getText().toString());
startActivity(intent);
break;
case R.id.buttonPrat:
Toast.makeText(getApplicationContext(), "ouverture fenêtre Praticien !", Toast.LENGTH_LONG).show();
Intent intentlArt = new Intent(MainActivity.this, ListPraticiens.class);
startActivity(intentlArt);
break;
case R.id.buttonAnciennesVisites:
Toast.makeText(getApplicationContext(), "ouverture fenêtre Praticien !", Toast.LENGTH_LONG).show();
Intent intentaVis = new Intent(MainActivity.this, ListeVisitesMax.class);
intentaVis.putExtra("dateMax",txtDateMax.getText().toString());
startActivity(intentaVis);
break;
}
}
};
buttonDernieresVisites.setOnClickListener(onClickLister);
buttonPracticien.setOnClickListener(onClickLister);
buttonPratAVis.setOnClickListener(onClickLister);
}
public void testBd() {
// ArrayList<Praticien> listeArticleRecherchetest;
VisiteDAO articleAccestest = new VisiteDAO(this);
//Cr�ation d'un Article
Praticien unArticle = new Praticien("JEAN EUDE","RUE COQUILLe","45000","ORLEANS");
Visite uneVisite = new Visite("1999-06-28","Pas terrible","panique","Louis Armstrong",75,1);
long ret = articleAccestest.addVisite(uneVisite);
Toast.makeText(getApplicationContext(),"test : "+ ret, Toast.LENGTH_LONG).show();
//Pour v�rifier que l'on a bien cr�� un Article dans la BDD
//on extrait l�article de la BDD gr�ce � la d�signation de l'article que l'on a cr�� pr�c�demment
Visite uneVisiteFromBdd = articleAccestest.getVisite(1);
//Si un unArticle est retourn� (donc si le unArticle � bien �t� ajout� � la BDD)
if (uneVisiteFromBdd != null) {
//On affiche les infos de l�Article dans un Toast
Toast.makeText(this, uneVisiteFromBdd.getDATE(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Article non trouvé", Toast.LENGTH_LONG).show();
}
}
}
|
C#
|
UTF-8
| 612 | 3.15625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoveObsoleteSpaces
{
class Program
{
static void Main(string[] args)
{
char[] delim = { ' ' };
string strOriginal = "Jestem jaki jestem i inny nie bede. ";
string strOutput = string.Join(" ", strOriginal.Split(delim, StringSplitOptions.RemoveEmptyEntries));
Console.WriteLine(strOriginal);
Console.WriteLine(strOutput);
Console.ReadKey();
}
}
}
|
C
|
UTF-8
| 683 | 3.71875 | 4 |
[] |
no_license
|
#include <stdio.h>
#include "utils.h"
int main()
{
int count;
char filename[50];
printf("Enter Filename to write to >> ");
scanf("%s", filename);
printf("Enter Number of Lines to write >> ");
scanf("%d", &count);
// extremely weird bug where not doing this skips over the first
// iteration of the loop to scan a new loop
// dispose of the newline character by using a single getchar()
getchar();
printf("Reading lines...\n");
int status = AppendNLines(filename, count);
if (status == 0)
{
printf("%d Lines succesfully written!\n", count);
}
else
{
printf("Error!\n");
}
return 0;
}
|
C#
|
UTF-8
| 72,442 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
namespace Fynydd.Halide
{
/// <summary>
/// The Reader class provides a more powerful, flexible SQL reader class.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// </code>
/// Add the following to your web.config file in order to use the Halide DataReader without specifying a connection string.
/// <code>
/// <![CDATA[
/// <connectionStrings>
/// <add name="Halide"
/// connectionString="Data Source=[server name or address]; Initial Catalog=[database name];
/// User ID=[user name]; password=[password]; Connection Timeout=30;"
/// providerName="System.Data.SqlClient" />
/// </connectionStrings>
/// ]]>
/// </code>
/// </example>
public class DataReader : System.IDisposable
{
#region Variables
private OleDbConnection cn_Oledb;
private OleDbDataReader dr_Oledb;
private OleDbCommand cmd_Oledb;
private string oledb_ConnectionString;
private string oledb_CommandString;
private SqlConnection cn;
private SqlDataReader dr;
private SqlCommand cmd;
private DataTable schemaTable;
private bool schemaAvailable = false;
private Exception _lastSqlError;
private string _connectionStringName = "Halide";
/// <summary>
/// SQL Command String.
/// </summary>
public string sqlCommandString = "";
private string xmlResult = null;
/// <summary>
/// Number of rows that have been read.
/// </summary>
private int _RowsRead = 0;
#endregion
#region Constants
/// <summary>
/// External file connection strings, for use with Excel and Access file connections.
/// Placeholder {FILEPATH} must be replaced with actual file path.
/// Placeholder {PASSWORD} must be replaced with password, if applicable.
/// </summary>
public enum ConnectionStrings
{
/// <summary>
/// XLSX OLEDB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Extended Properties=\"Excel 12.0 Xml;HDR=YES\";")]
XLSX_OLEDB,
/// <summary>
/// XLSX
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";")]
XLSX_All_Text_OLEDB,
/// <summary>
/// XLSB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Extended Properties=\"Excel 12.0;HDR=YES\";")]
XLSB_OLEDB,
/// <summary>
/// XLSM
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Extended Properties=\"Excel 12.0 Macro;HDR=YES\";")]
XLSM_OLEDB,
/// <summary>
/// XLS JET
/// </summary>
[DescriptionAttribute("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={FILEPATH};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";")]
XLS_Jet_OLEDB,
/// <summary>
/// XLS OLEDB
/// </summary>
[DescriptionAttribute("OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source={FILEPATH};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";")]
XLS_OLEDB_Alt,
/// <summary>
/// ACCDB OLEDB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Persist Security Info=False;")]
ACCDB_OLEDB,
/// <summary>
/// ACCDB OLEDB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FILEPATH};Jet OLEDB:Database password={PASSWORD};")]
ACCDB_With_password_OLEDB,
/// <summary>
/// MDB OLEDB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={FILEPATH};User Id=admin;password=;")]
MDB_OLEDB,
/// <summary>
/// MDB OLEDB
/// </summary>
[DescriptionAttribute("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={FILEPATH};Jet OLEDB:Database password={PASSWORD};")]
MDB_With_password_OLEDB
}
#endregion
#region Properties
/// <summary>
/// Returns the # of rows read so far.
/// </summary>
public int RowsRead
{
get
{
return _RowsRead;
}
}
/// <summary>
/// Determine if schema information is available.
/// </summary>
public bool SchemaAvailable
{
get
{
return schemaAvailable;
}
}
/// <summary>
/// Retrieve the last SQL error that occurred.
/// </summary>
/// <returns>Last SQL Exception</returns>
public Exception SqlLastError
{
get
{
return _lastSqlError;
}
set
{
_lastSqlError = value;
}
}
/// <summary>
/// Connection string name within the Web.config file.
/// </summary>
public string connectionStringName
{
get
{
return _connectionStringName;
}
set
{
_connectionStringName = value;
}
}
/// <summary>
/// Connection string loaded via the connectionStringName property.
/// </summary>
public string ConnectionString
{
get
{
string CS = "";
try
{
CS = System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
catch
{
if (String.IsNullOrEmpty(CS))
{
CS = "";
}
}
return CS;
}
}
/// <summary>
/// Returns true if there are rows to return.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.HasRows;
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <value>A boolean representing the availability of rows to read.</value>
public bool HasRows
{
get
{
try
{
if (dr_Oledb != null)
{
return dr_Oledb.HasRows;
}
else
{
return dr.HasRows;
}
}
catch (Exception err)
{
_lastSqlError = err;
return false;
}
}
}
/// <summary>
/// Returns the number of fields in a recordset.
/// </summary>
/// <value>An integer.</value>
public int FieldCount
{
get
{
try
{
if (dr_Oledb != null)
{
return dr_Oledb.FieldCount;
}
else
{
return dr.FieldCount;
}
}
catch (Exception err)
{
_lastSqlError = err;
return 0;
}
}
}
/// <summary>
/// Return the SqlDataReader object.
/// </summary>
public SqlDataReader SqlDataReader
{
get
{
return dr;
}
}
/// <summary>
/// Return the OleDbDataReader object.
/// </summary>
public OleDbDataReader OlwDbDataReader
{
get
{
return dr_Oledb;
}
}
#endregion
#region Constructors / Deconstructors / Disposal
/// <summary>
/// Instantiate the class by passing a SQL command string, where clause, order by clause,
/// rows per page, and page number, to receive only that page's rows. Only compatible with
/// Microsoft SQL Server 2005 and later.
///
/// If you insert [WHERECLAUSE] within your SELECT statement, you can force the passed
/// where clause to be inserted for you; for advanced queries. The same holds true for
/// [ORDERBY]. Remember NOT to include the "WHERE" or "ORDER BY" text in your passed arguments.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test", "ID>5", "LastName ASC, FirstName ASC", 10, 3, "Halide");
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="whereClause">Where clause without the "Where".</param>
/// <param name="orderByClause">Order BY clause without the "order by".</param>
/// <param name="pageNum">Which page full of records to read.</param>
/// <param name="perPage">How many records per page?</param>
/// <param name="useConnectionStringName">Which connection string to use from within the Web.config file?</param>
public DataReader(string commandText, string whereClause, string orderByClause, int perPage, int pageNum, string useConnectionStringName)
{
connectionStringName = useConnectionStringName;
ReadByPage(commandText, whereClause, orderByClause, perPage, pageNum);
}
/// <summary>
/// Instantiate the class by passing a SQL command string, where clause, order by clause,
/// rows per page, and page number, to receive only that page's rows. Only compatible with
/// Microsoft SQL Server 2005 and later. Uses the default "Halide" connection string.
///
/// If you insert [WHERECLAUSE] within your SELECT statement, you can force the passed
/// where clause to be inserted for you; for advanced queries. The same holds true for
/// [ORDERBY]. Remember NOT to include the "WHERE" or "ORDER BY" text in your passed arguments.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test", "ID>5", "LastName ASC, FirstName ASC", 10, 3);
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="whereClause">Where clause without the "Where".</param>
/// <param name="orderByClause">Order BY clause without the "order by".</param>
/// <param name="pageNum">Which page full of records to read.</param>
/// <param name="perPage">How many records per page?</param>
public DataReader(string commandText, string whereClause, string orderByClause, int perPage, int pageNum)
{
ReadByPage(commandText, whereClause, orderByClause, perPage, pageNum);
}
/// <summary>
/// Instantiate the class.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader();
/// </code>
/// </example>
public DataReader()
{
}
/// <summary>
/// Instantiate the class by passing a SQL command string.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
public DataReader(string commandText)
{
sqlCommandString = commandText;
try
{
cn = new SqlConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = commandText;
cmd.CommandTimeout = 0;
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Instantiate the class by passing a SQL command string. Optionally enables getting schema information.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test", true);
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="getSchema">Determines if schema information should also be retured, enabling various other methods and properties.</param>
public DataReader(string commandText, bool getSchema)
{
sqlCommandString = commandText;
try
{
cn = new SqlConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandTimeout = 0;
cmd.CommandText = commandText;
if (getSchema)
{
dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
schemaTable = dr.GetSchemaTable();
dr.Close();
schemaAvailable = true;
}
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Instantiate the class by passing a SQL command string and connection string name.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test", "Halide");
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="connectionName">Name of a connection string within the Web.Config file.</param>
public DataReader(string commandText, string connectionName)
{
sqlCommandString = commandText;
try
{
connectionStringName = connectionName;
cn = new SqlConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandTimeout = 0;
cmd.CommandText = commandText;
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Instantiate the class for connecting to an external data source file.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("SELECT * FROM Sheet", "/uploads/sheet.xls", "", DataReader.ConnectionStrings.XLS_OLEDB);
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="filePath">Path to the file.</param>
/// <param name="password">password for the file, if any, or a blank string.</param>
/// <param name="Connection_String">DataReader.ConnectionString constant which defines the file type.</param>
public DataReader(string commandText, string filePath, string password, ConnectionStrings Connection_String)
{
oledb_CommandString = commandText;
string cs = StringValueOf(Connection_String).Replace("{FILEPATH}", filePath).Replace("{PASSWORD}", password);
oledb_ConnectionString = cs;
try
{
cn_Oledb = new OleDbConnection(cs);
cmd_Oledb = new OleDbCommand(commandText, cn_Oledb);
cmd_Oledb.CommandTimeout = 0;
cn_Oledb.Open();
dr_Oledb = cmd_Oledb.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Instantiate the class by passing a SQL command string, optionally enables getting schema information,
/// pass a connection string name.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test", true, "Halide");
/// </code>
/// </example>
/// <param name="commandText">A SQL command to execute.</param>
/// <param name="getSchema">Determines if schema information should also be retured, enabling various other methods and properties.</param>
/// <param name="connectionName">Name of a connection string within the Web.Config file.</param>
public DataReader(string commandText, bool getSchema, string connectionName)
{
sqlCommandString = commandText;
try
{
connectionStringName = connectionName;
cn = new SqlConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
cmd = new SqlCommand();
cmd.CommandTimeout = 0;
cmd.Connection = cn;
cmd.CommandText = commandText;
if (getSchema)
{
dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
schemaTable = dr.GetSchemaTable();
dr.Close();
schemaAvailable = true;
}
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Closes the Smart Reader object when the class is destroyed.
/// </summary>
~DataReader()
{
Close();
}
/// <summary>
/// Close a previously opened DataReader object. You must close an opened DataReader object when finished using it!
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Close();
/// </code>
/// </example>
/// <returns>Nothing.</returns>
public void Close()
{
try
{
if (cn != null)
{
cn.Dispose();
cmd.Dispose();
}
if (cn_Oledb != null)
{
cn_Oledb.Dispose();
cmd_Oledb.Dispose();
}
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/// <summary>
/// Disposes the SmartReader.
/// </summary>
public void Dispose()
{
Close();
}
#endregion
#region Indexers
/// <summary>
/// Shorthand for the GetString method. Returns a record as a string by name.
/// </summary>
/// <value>
/// Record value as a string.
/// </value>
public string this[string columnName]
{
get
{
return GetString(columnName);
}
}
/// <summary>
/// Shorthand for the GetString method. Returns a record as a string by column number.
/// </summary>
/// <value>
/// Record value as a string.
/// </value>
public string this[int columnIndex]
{
get
{
return GetString(columnIndex);
}
}
#endregion
#region Utility / Schema Methods
private static string StringValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
private static Object EnumValueOf(string value, Type enumType)
{
String[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (StringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
{
return Enum.Parse(enumType, name);
}
}
throw new ArgumentException("The string is not a description or value of the specified enum.");
}
/// <summary>
/// Used by the constructor to read in a page of results.
/// </summary>
private void ReadByPage(string commandText, string WhereClause, string OrderByClause, int PerPage, int PageNum)
{
string template = "WITH VIRTUAL_HALIDE_ROWSET AS (SELECT ROW_NUMBER() OVER( ORDER BY [ORDERBY] ) AS ROWNUMBER, * FROM ([SELECT]) AS ML_HALIDE WHERE [WHERECLAUSE]) SELECT * FROM VIRTUAL_HALIDE_ROWSET WHERE ROWNUMBER BETWEEN CONVERT(varchar, [BEGINRECORD]) and CONVERT(varchar, [ENDRECORD]);";
if (PerPage > 0 && PageNum > 0)
{
template = template.Replace("[ORDERBY]", OrderByClause);
template = template.Replace("[SELECT]", commandText);
template = template.Replace("[WHERECLAUSE]", WhereClause);
int beginRecord = (PerPage * PageNum) - PerPage + 1;
int endRecord = (PerPage * PageNum);
template = template.Replace("[BEGINRECORD]", beginRecord.ToString());
template = template.Replace("[ENDRECORD]", endRecord.ToString());
sqlCommandString = template;
try
{
cn = new SqlConnection();
cn.ConnectionString = ConnectionString;
cn.Open();
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandTimeout = 0;
cmd.CommandText = template;
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
}
/// <summary>
/// Read the first (or next) row in the query.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// while (reader.Read())
/// {
/// ...
/// }
/// reader.Close();
/// </code>
/// </example>
/// <returns>true if read, false if end of data.</returns>
public bool Read()
{
bool output = false;
try
{
if (dr_Oledb != null)
{
output = dr_Oledb.Read();
}
else
{
output = dr.Read();
}
if (output)
{
_RowsRead++;
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Switch to the next result set; for use with SQL statements that return multiple (compound) recordsets.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.NextResult();
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <returns>true if result set is switched, false if not.</returns>
public bool NextResult()
{
try
{
if (dr_Oledb != null)
{
return dr_Oledb.NextResult();
}
else
{
return dr.NextResult();
}
}
catch (Exception err)
{
_lastSqlError = err;
return false;
}
}
/// <summary>
/// Retrieve the columns and their schema information as an ASCII text string for output.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// Response.Write (reader.ListSchema().Replace("\r\n", "<br />"));
/// ...
/// reader.Close();
/// ]]>
/// </code>
/// </example>
/// <returns>A string</returns>
public string ListSchema()
{
string output = "Schema information is not available. Instantiate the Smartreader with a true value to use schema-based features.";
if (schemaAvailable)
{
output = "";
try
{
foreach (System.Data.DataRow myField in schemaTable.Rows)
{
//For each property of the field...
foreach (System.Data.DataColumn myProperty in schemaTable.Columns)
{
//Display the field name and value.
output += myProperty.ColumnName + " = " + myField[myProperty].ToString() + "\r\n";
}
output += "\r\n";
}
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Get the primary key column name, or an empty string if schema is not available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetPrimarykeyName();
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <returns>A string with the column name of the primary key.</returns>
public string GetPrimarykeyName()
{
if (schemaAvailable)
{
try
{
// Find by iteration
foreach (System.Data.DataRow myField in schemaTable.Rows)
{
foreach (System.Data.DataColumn myProperty in schemaTable.Columns)
{
if (myProperty.ColumnName.ToLower() == "iskey")
{
return myField["columnName"].ToString();
}
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return "";
}
/// <summary>
/// Get the size (dimension) of the column, or zero if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// int result = reader.GetColumnSize("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>An integer.</returns>
public int GetColumnSize(string columnName)
{
int output = 0;
if (schemaAvailable)
{
try
{
System.Data.DataColumn[] myPrimaryKey = new System.Data.DataColumn[1];
myPrimaryKey[0] = schemaTable.Columns["columnName"];
schemaTable.PrimaryKey = myPrimaryKey;
System.Data.DataRow myDataRow = schemaTable.Rows.Find(columnName);
output = (int)myDataRow["ColumnSize"];
}
catch (Exception err)
{
_lastSqlError = err;
}
}
/*
// Find by iteration
foreach (DataRow myField in schemaTable.Rows)
{
if (myField["columnName"].ToString().ToLower() == columnName.ToLower())
{
//For each property of the field...
foreach (DataColumn myProperty in schemaTable.Columns)
{
if (myProperty.ColumnName.ToLower() == "columnsize")
{
return (int)myField[myProperty];
}
}
}
}
*/
return output;
}
/// <summary>
/// Is the specified column a primary key? Returns false if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.GetColumnIsKey("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>true or false.</returns>
public bool GetColumnIsKey(string columnName)
{
bool output = false;
if (schemaAvailable)
{
try
{
if (GetPrimarykeyName().ToLower() == columnName.ToLower())
{
output = true;
}
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Does a specified column allow nulls? Returns false if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.GetColumnAllowNulls("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>true or false.</returns>
public bool GetColumnAllowNulls(string columnName)
{
bool output = false;
if (schemaAvailable)
{
try
{
System.Data.DataColumn[] myPrimaryKey = new System.Data.DataColumn[1];
myPrimaryKey[0] = schemaTable.Columns["columnName"];
schemaTable.PrimaryKey = myPrimaryKey;
System.Data.DataRow myDataRow = schemaTable.Rows.Find(columnName);
output = (bool)myDataRow["AllowDBNull"];
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Is a specified column an identity? Returns false if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.GetColumnIsIdentity("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>true or false.</returns>
public bool GetColumnIsIdentity(string columnName)
{
bool output = false;
if (schemaAvailable)
{
try
{
System.Data.DataColumn[] myPrimaryKey = new System.Data.DataColumn[1];
myPrimaryKey[0] = schemaTable.Columns["columnName"];
schemaTable.PrimaryKey = myPrimaryKey;
System.Data.DataRow myDataRow = schemaTable.Rows.Find(columnName);
output = (bool)myDataRow["IsIdentity"];
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Is a specified column an auto-incrementing field? Returns false if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.GetColumnIsAutoIncrement("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>true or false.</returns>
public bool GetColumnIsAutoIncrement(string columnName)
{
bool output = false;
if (schemaAvailable)
{
try
{
System.Data.DataColumn[] myPrimaryKey = new System.Data.DataColumn[1];
myPrimaryKey[0] = schemaTable.Columns["columnName"];
schemaTable.PrimaryKey = myPrimaryKey;
System.Data.DataRow myDataRow = schemaTable.Rows.Find(columnName);
output = (bool)myDataRow["IsAutoIncrement"];
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Return a column's equivalent system data type name (e.g. "String", "Int64", et al.).
/// Returns an empty string if no schema information is available.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetColumnSystemDataType("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>Data type name as a string.</returns>
public string GetColumnSystemDataType(string columnName)
{
string output = "";
if (schemaAvailable)
{
try
{
System.Data.DataColumn[] myPrimaryKey = new System.Data.DataColumn[1];
myPrimaryKey[0] = schemaTable.Columns["columnName"];
schemaTable.PrimaryKey = myPrimaryKey;
System.Data.DataRow myDataRow = schemaTable.Rows.Find(columnName);
output = myDataRow["DataType"].ToString();
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
/// <summary>
/// Retrieve the SQL data type name of a specified column (e.g. "varchar", "int", "smallint", et al.).
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetDataTypeName(0);
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnIndex">Number of the column.</param>
/// <returns>A string.</returns>
public string GetDataTypeName(int columnIndex)
{
string output = string.Empty;
try
{
output = dr.GetDataTypeName(columnIndex);
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Retrieve the SQL data type name of a specified column (e.g. "varchar", "int", "smallint", et al.).
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetDataTypeName("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of the column.</param>
/// <returns>A string.</returns>
public string GetDataTypeName(string columnName)
{
try
{
return GetDataTypeName(dr.GetOrdinal(columnName));
}
catch (Exception err)
{
_lastSqlError = err;
return "";
}
}
/// <summary>
/// Get a column name by its number.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.ColumnName(0);
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnNumber">Number of column to retrieve.</param>
/// <returns>A string.</returns>
public string ColumnName(int columnNumber)
{
try
{
if (dr_Oledb != null)
{
return dr_Oledb.GetName(columnNumber);
}
else
{
return dr.GetName(columnNumber);
}
}
catch (Exception err)
{
_lastSqlError = err;
return "";
}
}
/// <summary>
/// Is a specified column value empty or null?
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.IsNullOrEmpty("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to evaluate.</param>
/// <returns>true if column value is null or empty, false if not.</returns>
public bool IsNullOrEmpty(string columnName)
{
try
{
if (dr_Oledb != null)
{
return String.IsNullOrEmpty(GetString(dr_Oledb.GetOrdinal(columnName)));
}
else
{
return String.IsNullOrEmpty(GetString(dr.GetOrdinal(columnName)));
}
}
catch (Exception err)
{
_lastSqlError = err;
return false;
}
}
#endregion
#region Column Value / Data Return Methods
/// <summary>
/// Create a dynamic DataTable object from a SQL data statement.
/// One use for this method is to create a data source for other
/// controls that want a DataTable, like 3rd party controls.
/// </summary>
/// <returns>DataTable object</returns>
public DataTable ReadTable()
{
return ReadTable(false);
}
/// <summary>
/// Create a dynamic DataTable object from a SQL data statement.
/// One use for this method is to create a data source for other
/// controls that want a DataTable, like 3rd party controls.
/// </summary>
/// <param name="addBlank">Determine whether to add a blank row to the end or not.</param>
/// <returns>DataTable object</returns>
public DataTable ReadTable(bool addBlank)
{
DataTable outp = new DataTable();
DateTime start = DateTime.Now;
try
{
if (dr_Oledb != null)
{
using (OleDbConnection con = new OleDbConnection(oledb_ConnectionString))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(oledb_CommandString, con))
{
con.Open();
da.Fill(outp);
}
}
if (addBlank)
{
DataRow drow = outp.NewRow();
outp.Rows.InsertAt(drow, 0);
}
}
else
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlCommandString, con))
{
con.Open();
da.Fill(outp);
}
}
if (addBlank)
{
DataRow drow = outp.NewRow();
outp.Rows.InsertAt(drow, 0);
}
}
}
catch { }
return (outp);
}
/// <summary>
/// Read a column value in as a DateTime object.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// DateTime reader.GetDateTime("thedate");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>DateTime object.</returns>
public DateTime GetDateTime(string columnName)
{
DateTime output = new DateTime(1900, 1, 1);
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
try
{
if (dr_Oledb != null)
{
output = dr_Oledb.GetDateTime(ord);
}
else
{
output = dr.GetDateTime(ord);
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a nullable DateTime object.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// DateTime? dt = reader.GetDateTimeNullable("thedate");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>DateTime object.</returns>
public DateTime? GetDateTimeNullable(string columnName)
{
DateTime? output = null;
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
try
{
if (dr_Oledb != null)
{
output = dr_Oledb.GetDateTime(ord);
}
else
{
output = dr.GetDateTime(ord);
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a string formatted as a date.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetDate("thedate");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve</param>
/// <returns>A string with the column value as a date.</returns>
public string GetDate(string columnName)
{
string output = string.Empty;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = "";
}
else
{
output = dr_Oledb.GetDateTime(ord).ToString("M/d/yyyy");
}
}
else
{
if (dr.IsDBNull(ord))
{
output = "";
}
else
{
output = dr.GetDateTime(ord).ToString("M/d/yyyy");
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a string formatted as a time.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetTime("thedate");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A string with the column value as a time.</returns>
public string GetTime(string columnName)
{
string output = string.Empty;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = "";
}
else
{
output = dr_Oledb.GetDateTime(ord).ToString("h:mm tt");
}
}
else
{
if (dr.IsDBNull(ord))
{
output = "";
}
else
{
output = dr.GetDateTime(ord).ToString("h:mm tt");
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a string formatted as money.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetMoney("cost");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A string with the column formatted as currency.</returns>
public string GetMoney(string columnName)
{
string output = string.Empty;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = "";
}
else
{
output = dr_Oledb.GetDouble(ord).ToString("0.00");
}
}
else
{
if (dr.IsDBNull(ord))
{
output = "";
}
else
{
output = dr.GetSqlMoney(ord).ToDouble().ToString("0.00");
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as an integer.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// int result = reader.GetInt("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>An integer.</returns>
public int GetInt(string columnName)
{
int output = 0;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToInt32(dr_Oledb[ord].ToString());
}
}
else
{
if (dr.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToInt32(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a nullable int.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// int? result = reader.GetInt32Nullable("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A nullable int</returns>
public int? GetInt32Nullable(string columnName)
{
int? output = null;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (!dr_Oledb.IsDBNull(ord))
{
output = Convert.ToInt32(dr_Oledb[ord].ToString());
}
}
else
{
if (!dr.IsDBNull(ord))
{
output = Convert.ToInt32(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as an int.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// int result = reader.GetInt32("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>An int.</returns>
public int GetInt32(string columnName)
{
return GetInt(columnName);
}
/// <summary>
/// Read a column value in as a nullable Int64.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// Int64? result = reader.GetInt64Nullable("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A nullable Int64.</returns>
public Int64? GetInt64Nullable(string columnName)
{
Int64? output = null;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (!dr_Oledb.IsDBNull(ord))
{
output = Convert.ToInt64(dr_Oledb[ord].ToString());
}
}
else
{
if (!dr.IsDBNull(ord))
{
output = Convert.ToInt64(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a long.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// long result = reader.GetLong("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A long.</returns>
public long GetLong(string columnName)
{
long output = 0;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToInt64(dr_Oledb[ord].ToString());
}
}
else
{
if (dr.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToInt64(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as an Int64.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// long result = reader.GetInt64("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>An Int64.</returns>
public Int64 GetInt64(string columnName)
{
return GetLong(columnName);
}
/// <summary>
/// Read a column value in as a double.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// double result = reader.GetDouble("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A double.</returns>
public double GetDouble(string columnName)
{
double output = 0;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToDouble(dr_Oledb[ord].ToString());
}
}
else
{
if (dr.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToDouble(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a decimal.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// decimal result = reader.GetDecimal("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A decimal.</returns>
public decimal GetDecimal(string columnName)
{
decimal output = 0;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToDecimal(dr_Oledb[ord].ToString());
}
}
else
{
if (dr.IsDBNull(ord))
{
output = 0;
}
else
{
output = Convert.ToDecimal(dr[ord].ToString());
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a float.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// float result = reader.GetFloat("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A float.</returns>
public float GetFloat(string columnName)
{
float output = 0;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = 0;
}
else
{
output = dr_Oledb.GetFloat(ord);
}
}
else
{
if (dr.IsDBNull(ord))
{
output = 0;
}
else
{
output = dr.GetFloat(ord);
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read an XML result from a stored procedure.
/// Used to bypass the 2,033 byte limit (multiple row) segmentation of XML results
/// when simply requesting the column as a string.
/// Reads in column 0 of all rows in the result set and appends them.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("EXEC prGetXML @email='me@example.com'");
/// reader.Read();
/// string XMLresult = reader.GetXMLResult();
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <returns>A string with the XML result.</returns>
public string GetXMLResult()
{
if (xmlResult == null)
{
try
{
if (!dr.IsDBNull(0))
{
if (this.HasRows)
{
StringBuilder output = new StringBuilder("");
if (this.RowsRead > 0)
{
output.Append(this.GetString(0));
}
while (this.Read())
{
output.Append(this.GetString(0));
}
xmlResult = output.ToString();
}
}
else
{
xmlResult = "";
}
}
catch (Exception err)
{
_lastSqlError = err;
xmlResult = "";
}
}
return xmlResult;
}
/// <summary>
/// Read a column value in as a string, by its column number.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetString(0);
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnIndex">Number of column to retrieve.</param>
/// <returns>A string.</returns>
public string GetString(int columnIndex)
{
string output = string.Empty;
try
{
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(columnIndex))
{
output = "";
}
else
{
output = dr_Oledb[columnIndex].ToString();
}
}
else
{
if (dr.IsDBNull(columnIndex))
{
output = "";
}
else
{
output = dr[columnIndex].ToString();
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in as a string by its column name. Can return nulls.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetStringNullable("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A string value or null.</returns>
public string GetStringNullable(string columnName)
{
try
{
string x = null;
if (dr_Oledb != null)
{
if (!dr_Oledb.IsDBNull(dr_Oledb.GetOrdinal(columnName)))
{
x = dr_Oledb[dr_Oledb.GetOrdinal(columnName)].ToString();
}
}
else
{
if (!dr.IsDBNull(dr.GetOrdinal(columnName)))
{
x = dr[dr.GetOrdinal(columnName)].ToString();
}
}
return x;
}
catch (Exception err)
{
_lastSqlError = err;
return null;
}
}
/// <summary>
/// Read a column value in as a string, by its column name.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetString("ID", "none");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <param name="defaultValue">Default value to return if string is null or empty.</param>
/// <returns>A string.</returns>
public string GetString(string columnName, string defaultValue)
{
try
{
string x = "";
if (dr_Oledb != null)
{
x = GetString(dr_Oledb.GetOrdinal(columnName));
if (String.IsNullOrEmpty(x))
{
x = defaultValue;
}
}
else
{
x = GetString(dr.GetOrdinal(columnName));
if (String.IsNullOrEmpty(x))
{
x = defaultValue;
}
}
return x;
}
catch (Exception err)
{
_lastSqlError = err;
return "";
}
}
/// <summary>
/// Read a column value in as a string, by its column name.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetString("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A string.</returns>
public string GetString(string columnName)
{
return GetString(columnName, "");
}
/// <summary>
/// Read a column value in as a boolean, by its column name.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// bool result = reader.GetBoolean("ID");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A boolean.</returns>
public bool GetBoolean(string columnName)
{
bool output = false;
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = false;
}
else
{
output = dr_Oledb.GetBoolean(ord);
}
}
else
{
if (dr.IsDBNull(ord))
{
output = false;
}
else
{
output = dr.GetBoolean(ord);
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Read a column value in and process as "Yes", "No", or "n/a" using the GetBoolean method.
/// </summary>
/// <example>
/// <code>
/// DataReader reader = new DataReader("select * from test");
/// reader.Read();
/// string result = reader.GetYesNo("choice");
/// ...
/// reader.Close();
/// </code>
/// </example>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A string.</returns>
public string GetYesNo(string columnName)
{
string output = "n/a";
try
{
int ord = (dr_Oledb != null ? dr_Oledb.GetOrdinal(columnName) : dr.GetOrdinal(columnName));
if (dr_Oledb != null)
{
if (dr_Oledb.IsDBNull(ord))
{
output = "n/a";
}
else if (dr_Oledb.GetBoolean(ord))
{
output = "Yes";
}
else
{
output = "No";
}
}
else
{
if (dr.IsDBNull(ord))
{
output = "n/a";
}
else if (dr.GetBoolean(ord))
{
output = "Yes";
}
else
{
output = "No";
}
}
}
catch (Exception err)
{
_lastSqlError = err;
}
return output;
}
/// <summary>
/// Gets a numeric field that represents minutes (ie 125)
/// and converts it to an hour format (ie 2:05)
/// </summary>
/// <param name="columnName">Name of column to retrieve.</param>
/// <returns>A formatted string.</returns>
public string GetStringOfMinutes(string columnName)
{
string output = "";
string d;
if (dr_Oledb != null)
{
d = GetString(dr_Oledb.GetOrdinal(columnName));
}
else
{
d = GetString(dr.GetOrdinal(columnName));
}
if (!String.IsNullOrEmpty(d))
{
try
{
Double x = Convert.ToDouble(d);
output = Math.Floor(x / 60).ToString() + ":";
x -= Math.Floor(x / 60) * 60;
output += x.ToString().PadLeft(2, '0');
}
catch (Exception err)
{
_lastSqlError = err;
}
}
return output;
}
#endregion
}
}
|
Java
|
UTF-8
| 2,069 | 2.25 | 2 |
[] |
no_license
|
package cn.com.bbut.iy.itemmaster.service.base;
import cn.com.bbut.iy.itemmaster.constant.ConstantsCache;
import cn.com.bbut.iy.itemmaster.dto.base.GridDataDTO;
import cn.com.bbut.iy.itemmaster.dto.base.MenuDTO;
import cn.com.bbut.iy.itemmaster.dto.base.MenuParamDTO;
import cn.com.bbut.iy.itemmaster.dto.base.role.MenuPermDTO;
import cn.com.bbut.iy.itemmaster.entity.base.Menu;
import org.springframework.cache.annotation.Cacheable;
import java.util.Collection;
/**
* 菜单相关功能
*
* @author shiy
*/
public interface MenuService {
/**
* 取得指定用户可见菜单(全部菜单体系)
*
* <p>
* 0. 取得用户id对应的所有角色<br/>
* 1. 取得所有角色对应的初级菜单(不重复)<br/>
* 2. 取得各初级菜单对应的子菜单<br/>
* 3. 拼接返回<br/>
* </p>
*
* @param userId
* 用户名
* @return 菜单集合或null
*/
Collection<MenuDTO> getMenus(String userId);
/**
* 取得指定角色用户可见菜单(全部菜单体系)
*
* <p>
* 1. 取得所有角色对应的初级菜单(不重复)<br/>
* 2. 取得各初级菜单对应的子菜单<br/>
* 3. 拼接返回<br/>
* </p>
*
* @param roleIds
* 角色id集合
*
* @return 菜单集合或null
*/
Collection<MenuDTO> getMenus(Collection<Integer> roleIds);
/**
* 获取指定菜单信息
*
* @param id
* menuid
* @return 菜单对象或null
*/
//@Cacheable(ConstantsCache.CACHE_MENU)
Menu getMenu(int id);
/**
* 取得所有菜单集合(角色模块专用)
*
* @return
*/
Collection<Menu> getAllMenus();
/**
* 取得所有菜单集合(角色模块专用)
*
* @param orderByCause
* 排序
*
* @return
*/
Collection<Menu> getAllMenus(String orderByCause);
/**
* 得到检索数据
*
* @param param
* @return
*/
GridDataDTO<Menu> getData(MenuParamDTO param);
}
|
Ruby
|
UTF-8
| 1,403 | 2.78125 | 3 |
[] |
no_license
|
require 'van'
describe Van do
describe 'initialization' do
it 'has a default capacity' do
van = Van.new
expect(van.capacity).to eq Van::DEFAULT_CAPACITY
end
it 'can be created with any capacity' do
van = Van.new(5)
expect(van.capacity).to eq 5
end
end
describe '#collect_broken_bike' do
let(:bike) { Bike.new }
let(:broken_bike) { double :bike, broken?: true }
let(:docking_station) { DockingStation.new }
it 'collects broken bikes' do
docking_station.dock(broken_bike)
subject.collect_broken_bike(broken_bike, docking_station)
expect(subject.bikes.length).to eq 1
end
it 'raised an error if there are no bikes bikes' do
expect { subject.collect_broken_bike(broken_bike, docking_station) }.to raise_error('no bikes available')
end
it 'raises an error if the bike is working' do
allow(bike).to receive(:broken?).and_return(false)
expect { subject.collect_broken_bike(bike, docking_station) }.to raise_error('bike is working')
end
it 'raises an error if full' do
subject.capacity.times { docking_station.dock(broken_bike) }
subject.capacity.times { subject.collect_broken_bike(broken_bike, docking_station) }
docking_station.dock(broken_bike)
expect { subject.collect_broken_bike(broken_bike, docking_station) }.to raise_error('van full')
end
end
end
|
Shell
|
UTF-8
| 890 | 2.90625 | 3 |
[] |
no_license
|
#!/bin/bash
[[ -z "${SPARK_ACTION}" ]] && { echo "SPARK_ACTION required"; exit 1; }
# ACTIONS start-zk, start-kafka, create-topic,
echo "Running action ${SPARK_ACTION}"
case ${SPARK_ACTION} in
"spark-submit-python")
./bin/spark-submit --packages $2 /opt/tap/$1
;;
"showdown")
# ./bin/spark-submit --packages $2 /opt/tap/$1
./bin/spark-submit --packages "org.apache.spark:spark-streaming-kafka-0-8_2.11:2.4.5,org.elasticsearch:elasticsearch-hadoop:7.7.0" /opt/tap/showdown_es.py
;;
"dataframe")
# ./bin/spark-submit --packages $2 /opt/tap/$1
./bin/spark-submit --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.4.5 /opt/tap/dataframe.py
;;
"training")
# ./bin/spark-submit --packages $2 /opt/tap/$1
./bin/spark-submit --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.4.5 /opt/tap/training.py
;;
"bash")
while true
do
echo "Keep Alive"
sleep 10
done
;;
esac
|
Python
|
UTF-8
| 1,536 | 3.328125 | 3 |
[] |
no_license
|
# --- Day 3: ####### ---
#
# Part 1: Count trees hit down path through tiled hillside
# Part 2: Count trees hit down multiple paths
#
import sys
sys.path.append("..")
from AoCCommon.InputToArray import InputToArray
a = InputToArray()
mydata = a.array
testinput =\
"""
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#"""
treerows = testinput.split('\n')
treerows = [x for x in treerows if x]
treecoords = []
def part1():
for i,row in enumerate(mydata):
for j in range(len(row)):
if row[j] == "#":
treecoords.append((i,j))
mylocation = [0,0]
print(treecoords)
width = len(mydata[0])
hits = 0
for i in range(len(mydata)):
mylocation[0] += 1
mylocation[1] += 3
if (mylocation[0], mylocation[1]%width) in treecoords:
hits += 1
print(hits)
def part2():
for i, row in enumerate(mydata):
for j in range(len(row)):
if row[j] == "#":
treecoords.append((i, j))
width = len(mydata[0])
paths = [[1,1],[1,3],[1,5],[1,7],[2,1]]
hits = [0 for x in paths]
for i,path in enumerate(paths):
mylocation = [0, 0]
while mylocation[0] < len(mydata):
mylocation[0] += path[0]
mylocation[1] += path[1]
if (mylocation[0], mylocation[1] % width) in treecoords:
hits[i] += 1
print(hits[0]*hits[1]*hits[2]*hits[3]*hits[4])
part2()
|
PHP
|
UTF-8
| 6,557 | 2.515625 | 3 |
[] |
no_license
|
<?php
class AdminBuildingController extends \BaseController {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$data['customers'] = Customer::orderBy('name')->get();
$data['buildings'] = Building::all();
return View::make('admin.building.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
$data['thisBldg'] = new Building();
$data['customers'] = Customer::orderBy('name')->get();
$customer_list = [''=>'Choose a Customer Account'];
foreach($data['customers'] as $customer) {
$customer_list[$customer->id] = $customer->name;
}
$data['customer_list'] = $customer_list;
return View::make('admin.building.create', $data);
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$building = new Building();
foreach(Input::except('_token', '_method') as $key => $value) {
$building->$key = $value;
}
if($building->save()) {
SystemLog::info(0, 'New building #'.$building->id.'('.$building->name.') was created by user #'.Auth::user()->id.'('.Auth::user()->email.')', 23);
Session::flash('message',"$building->name was successfully created");
Session::flash('alert-class', 'alert-success alert-dismissable');
}else{
SystemLog::error(0, 'Failed to create new building '.$building->name.' as attempted by user #'.Auth::user()->id.'('.Auth::user()->email.')', 24);
Session::flash('message', "There was an error creating $building->name");
Session::flash('alert-class', 'alert-danger alert-dismissable');
}
return Redirect::route('admin.building.index');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$data['thisBldg'] = Building::find($id);
$data['customers'] = Customer::orderBy('name')->get();
$customer_list = [''=>'Choose a Customer Account'];
foreach($data['customers'] as $customer) {
$customer_list[$customer->id] = $customer->name;
}
$data['customer_list'] = $customer_list;
return View::make('admin.building.edit', $data);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
$building = Building::find($id);
foreach(Input::except('_token', '_method') as $key => $value) {
$building->$key = $value;
}
if($building->save()) {
SystemLog::info(0, 'Updated building #'.$building->id.'('.$building->name.') was created by user #'.Auth::user()->id.'('.Auth::user()->email.')', 23);
Session::flash('message', "$building->name was successfully updated");
Session::flash('alert-class', 'alert-success alert-dismissable');
}else{
SystemLog::error(0, 'Failed to update building #'.$building->id.'('.$building->name.') as attempted by user #'.Auth::user()->id.'('.Auth::user()->email.')', 24);
Session::flash('message', "There was an error updating $building->name");
Session::flash('alert-class', 'alert-danger alert-dismissable');
}
return Redirect::route('admin.building.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
$building = Building::find($id);
$systems = System::where('building_id', $building->id)->get();
/* Clean up the building's systems */
foreach($systems as $system) {
/* Retire all devices */
try{
Device::where('system_id', $system->id)->update(['retired' => 1]);
SystemLog::info($system->id, 'Retired all devices for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 25);
}catch(Exception $e) {
SystemLog::error($system->id, 'Failed to retire all devices for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 26);
}
/* Revoke user access */
try{
BuildingManager::where('building_id', $building->id)->delete();
BuildingGroupMember::where('building_id', $building->id)->delete();
SystemLog::info($system->id, 'Revoked all user access for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 33);
}catch(Exception $e) {
SystemLog::error($system->id, 'Failed to revoked all user access for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 34);
}
/* Remove email subscriptions*/
try{
Alert::where('building_id', $building->id)->delete();
SystemLog::info($system->id, 'Removed email subscriptions for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 15);
}catch(Exception $e) {
SystemLog::error($system->id, 'Failed to remove email subscriptions for system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 16);
}
/* Delete the system */
if( $system->delete() ) {
SystemLog::info($system->id, 'Deleted system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 25);
}else{
SystemLog::error($system->id, 'Failed to delete system #'.$system->id.'('.$system->name.') along with deletion of building #'.$building->id.'('.$building->name.')', 26);
}
}
if($building->delete()) {
SystemLog::info(0, 'Building #'.$building->id.'('.$building->name.') was deleted by user #'.Auth::user()->id.'('.Auth::user()->email.')', 23);
Session::flash('message', "The $building->name building was successfully removed");
Session::flash('alert-class', 'alert-success alert-dismissable');
}else{
SystemLog::error(0, 'Failed to update building #'.$building->id.'('.$building->name.') as attempted by user #'.Auth::user()->id.'('.Auth::user()->email.')', 24);
Session::flash('message', "There was a problem removing the $building->name building. You may need to try again.");
Session::flash('alert-class', 'alert-danger alert-dismissable');
}
return Redirect::route('admin.building.index');
}
}
|
Python
|
UTF-8
| 5,139 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import cv2
import json
import logging
import numpy as np
import os
import sys
def get_name():
return "object_detection"
def get_short_description():
return "Dectect objects using Yolo model"
def get_description():
return """Retrieves objects on images.
It will return a frame by frame analysis.
The process is base on OpenCV with Yolo model.
"""
def get_version():
return "0.0.1"
def get_parameters():
return [
{
"identifier": "source_path",
"label": "Source path",
"kind": ["string"],
"required": True,
},
{
"identifier": "destination_path",
"label": "Destination path",
"kind": ["string"],
"required": True,
},
{
"identifier": "confidence",
"label": "Confidence level of matching detected objects",
"kind": ["integer"],
"required": False,
},
{
"identifier": "requirements",
"label": "Requirements",
"kind": ["requirements"],
"required": False,
}
]
def init():
global knowledgeNetwork, layerNames, yoloLabels
logLevel = os.environ.get('RUST_LOG', 'warning').upper()
timestamp = "%(asctime)s.%(msecs)03d000000 UTC"
logFormat = "%s - - {job_queue:s} - - %(levelname)s - %(message)s".format(
timestamp,
job_queue=os.getenv("AMQP_QUEUE", default="unknown_queue")
)
logging.basicConfig(stream=sys.stdout,
level=logLevel,
format=logFormat,
datefmt="%Y-%m-%d %H:%M:%S"
)
labelsPath = "/sources/models/coco.names"
configPath = "/sources/models/yolov3.cfg"
weightsPath = "/sources/models/yolov3.weights"
yoloLabels = open(labelsPath).read().strip().split("\n")
# load our YOLO object detector trained on COCO dataset (80 classes)
# and determine only the *output* layer names that we need from YOLO
knowledgeNetwork = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
layerNames = knowledgeNetwork.getLayerNames()
layerNames = [
layerNames[i[0] - 1]
for i in knowledgeNetwork.getUnconnectedOutLayers()
]
def init_process(stream_handler, format_context, parameters):
global confidence
video_filters = [
{
"name": "format",
"label": "format_filter",
"parameters": {
"pix_fmts": "rgb24"
}
}
]
video_stream = stream_handler.new_video_stream(0, video_filters)
confidence = parameters["confidence"] / 100
# returns a list of description of the streams to be processed
return [
video_stream
]
def process_frame(job_id, stream_index, frame):
global confidence, knowledgeNetwork, layerNames, yoloLabels
img_np = np.fromstring(frame.data[0], dtype=np.uint8)
img_np = img_np.reshape((3, frame.width, frame.height), order='F')
img_np = np.swapaxes(img_np, 0, 2)
blob = cv2.dnn.blobFromImage(
img_np,
1 / 255.0, (512, 512),
swapRB=False,
crop=False
)
knowledgeNetwork.setInput(blob)
layerOutputs = knowledgeNetwork.forward(layerNames)
detectedObjects = []
# loop over each of the layer outputs
for layerOutput in layerOutputs:
# loop over each of the detections
for detection in layerOutput:
# extract the class ID and confidence (i.e., probability) of
# the current object detection
scores = detection[5:]
classID = np.argmax(scores)
objectConfidence = scores[classID]
# filter out weak predictions by ensuring the detected
# probability is greater than the minimum probability
if objectConfidence > confidence:
# scale the bounding box coordinates back relative to the
# size of the image, keeping in mind that YOLO actually
# returns the center (x, y)-coordinates of the bounding
# box followed by the boxes' width and height
box = detection[0:4] * np.array([
frame.width,
frame.height,
frame.width,
frame.height
])
(centerX, centerY, width, height) = box.astype("int")
# use the center (x, y)-coordinates to derive the top and
# and left corner of the bounding box
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
detectedObjects.append({
'label': yoloLabels[classID],
'confidence': float(objectConfidence),
'boxe': [x, y, int(width), int(height)]
})
return detectedObjects
def ending_process():
'''
Function called at the end of the media process
(the "media" feature must be activated).
'''
logging.info("Ending Python worker process...")
|
Java
|
UTF-8
| 277 | 1.78125 | 2 |
[] |
no_license
|
package com.MQ.www;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Basic {
public static void main(String[] args) {
WebDriver driver=new ChromeDriver();
driver.get("https://www.flipkart.com");
}
}
|
Markdown
|
UTF-8
| 647 | 2.921875 | 3 |
[] |
no_license
|
# Jopus
Simple, fast, and efficient wrapper for libopusfile which allows you easily read `.ogg` files from Python.
# Installation
## Requirements
### Ubuntu
`apt-get install libogg-dev libopus-dev libopusfile-dev`
### MacOS
`brew install opus opusfile libogg`
When requirements have been installed:
1. `git clone https://github.com/yutkin/jopus.git`
2. `cd jopus`
4. `pip install -r requirements.txt`
3. `pip install .`
# Usage example
```python
import jopus
# open file on file system
opus_file = jopus.open_file("/path_to_file.ogg")
# open file by URL
opus_file = jopus.open_url("https://hostname.com/opus_audio.ogg")
print(opus_file)
```
|
Java
|
UTF-8
| 2,287 | 3.765625 | 4 |
[] |
no_license
|
import java.util.Comparator;
/**
* TODO: Complete the implementation of this class.
*
* A HuffmanTree represents a variable-length code such that the shorter the
* bit pattern associated with a character, the more frequently that character
* appears in the text to be encoded.
*/
public class HuffmanTree {
class Node {
protected char key;
protected int priority;
protected Node left, right;
public Node(int priority, char key) {
this(priority, key, null, null);
}
public Node(int priority, Node left, Node right) {
this(priority, '\0', left, right);
}
public Node(int priority, char key, Node left, Node right) {
this.key = key;
this.priority = priority;
this.left = left;
this.right = right;
}
public boolean isLeaf() {
return left == null && right == null;
}
public String toString() {
return String.format("%s:%f", key, priority);
}
}
protected Node root;
/**
* TODO
*
* Creates a HuffmanTree from the given frequencies of letters in the
* alphabet using the algorithm described in lecture.
*/
public HuffmanTree(FrequencyTable charFreqs) {
Comparator<Node> comparator = (x, y) -> {
/**
* TODO: x and y are Nodes
* x comes before y if x's count is less than y's count
*/
return 0;
};
PriorityQueue<Node> forest = new Heap<Node>(comparator);
/**
* TODO: Complete the implementation of Huffman's Algorithm.
* Start by populating forest with leaves.
*/
}
/**
* TODO
*
* Returns the character associated with the prefix of bits.
*
* @throws DecodeException if bits does not match a character in the tree.
*/
public char decodeChar(String bits) {
return '\0';
}
/**
* TODO
*
* Returns the bit string associated with the given character. Must
* search the tree for a leaf containing the character. Every left
* turn corresponds to a 0 in the code. Every right turn corresponds
* to a 1. This function is used by CodeBook to populate the map.
*
* @throws EncodeException if the character does not appear in the tree.
*/
public String lookup(char ch) {
return "";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.