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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 766 | 2.640625 | 3 | [] | no_license | import cv2
from imagePCA import fullProcess, trial2
numberFrames = 120
numberComponents = 200
FPS = 24
width = 1920
height = 1080
fourcc = cv2.VideoWriter_fourcc(*'MP42')
video = cv2.VideoWriter('compressedCars_200.avi', fourcc, float(FPS), (width, height))
# Function to extract frames
def compressVideo(path):
vidObj = cv2.VideoCapture(path)
count = 0
success = 1
while success and count < numberFrames:
count += 1
print (count, flush=True)
success, image = vidObj.read()
# print (image.shape, type(image))
new_image = trial2(image, numberComponents)
# print (type(new_image))
video.write(new_image)
video.release()
if __name__ == '__main__':
compressVideo('test_cars.mp4') |
Python | UTF-8 | 1,674 | 2.703125 | 3 | [] | no_license | import os, os.path, datetime, re
from pieberry.pieobject import PieObject
from pieberry.pieobject.diagnostic import determine_file_type
re_dateprefix = re.compile(r'^[12][0-9]{3}[01][0-9][0123][0-9]')
def get_fake_metadata(fn):
m = re_dateprefix.match(os.path.basename(fn))
if m:
# if it has a date prefix already, use that to infer the relevant
# date of the file
dateprefix = m.group(0)
ftime = '%s %s %s' % (dateprefix[0:4], dateprefix[4:6], dateprefix[6:8])
cdate = datetime.datetime.strptime(ftime, '%Y %m %d')
ttl = os.path.splitext(os.path.basename(fn))[0][8:].lstrip(' -')
else:
# if no date prefix, use os.stat to infer the date of the file
ttl = os.path.splitext(os.path.basename(fn))[0]
cdate = datetime.datetime.fromtimestamp(os.stat(fn)[9])
mdate = datetime.datetime.fromtimestamp(os.stat(fn)[8])
assert type(ttl) == unicode
r = {
'creation_date': cdate,
'creation_date_guessed': True,
'modification_date': mdate,
'title': ttl,
'author': u''
}
return r
def get_fake_metadata_for_aspect(obj):
return get_fake_metadata(obj.FileData_FullPath)
def get_fake_metadata_object(fn):
'''get object with metadata gleaned only from the file system
takes a full path'''
d = get_fake_metadata(fn)
obj = PieObject(
title = d['title'],
date = d['creation_date'])
obj.FileData_DateCreated = d['creation_date']
obj.FileData_DateModified = d['modification_date']
obj.FileData_FileType = determine_file_type(fn)
obj.FileData_FileName = os.path.basename(fn)
return obj
|
Go | UTF-8 | 1,652 | 3.015625 | 3 | [
"Unlicense"
] | permissive | package model
import "time"
//RouteOwnershipStore store which server know which token
type RouteOwnershipStore struct {
whoKnows map[ /*token*/ string] /*addr*/ string //store data include self data for easier clone to other new join machine
whenExpire map[int64][] /*token*/ string
}
var sharedRouteOwnershipStore = RouteOwnershipStore{
whoKnows: make(map[string]string),
whenExpire: make(map[int64][]string),
}
//GetRouteOwnershipStore get singleton instance of RouteOwnershipStore
func GetRouteOwnershipStore() *RouteOwnershipStore {
return &sharedRouteOwnershipStore
}
//RemoveToken remove a token; usually used when remote server give up processing a record
func (s *RouteOwnershipStore) RemoveToken(tk string) {
delete(s.whoKnows, tk)
}
//QueryRouteOwnership let server ask
func (s *RouteOwnershipStore) QueryRouteOwnership(token string) (addr string, found bool) {
//read only no modification, no mutex lock
addr, found = s.whoKnows[token]
return
}
//AddRouteOwnership get
func (s *RouteOwnershipStore) AddRouteOwnership(addr, token string, expire int64) {
s.whenExpire[expire] = append(s.whenExpire[expire], token)
s.whoKnows[token] = addr
}
//
func (s *RouteOwnershipStore) ExportTokenOwners() (map[ /*token*/ string] /*addr*/ string, map[int64][] /*token*/ string) {
return s.whoKnows, s.whenExpire
}
//CleanExpired clear records that expired
func (s *RouteOwnershipStore) CleanExpired() {
var ct = time.Now().UnixNano()
for xt, tks := range s.whenExpire {
if ct > xt {
return //all handled
}
if tks != nil {
for _, tk := range tks {
delete(s.whoKnows, tk)
}
}
delete(s.whenExpire, xt)
}
}
|
Java | UTF-8 | 16,195 | 2.078125 | 2 | [] | no_license | package com.service.suspect.impl;
import com.common.utils.StringHelp;
import com.entity.DicCommon;
import com.entity.DicUnit;
import com.entity.suspect.EtGang;
import com.entity.suspect.EtSuspect;
import com.entity.suspect.OperSuspectVo;
import com.mapper.suspect.EtGangMapper;
import com.mapper.suspect.EtSuspectMapper;
import com.mapper.suspect.RlSuspectGangMapper;
import com.service.suspect.TreeServiceInfc;
import com.vo.TreeNodeVo;
import com.vo.suspect.SuspectTreeNodeVo;
import com.vo.suspect.SuspectTreePo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import javax.annotation.Resource;
/**
* Created by Auri on 2018/2/3.
* Desc:
*/
@Service
@Transactional
public class TreeServiceImpl implements TreeServiceInfc {
@Resource
protected EtSuspectMapper etSuspectMapper;
@Resource
private EtGangMapper etGangMapper;
@Resource
private RlSuspectGangMapper rlSuspectGangMapper;
@Override
public List<SuspectTreeNodeVo> listTreeNodesByType(List<DicCommon> suspectClassDics, String paramStr,String userId,String entryUnit) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
EtSuspect etParam = buildParam(paramStr);
//查询人员 可看自己录的和别人授权给自己的
etParam.setEntry(userId);
if(!"".equals(entryUnit)){
etParam.setEntryUnit(entryUnit);
}
List<SuspectTreePo> ets = etSuspectMapper.fuzzeyQuery(etParam);
// 生成文件夹node
String ortherId = String.valueOf(System.currentTimeMillis() / 1000);
List<SuspectTreeNodeVo> roots = buildRootNodes(suspectClassDics, ortherId);
// 生成子节点
List<SuspectTreeNodeVo> subNodes = buildSuspectNodes(ets, roots, ortherId);
nodes.addAll(roots);
nodes.addAll(subNodes);
return nodes;
}
@Override
public List<SuspectTreeNodeVo> listTreeNodesByUnit(List<DicUnit> units, String paramStr,String userId,String entryUnit) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
EtSuspect etParam = buildParam(paramStr);
//查询人员 可看自己录的和别人授权给自己的
etParam.setEntry(userId);
if(!"".equals(entryUnit)){
etParam.setEntryUnit(entryUnit);
}
List<SuspectTreePo> ets = etSuspectMapper.fuzzeyQuery(etParam);
// 生成文件夹node
String ortherId = String.valueOf(System.currentTimeMillis() / 1000);
List<SuspectTreeNodeVo> roots = buildRootNodesII(units, ortherId);
// 生成子节点
List<SuspectTreeNodeVo> subNodes = buildSuspectNodesII(ets, roots, ortherId);
nodes.addAll(roots);
nodes.addAll(subNodes);
return nodes;
}
@Override
public List<SuspectTreeNodeVo> listTreeNodesByGang(List<EtGang> gangs, String paramStr, String userId) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
//List<EtGang> gangs = etGangMapper.selectAll();
gangs = etGangMapper.selectAll(paramStr);
if(gangs.size() == 0 ){
gangs = null;
}
List<Map<String, Object>> rlGangs = rlSuspectGangMapper.fuzzeyQuery(paramStr,userId);
// 生成文件夹node
String ortherId = String.valueOf(System.currentTimeMillis() / 1000);
List<SuspectTreeNodeVo> roots = buildRootNodesIII(gangs, ortherId);
// 生成子节点
List<SuspectTreeNodeVo> subNodes = buildSuspectNodesIII(rlGangs, roots, ortherId);
// List<SuspectTreeNodeVo> subNodes = new ArrayList<>();
nodes.addAll(roots);
nodes.addAll(subNodes);
return nodes;
}
@Override
public List<SuspectTreeNodeVo> listTreeNodesByPermission(String sysUserId, String paramStr, Set<String> defaultSuspectIds) {
defaultSuspectIds = defaultSuspectIds == null ? new HashSet<String>() : defaultSuspectIds;
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
Map<String, String> params = new HashMap<>();
params.put("userId", sysUserId);
params.put("paramStr", paramStr);
List<OperSuspectVo> ets = etSuspectMapper.fuzzeyQueryWithPermission(params);
// 生成子节点
int len = ets.size();
int index = 0;
while (index < len) {
OperSuspectVo et = ets.get(index);
if (!defaultSuspectIds.contains(et.getSuspectId())) // 已选择的人员不再出现
{
SuspectTreeNodeVo stNode = buildNode(et.getSuspectId(), "00", et.getSuspectId(), et.getName(), false, TreeNodeVo.TYPE_NODE, et.getUserId(), et.getPermissionCode());
nodes.add(stNode);
}
index++;
}
Collections.sort(nodes, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
return temp;
}
});
return nodes;
}
private List<SuspectTreeNodeVo> buildSuspectNodesIII(List<Map<String, Object>> rls, List<SuspectTreeNodeVo> rootNodes, String ortherId) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
if (rls == null || rls.isEmpty()) {
return nodes;
}
int len = rls.size();
int index = 0;
while (index < len) {
Map<String, Object> rl = rls.get(index);
String gangIdStr = String.valueOf(rl.get("gangId"));
String userId = String.valueOf(rl.get("userId"));
// String permissionCodeStr = String.valueOf(rl.get("permissionCode"));
int permissionCode =0;// StringHelp.isEmpty(permissionCodeStr) ? -1 : Integer.valueOf(permissionCodeStr);
SuspectTreeNodeVo stNode = null;
// 依据团伙ID 分配结点所在目录
if (StringHelp.isNotEmpty(gangIdStr)) {
for (SuspectTreeNodeVo rootNode : rootNodes) {
String idStr = rootNode.getId();
if (gangIdStr.contains(idStr)) {
String suspectId = String.valueOf(rl.get("suspectId"));
String byName=String.valueOf(rl.get("byName"));
if(byName!=null&&!"".equals(byName)){
byName=" ("+byName+")";
}else{
byName="";
}
stNode = buildNode(suspectId, idStr, suspectId, String.valueOf(rl.get("name"))+byName, false, TreeNodeVo.TYPE_NODE, userId, permissionCode);
break;
}
}
}
// 无对应团伙 分配至“其他”目录下
if (stNode == null) {
String suspectId = String.valueOf(rl.get("suspectId"));
String byName=String.valueOf(rl.get("byName"));
if(byName!=null&&!"".equals(byName)){
byName=" ("+byName+")";
}else{
byName="";
}
stNode = buildNode(suspectId, ortherId, suspectId, String.valueOf(rl.get("name"))+byName, false, TreeNodeVo.TYPE_NODE, userId, permissionCode);
}
nodes.add(stNode);
index++;
}
Collections.sort(nodes, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
// int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
// return temp;
return o1.getId().compareTo(o2.getId());
}
});
return nodes;
}
private List<SuspectTreeNodeVo> buildSuspectNodesII(List<SuspectTreePo> ets, List<SuspectTreeNodeVo> rootNodes, String ortherId) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
if (ets == null || ets.isEmpty()) {
return nodes;
}
int len = ets.size();
int index = 0;
while (index < len) {
SuspectTreePo et = ets.get(index);
String entryUnitStr = String.valueOf(et.getEntryUnit());
SuspectTreeNodeVo stNode = null;
// 依据重点人员录入单位 分配结点所在目录
if (StringHelp.isNotEmpty(entryUnitStr)) {
for (SuspectTreeNodeVo rootNode : rootNodes) {
String idStr = rootNode.getId();
if (entryUnitStr.contains(idStr)) {
stNode = buildNode(et.getSuspectId(), idStr, et.getSuspectId(), et.getName(), false, TreeNodeVo.TYPE_NODE, et.getUserId(), et.getPermissionCode());
break;
}
}
}
// 无对应单位 分配至“其他”目录下
if (stNode == null) {
stNode = buildNode(et.getSuspectId(), ortherId, et.getSuspectId(), et.getName(), false, TreeNodeVo.TYPE_NODE, et.getUserId(), et.getPermissionCode());
}
nodes.add(stNode);
index++;
}
Collections.sort(nodes, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
// int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
// return temp;
return o1.getId().compareTo(o2.getId());
}
});
return nodes;
}
/**
* 依据一级目录 构建子级目录
*
* @param ets
* @param rootNodes
* @return
*/
private List<SuspectTreeNodeVo> buildSuspectNodes(List<SuspectTreePo> ets, List<SuspectTreeNodeVo> rootNodes, String ortherId) {
List<SuspectTreeNodeVo> nodes = new ArrayList<>();
if (ets == null || ets.isEmpty()) {
return nodes;
}
int len = ets.size();
int index = 0;
while (index < len) {
SuspectTreePo et = ets.get(index);
String suspectType = String.valueOf(et.getSuspectType());
SuspectTreeNodeVo stNode = null;
// 依据重点人员类型 分配结点所在目录
if (StringHelp.isNotEmpty(suspectType)) {
for (SuspectTreeNodeVo rootNode : rootNodes) {
String idStr = rootNode.getId();
if (suspectType.contains(idStr)) {
stNode = buildNode(et.getSuspectId(), idStr, et.getSuspectId(), et.getName(), false, TreeNodeVo.TYPE_NODE, et.getUserId(), et.getPermissionCode());
break;
}
}
}
// 无对应重点人员类型 分配至“其他”目录下
if (stNode == null) {
stNode = buildNode(et.getSuspectId(), ortherId, et.getSuspectId(), et.getName(), false, TreeNodeVo.TYPE_NODE, et.getUserId(), et.getPermissionCode());
}
nodes.add(stNode);
index++;
}
Collections.sort(nodes, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
return temp;
}
});
return nodes;
}
private EtSuspect buildParam(String paramStr) {
EtSuspect etSuspect = new EtSuspect();
if (StringHelp.isEmpty(paramStr)) {
paramStr = "";
}
etSuspect.setName(paramStr);
etSuspect.setByname(paramStr);
etSuspect.setIdcardNum(paramStr);
return etSuspect;
}
/**
* 构建一级目录
*
* @param gangs
* @return
*/
private List<SuspectTreeNodeVo> buildRootNodesIII(List<EtGang> gangs, String ortherId) {
List<SuspectTreeNodeVo> roots = new ArrayList<>();
if (gangs == null || gangs.isEmpty()) {
return roots;
}
for (int i = 0; i < gangs.size(); i++) {
boolean isOpen = false;
if (i == 0) {
isOpen = true;
}
EtGang gang = gangs.get(i);
SuspectTreeNodeVo temp = buildNode(gang.getId(), "00", "", gang.getGangName(), isOpen, TreeNodeVo.TYPE_DIR, null, -1);
roots.add(temp);
}
Collections.sort(roots, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
return temp;
}
});
SuspectTreeNodeVo orderN = buildOtherDicNode(ortherId);
roots.add(orderN);
return roots;
}
/**
* 构建一级目录
*
* @param units
* @return
*/
private List<SuspectTreeNodeVo> buildRootNodesII(List<DicUnit> units, String ortherId) {
List<SuspectTreeNodeVo> roots = new ArrayList<>();
if (units == null || units.isEmpty()) {
return roots;
}
for (int i = 0; i < units.size(); i++) {
boolean isOpen = false;
if (i == 0) {
isOpen = true;
}
DicUnit dic = units.get(i);
SuspectTreeNodeVo temp = buildNode(dic.getCode(), "00", "", dic.getName(), isOpen, TreeNodeVo.TYPE_DIR, null, -1);
roots.add(temp);
}
Collections.sort(roots, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
return temp;
}
});
SuspectTreeNodeVo orderN = buildOtherDicNode(ortherId);
roots.add(orderN);
return roots;
}
/**
* 构建一级目录
*
* @param suspectClassDics
* @return
*/
private List<SuspectTreeNodeVo> buildRootNodes(List<DicCommon> suspectClassDics, String ortherDicId) {
List<SuspectTreeNodeVo> roots = new ArrayList<>();
if (suspectClassDics == null || suspectClassDics.isEmpty()) {
return roots;
}
for (int i = 0; i < suspectClassDics.size(); i++) {
boolean isOpen = false;
if (i == 0) {
isOpen = true;
}
DicCommon dic = suspectClassDics.get(i);
SuspectTreeNodeVo temp = buildNode(dic.getDicCode(), "00", "", dic.getDicValue(), isOpen, TreeNodeVo.TYPE_DIR, null, -1);
roots.add(temp);
}
Collections.sort(roots, new Comparator<SuspectTreeNodeVo>() {
@Override
public int compare(SuspectTreeNodeVo o1, SuspectTreeNodeVo o2) {
int temp = o1.getId().compareTo(o2.getId()) > 0 ? 1 : -1;
return temp;
}
});
SuspectTreeNodeVo orderN = buildOtherDicNode(ortherDicId);
roots.add(orderN);
return roots;
}
private SuspectTreeNodeVo buildOtherDicNode(String otherId) {
return buildNode(otherId, "00", "", "其他", false, TreeNodeVo.TYPE_DIR, null, -1);
}
private SuspectTreeNodeVo buildNode(String id, String pId, String suspectNo, String name, boolean isOpen, int nodeType, String userId, int permissionCode) {
id = StringHelp.isEmpty(id) ? "" : id;
SuspectTreeNodeVo node = new SuspectTreeNodeVo();
node.setId(id);
node.setpId(pId);
node.setName(name);
node.setOpen(isOpen);
node.setType(nodeType);
node.setSuspectNo(suspectNo);
node.setUserId(userId);
node.setPermissionCode(permissionCode);
if (nodeType == TreeNodeVo.TYPE_DIR) {
// node.setIconOpen("view/assets/images/gallery/file_open.png");
node.setIcon("view/assets/images/gallery/file_close.png");
} else {
node.setIcon("view/assets/images/gallery/person_open.png");
}
return node;
}
}
|
JavaScript | UTF-8 | 943 | 3.21875 | 3 | [] | no_license | /**
* A simple wrapper for short Audio playback, used to play
* FX sounds such as the sound played when you hit the wall.
* @param {String} path URL / relative path to sound file.
* @param {Number} volume A volume level between 0 and 1, defaults to 1
*/
export default class Sound {
constructor(path, volume) {
var that = this;
this.path = path;
this.audio = new Audio();
this.audio.src = path;
this.audio.loop = false;
this.audio.volume = volume || 1;
this.ready = false;
this.audio.addEventListener('canplay', function() {
that.ready = true;
});
}
pause() {
this.audio.pause();
}
stop() {
if(this.ready) {
this.audio.currentTime = 0;
this.pause();
}
}
play() {
var that = this;
if(this.audio.playing) {
this.stop();
this.audio.currentTime = 0;
}
this.audio.play();
}
} |
TypeScript | UTF-8 | 2,216 | 2.8125 | 3 | [] | no_license | /*
file handles updating users details
*/
import { User } from "../entity/User";
import { getConnection } from "typeorm";
import { InputUpdateUser, UpdateUser } from "./users-interface";
import { passwordHash } from "./users-helpers";
import { existingEmailCheck, regexEmailCheck } from "./users-helpers";
import { ApiError } from "../errors";
/** update user details from InputUpdateUser object and id */
export async function updateUser(
id: string,
input_changes: InputUpdateUser
): Promise<void> {
const changes: UpdateUser = {};
await Promise.all(
Object.keys(input_changes).map(async (key) => {
// if the password changes, hash the password
if (key === "password") {
changes.password_hash = await passwordHash(input_changes.password);
return;
} else if (key === "email") {
// check if valid email
if (!regexEmailCheck(input_changes.email)) {
throw new ApiError(
"user_update/invalid_email",
"Please enter a valid email"
);
}
// check if email already exists in database
if (await existingEmailCheck(input_changes.email)) {
throw new ApiError(
"user_update/email_exists",
"This email already belongs to a Tasker account."
);
}
changes.email = input_changes.email;
return;
} else if (
// keep updates to database very clean
key === "first_name" ||
key === "last_name" ||
key === "avatar_url" ||
key === "bio"
) {
// otherwise, update it
changes[key as keyof UpdateUser] =
input_changes[key as keyof InputUpdateUser];
return;
}
// if they're not a correct key, don't update
throw new ApiError(
"user_update/invalid_change",
"Cannot Modify Nonexistent Properties of User"
);
})
);
// attempt to update user
const status = await getConnection().manager.update(
User,
{ id: id },
changes
);
// if user to update doesn't exist, throw error
if (status.affected == 0) {
throw new ApiError("user_update/no_user", "No such user exists");
}
return;
}
|
Java | UTF-8 | 2,468 | 2.5625 | 3 | [] | no_license | package protocol.subprotocol.handler;
import protocol.Chunk;
import protocol.Peer;
import java.util.concurrent.TimeUnit;
import static protocol.subprotocol.Subprotocol.PUTCHUNK;
public class PutchunkHandler extends Handler implements Runnable {
private static final int MAX_PUTCHUNK_REPEAT = 5;
private static final int PUTCHUNK_INBETWEEN_TIME_MS = 1000;
private int repeatCnt;
private Chunk chunk;
private String fileId;
private int repDegree;
private boolean enhanced;
public PutchunkHandler(Chunk chunk, String fileId, int repDegree, boolean enhanced) {
this.chunk = chunk;
this.fileId = fileId;
this.repDegree = repDegree;
this.repeatCnt = 0;
this.enhanced = enhanced;
}
@Override
public void run() {
handle();
}
@Override
public void handle() {
if (repeatCnt < MAX_PUTCHUNK_REPEAT) {
int chunkNo = chunk.getChunkNo();
String chunkId = fileId + "_" + chunkNo;
if (Peer.getDataContainer().getStoredCurrRepDegree(chunkId) >= repDegree ||
Peer.getDataContainer().getBackedUpChunkCurrRepDegree(chunkId) >= repDegree)
return;
byte[] body = chunk.getBody();
byte[] message;
if(enhanced)
message = buildMessage(PUTCHUNK, MSG_CONFIG_PUTCHUNK, fileId, chunkNo, repDegree, body, completionPercentage());
else
message = buildMessage(PUTCHUNK, MSG_CONFIG_PUTCHUNK, fileId, chunkNo, repDegree, body);
Peer.getBackupChannel().write(message);
++repeatCnt;
//delay for stored msg receiving
Peer.getExecutor().schedule(this, PUTCHUNK_INBETWEEN_TIME_MS, TimeUnit.MILLISECONDS);
}
}
private float completionPercentage() {
float percentage = 0;
switch (repeatCnt) {
case 0:
percentage = (float) 0.6;
break;
case 1:
percentage = (float) 0.75;
break;
case 2:
percentage = (float) 0.85;
break;
case 3:
percentage = (float) 1.0;
break;
case 4:
percentage = (float) 1.0;
break;
default:
percentage = (float) 1.0;
break;
}
return percentage;
}
}
|
Shell | UTF-8 | 1,590 | 4.125 | 4 | [] | no_license | #!/usr/bin/env bash
# outputs md5s of files in a given directory
# depending on mode and cpu it could be faster if run on parallel mode
# use the time to see the difference
# in my simple experiment, the parallel was 4 times faster
function showHelp()
{
echo "parallel_md5.sh [-s] /path/to/dir "
exit 1
}
parallel=1
while getopts "h?s" opt; do
case "$opt" in
h|\?)
showHelp
;;
s)
parallel=0
;;
esac
done
shift $(expr $OPTIND - 1 )
if [[ $# == 0 ]]; then
showHelp
fi
dir="$1"
ENV_PLATFORM="Linux"
unameStr=`uname`
if [[ "$unameStr" = "Darwin" ]]; then
ENV_PLATFORM="Mac";
fi
filesStr=$(find "$dir" -maxdepth 1 -type f)
files=
file=
i=
IFS=$'\n' read -rd '' -a files <<<"$filesStr"
if [[ $parallel == 1 ]]; then
pidArray=()
for (( i=0 ; i < ${#files[@]} ; i++ )); do
file=${files[$i]}
if [[ "$file" != "$dir" ]]; then
if [[ -r "$file" ]]; then
if [ $ENV_PLATFORM == "Mac" ]; then
md5 $file &
pidArray+=("$!")
else
md5sum $file &
pidArray+=("$!")
fi
fi
fi
done
wait ${pidArray[@]}
else
for (( i=0 ; i < ${#files[@]} ; i++ )); do
file=${files[$i]}
if [[ "$file" != "$dir" ]]; then
if [[ -r "$file" ]]; then
if [ $ENV_PLATFORM == "Mac" ]; then
md5 $file
else
md5sum $file
fi
fi
fi
done
fi
|
C++ | UTF-8 | 2,356 | 2.65625 | 3 | [] | no_license | #ifndef PARTICLE_H
#define PARTICLE_H
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<math.h>
using namespace std;
class CParticle{
public:
CParticle(){
init();
}
void init(){
kn=1e+6;
cn=0;//1e+2;
x=0; y=0; r=1;
vx=0; vy=0;
ax=0; ay=0;
ax0=0; ay0=0;
q=0;w=0;
aq=0; aq=0;
aq0=0; aq0=0;
fx=0; fy=0;
density=1;
update_mass();
}
void update_mass(){
m=density*M_PI*r*r;
}
CParticle(double _x, double _y, double _r){
init();
set_pos(_x,_y);
r=_r;
density=1;
}
void set_pos(double _x, double _y ){
x=_x;
y=_y;
}
void set_vel(double _vx, double _vy ){
vx=_vx;
vy=_vy;
}
double dist(const CParticle &p)const{
return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
}
double dist2(const CParticle &p)const{
return (x-p.x)*(x-p.x)+(y-p.y)*(y-p.y);
}
bool collide(const CParticle &p)const{
};
void interact(CParticle &p){
double d2=dist2(p);
if( d2 > (r+p.r)*(r+p.r))return;
double d=sqrt(d2);
double ovl= fabs(d - (r+p.r));
double vn=sqrt((vx-p.vx)*(vx-p.vx)+(vy-p.vy)*(vy-p.vy));
double fn=kn*pow(ovl,1.5);//-cn*vn;
double nx=(x-p.x)/d;
double ny=(y-p.y)/d;
fx+=fn*nx;
fy+=fn*ny;
p.fx-=fn*nx;
p.fy-=fn*ny;
}
double energy(){
return 0.5*m*(vx*vx+vy*vy);
}
void predict(double dt){
//atualzação das posições (Beeman's algorithm)
x+=(vx + (2.0*ax/3.0 - ax0/6.0)*dt)*dt;
y+=(vy + (2.0*ay/3.0 - ay0/6.0)*dt)*dt;
q+=(w + (2.0*aq/3.0 - aq0/6.0)*dt)*dt;
//if(q>2.0*M_PI) q-=2.0*M_PI; if(q<0) q+=2.0*M_PI;
tempDt=dt;
}
void update_accel(){
axtemp=ax;
aytemp=ay;
ax=fx/m;
ay=fy/m;
//aq=T/I;
}
void correct(){
static double dtt;
double dt=tempDt;
dtt=6.*dt*dt;
x+=(2*ax-2*axtemp+ax0)*dtt;
y+=(2*ay-2*aytemp+ay0)*dtt;
//vx+=(5*ax+2*axtemp-ax0)*dt/12.0;
//vy+=(5*ay+2*aytemp-ay0)*dt/12.0;
vx+=(ax/3+5*axtemp/6-ax0/6)*dt;
vy+=(ay/3+5*aytemp/6-ay0/6)*dt;
q+=(5*aq+2*aq1-aq0)*dt/12.0;
if(q>2.0*M_PI) q-=2.0*M_PI; if(q<0) q+=2.0*M_PI;
ax0=axtemp;
ay0=aytemp;
}
void print(ostream &out=cout)const{
out<< x <<"\t"<< y <<"\t"<< r <<endl;
}
double kn, cn;
double x, y, r;
double vx, vy;
double ax, ay;
double ax0, ay0, axtemp, aytemp;
double w, q, aq, aq0, aq1;
double fx, fy;
double m;
private:
double density;
double tempDt;
};
#endif /* PARTICLE_H */
|
Java | UTF-8 | 18,681 | 1.710938 | 2 | [] | no_license | package es.pfctonimartos.tpms;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler handler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt gatt;
public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String WRITE_UUID = "0000ffe9-0000-1000-8000-00805f9b34fb";
public final static String READ_UUID = "0000ffe4-0000-1000-8000-00805f9b34fb";
public final static String SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
public final static String QUERYID = "FC02D52B";
private TextView FLpressure;
private TextView FLtemperature;
private TextView FRpressure;
private TextView FRtemperature;
private TextView RLpressure;
private TextView RLtemperature;
private TextView RRpressure;
private TextView RRtemperature;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpViews();
handler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
private void setUpViews() {
FLpressure = (TextView) findViewById(R.id.frontLeftPressure);
FLtemperature = (TextView) findViewById(R.id.frontLeftTemperature);
FRpressure = (TextView) findViewById(R.id.frontRightPressure);
FRtemperature = (TextView) findViewById(R.id.frontRightTemperature);
RLpressure = (TextView) findViewById(R.id.rearLeftPressure);
RLtemperature = (TextView) findViewById(R.id.rearLeftTemperature);
RRpressure = (TextView) findViewById(R.id.rearRightPressure);
RRtemperature = (TextView) findViewById(R.id.rearRightTemperature);
}
@Override
protected void onResume() {
super.onResume();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
mLEScanner = bluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
scanLeDevice(true);
}
}
@Override
protected void onPause() {
super.onPause();
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
@Override
protected void onDestroy() {
if (gatt == null) {
return;
}
gatt.close();
gatt = null;
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
mLEScanner.stopScan(mScanCallback);
}
}, SCAN_PERIOD);
mLEScanner.startScan(filters, settings, mScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("callbackType", String.valueOf(callbackType));
Log.i("result", result.toString());
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult - Results", sr.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
byte[] advertisement = scanRecord;
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("onLeScan", device.toString());
connectToDevice(device);
}
});
}
};
public void connectToDevice(BluetoothDevice device) {
if (gatt == null && device.toString().equalsIgnoreCase("D0:B5:C2:E8:40:6B")) {
gatt = device.connectGatt(this, false, gattCallback);
scanLeDevice(false);// will stop after first device detection
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i("onConnectionStateChange", "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.i("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
Log.i("onServicesDiscovered", services.toString());
//gatt.readCharacteristic(services.get(1).getCharacteristics().get(0));
// Por cada servicio recibido
for (BluetoothGattService service : services) {
// Buscamos en cada una de sus características
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
// Si la caracterísitca es WRITE
if (characteristic.getUuid().toString().equalsIgnoreCase(WRITE_UUID)) {
Log.i("WRITE_UUID GOT:", WRITE_UUID);
sendCharacteristic(gatt, characteristic);
}
// Si la característica es READ, configuramos una notificación
if (characteristic.getUuid().toString().equalsIgnoreCase(READ_UUID)) {
Log.i("READ_UUID GOT:", READ_UUID);
gatt.setCharacteristicNotification(characteristic, true);
}
// Si la característica es SERVICE, guardamos el dispositivo
if (characteristic.getUuid().toString().equalsIgnoreCase(SERVICE_UUID)) {
Log.i("SERVICE_UUID GOT:", SERVICE_UUID);
}
}
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == gatt.GATT_SUCCESS) {
byte[] arrayOfByte = characteristic.getValue();
// Procesado posterior
Log.i("onCharacteristicRead", characteristic.toString());
gatt.disconnect();
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
// le pasaremos la QUERY por aquí
//writeBytes(UtilsConfig.chatOrders(QUERYID));
Log.i("onCharacteristicWrite", characteristic.toString());
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
byte[] arrayOfByte = characteristic.getValue();
//if(arrayOfByte[4]!=0 && arrayOfByte[5]!=0) {
showData(arrayOfByte);
//}
gatt.readCharacteristic(characteristic);
// Esta función se lanzará cuando recibamos una respuesta tras ejecutar un << writeCharacteristic(characteristic) >>
// También se autodispara en caso de activar notificaciones
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
public void sendCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
byte[] query = QUERYID.getBytes();
byte[] data = chatOrder(query);
characteristic.setValue(data);
gatt.writeCharacteristic(characteristic);
}
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
public static byte[] chatOrder(byte[] m) {
if (m.length % 2 != 0) {
return null;
}
byte[] bytes = new byte[(m.length / 2)];
int i = 0;
int j = 0;
while (i < m.length) {
bytes[j] = UnitsManager.uniteByte(m[i], m[i + 1]);
i += 2;
j += 1;
}
return bytes;
}
public void showData(byte[] data) {
int order = data[2];
int sensorId = data[3];
switch (order) {
case -43:
getSensorsIds(data);
break;
case 1:
getCurrentId(sensorId);
getTyre(sensorId, data);
break;
}
}
public static void getSensorsIds(byte[] data) {
byte[] items = new byte[4];
int j = 1;
for(int i = 3; i < data.length; i=+4){
if(data[i]!=0){
System.arraycopy(data, i, items, 0, items.length);
Log.d("BUCLE_ID_"+j, UnitsManager.bytesToHex(items));
}
j++;
}
System.arraycopy(data, 3, items, 0, items.length);
Log.d("ID1", UnitsManager.bytesToHex(items));
System.arraycopy(data, 7, items, 0, items.length);
Log.d("ID2", UnitsManager.bytesToHex(items));
System.arraycopy(data, 11, items, 0, items.length);
Log.d("ID3", UnitsManager.bytesToHex(items));
System.arraycopy(data, 15, items, 0, items.length);
Log.d("ID4", UnitsManager.bytesToHex(items));
}
public static void getCurrentId(int sensorId) {
Integer sensor = sensorId;
switch (sensor) {
case 1:
Log.d("FRONT LEFT SENSOR", sensor.toString());
break;
case 2:
Log.d("FRONT RIGHT SENSOR", sensor.toString());
break;
case 3:
Log.d("REAR LEFT SENSOR", sensor.toString());
break;
case 4:
Log.d("REAR RIGHT SENSOR", sensor.toString());
break;
}
}
public Tyre getTyre(int sensorId, byte[] data) {
HashMap<String, String> tyreData = new HashMap<>();
tyreData.put("IR", Integer.valueOf(UnitsManager.getAbsValue(data[4])).toString());
tyreData.put("TY", Integer.valueOf(UnitsManager.getAbsValue(data[5])).toString());
tyreData.put("TW", Integer.valueOf(UnitsManager.getAbsValue(data[6])).toString());
tyreData.put("DL", Integer.valueOf(UnitsManager.getAbsValue(data[7])).toString());
tyreData.put("DISTYPE", Integer.valueOf(UnitsManager.getAbsValue(data[8])).toString());
final Tyre tyre = getTyreData(tyreData, sensorId);
byte dd = (byte) tyre.getIr();
Integer ir = UnitsManager.byteToInt(dd, sensorId);
String pressure = UnitsManager.getPressureValue(tyre.getTy());
String temperature = UnitsManager.getTemValue(tyre.getTw());
Log.d("Pressure: ", pressure);
Log.d("Temperature: ", temperature);
Log.d("Last_IR: ", ir.toString());
printInView(pressure, temperature, sensorId);
return tyre;
}
//TODO: prepare propertyNames in calling method
private String preparePropertyName (final String propertyName, final int sensorId){
String sensorPosition = "";
String sensorName;
String property = propertyName.toUpperCase();
switch (sensorId){
case 1:
sensorPosition = "FL_WHEEL_";
break;
case 2:
sensorPosition = "FR_WHEEL_";
break;
case 3:
sensorPosition = "RL_WHEEL_";
break;
case 4:
sensorPosition = "RR_WHEEL_";
break;
}
sensorName = sensorPosition.concat(propertyName);
return sensorName;
}
private String preparePropertyUnit (final String propertyName){
String propertyUnit = "";
switch (propertyName){
case "pressure":
propertyUnit = "bar";
break;
case "temperature":
propertyUnit = "ºC";
break;
}
return propertyUnit;
}
//TODO: device_id needs a reliable value (I think the wheel sensor one)
private JSONObject createJSONObject (final String propertyName, final String propertyValue, final int sensorId) throws JSONException {
Date timestamp = new Date();
JSONObject dataPoint = new JSONObject();
JSONObject dataPoints = new JSONObject();
JSONObject singleSensor = new JSONObject();
JSONObject jsonObject = new JSONObject();
dataPoint.put("time", timestamp);
dataPoint.put("value", propertyValue);
dataPoints.put("data_points", dataPoint);
singleSensor.put("data_points", dataPoint);
singleSensor.put("sensor_name", propertyName);
singleSensor.put("units", propertyValue);
jsonObject.put("device_id", sensorId);
jsonObject.put("sensors", singleSensor);
return jsonObject;
}
private void createJSONFile(final JSONObject jsonDataObject){
//File file = new File(Environment.getExternalStorageDirectory() + "Android/data/com.sensorspark.carmetry/files/test.txt");
}
private void printInView(final String pressure, final String temperature, final int sensorId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (sensorId){
case 1:
FLpressure.setText(pressure.concat(" Bar"));
FLtemperature.setText(temperature.concat(" ºC"));
break;
case 2:
FRpressure.setText(pressure.concat(" Bar"));
FRtemperature.setText(temperature.concat(" ºC"));
break;
case 3:
RLpressure.setText(pressure.concat(" Bar"));
RLtemperature.setText(temperature.concat(" ºC"));
break;
case 4:
RRpressure.setText(pressure.concat(" Bar"));
RRtemperature.setText(temperature.concat(" ºC"));
break;
}
}
});
}
private static Tyre getTyreData(HashMap<String, String> tyreData, int id) {
Tyre tyre = new Tyre();
tyre.setId(id);
tyre.setIr(Integer.parseInt(tyreData.get("IR")));
tyre.setDl(Integer.parseInt(tyreData.get("DL")));
tyre.setTy(Integer.parseInt(tyreData.get("TY")));
tyre.setTw(Integer.parseInt(tyreData.get("TW")));
tyre.setDis(Integer.parseInt(tyreData.get("DISTYPE")));
return tyre;
}
/********************************/
/* DEFAULT GATT CHARACTERISTICS */
/********************************/
// ScanResult{mDevice=D0:B5:C2:E8:40:6B,
// mScanRecord=ScanRecord [ mAdvertiseFlags=6,
// mServiceUuids=[0000fff0-0000-1000-8000-00805f9b34fb, 0000ffb0-0000-1000-8000-00805f9b34fb],
// mManufacturerSpecificData={0=[-1, -1, -1, -1, 100, 0, -1]},
// mServiceData={},
// mTxPowerLevel=0,
// mDeviceName=ZhiXuan-TPMS],
// mRssi=-49,
// mTimestampNanos=207430302345260}
}
|
Python | UTF-8 | 21,051 | 2.9375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 8 14:15:54 2014
@author: Brian Donovan (briandonovan100@gmail.com)
"""
from routing.BiDirectionalSearch import bidirectional_search
from routing.Map import Map
from Trip import Trip
from datetime import datetime
import csv
import math
from multiprocessing import Pool
from functools import partial
import sys, traceback
MAX_SPEED = 30
INITIAL_IDLE_TIME = 300
DW_ABS = 1
DW_REL = 2
DW_GAUSS = 1
DW_LASSO = 2
DW_THRESH = 3
# Computes the average velocity across a series of trips
# computed as total_dist / total_time (longer trips get more weight)
# Params:
# trips - a list of Trips
# Returns:
# the average velocity
def compute_avg_velocity(trips):
s_t = 0.0
s_d = 0.0
for trip in trips:
s_t += trip.time
s_d += trip.dist
avg_velocity = s_d / s_t
return avg_velocity
# Computes a trips weight based on how closely the estimated distance and true distance match
# There are several different ways to compute the weight
# Params:
# distance_weighting - could be None for equal weighting, or a tuple
# (val_type, kern_type, bandwidth) where:
# val_type - either DW_ABS or DW_REL. Weighting can be based on absolute or relative error
# kern_type - either DW_GAUSS, DW_LASSO, or DW_THRESH. For Gaussian, Lasso, or Threshold weighting
# bandwidth - (or length-scale) determines the gaussian sdev, lasso width, or threshold for the weighting scheme
# true_dist - the true reported distance of a trip
# est_dist - the computed distance of a trip based on the shortest path
def compute_weight(distance_weighting, true_dist, est_dist):
if(distance_weighting==None):
return 1
(val_type, kern_type, bandwidth) = distance_weighting
if(val_type==DW_ABS):
dist_err = est_dist - true_dist
elif(val_type==DW_REL):
if(true_dist==0):
dist_err=1
else:
dist_err = (est_dist - true_dist)/ true_dist
if(kern_type==DW_GAUSS):
return math.e**(-(dist_err/bandwidth)**2)
elif(kern_type==DW_LASSO):
return 1 - min(1,abs(dist_err / bandwidth))
elif(kern_type==DW_THRESH):
return 1 * (dist_err < bandwidth)
# Predicts the duration of a single trip based on its origin, destination, and the state of traffic
# Computes several L1-based error metrics in the process, which measure the prediction accuracy
# It is assumed that the driver will take the shortest path
# This function can be used in a few different contexts, which are given by the parameters route and proposed
# Params:
# road_map - a Map object which has some travel times on each link
# trips - a set of Trips that will be routed and predicted
# route - if True, the shortest paths will be computed (very costly)
# otherwise, the existing ones will be used (trip.path_links)
# proposed - if True, link.proposed_time will be used as the cost instead of link.time
# max_speed - the maximum speed of any Link. Will be computed if None (a little costly).
# This is used by the A* heuristic - only important if route=True
# distance_weighting - the method for computing the weight. see compute_weight()
# Returns:
# trip - the same trip that was given as input
# error - the value of the error metric (which we are trying to minimize)
# l1_error - the absolute error
# sum_perc_error - the (positive) percentage error
# num_trips - the number of trips represented by this one "unique trip"
def predict_trip_time(trip, road_map, route=True, proposed=False, max_speed = None,
distance_weighting=None, flatten_after = False, model_idle_time=True):
try:
if(flatten_after):
road_map.unflatten()
trip.unflatten(road_map)
error = 0.0
l1_error = 0.0
sum_perc_error = 0
num_trips = 0
if(route):
trip.path_links = bidirectional_search(trip.origin_node, trip.dest_node, use_astar=True, max_speed=max_speed)
if(model_idle_time):
trip.path_links.append(road_map.idle_link)
if(proposed):
trip.estimated_time = sum([link.proposed_time for link in trip.path_links])
else:
trip.estimated_time = sum([link.time for link in trip.path_links])
trip.estimated_dist = sum([link.length for link in trip.path_links])
# This trip may actually represent several duplicate trips (in terms of origin/destination),
# which may have different true times - the dup_times parameter loops through these
for true_time in trip.dup_times:
l1_error += abs(trip.estimated_time - true_time)
# If we are using distance weighting, compute weight with Gaussian kernel
weight = compute_weight(distance_weighting, trip.dist, trip.estimated_dist)
error += abs(trip.estimated_time - true_time) * weight
sum_perc_error += (abs(trip.estimated_time - true_time) / true_time)
num_trips += 1
if(flatten_after):
trip.flatten()
return trip, error, l1_error, sum_perc_error, num_trips
except:
raise Exception("".join(traceback.format_exception(*sys.exc_info())))
# Predicts the travel times for many trips, can make use of parallel processing
def predict_trip_times(road_map, trips, route=True, proposed=False, max_speed = None,
distance_weighting=None, model_idle_time=True, pool=None):
if(max_speed==None):
max_speed = road_map.get_max_speed()
if(pool==None):
# Create a partial function, which only takes a Trip as input (all of the others are given constants)
# This makes it easy to use with the map() function
trip_func = partial(predict_trip_time, road_map=road_map,route=route, proposed=proposed,
max_speed=max_speed, distance_weighting=distance_weighting,
model_idle_time=model_idle_time, flatten_after=False)
# Predict the travel times for all of the trips
output_list = map(trip_func, trips)
else:
# If we are using several cpus, we will use Pool.map() instead
# However, the Trips and Map must be flattened before they can be sent to worker processes
print("Flattening everything.")
for trip in trips:
trip.flatten()
road_map.flatten()
print("Splitting")
# Create a partial function, which only takes a Trip as input (all of the others are given constants)
# This makes it easy to use with the map() function.
# The trips must be flattened, since they are being sent across processes
trip_func = partial(predict_trip_time, road_map=road_map,route=route, proposed=proposed,
max_speed=max_speed, distance_weighting=distance_weighting,
model_idle_time=model_idle_time, flatten_after=True)
# create the multiprocessing pool to route the Trips in parallel
# Perform the routing with one chunk per CPU
ideal_chunksize = (len(trips) / pool._processes) + 1
output_list = pool.map(trip_func, trips, chunksize=ideal_chunksize)
pool.terminate()
print("Unflattening trips")
routed_trips = [trip for trip, error, l1_error, sum_perc_error, num_trips in output_list]
# The Pool returns a new copy of the trips - the relevant data must be copied back to the originals
# The Trip must also be unflattened, for use with the current Map
for i in xrange(len(trips)):
trips[i].path_link_ids = routed_trips[i].path_link_ids
trips[i].estimated_time = routed_trips[i].estimated_time
trips[i].estimated_dist = routed_trips[i].estimated_dist
trips[i].unflatten(road_map)
total_error = 0.0
total_l1 = 0.0
total_perc_error = 0.0
total_num_trips = 0
for trip, error, l1_error, sum_perc_error, num_trips in output_list:
total_error += error
total_l1 += l1_error
total_perc_error += sum_perc_error
total_num_trips += num_trips
avg_error = total_l1 / total_num_trips
avg_perc_error = total_perc_error / total_num_trips
return total_error, avg_error, avg_perc_error
# Compute link offsets based on trip time errors. Link offsets indicate whether
# this link's travel time should increase or decrease, in order to decrease the
# error metric. The sign of link offset should be the same as the sign of the
# derivative of the error function with respect to this link's cost.
# Params:
# road_map - a Map object
# unique_trips - a list of Trip objects
# distance_weighting - the method for computing the weight. see compute_weight()
def compute_link_offsets(road_map, unique_trips, distance_weighting=None):
#Start offsets at 0
for link in road_map.links:
link.offset = 0
link.num_trips = 0
# If we overestimate, increase link offsets
# If we underestimate, decrease link offsets
for trip in unique_trips:
weight = compute_weight(distance_weighting, trip.dist, trip.estimated_dist)
for link in trip.path_links:
link.num_trips += weight * len(trip.dup_times)
#print str(use_distance_weighting) + ": " + str(trip.estimated_dist) + " - " + str(trip.dist) + " --> " + str(weight)
for true_time in trip.dup_times:
if(trip.estimated_time > true_time):
for link in trip.path_links:
link.offset += weight
elif(trip.estimated_time < true_time):
for link in trip.path_links:
link.offset -= weight
# Uses an iterative algorithm, similar to the one supplied in
# http://www.pnas.org/content/111/37/13290
# in order to estimate link-by link travel times, using many Trips.
# Upon completion, all of the Link objects in road_map.links will have their
# .time attribute modified
# Some diagonstics are also computed in order to assess the model's quality over iterations
# Params:
# road_map - a Map object, which contains the road geometry
# trips - a list of Trip objects.
# max_iter - maximum number of iterations before the experiment ends
# test_set - an optional hold-out test set to assess how well the model generalizes.
# distance_weighting - the method for computing the weight. see compute_weight()
# model_idle_time - Assumes that each trip includes a fixed amount of idle time (which will be estimated)
# Returns:
# iter_avg_errors - A list of the average absolute errors at each iteration
# iter_perc_errors - A list of average percent errors at each iteration
# test_avg_errors - A list of average absolute errors on the test set at each iteration
# test_perc_errors - A list of average percent errors on the test set at each iteration
def estimate_travel_times(road_map, trips, max_iter=20, test_set=None, distance_weighting=None, model_idle_time=False, initial_idle_time=0):
#print("Estimating traffic. use_distance_weighting=" + str(use_distance_weighting))
DEBUG = False
#Collapse identical trips
unique_trips = road_map.match_trips_to_nodes(trips)
if(len(unique_trips) == 0):
raise Exception("No trips to estimate traffic.")
if(test_set!= None):
unique_test_trips = road_map.match_trips_to_nodes(test_set)
# Set initial travel times to average velocity across trips
avg_velocity = compute_avg_velocity(trips)
road_map.set_all_link_speeds(avg_velocity)
# Set the initial idle time
road_map.idle_link.time = initial_idle_time
iter_avg_errors = []
iter_perc_errors = []
test_avg_errors = []
test_perc_errors = []
outer_iter = 0
outer_loop_again = True
# Outer loop - route all of the trips and produce travel time estimates
# Will stop once the travel times cannot be improved (or max_iter is reached)
while(outer_loop_again and outer_iter < max_iter):
outer_iter += 1
if(DEBUG):
print("################## OUTER LOOP " + str(outer_iter) + " ######################")
print(model_idle_time)
t1 = datetime.now()
max_speed = road_map.get_max_speed()
if(DEBUG):
print("max speed = " + str(max_speed))
# Determine optimal routes for all trips, and predict the travel times
# This is the most costly part of each iteration
# l1_error stores the sum of all absolute errors
error_metric, avg_trip_error, avg_perc_error = predict_trip_times(road_map,
unique_trips, route=True, distance_weighting=distance_weighting,
model_idle_time=model_idle_time)
iter_avg_errors.append(avg_trip_error)
iter_perc_errors.append(avg_perc_error)
# If we have a test set, also evaluate the map on it
if(test_set != None):
test_l1_error, test_avg_trip_error, test_perc_error = predict_trip_times(
road_map, unique_test_trips, route=True, model_idle_time=model_idle_time)
test_avg_errors.append(test_avg_trip_error)
test_perc_errors.append(test_perc_error)
#Determine which links need to increase or decrease their travel time
compute_link_offsets(road_map, unique_trips, distance_weighting=distance_weighting)
t2 = datetime.now()
if(DEBUG):
print("Time to route: " + str(t2 - t1))
eps = .2 # The step size
outer_loop_again = False # Start optimistic - this might be the last iteration
# The results of the inner loop may tell us that we need to loop again
# Inner loop - use errors on Trips to refine the Links' travel times
# We will try making a small step, but will make it even smaller if we overshoot
# The inner loop stops if we find a step that makes an improvement, or the step size gets too small
# A small step size will also trigger the outer loop to stop
while(eps > .0001):
if(DEBUG):
print("Taking a step at eps=" + str(eps))
#Inner Loop Step 1 - propose new travel times on the links
#Links with a positive offset are systematically overestimated - travel times should be decreased
#Links with a negative offset are systematically underestiamted - travel times should be increased
for link in road_map.links:
if(DEBUG and link==road_map.idle_link):
print("***** " + str(link.offset))
if(link.offset > 0):
link.proposed_time = link.time / (1 + eps)
elif(link.offset < 0):
link.proposed_time = link.time * (1 + eps)
else:
link.proposed_time = link.time
#Constrain the travel time to a physically realistic value
if(link != road_map.idle_link):
link.proposed_time = max(link.proposed_time, link.length/MAX_SPEED)
# Inner Loop Step 2 - Evaluate proposed travel times in terms of L1 error
# Use routes to predict travel times for trips
# We do not compute new routes yet (route=False), we use the existing ones
new_error_metric, new_avg_trip_error, new_avg_perc_error = predict_trip_times(
road_map, unique_trips, route=False, proposed=True, max_speed=0,
distance_weighting=distance_weighting, model_idle_time=model_idle_time)
if(DEBUG):
print("Old L1 = " + str(error_metric))
print("New L1 = " + str(new_error_metric))
print("Avg = " + str(avg_trip_error))
# Inner Loop Step 3 - Accept the change if it is an improvement
if(new_error_metric < error_metric):
if(DEBUG):
print("Accepting")
# The step decreased the error - accept it!
for link in road_map.links:
if(DEBUG and link==road_map.idle_link):
print (">>>" + str(link.proposed_time))
link.time = link.proposed_time
# Now that the travel times have changed, we need to route the trips again
outer_loop_again = True
break
else:
# The step increased the error - reject it!
# This means we overshot - retry with a smaller step size
eps *= .75
#Compute the final error metrics after the last iteration
error_metric, avg_trip_error, avg_perc_error = predict_trip_times(road_map, unique_trips, route=False, max_speed=0)
iter_avg_errors.append(avg_trip_error)
iter_perc_errors.append(avg_perc_error)
# If we have a test set, also evaluate the map on it
if(test_set != None):
test_l1_error, test_avg_trip_error, test_perc_error = predict_trip_times(road_map, unique_test_trips, route=True)
test_avg_errors.append(test_avg_trip_error)
test_perc_errors.append(test_perc_error)
return (iter_avg_errors, iter_perc_errors, test_avg_errors, test_perc_errors)
def load_trips(filename, limit=float('inf')):
trips = []
with open(filename, "r") as f:
reader = csv.reader(f)
reader.next()
for line in reader:
trips.append(Trip(line))
if(len(trips) >= limit):
break
return trips
def test_on_small_sample():
print("Loading trips")
trips = load_trips("sample_2.csv", 20000)
print("We have " + str(len(trips)) + " trips")
print("Loading map")
nyc_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv")
print("Estimating travel times")
estimate_travel_times(nyc_map, trips)
def plot_unique_trips():
from matplotlib import pyplot as plt
trip_lookup = {}
print("Loading map")
road_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv")
print("Matching nodes")
sizes = []
with open("sample.csv", "r") as f:
reader = csv.reader(f)
reader.next()
for line in reader:
trip = Trip(line)
trip.num_occurrences = 1
trip.origin_node = road_map.get_nearest_node(trip.fromLat, trip.fromLon)
trip.dest_node = road_map.get_nearest_node(trip.toLat, trip.toLon)
if((trip.origin_node, trip.dest_node) in trip_lookup):
#Already seen this trip at least once
trip_lookup[trip.origin_node, trip.dest_node].num_occurrences += 1
elif trip.origin_node !=None and trip.dest_node != None:
#Never seen this trip before
trip_lookup[trip.origin_node, trip.dest_node] = trip
sizes.append(len(trip_lookup))
plt.plot(range(len(sizes)), sizes)
plt.xlabel("Inner Loop Iteration")
plt.ylabel("L1 Error (sec)")
fig = plt.gcf()
fig.set_size_inches(20,10)
fig.savefig('test2png.png',dpi=100)
#Make unique trips into a list and return
new_trips = [trip_lookup[key] for key in trip_lookup]
return new_trips
def test_parallel_routing():
pool = Pool(8)
for cpus in range(1,9):
if(cpus>1):
pool = Pool(cpus)
else:
pool = None
print("Loading trips")
trips = load_trips("sample_3.csv", 100000)
print("We have " + str(len(trips)) + " trips")
print("Loading map")
nyc_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv")
print("Map-matching trips")
unique_trips = nyc_map.match_trips_to_nodes(trips)
print ("**** Running with " + str(cpus) + " CPUs")
d1 = datetime.now()
predict_trip_times(nyc_map, unique_trips, route=True, proposed=False, max_speed = None,
distance_weighting=None, pool=pool)
d2 = datetime.now()
print ("**** " + str(d2 - d1))
if(pool!=None):
pool.terminate()
del pool
del trips
del nyc_map
del unique_trips
del d1
del d2
if(__name__=="__main__"):
t1 = datetime.now()
test_parallel_routing()
t2 = datetime.now()
print("TOTAL TIME = " + str(t2 - t1))
#plot_unique_trips()
|
C++ | UTF-8 | 476 | 2.96875 | 3 | [] | no_license | /*****************************************************
PROGRAMA QUE CALCULA LA VELOCIDAD DE UNA PARTICULA
Nombre: Nicolás Cano Botero
MARZO 22/2021
******************************************************/
#include <iostream>
using namespace std;
int main ()
{
float d , t;
float velocidad;
cout<< "Ingresar la distancia: ";
cin>> d;
cout<< "Ingresar el tiempo: ";
cin>> t;
velocidad = (d/t);
cout<< "La velocidad es: " << velocidad << "m/s";
} |
Java | UTF-8 | 2,848 | 2.875 | 3 | [] | no_license | package StudentBAL;
import StudentBean.CourseBean;
import connection.DBConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CourseBal {
DBConnection con = new DBConnection();
CourseBean courseBean = null;
Connection connect = con.getConnection();
public ArrayList<CourseBean> getCourses() {
ArrayList<CourseBean> arrLst = new ArrayList<CourseBean>();
try {
Statement stat = connect.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM courses");
while (rs.next()) {
courseBean = new CourseBean(rs.getInt(1), rs.getString(2));
arrLst.add(courseBean);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return arrLst;
}
public void insertCourses(String course) {
try {
Statement createStatement = connect.createStatement();
int check = createStatement.executeUpdate("INSERT INTO courses (`Course Name`) VALUES ('"+course+"');");
if (check == 1) {
JOptionPane.showMessageDialog(null, "Course Added Successfully");
} else {
JOptionPane.showMessageDialog(null, "UnSuccessful");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public void updateCourse(CourseBean courseBean) {
try {
Statement createStatement = connect.createStatement();
int check = createStatement.executeUpdate("UPDATE courses SET `Course Name` = '"+courseBean.getCourseName()+"' WHERE `Course ID` = '"+courseBean.getId()+"';");
if (check == 1) {
JOptionPane.showMessageDialog(null, "Course Updated Successfully");
} else {
JOptionPane.showMessageDialog(null, "UnSuccessful");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public void deleteCourse(int id){
try {
Statement createStatement = connect.createStatement();
int check = createStatement.executeUpdate("DELETE FROM courses WHERE `Course ID` = '"+id+"';");
if (check == 1) {
JOptionPane.showMessageDialog(null, "Course Deleted Successfully");
} else {
JOptionPane.showMessageDialog(null, "UnSuccessful");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
|
Python | UTF-8 | 1,356 | 2.953125 | 3 | [] | no_license |
# coding: utf-8
# In[141]:
import math
from collections import Counter
import pandas as pd
import numpy as np
import os
import sys
import getopt
import csv
def entropy_single(seq):
seq=seq.upper()
num, length = Counter(seq), len(seq)
return -sum( freq/length * math.log(freq/length, 2) for freq in num.values())
def se(filename,outt):
data=list((pd.read_csv(filename,sep=',',header=None)).iloc[:,0])
# print(data)
Val=[]
header=["Shannon-Entropy"]
for i in range(len(data)):
data1=''
data1=str(data[i])
data1=data1.upper()
allowed = set(('A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'))
is_data_invalid = set(data1).issubset(allowed)
if is_data_invalid==False:
print("Error: Please check for invalid inputs in the sequence.","\nError in: ","Sequence number=",i+1,",","Sequence = ",data[i],",","\nNOTE: Spaces, Special characters('[@_!#$%^&*()<>?/\|}{~:]') and Extra characters(BJOUXZ) should not be there.")
return
Val.append(round((entropy_single(str(data[i]))),3))
#print(Val[i])
file= open(outt,'w', newline='\n')#output file
with file:
writer=csv.writer(file,delimiter='\n');
writer.writerow(header)
writer.writerow(Val);
return Val
|
Markdown | UTF-8 | 613 | 2.90625 | 3 | [] | no_license | # BangDreamSongRandom
[NOT FOR SALE] Just random data in an Excel file
<br><br>
Directory Structure:
<br>
|SomeFolder <br>
|-------|BandoriRandomSong.exe <-- Run this file<br>
|-------|src <br>
|-------|---|song_list.xlsx
<br><br>
=== GUI ===<br>

<br><br>
=== HOW TO USE === <br>
1.Set songs in an excel file (path: src/song_list.xlsx) <br>
2.Double click [BandoriRandomSong.exe] for use the program <br>
3.Click [Random Now] button <br>
4.Enjoy !
<br><br>
P.S. In the Version 1.0 is terrible programming structure and bad design because I didn't plan anything before develop it. Sorry.
|
Java | UTF-8 | 2,607 | 2.265625 | 2 | [] | no_license | package com.cdancy.jenkins.rest.domain.job;
import org.jclouds.javax.annotation.Nullable;
import javax.annotation.Generated;
/**
* @author: seal
* @Description:
* @company: xingfeiinc
* @e-mail: linxiao@xingfeiinc.com
* @date: 2018-10-29 16:50
*/
@Generated("com.google.auto.value.processor.AutoValueProcessor")
final class AutoValue_Cause extends Cause {
private final String clazz;
private final String shortDescription;
private final String userId;
private final String userName;
AutoValue_Cause(
@Nullable String clazz,
String shortDescription,
@Nullable String userId,
@Nullable String userName) {
this.clazz = clazz;
if (shortDescription == null) {
throw new NullPointerException("Null shortDescription");
}
this.shortDescription = shortDescription;
this.userId = userId;
this.userName = userName;
}
@Nullable
@Override
public String clazz() {
return clazz;
}
@Override
public String shortDescription() {
return shortDescription;
}
@Nullable
@Override
public String userId() {
return userId;
}
@Nullable
@Override
public String userName() {
return userName;
}
@Override
public String toString() {
return "Cause{"
+ "clazz=" + clazz + ", "
+ "shortDescription=" + shortDescription + ", "
+ "userId=" + userId + ", "
+ "userName=" + userName
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Cause) {
Cause that = (Cause) o;
return ((this.clazz == null) ? (that.clazz() == null) : this.clazz.equals(that.clazz()))
&& (this.shortDescription.equals(that.shortDescription()))
&& ((this.userId == null) ? (that.userId() == null) : this.userId.equals(that.userId()))
&& ((this.userName == null) ? (that.userName() == null) : this.userName.equals(that.userName()));
}
return false;
}
@Override
public int hashCode() {
int h$ = 1;
h$ *= 1000003;
h$ ^= (clazz == null) ? 0 : clazz.hashCode();
h$ *= 1000003;
h$ ^= shortDescription.hashCode();
h$ *= 1000003;
h$ ^= (userId == null) ? 0 : userId.hashCode();
h$ *= 1000003;
h$ ^= (userName == null) ? 0 : userName.hashCode();
return h$;
}
}
|
Python | UTF-8 | 9,990 | 2.59375 | 3 | [] | no_license | __author__ = 'kevin'
# import statistics as stat
import networkx as nx
import os
from attacksurfacemeter.call import Call
from attacksurfacemeter.call_graph import CallGraph
from attacksurfacemeter.environments import Environments
from attacksurfacemeter.loaders.javacg_loader import JavaCGLoader
class AndroidCallGraph(CallGraph):
"""
Represents the Call Graph of a software system.
Encapsulates a graph data structure where each node is a method/function call.
Attributes:
source: String that contains where the source code that this Call Graph represents comes from.
call_graph: networkx.DiGraph. Internal representation of the graph data structure.
"""
_android_override_input_methods = []
_android_override_output_methods = []
_android_black_list_packages = []
_android_black_list_edges = []
def __init__(self, source, graph, generation_errors=None):
"""
CallGraph constructor
Instantiates a new CallGraph object and generates a networkx.DiGraph representing the Call Graph of
a program.
Args:
source: String that contains where the source code that this Call Graph represents comes from.
graph: networkx.DiGraph. Internal representation of the graph data structure.
Returns:
A new instance of type CallGraph.
"""
self.source = source
self.call_graph = graph
self.errors = generation_errors
self._entry_points = set()
self._exit_points = set()
self._execution_paths = list()
@staticmethod
def _load_function_list(function_list_file):
file_name = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', function_list_file)
with open(file_name) as f:
functions = f.read().splitlines()
return functions
@staticmethod
def _get_android_override_input_methods():
if not AndroidCallGraph._android_override_input_methods:
AndroidCallGraph._android_override_input_methods = AndroidCallGraph._load_function_list("android_override_input_methods")
return AndroidCallGraph._android_override_input_methods
@staticmethod
def _get_android_override_output_methods():
if not AndroidCallGraph._android_override_output_methods:
AndroidCallGraph._android_override_output_methods = AndroidCallGraph._load_function_list("android_override_output_methods")
return AndroidCallGraph._android_override_output_methods
@staticmethod
def _get_android_edge_black_list():
if not AndroidCallGraph._android_black_list_edges:
file_name = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data", "android_edge_black_list_extended")
black_list_call_graph = AndroidCallGraph.from_loader(JavaCGLoader(file_name))
AndroidCallGraph._android_black_list_edges = black_list_call_graph.edges
return AndroidCallGraph._android_black_list_edges
@staticmethod
def _load_android_package_black_list():
if not AndroidCallGraph._android_black_list_packages:
AndroidCallGraph._android_black_list_packages = AndroidCallGraph._load_function_list("android_package_black_list")
return AndroidCallGraph._android_black_list_packages
def calculate_entry_and_exit_points(self):
self._calculate_entry_and_exit_points()
override_input_methods = [m.split('.')[-1] for m in AndroidCallGraph._get_android_override_input_methods()]
entry_points_to_add = {n: n for n in self.call_graph.nodes() if n.function_name in override_input_methods}
self._entry_points = AndroidCallGraph._merge_dicts(self._entry_points, entry_points_to_add)
override_output_methods = [m.split('.')[-1] for m in AndroidCallGraph._get_android_override_output_methods()]
exit_points_to_add = {n: n for n in self.call_graph.nodes() if n.function_name in override_output_methods}
self._exit_points = AndroidCallGraph._merge_dicts(self._exit_points, exit_points_to_add)
@staticmethod
def _merge_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy.
"""
z = x.copy()
z.update(y)
return z
def calculate_attack_surface_nodes(self):
# Sub-graphing only those nodes connected to the attack surface
attack_surface_nodes = set()
for en in self.entry_points:
attack_surface_nodes.add(en)
for des in self.get_descendants(en):
attack_surface_nodes.add(des)
for ex in self.exit_points:
attack_surface_nodes.add(ex)
for anc in self.get_ancestors(ex):
attack_surface_nodes.add(anc)
self.attack_surface_graph = nx.subgraph(self.call_graph, attack_surface_nodes)
def collapse_android_black_listed_edges(self):
"""
Collapses all black listed edges into package nodes. It is important to call this meethod
before any further manipulation (via the collapse_android_black_listed_packages method)
because this way we make sure that all black listed edges get collapsed and we don't end up
collapsing. Also, this way we ignore any input/output method that appears in the black listed
nodes so that they don't appear in the metrics.
"""
get_hash = lambda edge_to_hash: str(hash(edge_to_hash[0])) + str(hash(edge_to_hash[1]))
black_listed_edges = AndroidCallGraph._get_android_edge_black_list()
black_listed_edges = {get_hash(e): True for e in black_listed_edges}
nodes_to_remove = set()
edges_to_remove = []
edges_to_add = []
black_list_nodes = dict()
for edge in self.call_graph.edges():
caller, callee = edge
caller_id = hash(caller)
callee_id = hash(callee)
edge_id = get_hash(edge)
edge_is_in_black_list = edge_id in black_listed_edges
if edge_is_in_black_list:
edges_to_remove.append(edge)
caller_package_node = Call(caller.package_name, "package_node", Environments.ANDROID)
callee_package_node = Call(callee.package_name, "package_node", Environments.ANDROID)
edges_to_add.append((caller_package_node, callee_package_node))
# A node can only be removed if all its edges are in the black list.
# After the collapse process, nodes whose edges are all in the black
# list would be totally disconnected and substituted by their respective
# package node. We need to remove those.
if caller_id not in black_list_nodes:
black_list_nodes[caller_id] = {
'node': caller,
'all_edges_black_list': True
}
if callee_id not in black_list_nodes:
black_list_nodes[callee_id] = {
'node': callee,
'all_edges_black_list': True
}
if caller_id in black_list_nodes:
if not edge_is_in_black_list:
black_list_nodes[caller_id]['all_edges_black_list'] = False
if callee_id in black_list_nodes:
if not edge_is_in_black_list:
black_list_nodes[callee_id]['all_edges_black_list'] = False
for node_id, black_list_node in black_list_nodes.items():
if black_list_node['all_edges_black_list']:
nodes_to_remove.add(black_list_node['node'])
self.call_graph.remove_edges_from(edges_to_remove)
self.call_graph.remove_nodes_from(nodes_to_remove)
self.call_graph.add_edges_from(edges_to_add)
# Use this if planing to create a gml to open with gephi
# for e in edges_to_add:
# edge_data = self.call_graph.get_edge_data(*e)
#
# if not edge_data:
# self.call_graph.add_edge(*e, weight=1)
# else:
# self.call_graph.add_edge(*e, weight=edge_data["weight"] + 1)
def collapse_android_black_listed_packages(self):
black_listed_packages = AndroidCallGraph._load_android_package_black_list()
nodes_to_remove = set()
edges_to_remove = []
edges_to_add = []
for edge in self.call_graph.edges():
caller, callee = edge
if not (caller.is_input_function() or caller.is_output_function() or
callee.is_input_function() or callee.is_output_function()):
if caller.package_name in black_listed_packages and callee.package_name in black_listed_packages:
edges_to_remove.append(edge)
nodes_to_remove.add(caller)
nodes_to_remove.add(callee)
edges_to_add.append((caller.package_name, callee.package_name))
elif caller.package_name in black_listed_packages:
edges_to_remove.append(edge)
nodes_to_remove.add(caller)
edges_to_add.append((caller.package_name, callee))
elif callee.package_name in black_listed_packages:
edges_to_remove.append(edge)
nodes_to_remove.add(callee)
edges_to_add.append((caller, callee.package_name))
self.call_graph.remove_edges_from(edges_to_remove)
self.call_graph.remove_nodes_from(nodes_to_remove)
for e in edges_to_add:
edge_data = self.call_graph.get_edge_data(*e)
if not edge_data:
self.call_graph.add_edge(*e, weight=1)
else:
self.call_graph.add_edge(*e, weight=edge_data["weight"] + 1) |
Python | UTF-8 | 276 | 2.890625 | 3 | [] | no_license | # https://github.com/joaohelis/n_ary_tree_with_python/blob/master/n_ary_tree.py
from trees.n_ary_trees.Node import Node
class NAryTree(Node):
def __init__(self):
self.root = None
self.size = 0
def insert(self, key, parent_key):
pass |
C++ | UTF-8 | 908 | 2.96875 | 3 | [] | no_license | #include "CircularIslandMaskFilter.hh"
CircularIslandMaskFilter::CircularIslandMaskFilter(float innerRadius, float outerRadius, PerlinNoiseGenerator &perlin):
mPerlin(perlin),
mInnerRadius(innerRadius / 2.0f),
mOuterRadius(outerRadius / 2.0f)
{
}
double CircularIslandMaskFilter::filter(double x, double y, double val)
{
glm::vec2 center(0.5, 0.5);
glm::vec2 directionVector = glm::vec2(x, y) - center;
glm::vec2 normalizedDir = glm::normalize(directionVector);
/// @todo Decide if even needed. Looks plausable even without the perlin component
double perlinSample = mPerlin.noise(normalizedDir.x, normalizedDir.y, 0.6);
float length = glm::length(directionVector);
if(length < mInnerRadius)
return val;
else if(length < mOuterRadius)
{
return val * glm::smoothstep(mOuterRadius, mInnerRadius, length);
}
else
return 0;
}
|
Java | UTF-8 | 3,440 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | package java_hadoop.chapter9;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java_hadoop.chapter6.NcdcRecordParser;
import java_hadoop.chapter8.JobBuilder;
import java_hadoop.chapter9.MaxTemperatureUsingSecondarySort.MaxTemperatureReducer;
/**
* Example 9-13. Application to find the maximum temperature by station, showing station names from a lookup table passed as a distributed cache file
*
* @author liuzhao
*
*/
public class MaxTemperatureByStationNameUsingDistributedCacheFile extends Configured implements Tool {
static class StationTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private NcdcRecordParser parser = new NcdcRecordParser();
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
parser.parse(value);
if (parser.isValidTemperature()) {
context.write(new Text(parser.getStationId()), new IntWritable(parser.getAirTemperature()));
}
}
}
static class MaxTemperatureReducerWithStationLookup extends Reducer<Text, IntWritable, Text, IntWritable> {
private NcdcStationMetadata metadata;
@Override
protected void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
String stationName = metadata.getStationName(key.toString());
int maxValue = Integer.MIN_VALUE;
for (IntWritable value : values) {
maxValue = Math.max(maxValue, value.get());
}
context.write(new Text(stationName), new IntWritable(maxValue));
}
@Override
protected void setup(Reducer<Text, IntWritable, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
metadata = new NcdcStationMetadata();
metadata.initialize(new File("stations-fixed-width.txt"));
}
}
@Override
public int run(String[] args) throws Exception {
Job job = JobBuilder.parseInputAndOuput(this, getConf(), args);
if (job == null) {
return -1;
}
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(StationTemperatureMapper.class);
job.setCombinerClass(MaxTemperatureReducer.class);
job.setReducerClass(MaxTemperatureReducerWithStationLookup.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new MaxTemperatureByStationNameUsingDistributedCacheFile(), args);
System.exit(exitCode);
}
}
class NcdcStationMetadata {
public void initialize(File file) {
// TODO Auto-generated method stub
}
public String getStationName(String key) {
// TODO Auto-generated method stub
return null;
}
}
//bin/hadoop jar ~/workspace/GitHub/java_hadoop/target/java_hadoop-0.0.1-SNAPSHOT.jar java_hadoop.chapter9.MaxTemperatureByStationNameUsingDistributedCacheFile -conf conf/hadoop-local.xml -files test/input/ncdc/metadata/stations-fixed-width.txt test/input/ncdc/all test/output |
SQL | UTF-8 | 755 | 2.53125 | 3 | [] | no_license | --1----------------
declare
v_date date;
v_no number:=10;
v_name varchar2(100) not null:='khaled'; --when you use not null then you should give value
begin
dbms_output.put_line(v_date);
dbms_output.put_line(v_no);
dbms_output.put_line(v_name);
v_no:=v_no+10;
v_name:='carla';
dbms_output.put_line(v_name);
v_date:='10-May-2012';
dbms_output.put_line(v_date);
dbms_output.put_line(v_no);
end;
----------------------------------
--2---------
declare
v_date date:=sysdate;
v_no number:=10*2;
v_pi constant number:= 3.14;
begin
dbms_output.put_line(v_date);
dbms_output.put_line(v_no);
dbms_output.put_line(v_pi);
v_date:=v_date+10;
dbms_output.put_line(v_date);
--v_pi:=10; if you try to do this then you will get error;
end;
----------------------------
|
Python | UTF-8 | 11,299 | 2.828125 | 3 | [] | no_license | #/usr/bin/python3
#~/anaconda3/bin/python
'''This module takes a list of barcodes as input. It searches ArchivesSpace and
Voyager for those barcodes and returns collection information. This application
is used for Yale MSSA's LSF transfer process.'''
import csv
import json
import logging
import sys
import os
from time import time, sleep
from subprocess import call as sc_call
import requests
from tqdm import tqdm
#TODO: Implement asyncio, add config file; put in a class
def keeptime(start):
'''Tracks time it takes functio to run and records in output log'''
elapsedtime = time() - start
minutes, seconds = divmod(elapsedtime, 60)
hours, minutes = divmod(minutes, 60)
logging.debug('%d:%02d:%02d' % (hours, minutes, seconds))
def open_outfile(filepath):
'''Opens the log file and output file after the function finishes'''
if sys.platform == "win32":
os.startfile(filepath)
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
sc_call([opener, filepath])
def error_log():
'''Creates a basic logger for this program'''
if sys.platform == "win32":
logger = '\\Windows\\Temp\\error_log.log'
else:
logger = '/tmp/error_log.log'
logging.basicConfig(filename=logger, level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
return logger
def login():
'''Logs in to the ArchivesSpace API'''
try:
url = input('Please enter the ArchivesSpace API URL: ')
username = input('Please enter your username: ')
password = input('Please enter your password: ')
auth = requests.post(url+'/users/'+username+'/login?password='+password).json()
#if session object is returned then login was successful; if not it failed.
if 'session' in auth:
session = auth["session"]
headers = {'X-ArchivesSpace-Session':session, 'Content_Type': 'application/json'}
print('\nLogin successful!\n')
logging.debug('Success!')
else:
print('\nLogin failed! Check credentials and try again\n')
logging.debug('Login failed')
logging.debug(auth.get('error'))
url, headers = login()
return url, headers
except Exception:
print('\nLogin failed! Check credentials and try again!\n')
logging.exception('Error: ')
url_recurse, headers_recurse = login()
return url_recurse, headers_recurse
#Open a CSV in reader mode
#CHANGE THIS TO JUST BE A LIST...
def opencsv():
'''Opens a CSV input file as a list'''
try:
input_csv = input('Please enter path to CSV: ')
file = open(input_csv, 'r', encoding='utf-8')
#I want this as a list not a generator since it's relatively
#small and need the length for the tqdm counter
csvlist = [[barcode.strip()] for barcode in file.readlines() if 'barcode' not in barcode]
return (input_csv, csvlist)
except Exception:
logging.exception('Error: ')
logging.debug('Trying again...')
print('\nCSV not found. Please try again.\n')
input_csv_recurse, csvlist_recurse = opencsv()
return (input_csv_recurse, csvlist_recurse)
def set_repository(api_url, headers):
'''Lets the user select their repository'''
try:
repo_data = requests.get(api_url + '/repositories').json()
repo_list = [[repo['name'], repo['uri'].replace('/repositories/', '')] for repo in repo_data]
print('\n')
for repo_name, repo_number in repo_list:
print(f'{repo_number}: {repo_name}')
print('\n')
repository_number = input('Please enter repository number from list above: ')
return repository_number
except Exception:
logging.exception('Error: ')
def opencsvout(infilename):
'''Opens a CSV outfile in writer mode'''
try:
output_csv = infilename[:-4] + '_outfile.csv'
fileob = open(output_csv, 'a', encoding='utf-8', newline='')
csvout = csv.writer(fileob)
return (output_csv, fileob, csvout)
except Exception:
logging.exception('Error: ')
print('\nError creating outfile. Please try again.\n')
infile_recurse, fileob_recurse, csvout_recurse = opencsvout(infilename)
return (infile_recurse, fileob_recurse, csvout_recurse)
def search_voyager_helper(item_data, voyager_url, get_bib_item_ep, barcode):
'''Processes results from Voyager search, searches bib data endpoint
for title information.'''
try:
bib_id = item_data['bibid']
call_number = item_data['callno']
location = item_data['locname']
if 'itemenum' in item_data:
#would want to split this eventually
box_num = item_data['itemenum']
series = 'see container_number field'
container_profile = 'see container_number field'
else:
box_num = 'no_box_number'
series = 'no_series'
container_profile = 'no_container_profile'
#there should not be more than one result here, for sure...
search_bib_item = requests.get(voyager_url + get_bib_item_ep + bib_id).json()
#is this good? Any time this wouldn't work?
title = search_bib_item['record'][0]['title']
return [barcode, series, call_number, box_num, title, container_profile, location]
# do better
except Exception:
logging.exception('Error: ')
#should this return something?
def search_voyager(barcode, voyager_url, get_item_ep, get_bib_item_ep):
'''Searches Voyager for a barcode and retrieves item information.'''
search_item = requests.get(voyager_url + get_item_ep + barcode).json()
if search_item == {'items': [{'barcode': 'NA'}]}:
result = [barcode, 'No results found in AS or Voyager']
else:
#this assumes that there is only one result for the barcode
#- which should be the case, I think...
if len(search_item['items']) == 1:
item_data = search_item['items'][0]
else:
for i, item in enumerate(search_item['items']):
if item['barcode'] == barcode:
item_data = search_item['items'][i]
result = search_voyager_helper(item_data, voyager_url, get_bib_item_ep, barcode)
return result
def as_search_processing(barcode, search):
'''Processes search results from ArchivesSpace API'''
#Searching identifier and title, which are both required fields
identifier = search['response']['docs'][0]['collection_identifier_stored_u_sstr'][0]
title = search['response']['docs'][0]['collection_display_string_u_sstr'][0]
#Checking for a series
if 'series_identifier_stored_u_sstr' in search['response']['docs'][0]:
series = search['response']['docs'][0]['series_identifier_stored_u_sstr'][0]
else:
series = 'no_series'
#logging.debug('No series. ' + str(search['response']['docs'][0]))
#Checking for container info
record_json = json.loads(search['response']['docs'][0]['json'])
#Indicator is a required field
container_number = record_json['indicator']
#Checking for a container profile
if 'container_profile_display_string_u_sstr' in search['response']['docs'][0]:
container_profile = search['response']['docs'][0]['container_profile_display_string_u_sstr'][0]
else:
container_profile = 'no_container_profile'
#logging.debug('No container profile. ' + str(search['response']['docs'][0]))
#Writing everything to the output CSV
if 'location_display_string_u_sstr' in search['response']['docs'][0]:
location_title = search['response']['docs'][0]['location_display_string_u_sstr'][0]
else:
location_title = 'no_location'
return [barcode, series, identifier, container_number, title, container_profile, location_title]
def search_barcodes(csvfile, csvoutfile, api_url, headers, voyager_url, get_item_ep, get_bib_item_ep, repo_num):
'''Loops through CSV list and searches ArchivesSpace. If record not
found in ArchivesSpace the function will search Voyager'''
for row in tqdm(csvfile, ncols=75):
barcode = row[0]
try:
logging.debug(barcode)
#f strings please
search = requests.get(api_url + '/repositories/' + repo_num + '/top_containers/search?q=barcode_u_sstr:' + barcode, headers=headers).json()
if search['response']['numFound'] != 0:
newrow = as_search_processing(barcode, search)
csvoutfile.writerow(newrow)
#elif here, or is this ok? Don't want to
else:
voyager_results = search_voyager(barcode, voyager_url, get_item_ep, get_bib_item_ep)
csvoutfile.writerow(voyager_results)
#do better
except Exception:
#print('Error! Could not retrieve record ' + str(row))
logging.exception('Error: ')
#logging.debug(str(search))
row.append('ERROR')
csvoutfile.writerow(row)
#print("\n\nCredit: program icon was made by http://www.freepik.com on https://www.flaticon.com/ and is licensed by Creative Commons BY 3.0 (CC 3.0 BY")
def main():
'''Main function'''
print('''\n\n
#################################################
#################################################
#################### HELLO! ###################
#################################################
##### WELCOME TO THE LSF TRANSFER BARCODE #####
##### LOOKUP TOOL! #####
#################################################
#################################################
\n\n''')
sleep(1)
print(" Let's get started!\n\n")
sleep(1)
barcode_logfile = error_log()
starttime = time()
logging.debug('Connecting to ArchivesSpace API...')
api_url, headers = login()
#logging.debug('Opening barcode file...')
ininput_string, csvfile = opencsv()
#logging.debug('Opening output file...')
repo_num = set_repository(api_url, headers)
input_string, fileobject, csvoutfile = opencsvout(ininput_string)
csv_headers = ['barcode', 'series', 'identifier', 'container_number', 'title', 'container_profile', 'location']
csvoutfile.writerow(csv_headers)
#I think this should all be in a class fr
voy_api_url = 'http://libapp.library.yale.edu/VoySearch/'
get_item = 'GetItem?barcode='
get_bib_item = 'GetBibItem?bibid='
print('\nPlease wait a moment...\n')
search_barcodes(csvfile, csvoutfile, api_url, headers, voy_api_url, get_item, get_bib_item, repo_num)
fileobject.close()
keeptime(starttime)
logging.debug('All Done!')
print('\nAll Done!')
open_outfile(input_string)
open_outfile(barcode_logfile)
if __name__ == "__main__":
main()
|
Python | UTF-8 | 4,215 | 2.859375 | 3 | [
"MIT"
] | permissive | # -*- coding:utf-8 -*-
import numpy as np
from scipy.stats import multinomial
from scipy.stats import dirichlet
def cumulative_algorithm(p: list) -> int:
p = np.array(p)
for i in range(1, len(p)):
p[i] = p[i-1] + p[i]
u = np.random.uniform(0, 1) * p[-1]
i = 0
while i < len(p):
if p[i] > u:
break
i += 1
return i
sport_list = np.array(["basketball", "football", "tennis", "volleyball"])
policy_list = np.array(["China", "USA", "Japan", "trade"])
science_list = np.array(["paper", "academic", "university"])
test_doc = [sport_list, policy_list, science_list]
class LatentDirichletAllocation:
def __init__(self):
# 文档数量M 主题数量K 单词数量 V
self.M, self.K, self.V = -1, -1, -1
# 文档-主题的Dirichlet分布参数 主题-单词的Dirichlet分布参数
self.alpha, self.beta = -1, -1
# 文档-主题的分布矩阵 主题-单词的分布矩阵
self.theta, self.phi = -1, -1
# 通过word_id查询word 通过word查询word_id
self.word_dict, self.word_inv_dict = {}, {}
pass
def build_word_dict(self, doc):
tmp_w_list = []
for doc_item in doc:
tmp_w_list.extend(list(set(doc_item)))
w_list = list(set(tmp_w_list))
self.V = len(w_list)
self.M = len(doc)
self.word_dict = {i: w for i, w in enumerate(w_list)}
self.word_inv_dict = {w: i for w, i in enumerate(w_list)}
def generate(self, alpha, beta, n, k,):
dirichlet()
pass
def collapsed_gibbs_sampling(self, doc, k: int, alpha, beta, iter_num):
""" 创建计数矩阵和计数向量 """
doc_topic_mat = np.zeros([self.M, self.K]) # 文本-话题频率矩阵
topic_word_mat = np.zeros([self.K, self.V]) # 话题-单词频率矩阵
doc_topic_vector = np.zeros([self.M]) # 文本-话题和 向量
topic_word_vector = np.zeros([self.K]) # 话题-单词和 向量
word_topic_mapping = np.zeros_like(doc) # 记录每个文本中每个单词对应的主题
z = np.array([self.M])
""" 初始化计数矩阵和计数向量
对给定的所有文本的单词序列 每个位置上随机指派一个话题 整体构成所有文本的话题序列
"""
for (doc_id, doc_item) in enumerate(doc): # 遍历所有文本
for (word_id, word) in enumerate(doc_item): # 遍历所有单词
# 查询word对应的word_index
word_index = self.word_inv_dict[word]
# 从均匀分布中抽样一个话题 得到topic_id
topic_id = np.random.randint(0, self.K)
# 记录当前文本对应的主题
word_topic_mapping[doc_id, word_id] = topic_id
# 根据采样出的话题,更新四个计数单元
doc_topic_mat[doc_id, topic_id] += 1
topic_word_mat[topic_id, word_index] += 1
doc_topic_vector[doc_id] += 1
topic_word_vector[topic_id] += 1
""" 燃烧期准备
在每一个位置上计算在该位置上的话题的 满条件概率分布
然后进行随机抽样 得到该位置的新的话题 分派给这个位置
"""
for (doc_id, doc_item) in enumerate(doc): # 遍历所有文本
for (word_id, word) in enumerate(doc_item): # 遍历所有单词
# 查询word对应的word_index和topic_id
word_index = self.word_inv_dict[word]
topic_id = word_topic_mapping[doc_id, word_id]
# 根据当前单词对应的话题,更新四个计数单元
doc_topic_mat[doc_id, topic_id] -= 1
topic_word_mat[topic_id, word_index] -= 1
doc_topic_vector[doc_id] -= 1
topic_word_vector[topic_id] -= 1
# 按照 满条件分布 进行抽样
topic_prob_list = self.full_condition_dist()
def full_condition_dist(self) -> list:
""" 按照满条件分布进行抽样 """
pass
if __name__ == '__main__':
pass |
SQL | UTF-8 | 16,555 | 2.75 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 29, 2018 at 07:12 PM
-- Server version: 10.1.25-MariaDB
-- PHP Version: 7.1.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pepproject`
--
-- --------------------------------------------------------
--
-- Table structure for table `conversations`
--
CREATE TABLE `conversations` (
`id` int(11) NOT NULL,
`sender_id` int(11) DEFAULT NULL,
`recipient_id` int(11) DEFAULT NULL,
`date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `conversations`
--
INSERT INTO `conversations` (`id`, `sender_id`, `recipient_id`, `date`) VALUES
(1, 9, 10, '2018-03-29 13:45:12'),
(2, 9, 1, '2018-03-29 17:55:27'),
(3, 9, 1, '2018-03-29 17:56:43'),
(4, 9, 10, '2018-03-29 17:57:46'),
(5, 9, 10, '2018-03-29 17:58:18'),
(6, 9, 10, '2018-03-29 18:00:43'),
(7, 9, 10, '2018-03-29 18:01:31'),
(8, 9, 10, '2018-03-29 18:05:56'),
(9, 9, 1, '2018-03-29 18:06:24'),
(10, 9, 1, '2018-03-29 18:09:13'),
(11, 9, 1, '2018-03-29 18:11:52'),
(12, 9, 1, '2018-03-29 18:12:37'),
(13, 9, 1, '2018-03-29 18:12:56'),
(14, 9, 1, '2018-03-29 18:13:53'),
(15, 9, 1, '2018-03-29 18:14:06'),
(16, 9, 1, '2018-03-29 18:17:02'),
(17, 9, 1, '2018-03-29 18:18:54'),
(18, 9, 1, '2018-03-29 18:20:46'),
(19, 9, 1, '2018-03-29 18:21:26'),
(20, 9, 1, '2018-03-29 18:22:13');
-- --------------------------------------------------------
--
-- Table structure for table `currency`
--
CREATE TABLE `currency` (
`id` int(11) NOT NULL,
`currency` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`abbrevation` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `groups`
--
CREATE TABLE `groups` (
`id` int(11) NOT NULL,
`name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`description` varchar(20) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `groups`
--
INSERT INTO `groups` (`id`, `name`, `description`) VALUES
(1, 'admin', 'Administrator'),
(2, 'members', 'General User');
-- --------------------------------------------------------
--
-- Table structure for table `kyc`
--
CREATE TABLE `kyc` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`idCard` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`comment` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`status` int(11) NOT NULL DEFAULT '0',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `kyc`
--
INSERT INTO `kyc` (`id`, `user_id`, `idCard`, `picture`, `comment`, `status`, `created`, `updated`) VALUES
(6, 10, 'uploads/images/kyc/1522253618635.jpg', 'uploads/images/kyc/1522253029322.PNG', NULL, 0, '2018-03-28 17:27:42', '2018-03-28 18:13:38'),
(14, NULL, NULL, 'uploads/images/kyc/1522251681575.jpg', NULL, 0, '2018-03-28 17:41:21', NULL),
(17, 9, 'uploads/images/kyc/1522254409548.PNG', 'uploads/images/kyc/1522254363578.jpg', NULL, 1, '2018-03-28 18:26:03', '2018-03-28 18:26:49');
-- --------------------------------------------------------
--
-- Table structure for table `login_attempts`
--
CREATE TABLE `login_attempts` (
`id` int(11) UNSIGNED NOT NULL,
`ip_address` varchar(45) NOT NULL,
`login` varchar(100) NOT NULL,
`time` int(11) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `messages`
--
CREATE TABLE `messages` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`message` longtext COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`video` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`document` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`date` datetime NOT NULL,
`is_broadcast` int(11) NOT NULL DEFAULT '0',
`subject` longtext COLLATE utf8_unicode_ci NOT NULL,
`conversation_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `messages`
--
INSERT INTO `messages` (`id`, `user_id`, `message`, `image`, `video`, `document`, `date`, `is_broadcast`, `subject`, `conversation_id`) VALUES
(1, NULL, '<p>dfdfdfdfd</p>', NULL, NULL, NULL, '2018-03-29 13:40:51', 0, 'dfdff', NULL),
(2, NULL, '<p>dfdfdd</p>', NULL, NULL, NULL, '2018-03-29 13:42:30', 0, 'rtrtrtt', NULL),
(3, NULL, '<p>sddsdsds</p>', NULL, NULL, NULL, '2018-03-29 13:45:12', 0, 'dfddf', NULL),
(4, NULL, '<p style=\"\">kjkjkjkjkjkjk</p>', NULL, NULL, NULL, '2018-03-29 17:49:15', 0, 'gffhghghffhgg', NULL),
(5, NULL, '<p style=\"\">ddkfdjhdjhfjdff</p>', NULL, NULL, NULL, '2018-03-29 17:56:43', 0, 'dfddfdfdf', 3),
(6, 9, '<p style=\"\">dfdfgfgfgfg</p>', NULL, NULL, NULL, '2018-03-29 18:05:56', 0, 'fgfgfgfgfgfgfg', 8),
(7, 9, '<p style=\"\">fgfggfgfgfgfg</p>', NULL, NULL, NULL, '2018-03-29 18:06:24', 0, 'lfkgkgfkkfg', 9),
(8, 9, '<p style=\"\">ddggdgdg</p>', NULL, NULL, NULL, '2018-03-29 18:09:13', 0, 'ggdgfgdg', 10),
(9, 9, '<p style=\"\">dfdfdfdf</p>', NULL, NULL, NULL, '2018-03-29 18:11:52', 0, 'dfdfdfdff', 11),
(10, 9, '<p style=\"\">dfdfddddf</p>', NULL, NULL, NULL, '2018-03-29 18:12:37', 1, 'sfsfsfsf', 12),
(11, 9, '<p style=\"\">sfdsfsfsdf</p>', NULL, NULL, NULL, '2018-03-29 18:12:56', 1, 'sfdsfsfs', 13),
(12, 9, '<p style=\"\">sfsdfsdfs</p>', NULL, NULL, NULL, '2018-03-29 18:13:53', 0, 'sfssf', 14),
(13, 9, '<p style=\"\">sfdsfdsfs</p>', NULL, NULL, NULL, '2018-03-29 18:14:06', 0, 'sfdsfsf', 15),
(14, 9, '<p style=\"\">ssfsfsfds</p>', NULL, NULL, NULL, '2018-03-29 18:17:02', 0, 'sdfggd', 16),
(15, 9, '<p style=\"\">sfdsfdfdgfgf</p>', NULL, NULL, NULL, '2018-03-29 18:18:54', 0, 'dfdfd', 17),
(16, 9, '<p style=\"\">dgdgfgdgdg</p>', NULL, NULL, NULL, '2018-03-29 18:20:46', 0, 'dffdgddg', 18),
(17, 9, '<p style=\"\">dgdfgfdgdg</p>', NULL, NULL, NULL, '2018-03-29 18:21:26', 0, 'fsdfsdfggd', 19),
(18, 9, '<p style=\"\">dfgdgdgdfg</p>', NULL, NULL, NULL, '2018-03-29 18:22:13', 0, 'ddfgdff', 20);
-- --------------------------------------------------------
--
-- Table structure for table `trade`
--
CREATE TABLE `trade` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`transactionId` int(11) NOT NULL,
`type` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`amount` double NOT NULL,
`rate` double NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` datetime DEFAULT NULL,
`buyCurrency_id` int(11) DEFAULT NULL,
`sellCurrency_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `transactions`
--
CREATE TABLE `transactions` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`trade_id` int(11) DEFAULT NULL,
`currency_id` int(11) DEFAULT NULL,
`transactionId` int(11) NOT NULL,
`type` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`amount` double NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`company` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`phone` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_on` datetime DEFAULT CURRENT_TIMESTAMP,
`last_login` datetime DEFAULT NULL,
`referral_id` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`active` int(11) NOT NULL DEFAULT '0',
`ip_address` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`activation_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`remember_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`forgotten_password_code` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`forgotten_password_time` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `email`, `first_name`, `last_name`, `company`, `phone`, `password`, `created_on`, `last_login`, `referral_id`, `active`, `ip_address`, `salt`, `activation_code`, `remember_code`, `forgotten_password_code`, `forgotten_password_time`) VALUES
(1, 'administrator', 'admin@admin.com', 'Admin', 'istrator', 'ADMIN', '0', '$2a$07$SeBknntpZror9uyftVopmu61qg0ms8Qv1yV6FG.kQOSM.9QhmTo36', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'a2wh97mnkjg', 1, '127.0.0.1', '', '', NULL, NULL, NULL),
(9, 'neontetras', 'swiftbird000@gmail.com', 'Kingsley', 'Anokam', NULL, '07063834927', '$2y$08$mbYMS9m1BI8h88OOrwujp.qm6EeTSK8EQyclcjanpKjilL52CtfMG', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'a2wh97mnkjg', 1, '::1', '', NULL, 'DWe4t93dY5TuS2l6JHxEr.', 'Fa63TXTMQppRzzfCfnbeju8d13f05ba3917b4a6c', 1522239819),
(10, 'oweowe', 'wew@oeor.com', 'Chima', 'Chima', NULL, '08093434423', '$2y$08$3OabJeQ032tGdBPoFM.M.e8I4oScFjT93NEC4jKPJ56LJ26ia2XWO', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 'ceQUaJVwsrdlo', 1, '::1', '', NULL, '8ta.WjxHaGtew1xXFL6wou', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `users_groups`
--
CREATE TABLE `users_groups` (
`user_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users_groups`
--
INSERT INTO `users_groups` (`user_id`, `group_id`) VALUES
(9, 2),
(10, 2);
-- --------------------------------------------------------
--
-- Table structure for table `wallet`
--
CREATE TABLE `wallet` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`currency` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`walletId` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`balance` double NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `conversations`
--
ALTER TABLE `conversations`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_C2521BF1F624B39D` (`sender_id`),
ADD KEY `IDX_C2521BF1E92F8F78` (`recipient_id`);
--
-- Indexes for table `currency`
--
ALTER TABLE `currency`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `groups`
--
ALTER TABLE `groups`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `kyc`
--
ALTER TABLE `kyc`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_91850F8EA76ED395` (`user_id`);
--
-- Indexes for table `login_attempts`
--
ALTER TABLE `login_attempts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_DB021E96A76ED395` (`user_id`),
ADD KEY `IDX_DB021E969AC0396` (`conversation_id`);
--
-- Indexes for table `trade`
--
ALTER TABLE `trade`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_7E1A4366A76ED395` (`user_id`),
ADD KEY `IDX_7E1A4366770FF9FC` (`buyCurrency_id`),
ADD KEY `IDX_7E1A4366A4A2AF17` (`sellCurrency_id`);
--
-- Indexes for table `transactions`
--
ALTER TABLE `transactions`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_EAA81A4CA76ED395` (`user_id`),
ADD KEY `IDX_EAA81A4CC2D9760` (`trade_id`),
ADD KEY `IDX_EAA81A4C38248176` (`currency_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_1483A5E9F85E0677` (`username`),
ADD UNIQUE KEY `UNIQ_1483A5E9E7927C74` (`email`),
ADD UNIQUE KEY `UNIQ_1483A5E9444F97DD` (`phone`);
--
-- Indexes for table `users_groups`
--
ALTER TABLE `users_groups`
ADD PRIMARY KEY (`user_id`,`group_id`),
ADD KEY `IDX_FF8AB7E0A76ED395` (`user_id`),
ADD KEY `IDX_FF8AB7E0FE54D947` (`group_id`);
--
-- Indexes for table `wallet`
--
ALTER TABLE `wallet`
ADD PRIMARY KEY (`id`),
ADD KEY `IDX_7C68921FA76ED395` (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `conversations`
--
ALTER TABLE `conversations`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `currency`
--
ALTER TABLE `currency`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `groups`
--
ALTER TABLE `groups`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `kyc`
--
ALTER TABLE `kyc`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT for table `login_attempts`
--
ALTER TABLE `login_attempts`
MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
--
-- AUTO_INCREMENT for table `trade`
--
ALTER TABLE `trade`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `transactions`
--
ALTER TABLE `transactions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `wallet`
--
ALTER TABLE `wallet`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `conversations`
--
ALTER TABLE `conversations`
ADD CONSTRAINT `FK_C2521BF1E92F8F78` FOREIGN KEY (`recipient_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `FK_C2521BF1F624B39D` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `kyc`
--
ALTER TABLE `kyc`
ADD CONSTRAINT `FK_91850F8EA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `messages`
--
ALTER TABLE `messages`
ADD CONSTRAINT `FK_DB021E969AC0396` FOREIGN KEY (`conversation_id`) REFERENCES `conversations` (`id`),
ADD CONSTRAINT `FK_DB021E96A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `trade`
--
ALTER TABLE `trade`
ADD CONSTRAINT `FK_7E1A4366770FF9FC` FOREIGN KEY (`buyCurrency_id`) REFERENCES `currency` (`id`),
ADD CONSTRAINT `FK_7E1A4366A4A2AF17` FOREIGN KEY (`sellCurrency_id`) REFERENCES `currency` (`id`),
ADD CONSTRAINT `FK_7E1A4366A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `transactions`
--
ALTER TABLE `transactions`
ADD CONSTRAINT `FK_EAA81A4C38248176` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`),
ADD CONSTRAINT `FK_EAA81A4CA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `FK_EAA81A4CC2D9760` FOREIGN KEY (`trade_id`) REFERENCES `trade` (`id`);
--
-- Constraints for table `users_groups`
--
ALTER TABLE `users_groups`
ADD CONSTRAINT `FK_FF8AB7E0A76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `FK_FF8AB7E0FE54D947` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`);
--
-- Constraints for table `wallet`
--
ALTER TABLE `wallet`
ADD CONSTRAINT `FK_7C68921FA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown | UTF-8 | 1,401 | 2.984375 | 3 | [] | no_license | 当你设置节点的渲染状态时,这个状态将被赋予当前的节点及其子节点。如 果子节点对同一个渲染状态设置了不同的属性参数,那么新的子节点状态参数将会覆盖原有的。换句话说,缺省情况下子节点可以改变自身的某个状态参数,或者继承父节点的同一个状态。
这种继承的特性在许多情况下都非常实用。但是有时候渲染可能需要更多特性。假设场景图形中有一个包含了实体多边形几何体的节点。如果要以线框模式来渲染场景图形,你的程序就需要覆盖这种多边形渲染模式状态,不论它出现在什么位置。
OSG 允许用户根据场景图形中任意位置的渲染属性和模式需求,而单独改变原有的状态继承特性。用户可以选择以下这几种枚举形式:
- osg::StateAttribute:: OVERRIDE - 如果你将一个渲染属性和模式设置为OVERRIDE,那么所有的子节点都将继承这一属性或模式,子节点对它们更改将会无效。
- osg::StateAttribute:: PROTECTED - 这种形式可以视为 OVERRIDE 的一个例外。凡是设置为PROTECTED的渲染属性或模式,均不会受到父节点的影响。
- osg::StateAttribute::INHERIT - 这种模式强制子节点继承父节点的渲染状态。其效果是子节点的渲染状态被解除,而使用父节点的状态替代。
|
Shell | UTF-8 | 116 | 3.328125 | 3 | [] | no_license | #!/bin/bash
a=0
while [ $a -lt 25 ]
do
echo "Hello World, the cirrent value of a : $a"
a=`expr $a + 1`
done
|
Java | UTF-8 | 588 | 2.5 | 2 | [] | no_license | package com.adonax.sivi;
import javax.swing.JTextPane;
public class AboutPane
{
static private String txt =
"SiVi was written by Phil Freihofner\n"
+ "with contributions from Sumio Kiyooki.\n"
+ "\n"
+ "Simplex Noise was originally developed by \n"
+ "Ken Perlin. We make use of an implementation \n"
+ "written and placed in the public domain by\n"
+ "Stefan Gustavson.\n\n"
+ "http://www.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java";
public static JTextPane getAboutText()
{
JTextPane tp = new JTextPane();
tp.setEditable(false);
tp.setText(txt);
return tp;
}
}
|
PHP | UTF-8 | 2,463 | 2.625 | 3 | [] | no_license | <?php
//View plans and comment on them
include_once "class_player.inc.php";
include_once("class_planner.inc.php");
include_once("class_plan.inc.php");
if (isset($_SESSION['user_id'])) {
$currentUser = $_SESSION['user_id'];
include_once "header2.inc.php";
}
else {
$currentUser = 0;
include_once "header.inc.php";
}
echo "<div class='bar'>";
if ($currentUser>0) echo "<p class='right'><a href='index.php?page=direwolf' class='clist'>[Return to character list]</a></p>";
else echo "<p class='right'><a href='index.php' class='clist'>[Return to Main Page]</a></p>";
ptag("h1", "Plans");
if (isset($_GET["node"])) {
if (!is_numeric($_GET["node"])) {
para("Error loading data.");
}
else {
$p2 = round($_GET["node"]);
$p = new Plan($mysqli, $p2);
if ($p->valid) {
if (isset($_POST["comment"])&&$currentUser>0) {
$com = mysqli_real_escape_string($mysqli, $_POST["comment"]);
$res = $p->addComment($currentUser, $com);
if ($res) para("Comment added successfully.");
else para("Adding comment failed.");
}
ptag("h2", $p->title);
para("Posted: " . $p->created . ", edited: " . $p->changed);
ptag("p", $p->getContents(), "class='longtext'");
if ($p->countComments()>0) $p->printComments();
else para("This has no comments yet.");
if ($currentUser>0) {
ptag("h3", "Add comment:");
echo "<form action='index.php?page=showplan&node=$p2' method='post' name='commentform' id='commentform'>";
echo "<div class='comment'>";
ptag("textarea", "", "form='commentform' cols='100' rows='4' name='comment' id='comment'");
?>
<script>
CKEDITOR.replace( 'comment' );
</script>
<?php
ptag("input", "", "type='submit' value='Comment'");
echo "</div>";
echo "</form>";
}
else para("In order to comment, you need to be logged in.");
}
}
}
$planner = new Planner($mysqli);
$plans = $planner->getPlans();
if (is_array($plans)) {
ptag("h2", "List of plans");
foreach ($plans as $plan) {
$p = new Plan($mysqli, $plan);
echo "<p>";
ptag("a", $p->title, "href='index.php?page=showplan&node=$plan' class='clist'");
echo "</p>";
echo "<p>Last changed: " . $p->changed;
echo " (" . $p->countComments() . " comments)";
echo "</p>";
}
}
if ($currentUser>0) echo "<p class='right'><a href='index.php?page=direwolf' class='clist'>[Return to character list]</a></p>";
else echo "<p class='right'><a href='index.php' class='clist'>[Return to Main Page]</a></p>";
echo "</div>";
?>
|
Java | UTF-8 | 257 | 1.609375 | 2 | [] | no_license | package cn.talianshe.android.bean;
import org.parceler.Parcel;
@Parcel
public class AssociationActivityInfo {
public String associationName;
public String associationId;
public String activityName;
public String activityId;
}
|
Shell | UTF-8 | 1,853 | 4.03125 | 4 | [
"MIT"
] | permissive | #!/bin/bash
usage() {
echo
echo "USAGE: $0 <archive_format> <student_media_dir>[,<student_media_dir>,...]"
echo
echo " Archive Formats:"
echo " 7z -7zip with LZMA compression split into 2G files"
echo " 7zma2 -7zip with LZMA2 compression split into 2G files"
echo " 7zcopy -7zip with no compression split into 2G files"
echo " tar -tar archive with no compression"
echo " tgz -gzip compressed tar archive"
echo " tbz -bzip2 compressed tar archive"
echo " txz -xz compressed tar archive"
echo
}
case ${1}
in
7z)
ARCHIVE_CMD="7z a -t7z -m0=LZMA -mmt=on -v2g"
ARCHIVE_EXT="7z"
;;
7zma2)
ARCHIVE_CMD="7z a -t7z -m0=LZMA2 -mmt=on -v2g"
ARCHIVE_EXT="7z"
;;
7zcopy)
ARCHIVE_CMD="7z a -t7z -mx=0 -v2g"
ARCHIVE_EXT="7z"
;;
tar)
ARCHIVE_CMD="tar cvf"
ARCHIVE_EXT="tar"
;;
tar.gz|tgz)
ARCHIVE_CMD="tar czvf"
ARCHIVE_EXT="tgz"
;;
tar.bz2|tbz)
ARCHIVE_CMD="tar cjvf"
ARCHIVE_EXT="tbz"
;;
tar.xz|txz)
ARCHIVE_CMD="tar cJvf"
ARCHIVE_EXT="txz"
;;
*)
usage
exit
;;
esac
if [ -z ${2} ]
then
echo "ERROR: No student media directories were provided."
exit 1
else
for SM_DIR in $(echo ${2} | sed 's/,/ /g')
do
if ! [ -d ${2} ]
then
echo "ERROR: The provided student media directory doesn't appear to exist."
echo "Skipping ..."
else
echo "---------------------------------------------------------------------"
echo "COMMAND: ${ARCHIVE_CMD} ${SM_DIR}.${ARCHIVE_EXT} ${SM_DIR}"
echo
${ARCHIVE_CMD} ${SM_DIR}.${ARCHIVE_EXT} ${SM_DIR}
echo
echo "COMMAND: md5sum ${SM_DIR}.${ARCHIVE_EXT}* > ${SM_DIR}.${ARCHIVE_EXT}.md5sums"
echo
md5sum ${SM_DIR}.${ARCHIVE_EXT}* > ${SM_DIR}.${ARCHIVE_EXT}.md5sums
fi
done
fi
|
C | UTF-8 | 17,568 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* UNIBA/Ampere 1.3
* Gruppo n.16 - Marco Furone, Michele Barile, Nicolo' Cucinotta, Simone Cervino
* Progetto universitario di gruppo intento alla creazione di un gestore dati per la musica, es: WinAmp
* da realizzare nell'ambito del corso di studi di Laboratorio di Informatica, a.a. 2019/20.
* Maggiori informazioni sul copyright su https://github.com/Soxasora/Ampere/blob/master/LICENSE
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../ricerca/MotoreRicerca.h"
#include "../gestori/GestoreAssociazioni.h"
#include "../gestori/GestoreFile.h"
#include "../gestori/GestoreBrani.h"
#include "../database/Brano.h"
#include "../gestori/GestoreArtisti.h"
#include "../gestori/GestoreAlbum.h"
#include "../gestori/GestoreGeneri.h"
#include "../database/Database.h"
#include "../database/DatabaseUtils.h"
#include "../sys/Messaggi.h"
#include "../sys/Utils.h"
#include "../sys/Impostazioni.h"
void inserireBranoGuidato(database *db) {
char scelta='a';
int i=0, nArtisti=0, nAlbum=0, nGeneri=0;
int* idArtisti = calloc(MAX_MEDIO, sizeof(int));
int* idAlbum = calloc(MAX_MEDIO, sizeof(int));
int* idGeneri = calloc(MAX_MEDIO, sizeof(int));
char *titolo, *artista, *album, *genere;
int durata=0, anno=0, ascolti=0;
// Registrazione
do {
if ((titolo=calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci titolo: ");
titolo = inputStringa(MAX_MEDIO,titolo);
}
do {
printf("\nQuanti artisti hanno lavorato su questo brano? ");
nArtisti = inputNumero();
} while (nArtisti<1||nArtisti>MAX_MEDIO);
i=0;
while (i<nArtisti) {
do {
if ((artista=calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci nome artista n.%d: ", i+1);
artista = inputStringa(MAX_MEDIO,artista);
creareArtistaSeNonEsiste(db, artista);
}
} while (db->ultimoEsito!=0);
idArtisti[i] = controllareEsistenzaArtista(db, artista);
if (artista!=NULL) {
free(artista);
artista=NULL;
}
i++;
}
do {
printf("\nDi quanti album fa parte questa canzone? ");
nAlbum = inputNumero();
} while (nAlbum<1||nAlbum>MAX_MEDIO);
i=0;
while (i<nAlbum) {
do {
if ((album=calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci nome album n.%d: ", i+1);
album = inputStringa(MAX_MEDIO,album);
creareAlbumSeNonEsiste(db, album);
}
} while (db->ultimoEsito!=0);
idAlbum[i] = controllareEsistenzaAlbum(db, album);
if (album!=NULL) {
free(album);
album=NULL;
}
i++;
}
do {
printf("\nQuanti generi ha questa canzone? ");
nGeneri = inputNumero();
} while (nGeneri<1||nGeneri>MAX_MEDIO);
i=0;
while (i<nGeneri) {
do {
if ((genere=calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci genere n.%d del brano: ", i+1);
genere = inputStringa(MAX_MEDIO,genere);
creareGenereSeNonEsiste(db, genere);
}
} while (db->ultimoEsito!=0);
idGeneri[i] = controllareEsistenzaGenere(db, genere);
if (genere!=NULL) {
free(genere);
genere=NULL;
}
i++;
}
do {
printf("\nInserisci durata del brano in secondi: ");
durata = inputNumero();
} while (durata<=0);
do {
printf("\nInserisci anno d'uscita del brano: ");
anno = inputNumero();
} while (anno<1950);
do {
printf("\nInserisci numero d'ascolti del brano: ");
ascolti = inputNumero();
} while (ascolti<=0);
struct Brano nuovoBrano = creareBrano(titolo, durata, anno, ascolti);
if (titolo!=NULL) {
free(titolo);
titolo=NULL;
}
// Mostra anteprima del brano
mostrareAnteprimaBrano(db, nuovoBrano, idArtisti, idAlbum, idGeneri);
scelta = richiesta(0);
if (scelta=='Y'||scelta=='y') {
// Ricerca similitudini
controllareSimilitudineBrano(db, nuovoBrano);
if (db->ultimoEsito==0) {
inserireBrano(db, nuovoBrano, idArtisti, idAlbum, idGeneri);
}
db->ultimoEsito=0;
} else {
db->ultimoEsito=-1;
}
if (idArtisti!=NULL) {
free(idArtisti);
idArtisti=NULL;
}
if (idAlbum!=NULL) {
free(idAlbum);
idAlbum=NULL;
}
if (idGeneri!=NULL) {
free(idGeneri);
idGeneri=NULL;
}
} while (db->ultimoEsito!=0);
}
struct Brano creareBrano(char titolo[], int durata, int anno, int ascolti) {
struct Brano nuovoBrano;
nuovoBrano.id = -1;
strcpy(nuovoBrano.titolo,titolo);
nuovoBrano.durata = durata;
nuovoBrano.anno = anno;
nuovoBrano.ascolti = ascolti;
return nuovoBrano;
}
void mostrareAnteprimaBrano(database *db, struct Brano nuovoBrano, int* idArtisti, int* idAlbum, int* idGeneri) {
int i=0;
int posAlbum = 0, posArtista = 0, posGenere = 0;
char *tempo = convertireSecondiInTempo(nuovoBrano.durata);
printf("\nIl brano che stai per inserire ha questi dettagli:"
"\nTitolo: %s"
"\nDurata: %s"
"\nArtisti: ", nuovoBrano.titolo, tempo);
if (tempo!=NULL) {
free(tempo); tempo=NULL;
}
i=0;
while (idArtisti[i]!=0) {
posArtista = ottenerePosDaID(db, 2, idArtisti[i]);
if (i!=0)
printf(", ");
printf("%s", db->artista[posArtista].nomeArte);
i++;
}
printf("\nAlbum: ");
i=0;
while (idAlbum[i]!=0) {
posAlbum = ottenerePosDaID(db, 1, idAlbum[i]);
if (i!=0)
printf(", ");
printf("%s", db->album[posAlbum].titolo);
i++;
}
printf("\nGeneri: ");
i=0;
while (idGeneri[i]!=0) {
posGenere = ottenerePosDaID(db, 3, idGeneri[i]);
if (i!=0)
printf(", ");
printf("%s", db->genere[posGenere].nome);
i++;
}
printf("\nAnno: %d"
"\nAscolti: %d", nuovoBrano.anno, nuovoBrano.ascolti);
}
void inserireBrano(database *db, struct Brano nuovoBrano, int idArtisti[], int idAlbum[], int idGeneri[]) {
cPrintf(C_VERDE, "\nInserimento del brano in corso... potrebbe esserci piu' di una associazione.");
int i=0;
int n=contareNelDatabase(db,0);
nuovoBrano.id = trovareUltimoId(db, 0)+1;
db->brano[n] = nuovoBrano;
// Associazioni
i=0;
while (idArtisti[i]!=0) {
inserireAssociazioneArtista(db,creareAssociazioneArtista(nuovoBrano.id, idArtisti[i]));
i++;
}
i=0;
while (idAlbum[i]!=0) {
inserireAssociazioneAlbum(db,creareAssociazioneAlbum(nuovoBrano.id, idAlbum[i]));
i++;
}
i=0;
while (idGeneri[i]!=0) {
inserireAssociazioneGenere(db,creareAssociazioneGenere(nuovoBrano.id, idGeneri[i]));
i++;
}
successo(1);
if (salvataggioDiretto) {
salvareBraniSuFile(db);
} else {
db->modificato=true;
}
}
void controllareSimilitudineBrano(database *db, struct Brano nuovoBrano) {
cPrintf(C_CIANO,"\nRicerco eventuali similitudini con i brani gia' presenti...");
char scelta='a';
int occorrenze=0, i=0, n=contareNelDatabase(db, 0);
bool trovato=false;
while (i<n) {
occorrenze=0;
if (comparareStringhe(db->brano[i].titolo, nuovoBrano.titolo)==0) {
occorrenze++;
if (db->brano[i].anno == nuovoBrano.anno) {
occorrenze++;
}
if (db->brano[i].durata == nuovoBrano.durata) {
occorrenze++;
}
}
if (occorrenze>0) {
printf("\n\n");
informazione(300);
cPrintf(C_CIANO,"\nBrano simile: ");
mostrareSingoloBrano(db, db->brano[i].id);
trovato=true;
}
i++;
}
if (trovato) {
scelta = richiesta(6);
if (scelta=='N'||scelta=='n') {
db->ultimoEsito=-1;
} else {
db->ultimoEsito=0;
}
} else {
successo(300);
db->ultimoEsito=0;
}
}
void inserireBranoSuFile(struct Brano brano) {
FILE* fp=fopen(file_brani, "a");
if (controllareSeFileVuoto(file_brani)==1) {
fprintf(fp, "%d|%s|%d|%d|%d", brano.id, brano.titolo, brano.durata, brano.anno, brano.ascolti);
} else {
fprintf(fp, "\n%d|%s|%d|%d|%d", brano.id, brano.titolo, brano.durata, brano.anno, brano.ascolti);
}
fclose(fp);
}
void modificareBranoGuidato(database *db) {
int id=0, campo=-1;
char scelta='a';
moduloRicercaBrani(db);
while (ottenerePosDaID(db, 0,id)==-1) {
printf("\n\nInserire l'identificativo del brano da modificare: ");
id = inputNumero();
if (ottenerePosDaID(db, 0,id)==-1) {
attenzione(211);
}
}
printf("\nHai scelto il brano:");
mostrareSingoloBrano(db, id);
scelta = richiesta(0);
if (scelta=='Y'||scelta=='y') {
do {
printf("\n===[Sistema di "C_GIALLO"modifica brani"C_RESET"]===");
printf("\n[1] Modifica il "C_CIANO"Titolo"C_RESET);
printf("\n[2] Modifica la "C_CIANO"Durata"C_RESET);
printf("\n[3] Modifica "C_CIANO"l'Anno"C_RESET);
printf("\n[4] Modifica gli "C_CIANO"Ascolti"C_RESET);
printf("\n[5] Modifica gli "C_CIANO"artisti d'appartenenza"C_RESET);
printf("\n[6] Modifica gli "C_CIANO"album d'appartenenza"C_RESET);
printf("\n[7] Modifica i "C_CIANO"generi d'appartenenza"C_RESET);
printf("\n[0] Esci");
while (campo<0||campo>7) {
printf("\n"C_VERDE"Inserisci la tua scelta"C_RESET": ");
campo = inputNumero();
}
if (campo!=0) {
creareBranoModificato(db, campo, id);
} else {
db->ultimoEsito=-2;
}
} while (db->ultimoEsito==-1);
}
}
void creareBranoModificato(database *db, int campo, int id) {
char scelta='a';
int pos = ottenerePosDaID(db, 0, id);
struct Brano branoModificato = db->brano[pos];
int* idAssociazioni = calloc(MAX_MEDIO, sizeof(int));
do {
if (campo==1) {
char *titolo = calloc(MAX_MEDIO, sizeof(char));
printf("\nInserisci nuovo titolo: ");
titolo = inputStringa(MAX_MEDIO,titolo);
strcpy(branoModificato.titolo, titolo);
if (titolo!=NULL) {
free(titolo);
titolo=NULL;
}
} else if (campo==2) {
int durata=0;
while (durata<1) {
printf("\nInserisci nuova durata (in secondi): ");
durata = inputNumero();
}
branoModificato.durata = durata;
} else if (campo==3) {
int anno=0;
while (anno<1950) {
printf("\nInserisci nuovo anno: ");
anno = inputNumero();
}
branoModificato.anno = anno;
} else if (campo==4) {
int ascolti=0;
while (ascolti<=0) {
printf("\nInserisci nuovi ascolti: ");
ascolti = inputNumero();
}
branoModificato.ascolti = ascolti;
} else if (campo==5) {
char *artista;
int i=0, nArtisti=0;
idAssociazioni = calloc(MAX_MEDIO, sizeof(int));
printf("\nQuanti artisti ha il brano? ");
nArtisti = inputNumero();
i=0;
while (i<nArtisti) {
do {
if ((artista = calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci nome d'arte artista n.%d: ", i+1);
artista = inputStringa(MAX_MEDIO,artista);
creareArtistaSeNonEsiste(db, artista);
idAssociazioni[i] = controllareEsistenzaArtista(db, artista);
}
} while (db->ultimoEsito!=0);
if (artista!=NULL) {
free(artista);
artista=NULL;
}
i++;
}
} else if (campo==6) {
char *album;
int i=0, nAlbum=0;
idAssociazioni = calloc(MAX_MEDIO, sizeof(int));
printf("\nQuanti album ha il brano? ");
nAlbum = inputNumero();
i=0;
while (i<nAlbum) {
do {
if ((album = calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci nome album n.%d: ", i+1);
album = inputStringa(MAX_MEDIO,album);
creareAlbumSeNonEsiste(db, album);
idAssociazioni[i] = controllareEsistenzaAlbum(db, album);
}
} while (db->ultimoEsito!=0);
if (album!=NULL) {
free(album);
album=NULL;
}
i++;
}
} else if (campo==7) {
char *genere;
int i=0, nGeneri=0;
idAssociazioni = calloc(MAX_MEDIO, sizeof(int));
printf("\nQuanti generi ha il brano? ");
nGeneri = inputNumero();
i=0;
while (i<nGeneri) {
do {
if ((genere = calloc(MAX_MEDIO, sizeof(char)))) {
printf("\nInserisci nome del genere n.%d: ", i+1);
genere = inputStringa(MAX_MEDIO, genere);
creareGenereSeNonEsiste(db, genere);
idAssociazioni[i] = controllareEsistenzaGenere(db, genere);
}
} while (db->ultimoEsito!=0);
if (genere!=NULL) {
free(genere);
genere=NULL;
}
i++;
}
}
mostrareAnteprimaModificaBrano(db, id, campo, branoModificato, idAssociazioni);
scelta = richiesta(0);
if (scelta=='Y'||scelta=='y') {
modificareBrano(db, id, campo, branoModificato, idAssociazioni);
db->ultimoEsito=0;
} else {
scelta = richiesta(3);
if (scelta=='Y'||scelta=='y') {
db->ultimoEsito=-2;
} else {
db->ultimoEsito=-1;
}
}
if (idAssociazioni!=NULL) {
free(idAssociazioni);
idAssociazioni=NULL;
}
} while (db->ultimoEsito==-2);
}
void mostrareAnteprimaModificaBrano(database *db, int idBrano, int campo, struct Brano branoModificato, int idAssociazioni[]) {
printf("\n===[Brano ORIGINALE]===");
mostrareSingoloBrano(db, idBrano);
printf("\n\n===[Brano MODIFICATO]===");
char *tempo = convertireSecondiInTempo(branoModificato.durata);
int i=0;
printf("\nTitolo: %s"
"\nDurata: %s", branoModificato.titolo, tempo);
if (tempo!=NULL) {
free(tempo); tempo=NULL;
}
if (campo==5) {
printf(C_VERDE"\n[MODIFICATO]"C_RESET" Artisti: ");
int posArtista=0;
while (idAssociazioni[i]!=0) {
posArtista = ottenerePosDaID(db, 2, idAssociazioni[i]);
if (i!=0)
printf(", ");
printf("%s", db->artista[posArtista].nomeArte);
i++;
}
} else {
mostrareAssociazioni(db, 0, idBrano);
}
if (campo==6) {
printf(C_VERDE"\n[MODIFICATO]"C_RESET" Album: ");
int posAlbum = 0;
while (idAssociazioni[i]!=0) {
posAlbum = ottenerePosDaID(db, 1, idAssociazioni[i]);
if (i!=0)
printf(", ");
printf("%s", db->album[posAlbum].titolo);
i++;
}
} else {
mostrareAssociazioni(db, 1, idBrano);
}
if (campo==7) {
printf(C_VERDE"\n[MODIFICATO]"C_RESET" Generi: ");
int posGenere = 0;
while (idAssociazioni[i]!=0) {
posGenere = ottenerePosDaID(db, 3, idAssociazioni[i]);
if (i!=0)
printf(", ");
printf("%s", db->genere[posGenere].nome);
i++;
}
} else {
mostrareAssociazioni(db, 2, idBrano);
}
printf("\nAnno: %d"
"\nAscolti: %d", branoModificato.anno, branoModificato.ascolti);
}
void modificareBrano(database *db, int idBrano, int campo, struct Brano branoModificato, int idAssociazioni[]) {
int posBrano = ottenerePosDaID(db, 0, idBrano);
db->brano[posBrano] = branoModificato;
// Associazioni
int i=0;
if (campo==5) {
cancellareAssociazioniArtisti(db, idBrano);
i=0;
while (idAssociazioni[i]!=0) {
inserireAssociazioneArtista(db,creareAssociazioneArtista(branoModificato.id, idAssociazioni[i]));
i++;
}
} else if (campo==6) {
cancellareAssociazioniAlbum(db, idBrano);
i=0;
while (idAssociazioni[i]!=0) {
inserireAssociazioneAlbum(db,creareAssociazioneAlbum(branoModificato.id, idAssociazioni[i]));
i++;
}
} else if (campo==7) {
cancellareAssociazioniGenere(db, idBrano);
i=0;
while (idAssociazioni[i]!=0) {
inserireAssociazioneGenere(db,creareAssociazioneGenere(branoModificato.id, idAssociazioni[i]));
i++;
}
}
successo(7);
if (salvataggioDiretto) {
salvareBraniSuFile(db);
} else {
db->modificato=true;
}
}
void cancellareBranoGuidato(database *db) {
int id=0;
char scelta='a';
moduloRicercaBrani(db);
while (ottenerePosDaID(db, 0,id)==-1) {
printf("\n\nInserire l'identificativo del brano da cancellare: ");
id = inputNumero();
if (ottenerePosDaID(db, 0,id)==-1) {
printf("\nBrano non trovato, riprovare");
}
}
printf("\nHai scelto il brano:");
mostrareSingoloBrano(db, id);
scelta = richiesta(0);
if (scelta=='Y'||scelta=='y') {
cancellareBrano(db, id);
}
}
void cancellareBrano(database *db, int id) {
int n = contareNelDatabase(db,0);
int i = ottenerePosDaID(db, 0, id);
while (i<n-1) {
db->brano[i] = db->brano[i+1];
i++;
}
db->brano[n-1].id = 0;
cancellareAssociazioniBrano(db, id);
successo(13);
if (salvataggioDiretto) {
salvareBraniSuFile(db);
} else {
db->modificato=true;
}
}
// TESTI
void apriTesto(int idBrano) {
char *posizione_testo = calloc(MAX_ENORME, sizeof(char));
char *comando = calloc(MAX_ENORME+10, sizeof(char));
FILE *fp;
if(os==0) {
sprintf(posizione_testo, "%s/%d%s", cartella_testi, idBrano, ".txt");
fp=fopen(posizione_testo, "r");
if (fp==NULL) {
printf("\nIl brano scelto non possiede al momento del testo.");
} else {
system(posizione_testo);
}
fclose(fp);
} else if (os==1) {
sprintf(posizione_testo, "%s/%d%s", cartella_testi, idBrano, ".txt");
fp=fopen(posizione_testo, "r");
if (fp==NULL) {
printf("\nIl brano scelto non possiede al momento del testo.");
} else {
strcpy(comando, "open ");
strcat(comando, posizione_testo);
system(comando);
}
fclose(fp);
} else if (os==2) {
sprintf(posizione_testo, "%s/%d%s", cartella_testi, idBrano, ".txt");
fp=fopen(posizione_testo, "r");
if (fp==NULL) {
printf("\nIl brano scelto non possiede al momento del testo.");
} else {
strcpy(comando, "nano ");
strcat(comando, posizione_testo);
system(comando);
}
fclose(fp);
}
if (posizione_testo!=NULL) {
free(posizione_testo);
posizione_testo=NULL;
}
if (comando!=NULL) {
free(comando);
comando=NULL;
}
}
void apriTestoDaRicerca(database *db) {
int scelta=-1, idBrano=0;
do {
printf("\nCerca brano del quale si vuole aprire il testo");
moduloRicercaBrani(db);
if (db->ultimoEsito==-1) {
scelta = richiesta(2);
if (scelta=='Y'||scelta=='y') {
printf("\nContinuo con l'apertura del testo.");
db->ultimoEsito=0;
} else {
printf("\nUscito dall'apertura del testo.");
}
} else if (db->ultimoEsito==1) {
do {
printf("\nInserisci id del brano selezionato, altrimenti [-1] per cercare di nuovo: ");
idBrano = inputNumero();
if (idBrano==-1) {
db->ultimoEsito=2;
} else {
if (ottenerePosDaID(db, 0,idBrano)==-1) {
printf("\nBrano non trovato, riprovare");
db->ultimoEsito=0;
} else {
apriTesto(idBrano);
db->ultimoEsito=-1;
}
}
} while (db->ultimoEsito==0);
}
} while (db->ultimoEsito!=-1);
}
|
Java | UTF-8 | 9,130 | 1.539063 | 2 | [
"MIT"
] | permissive | package io.onedev.server.web.component.issue.authorizations;
import static io.onedev.server.model.IssueAuthorization.PROP_ISSUE;
import static io.onedev.server.model.IssueAuthorization.PROP_USER;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.google.common.collect.Sets;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.IssueAuthorizationManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueAuthorization;
import io.onedev.server.model.User;
import io.onedev.server.persistence.dao.EntityCriteria;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.util.Similarities;
import io.onedev.server.util.facade.UserCache;
import io.onedev.server.web.WebConstants;
import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
import io.onedev.server.web.behavior.OnTypingDoneBehavior;
import io.onedev.server.web.component.datatable.DefaultDataTable;
import io.onedev.server.web.component.select2.Response;
import io.onedev.server.web.component.select2.ResponseFiller;
import io.onedev.server.web.component.select2.SelectToAddChoice;
import io.onedev.server.web.component.user.UserAvatar;
import io.onedev.server.web.component.user.choice.AbstractUserChoiceProvider;
import io.onedev.server.web.component.user.choice.UserChoiceResourceReference;
import io.onedev.server.web.page.admin.usermanagement.profile.UserProfilePage;
@SuppressWarnings("serial")
public abstract class IssueAuthorizationsPanel extends Panel {
private String query;
private DataTable<IssueAuthorization, Void> authorizationsTable;
private SortableDataProvider<IssueAuthorization, Void> dataProvider ;
public IssueAuthorizationsPanel(String id) {
super(id);
}
private EntityCriteria<IssueAuthorization> getCriteria() {
EntityCriteria<IssueAuthorization> criteria =
EntityCriteria.of(IssueAuthorization.class);
if (query != null) {
criteria.createCriteria(PROP_USER).add(Restrictions.or(
Restrictions.ilike(User.PROP_NAME, query, MatchMode.ANYWHERE),
Restrictions.ilike(User.PROP_FULL_NAME, query, MatchMode.ANYWHERE)));
} else {
criteria.setCacheable(true);
}
criteria.add(Restrictions.eq(PROP_ISSUE, getIssue()));
return criteria;
}
@Override
protected void onInitialize() {
super.onInitialize();
TextField<String> searchField;
add(searchField = new TextField<String>("filterUsers", Model.of(query)));
searchField.add(new OnTypingDoneBehavior(100) {
@Override
protected void onTypingDone(AjaxRequestTarget target) {
query = searchField.getInput();
if (StringUtils.isBlank(query))
query = null;
target.add(authorizationsTable);
}
});
add(new SelectToAddChoice<User>("addNew", new AbstractUserChoiceProvider() {
@Override
public void query(String term, int page, Response<User> response) {
UserCache cache = OneDev.getInstance(UserManager.class).cloneCache();
List<User> users = new ArrayList<>(cache.getUsers());
users.removeAll(getIssue().getAuthorizedUsers());
users.sort(cache.comparingDisplayName(Sets.newHashSet()));
users = new Similarities<User>(users) {
@Override
public double getSimilarScore(User object) {
return cache.getSimilarScore(object, term);
}
};
new ResponseFiller<>(response).fill(users, page, WebConstants.PAGE_SIZE);
}
}) {
@Override
protected void onInitialize() {
super.onInitialize();
getSettings().setPlaceholder("Authorize user...");
getSettings().setFormatResult("onedev.server.userChoiceFormatter.formatResult");
getSettings().setFormatSelection("onedev.server.userChoiceFormatter.formatSelection");
getSettings().setEscapeMarkup("onedev.server.userChoiceFormatter.escapeMarkup");
}
@Override
protected void onSelect(AjaxRequestTarget target, User selection) {
IssueAuthorization authorization = new IssueAuthorization();
authorization.setIssue(getIssue());
authorization.setUser(OneDev.getInstance(UserManager.class).load(selection.getId()));
OneDev.getInstance(IssueAuthorizationManager.class).create(authorization);
target.add(authorizationsTable);
Session.get().success("User authorized");
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(SecurityUtils.isAdministrator());
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new UserChoiceResourceReference()));
}
});
List<IColumn<IssueAuthorization, Void>> columns = new ArrayList<>();
columns.add(new AbstractColumn<IssueAuthorization, Void>(Model.of("Name")) {
@Override
public void populateItem(Item<ICellPopulator<IssueAuthorization>> cellItem, String componentId,
IModel<IssueAuthorization> rowModel) {
User user = rowModel.getObject().getUser();
Fragment fragment = new Fragment(componentId, "nameFrag", IssueAuthorizationsPanel.this);
Link<Void> link = new BookmarkablePageLink<Void>("link", UserProfilePage.class,
UserProfilePage.paramsOf(user));
link.add(new UserAvatar("avatar", user));
link.add(new Label("name", user.getDisplayName()));
fragment.add(link);
cellItem.add(fragment);
}
});
columns.add(new AbstractColumn<IssueAuthorization, Void>(Model.of("")) {
@Override
public void populateItem(Item<ICellPopulator<IssueAuthorization>> cellItem, String componentId,
IModel<IssueAuthorization> rowModel) {
Fragment fragment = new Fragment(componentId, "actionFrag", IssueAuthorizationsPanel.this);
fragment.add(new AjaxLink<Void>("unauthorize") {
@Override
public void onClick(AjaxRequestTarget target) {
IssueAuthorization authorization = rowModel.getObject();
OneDev.getInstance(IssueAuthorizationManager.class).delete(authorization);
Session.get().success("User '" + authorization.getUser().getDisplayName() + "' unauthorized");
target.add(authorizationsTable);
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
IssueAuthorization authorization = rowModel.getObject();
String message = "Do you really want to unauthorize user '"
+ authorization.getUser().getDisplayName() + "'?";
attributes.getAjaxCallListeners().add(new ConfirmClickListener(message));
}
});
cellItem.add(fragment);
}
});
dataProvider = new SortableDataProvider<IssueAuthorization, Void>() {
@Override
public Iterator<? extends IssueAuthorization> iterator(long first, long count) {
EntityCriteria<IssueAuthorization> criteria = getCriteria();
criteria.addOrder(Order.desc(IssueAuthorization.PROP_ID));
return OneDev.getInstance(IssueAuthorizationManager.class).query(criteria, (int)first,
(int)count).iterator();
}
@Override
public long size() {
return OneDev.getInstance(IssueAuthorizationManager.class).count(getCriteria());
}
@Override
public IModel<IssueAuthorization> model(IssueAuthorization object) {
Long id = object.getId();
return new LoadableDetachableModel<IssueAuthorization>() {
@Override
protected IssueAuthorization load() {
return OneDev.getInstance(IssueAuthorizationManager.class).load(id);
}
};
}
};
add(authorizationsTable = new DefaultDataTable<IssueAuthorization, Void>(
"authorizations", columns, dataProvider, WebConstants.PAGE_SIZE, null));
}
protected abstract Issue getIssue();
}
|
Go | UTF-8 | 618 | 2.578125 | 3 | [] | no_license | package models
import(
"fmt"
"github.com/astaxie/beego/orm"
_"github.com/go-sql-driver/mysql"
)
type Page struct {
Id int
Website string
Email string
}
func init() {
// 注册数据库
orm.RegisterDataBase("default","mysql",
"root@123456@tcp(127.0.0.1:3306)/test?charset=utf8")
orm.RegisterModel(new(Page))
}
func GetPage() Page {
//rtn:=Page{Website: "hellobeego.com", Email: "model@beego.com"}
//return rtn
o:=orm.NewOrm()
//p:=Page{1}
p:=Page{Id:1}
err:=o.Read(&p)
fmt.Println(err)
return p
}
func UpdatePage(){
p:=Page{Id: 1, Email: "myemail2131",}
o:=orm.NewOrm()
o.Update(&p,"Email")
}
|
TypeScript | UTF-8 | 1,470 | 3.640625 | 4 | [
"MIT"
] | permissive | export interface BoomProps {
min: number,
max: number,
s1: string,
s2: string
}
/**
* Provide to find boom number
*/
export default class Boom {
/**
* props holds general properties to find boom number.
*/
private props: BoomProps;
/**
*
* @param props
*/
public constructor(props: BoomProps) {
this.props = props;
}
/**
* Provide to find boom number by the given number.
* @param k
* @return {string}
*/
public find(k: number){
if(k < this.props.min || k > this.props.max) {
throw new Error(`Number must between ${this.props.min} and ${this.props.max}`)
}
// shift number as 1.
let sm = (k + 1);
// find bytes of the number.
let findValue = ( sm >>> 0).toString(2);
findValue = Boom.replaceAll(findValue, "0", this.props.s1);
findValue = Boom.replaceAll(findValue, "1", this.props.s2).slice(1);
return findValue;
}
/**
* Provides to replace same things by the given regex.
* @param src
* @param search
* @param replacement
* @return {string|LoDashExplicitWrapper<string>|void}
*/
public static replaceAll = function(src, search, replacement) {
return src.replace(new RegExp(search, "g"), replacement);
};
/**
* Gets property of Boom
* @return {BoomProps}
*/
getProps(){
return this.props;
}
} |
JavaScript | UTF-8 | 602 | 3.109375 | 3 | [] | no_license | 'use strict';
(function () {
// Урезанный полифилл для insertAdjacentElement позиции afterend (других не использовал). В старой мозилле этот метод не работает. Пришлось на коленке изобретать свой.
if (!Element.prototype.insertAdjacentElement) {
Element.prototype.insertAdjacentElement = function (position, element) {
if (position === 'afterend') {
var parent = this.parentElement;
parent.insertBefore(element, this.nextElementSibling);
}
}
}
})();
|
Markdown | UTF-8 | 3,026 | 2.921875 | 3 | [] | no_license | ---
layout: doc
title: MMT Statistics Exporter
---
This adds the build target 'statistics' to MMT producing statistical information about an archive, an mmt document or a theory. The statistics are generated from the relational data files in an archive and are written to JSON files in export/statistics, one file per MMT document. Each statistics file contains a list of tuples of a key and a list of key value pairs (formally a JSON array of JSON objects consisting of a JSONString and a JSON array of JSON objects), each pair consist of a key describing the `sorts of relations to the declaration` considered and a list of tuples, consisting of a key describing the `type of declarations` counted and the count itself.
How exactly different declarations in the archive are counted is detailed below:
### Types of declarations
The statistics distinguishes the following `types of declarations` (abbreviated by a short `key` in the JSON files):
- `document`, `theory` and `view` declared in the archive or document (transitive closure of the `declares` relation)
- `explicit theory morphism` (transitive closure of views)
- `any theory morphism`(transitive closure of any (explicit or implicit theory morphisms))
- `constant` of different type declared (as above) in the archive or document:
- `structure` and `pattern`
- `untyped constant` (can't be differentiated further) and `maltyped constant` (whoose type cannot be inferred succesfully)
- Term-level constants (which ultimately return a term)
- `data constructor`
- `rule`
- Type-level constants (which ultimately return a type)
- `datatype constructor`
- `judgment constructor`
- constants of a `high universe` (returning a kind, or classes even higher in the type hirachy)
- If not annotated otherwise (in the relational files) there are two fallbacks for declarations:
- `typed constant` for typed constants and `other` for non-constants
### Sorts of relations to the declarations
These types of declarations are counted for the following `sorts of relations to the declaration` of the given archive/document/theory as follows:
- `Declared declaration` (via possibly multiple intermediate declarations) of the given theory/document/archive
- `Induced declaration by explicit morphisms (views)` (via possibly multiple intermediate views)
- `Induced declaration by any morphisms` (via possibly multiple intermediate morphisms)
- `Alignment` (possibly via multiple intermediate alignments) of declared (as above) declarations
Since the statistics are based on the relational files, when an archive is updated, it needs to be rebuilt first, before the statistics can be updated.
### Examples of one exported JSON file
The following example can be found in MMT/examples/export/statistics/narration/nat.json:
`[
{
"decl": [
{
"any_mor": 16
},
{
"theo": 4
},
{
"type": 2
},
{
"ty_con": 8
},
{
"data": 39
}
]
}
]
|
C++ | UTF-8 | 783 | 2.921875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
string findCommonStringOnRightBox(vector<string>& boxIds) {
string returnString = "";
for (int i = 0; i < boxIds.size(); i++)
{
for (int j = i+1; j < boxIds.size(); j++)
{
int numberOfDifferentLetters = 0;
int lastDifferentIndex = 0;
for (int k = 0; k < boxIds[i].size(); k++)
{
if (boxIds[i][k] != boxIds[j][k]) {
numberOfDifferentLetters++;
lastDifferentIndex = k;
}
}
if (numberOfDifferentLetters == 1) {
returnString += boxIds[i].substr(0, lastDifferentIndex);
returnString += boxIds[i].substr(lastDifferentIndex+1, boxIds[i].size() -1);
return returnString;
}
}
}
return returnString;
}
};
|
JavaScript | UTF-8 | 1,785 | 2.984375 | 3 | [] | no_license | import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const Statistics = (props) => {
if (props.total === 0 && props.alert === true) {
return (
<tr>
<td>No feedback given</td>
</tr>
)
}
else if (props.total === 0) {
return (
<tr></tr>
)
}
else return (
<tr>
<td>{props.text} {props.value}</td>
</tr>
)
}
const Button = ({ handleClick, text }) => (
<button onClick={handleClick}>
{text}
</button>
)
const App = () => {
const [good, setGood] = useState(0)
const [neutral, setNeutral] = useState(0)
const [bad, setBad] = useState(0)
const handleGoodClick = () => {
setGood(good + 1)
}
const handleNeutralClick = () => {
setNeutral(neutral + 1)
}
const handleBadClick = () => {
setBad(bad + 1)
}
return (
<div>
<div>
<h1>Give Feedback</h1>
<Button handleClick={handleGoodClick} text='good' />
<Button handleClick={handleNeutralClick} text='neutral' />
<Button handleClick={handleBadClick} text='bad' />
<h1>Statistics</h1>
<table>
<tbody>
<Statistics alert={true} total={good+bad+neutral}/>
<Statistics text="good" value={good} total={good+bad+neutral} />
<Statistics text="neutral" value={neutral} total={good+bad+neutral}/>
<Statistics text="bad" value={bad} total={good+bad+neutral}/>
<Statistics text="all" value={good+bad+neutral} total={good+bad+neutral}/>
<Statistics text="average" value={(good-bad)/(good+bad+neutral)} total={good+bad+neutral}/>
<Statistics text="positive" value={(good)/(bad+good+neutral)*100} total={good+bad+neutral}/>
</tbody>
</table>
</div>
</div>
)
}
ReactDOM.render(<App />,
document.getElementById('root')
) |
Markdown | UTF-8 | 812 | 2.96875 | 3 | [] | no_license | Question: https://leetcode.com/problems/palindromic-substrings/
---
try_1.py: O(n^2) O(n)
* Runtime: 220 ms, faster than 49.96% of Python3 online submissions for Palindromic Substrings.
* Memory Usage: 22.1 MB, less than 27.39% of Python3 online submissions for Palindromic Substrings.
> dp[i][j] = i~j is palindrone
---
try_2.py: O(n) O(n)
* Runtime: 66 ms, faster than 99.09% of Python3 online submissions for Palindromic Substrings.
* Memory Usage: 13.9 MB, less than 79.07% of Python3 online submissions for Palindromic Substrings.
> manacher's algorithm
---
try_3.py: O(n) O(n)
* Runtime: 40 ms, faster than 99.72% of Python3 online submissions for Palindromic Substrings.
* Memory Usage: 14.1 MB, less than 67.91% of Python3 online submissions for Palindromic Substrings.
> manacher's algorithm |
Java | UTF-8 | 7,119 | 1.5625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2017 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.baidu.hugegraph.io;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoIo;
import org.apache.tinkerpop.shaded.kryo.Kryo;
import org.apache.tinkerpop.shaded.kryo.Serializer;
import org.apache.tinkerpop.shaded.kryo.io.Input;
import org.apache.tinkerpop.shaded.kryo.io.Output;
import com.baidu.hugegraph.backend.id.EdgeId;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.backend.id.Id.IdType;
import com.baidu.hugegraph.backend.id.IdGenerator;
import com.baidu.hugegraph.schema.EdgeLabel;
import com.baidu.hugegraph.schema.IndexLabel;
import com.baidu.hugegraph.schema.PropertyKey;
import com.baidu.hugegraph.schema.VertexLabel;
import com.baidu.hugegraph.type.define.HugeKeys;
import com.baidu.hugegraph.util.StringEncoding;
public class HugeGryoModule {
private static GraphSONSchemaSerializer schemaSerializer =
new GraphSONSchemaSerializer();
public static void register(HugeGraphIoRegistry io) {
io.register(GryoIo.class, Optional.class, new OptionalSerializer());
// HugeGraph id serializer
io.register(GryoIo.class, IdGenerator.StringId.class,
new IdSerializer());
io.register(GryoIo.class, IdGenerator.LongId.class,
new IdSerializer());
io.register(GryoIo.class, EdgeId.class, new EdgeIdSerializer());
// HugeGraph schema serializer
io.register(GryoIo.class, PropertyKey.class,
new PropertyKeyKryoSerializer());
io.register(GryoIo.class, VertexLabel.class,
new VertexLabelKryoSerializer());
io.register(GryoIo.class, EdgeLabel.class,
new EdgeLabelKryoSerializer());
io.register(GryoIo.class, IndexLabel.class,
new IndexLabelKryoSerializer());
}
static class OptionalSerializer extends Serializer<Optional<?>> {
@Override
public void write(Kryo kryo, Output output, Optional<?> optional) {
if (optional.isPresent()) {
kryo.writeClassAndObject(output, optional.get());
} else {
kryo.writeObject(output, null);
}
}
@Override
public Optional<?> read(Kryo kryo, Input input, Class<Optional<?>> c) {
Object value = kryo.readClassAndObject(input);
return value == null ? Optional.empty() : Optional.of(value);
}
}
static class IdSerializer extends Serializer<Id> {
@Override
public void write(Kryo kryo, Output output, Id id) {
output.writeByte(id.type().ordinal());
byte[] idBytes = id.asBytes();
output.write(idBytes.length);
output.writeBytes(id.asBytes());
}
@Override
public Id read(Kryo kryo, Input input, Class<Id> clazz) {
int type = input.readByteUnsigned();
int length = input.read();
byte[] idBytes = input.readBytes(length);
return IdGenerator.of(idBytes, IdType.values()[type]);
}
}
static class EdgeIdSerializer extends Serializer<EdgeId> {
@Override
public void write(Kryo kryo, Output output, EdgeId edgeId) {
byte[] idBytes = edgeId.asBytes();
output.write(idBytes.length);
output.writeBytes(edgeId.asBytes());
}
@Override
public EdgeId read(Kryo kryo, Input input, Class<EdgeId> clazz) {
int length = input.read();
byte[] idBytes = input.readBytes(length);
return EdgeId.parse(StringEncoding.decode(idBytes));
}
}
private static void writeEntry(Kryo kryo,
Output output,
Map<HugeKeys, Object> schema) {
/* Write columns size and data */
output.writeInt(schema.keySet().size());
for (Map.Entry<HugeKeys, Object> entry : schema.entrySet()) {
kryo.writeObject(output, entry.getKey());
kryo.writeClassAndObject(output, entry.getValue());
}
}
@SuppressWarnings("unused")
private static Map<HugeKeys, Object> readEntry(Kryo kryo, Input input) {
int columnSize = input.readInt();
Map<HugeKeys, Object> map = new LinkedHashMap<>();
for (int i = 0; i < columnSize; i++) {
HugeKeys key = kryo.readObject(input, HugeKeys.class);
Object val = kryo.readClassAndObject(input);
map.put(key, val);
}
return map;
}
static class PropertyKeyKryoSerializer extends Serializer<PropertyKey> {
@Override
public void write(Kryo kryo, Output output, PropertyKey pk) {
writeEntry(kryo, output, schemaSerializer.writePropertyKey(pk));
}
@Override
public PropertyKey read(Kryo kryo, Input input, Class<PropertyKey> c) {
// TODO
return null;
}
}
static class VertexLabelKryoSerializer extends Serializer<VertexLabel> {
@Override
public void write(Kryo kryo, Output output, VertexLabel vl) {
writeEntry(kryo, output, schemaSerializer.writeVertexLabel(vl));
}
@Override
public VertexLabel read(Kryo kryo, Input input, Class<VertexLabel> c) {
// TODO
return null;
}
}
static class EdgeLabelKryoSerializer extends Serializer<EdgeLabel> {
@Override
public void write(Kryo kryo, Output output, EdgeLabel el) {
writeEntry(kryo, output, schemaSerializer.writeEdgeLabel(el));
}
@Override
public EdgeLabel read(Kryo kryo, Input input, Class<EdgeLabel> clazz) {
// TODO
return null;
}
}
static class IndexLabelKryoSerializer extends Serializer<IndexLabel> {
@Override
public void write(Kryo kryo, Output output, IndexLabel il) {
writeEntry(kryo, output, schemaSerializer.writeIndexLabel(il));
}
@Override
public IndexLabel read(Kryo kryo, Input input, Class<IndexLabel> c) {
// TODO
return null;
}
}
}
|
C# | UTF-8 | 1,914 | 3.265625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Media;
namespace LearningRobot
{
class Time : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private int allTime = 0;
private int seconds = 0;
private int minutes=0;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
// The constructor is private to enforce the factory pattern.
// This property represents an ID, suitable
// for use as a primary key in a database.
public int AllTime
{
get
{
return this.allTime;
}
set
{
if (value != this.allTime)
{
this.allTime = value;
NotifyPropertyChanged("AllTime");
}
}
}
public int Seconds
{
get
{
return this.seconds;
}
set
{
if (value != this.seconds)
{
this.seconds = value;
NotifyPropertyChanged("Seconds");
}
}
}
public int Minutes
{
get
{
return this.minutes;
}
set
{
if (value != this.minutes)
{
this.minutes = value;
NotifyPropertyChanged("Minutes");
}
}
}
}
}
|
Markdown | UTF-8 | 12,361 | 2.75 | 3 | [
"MIT"
] | permissive | # 引言
## 一、需求方面
### 故事一
长沙21岁大学生和女友在网吧上通宵网时,女友手机被偷。为帮女友找回手机,小李在网吧兼职做夜班网管,蹲守了13个通宵后,小李终于等到窃贼,将其抓获。女朋友知道后十分感动但是她已经跟了送她爱疯5的学长。
### 结论
(这是一个产品经理和用户需求的故事。)法海不懂爱,难免,但素素却一定要知道其心结所在,不然过一段时间又来次水浸金山,那不如去威利斯更浪漫些吧。
### 故事二
一个学生看见一只乌龟艰难地在河边陡坡上挣扎前行,心想这只可怜的乌龟本应呆在水中,一定是被碎石困住了。于是他拎起它,放回水里。旁边的教授说:"你知道它花了多大努力才爬上岸来产卵吗?"。
### 结论
做市场需要科学的根据,而非主观臆断。帮龟之前学下龟语,帮人之前懂些人心,这才叫帮上忙啊!
### 故事三
一位老太太每天去菜市场买菜买水果。一天早晨,她提着篮子,来到菜市场。遇到第一个小贩,卖水果的,问:你要不要买一些水果?老太太说你有什么水果?小贩 说我这里有李子、桃子、苹果、香蕉,你要买哪种呢?老太太说我正要买李子。小贩赶忙介绍我这个李子,又红又甜又大,特好吃。老太太仔细一看,果然如此。但 老太太却摇摇头,没有买,走了。
老太太继续在菜市场转。遇到第二个小贩。这个小贩也像第一个一样,问老太太买什么水果?老太太说买李子。小贩接着问,我这里有很多李子,有大的,有小的,有酸的,有甜的,你要什么样的呢?老太太说要买酸李子,小贩说我这堆李子特别酸,你尝尝?老太太一咬,果然很酸,满口的酸水。老太太受不了了,但越酸越高兴,马上买了一斤李子。
但老太太没有回家,继续在市场转。遇到第三个小贩,同样,问老太太买什么?(探寻基本需求)老太太说买李子。小贩接着问你买什么李子,老太太说要买酸李子。但他很好奇,又接着问,别人都买又甜又大的李子,你为什么要买酸李子?(通过纵深提问挖掘需求)老太太说,我儿媳妇怀孕了,想吃酸的。小贩马上说, 老太太,你对儿媳妇真好!儿媳妇想吃酸的,就说明她想给你生个孙子,所以你要天天给她买酸李子吃,说不定真给你生个大胖小子!老太太听了很高兴。小贩又问,那你知道不知道这个孕妇最需要什么样的营养?(激发出客户需求)老太太不懂科学,说不知道。小贩说,其实孕妇最需要的维生素,因为她需要供给这个胎儿维生素。所以光吃酸的还不够,还要多补充维生素。他接着问那你知不知道什么水果含维生素最丰富?(引导客户解决问题)老太太还是不知道。小贩说,水果之中,猕猴桃含维生素最丰富,所以你要是经常给儿媳妇买猕猴桃才行!这样的话,你确保你儿媳妇生出一个漂亮健康的宝宝。老太太一听很高兴啊,马上买了一斤猕猴桃。当老太太要离开的时候,小贩说我天天在这里摆摊,每天进的水果都是最新鲜的,下次来就到我这里来买,还能给你优惠。从此以后,这个老太太每天在他这里买水果。
### 结论
上面已经说得很明了了,深入挖掘用户需求,才能挖到矿,而不是坑。
### and then...
需求是人的一种本能,就好像人饿需要吃,饱是需求(目的);人累需要休息,恢复体力是需求(目的);人走需要路,到达目的地是需求(目的)。人做出的每一个举动都是由其需求,或者说是欲求作为支撑而产生的。
而作为产家(具有生产能力的组织、个人,而我们都是产家),需要知道的是,每一样产品必然由内部规律发展和外部需求更新作为动力才得以产生的。
在这里,我想分享三种由需求产生的定位,内容可能比较片面,请多多包容。
1. 以人为本。强调用户体验,其主体为用户,这种定位的目标是想让产品融入用户的生活、理念当中,让用户产生依赖,排斥外物。事例有苹果公司。
2. 以技术为本。强调创新思想,其主体是行业,这种地位的目标是引领行业的发展,起到标杆作用,甚至影响世界发展的步伐,对外延行业也具有深厚的影响。事例有IBM公司。
3. 以效率为本。强调综合能力,其主体是市场,这种定位的目标是快速生成所需产品,综合使用多种手段以达到目的,迅速抢占市场份额。事例有很多很多这样的公司,包括俺们公司。
### So
需求是目的,是本质的东西,是驱使行为产生的必然条件,仅追求表征,是一种错误的理解(如华而不实的效果)。
之前一直有人问html5能做什么,其实这是本末倒置的;需求必须放在第一位,与其更多地去提出某些技术疑问,倒不如想想还有哪些需求没有被发掘出来,但前提是需求必须合理,而不要想YY。
任何一个伟大的产品都是由那么一个、两个需求慢慢探索、深化、延展而来的,相信未来我们也能做出这样的产品。
## 二、技术方面
在了解完需求之后,现在就要根据需求去选择相应的手段进行实施,常人说“方法总比困难多”,在众多的方法中,它应该称得上最亮丽的一员,让我来介绍一下今天的主角——HTML。
### HTML发展史
1980年,由蒂姆·伯纳斯·李,互联网之父,创建出来,当时是以纯文本为基础,并配合少量的Tag,作为他们小部分人群进行信息交流之用。作为爸爸,不太满足孩纸只能干这些事情,然后他把伟大的理想寄托在这四肢残缺的孩纸身上(故事有点类似阿童木的桥段)。在之后几年的工作里,他不断强化,孩纸也在爸爸的襁褓中从徐徐爬行,到正常行走(虽然还是有点变扭)。然后契机终于出现了,到了1993年,他孩纸的fans cup终于成立了——HTML+,随后这个不大不小的组织终于在老爸的辛勤付出中成为了众所周知的W3C组织。在大家的细心照料和严加看管之下,孩纸终于在2000年5月15日拿到ta出生以来第一张毕业证——ISO HTML(基于严格的HTML4.01语法),他爸感慨万分啊!虽然孩纸个子虽小,但力量十足,可孩纸也学会了低调做人,高调做事。2010年的那个秋天,乔帮主看不过眼了,向各路英雄发话:“这孩纸我照顶了!”,无奈的F弟弟也许从此再也拿不到一等奖学金了,悲催的人生啊!从此,html这娃过上了幸福而波折的生活了!(故事仍在继续......预知后事如何,请看下回分解)
### Web发展史
而所谓打死不离亲兄弟,web这个brother始终是html的坚强后盾,不离不弃,互相依偎,相互鼓励,不过他为人更低调,通常喜欢人家叫他n.0,表面平静,但内里暗藏汹涌,他的方向很专一——就是学做人,但想法和做法却很多,这里就不一一介绍了。
### 外延发展
两兄弟十分博爱,并喜欢帮助他人,由此,不少的干兄弟姐妹也在他们的庇护中,茁壮成长。
* 视觉设计
* 体验设计
* 程序语言
* 种类/概念
* 插件
* 库(前端库、后端库)
* 浏览器
### 为什么需要HTML
讲了这么多,让我归纳一下,html这孩纸存在的理由。
1. 易学易用
2. 相对统一,css/js等的调用在各种平台相对统一
3. 有序结构,符合XML的结构
4. 横跨平台,通过浏览器这个无所不知的平台,就可以运行页面了
5. 模块清晰,img负责图片展示、css负责样貌展示、javascript负责效果行为、title负责标题展示、h系列负责文章标题等
6. 广度延伸,电脑、手机、电视、平板设备、电子书等
7. 强大功能,video、object、embed、audio、canvas、svg、web storage、web DB、drag and drop等
### So
技术是途径,是加快达成目的的重要力量。
web的发展离不开html这个重要的展示载体,html的成长也离不开web的发展方向和动力,两者相互相成。
web的发展是不断收拢外延,贴近人心的过程。
html伴随web的发展,其内涵和功能不断得到充实,而且也不断向软件工程靠拢,趋向标准化。
html伴随web的发展,其内涵和功能不断得到充实,而且也不断向软件工程靠拢,趋向标准化。
html发展到现在基本上已经可以满足大多数人的需求。
如果只将html定位于浏览器的展示载体,你会失去很多,时至今日,它已经渗透到多个方面,如服务器、桌面程序、手机程序、独立展示平台(如图书馆的大屏触控电子书)等。
## 三、具体案例
所谓“心动不如行动”,现在就让我们来窥见一下,究竟HTML有哪些葫芦用来装他的药。
* 游戏网站(2D、3D)
* 实时响应网站
* 单页网站
* 个人网站
* 购物网站
* 后台管理网站
### So
HTML5发展至今已经可以做很多5年前想都不敢想的事情。
想法有多大,H就有多大!(当然,前提是没大牛,没奶喝)
## 四、优势特征
竟然已经有那么多的公司、项目在使用HTML5,那让我们来看一下它到底有哪些优势和特点。
### 八大技术特征
1. 本地存储——在应用缓存,本地存储,索引数据库和文件应用程序接口的帮助下,HTML5应用甚至能在没有因特网连接的情况下工作。
2. 语义学——作为HTML5的前端和中心,语义学能够赋予框架结构以意义。更详尽的标签组合以及资源描述框架,微型数据和微型格式将为你和你的用户打造一套数据驱动的网络。
3. 设备访问——地理定位只是一个开始,HTML5能够让应用程序访问连结到你计算机上的任何设备。
4. 连结性——更有效率的连结性将能带来更实时的聊天,更快的游戏速度以及更好的沟通交流。服务器与客户端之间的网络套接字和邮件摄像头将比以往更加便捷
5. 多媒体——音频和视频可是HTML5世界的一等公民,他们将与你的应用程序和网站和睦共处。灯光,摄影,开始!
6. 平面和三维效果——在SVG, Canvas, WebGL和CSS3 3D效果这些特性之间,你一定能找到让你的用户眼花缭乱,美不胜收的创意。
7. 性能和集成——使你的应用程序和网络在大量诸如Web Workers和XMLHttpRequest 2这样的技术下更加快速。没有人愿意停下了等你跟进的。
8. CSS3——在不牺牲你的讲义结构和性能的情况下,CSS3提供了大量的样式效果和加强你的网络应用。另外WOFF(Web Open Font Format)提供了前所未有的印刷灵活性控制。
### 个人总结的优势
1. 响应式布局,面向多终端——适应不同分辨率、设备,对布局进行调整(需要配合适当的设计板式和CSS即可基本满足)。
2. 渐进增强——基础条件上兼容旧式浏览器,新式浏览器则可以调用相关新功能。
3. 逐渐贴近软件应用发展——从近年来的发展方向上看,web app定会不断深化,从开发模式到设计思想上,会不断吻合现代软件开发的发展途径。
4. 各种强化的内置组件——如video、canvas、input等的元素。
5. 合理的语义化和功能结构元素——从字面上看就能知道元素的作用,如video表示视频标签。
6. 各种贴心的细节关怀——如input的各种type在移动设备上的表现和内置作用,以及为其添加的新属性require、patten等,无不表现其对开发者和初学者的细节关怀。
7. 一次开发,多平台使用——只要有浏览器或阴性还有浏览器,页面就可以展示。
8. 利于seo——提供更多的seo进行定位的元素和属性,但前提是要遵循语义化的结构。
## 总结
最后,用一句话总结就是——
> 信距!无死错人嘅!
|
Python | UTF-8 | 3,463 | 2.578125 | 3 | [] | no_license | from pathlib import Path
from flask import g, current_app
from sketchbook.db import get_db
from werkzeug.utils import secure_filename
from werkzeug.exceptions import abort
def load_projects():
"""Load projects of a logged in user and keep in g to make available for menu etc"""
if not g.user:
g.projects = None
else:
g.projects = get_db().execute("SELECT * FROM project WHERE user_fk = ? AND name NOT LIKE '.%';", (g.user['id'], )).fetchall()
def get_projects(include_private=False):
"""Load all projects for a logged in user"""
db = get_db()
sql = "SELECT * FROM project WHERE user_fk = ?"
if not include_private:
sql += " AND name NOT LIKE '.%'"
return db.execute(sql, (g.user['id'], )).fetchall()
def get_project(id):
"""
Load a single project by id
:param id: <int> id of project to load
:returns: <sqlite3.Row> project
"""
db = get_db()
project = db.execute("SELECT * FROM project WHERE id = ?;", (id, )).fetchone()
if project is None:
abort(404, f"Could not find project with id {id}")
if project['user_fk'] != g.user['id']:
abort(403, "You can only edit projects that you own")
return project
def get_project_byname(name):
db = get_db()
project = db.execute("SELECT * FROM project WHERE name = ?;", (name, )).fetchone()
if project is None:
abort(404, f"Could not find project with name {name}")
if project['user_fk'] != g.user['id']:
abort(403, "You can only edit projects that you own")
return project
def get_items(project_id):
"""
Load all items belonging to a certain project.
:param project_id: <int> id of project
:return: <list> list of items
"""
db = get_db()
items = db.execute("SELECT * FROM item WHERE project_fk = ? AND user_fk = ?;", (project_id, g.user['id'] )).fetchall()
return items
def get_item(id):
"""
Get one item by id
:param id: <int> id of item to get
:return: <sqlite3.Row> item
"""
db = get_db()
item = db.execute("SELECT * FROM item WHERE id = ?;", (id, )).fetchone()
if item is None:
abort(404, f"Could not find item with id {id}")
if item['user_fk'] != g.user['id']:
abort(403, "You can only edit and view items that you own")
return item
def is_unique_name(name):
"""
Check if a project name is unique.
:param name: <str> name to check
:return: <bool> True or False
"""
db = get_db()
project = db.execute("SELECT * FROM project WHERE name = ? AND user_fk = ?;", (name, g.user['id'])).fetchone()
if project is not None:
return False
return True
def delete_item(item):
"""
Delete an item. Deletes the copy of the item if it's an image or pdf
:param item: <sqlite.Row> item
:return: <int> item id
"""
if item['local_path']:
local_path = current_app.root_path + item['local_path']
Path(local_path).unlink()
db = get_db()
db.execute("DELETE FROM item WHERE id = ?;", (item['id'], ))
db.commit()
iid = item['id']
del item
return iid
def is_allowed_type(filename):
extension = filename.split('.')[-1].lower()
return '.' in filename and extension in current_app.config['ALLOWED_EXTENSIONS']
def save_uploaded_file(file):
if not '.' in file.filename:
error = "no . in filename"
return False, error
if not is_allowed_type(file.filename):
error = f"Illegal filetype ({file.filename.split('.')[-1].lower()})"
return False, error
filename = secure_filename(file.filename)
local_path = g.user['user_dir'] + '/' + filename
save_path = current_app.root_path + local_path
file.save(save_path)
return local_path, None
|
Swift | UTF-8 | 9,237 | 3.203125 | 3 | [] | no_license | //
// Day5.swift
// Year2019
//
// Created by PJ COOK on 05/12/2019.
// Copyright © 2019 Software101. All rights reserved.
//
import Foundation
import InputReader
public class AdvancedIntCodeComputer {
private var data: [Int]
public var readData: [Int] { return data }
public init(data: [Int]) {
self.data = data
}
private func readData(_ index: Int) -> Int {
return data[index]
}
private func writeData(_ index: Int, _ value: Int) {
data[index] = value
}
public func process(_ readInput: ()->Int, processOutput: ((Int)->())? = nil, finished: (()->Void)? = nil, forceWriteMode: Bool = true) -> Int {
var instructionIndex = 0
var output = -1
func writeOutput(_ value: Int) {
output = value
processOutput?(output)
}
// print(data)
var instruction = Instruction(
readData: readData,
writeData: writeData,
finished: {},
writeOutput: writeOutput,
readInput: readInput,
instructionIndex: instructionIndex,
forceWriteMode: forceWriteMode
)
// print(data)
while instruction.opCode != .finished {
// print(data)
instructionIndex = instruction.instructionIndex
instruction = Instruction(
readData: readData,
writeData: writeData,
finished: {},
writeOutput: writeOutput,
readInput: readInput,
instructionIndex: instructionIndex,
relativeBase: instruction.relativeBase,
forceWriteMode: forceWriteMode
)
}
finished?()
return output
}
}
public struct Instruction {
public enum OpCode: Int {
case add = 1
case multiply = 2
case input = 3
case output = 4
case jumpIfTrue = 5
case jumpIfFalse = 6
case lessThan = 7
case equals = 8
case adjustRelativeBase = 9
case finished = 99
public func incrementPosition(_ instructionIndex: Int) -> Int {
switch self {
case .jumpIfTrue, .jumpIfFalse: return instructionIndex
case .add, .multiply, .lessThan, .equals: return instructionIndex + 4
case .input, .output, .adjustRelativeBase: return instructionIndex + 2
case .finished: return instructionIndex
}
}
}
public enum Mode: Int {
case position = 0
case immediate = 1
case relative = 2
}
public let opCode: OpCode
public let instructionIndex: Int
public let relativeBase: Int
public init(
readData: (Int)->Int,
writeData: (Int, Int)->Void,
finished: ()->Void,
writeOutput: (Int)->Void,
readInput: ()->Int?,
instructionIndex: Int,
relativeBase: Int = 0,
forceWriteMode: Bool = true
) {
var instructionIndex = instructionIndex
let instruction = readData(instructionIndex)
let d = instruction % 100
let c = instruction % 10000 % 1000 / 100
let b = instruction % 10000 / 1000
let a = instruction / 10000
guard
let mode3 = Mode(rawValue: a),
let mode2 = Mode(rawValue: b),
let mode1 = Mode(rawValue: c),
let code = OpCode(rawValue: d)
else {
opCode = .finished
self.instructionIndex = instructionIndex
self.relativeBase = relativeBase
return
}
opCode = code
let param2Mode = mode2
let param1Mode = mode1
let writeMode = forceWriteMode ? .position : mode3
// print(opCode, param1Mode, param2Mode, writeMode, readData(instructionIndex+1), readData(instructionIndex+2), readData(instructionIndex+3))
switch opCode {
case .add:
let (value1, value2, writeIndex) =
Instruction.readThreeValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode, writeMode: writeMode)
writeData(writeIndex, value1 + value2)
self.relativeBase = relativeBase
case .multiply:
let (value1, value2, writeIndex) =
Instruction.readThreeValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode, writeMode: writeMode)
writeData(writeIndex, value1 * value2)
self.relativeBase = relativeBase
case .input:
let writeIndex = Instruction.writePosition(readData: readData, instructionIndex: instructionIndex+1, relativeBase: relativeBase, mode: param1Mode)
if let input = readInput() {
writeData(writeIndex, input)
}
self.relativeBase = relativeBase
case .output:
let output = Instruction.read(readData: readData, instructionIndex: instructionIndex+1, relativeBase: relativeBase, mode: param1Mode)
writeOutput(output)
self.relativeBase = relativeBase
case .jumpIfTrue:
let (value1, value2) =
Instruction.readTwoValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode)
instructionIndex = value1 != 0 ? value2 : instructionIndex + 3
self.relativeBase = relativeBase
case .jumpIfFalse:
let (value1, value2) =
Instruction.readTwoValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode)
instructionIndex = value1 == 0 ? value2 : instructionIndex + 3
self.relativeBase = relativeBase
case .lessThan:
let (value1, value2, writeIndex) =
Instruction.readThreeValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode, writeMode: writeMode)
writeData(writeIndex, value1 < value2 ? 1 : 0)
self.relativeBase = relativeBase
case .equals:
let (value1, value2, writeIndex) =
Instruction.readThreeValues(readData: readData, instructionIndex: instructionIndex, relativeBase: relativeBase, param1Mode: param1Mode, param2Mode: param2Mode, writeMode: writeMode)
writeData(writeIndex, value1 == value2 ? 1 : 0)
self.relativeBase = relativeBase
case .adjustRelativeBase:
let value1 = Instruction.read(readData: readData, instructionIndex: instructionIndex+1, relativeBase: relativeBase, mode: param1Mode)
self.relativeBase = relativeBase + value1
case .finished:
self.relativeBase = relativeBase
finished()
}
self.instructionIndex = opCode.incrementPosition(instructionIndex)
}
private static func readTwoValues(readData: (Int)->Int, instructionIndex: Int, relativeBase: Int, param1Mode: Mode, param2Mode: Mode) -> (Int,Int) {
(
Instruction.read(readData: readData, instructionIndex: instructionIndex+1, relativeBase: relativeBase, mode: param1Mode),
Instruction.read(readData: readData, instructionIndex: instructionIndex+2, relativeBase: relativeBase, mode: param2Mode)
)
}
private static func readThreeValues(readData: (Int)->Int, instructionIndex: Int, relativeBase: Int, param1Mode: Mode, param2Mode: Mode, writeMode: Mode) -> (Int,Int,Int) {
return (
Instruction.read(readData: readData, instructionIndex: instructionIndex+1, relativeBase: relativeBase, mode: param1Mode),
Instruction.read(readData: readData, instructionIndex: instructionIndex+2, relativeBase: relativeBase, mode: param2Mode),
Instruction.writePosition(readData: readData, instructionIndex: instructionIndex+3, relativeBase: relativeBase, mode: writeMode)
)
}
private static func writePosition(readData: (Int)->Int, instructionIndex: Int, relativeBase: Int, mode: Mode) -> Int {
switch mode {
case .immediate: return instructionIndex
case .position: return readData(instructionIndex)
case .relative: return relativeBase + readData(instructionIndex)
}
}
private static func read(readData: (Int)->Int, instructionIndex: Int, relativeBase: Int, mode: Mode) -> Int {
switch mode {
case .immediate: return readData(instructionIndex)
case .position: return readData(readData(instructionIndex))
case .relative: return readData(relativeBase + readData(instructionIndex))
}
}
}
|
PHP | UTF-8 | 2,026 | 3.5 | 4 | [] | no_license | <?php
/*
Realizar una clase llamada “Auto” que posea los siguientes atributos privados:
_color (String)
_precio (Double)
_marca (String).
_fecha (DateTime)
Realizar un constructor capaz de poder instanciar objetos pasándole todos los parámetros:
Realizar un método de instancia llamado “AgregarImpuestos”, que recibirá un doble por
parámetro y que se sumará al precio del objeto.
Realizar un método de clase llamado “MostrarAuto”, que recibirá un objeto de tipo “Auto”
por parámetro y que mostrará todos los atributos de dicho objeto.
Crear el método de instancia “Equals” que permita comparar dos objetos de tipo “Auto”. Sólo
devolverá TRUE si ambos “Autos” son de la misma marca.
Crear un método de clase, llamado “Add” que permita sumar dos objetos “Auto” (sólo si son
de la misma marca, y del mismo color, de lo contrario informarlo) y que retorne un Double con
la suma de los precios o cero si no se pudo realizar la operación.
Ejemplo: $importeDouble = Auto::Add($autoUno, $autoDos);
En testAuto.php:
● Crear dos objetos “Auto” de la misma marca y distinto color.
● Crear dos objetos “Auto” de la misma marca, mismo color y distinto precio.
● Crear un objeto “Auto” utilizando la sobrecarga restante.
● Utilizar el método “AgregarImpuesto” en los últimos tres objetos, agregando $ 1500
al atributo precio.
Villegas, Octavio PHP- 2019 Página 1
● Obtener el importe sumado del primer objeto “Auto” más el segundo y mostrar el
resultado obtenido.
● Comparar el primer “Auto” con el segundo y quinto objeto e informar si son iguales o
no.
● Utilizar el método de clase “MostrarAuto” para mostrar cada los objetos impares (1, 3,
5)
*/
class Auto
{
private $color;
private $precio;
private $marca;
private $fecha;
function __construct($color,$precio,$marca,$fecha)
{
this->color = $color;
this->precio = $precio;
this->marca = $marca;
this->fecha = $fecha;
}
}
?> |
Markdown | UTF-8 | 2,727 | 2.84375 | 3 | [] | no_license | ---
title: "Cómo: Trabajar con diccionarios mediante LINQ to XML (C#) | Microsoft Docs"
ms.custom:
ms.date: 2015-07-20
ms.prod: .net
ms.reviewer:
ms.suite:
ms.technology:
- devlang-csharp
ms.topic: article
dev_langs:
- CSharp
ms.assetid: 57bcefe3-8433-4d3b-935a-511c9bcbdfa8
caps.latest.revision: 3
author: BillWagner
ms.author: wiwagn
translationtype: Human Translation
ms.sourcegitcommit: a06bd2a17f1d6c7308fa6337c866c1ca2e7281c0
ms.openlocfilehash: 1570e4bb0be707d1c27e8bdfc1ef853413d70784
ms.lasthandoff: 03/13/2017
---
# <a name="how-to-work-with-dictionaries-using-linq-to-xml-c"></a>Cómo: Trabajar con diccionarios mediante LINQ to XML (C#)
A menudo resulta cómodo convertir variedades de estructuras de datos a XML y de XML a otras estructuras de datos. En este tema se muestra una implementación específica de este enfoque general mediante una conversión de <xref:System.Collections.Generic.Dictionary%602> a XML y de XML.
## <a name="example"></a>Ejemplo
En este ejemplo se usa una forma de construcción funcional en la que una consulta proyecta nuevos objetos <xref:System.Xml.Linq.XElement> y la colección resultante se pasa como argumento al constructor del objeto raíz <xref:System.Xml.Linq.XElement>.
```csharp
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Child1", "Value1");
dict.Add("Child2", "Value2");
dict.Add("Child3", "Value3");
dict.Add("Child4", "Value4");
XElement root = new XElement("Root",
from keyValue in dict
select new XElement(keyValue.Key, keyValue.Value)
);
Console.WriteLine(root);
```
Este código genera el siguiente resultado:
```xml
<Root>
<Child1>Value1</Child1>
<Child2>Value2</Child2>
<Child3>Value3</Child3>
<Child4>Value4</Child4>
</Root>
```
## <a name="example"></a>Ejemplo
El siguiente código genera un diccionario de XML.
```csharp
XElement root = new XElement("Root",
new XElement("Child1", "Value1"),
new XElement("Child2", "Value2"),
new XElement("Child3", "Value3"),
new XElement("Child4", "Value4")
);
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (XElement el in root.Elements())
dict.Add(el.Name.LocalName, el.Value);
foreach (string str in dict.Keys)
Console.WriteLine("{0}:{1}", str, dict[str]);
```
Este código genera el siguiente resultado:
```
Child1:Value1
Child2:Value2
Child3:Value3
Child4:Value4
```
## <a name="see-also"></a>Vea también
[Proyecciones y transformaciones (LINQ to XML) (C#)](../../../../csharp/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md)
|
Rust | UTF-8 | 2,507 | 2.921875 | 3 | [] | no_license | use super::biome::{Biome, BiomeLibrary};
use super::layers::{Layer, SoilLayer, TileLayer};
use super::tile::{Soil, Tile};
use crate::wg_utils::point_2d::Point2D;
use tcod::console::Console;
pub struct Map {
pub width: i32,
pub height: i32,
pub soils: SoilLayer,
pub tiles: TileLayer,
pub biome: Biome,
}
impl Map {
pub fn create(
width: i32,
height: i32,
soils: SoilLayer,
tiles: TileLayer,
biome: Biome,
) -> Self {
Map {
width,
height,
soils,
tiles,
biome,
}
}
pub fn draw(&self, map_console: &mut tcod::console::Offscreen) -> () {
for y in 0..self.height {
for x in 0..self.width {
let current_soil_ref: &Soil = self.soils.get_cell_ref_from_point(x, y);
let current_tile_ref: &Tile = self.tiles.get_cell_ref_from_point(x, y);
map_console.print(x, y, ¤t_tile_ref.glyph);
map_console.set_char_background(
x,
y,
tcod::Color::new(
current_soil_ref.color[0],
current_soil_ref.color[1],
current_soil_ref.color[2],
),
tcod::BackgroundFlag::Set,
);
map_console.set_char_foreground(
x,
y,
tcod::Color::new(
current_tile_ref.color[0],
current_tile_ref.color[1],
current_tile_ref.color[2],
),
);
}
}
}
}
pub struct MapGenerator;
impl MapGenerator {
pub fn generate_map(width: i32, height: i32) -> Map {
let mut tiles: TileLayer = TileLayer::create_empty(width, height);
let mut soils: SoilLayer = SoilLayer::create_empty(width, height);
let biome = BiomeLibrary::get_biome_by_name("plains").unwrap();
for index in 0..(width * height) {
let point: Point2D = Point2D::calc_point_from_index(index, width);
let picked_soil = biome.pick_random_soil();
soils.replace_cell((point.x, point.y), picked_soil);
let picked_tile = biome.pick_random_tile();
tiles.replace_cell((point.x, point.y), picked_tile);
}
Map::create(width, height, soils, tiles, biome)
}
}
|
Markdown | UTF-8 | 1,150 | 2.71875 | 3 | [
"MIT"
] | permissive | <text lang="cn">
#### 预加载的卡片
数据读入前会有文本块样式。
</text>
```html
<template>
<div>
<s-switch on-change='onChange' />
<s-card
title="Card title"
hoverable="{{true}}"
style="width: 300px;margin-top: 16px;"
loading="{{loading}}"
>
<template slot="extra">
<a href="#">More</a>
</template>
<s-meta title="Europe Street beat" description="www.instagram.com">
<template slot="avatar">
<s-avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
</template>
</s-meta>
</s-card>
</div>
</template>
<script>
import {Card, Avatar, Switch} from 'santd';
export default {
components: {
's-card': Card,
's-meta': Card.Meta,
's-avatar': Avatar,
's-switch': Switch
},
initData() {
return {
loading: true
}
},
onChange(checked) {
this.data.set('loading', !checked);
console.log(checked);
}
}
</script>
```
|
C | UTF-8 | 248 | 3.734375 | 4 | [] | no_license | #include<stdio.h>
int fact(int);
void main()
{
int n,factorial;
printf("Enter the number: ");
scanf("%d",&n);
factorial=fact(n);
printf("factorial is %d",factorial);
}
int fact(m)
{
if(m==0)
return(1);
else
return(m*fact(m-1));
}
|
Markdown | UTF-8 | 3,188 | 4.375 | 4 | [] | no_license | ### LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
```
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
```
https://leetcode.com/problems/lru-cache/#/description
```
//1.Hash table: key->list_iterator
//2.Maintain a recent used list (find/update to front/remove back)
namespace {
struct KeyValue{
int key;
int value;
KeyValue(int k,int v):key(k),value(v){}
};
}
class LRUCache {
private:
const int m_capacity;
list<KeyValue> m_list;
typedef list<KeyValue>::iterator ListIter;
unordered_map<int,ListIter> m_hash;
typedef unordered_map<int,ListIter> HashTable;
void updateToRecentUsed(HashTable::iterator & hash_it, const KeyValue key_value){
m_list.erase(hash_it->second);
m_list.push_front(key_value);
hash_it->second = m_list.begin();
}
void checkCapacityAndDelete(){
if(m_hash.size()>m_capacity){
KeyValue key_value = m_list.back();
m_list.pop_back();
HashTable::iterator hash_it = m_hash.find(key_value.key);
if(hash_it!=m_hash.end()){
m_hash.erase(hash_it);
}
}
}
public:
LRUCache(int capacity):m_capacity(capacity) {}
int get(int key) {
int get_value = -1;
HashTable::iterator hash_it = m_hash.find(key);
if(hash_it!=m_hash.end()){
KeyValue key_value = *(hash_it->second);
get_value = key_value.value;
//update to recent used
updateToRecentUsed(hash_it,key_value);
}
return get_value;
}
void put(int key, int value) {
HashTable::iterator hash_it = m_hash.find(key);
KeyValue key_value(key,value);
std::cout<<"put:"<<key<<","<<value<<std::endl;
//Not Found
//insert
if(hash_it == m_hash.end()){
m_list.push_front(key_value);
m_hash[key] = m_list.begin();
checkCapacityAndDelete();
std::cout<<"insert:"<<key<<","<<value<<std::endl;
return;
}
//Found
//update to recentd
std::cout<<"found:"<<key<<std::endl;
updateToRecentUsed(hash_it,key_value);
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
``` |
C++ | UTF-8 | 3,421 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | /*
* CodeBuffer.cpp
*
* Created on: March 3, 2010
* Author: lawrence.daniels@gmail.com
*/
#include <stdio.h>
#include "CodeBuffer.h"
/**
* Constructor
*/
CodeBuffer::CodeBuffer( int initialSize, int growth ): ByteBuffer( initialSize, growth ) {
// do nothing
}
/**
* Constructor
*/
CodeBuffer::CodeBuffer( char* buffer, int bufferSize, int growth ): ByteBuffer( buffer, bufferSize, growth ) {
// do nothing
}
/**
* Destruction
*/
CodeBuffer::~CodeBuffer() {
// do nothing
}
/**
* Allocates a block of memory
* @param size the size of the desired memory block
*/
OFFSET_T CodeBuffer::allocate( OFFSET_T size ) {
// make sure enough memory exists
ensurePosition( length + size );
// mark the start of the allocated segment
OFFSET_T start = length;
// allocate the block
length += size;
// return an offset to the block
return start;
}
/**
* Displays the contents of the buffer at
* the current positions
*/
void CodeBuffer::dump( int count ) {
const int width = 16;
char *buf1 = new char[width*3+1];
char *buf2 = new char[width+1];
// zero the buffers
*buf1 = '\0';
*buf2 = '\0';
// get a pointer to the buffer
char* p = &buffer[position];
OFFSET_T index = position;
int n = 0;
for( n = 1; n <= count; n++ ) {
const char c = *p;
sprintf( buf1, "%s %02X", buf1, c & 0xFF );
sprintf( buf2, "%s%c", buf2, ( c >= 33 && c <= 126 ) ? c : '.' );
p++;
index++;
if( n % width == 0 ) {
printf( "[%08lX]%s %s\n", index - width, buf1, buf2 );
*buf1 = '\0';
*buf2 = '\0';
}
}
// display the last row
if( n % width > 0 ) {
printf( "[%08lX]%-48s %-16s\n", index - ( ( n - 1 ) % width ), buf1, buf2 );
}
// delete the buffers
delete buf1;
delete buf2;
}
/**
* Retrieves the next instruction from the current position within buffer
*/
INSTRUCTION_T CodeBuffer::getInstruction( OFFSET_T offset ) {
// cache the instruction size
int size_t = sizeof( INSTRUCTION_T );
// is there's sufficient capacity?
if( offset + size_t > length ) {
return 0;
}
// create an integer pointer to current position
INSTRUCTION_T *p = (INSTRUCTION_T*)&buffer[offset];
// return the next instruction
return *p;
}
/**
* Retrieves a reference to the instruction from the given offset within buffer
*/
INSTRUCTION_T* CodeBuffer::getInstructionPtr( OFFSET_T offset ) {
// cache the instruction size
int size_t = sizeof( INSTRUCTION_T );
// is there's sufficient capacity?
if( offset + size_t > length ) {
printf( "CodeBuffer::getInstruction - attempt to access data beyond the limit (p = %05lX, limit=%05lX)\n", offset + size_t, length );
return NULL;
}
// create an integer pointer to current position
INSTRUCTION_T *p = (INSTRUCTION_T*)&buffer[offset];
// return the value
return p;
}
/**
* Adds an instruction to the underlying buffer
* @param instruction the given instruction
*/
OFFSET_T CodeBuffer::putInstruction( INSTRUCTION_T instruction ) {
// get the current offset
OFFSET_T curofs = position;
// get the size of the instruction
int size_t = sizeof(INSTRUCTION_T);
// make sure the buffer is large enough
ensurePosition( position + size_t );
// create a pointer to current offset
INSTRUCTION_T *p = (INSTRUCTION_T*)&buffer[position];
// write the instruction to memory
*p = instruction;
// advance the pointer
position += size_t;
// protect the internal integrity
update();
// return the last offset
return curofs;
}
|
Java | UTF-8 | 966 | 2.8125 | 3 | [] | no_license | package com.Authorization;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CodeGenerator {
private String macAddr;
private String addCode;
public CodeGenerator(String macAddr){
this.macAddr = macAddr;
}
public CodeGenerator(String macAddr, String addCode){
this.macAddr = macAddr;
this.addCode = addCode;
}
public String genCode(){ // creates MD5 hash
String md5 = "";
String mixedCode = macAddr+addCode;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(mixedCode.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < byteData.length ; i++){
sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
}
md5 = sb.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return md5.substring(0, 15);
}
}
|
Java | UTF-8 | 425 | 2.25 | 2 | [] | no_license | package customer;
import java.util.List;
public interface CustomerService {
//CRUD (Create, Read, Update, Delete)
void customer_insert(CustomerVO vo); //고객 정보 신규 저장
List<CustomerVO> customer_list(); //고객 목록 조회
CustomerVO customer_detail(int id); //고객 상세 조회
void customer_update(CustomerVO vo); //고객 정보 변경
void customer_delete(int id); //고객 정보 삭제
}
|
Markdown | UTF-8 | 2,761 | 2.953125 | 3 | [] | no_license | # Disclaimer
Wrote this in my free time as a **private person**. **This is not affiliated with SAP!**
# Purpose
The purpose of this tool is to allow a **oAuth user grant flow JWT retrieval** been automated within a CLI tool.
Most tools only implemented client credentials flow.
This CLI tool will boostrap a small http server in the background that will take care of the oAuth redirect after a successfull authentication at the IdP.
**After the callback has been triggered it will print the JWT with the user principal on the console.**
# Usage
The MacOS binary is already been shipped in this repo, but feel free to build it once again if you don't trust or if you need a Windows binary :)
```zsh
go build -o /usr/local/bin/xsuaa-cli cmd/main.go
```
# How to use it?
```zsh
xsuaa-cli -username user -password "password" -api https://api.cf.sap.hana.ondemand.com -appname yourappname
```
# arguments
```zsh
-api string
API endpoint of CF controller
-appguid string
App Guid - Setting this will ignore the app name parameter. Either appguid or appname must be set.
-appname string
Name of your app. Must be unique. Either appguid or appname must be set.
-h Prints out the list of arguments and their description
-help
Prints out the list of arguments and their description
-i Interactive mode - When multiple apps are found for a given name you are able to choose
-password string
Password to login at api endpoint
-username string
User to login at api endpoint
-verbose
Verbose mode
```
Guess the most important argument is either **appguid** or **appname**.
If you set **appguid** it will ignore the appname argument and tries to get the token for the given appguid.
**appname** is a little bit more flexible. By default the CLI tries to find an app for the given name, but refuses to retrieve a JWT if multiple apps are found.
## Interactive mode
You can use the **-i** argument to tell the CLI tool to go in interactive mode. If the CLI finds more than one suitable app for a given name it will show you a list to choose from.
An example for interactive mode might go like this:
```zsh
xsuaa-cli -username user -password "password" -api https://api.cf.sap.hana.ondemand.com -appname yourappname -i
```
As a result you might then see something like this, showing you some meta about the app to make your life easier
```zsh
Multiple apps found for given name - please choose the app from the given list
1. Org: SAP_IT_Cloud_sapitcft Space: onboarding GUID: 451f2afb-c6b6-4dc9-8506-7d8f332805a8
2. Org: SAP_IT_Cloud_sapitcf Space: onboarding GUID: 0243b047-c34b-4a33-a2de-439df9367036
```
If only ONE app is found for a given name, no choice needs to be made.
|
Java | UTF-8 | 1,514 | 3.078125 | 3 | [] | 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 lab7b_2;
/**
*
* @author andro
*/
interface TVStation {
String SATELLITE_NAME = "SKY Network";
String CABLE_TV_NAME = "TATA";
double SIGNAL_FREQUENCY = 67;
abstract void show();
}
class Programme {
String programmeName;
String sponser;
Programme(String programmeName, String sponser) {
this.programmeName = programmeName;
this.sponser = sponser;
}
void display() {
System.out.println("Programme Name : " + this.programmeName);
System.out.println("Sponser : " + this.sponser);
}
}
class Broadcast extends Programme implements TVStation {
public Broadcast(String programmeName, String sponser) {
super(programmeName, sponser);
}
@Override
public void show() {
System.out.println("Satellite Name : " + SATELLITE_NAME);
System.out.println("Cable TV Name : " + CABLE_TV_NAME);
System.out.println("Signal Frequency : " + SIGNAL_FREQUENCY);
}
}
public class Lab7b_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Broadcast broadcast = new Broadcast("MasterChef", "Ford");
broadcast.display();
broadcast.show();
}
}
|
Java | UTF-8 | 1,184 | 3.703125 | 4 | [] | no_license | package arithmetic;
/**
* @ClassName LongestSequence
* @Description 输入一串数字,找出最长序列长度
* @Author Cao.Zhuang
* @Date 2019/9/26 9:34
*/
public class LongestSequence {
public static void main(String[] args) {
int[] nums = {5, 2, 4, 3, 9, 10};
int[] dp = new int[nums.length];
for (int i = 0; i < dp.length; i++) {
dp[i] = 0;
}
dp[0] = 1;
System.err.println(longestLen(nums, dp));
}
private static int longestLen(int[] nums, int[] dp) {
int maxLen = 0;
for (int i = 0; i < nums.length; i++) {
if (dp[i] == 0) {
int max = 0;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
max = Math.max(max, dp[j] + 1);
}
}
max = max == 0 ? 1 : max;
maxLen = Math.max(maxLen, max);
dp[i] = max;
}
}
for (int i : dp) {
System.err.print(i + " ");
}
System.err.print("\n");
return maxLen;
}
}
|
JavaScript | UTF-8 | 1,052 | 3.25 | 3 | [] | no_license | const express = require('express');
const app = express();
// "/" => "Hi there"
app.get("/", (req, res) => res.send("Hi there, welcome to my assignment!"));
app.get("/speak/:animal", (req, res) => {
const sounds = {
dog: "woof",
pig: "oink",
cat: "I hate you human",
cow: "moo",
goldfish: "..."
};
let animal = req.params.animal.toLowerCase();
var sound = sounds[animal];
res.send("The " + animal + " goes '" + sound + "'.");
});
app.get("/repeat/:message/:times", (req, res) => {
let message = req.params.message + " ";
let times = Number(req.params.times);
let result = "";
for (var i = 0; i < times; i++) {
result += message;
}
res.send(result);
});
// Route for everything else that doesn't match defined routes, should ALWAYS be last because of route order
app.get("*", (req, res) => res.send("You're a noob, there's nothing here!"));
// Tell Express to listen for requests (start server)
app.listen(3000, () => console.log("Server has started.")); |
PHP | UTF-8 | 584 | 2.53125 | 3 | [] | no_license | <?php
session_start();
$name = $_POST['name'];
$phone = $_POST['phone'];
$arr = array();
$con = mysqli_connect('localhost','root','','access');
// trying to acccess the data of both the table in one array and storing it in session
$data = "SELECT * FROM customer,account where customer.Name = account.Name AND customer.Name='$name'";
$result = mysqli_query($con,$data);
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row;
}
// echo "<pre>";print_r($arr);exit();
$_SESSION["customer"] = $arr;
header("Location:../Admin/admin.php");
?> |
C# | UTF-8 | 774 | 3.765625 | 4 | [] | no_license | using System;
using System.Collections.Generic;
public static class RotationalCipher
{
private static char rotateChar(char ch, int rot)
{
bool isUpper = char.IsUpper(ch);
int currVal = char.ToLower(ch) - 'a';
int newVal = (currVal + rot) % 26;
char newCh = (char)('a' + newVal);
newCh = isUpper ? char.ToUpper(newCh) : newCh;
return newCh;
}
public static string Rotate(string text, int shiftKey)
{
List<char> cipher = new List<char>();
foreach(char ch in text)
{
if (char.IsLetter(ch))
{
cipher.Add(rotateChar(ch, shiftKey));
}
else cipher.Add(ch);
}
return string.Join("", cipher.ToArray());
}
} |
C++ | UTF-8 | 1,328 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#include "LayoutUI.h"
#include "EightEngine\EventManager\EventManager.h"
#include "EightEngine\EventManager\Events\ChangeMenuScreenEventData.h"
void LayoutUI::KeyDown(UINT keyCode)
{
}
void LayoutUI::MoveEvent(const DirectX::XMFLOAT3 &movingDirection)
{
EIGHT_ASSERT(!(movingDirection.z < -1.f || movingDirection.z > 1.f),
"Moving direction must be in <-1, 1> range");
m_ClickableGuiElements[m_SelectedGuiElement]->VHighLightOff();
m_SelectedGuiElement -= static_cast<int>(movingDirection.z);
if (m_SelectedGuiElement > static_cast<int>(m_ClickableGuiElements.size()) - 1)
{
m_SelectedGuiElement = 0;
}
else if (m_SelectedGuiElement < 0)
{
m_SelectedGuiElement = static_cast<int>(m_ClickableGuiElements.size() - 1);
}
m_ClickableGuiElements[m_SelectedGuiElement]->VHighLightOn();
}
void LayoutUI::MouseClick(int x, int y)
{
for (auto &guiElement : m_ClickableGuiElements)
{
if (guiElement->VMouseEvent(x, y))
{
guiElement->VRun();
break;
}
}
}
void LayoutUI::MouseMove(int x, int y)
{
for (UINT i = 0; i < m_ClickableGuiElements.size(); i++)
{
auto &guiElement = m_ClickableGuiElements[i];
if (guiElement->VMouseEvent(x, y))
{
m_ClickableGuiElements[m_SelectedGuiElement]->VHighLightOff();
m_SelectedGuiElement = i;
guiElement->VHighLightOn();
}
}
}
|
JavaScript | UTF-8 | 5,663 | 2.609375 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"GPL-1.0-or-later",
"MIT",
"CPL-1.0",
"NPL-1.1",
"MPL-1.1"
] | permissive | /*
* Copyright 2008 The Closure Compiler Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Definitions for W3C's Selection API.
*
* @see https://w3c.github.io/selection-api/
*
* @externs
*/
/**
* @constructor
* @see http://w3c.github.io/selection-api/#selection-interface
*/
function Selection() {}
/**
* @type {?Node}
* @see https://w3c.github.io/selection-api/#dom-selection-anchornode
*/
Selection.prototype.anchorNode;
/**
* @type {number}
* @see https://w3c.github.io/selection-api/#dom-selection-anchoroffset
*/
Selection.prototype.anchorOffset;
/**
* @type {?Node}
* @see https://w3c.github.io/selection-api/#dom-selection-focusnode
*/
Selection.prototype.focusNode;
/**
* @type {number}
* @see https://w3c.github.io/selection-api/#dom-selection-focusoffset
*/
Selection.prototype.focusOffset;
/**
* @type {boolean}
* @see https://w3c.github.io/selection-api/#dom-selection-iscollapsed
*/
Selection.prototype.isCollapsed;
/**
* @type {number}
* @see https://w3c.github.io/selection-api/#dom-selection-rangecount
*/
Selection.prototype.rangeCount;
/**
* @type {string}
* @see https://w3c.github.io/selection-api/#dom-selection-type
*/
Selection.prototype.type;
/**
* @param {number} index
* @return {!Range}
* @nosideeffects
* @see https://w3c.github.io/selection-api/#dom-selection-getrangeat
*/
Selection.prototype.getRangeAt = function(index) {};
/**
* TODO(tjgq): Clean up internal usages and make the `range` parameter a
* `!Range` per the spec.
* @param {?Range} range
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-addrange
*/
Selection.prototype.addRange = function(range) {};
/**
* @param {!Range} range
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-removerange
*/
Selection.prototype.removeRange = function(range) {};
/**
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-removeallranges
*/
Selection.prototype.removeAllRanges = function() {};
/**
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-empty
*/
Selection.prototype.empty = function() {};
/**
* @param {?Node} node
* @param {number=} offset
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-collapse
*/
Selection.prototype.collapse = function(node, offset) {};
/**
* @param {?Node} node
* @param {number=} offset
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-setposition
*/
Selection.prototype.setPosition = function(node, offset) {};
/**
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-collapsetostart
*/
Selection.prototype.collapseToStart = function() {};
/**
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-collapsetoend
*/
Selection.prototype.collapseToEnd = function() {};
/**
* TODO(tjgq): Clean up internal usages and make the `node` parameter a `!Node`
* per the spec.
* @param {?Node} node
* @param {number=} offset
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-extend
*/
Selection.prototype.extend = function(node, offset) {};
/**
* TODO(tjgq): Clean up internal usages and make the `anchorNode` and
* `focusNode` parameters `!Node` per the spec.
* @param {?Node} anchorNode
* @param {number} anchorOffset
* @param {?Node} focusNode
* @param {number} focusOffset
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-setbaseandextent
*/
Selection.prototype.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {};
/**
* TODO(tjgq): Clean up internal usages and make the `node` parameter a `!Node`
* per the spec.
* @param {?Node} node
* @return {undefined}
* @see http://w3c.github.io/selection-api/#dom-selection-selectallchildren
*/
Selection.prototype.selectAllChildren = function(node) {};
/**
* @return {undefined}
* @see https://w3c.github.io/selection-api/#dom-selection-deletefromdocument
*/
Selection.prototype.deleteFromDocument = function() {};
/**
* @param {!Node} node
* @param {boolean=} allowPartialContainment
* @return {boolean}
* @nosideeffects
* @see https://w3c.github.io/selection-api/#dom-selection-containsnode
*/
Selection.prototype.containsNode = function(node, allowPartialContainment) {};
/**
* @return {?Selection}
* @nosideeffects
* @see https://w3c.github.io/selection-api/#dom-window-getselection
*/
Window.prototype.getSelection = function() {};
/**
* @return {?Selection}
* @nosideeffects
* @see https://w3c.github.io/selection-api/#dom-document-getselection
*/
Document.prototype.getSelection = function() {};
/**
* TODO(tjgq): Clean up internal usages and make this `?function(!Event): void`
* per the spec.
* @type {?function(?Event)}
* @see https://w3c.github.io/selection-api/#dom-globaleventhandlers-onselectstart
*/
Element.prototype.onselectstart;
/**
* @type {?function(!Event): void}
* @see https://w3c.github.io/selection-api/#dom-globaleventhandlers-onselectionchange
*/
Element.prototype.onselectionchange;
|
Java | UTF-8 | 1,677 | 2.125 | 2 | [] | no_license | package com.changuang.domain.entity;
// Generated 2017-12-1 14:27:22 by Hibernate Tools 4.0.0.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
/**
* UserType generated by hbm2java
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "user_type", catalog = "tochatting")
public class UserType implements java.io.Serializable {
private Integer recid;
private String usertypeName;
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
private Date createTime;
public UserType() {
}
public UserType(String usertypeName, Date createTime) {
this.usertypeName = usertypeName;
this.createTime = createTime;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "recid", unique = true, nullable = false)
public Integer getRecid() {
return this.recid;
}
public void setRecid(Integer recid) {
this.recid = recid;
}
@Column(name = "usertype_name", length = 20)
public String getUsertypeName() {
return this.usertypeName;
}
public void setUsertypeName(String usertypeName) {
this.usertypeName = usertypeName;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_time", length = 19)
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
|
Python | UTF-8 | 229 | 3.3125 | 3 | [] | no_license | list1 = [int(i) for i in input()]
count = 0
for i in range(0, len(list1)):
if (list1[i] == 1):
count = count + 1
if (count % 2 == 0):
list1.append(0)
else:
list1.append(1)
for i in list1:
print(i, end="")
|
TypeScript | UTF-8 | 1,680 | 2.5625 | 3 | [] | no_license | 'use strict';
class DianPing {
from = '';
txHash = '';
time = 0;
dpType = '0';
link = '';
name = '';
score = '';
content = '';
constructor(text) {
if (!text) {
return;
}
const o = JSON.parse(text);
this.from = o.from;
this.txHash = o.txHash;
this.time = o.time;
this.link = o.link;
this.name = o.name;
this.score = o.score;
this.content = o.content;
}
toString() {
return JSON.stringify(this);
}
}
const NasDianPing = function () {
LocalContractStorage.defineMapProperty(this, 'sendMap');
LocalContractStorage.defineMapProperty(this, 'recvMap');
};
NasDianPing.prototype = {
init: function () {
},
_push(collectionName, key, value) {
let item = this[collectionName].get(key);
if (!item) {
item = [];
}
item.push(value);
this[collectionName].put(key, item);
},
createDianPing: function (dpType, link, name, score, content) {
const item = new DianPing();
item.from = Blockchain.transaction.from;
item.txHash = Blockchain.transaction.hash;
item.time = Blockchain.transaction.timestamp * 1000;
item.dpType = dpType;
item.link = link;
item.name = name;
item.score = score;
item.content = content;
this._push('sendMap', item.from, item);
this._push('recvMap', item.dpType, item);
return item;
},
queryUserVoucher: function (from) {
let send = this.sendMap.get(from);
if (!send) {
send = [];
}
return send;
},
queryCatVoucher: function (dpType) {
let recv = this.recvMap.get(dpType);
if (!recv) {
recv = [];
}
return recv;
}
};
module.exports = NasDianPing;
|
Markdown | UTF-8 | 5,321 | 3.484375 | 3 | [
"MIT"
] | permissive | ---
date: 2021-12-22
title: 'System Design: SQL vs NoSQL'
---
When deciding what type of database to use for an application system, it's important to know about the strengths and weaknesses of your options. The main two types are SQL (relational database) and NoSQL (non-relational / distributed database).
## SQL
SQL Databases are also known as relational databases. Examples of popular SQL databases include MySQL, PostgreSQL, Microsoft SQL Server, Oracle, CockroachDB. They offer strength in the following areas:
1. **Relationships**: Allows easy querying between data among multiple tables. These relationships are defined using primary and foreign key columns.
2. **Structured Data**: The data is structured using SQL schemas which define the columns and tables in the DB. Because the model / format of the data must be known before storing anything, it reduces room for error in saving data.
3. **ACID compliant**: Atomicity, Consistency, Isolation, Durability. SQL transactions are executed atomically, meaning they are either all excuted or not executed at all if any statement in the group fails. An example of the importance of this feature is demonstrated in the scenario where a user is looking to transfer money from their bank, but lack sufficient funds. Instead of the withdrawal executing, the entire transaction would just fail.
```SQL
BEGIN TRANSACTION t1;
UPDATE balances SET balance = balance - 100 WHERE account_id = 1;
UPDATE balances SET balance = balance + 25 WHERE account_id = 2;
COMMIT TRANSACTION
```
On the other hand, SQL Databases present weaknesses in the following ways:
1. **Structured Data**: Columns and tables have to be set up ahead of time, so these databases take more time to set up compared to NoSQL. They are also not as good at storing/querying unstructured data.
2. **Scaling is difficult**: Horizontal scaling is difficult, so if a system is write-heavy the only option is often to vertically scale the database up which is more expensive in general than provisioning additional servers. For read-heavy systems, you can provision multiple read-only replicas of the DB.
## NoSQL
NoSQL stands for "Not only SQL" and emerged with big data and web/mobile applications. It is rooted in graph, document, key-value pairs and wide-column stores. Examples of popular NoSQL databases include MongoDB, Redis, DynamoDB, Cassandra, CouchDB. The advantages this type of database offers includes:
1. **Unstructured Data**: It does not support table relationships, but instead stores data in documents or key-value pairs. This makes the database more flexible and easier to set up, particularly when storing unstructured data.
2. **Horizontal Scaling**: NoSQL databases can be divded across different data stores, allowing for distributed databases, since it lacks relationships. This makes it easier to scale the DB for large amounts of data without having to purchase a single, expensive sever. They support both read-heavy and write-heavy systems.
The weaknesses for this type of database include:
1. **Eventual Consistency**: Because these databases are usually designed for distributed use cases, after writing to one shard in a distributed NoSQL cluster, there is a small delay before the change is propagated to other replicas. During this time, reading from a replica can yield inaccurate information. Note, this isn't necessarily a weakness of NoSQL databases but rather distributed databases in general.
## SQL vs NoSQL Scenarios
**_Amazon Targeted Ads_**: Let's say you are building a targeted product advertisement engine that is personalized for customers. What kind of database should be used?
**NoSQL.** There are a few considerations to make. One, this service needs to be built for Amazon's tens of millions of customers so horizontal scaling is important. It's also probably fine that that the data is a little out of date but eventually consistency since it's just recommendations.
---
**_Banks Loans_**: We want to build a service at our bank to allow users to apply for loans through our application. The database will store loan applications which includes information about the loan amount, user's current balance, and user's prior transaction history. What kind of database should be used?
**SQL.** In financial applications, data consistency is very important. Also, there are many relational tables in this scenario including tables for User, Loan, and Transaction.
---
**_Website Session Store_**: You want to create a session store to manage session information for each user who might visit a website. What type of database should be used?
**NoSQL.** Information about a user's session is unstructured in nature since each user's session differs. It's easier to store this type of information in a schema-less document. Moreover, low-latency access to session data is important for a good user experience.
---
**_Health Care Company Info_**: We want a database to maintain information about the different offices for health care provider company. The offices are in different states and have many doctors who work with multiple patients. What type of database should be used?
**SQL.** There are many relations in the schema that are apparent: An Office has many Doctors, a Doctor has many Patients, and a Patient has many health records.
|
Swift | UTF-8 | 392 | 2.609375 | 3 | [] | no_license | class Solution {
func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
var rest = 0
var run = 0
var res = 0
for i in gas.indices {
run += gas[i] - cost[i]
rest += gas[i] - cost[i]
if run < 0 {
res = i + 1
run = 0
}
}
return rest < 0 ? -1 : res
}
}
|
JavaScript | UTF-8 | 3,205 | 3.390625 | 3 | [] | no_license | // var apiKey = "0b52128a7a6341f58a4008807c5a9bca";
// var apiKey = "a4665615a30f4922b1cdd9ba14a85e5c";
var apiKey = "872bc99d756a4f50a85f8f88f801cdb5";
// var apiKey = "ad074955fa2a4c79a5b3f5d5a65fc461";
var ingredientButton = document.getElementById("submit-button");
//Input button on click
// var ingredient= "ingredient".value();
function getIngredient() {
event.preventDefault();
var ingredientSearch = document.getElementById("search-input").value;
var requestUrl =
"https://api.spoonacular.com/recipes/findByIngredients?apiKey=872bc99d756a4f50a85f8f88f801cdb5&ingredients=" +
ingredientSearch +
"&number=1";
// console.log("click");
// console.log(ingredientSearch);
fetch(requestUrl)
.then(function (response) {
return response.json();
})
.then(function (data) {
renderRecipe(data);
});
}
function renderRecipe(data) {
var recipeTitle = data[0].title;
var imageUrl = data[0].image;
var recipeSection = document.getElementById('recipe-section');
var usedIngredientCount = data[0].usedIngredientCount;
var missedIngredientCount = data[0].missedIngredientCount;
var imageUrl = data[0].image
document.getElementById('recipe-header').textContent = recipeTitle;
document.getElementById('recipe-image').setAttribute('src', imageUrl);
var idEl = data[0].id;
console.log(idEl);
var instructionUrl = "https://api.spoonacular.com/recipes/" + idEl + "/analyzedInstructions?apiKey=872bc99d756a4f50a85f8f88f801cdb5";
fetch(instructionUrl)
.then(function (response) {
return response.json();
})
.then(function (data) {
document.getElementById('instructions-list').innerHTML ="";
for (let i = 0; i < data[0].steps[i].step.length; i+=1) {
var insructions = data[0].steps[i].step;
console.log (insructions)
document.getElementById('instructions-list').innerHTML += "<li>" + insructions + "</li>";
}
});
var ingredientsList = document.createElement('p');
ingredientsList.setAttribute('id', 'ingredients-list');
recipeSection.appendChild(ingredientsList);
document.getElementById('ingredients-list').innerHTML ="";
document.getElementById('ingredients-needed').innerHTML ="";
for (let i = 0; i < usedIngredientCount; i++) {
var usedIngredient = data[0].usedIngredients[i].original
console.log(usedIngredient)
document.getElementById('ingredients-list').innerHTML += usedIngredient + ";" + "<br>";
}
for (let i = 0; i < missedIngredientCount; i++) {
var missedIngredient = data[0].missedIngredients[i].original
console.log(missedIngredient)
document.getElementById('ingredients-needed').innerHTML += missedIngredient + ";" + "<br>";
}
}
ingredientButton.addEventListener("click", getIngredient);
// sample api call formatting from the site. *this formatting works when using the apiKey var above.
//https://api.spoonacular.com/recipes/716429/information?apiKey=YOUR-API-KEY&includeNutrition=true.
//"https://api.spoonacular.com/recipes/findByIngredients?apiKey=0b52128a7a6341f58a4008807c5a9bca&ingredients=apples,+flour,+sugar&number=1"
//GetElementById - container to display image
// set attribute ("src", response.image)
// https://api.spoonacular.com/recipes/324694/analyzedInstructions?apiKey=a4665615a30f4922b1cdd9ba14a85e5c |
JavaScript | UTF-8 | 711 | 3.28125 | 3 | [] | no_license | /**
* getViewport() returns the workable width and height of your system
* First element in the array returns the innerWidth
* Second element in the array returns the innerHeight
* @returns {*[]}
*/
function getViewport() {
var a, b;
void 0 !== typeof window.innerWidth ? (a = window.innerWidth, b = window.innerHeight) : void 0 !== typeof document.documentElement && void 0 !== typeof document.documentElement.clientWidth && 0 !== document.documentElement.clientWidth ? (a = document.documentElement.clientWidth, b = document.documentElement.clientHeight) : (a = document.getElementsByTagName("body")[0].clientWidth, b = document.getElementsByTagName("body")[0].clientHeight);
return [a, b]
} |
Java | UTF-8 | 3,409 | 2.65625 | 3 | [] | no_license | package ru.job4j.solid.srp;
import org.junit.Test;
import ru.job4j.solid.srp.report.Report;
import ru.job4j.solid.srp.report.ReportBUH;
import ru.job4j.solid.srp.report.ReportHR;
import ru.job4j.solid.srp.report.ReportIT;
import ru.job4j.solid.srp.store.MemStore;
import java.util.Calendar;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
/*
* Тест
* основа производства изменений TDD,
* начинаем с тестов
*/
public class ReportEngineTest {
@Test
public void whenNewGeneratedThreeHR() {
MemStore store = new MemStore();
Employee worker = new Employee("Ivan", 100);
Employee worker2 = new Employee("Semen", 1000);
Employee worker3 = new Employee("Alex", 99);
store.add(worker);
store.add(worker2);
store.add(worker3);
Report engine = new ReportHR(store);
StringBuilder heading = new StringBuilder().append("Name; Salary;").append(System.lineSeparator());
var expect1 = new StringBuilder()
.append(worker.getName()).append(";")
.append(worker.getSalary()).append(";")
.append(System.lineSeparator());
var expect2 = new StringBuilder()
.append(worker2.getName()).append(";")
.append(worker2.getSalary()).append(";")
.append(System.lineSeparator());
var expect3 = new StringBuilder()
.append(worker3.getName()).append(";")
.append(worker3.getSalary()).append(";")
.append(System.lineSeparator());
assertThat(engine.generateReport(em -> true), is(String.format("%s%s%s%s", heading, expect2, expect1, expect3)));
}
@Test
public void whenGeneratedBUH() {
MemStore store = new MemStore();
Calendar now = Calendar.getInstance();
Employee worker = new Employee("Ivan", now, now, 100);
store.add(worker);
Report engine = new ReportBUH(store);
StringBuilder heading = new StringBuilder().append("Name; Hired; Fired; Salary;");
StringBuilder expect = new StringBuilder()
.append(System.lineSeparator())
.append(worker.getName()).append(";")
.append(worker.getHired()).append(";")
.append(worker.getFired()).append(";")
.append(worker.getSalary()).append(";")
.append(System.lineSeparator());
assertThat(engine.generateReport(em -> true), is((heading.append(expect).toString())));
}
@Test
public void whenGeneratedIT() {
MemStore store = new MemStore();
Calendar now = Calendar.getInstance();
Employee worker = new Employee("Ivan", now, now, 100);
store.add(worker);
Report engine = new ReportIT(store);
StringBuilder expect = new StringBuilder()
.append("Name; Hired; Fired; Salary;")
.append(System.lineSeparator())
.append(worker.getName()).append(";")
.append(worker.getHired()).append(";")
.append(worker.getFired()).append(";")
.append(worker.getSalary()).append(";")
.append(System.lineSeparator());
assertNotEquals(engine.generateReport(em -> true), expect);
}
} |
Markdown | UTF-8 | 1,211 | 3.078125 | 3 | [] | no_license | ---
layout: post
title: "Book review: Spring Boot in Action"
date: 2017-02-11 14:30:00 +0100
categories: jekyll update
---
Spring is a widely used application framework. However, configuring a Spring application can be pretty painful.
Spring Boot heavily simplifies the development by embedding a lot that is needed. It provides, for instance, a servlet container and
support for an easier configuration. These are only two essentials of Spring Boot
<br/>
*Spring Boot in Action* by Craig Walls is a good introduction. The author starts by highlighting what Spring Boot is and what it is not respectively.
After that, the reader can get started learning Spring Boot in a nicely structured way. Throughout the book, one application is developed
while various features of Spring Boot are explained and used.
<br/>
One thing I like much is that the author does propose different build tools (maven and gradle), so that the reader is not "forced" to follow
one way to succeed completing the different milestones.
<br/>
In the end, the author presents even different approaches to deploy the sample application to different cloud solutions. Again, the reader is not
"locked" to one solution.

|
C# | UTF-8 | 4,117 | 2.734375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
namespace DataBaseProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//DatagridView Proprietes
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Surname";
dataGridView1.Columns[2].Name = "Email";
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
//Selection Mode
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
}
//ADD TO DGVIEW
private void add(String name, String surname, String email)
{
dataGridView1.Rows.Add(name,surname,email);
clearTxts();
}
//CLEAR TXTS
private void clearTxts()
{
nametxt.Text = "";
surntxt.Text = "";
emailtxt.Text = "";
}
//UPDATE DGVIEW
private void update()
{
dataGridView1.SelectedRows[0].Cells[0].Value = nametxt.Text;
dataGridView1.SelectedRows[0].Cells[1].Value = surntxt.Text;
dataGridView1.SelectedRows[0].Cells[2].Value = emailtxt.Text;
clearTxts();
}
//DELETE ROWS
private void delete()
{
if (MessageBox.Show("Delete?", "DELETE", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
int index = dataGridView1.SelectedRows[0].Index;
dataGridView1.Rows.RemoveAt(index);
clearTxts();
}
}
private void OnButtonClear(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
}
private void OnButtonUpdate(object sender, EventArgs e)
{
update();
}
private void OnButtonAdd(object sender, EventArgs e)
{
add(nametxt.Text, surntxt.Text, emailtxt.Text);
}
private void OnButtonDelete(object sender, EventArgs e)
{
delete();
}
private void OnButtonImport(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(@"C:\test\table.txt");
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('/');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
dataGridView1.Rows.Add(row);
}
}
private void OnExportClick(object sender, EventArgs e)
{
Excel.Application exApp = new Excel.Application();
exApp.Workbooks.Add();
Excel.Worksheet wsh = (Excel.Worksheet)exApp.ActiveSheet;
int i, j;
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
wsh.Cells[i + 1, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
exApp.Visible = true;
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
nametxt.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
surntxt.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
emailtxt.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
}
}
}
|
PHP | UTF-8 | 2,452 | 2.828125 | 3 | [] | no_license | <?php
require_once "ConectBD.php";
class ManipulacaoDados extends \Classes\ConectBD{
public $mes;
public $dia;
public $ano;
private $caminho,$arquivo;
public function __construct(){
parent::__construct();
$this->mes = date("m");
$this->dia = date("d");
$this->ano = date("Y");
$this->caminho = null;
}
public function h1InforDate(){
$this->formatPTBR();
return "01/".$this->mes."/".$this->ano." à ".date("d/m/Y");
}
private function formatPTBR(){
setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
}
public function optionSqlData(){
try {
$sql = $this->conectBD()->prepare("SELECT DISTINCT(CONCAT(MONTHNAME(resolucao),'/',YEAR(resolucao))),CONCAT(YEAR(resolucao),'-',LPAD(MONTH(resolucao), 2, '0')) FROM tb_ocorrencia ORDER BY resolucao");
if ($sql->execute()) {
foreach ($sql->fetchAll(\PDO::FETCH_NUM) as $val) {
$dado[] = array($val[0],$val[1]);
}
if(isset($dado)){
return $dado;
}else{
throw new \Exception("ERRO: Variavel dado encontra-se sem valores!");
}
} else {
throw new \Exception("ERRO: " . implode(" ", $sql->errorInfo()));
}
} catch (\Exception $e) {
return array("ERRO: ".$e->getMessage(),"Linha: ".$e->getLine(),"Arquivos: ".$e->getFile());
}
}
public function getMes(){
return $this->mes;
}
public function setMes($mes){
$this->mes = $mes;
}
public function getDia(){
return $this->dia;
}
public function setDia($dia){
$this->dia = $dia;
}
public function getAno(){
return $this->ano;
}
public function setAno($ano){
$this->ano = $ano;
}
public function getCaminho(){
return $this->caminho;
}
public function setCaminho($caminho){
$this->caminho = $caminho;
}
public function getArquivo(){
return $this->arquivo;
}
public function setArquivo($arquivo){
$this->arquivo = $arquivo;
}
}
?> |
C | GB18030 | 487 | 3.90625 | 4 | [] | no_license | #include<stdio.h>
int main() {
char c;
//c = getchar();
int count1=0, count2=0, count3=0, count4=0;
printf("һַ\n");
while ((c = getchar()) != '\n') {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
count1++;
else if (c == ' ')
count2++;
else if (c >= '0' && c <= '9')
count3++;
else
count4++;
}
printf("Ӣĸ%d\nո%d\n%d\nַ%d\n",count1,count2,count3,count4);
} |
Java | UTF-8 | 527 | 3.515625 | 4 | [
"MIT"
] | permissive | package di.anno02;
import javax.annotation.Resource;
public class Car {
private Tire tire;
public Car() {
System.out.println("Car()...");
}
// @Resource -> 생성자에는 붙일수 없음
public Car(Tire tire) {
this.tire = tire;
System.out.println("Car(Tire)...");
}
@Resource // Resource : set에만 할수있음
public void setTire(Tire tire) {
this.tire = tire;
System.out.println("setter");
}
public void prnTireBrand() {
System.out.println("장착된 타이어 : " + tire.getBrand());
}
}
|
Python | UTF-8 | 738 | 3.359375 | 3 | [] | no_license | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
counter = 0
curr = head
while curr:
counter += 1
curr = curr.next
curr = head
count = int((counter-1)/2) if counter%2 else int(counter/2)
memo = []
for _ in range(count):
memo.append(curr.val)
curr = curr.next
curr = curr.next if counter%2 else curr
for i in range(count):
if curr.val != memo[-i-1]:
return False
curr = curr.next
return True
|
Markdown | UTF-8 | 1,639 | 3.8125 | 4 | [] | no_license | # Unit 3: Javascript Fundamentals
## Module 3.1
### Course Material
* 3.1 [Think like a computer: the logic of programming](https://openclassrooms.com/en/courses/5261196-think-like-a-computer-the-logic-of-programming)
* OC course time: 4 hrs
### Mini-Projects
* Included in OC course:
* Mini-Project 3.1a:
[Write logic for two simple loops](Module3.1/Mini-Project3.1a)
* Mini-Project 3.1b:
[Magic function machine](Module3.1/Mini-Project3.1b)
### Self-Graded Assignments
* Included in OC course:
* 4 auto-graded quizzes
## Module 3.2
### Course Material
* 3.2 [Learn Programming with Javascript](https://openclassrooms.com/en/courses/5664271-learn-programming-with-javascript)
* OC course time: 15 hrs
### Mini-Projects
* **Not** included in OC course:
* Mini Project 3.2a:
[Loops in Javascript - Laughing machine](Module3.2/Mini-Project3.2a)
* Mini-Project 3.2b:
[Javascript function practice](Module3.2/Mini-Project3.2b)
### Self-Graded Assignments
* Included in OC course:
* 4 auto-graded quizzes
* Variables & data types
* Creating variables
* Equal operator
* Constants
* Data types
* Objects, classes & dot notation
* Create an object
* Get values from an object
* Create a class
* Collections
* Create an array
* Working with arrays
* Control flow
* If/else statements
* Logical operators
* Loops
* For loops
* Functions
* Instance methods
* Do not repeat yourself (DRY principle)
## Unit 3 Project
Open the [Unit 3 Project here](Unit3-Project).
|
Java | UTF-8 | 2,040 | 2.265625 | 2 | [] | no_license | package SampleMaven.SampleMaven.Pages;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import SampleMaven.SampleMaven.SeleniumPractice.testSuite.BaseTest;
public class Home extends BaseTest {
public static final String btnReturn="//*[@id='Return']";
public static final String btnOneWay="//*[@id='oneWay_trigger']";
public static final String txtReturn="//*[@id='txtEndDate']";
public static final String ddlSuffix="//*[@id='TG_Register.G_PIName.Q_Suffix.Suffix']";
public Boolean isReturnSelected() {
return driver.findElement(By.xpath(btnReturn)).isSelected();
}
public Boolean isTxtReturnenabled() {
return driver.findElement(By.xpath(txtReturn)).isEnabled();
}
public void selectsuffix(String suffix) {
Select ss= new Select(driver.findElement(By.xpath(ddlSuffix)));
ss.selectByVisibleText(suffix);
List<WebElement>ll=ss.getOptions();
//ss.isMultiple()
for(WebElement ele:ll) {
if(ele.getText().equals("India")) {
ele.click();
break;
}
System.out.println(ele.getText());
}
for(int i=0;i<ll.size();i++) {
System.out.println(ll.get(i).getText());
}
}
/*
* Switch frame code for learning
*
*/
public void learningMethods() {
Alert aa=driver.switchTo().alert();
aa.accept();
aa.dismiss();
List<WebElement>frames= driver.findElements(By.tagName("iframe"));
for(WebElement ele:frames) {
driver.switchTo().frame(ele.getText());
}
driver.switchTo().defaultContent();
}
/*
* windows switch code
*/
public void LearningWindows() {
String parentWindow=driver.getWindowHandle();
//operation performed like click button
Set<String>windows=driver.getWindowHandles();
for(String ss:windows) {
if(!ss.equalsIgnoreCase(parentWindow)) {
driver.switchTo().window(ss);
//perform operation here for that window
driver.close();
}
}
driver.switchTo().window(parentWindow);
}
} |
Java | UTF-8 | 788 | 4.0625 | 4 | [] | no_license | /**
*
* @author David Lambropolos
*
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
* Find the sum of all the multiples of 3 or 5 below 1000.
*
*/
public class MultiplesOf3and5
{
public static void main(String[] args)
{
long start = System.currentTimeMillis(); //Start timing
int sum = 0;
for(int i = 1; i < 1000; i++)
{
if(i%3 == 0 || i%5 == 0)
{
sum+=i;
}
}
System.out.println("The sum is: " + sum);
long end = System.currentTimeMillis(); //End timing
System.out.println("Time for execution = "+(end-start)+"ms");
}
}
/**
* /////////////////
* //// OUTPUT ////
* ////////////////
*
* The sum is: 233168
* Time for execution = 0ms
*/
|
Markdown | UTF-8 | 574 | 2.921875 | 3 | [] | no_license | # shuffle-quest
## About
Sometimes when I shuffle cards, it is bad. I only take some random small number of cards off of the top and the bottom, then put those cards collectively either on the top or bottom of the deck. Basically I am just cutting the deck over and over, in disguise as something else.
I have taught The Computer to also shuffle this way, in solidarity with me, a poor shuffler.
## Enhancements
Someday... maybe there will be *more* ways to shuffle. Pile shuffling. True random shuffling. No shuffling. The possibilities are unlimited.
## Wow
Yes. Wow.
|
C# | UTF-8 | 1,895 | 2.609375 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(Ball))]
public class BallDragLaunch : MonoBehaviour {
private Ball ball;
private Vector3 dragStart, dragEnd;
private float startTime, endTime;
void Start () {
ball = GetComponent<Ball>();
}
/**
* Capture the time and position of mouse click and hold.
* Used to calculate the velocity ball is launched at.
*/
public void CaptureDragStart()
{
if (!ball.inPlay)
{
dragStart = Input.mousePosition;
startTime = Time.time;
}
}
/**
* Capture the time and position of mouse release.
* Used to calculate the velocity ball is launched at.
* Also launch the ball.
*/
public void CaptureDragEndAndLaunch()
{
if (!ball.inPlay)
{
// Launch ball
dragEnd = Input.mousePosition;
endTime = Time.time;
float dragDuration = endTime - startTime;
float distanceX = dragEnd.x - dragStart.x;
float distanceY = dragEnd.y - dragStart.y;
float launchSpeedX = distanceX / dragDuration;
float launchSpeedZ = distanceY / dragDuration; // translation from 2d screen (x, y) to 3d world (z)
Vector3 launchVelocity = new Vector3(launchSpeedX, 0, launchSpeedZ);
ball.Launch(launchVelocity);
}
}
/**
* Nudge the ball to either side before launching.
*/
public void MoveStart(float xNudge)
{
if (ball.inPlay == false)
{
ball.transform.Translate(new Vector3(xNudge, 0, 0));
// Clamp to lane
Vector3 pos = ball.transform.position;
pos.x = Mathf.Clamp(transform.position.x, -50, 50);
ball.transform.position = pos;
}
}
}
|
JavaScript | UTF-8 | 254 | 2.671875 | 3 | [] | no_license | class pizza(s,m,v){
this.size = s;
this.meatToppings = m;
this.veggieToppings = v;
//type construct below
sizeCost (){
if(this.size = "Small")
return sizecost = "7.99"
//type instance functions below
//type class functions below
}
|
Java | UTF-8 | 10,544 | 1.71875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.analysis.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.modules.php.analysis.commands.CodeSniffer;
import org.netbeans.modules.php.analysis.commands.CodingStandardsFixer;
import org.netbeans.modules.php.analysis.commands.MessDetector;
import org.netbeans.modules.php.analysis.commands.PHPStan;
import org.netbeans.modules.php.api.util.FileUtils;
import org.netbeans.modules.php.api.util.UiUtils;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.util.NbBundle;
public final class AnalysisUiUtils {
private static final String CODE_SNIFFER_LAST_FOLDER_SUFFIX = ".codeSniffer"; // NOI18N
private static final String CODING_STANDARDS_FIXER_LAST_FOLDER_SUFFIX = ".codingStandarsFixer"; // NOI18N
private static final String MESS_DETECTOR_LAST_FOLDER_SUFFIX = ".messDetector"; // NOI18N
private static final String MESS_DETECTOR_RULE_SET_FILE_LAST_FOLDER_SUFFIX = ".messDetector.ruleSetFile"; // NOI18N
private static final String PHPSTAN_LAST_FOLDER_SUFFIX = ".phpstan"; // NOI18N
private static final String PHPSTAN_CONFIGURATION_LAST_FOLDER_SUFFIX = ".phpstan.config"; // NOI18N
private AnalysisUiUtils() {
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.code.sniffer.title=Select Code Sniffer")
public static File browseCodeSniffer() {
return browse(CODE_SNIFFER_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_code_sniffer_title());
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.coding.standards.fixer.title=Select Coding Standards Fixer")
public static File browseCodingStandardsFixer() {
return browse(CODING_STANDARDS_FIXER_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_coding_standards_fixer_title());
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.mess.detector.title=Select Mess Detector")
public static File browseMessDetector() {
return browse(MESS_DETECTOR_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_mess_detector_title());
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.mess.detector.rule.set.title=Select Mess Detector Rule Set")
public static File browseMessDetectorRuleSet() {
return browse(MESS_DETECTOR_RULE_SET_FILE_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_mess_detector_rule_set_title());
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.phpstan.title=Select PHPStan")
public static File browsePHPStan() {
return browse(PHPSTAN_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_phpstan_title());
}
@CheckForNull
@NbBundle.Messages("AnalysisUiUtils.browse.phpstan.configuration.title=Select PHPStan Configuration File")
public static File browsePHPStanConfiguration() {
return browse(PHPSTAN_CONFIGURATION_LAST_FOLDER_SUFFIX, Bundle.AnalysisUiUtils_browse_phpstan_configuration_title());
}
@CheckForNull
private static File browse(String lastFolderSuffix, String title) {
File file = new FileChooserBuilder(AnalysisUiUtils.class.getName() + lastFolderSuffix)
.setFilesOnly(true)
.setTitle(title)
.showOpenDialog();
return file;
}
@CheckForNull
@NbBundle.Messages({
"AnalysisUiUtils.search.code.sniffer.title=Code Sniffer scripts",
"AnalysisUiUtils.search.code.sniffer.scripts=Co&de Sniffer scripts:",
"AnalysisUiUtils.search.code.sniffer.pleaseWaitPart=Code Sniffer scripts",
"AnalysisUiUtils.search.code.sniffer.notFound=No Code Sniffer scripts found."
})
public static String searchCodeSniffer() {
SearchParameter param = new SearchParameter()
.setFilenames(Arrays.asList(CodeSniffer.NAME, CodeSniffer.LONG_NAME))
.setWindowTitle(Bundle.AnalysisUiUtils_search_code_sniffer_title())
.setListTitle(Bundle.AnalysisUiUtils_search_code_sniffer_scripts())
.setPleaseWaitPart(Bundle.AnalysisUiUtils_search_code_sniffer_pleaseWaitPart())
.setNoItemsFound(Bundle.AnalysisUiUtils_search_code_sniffer_notFound());
return search(param);
}
@CheckForNull
@NbBundle.Messages({
"AnalysisUiUtils.search.coding.standards.fixer.title=Coding Standards Fixer scripts",
"AnalysisUiUtils.search.coding.standards.fixer.scripts=C&oding Standards Fixer scripts:",
"AnalysisUiUtils.search.coding.standards.fixer.pleaseWaitPart=Coding Standards Fixer scripts",
"AnalysisUiUtils.search.coding.standards.fixer.notFound=No Coding Standards Fixer scripts found."
})
public static String searchCodingStandardsFixer() {
SearchParameter param = new SearchParameter()
.setFilenames(Arrays.asList(CodingStandardsFixer.NAME, CodingStandardsFixer.LONG_NAME))
.setWindowTitle(Bundle.AnalysisUiUtils_search_coding_standards_fixer_title())
.setListTitle(Bundle.AnalysisUiUtils_search_coding_standards_fixer_scripts())
.setPleaseWaitPart(Bundle.AnalysisUiUtils_search_coding_standards_fixer_pleaseWaitPart())
.setNoItemsFound(Bundle.AnalysisUiUtils_search_coding_standards_fixer_notFound());
return search(param);
}
@CheckForNull
@NbBundle.Messages({
"AnalysisUiUtils.search.mess.detector.title=Mess Detector scripts",
"AnalysisUiUtils.search.mess.detector.fixer.scripts=M&ess Detector scripts:",
"AnalysisUiUtils.search.mess.detector.fixer.pleaseWaitPart=Mess Detector scripts",
"AnalysisUiUtils.search.mess.detector.fixer.notFound=No Mess Detector scripts found."
})
public static String searchMessDetector() {
SearchParameter param = new SearchParameter()
.setFilenames(Arrays.asList(MessDetector.NAME, MessDetector.LONG_NAME))
.setWindowTitle(Bundle.AnalysisUiUtils_search_mess_detector_title())
.setListTitle(Bundle.AnalysisUiUtils_search_mess_detector_fixer_scripts())
.setPleaseWaitPart(Bundle.AnalysisUiUtils_search_mess_detector_fixer_pleaseWaitPart())
.setNoItemsFound(Bundle.AnalysisUiUtils_search_mess_detector_fixer_notFound());
return search(param);
}
@CheckForNull
@NbBundle.Messages({
"AnalysisUiUtils.search.phpstan.title=PHPStan scripts",
"AnalysisUiUtils.search.phpstan.scripts=P&HPStan scripts:",
"AnalysisUiUtils.search.phpstan.pleaseWaitPart=PHPStan scripts",
"AnalysisUiUtils.search.phpstan.notFound=No PHPStan scripts found."
})
public static String searchPHPStan() {
SearchParameter param = new SearchParameter()
.setFilenames(Arrays.asList(PHPStan.NAME, PHPStan.LONG_NAME))
.setWindowTitle(Bundle.AnalysisUiUtils_search_phpstan_title())
.setListTitle(Bundle.AnalysisUiUtils_search_phpstan_scripts())
.setPleaseWaitPart(Bundle.AnalysisUiUtils_search_phpstan_pleaseWaitPart())
.setNoItemsFound(Bundle.AnalysisUiUtils_search_phpstan_notFound());
return search(param);
}
@CheckForNull
private static String search(SearchParameter param) {
return UiUtils.SearchWindow.search(new UiUtils.SearchWindow.SearchWindowSupport() {
@Override
public List<String> detect() {
return FileUtils.findFileOnUsersPath(param.getFilenames().toArray(new String[param.getFilenames().size()]));
}
@Override
public String getWindowTitle() {
return param.getWindowTitle();
}
@Override
public String getListTitle() {
return param.getListTitle();
}
@Override
public String getPleaseWaitPart() {
return param.getPleaseWaitPart();
}
@Override
public String getNoItemsFound() {
return param.getNoItemsFound();
}
});
}
//~ Inner class
private static final class SearchParameter {
private final List<String> filenames = new ArrayList<>();
private String windowTitle;
private String listTitle;
private String pleaseWaitPart;
private String noItemsFound;
public List<String> getFilenames() {
return Collections.unmodifiableList(filenames);
}
public String getWindowTitle() {
return windowTitle;
}
public String getListTitle() {
return listTitle;
}
public String getPleaseWaitPart() {
return pleaseWaitPart;
}
public String getNoItemsFound() {
return noItemsFound;
}
SearchParameter setFilenames(List<String> filenames) {
this.filenames.clear();
this.filenames.addAll(filenames);
return this;
}
SearchParameter setWindowTitle(String windowTitle) {
this.windowTitle = windowTitle;
return this;
}
SearchParameter setListTitle(String listTitle) {
this.listTitle = listTitle;
return this;
}
SearchParameter setPleaseWaitPart(String pleaseWaitPart) {
this.pleaseWaitPart = pleaseWaitPart;
return this;
}
SearchParameter setNoItemsFound(String noItemsFound) {
this.noItemsFound = noItemsFound;
return this;
}
}
}
|
Python | UTF-8 | 347 | 3.5625 | 4 | [] | no_license | #Naive Approach
A="abcb"
def first_recur(A):
for i in xrange(len(A)):
if A[i] in [k for k in A[i+1:]]:
#print i
return A[i]
return None
#print (first_recur(A))
#print A[1:]
#Better Approach
def fRecur(A):
d={}
for i in A:
if (i in d):
return i
else:
d[i]=i
return None
print (fRecur(A)) |
C++ | UTF-8 | 10,278 | 3.25 | 3 | [] | no_license | //
// main.cpp
// HoughTransform
//
// Created by Angelo Gonzalez on 12/17/14.
// Copyright (c) 2014 Angelo Gonzalez. All rights reserved.
//
#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
using namespace cv;
//polar line equation: d = ccos(theta) - rsin(theta)
float euclidean(Mat &histogram1, Mat &histogram2) {
float distance = 0;
for (int x = 0; x < histogram1.rows; x++) {
distance += (histogram1.at<float>(x) - histogram2.at<float>(x)) * (histogram1.at<float>(x) - histogram2.at<float>(x));
}
return sqrt(distance);
}
float manhattan(Mat &histogram1, Mat &histogram2) {
float distance = 0;
for (int x = 0; x < histogram1.rows; x++) {
distance += abs(histogram1.at<float>(x) - histogram2.at<float>(x));
}
return distance;
}
//how I'm storing the point list
struct Coordinate {
int x;
int y;
};
//to sort vectors by size() with sort()
struct CapacityGreater : public binary_function<vector<Coordinate>, vector<Coordinate>, bool>
{
bool operator()(const vector<Coordinate> &a, const vector<Coordinate> &b) const {
return a.size() > b.size();
}
};
//takes in the original unaltered color image, number of lines to draw, percentage of magnitude to threshold by (0 to 1), number of steps for d,
//and number of steps for theta
Mat houghTransform(Mat &input, int numLines, double thresholdPercent, int binStepD, int binStepTheta) {
//histogram to count the horizontal, vertical, and diagonal
Mat histogram = Mat(3, 1, CV_32F, 0.0);
Mat greyImage, image;
cvtColor(input, image, CV_BGR2GRAY);
//Noise Reduction
GaussianBlur(image, greyImage, Size(3, 3), 1.5);
//compute the max possible d for each image and then calculate the number of bins for the accumulator array
int maxSizeD = sqrt(pow(greyImage.rows, 2) + pow(greyImage.cols, 2));
int binsD = maxSizeD / binStepD;
int binsTheta = 360 / binStepTheta;
//3D vector to store a vector of Coordinate structs
vector<vector<vector<Coordinate>>> accArray;
accArray.resize(binsD);
for (int i = 0; i < accArray.size(); i++) {
accArray[i].resize(binsTheta);
}
//calculate gradients
Mat gradX = Mat(greyImage.rows, greyImage.cols, CV_32F, 0.0);
Mat gradY = Mat(greyImage.rows, greyImage.cols, CV_32F, 0.0);
Sobel(greyImage, gradX, CV_32F, 1, 0, 3);
Sobel(greyImage, gradY, CV_32F, 0, 1, 3);
//calculate mags
Mat sum = Mat(greyImage.rows, greyImage.cols, CV_64F);
Mat prodX = Mat(greyImage.rows, greyImage.cols, CV_64F);
Mat prodY = Mat(greyImage.rows, greyImage.cols, CV_64F);
multiply(gradX, gradX, prodX);
multiply(gradY, gradY, prodY);
sum = prodX + prodY;
sqrt(sum, sum);
Mat mag = sum.clone();
//get the maximum magnitude and calculate the threshold based on the percentage given
double maxMag;
minMaxIdx(mag, 0, &maxMag);
int threshold = maxMag * thresholdPercent;
//calculate slopes
Mat slopes = Mat(greyImage.rows, greyImage.cols, CV_32F, 0.0);
divide(gradY, gradX, slopes);
//calculate angles
Mat theta = Mat(slopes.rows, slopes.cols, CV_32F, 0.0);
for (int x = 0; x < slopes.rows; x++) {
for (int y = 0; y < slopes.cols; y++) {
//for easier range checking
float currentDirection = atan(slopes.at<float>(x, y)) * (180 / 3.142);
//get full range of angles 0 to 360 this is what will be used for theta
int currentDir360 = atan2(gradY.at<float>(x, y), gradX.at<float>(x, y)) * (180 / M_PI);
if(currentDirection < 0) currentDirection += 180;
if(currentDir360 < 0) currentDir360 += 360;
theta.at<float>(x, y) = (currentDir360);
//increase the count of horizontal, vertical and diagonal lines in their respective bins if it passes the threshold
if (mag.at<float>(x, y) > threshold) {
if ((currentDirection > 22.5 && currentDirection <= 67.5) || (currentDirection > 112.5 && currentDirection <= 157.5)) {
histogram.at<float>(2) += 1;
}
else if (currentDirection > 67.5 && currentDirection <= 112.5) {
histogram.at<float>(1) += 1;
}
else {
histogram.at<float>(0) += 1;
}
}
}
}
//calculate d
//polar line equation: d = c * cos(theta) - r * sin(theta)
Mat d = Mat(theta.rows, theta.cols, CV_32F, 0.0);
for (int x = 0; x < theta.rows; x++) {
for (int y = 0; y < theta.cols; y++) {
//cosine and sine functions take in radians so convert angle to radians to compute the proper d
float computedD = abs(y * cos(theta.at<float>(x, y) * (M_PI / 180)) - x * sin(theta.at<float>(x, y) * (M_PI / 180)));
d.at<float>(x, y) = computedD;
}
}
//quantize the data and accumulate the array
for (int x = 0; x < theta.rows; x++) {
for (int y = 0; y < theta.cols; y++) {
//threshold for the magnitude
if (mag.at<float>(x, y) < threshold) {
continue;
}
//if theta is 360 make it 0
int angle = theta.at<float>(x, y);
if (angle == 360) {
angle = 0;
}
//cout << "row: " << x << "col: " << y << "d: " << d.at<float>(x, y) << "theta: " << angle << endl;
int D = d.at<float>(x, y);
//accumulate and quantize
Coordinate pt;
pt.x = y;
pt.y = x;
accArray.at(D / binStepD).at(angle / binStepTheta).push_back(pt);
}
}
//4 main lines we care about
Coordinate line1Start, line1End, line2Start, line2End, line3Start, line3End, line4Start, line4End;
//count the number of lines and push any Coordinate vectors that exist into the 2D vector list to be sorted
vector<vector<Coordinate>> list;
int totalNumLines = 0;
for (int x = 0; x < accArray.size(); x++) {
for (int y = 0; y < accArray[0].size(); y++) {
if (accArray.at(x).at(y).size() != 0) {
totalNumLines++;
list.push_back(accArray.at(x).at(y));
}
}
}
//sort the 2D vector of Coodinates by their weights (or size())
sort(list.begin(), list.end(), CapacityGreater());
line1Start = list[0].front();
line1End = list[0].back();
line2Start = list[1].front();
line2End = list[1].back();
line3Start = list[2].front();
line3End = list[2].back();
line4Start = list[3].front();
line4End = list[3].back();
Point l1p1(line1Start.x, line1Start.y);
Point l1p2(line1End.x, line1End.y);
Point l2p1(line2Start.x, line2Start.y);
Point l2p2(line2End.x, line2End.y);
Point l3p1(line3Start.x, line3Start.y);
Point l3p2(line3End.x, line3End.y);
Point l4p1(line4Start.x, line4Start.y);
Point l4p2(line4End.x, line4End.y);
line(input, l1p1, l1p2, Scalar(0,0,255), 2, CV_AA);
line(input, l2p1, l2p2, Scalar(0,255,0), 2, CV_AA);
line(input, l3p1, l3p2, Scalar(255,0,0), 2, CV_AA);
line(input, l4p1, l4p2, Scalar(127,127,127), 2, CV_AA);
//if there are more lines that were specified to be drawn in the parameters, then draw more as white lines
if (numLines > 4) {
for (int i = 4; i < numLines; i++) {
Point p1(list.at(i).front().x, list.at(i).front().y);
Point p2(list.at(i).back().x, list.at(i).back().y);
line(input, p1, p2, Scalar(255, 255, 255), 2, CV_AA);
}
}
imshow("Hough Transform", input);
waitKey();
//divide each histogram bin by the total number of lines found
for (int i = 0; i < histogram.rows; i++) {
histogram.at<float>(i) = histogram.at<float>(i) / totalNumLines;
}
return histogram;
}
int main(int argc, const char * argv[]) {
string inFileName = argv[1];
ifstream inFile(inFileName.c_str(), ios_base::in); // creates an input file stream
string queryFileName;
inFile >> queryFileName; // reads the first line of the file into queryFileName
// make histogram(s) from the image with the name: queryFileName
Mat queryInput = imread(queryFileName);
Mat houghHistogram;
houghHistogram = houghTransform(queryInput, 15, .25, 4, 4);
//maps for storing distances
map<float, string> L1Hough;
map<float, string> L2Hough;
while (!inFile.eof())
{
string anotherFileName;
inFile >> anotherFileName;
// make histogram(s) from the image with the name: anotherFileName
// use the histogram(s) made from the queryFileName and the ones from
// anotherFileName and compare them with L1, L2, etc.
Mat anotherInput = imread(anotherFileName);
Mat histogram;
histogram = houghTransform(anotherInput, 15, .25, 4, 4);
L1Hough[manhattan(houghHistogram, histogram)] = anotherFileName;
L2Hough[euclidean(houghHistogram, histogram)] = anotherFileName;
}
printf("%s \n", "L1 Hough Transform");
printf("%s %s \n", "Query Image: ", queryFileName.c_str());
//Intersection for color histograms
for(map<float,string>::iterator it=L1Hough.begin(); it!=L1Hough.end(); ++it) {
printf("%10f %s %50s \n", (*it).first , ": ", (*it).second.c_str());
}
cout << endl;
printf("%s \n", "L2 Hough Transform");
printf("%s %s \n", "Query Image: ", queryFileName.c_str());
//Intersection for color histograms
for(map<float,string>::iterator it=L2Hough.begin(); it!=L2Hough.end(); ++it) {
printf("%10f %s %50s \n", (*it).first , ": ", (*it).second.c_str());
}
cout << endl;
return 0;
}
|
C | UTF-8 | 211 | 3 | 3 | [] | no_license |
#include <stdio.h>
#include<string.h>
void main()
{
char a[10];
int m;
scanf("%s",a);
m=strlen(a);
if(m%2==0)
{
a[m/2]='*';
a[(m/2)-1]='*';
}
else
{
a[m/2]='*';
}
printf("%s",a);
getch();
}
|
Java | UTF-8 | 4,440 | 2.90625 | 3 | [] | no_license | package driver;
import device.Device;
import scanTools.NetScan;
import scanTools.PortScan;
import utils.Gateway;
import utils.LocalHost;
import javax.swing.*;
import java.util.ArrayList;
public class GUI extends JFrame {
private JPanel rootPanel;
private JPanel topPanel;
private JPanel leftPanel;
private JRadioButton fullPortScanRadioButton;
private JRadioButton quickPortScanRadioButton;
private JList foundDevicesList;
private JButton scanButton;
private JProgressBar progressBar1;
private JTabbedPane tabbedPane1;
private JLabel hostLabel;
private JLabel GatewayLabel;
private JLabel hostAddressText;
private JLabel GatewayAddressText;
private JLabel MACLabel;
private JLabel DeviceIPLabel;
private JButton startTCPPortScanButton;
private JList portList;
static DefaultListModel portModel;
public GUI() {
DefaultListModel<Device> model = new DefaultListModel<>();
ArrayList<Device> foundDevices = new ArrayList<>();
foundDevicesList.setModel(model);
portModel = new DefaultListModel();
NetScan netScan = new NetScan();
PortScan portScan = new PortScan();
//get local and set localHost to get Address
LocalHost localHost = new LocalHost();
localHost.setLocalHost();
//get gateway and set gateway to get Address
Gateway gateway = new Gateway();
gateway.setGateway();
//scan button
scanButton.addActionListener(e -> {
netScan.scan();
//fill the foundList
for(int i= 0;i<netScan.getFoundDevices().size();i++) {
foundDevices.add(netScan.getFoundDevice(i));
model.addElement(foundDevices.get(i));
}
});
//listModel
foundDevicesList.getSelectionModel().addListSelectionListener(e -> {
Device d = (Device) foundDevicesList.getSelectedValue();
DeviceIPLabel.setText(d.getIPString());
MACLabel.setText(d.getMacAddress());
setJlist();
});
//TCP Scan will present error box if no device is selected
//otherwise check which RadioButton is selected and use that value in the ScanType
startTCPPortScanButton.addActionListener(e ->{
Device d = (Device) foundDevicesList.getSelectedValue();
if (d == null) {
JOptionPane.showMessageDialog(rootPanel, "Scan the network and select a device to port scan", "Oops!", JOptionPane.WARNING_MESSAGE);
} else {
//radio buttons
String radioSelection = null;
boolean quickSelect = quickPortScanRadioButton.isSelected();
boolean fullSelect = fullPortScanRadioButton.isSelected();
if(quickSelect){
radioSelection = "quick";
}else if(fullSelect){
radioSelection = "full";
}else{
JOptionPane.showMessageDialog(rootPanel, "Select a device to port scan", "Oops!", JOptionPane.WARNING_MESSAGE);
return;
}
System.out.println("selected RadioButton : "+radioSelection);
portScan.scanTCP(d, radioSelection);
System.out.println(d.getPorts());
}
});
//rootPanel
setTitle("Network Scanner");
add(rootPanel);
hostAddressText.setText(localHost.getLocalHost());
GatewayAddressText.setText(gateway.getGateway());
}
/**
* Used to set the model of the JList to display device open ports.
*
* when a device is selected, clears the portList model and re-adds the data
*
*/
private void setJlist (){
foundDevicesList.getSelectionModel().addListSelectionListener(e -> {
Device d = (Device) foundDevicesList.getSelectedValue();
Object[] objectArray = null;
if(d.getPorts()!= null) {
objectArray = d.getPorts().entrySet().toArray();
portModel.clear();
for (int i = 0; i < d.getPorts().size(); i++) {
portModel.addElement(objectArray[i]);
portList.setModel(portModel);
System.out.println("portModel:" + portModel);
}
}
});
}
}
|
Java | UTF-8 | 1,672 | 2.140625 | 2 | [] | no_license | package com.rsw.servlet.mycourse;
import com.google.gson.Gson;
import com.rsw.dao.Imp.userTeacherImp;
import com.rsw.entity.BaseResponse;
import com.rsw.entity.UserCourse;
import com.rsw.entity.UserTeacher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet(urlPatterns = "/displayMyCourse")
public class DisplayMyCourse extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String id = (String)request.getSession().getAttribute("userid");
List<UserCourse> courses = new ArrayList<UserCourse>();
courses = new userTeacherImp().queryCourseById(id);
BaseResponse<List<UserCourse>> baseResponse = new BaseResponse<List<UserCourse>>();
baseResponse.setCode(0);
baseResponse.setMsg("请求成功");
baseResponse.setData(courses);
baseResponse.setCount(20);
Gson gson = new Gson();
String json =gson.toJson(baseResponse);
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
Python | UTF-8 | 2,495 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | '''
A logistic regression learning algorithm example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
import numpy as np
import tensorflow as tf
# assert tf.__version__ == "1.8.0"
tf.set_random_seed(20180130)
np.random.seed(20180130)
# Import MINST data
import sys
sys.path.append("/data")
import scripts.study_case.ID_3.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
from datetime import datetime
import sys
sys.path.append("/data")
start_time = datetime.now()
# Parameters
learning_rate = 0.005
training_epochs = 25
batch_size = 100
display_step = 1
# tf Graph Input
x = tf.placeholder("float", [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder("float", [None, 10]) # 0-9 digits recognition => 10 classes
# Create model
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model
activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
# Minimize error using cross entropy
#MUTATION#
cost = -tf.reduce_sum(y*tf.log(activation)) # Cross entropy
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) # Gradient Descent
obj_var = tf.reduce_min(tf.abs(activation))
# Initializing the variables
init = tf.initialize_all_variables()
'''inserted code'''
from scripts.utils.tf_utils import TensorFlowScheduler
scheduler = TensorFlowScheduler(name="ghips9")
'''inserted code'''
# Launch the graph
with tf.Session() as sess:
tf.train.write_graph(sess.graph_def, '/data/scripts/study_case/pbtxt_files', 'GHIPS9.pbtxt')
sess.run(init)
# Training cycle
while True:
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
# Compute average loss
cross_entropy_val = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})
'''inserted code'''
scheduler.loss_checker(cross_entropy_val)
'''inserted code'''
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
'''inserted code'''
scheduler.check_time()
'''inserted code'''
# avg_cost += cross_entropy_val/total_batch
|
Shell | UTF-8 | 1,835 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -eo pipefail
# build jsdocs (Python is installed on the Node 10 docker image).
if [[ -z "$CREDENTIALS" ]]; then
# if CREDENTIALS are explicitly set, assume we're testing locally
# and don't set NPM_CONFIG_PREFIX.
export NPM_CONFIG_PREFIX=${HOME}/.npm-global
export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin"
cd $(dirname $0)/../..
fi
npm install
npm run docs
# create docs.metadata, based on package.json and .repo-metadata.json.
npm i json@9.0.6 -g
python3 -m docuploader create-metadata \
--name=$(cat .repo-metadata.json | json name) \
--version=$(cat package.json | json version) \
--language=$(cat .repo-metadata.json | json language) \
--distribution-name=$(cat .repo-metadata.json | json distribution_name) \
--product-page=$(cat .repo-metadata.json | json product_documentation) \
--github-repository=$(cat .repo-metadata.json | json repo) \
--issue-tracker=$(cat .repo-metadata.json | json issue_tracker)
cp docs.metadata ./docs/docs.metadata
# deploy the docs.
if [[ -z "$CREDENTIALS" ]]; then
CREDENTIALS=${KOKORO_KEYSTORE_DIR}/73713_docuploader_service_account
fi
if [[ -z "$BUCKET" ]]; then
BUCKET=docs-staging
fi
python3 -m docuploader upload ./docs --credentials $CREDENTIALS --staging-bucket $BUCKET
|
Python | UTF-8 | 1,580 | 2.578125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | import vampytest
from ....oauth2 import Oauth2Scope
from ....permission import Permission
from ..application_install_parameters import ApplicationInstallParameters
from .test__ApplicationInstallParameters__constructor import _assert_is_every_attribute_set
def test__ApplicationInstallParameters__from_data():
"""
Tests whether ``ApplicationInstallParameters.from_data`` works as intended.
"""
permissions = Permission(123)
scopes = [Oauth2Scope.bot, Oauth2Scope.email]
data = {
'permissions': format(permissions, 'd'),
'scopes': [scope.value for scope in scopes],
}
application_install_parameters = ApplicationInstallParameters.from_data(data)
_assert_is_every_attribute_set(application_install_parameters)
vampytest.assert_eq(application_install_parameters.permissions, permissions)
vampytest.assert_eq(application_install_parameters.scopes, tuple(scopes))
def test__ApplicationInstallParameters__to_data():
"""
Tests whether ``ApplicationInstallParameters.to_data`` works as intended.
Case: Include defaults.
"""
permissions = Permission(123)
scopes = [Oauth2Scope.bot, Oauth2Scope.email]
application_install_parameters = ApplicationInstallParameters(
permissions = permissions,
scopes = scopes,
)
expected_output = {
'permissions': format(permissions, 'd'),
'scopes': [scope.value for scope in scopes],
}
vampytest.assert_eq(application_install_parameters.to_data(defaults = True), expected_output)
|
Java | UTF-8 | 475 | 2.640625 | 3 | [] | no_license | package com.dradest.designpatterns.factorypattern.carfactory;
import com.dradest.designpatterns.factorypattern.carparts.chassis.Chassis;
import com.dradest.designpatterns.factorypattern.carparts.electricity.Electricity;
import com.dradest.designpatterns.factorypattern.carparts.tyres.Tyres;
public interface CarFactory {
public Chassis createChassis(String carType);
public Tyres createTyres(String carType);
public Electricity doElectricJob(String carType);
}
|
Java | UTF-8 | 273 | 3.484375 | 3 | [] | no_license | public class FiniteSum {
public static void main(String[] args) {
// To find the finite sum of the numbers
int n = 100,sum=0;
for (int i=0;i<n;i++)
{
sum+=i;
}
System.out.print("The sum of the numbers from 0 to 99 is : ");
System.out.println(sum);
}
}
|
Swift | UTF-8 | 1,014 | 3.84375 | 4 | [] | no_license | //: [Previous](@previous)
import Foundation
// 创建树
// 根节点
let tree = TreeNode(15)
// 第二层
let one = TreeNode(1)
tree.add(one)
let seventeen = TreeNode(17)
tree.add(seventeen)
let twenty = TreeNode(20)
tree.add(twenty)
// 第三层
let one2 = TreeNode(1)
let five = TreeNode(5)
let zero = TreeNode(0)
one.add(one2)
one.add(five)
one.add(zero)
let two = TreeNode(2)
seventeen.add(two)
let five2 = TreeNode(5)
let seven = TreeNode(7)
twenty.add(five2)
twenty.add(seven)
func printEachLevel<T>(for tree: TreeNode<T>) {
var queue = Queue<TreeNode<T>>()
var nodesLeftInCurrentLevel = 0
queue.enqueue(tree)
while !queue.isEmpty {
nodesLeftInCurrentLevel = queue.count
// 循环打印一层
while nodesLeftInCurrentLevel > 0 {
guard let node = queue.dequeue() else { break }
print("\(node.value)", terminator: " ")
node.children.forEach { queue.enqueue($0) }
nodesLeftInCurrentLevel -= 1
}
// 换行
print()
}
}
printEachLevel(for: tree)
|
Java | UTF-8 | 1,141 | 4.21875 | 4 | [] | no_license | package anonymous_classes_enums.task1;
//Создайте перечислительный тип (enum) Animals, содержащий конструктор,
// который должен принимать целочисленное значение (возраст животного),
// и содержать перегруженный метод toString(), который должен возвращать
// название экземпляра и возраст животного.
enum Animals{
CAT(2), DOG(10), MONKEY(9), ZEBRA(5);
int year;
Animals(int year){
this.year = year;
}
@Override
public String toString() {
return "Имя животного: " + this.name() + " возраст: " + year;
}
}
class Main{
public static void main(String[] args) {
Animals a1 =Animals.CAT;
Animals a2 =Animals.DOG;
Animals a3 =Animals.MONKEY;
Animals a4 =Animals.ZEBRA;
System.out.println(a1.toString());
System.out.println(a2.toString());
System.out.println(a3.toString());
System.out.println(a4.toString());
}
}
|
Markdown | UTF-8 | 8,366 | 3.21875 | 3 | [] | no_license | ---
layout: post
title: 读《Emotional Intelligence:Why it can matter more than IQ》
category: 读后感
---
这是2019年读的第020本书,Daniel Goleman 著,累计用时16小时
>All emotions are, in essence, impulses to act, the instant plans for handling life that evolution has instilled in us. The very root of the word emotion is motere, the Latin verb "to move", plus the prefix "e-" to connote "move away", suggesting that a tendency to act is implicit in every emotion. That emotional lead to actions is most obvious in watching animals or children; it is only in "civilized" adults we so often find the great anomaly in the animal kingdom, emotions — root impulses to act — divorced from obvious reaction.
>"Anatomically the emotional system can act independently of the neocortex," LeDoux told me. "Some emotional reactions and emotional memories can be formed without any conscience, cognitive participation at all." The amygdala can house memories and response repertoires that we enact without quite realizing why we do so because the shortcut from thalamus to amygdala completely bypasses the neocortex. This bypass seems to allow the amygdala to be a repository for emotional impressions and memories that we have never known about in full awareness. LeDoux proposes that it is the amygdala's subterranean role in memory that explains, for example, a startling experiment in which people acquired a preference of oddly shaped geometric figures that had been flashed at them so quickly that they had no conscious awareness of having seen them at all!
>As Henry Roth observed in his novel Call It Sleep about this power of language. "If you could put words to what you felt, it was yours." The corollary, of course, is the alexithymic's dilemma: having no words for feelings means not making the feelings your own.
>Being able to enter flow is emotional intelligence at its best; flow represents perhaps the ultimate in harnessing the emotions in the service of performance and learning. In flow the emotions are not just contained and channeled, but positive, energized, and aligned with the task at hand. To be caught in the ennui of depression or agitation of anxiety is to be barred from flow. Yet flow (or a milder microflow) is an experience almost everyone enters from time to time, particularly when performing at their peak or stretching beyond their former limits. It is perhaps best captured by ecstatic lovemaking, the merging of two into a fluidly harmonious one.
>Meanwhile, boys and girls are taught very different lessons about handling emotions. Parents, in general, discuss emotions — with the exception of anger — more with their daughters than their sons. Girls are exposed to more information about emotions than are boys: when parents make up stories to tell their preschool children, they use more emotion words when talking to daughters than to sons; when mothers play with their infants, they display a wider range of emotions to daughters than to sons; when mother talk to daughters about feelings, they discuss in more detail the emotional state itself than they do with their sons — though with the sons they go into more detail about the causes and consequences of emotions like anger (probably as a cautionary tale).
>Some of the reasons are patently obvious — imagine the consequences for a working group when someone is unable to keep from exploding in anger or has no sensitivity about what the people around him are feeling. All the deleterious effects of agitation on thinking reviewed in Chapter 6 operate in the workplace too: When emotionally upset, people cannot remember, attend, learn or make decisions clearly. As one management consultant put it, "Stress makes people stupid."
>Whenever people come together to collaborate, whether it be in an executive planning meeting or as a team working toward a shared product, there is a very real sense in which they have a group IQ, the sum total of the talents and skills of all those involved. And how well they accomplish their task will be determined by how high the IQ is. The single most important element in group intelligence, it turns out, is not the average IQ in the academic sense, but rather in terms of emotional intelligence. The key to a high group IQ is social harmony. It is this ability to harmonize that, all other things being equal, wil make one group especially talented, productive, and successful, and another — with members whose talent and skill are equal in other regards — do poorly.
>Informal networks are especially critical for handling unanticipated problems. "The formal organization is set up to handle easily anticipated problems," one study of these networks observes. "But when unexpected problems arise, the informal organization kicks in. Its complex web of social ties form every time colleagues communicate, and solidify over time into surprisingly stable networks. Highly adaptive, informal networks move diagonally and elliptically, skipping entire functions to get things done."
>In brain terms, we can speculate, the limbic circuitry would send alarm signals in response to cues of a feared event, but the prefrontal cortex and related zones would have learned a new, more healthy response. In short, emotional lessons — even the most deeply implanted habits of the heart learned in childhood — can be reshaped. Emotional learning is lifelong.
>A key social ability is empathy, understanding others' feelings and taking their perspective, and respecting differences in how people feel about things. Relationships are a major focus, including learning to be a good listener and question-asker; distinguishing between what someone says or does and your own reactions and judgements; being assertive rather than angry or passive; and learning the arts of cooperation, conflict resolution, and negotiating compromise.
>"Dreams are private myths; myths are shared dreams"
这本书书名直译为《情绪智力》,和我们通常理解的情商类似,但读完感觉还是有点差别。我们常说某人“情商高”,是指一个人在和他人沟通和交往中,善于表达自己的想法和情绪,和“性格外向”有一些交叉的部分。而书中讲到的情绪智力,则更偏重于对于情绪本身的掌控能力,这就包括能正确地了解自己的情绪,同时也能很好地理解他人的情绪。
要想准确地了解自己的情绪,尤其是当下的情绪,首先要能用准确的词汇将它描述出来。就像书中的一句话的大意说的:“只有能描述的情绪,才是你自己所能拥有的情绪”,我对这句话的理解是,如果我们缺乏足够的语言来描述自己的情绪,那么我们也无法理清这些情绪的来龙去脉,更别说掌控他们了。
作为阐述情绪智力的专著,书中自然要从各种不同的场景来探讨情绪智力起作用或者缺失时的情形:由情绪失控引起的极端暴力、日常和他人的相处、家庭的和睦、病人的康复、心理创伤等等话题。总之一句话,较高的情绪智力能带来更好的生活质量,而情绪智力本身是能后天通过学习和训练习得的。本书在最后的章节还专门介绍了一些在美国针对小学生情绪智力的教育项目。
我从小是一个内向又自卑的小孩,后来大了一点又变成了一个情绪易波动的愤青。而到现在快要接近而立之年,大概是要感谢自己经历的人和事,当然也还有自己的努力,现在的我,在书中提到的情绪智力上,有了可以说是飞跃般的提升。当我在上学直到刚开始工作的时候,我会觉得和人打交道是一件极痛苦又没有意义的事情,写一辈子的代码才是最幸福的事情。而现在的我,既能享受进入心流的状态专心编写和调试计算机程序的过程,也更愿意去和各种不同的人面对面交流。很喜欢沉思录里说过的一句话:“我们生来是为合作的,如双足、两手、上下眼皮、上下排的牙齿。”。而要能实现自身更大的价值,为社会创造更多贡献,就应该学会更好地去和他人协作。因此,提高自己的情绪智力是一件很重要的事情,而这也如书中所言:情绪智力的学习是一辈子的事情。
诸君共勉之。 |
Java | UTF-8 | 404 | 2.078125 | 2 | [] | no_license | package services.orders;
import customerproductorder.models.Customer;
import customerproductorder.models.Order;
import java.util.List;
public interface OrderServiceInterface {
public void create(Order newOrder);
public Order get(Customer customer);
public Order get(int id);
public List<Order> getAll();
public void delete(int id);
public void save(Order changedOrder);
}
|
C# | UTF-8 | 18,084 | 3.015625 | 3 | [
"CC-BY-NC-4.0",
"CC-BY-NC-SA-4.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
using HeroFight;
[TestClass]
public class StructureTests
{
private static readonly Assembly ProjectAssembly = typeof(StartUp).Assembly;
// Class names
private Type[] classes01 =
{
GetType01("Hero"),
};
[TestMethod]
public void TestFieldIsPrivate()
{
foreach (var className in classes01)
{
AssertFields(className);
}
}
private void AssertFields(Type className)
{
var fields = className.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var fieldInfo in fields)
{
Assert.IsTrue(fieldInfo.IsPrivate, $"{fieldInfo.Name} in {className.Name} is NOT Private");
}
}
private static Type GetType01(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T02.cs
private Type[] classes02 =
{
GetType02("Hero"),
};
private Dictionary<string, Type> propertiesTypes = new Dictionary<string, Type>()
{
{ "Name", typeof(string)},
{ "Level",typeof(int)},
{ "Experience", typeof(int)},
{ "Weapon", GetType02("Weapon")},
{ "Power", typeof(double)},
};
[TestMethod]
public void TestPropertiesExist()
{
foreach (var className in classes02)
{
AssertFields02(className);
}
}
private void AssertFields02(Type className)
{
var properties = className
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var propertyInfo in properties)
{
Assert.IsTrue(this.propertiesTypes.ContainsKey(propertyInfo.Name), $"{propertyInfo.Name} in {className.Name} is NOT Defined");
}
}
private static Type GetType02(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T03.cs
private Type[] classes03 =
{
GetType03("Hero"),
};
private string propertyName = "Name";
[TestMethod]
public void TestNameSetMethodIsPrivate()
{
foreach (var className in classes03)
{
AssertPropertySetMethodIsPrivate(className);
}
}
private void AssertPropertySetMethodIsPrivate(Type className)
{
var property = className
.GetProperty(propertyName);
Assert.IsTrue(property.SetMethod.IsPrivate,
$"Property {propertyName} set method is not private");
}
private static Type GetType03(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T04.cs
private Type[] classes04 =
{
GetType04("Hero"),
};
private string propertyName04 = "Level";
[TestMethod]
public void TestNameSetMethodIsPrivate04()
{
foreach (var className in classes04)
{
AssertPropertySetMethodIsPrivate04(className);
}
}
private void AssertPropertySetMethodIsPrivate04(Type className)
{
var property = className
.GetProperty(propertyName04);
Assert.IsTrue(property.SetMethod.IsPrivate,
$"Property {propertyName} set method is not private");
}
private static Type GetType04(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T05.cs
private Type[] classes05 =
{
GetType05("Hero"),
};
private Type[] constructorParametersTypes =
{
typeof(string),
};
[TestMethod]
public void TestConstructorParametersAndAccessModifier()
{
foreach (var className in classes05)
{
AssertConstructorIsFamily05(className);
}
}
private void AssertConstructorIsFamily05(Type className)
{
ConstructorInfo constructor = className
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
constructorParametersTypes, null);
Assert.IsNotNull(constructor);
Assert.IsTrue(constructor.IsFamily);
}
private static Type GetType05(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T06.cs
private Type[] classes06 =
{
GetType06("Hero"),
};
[TestMethod]
public void TestClassIsAbstract()
{
foreach (var className in classes06)
{
AssertClassIsAbstract06(className);
}
}
private void AssertClassIsAbstract06(Type className)
{
Assert.IsTrue(className.IsAbstract);
}
private static Type GetType06(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T07.cs
private Type[] classes07 =
{
GetType07("Assassin"),
};
private Type baseClass = GetType07("Hero");
[TestMethod]
public void TestSwordBaseClass()
{
foreach (var className in classes07)
{
AssertBaseClass07(className);
}
}
private void AssertBaseClass07(Type className)
{
Assert.IsTrue(className.BaseType == baseClass);
}
private static Type GetType07(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T08.cs
private Type[] classes08 =
{
GetType08("Priest"),
};
private Type baseClass08 = GetType08("Hero");
[TestMethod]
public void TestSwordBaseClass08()
{
foreach (var className in classes08)
{
AssertBaseClass08(className);
}
}
private void AssertBaseClass08(Type className)
{
Assert.IsTrue(className.BaseType == baseClass08);
}
private static Type GetType08(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T09.cs
private Type[] classes09 =
{
GetType09("Warrior"),
};
private Type baseClass09 = GetType09("Hero");
[TestMethod]
public void TestSwordBaseClass09()
{
foreach (var className in classes09)
{
AssertBaseClass09(className);
}
}
private void AssertBaseClass09(Type className)
{
Assert.IsTrue(className.BaseType == baseClass09);
}
private static Type GetType09(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//WeaponTests ========================================================
//T01.cs
private Type[] classes10 =
{
GetType10("Weapon"),
};
[TestMethod]
public void TestFieldIsPrivate01()
{
foreach (var className in classes10)
{
AssertFields01(className);
}
}
private void AssertFields01(Type className)
{
var fields = className
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var fieldInfo in fields)
{
Assert.IsTrue(fieldInfo.IsPrivate,
$"{fieldInfo.Name} in {className.Name} is NOT Private");
}
}
private static Type GetType10(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T02.cs
private Type[] classes11 =
{
GetType11("Weapon"),
};
private Dictionary<string, Type> propertiesTypes11 = new Dictionary<string, Type>()
{
{ "Name", typeof(string)},
{ "Strength",typeof(int)},
{ "Agility", typeof(int)},
{ "Intelligence", typeof(int)},
};
[TestMethod]
public void TestPropertiesExist02()
{
foreach (var className in classes11)
{
AssertFields02W(className);
}
}
private void AssertFields02W(Type className)
{
var properties = className
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var propertyInfo in properties)
{
Assert.IsTrue(this.propertiesTypes11.ContainsKey(propertyInfo.Name), $"{propertyInfo.Name} in {className.Name} is NOT Defined");
}
}
private static Type GetType11(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T03.cs
private Type[] classes12 =
{
GetType12("Weapon"),
};
private string propertyName12 = "Name";
[TestMethod]
public void TestNameSetMethodIsPrivate03()
{
foreach (var className in classes12)
{
AssertPropertySetMethodIsPrivate03(className);
}
}
private void AssertPropertySetMethodIsPrivate03(Type className)
{
var property = className
.GetProperty(propertyName12);
Assert.IsTrue(property.SetMethod.IsPrivate,
$"Property {propertyName} set method is not private");
}
private static Type GetType12(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T04.cs
private Type[] classes13 =
{
GetType13("Weapon"),
};
private string propertyName13 = "Strength";
[TestMethod]
public void TestStrengthSetMethodIsPrivateOrIsFamily()
{
foreach (var className in classes13)
{
AssertPropertySetMethodIsPrivateOrIsFamily(className);
}
}
private void AssertPropertySetMethodIsPrivateOrIsFamily(Type className)
{
var property = className
.GetProperty(propertyName13);
Assert.IsTrue(property.SetMethod.IsPrivate || property.SetMethod.IsFamily);
}
private static Type GetType13(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T05.cs
private Type[] classes14 =
{
GetType14("Weapon"),
};
private string propertyName14 = "Agility";
[TestMethod]
public void TesAgilitySetMethodIsPrivateOrIsFamily05()
{
foreach (var className in classes14)
{
AssertPropertySetMethodIsPrivateOrFamily(className);
}
}
private void AssertPropertySetMethodIsPrivateOrFamily(Type className)
{
var property = className
.GetProperty(propertyName14);
Assert.IsTrue(property.SetMethod.IsPrivate || property.SetMethod.IsFamily);
}
private static Type GetType14(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T06.cs
private Type[] classes15 =
{
GetType15("Weapon"),
};
private string propertyName15 = "Intelligence";
[TestMethod]
public void TestIntelligenceSetMethodIsPrivateOrIsFamily()
{
foreach (var className in classes15)
{
AssertPropertySetMethodIsPrivate06(className);
}
}
private void AssertPropertySetMethodIsPrivate06(Type className)
{
var property = className
.GetProperty(propertyName15);
Assert.IsTrue(property.SetMethod.IsPrivate || property.SetMethod.IsFamily);
}
private static Type GetType15(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T07.cs
private Type[] classes16 =
{
GetType16("Weapon"),
};
private Type[] constructorParametersTypes16 =
{
typeof(string),
typeof(int),
typeof(int),
typeof(int),
};
[TestMethod]
public void TestConstructorParametersAndAccessModifier07()
{
foreach (var className in classes16)
{
AssertConstructorIsFamily(className);
}
}
private void AssertConstructorIsFamily(Type className)
{
ConstructorInfo constructor = className
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
constructorParametersTypes16, null);
Assert.IsNotNull(constructor);
Assert.IsTrue(constructor.IsFamily);
}
private static Type GetType16(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T08.cs
private Type[] classes17 =
{
GetType17("Weapon"),
};
[TestMethod]
public void TestClassIsAbstract08()
{
foreach (var className in classes17)
{
AssertClassIsAbstract(className);
}
}
private void AssertClassIsAbstract(Type className)
{
Assert.IsTrue(className.IsAbstract);
}
private static Type GetType17(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T09.cs
private Type[] classes18 =
{
GetType18("Sword"),
};
private Type baseClass18 = GetType18("Weapon");
[TestMethod]
public void TestSwordBaseClass09W()
{
foreach (var className in classes18)
{
AssertBaseClass18(className);
}
}
private void AssertBaseClass18(Type className)
{
Assert.IsTrue(className.BaseType == baseClass18);
}
private static Type GetType18(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T10.cs
private Type[] classes19 =
{
GetType19("Bow"),
};
private Type baseClass19 = GetType19("Weapon");
[TestMethod]
public void TestBowBaseClass()
{
foreach (var className in classes19)
{
AssertBaseClass10(className);
}
}
private void AssertBaseClass10(Type className)
{
Assert.IsTrue(className.BaseType == baseClass19);
}
private static Type GetType19(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
//T11.cs
private Type[] classes20 =
{
GetType20("MagicWand"),
};
private Type baseClass20 = GetType20("Weapon");
[TestMethod]
public void TestMagicWandBaseClass()
{
foreach (var className in classes20)
{
AssertBaseClass11(className);
}
}
private void AssertBaseClass11(Type className)
{
Assert.IsTrue(className.BaseType == baseClass20);
}
private static Type GetType20(string name)
{
var type = ProjectAssembly
.GetTypes()
.FirstOrDefault(t => t.Name == name);
return type;
}
}
}
|
C# | UTF-8 | 1,302 | 3.078125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DiffWords
{
public class OrfoepicDict : IPrimaryForm
{
private List<List<string>> Nouns;
public OrfoepicDict()
{
Nouns = ReadDict();
}
public Word Analize(Word _word)
{
foreach (List<string> n in this.Nouns)
{
if (n.Contains(_word.Value))
{
return new Word(n[0]);
}
}
return null;
}
private List<List<string>> ReadDict()
{
List<List<string>> result = new List<List<string>>();
List<string> temp = new List<string>();
foreach (string s in File.ReadLines(Environment.CurrentDirectory + @"\dict\orfoepic.txt"))
{
if (!string.IsNullOrEmpty(s.Trim()))
temp.Add(s.Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries)[0].Trim());
else
{
result.Add(new List<string>(temp));
temp = new List<string>();
}
}
return result;
}
}
}
|
Markdown | UTF-8 | 6,500 | 3.203125 | 3 | [
"MIT"
] | permissive | ---
description: Dans ce TP nous allons découvrir l'utilisation de VueJS sans Webpack. Nous allons donc utiliser directement le CDN de VueJS.
---
# Prise en main de VueJS 2.0
Dans ce TP nous allons découvrir l'utilisation de VueJS sans Webpack. Nous allons donc utiliser directement le CDN de VueJS.
::: details Table des matières
[[toc]]
:::
## Initialisation
Ajouter VueJS dans un projet est aussi simple que d'ajouter une librairie. Première étape, créer un fichier `index.html` puis insérer à l'intérieur « une structure HTML 5 »
::: tip
Si vous utilisez Visual Studio Code, vous pouvez faire html:5<kbd>Tab</kbd> une structure HTML sera automatiquement écrite.
:::
```html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Démo VueJS</title>
</head>
<body>
<!-- Votre code ici -->
</body>
</html>
```
Pour ajouter VueJS dans la page ? Il faut juste ajouter la balise script suivante dans le « head » de votre page :
```html
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
```
Et voilà !
## Ah ouais ? C'est aussi simple !?
Bon en vrai on va devoir ajouter quelques petits trucs… Si vous avez suivi pendant mon cours :
- Une balise « racine » qui contiendra notre template.
- Une balise script qui contiendra notre code JavaScript.
### Ajout des éléments
Remplacer le commentaire `<!-- Votre code ici -->` par
```html
<div id="app"></div>
<script>
var app = new Vue({
el: "#app",
mounted() {
console.log("Ding ! 🍪 Votre code fonctionne !");
},
});
</script>
```
🚀 Et voilà ! Là c'est vraiment tout. Votre code est prêt. Vous pouvez faire du VueJS 🍪.
## Tester votre code
Votre code doit dès à présent fonctionner ! Vérifier dans la console de votre navigateur que vous avez la phrase :
`Ding ! 🍪 Votre code fonctionne !`
## Un simple bouton
Nous allons ajouter un simple « button » dans notre page. Celui-ci affichera une `alert` lorsque l'utilisateur clique dessus. Modifier votre objet VueJS pour qu'il ressemble à :
```js
new Vue({
el: "#app",
mounted() {
console.log("Ding ! 🍪 Votre code fonctionne !");
},
methods: {
action() {
alert("🎉 Bravo 🎉");
},
},
});
```
Vous venez de déclarer une nouvelle méthode, celle-ci se nomme `action`, celle-ci affiche « Bravo ». Il faut donc maintenant l'appeler…
En VueJS, c'est simple ! Il vous suffit d'ajouter _dans_ `<div id="app"></div>` un bouton. Après modification votre code doit ressembler à :
```html
<div id="app">
<button @click="action">Clique ici</button>
</div>
```
🤓 Notez le `@click="action"` qui fait référence à votre méthode `action`.
🚀 Tester votre code.
## Afficher une liste
Un bouton c'est bien, mais une liste c'est mieux non ? Vous allez voir qu'afficher une liste c'est aussi simple qu'un bonjour 👋. Comme vu ensemble en cours, nous allons :
- Déclarez-les `data`.
- Faire un `v-for` dans le code.
### Les data
Vous vous souvenez comment déclarer les datas ? Non !? un petit rappel alors, nous allons déclarer un tableau (`[]`) directement dans la méthode `data` de notre objet VueJS. Quelque chose comme :
```js
data(){
return {
liste: ["Item 1", "Item 2", "Item 3"]
}
}
```
🤓 Notez que la variable est nommée `liste`.
Une fois intégré à votre code :
```js
new Vue({
el: "#app",
mounted() {
console.log("Ding ! 🍪 Votre code fonctionne !");
},
data() {
return {
liste: [],
};
},
methods: {
action() {
alert("🎉 Bravo 🎉");
},
},
});
```
🚀 Valider avec les Vue Dev Tools que votre liste est bien présente.
### Afficher la liste
Pour afficher la liste nous allons devoir faire un `v-for` sur l'élément qui sera `répété` ou `afficher plusieurs fois`. Exemple :
```html
<ul>
<li v-for="item in liste">{{item}}</li>
</ul>
```
Ajouter le code HTML dans la `div#data`, vous devez obtenir :
```html
<div id="app">
<button @click="action">Clique ici</button>
<ul>
<li v-for="item in liste">{{item}}</li>
</ul>
</div>
```
🚀 Tester votre application ! Vous devez voir les éléments de votre liste.
🤓 Tester d'ajouter un élément « à la main » via les VueJS dev tools.
## Ajouter un élément dans la liste
Le but de VueJS c'est aussi de rendre simple la modification de la vue / template / affichage. Nous allons (enfin vous…) modifier le code précédent pour ajouter dans la liste l'élément saisi par l'utilisateur :
Modifier la méthode action pour y mettre le code suivante :
```js
this.liste.push(prompt("Entrer une valeur"));
```
🚀 Tester votre code
## Et via un input ?
Un prompt c'est « pas très beau » non ? Passer par un input HTML serait quand même plus sympa ! Pour ça rien de plus simple, ajouter le code suivant dans `#app` :
```html
<input
type="text"
@keyup.enter="liste.push($refs['input'].value)"
ref="input"
/>
```
☝️ Quelques explications :
- `@keyup.enter` Permets de déclarer une méthode qui sera appelée lors de l'appui sur la touche entrée.
- `ref` permet de déclarer une référence vers l'élément HTML, celui-ci sera ensuite disponible par `$refs['input']`
## Et via un input 2 ?
La première solution est pas trop mal, mais, utiliser les data est serait certainement une meilleure idée. Autre solution, mais tout aussi simple (et certainement bien meilleur).
- Déclarer une nouvelle variable dans les `data`, par exemple, dans mon cas la variable est `saisie` :
```js
data(){
return {
saisie: "",
liste: ["Item", "Item 2"],
}
}
```
- Ajouter un input qui utiliser la variable saisie :
```html
<input type="text" v-model="saisie" @keyup.enter="liste.push(saisie)" />
```
☝️ Quelques explications :
- `v-model` Permets de connecter la variable saisie à votre input.
- `@keyup.enter` Permets de déclarer une méthode qui sera appelée lors de l'appui sur la touche entrée.
## L'input n'est pas vidé ?
Comme vous l'avez très certainement remarqué, le champ n'est pas vidé après une saisie… Vous avez deux solutions pour faire ça:
- Modifier le code dans le `@keyup.enter` pour effacer la variable `saisie`. (Via la création d'une nouvelle méthode dans votre objet).
- Autre solution via un watcher sur la variable `saisie`.
C'est à vous implémenté la première solution, puis la seconde.
|
Python | UTF-8 | 620 | 3.53125 | 4 | [
"MIT"
] | permissive | class Argentina:
def getPresident(self):
president = self.whoisinpower()
return "The current president is {}".format(president)
def whoisinpower(self):
return "Mauricio Macri"
def getPopulation(self):
return "45 Million"
def getCapital(self):
return "Buenos Aires"
def describe():
population = Argentina.getPopulation()
capital = Argentina.getCapital()
president = Argentina.getPresident()
return "Argentina is a beautiful country with a population of {}, \n whose capital is {} and whose president is {}".format(population, capital, president)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.