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
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 865
| 2.75
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Table {
public String table_name;
public int num_atts;
public List<String[]> atts_details;
public int num_records;
public int old_num_of_records;
Table(String name, HashMap mp )
{
table_name = name;
atts_details = new ArrayList<String []>();
String[] temp;
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
temp = new String[2];
temp[0] = (String)pairs.getKey(); //Attribute Name
temp[1] = (String)pairs.getValue(); //Attribute Type
atts_details.add(temp);
it.remove(); // avoids a ConcurrentModificationException
}
num_atts = atts_details.size();
}
Table()
{
}
}
|
PHP
|
UTF-8
| 2,038
| 2.65625
| 3
|
[] |
no_license
|
<?php
namespace Pandora\Service;
use Pandora\Config;
use Pandora\Http\Client;
final class LogDbService {
private $repoName;
private $auth;
public function __construct($repoName, $auth) {
$this->repoName = $repoName;
$this->auth = $auth;
}
/**
* @param string $queryString 查询表达式 eg: field1:field_val
* @param string $sortByField 指定排序的字段 eg: field1:asc,field2:desc
* @param int $offsetFrom 返回的日志开始的位置
* @param int $limitSize 返回的数据数量
* @param array $fields 指定只返回哪些字段 eg: array("field1", "field2", ...)
* @return \Pandora\Http\Response
*
* 参考 https://qiniu.github.io/pandora-docs/#/api/logdb?id=%e6%9f%a5%e8%af%a2%e6%97%a5%e5%bf%97
*/
public function searchLogs($queryString, $sortByField, $offsetFrom, $limitSize, array $fields = array()) {
$path = "/v5/repos/$this->repoName/search";
$params = array(
'query' => $queryString,
'sort' => $sortByField,
'from' => $offsetFrom,
'size' => $limitSize,
);
if (count($fields) != 0) {
$params['fields'] = implode(',', $fields);
}
$params = json_encode($params);
return $this->post($path, $params, 'application/json');
}
public function msearch($querybody) {
$path = "/v5/logdbkibana/msearch";
return $this->post($path, $querybody, 'text/plain');
}
private function post($path, $body, $contentType) {
return $this->request("POST", $path, $body, $contentType);
}
private function request($method, $path, $body, $contentType) {
$headers['Content-Type'] = $contentType;
$accessToken = $this->auth->createAccessToken($method, $path, $headers, $contentType);
$headers['Authorization'] = $accessToken;
$url = Config::LOG_DB_API_ADDRESS . $path;
return Client::request($method, $url, $body, $headers);
}
}
|
C#
|
UTF-8
| 2,034
| 2.546875
| 3
|
[] |
no_license
|
using System;
using Leaf.Parsing.AST.StatementNodes;
using Leaf.Parsing.AST.FunctionNodes;
using System.Collections.Immutable;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Linq;
using Leaf.Parsing.Grammar;
namespace Leaf.Parsing.AST.ValueNodes
{
public class FunctionCallNode : ValueNode, IStatementNode
{
private ValueNode _lValue = PlaceHolder;
private IReadOnlyList<ValueNode> _parameters = ImmutableList<ValueNode>.Empty;
public FunctionCallNode() {}
public FunctionCallNode(LeafParser.ValueContext ctx)
{
if (ctx.call == null)
throw new ArgumentException("Context does not define a function call.");
var values = ctx.value();
Line = ctx.Start.Line;
LValue = Create(values[0]);
var parameters = new ValueNode[values.Length - 1];
for (var i = 0; i < parameters.Length; i++)
parameters[i] = Create(values[i + 1]);
Parameters = parameters;
}
public FunctionCallNode(LeafParser.Function_callContext ctx)
{
var values = ctx.value();
Line = ctx.Start.Line;
LValue = Create(values[0]);
var parameters = new ValueNode[values.Length - 1];
for (var i = 0; i < parameters.Length; i++)
parameters[i] = Create(values[i + 1]);
Parameters = parameters;
}
public ValueNode LValue
{
get => _lValue;
set
{
_lValue = value;
_lValue.Parent = this;
}
}
public IReadOnlyList<ValueNode> Parameters
{
get => _parameters;
set
{
_parameters = value;
foreach (var parameter in _parameters)
parameter.Parent = this;
}
}
LeafAstNode? IStatementNode.Parent
{
get => Parent;
set => Parent = value;
}
protected override void InnerAppendToSource(IndentedTextWriter src)
{
_lValue.AppendToSource(src);
src.Write('(');
for (var i = 0; i < _parameters.Count; i++)
{
_parameters[i].AppendToSource(src);
if(i < _parameters.Count - 1) src.Write(", ");
}
src.Write(')');
if(Parent is ScopeNode)
src.Write(';');
}
}
}
|
Python
|
UTF-8
| 4,547
| 2.65625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
"""
filename: MultiStrokeFeatureObserver.py
description:
Doctest Examples:
"""
#-------------------------------------
import os
import math
import pdb
from Utils import GeomUtils
from Utils import Logger
from SketchFramework import Point
from SketchFramework import Stroke
from SketchFramework.Annotation import Annotation
from SketchFramework.Board import BoardObserver
logger = Logger.getLogger('MultiStrokeObserver', Logger.DEBUG )
#-------------------------------------
class MultiStrokeAnnotation(Annotation):
def __init__(self, tag):
Annotation.__init__(self)
self.name = tag
#-------------------------------------
class MultiStrokeMarker( BoardObserver ):
"Compares all strokes with templates and annotates strokes with any template within some threshold."
def __init__(self):
self.getBoard().AddBoardObserver( self , [MultiStrokeAnnotation])
self.getBoard().RegisterForStroke( self )
self._features = {} # To be: { stroke : (feature_vector) }
self._matchVector = None
self.overlaps = {}
def onStrokeAdded( self, stroke ):
"Compare this stroke to all templates, and annotate those matching within some threshold."
logger.debug("Scoring stroke")
#strokeVector = ( len(stroke.Points), GeomUtils.pointListOrientationHistogram(GeomUtils.strokeNormalizeSpacing(stroke, numpoints = len(stroke.Points) / 3.0).Points) )
strokeVector = generateFeatureVector(stroke)
logger.debug("Stroke Vector: %s" % (str(strokeVector)))
if self._matchVector == None:
self._matchVector = strokeVector
else:
bb1 = GeomUtils.strokelistBoundingBox([stroke])
for prevStk in self._features.keys():
bb2 = GeomUtils.strokelistBoundingBox([prevStk])
if GeomUtils.boundingboxOverlap(bb1, bb2):
self.overlaps.setdefault(stroke, set()).add(prevStk)
self.overlaps.setdefault(prevStk, set()).add(stroke)
self._features[stroke] = strokeVector
score = scoreVector(self._matchVector, strokeVector)
logger.debug(" Distance %s from baseline" % (score) )
if score < 0.02:
self.getBoard().AnnotateStrokes([stroke], MultiStrokeAnnotation("Match"))
for stk in self.overlaps.get(stroke, []):
multiVect = addVectors( [self._features[stroke], self._features[stk] ] )
logger.debug("Multiple vector: %s" % (str(multiVect)))
score = scoreVector(self._matchVector, multiVect)
logger.debug(" Distance %s from baseline" % (score) )
if score < 0.02:
self.getBoard().AnnotateStrokes([stroke, stk], MultiStrokeAnnotation("Match"))
def onStrokeRemoved(self, stroke):
"When a stroke is removed, remove circle annotation if found"
for anno in stroke.findAnnotations(MultiStrokeAnnotation, True):
self.getBoard().RemoveAnnotation(anno)
def generateFeatureVector(stroke):
finalVector = {}
finalVector['len'] = GeomUtils.strokeLength(stroke)
sNorm = GeomUtils.strokeNormalizeSpacing( stroke, max(finalVector['len'] / 4.0, 1) )
finalVector['orientations'] = GeomUtils.pointListOrientationHistogram(sNorm.Points)
return finalVector
def addVectors(vectList):
logger.debug("Adding Vectors")
for v in vectList:
logger.debug(" %s" % (str(v)))
retVect = {}
total = sum([v['len'] for v in vectList])
retVect['len'] = total
orientations = len(vectList[0]['orientations']) * [0]
if total > 0:
for i in range(len(vectList)):
w = vectList[i]['len'] / float(total)
for j in range(len(orientations)):
orientations[j] += w * vectList[i]['orientations'][j]
retVect['orientations'] = tuple(orientations)
logger.debug("-->%s" % (str(retVect)))
return retVect
def scoreVector(baseline, tester):
#orientations
orientationDist = 1.0
if len(baseline['orientations']) == len(tester['orientations']):
dist = 0.0
for i in range(len(baseline['orientations'])):
dist += (baseline['orientations'][i] - tester['orientations'][i]) ** 2
math.sqrt(dist)
orientationDist = dist / math.sqrt(2)
return orientationDist
|
Java
|
UTF-8
| 1,702
| 3.34375
| 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 Student;
import java.util.Scanner;
/**
*
* @author hi
*/
public class Student implements Comparable<Student>{
//fields
private String name;
private String sClass;
private float mark;
//constructor
public Student(String name, String sClass, float mark) {
this.name = name;
this.sClass = sClass;
this.mark = mark;
}
//setter
public void setName(String name) {
this.name = name;
}
public void setsClass(String sClass) {
this.sClass = sClass;
}
public void setMark(float mark) {
this.mark = mark;
}
//getter
public String getName() {
return name;
}
public String getsClass() {
return sClass;
}
public float getMark() {
return mark;
}
//method
//nhap thong tin cho sinh vien
// public void nhapInfo(){
// int flag = 0;
// Scanner s = new Scanner(System.in);
// do {
// try {
// System.out.println("Enter student name:");
// s = new Scanner(System.in);
// name = s.nextLine();
// if(name.equals(""))throw new Exception("Student name must not be empty");
// } catch (Exception e) {
// }
// } while (flag == 0);
// }
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.name);
}
}
|
C++
|
UTF-8
| 7,020
| 3.40625
| 3
|
[] |
no_license
|
#include "identificativo.h"
#include <algorithm>
const std::string Identificativo::VOCALI("AEIOU");
Identificativo::Identificativo() : Sesso(), nome(""), cognome("") {}
Identificativo::Identificativo(std::string n, std::string c) : Sesso(), nome(n), cognome(c) {}
Identificativo::Identificativo(const Identificativo& a) : Sesso(a), nome(a.nome), cognome(a.cognome) {}
unsigned int Identificativo::contaConsonanti(std::string str) throw() {
unsigned int c = 0; //c contiene il numero di consonanti trovate in str
std::string::const_iterator it = str.begin();
while(it < str.end()) {
if(std::find(VOCALI.begin(), VOCALI.end(), *it) == VOCALI.end()) ++c;
++it;
}
return c;
}
std::string Identificativo::generaCodCognome() const throw() {
//cognome contiene almeno 2 caratteri (da metodo controllo)
std::string str; //conterra' codice cognome
if(cognome.size() < 3) {
//cognome ha meno di 3 caratteri, si aggiunge X alla fine
//estrazione delle consonanti seguite dalle vocali, se presenti, nel loro ordine
std::string::size_type pos = VOCALI.find(*(cognome.begin()));
if(pos != std::string::npos) { //il primo carattere del cognome e' una vocale
//controllo del secondo carattere
pos = VOCALI.find(*(cognome.end()-1));
if(pos == std::string::npos) { //il secondo carattere e' una consonante, str deve contenere prima la consonante, poi la vocale
str.push_back(*(cognome.end()-1));
str.push_back(*(cognome.begin()));
} else str = cognome; //sono due vocali, str le contiene nel loro ordine
} else str = cognome; //sono due consonanti, str le contiene nel loro ordine
str.push_back('X'); //aggiunta X come terzo char
} else {
//cognome piu' lungo di 3 caratteri
//costruzione cognome con le consonanti
std::string::const_iterator it = cognome.begin();
while(it < cognome.end() && str.size() < 3) {
if(std::find(VOCALI.begin(), VOCALI.end(), *it) == VOCALI.end()) str.push_back(*it); // se e' una consonante viene inserita in str
++it;
}
//caso in cui le consonanti sono < 2
it = cognome.begin();
while(str.size() < 3){
if(std::find(VOCALI.begin(), VOCALI.end(), *it) != VOCALI.end())
str.push_back(*it);
++it;
}
}
return str;
}
std::string Identificativo::generaCodNome() const throw() {
//nome contiene almeno 2 caratteri (da metodo controllo)
std::string str; //conterra' codice nome
//controllo lunghezza nome
if(nome.size() < 3) {
//cognome ha meno di 3 caratteri, va aggiunta X alla fine
//estrazione delle consonanti seguite dalle vocali, se presenti, nel loro ordine
std::string::size_type pos = VOCALI.find(*(nome.begin()));
if(pos != std::string::npos) { //il primo carattere del nome e' una vocale
//controllo del secondo carattere
pos = VOCALI.find(*(nome.end()-1));
if(pos == std::string::npos) { //il secondo carattere e' una consonante, str deve contenere prima la consonante, poi la vocale
str.push_back(*(nome.end()-1));
str.push_back(*(nome.begin()));
} else str = nome; //sono due VOCALI, str le contiene nel loro ordine
} else str = nome; //sono due consonanti, str le contiene nel loro ordine
str.push_back('X'); //aggiunta X come terzo char
} else {
//nome piu' lungo di 3 caratteri
unsigned int cons = contaConsonanti(nome);
unsigned int aux = 0;
std::string::const_iterator it = nome.begin();
//numero consonanti >3, si estraggono da nome la 1a, 3a e 4a
while(it < nome.end() && str.size() < 3) {
if(cons > 3) {
if(std::find(VOCALI.begin(), VOCALI.end(), *it) == VOCALI.end()) {
if(aux != 1) str.push_back(*it);
++aux;
}
} else {
//numero consonanti <=3, si estraggono le consonanti di nome nel loro ordine
if(std::find(VOCALI.begin(), VOCALI.end(), *it) == VOCALI.end()) str.push_back(*it);
}
++it;
}
// caso in cui le consonanti sono < 2
it = nome.begin();
while(str.size() < 3){
if(std::find(VOCALI.begin(), VOCALI.end(), *it) != VOCALI.end())
str.push_back(*it);
++it;
}
}
return str;
}
std::istream& operator>>(std::istream& is, Identificativo& i) throw(CFexception) {
//possibili input contenenti spazi
std::string nome, cognome;
std::cout<<"Inserisci cognome: ";
std::cin.ignore(); //scarta carattere newline nel buffer di input (dalla precedente digitazione della funzione)
std::getline(is, cognome); //stop quando raggiunge carattere newline (newline letto e scartato)
if(is.gcount() == 0) throw AntrCorto();
std::cout<<"Inserisci nome: ";
std::getline(is, nome);
if(is.gcount() == 0) throw AntrCorto();
nome.erase(remove_if(nome.begin(), nome.end(), isspace), nome.end()); //eliminazione spazi nome
cognome.erase(remove_if(cognome.begin(), cognome.end(), isspace), cognome.end()); //eliminazione spazi cognome
std::transform(nome.begin(), nome.end(), nome.begin(), ::toupper); //conversione minuscole in maiuscole
std::transform(cognome.begin(), cognome.end(), cognome.begin(), ::toupper); //conversione minuscole in maiuscole
i.nome = nome;
i.cognome = cognome;
return is;
}
void Identificativo::creaDaCodice(const std::string& cod) throw() {
//cognome e nome conterranno il corrispondente codice estratto dal cf
cognome = cod.substr(0,3);
nome = cod.substr(3,3);
}
std::string Identificativo::generaCodice() const throw() {
return generaCodCognome() + generaCodNome();
}
void Identificativo::controllo() throw(CFexception) {
const std::string ALFABETO("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
//nome e cognome devono essere composti da almeno 2 caratteri
if(nome.size() < 2 || cognome.size() < 2) throw AntrCorto();
//controllo caratteri nome e cognome (le stringhe non contengono spazi)
//nome e cognome possono contenere solo lettere dell'alfabeto
std::string::size_type pos;
for(std::string::const_iterator it = nome.begin(); it != nome.end(); ++it) {
pos = ALFABETO.find(*it);
if(pos == std::string::npos) throw ErrAntr();
}
for(std::string::const_iterator it = cognome.begin(); it != cognome.end(); ++it) {
pos = ALFABETO.find(*it);
if(pos == std::string::npos) throw ErrAntr();
}
}
std::string Identificativo::toString() const throw() {
return (cognome + " " + nome);
}
Identificativo::operator bool() const throw() {
//controllo se oggetto identificativo ha valori assegnati (diversi da parametri di default)
return cognome != "";
}
|
Java
|
UTF-8
| 3,359
| 1.820313
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.adsdk.sdk.video;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.TypedValue;
import com.adsdk.sdk.Log;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
// Referenced classes of package com.adsdk.sdk.video:
// ResourceManager
class mUrl extends AsyncTask
{
Context mContext;
int mResourceId;
String mUrl;
final ResourceManager this$0;
private Drawable fetchImage(String s)
{
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)(new URL(s)).getContent());
if (bitmap == null) goto _L2; else goto _L1
_L1:
int i;
int j;
int k;
int l;
android.util.DisplayMetrics displaymetrics = mContext.getResources().getDisplayMetrics();
i = bitmap.getWidth();
j = bitmap.getHeight();
k = (int)TypedValue.applyDimension(1, i, displaymetrics);
l = (int)TypedValue.applyDimension(1, j, displaymetrics);
if (k == i && l == j)
{
break MISSING_BLOCK_LABEL_139;
}
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, k, l, false);
_L3:
BitmapDrawable bitmapdrawable = new BitmapDrawable(mContext.getResources(), bitmap1);
return bitmapdrawable;
Exception exception;
exception;
Log.e((new StringBuilder("Cannot fetch image:")).append(s).toString(), exception);
_L2:
return null;
bitmap1 = bitmap;
goto _L3
}
protected transient Boolean doInBackground(Void avoid[])
{
String s = mUrl;
Drawable drawable = null;
if (s != null)
{
int i = mUrl.length();
drawable = null;
if (i > 0)
{
drawable = fetchImage(mUrl);
}
}
if (drawable != null)
{
ResourceManager.access$1(ResourceManager.this).put(Integer.valueOf(mResourceId), drawable);
return Boolean.valueOf(true);
} else
{
return Boolean.valueOf(false);
}
}
protected volatile transient Object doInBackground(Object aobj[])
{
return doInBackground((Void[])aobj);
}
protected void onPostExecute(Boolean boolean1)
{
super.onPostExecute(boolean1);
Log.i((new StringBuilder("Fetched: ")).append(mUrl).toString());
android.os.Message message = ResourceManager.access$0(ResourceManager.this).obtainMessage(100, mResourceId, 0);
ResourceManager.access$0(ResourceManager.this).sendMessage(message);
}
protected volatile void onPostExecute(Object obj)
{
onPostExecute((Boolean)obj);
}
public (Context context, String s, int i)
{
this$0 = ResourceManager.this;
super();
mContext = context;
mUrl = s;
mResourceId = i;
Log.i((new StringBuilder("Fetching: ")).append(mUrl).toString());
}
}
|
Java
|
UTF-8
| 14,838
| 1.773438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.wisdom.acm.szxm.service.doc.impl;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import com.wisdom.acm.szxm.common.SzxmCommonUtil;
import com.wisdom.acm.szxm.mapper.doc.DocSectionMapper;
import com.wisdom.acm.szxm.mapper.sysscore.SubjectScoreDetailMapper;
import com.wisdom.acm.szxm.po.doc.DocSectionPo;
import com.wisdom.acm.szxm.service.doc.DocSectionService;
import com.wisdom.acm.szxm.service.sysscore.SubjectTemplateService;
import com.wisdom.acm.szxm.vo.sysscore.SubjectScoreItemVo;
import com.wisdom.base.common.enums.StatusEnum;
import com.wisdom.base.common.feign.CommProjectTeamService;
import com.wisdom.base.common.feign.sys.CommSectionService;
import com.wisdom.base.common.service.BaseService;
import com.wisdom.base.common.util.ListUtil;
import com.wisdom.base.common.util.PageUtil;
import com.wisdom.base.common.vo.DocRelationInfoVo;
import com.wisdom.base.common.vo.ProjectTeamVo;
import com.wisdom.base.common.vo.doc.DocProjectReleaseVo;
import com.wisdom.base.common.vo.doc.DocProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Author: szc
* @Date: 2019/7/17 17:12
* @Version 1.0
*/
@Service
public class DocSectionServiceImpl extends BaseService<DocSectionMapper, DocSectionPo> implements DocSectionService {
@Autowired
private CommProjectTeamService commProjectTeamService;
@Autowired
private SzxmCommonUtil szxmCommonUtil;
@Autowired
private CommSectionService commSectionService;
@Autowired
private SubjectTemplateService subjectTemplateService;
@Autowired
private SubjectScoreDetailMapper subjectScoreDetailMapper;
private static final Logger logger = LoggerFactory.getLogger(DocSectionServiceImpl.class);
/**
* 增加文档和标段的关联关系
*
* @param docProjectVo
* @param sectionId
*/
@Override
public DocProjectVo addDocSectionIdRelation(DocProjectVo docProjectVo, Integer sectionId) {
if (!ObjectUtils.isEmpty(sectionId)) {
DocSectionPo docSectionPo = new DocSectionPo();
docSectionPo.setDocId(docProjectVo.getId());
docSectionPo.setSectionId(sectionId);
this.insert(docSectionPo);
}
List<Integer> sectionIds = new ArrayList<>();
sectionIds.add(sectionId);
//获取标段数据集合
List<ProjectTeamVo> projectTeamVos = commProjectTeamService.querySectionList(sectionIds);
if (!ObjectUtils.isEmpty(projectTeamVos)) {
ProjectTeamVo projectTeamVo = projectTeamVos.get(0);
docProjectVo.setSection(projectTeamVo);
}
return docProjectVo;
}
@Override
public List<DocRelationInfoVo> addDocScore(String bizType, List<DocRelationInfoVo> docRelationInfoVos) {
Map<String, Integer> returnMap = subjectTemplateService.isInSubjectTemplate(bizType);
if (0 == returnMap.get("isRated")) {
//查询主观模板表判断是否需要评分 0 不需要
return docRelationInfoVos;
}
List<Integer> fileIds = ListUtil.toValueList(docRelationInfoVos, "fileId", Integer.class);
Map<String, Object> mapWhere = Maps.newHashMap();
mapWhere.put("fileIds", fileIds);
List<SubjectScoreItemVo> subjectScoreItemVos = subjectScoreDetailMapper.selectSubjectScore(mapWhere);
Map<Integer, SubjectScoreItemVo> scoreItemVoMap = ListUtil.listToMap(subjectScoreItemVos, "fileId", Integer.class);
if (ObjectUtils.isEmpty(scoreItemVoMap)) {
return docRelationInfoVos;
}
for (DocRelationInfoVo docRelationInfoVo : docRelationInfoVos) {
SubjectScoreItemVo subjectScoreItemVo = scoreItemVoMap.get(docRelationInfoVo.getFileId());
if (!ObjectUtils.isEmpty(subjectScoreItemVo)) {
docRelationInfoVo.setModuleTitle(subjectScoreItemVo.getModuleTitle());
docRelationInfoVo.setRater(subjectScoreItemVo.getRater());
docRelationInfoVo.setScore(subjectScoreItemVo.getScore());
docRelationInfoVo.setScoreTime(subjectScoreItemVo.getScoreTime());
}
}
return docRelationInfoVos;
}
/**
* 将标段拼接到文档列表
*
* @param projectId
* @param pageSize
* @param pageNum
* @param sectionIds
* @param projectVoPageInfoList
* @return
*/
@Override
public PageInfo<DocProjectVo> filterDocBySectionIds(Integer projectId, Integer pageSize, Integer pageNum, String sectionIds, List<DocProjectVo> projectVoPageInfoList) {
List<DocProjectVo> resultList = new ArrayList<>();
if (!ObjectUtils.isEmpty(projectVoPageInfoList)) {
List<Integer> sectionIdList = new ArrayList<>();
Map<Integer, DocProjectVo> docProjectVoMap = ListUtil.listToMap(projectVoPageInfoList, "id", Integer.class);
if (!sectionIds.contains(",") && Integer.valueOf(sectionIds).intValue() == 0) {
//没有选择标段时,按照当前登陆人的所有标段查询文档
sectionIdList = commSectionService.querySectionIdListList(projectId);
} else {
//查询能看到的所有标段List
List<String> sectionList = szxmCommonUtil.getSectionList(projectId.toString(), sectionIds);
for (String str : sectionList) {
int i = Integer.valueOf(str);
sectionIdList.add(i);
}
}
List<ProjectTeamVo> projectTeamVos = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
//获取标段数据集合
projectTeamVos = commProjectTeamService.querySectionList(sectionIdList);
}
Map<Integer, ProjectTeamVo> projectTeamVoMap = ListUtil.listToMap(projectTeamVos, "id", Integer.class);
Stopwatch started = Stopwatch.createStarted();
//获取指定标段内的文档
List<DocSectionPo> docSectionPoList = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
Example example = new Example(DocSectionPo.class);
Example.Criteria criteria = example.createCriteria();
criteria.andIn("sectionId", sectionIdList);
docSectionPoList = this.selectByExample(example);
}
logger.info("获取指定标段的文档id耗时为:{}秒", started.elapsed(TimeUnit.SECONDS));
if (!ObjectUtils.isEmpty(docSectionPoList)) {
List<Integer> docIds = ListUtil.toValueList(docSectionPoList, "docId", Integer.class);
Map<Integer, DocSectionPo> docSectionPoMap = ListUtil.listToMap(docSectionPoList, "docId", Integer.class);
for (Map.Entry<Integer, DocProjectVo> entry : docProjectVoMap.entrySet()) {
Integer id = entry.getKey();
if (docIds.contains(id)) {
DocProjectVo docProjectVo = entry.getValue();
DocSectionPo docSectionPo = docSectionPoMap.get(id);
Integer sectionId = docSectionPo.getSectionId();
ProjectTeamVo projectTeamVo = projectTeamVoMap.get(sectionId);
docProjectVo.setSection(projectTeamVo);
resultList.add(docProjectVo);
}
}
if (pageSize == -1) {
PageInfo<DocProjectVo> pageInfo = new PageInfo<>();
pageInfo.setSize(resultList.size());
pageInfo.setList(resultList);
return pageInfo;
}
}
}
//PageHelper.startPage(pageNum, pageSize);
//PageInfo<DocProjectVo> pageInfo = new PageInfo<>(resultList);
PageInfo<DocProjectVo> pageInfo = PageUtil.getPageInfo(resultList,pageSize,pageNum);
return pageInfo;
}
@Override
public List<DocProjectReleaseVo> filterDocReleaseBySectionIds(Integer projectId, String sectionIds, List<DocProjectReleaseVo> docProjectReleaseVos) {
List<DocProjectReleaseVo> resultList = new ArrayList<>();
if (!ObjectUtils.isEmpty(docProjectReleaseVos)) {
List<Integer> sectionIdList = new ArrayList<>();
Map<Integer, DocProjectReleaseVo> docProjectVoMap = ListUtil.listToMap(docProjectReleaseVos, "id", Integer.class);
boolean flag = false;
if (!sectionIds.contains(",") && Integer.valueOf(sectionIds).intValue() == 0) {
// flag = true;
sectionIdList = commSectionService.querySectionIdListList(projectId);
} else {
//查询能看到的所有标段List
List<String> sectionList = szxmCommonUtil.getSectionList(projectId.toString(), sectionIds);
for (String str : sectionList) {
int i = Integer.valueOf(str);
sectionIdList.add(i);
}
}
List<ProjectTeamVo> projectTeamVos = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
//获取标段数据集合
projectTeamVos = commProjectTeamService.querySectionList(sectionIdList);
}
// else{
// //获取项目下所有标段集合
// projectTeamVos = commProjectTeamService.querySectioinListByProjectId(projectId);
// }
Map<Integer, ProjectTeamVo> projectTeamVoMap = ListUtil.listToMap(projectTeamVos, "id", Integer.class);
//获取指定标段内的文档
List<DocSectionPo> docSectionPoList = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
Example example = new Example(DocSectionPo.class);
Example.Criteria criteria = example.createCriteria();
if (!ObjectUtils.isEmpty(sectionIdList)) {
criteria.andIn("sectionId", sectionIdList);
}
docSectionPoList = this.selectByExample(example);
}
if (!ObjectUtils.isEmpty(docSectionPoList)) {
List<Integer> docIds = ListUtil.toValueList(docSectionPoList, "docId", Integer.class);
Map<Integer, DocSectionPo> docSectionPoMap = ListUtil.listToMap(docSectionPoList, "docId", Integer.class);
for (Map.Entry<Integer, DocProjectReleaseVo> entry : docProjectVoMap.entrySet()) {
Integer id = entry.getKey();
if (docIds.contains(id)) {
DocProjectReleaseVo docProjectVo = entry.getValue();
DocSectionPo docSectionPo = docSectionPoMap.get(id);
Integer sectionId = docSectionPo.getSectionId();
ProjectTeamVo projectTeamVo = projectTeamVoMap.get(sectionId);
docProjectVo.setSection(projectTeamVo);
resultList.add(docProjectVo);
}
}
}
}
return resultList;
}
/**
* 将标段拼接到文档列表
*
* @param projectId
* @param sectionIds
* @param docProjectVos
* @return
*/
@Override
public List<DocProjectVo> filterDocProjectVosBySectionIds(Integer projectId, String sectionIds, List<DocProjectVo> docProjectVos) {
List<DocProjectVo> resultList = new ArrayList<>();
if (!ObjectUtils.isEmpty(docProjectVos)) {
List<Integer> sectionIdList = new ArrayList<>();
Map<Integer, DocProjectVo> docProjectVoMap = ListUtil.listToMap(docProjectVos, "id", Integer.class);
boolean flag = false;
if (!sectionIds.contains(",") && Integer.valueOf(sectionIds).intValue() == 0) {
// flag = true;
sectionIdList = commSectionService.querySectionIdListList(projectId);
} else {
//查询能看到的所有标段List
List<String> sectionList = szxmCommonUtil.getSectionList(projectId.toString(), sectionIds);
for (String str : sectionList) {
int i = Integer.valueOf(str);
sectionIdList.add(i);
}
}
List<ProjectTeamVo> projectTeamVos = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
//获取标段数据集合
projectTeamVos = commProjectTeamService.querySectionList(sectionIdList);
}
Map<Integer, ProjectTeamVo> projectTeamVoMap = ListUtil.listToMap(projectTeamVos, "id", Integer.class);
//获取指定标段内的文档
List<DocSectionPo> docSectionPoList = new ArrayList<>();
if (!ObjectUtils.isEmpty(sectionIdList)) {
Example example = new Example(DocSectionPo.class);
Example.Criteria criteria = example.createCriteria();
if (!ObjectUtils.isEmpty(sectionIdList)) {
criteria.andIn("sectionId", sectionIdList);
}
docSectionPoList = this.selectByExample(example);
}
if (!ObjectUtils.isEmpty(docSectionPoList)) {
List<Integer> docIds = ListUtil.toValueList(docSectionPoList, "docId", Integer.class);
Map<Integer, DocSectionPo> docSectionPoMap = ListUtil.listToMap(docSectionPoList, "docId", Integer.class);
for (Map.Entry<Integer, DocProjectVo> entry : docProjectVoMap.entrySet()) {
Integer id = entry.getKey();
if (docIds.contains(id)) {
DocProjectVo docProjectVo = entry.getValue();
DocSectionPo docSectionPo = docSectionPoMap.get(id);
Integer sectionId = docSectionPo.getSectionId();
ProjectTeamVo projectTeamVo = projectTeamVoMap.get(sectionId);
docProjectVo.setSection(projectTeamVo);
if (docProjectVo.getStatus().getId().equals(StatusEnum.RELEASE.getCode())) {
resultList.add(docProjectVo);
}
}
}
}
}
return resultList;
}
}
|
Markdown
|
UTF-8
| 834
| 2.796875
| 3
|
[] |
no_license
|
# 第三次实验
## 1.实验目标
掌握在Android应用中使用图片等资源的方法。
## 2.实验步骤
阅读实验要求:https://github.com/hzuapps/android-labs-2018/labels/Lab
## 3.实验要求
1.在界面上显示至少一张图片(按照自己的题目添加);
2.提交res/drawable及图片使用的代码;
3.提交res/values, res/layout等其他代码;
4.将应用运行结果截图,放到实验报告中;
5.点击图片(或按钮)时,打开另一个Activity。
6.在电脑上Android Studio编写代码
// 代码要可以运行!
## 4.实验结果

## 5.实验体会
通过老师给的提示,在界面显示出图片,可以说做得很粗糙,不过新手还是有很大的进步空间。
|
Python
|
UTF-8
| 403
| 2.984375
| 3
|
[] |
no_license
|
import time
import sys
if __name__ == "__main__" :
t1 = time.clock()
with open(sys.argv[1], 'r') as f:
lines = [[int(d) for d in e] for e in [a.split(" ") for a in f][:-1]]
for i in range(len(lines)-1, 0, -1):
lines[i-1] = [lines[i-1][j]+max(lines[i][j], lines[i][j+1]) for j in range(0, len(lines[i-1]))]
print(lines[0][0])
print(time.clock() - t1, "seconds")
|
Java
|
UTF-8
| 1,025
| 2.625
| 3
|
[] |
no_license
|
package contacts.parser;
import contacts.Contact;
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Parser {
public ArrayList<Contact> getContacts(File file) throws JAXBException {
Wrapper wrapper = new Wrapper();
JAXBContext context = JAXBContext.newInstance(wrapper.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
wrapper = (Wrapper) unmarshaller.unmarshal(file);
return wrapper.getContacts();
}
public void saveContacts(File file, ArrayList<Contact> con) throws JAXBException {
Wrapper wrapper = new Wrapper();
wrapper.setContacts(con);
JAXBContext context = JAXBContext.newInstance(wrapper.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(wrapper, file);
}
}
|
C#
|
UTF-8
| 1,161
| 2.75
| 3
|
[] |
no_license
|
using UnityEngine;
namespace Assets.Data
{
public class CameraController : MonoBehaviour
{
float mainSpeed = 100.0f; //regular speed
private float totalRun = 1.0f;
void Update()
{
//Keyboard commands
Vector3 p = GetBaseInput();
totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
p = p * mainSpeed;
p = p * Time.deltaTime;
transform.Translate(p);
}
private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
Vector3 pVelocity = new Vector3();
if (Input.GetKey(KeyCode.W))
{
pVelocity += new Vector3(0, 1, 0);
}
if (Input.GetKey(KeyCode.S))
{
pVelocity += new Vector3(0, -1, 0);
}
if (Input.GetKey(KeyCode.A))
{
pVelocity += new Vector3(-1, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
pVelocity += new Vector3(1, 0, 0);
}
return pVelocity;
}
}
}
|
C++
|
UTF-8
| 7,516
| 2.9375
| 3
|
[] |
no_license
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
using Block=vector<vector<int>>;
using Board=vector<vector<int>>;
struct Point{
int y,x;
};
const int dx[]={1,0,-1,0},dy[]={0,1,0,-1};//縦横のマス
const int ex[]={1,1,-1,-1},ey[]={-1,1,1,-1};//斜めのマス
//点数計算の仕組みを考える
//ブロックリストを作る
const vector<Block> red_block_list={
{{1}}, {{1,1}}, {{1,1,1}}, {{1,1}, {0,1}}, //1,2,3
{{1,1,1,1}}, {{1,1,1},{0,0,1}}, {{1,1,1},{0,1,0}}, {{1,1},{1,1}}, {{1,1,0},{0,1,1}}, //4
{{1,1,1,1,1}}, {{1,1,1,1},{0,0,0,0,1}}, {{1,1,1,0},{0,0,1,1}}, {{1,1,1},{0,1,1}}, //5
{{1,1,1},{1,0,1}}, {{1,1,1,1},{0,0,1,0}}, {{1,1,1},{0,1,0},{0,1,0}}, //5
{{1,0,0},{1,0,0},{1,1,1}},{{1,1,0},{0,1,1},{0,0,1}}, {{1,0,0},{1,1,1},{0,0,1}}, //5
{{1,0,0},{1,1,1},{0,1,0}}, {{0,1,0},{1,1,1},{0,1,0}} //5
};
const vector<Block> blue_block_list={
{{2}}, {{2,2}}, {{2,2,2}}, {{2,2}, {0,2}}, //1,2,3
{{2,2,2,2}}, {{2,2,2},{0,0,2}}, {{2,2,2},{0,2,0}}, {{2,2},{2,2}}, {{2,2,0},{0,2,2}}, //4
{{2,2,2,2,2}}, {{2,2,2,2},{0,0,0,0,2}}, {{2,2,2,0},{0,0,2,2}}, {{2,2,2},{0,2,2}}, //5
{{2,2,2},{2,0,2}}, {{2,2,2,2},{0,0,2,0}}, {{2,2,2},{0,2,0},{0,2,0}}, //5
{{2,0,0},{2,0,0},{2,2,2}},{{2,2,0},{0,2,2},{0,0,2}}, {{2,0,0},{2,2,2},{0,0,2}}, //5
{{2,0,0},{2,2,2},{0,2,0}}, {{0,2,0},{2,2,2},{0,2,0}} //5
};
//一つのブロックに対し上下反転などの8パターンを計算する
void createEightPatterns(Block block, vector<Block> &created);
//第二引数のblockを置ける最適な場所を計算, 第三引数はblockの色
Point findPlaceToPut(Board board, Block block,int color,Block &ans);
void printBlock(Block b);
int check(const Board &board,const Point point, const Block b,int color, Point &ans);
int main(){
Board board(20,vector<int>(20));
for(int i=0;i<20;i++)for(int j=0;j<20;j++)cin>>board[i][j];
//Block a={{0,1,0,0},{1,1,1,1}};
vector<Block> res(8);//必ず8個と指定
Block ans;//どのブロックを使うか(答え)
Point ans_p;//どこに置くか(ブロックの右上の座標)(答え)
for(auto a:blue_block_list)ans_p=findPlaceToPut(board,a,2, ans);
cout<<ans_p.y<<" "<<ans_p.x<<endl;
printBlock(ans);
}
void createEightPatterns(Block block, vector<Block> &created){
int height=block.size();
int width=block[0].size();
//もとのやつ
created[0]=block;
//上下反転
for(int i=height-1;i>=0;i--){
created[1].emplace_back(block[i]);
}
//左右反転
created[2]=block;
for(int i=0;i<height;i++){
std::reverse(created[2][i].begin(),created[2][i].end());
}
//上下左右反転
created[3]=created[1];
for(int i=0;i<height;i++)std::reverse(created[3][i].begin(),created[3][i].end());
//90度回転->左右反転
Block n(width,vector<int>(height));
for(int i=0;i<width;i++)for(int j=0;j<height;j++){
n[i][j]=block[j][i];
}
created[4]=n;
//90度回転
created[5]=n;
for(int i=0;i<width;i++)std::reverse(created[5][i].begin(),created[5][i].end());
//90度回転->上下左右回転
for(int i=width-1;i>=0;i--){
created[6].emplace_back(n[i]);
}
//90度回転->上下回転
for(int i=width-1;i>=0;i--){
created[7].push_back(created[5][i]);
}
}
void printBlock(Block b){
for(auto h:b){
for(auto w:h)cout<<w<<" ";
cout<<endl;
}
}
int mx=0;
Point ans_p;//置かれるブロックの右端の座標
Block ans_block;//ブロックの形(向き)
//ans_Bは当てはめるときのブロックの形
Point findPlaceToPut(Board board, Block block, int color,Block &ans_B){
vector<Point>temp_list;//おける場所のリスト(仮)
for(int yi=0;yi<20;yi++){
for(int xj=0;xj<20;xj++){
if(board[yi][xj]!=0)continue;
bool able_put=true;
//縦横のマスに自分と同じ色のブロックが置かれていないか
for(int k=0;k<4;k++){
int nx=xj+dx[k],ny=yi+dy[k];
if(nx<0 || ny<0 || nx>=20 || ny>=20)continue;
if(board[ny][nx]==color){
able_put=false;
break;
}
}
if(!able_put)continue;
able_put=false;
//斜めのマスに自分と同じ色のブロックが置かれているかどうか
for(int k=0;k<4;k++){
int nx=xj+ex[k],ny=yi+dy[k];
if(nx<0 || ny<0 || nx>=20 || ny>=20)continue;
if(board[ny][nx]==color)able_put=true;
}
if(able_put){
Point t;
t.x=xj,t.y=yi;
temp_list.emplace_back(t);
}
}
}
vector<Block>res(8);
createEightPatterns(block,res);
Point temp;
for(auto point:temp_list){
for(auto b:res){
int score=check(board,point,b,color,temp);
cout<<"2 score:mx"<<score<<" "<<mx<<endl;
if(score>=mx){
ans_p=temp;
ans_block=b;
mx=score;
cout<<"mx="<<mx<<endl;
}
cout<<"3 score:mx"<<score<<" "<<mx<<endl;
}
}
ans_B=ans_block;
return ans_p;
}
int check(const Board &board, const Point point, const Block b, int color,Point &ans){
int height=b.size(),width=b[0].size();
int res=0;//相手のブロックと接する回数を最大化
//(yi,xj)を(point.y,point.x)に合わせる
for(int yi=0;yi<height;yi++)for(int xj=0;xj<width;xj++){
if(b[yi][xj]==0)continue;
//(y,x)はboardでの、置きたいブロックの右上の座標
int y=point.y-yi,x=point.x-xj;
if(y<0 || x<0)continue;
int cnt=0;//相手のブロックと接する回数
bool able=true;
for(int i=0;i<height;i++)for(int j=0;j<width;j++){
if(b[i][j]==0){
//block_listの17, 18について考える必要がある(未)
if((0<=y+i && y+i<20 && 0<=x+j && x+j<20) && board[y+i][x+j]==color)able=false;
else if((0<=y+i && y+i<20 && 0<=x+j && x+j<20) && board[y+i][x+j]!=0)cnt++;
continue;
}
if(y+i>=20 || x+j>=20)able=false;
if(board[y+i][x+j]!=0)able=false;
if(i==0){
if(y!=0 && board[y+i-1][x+j]==color)able=false;//上のますが同じ色
else if(y!=0 && board[y+i-1][x+j]!=0)cnt++;
}
if(i==height-1){
if(y!=19 && board[y+i+1][x+j]==color)able=false;//下のマスが同じ色
else if(y!=19 && board[y+i+1][x+j]!=0)cnt++;
}
if(j==0){
if(x!=0 && board[y+i][x+j-1]==color)able=false;//左のマスが同じ色
else if(x!=0 && board[y+i][x+j-1]!=0)cnt++;
}
if(j==width-1){
if(x!=19 && board[y+i][x+j+1]==color)able=false;//右のマスが同じ色
else if(x!=19 && board[y+i][x+j-1]!=0)cnt++;
}
}
if(able){
printf("point:(%d %d) score:%d\n",y,x,cnt);
cout<<"Block"<<endl;
printBlock(b);
cout<<endl;
if(cnt>=res){
Point t;
t.x=x,t.y=y;
ans=t;
res=cnt;
}
}
}
return res;
}
|
Java
|
UTF-8
| 11,733
| 2.0625
| 2
|
[] |
no_license
|
package tk.zielony.materialrecents;
import android.content.*;
import android.content.res.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.util.*;
import android.view.*;
import android.view.animation.*;
import android.widget.*;
import com.meui.SwipeRecentApps.*;
import com.noas.animation.*;
import com.noas.view.*;
/**
* Created by Marcin on 2015-04-13.
* Bugs fix come from https://github.com/m0r0/MaterialRecents
* Modify by ME Failed Coder
*/
public class RecentsList extends FrameLayout implements GestureDetector.OnGestureListener {
Scroller scroller;
RecentsAdapter adapter;
GestureDetector gestureDetector;
int scroll = 0;
OnRecentEventListener mListener;
Rect childTouchRect[];
boolean isFirst = true;
private boolean verticalScrolling = false;
private boolean horizontalFlinging = false;
private int scrolledChild = -1;
private VelocityTracker tracker;
public interface OnRecentEventListener {
void onConfigurationChanged();
void onItemClick(int i);
void onItemLongClick(int i);
void onItemSwiped(int i);
}
public RecentsList(Context context) {
super(context);
initRecentsList();
}
public RecentsList(Context context, AttributeSet attrs) {
super(context, attrs);
initRecentsList();
}
public RecentsList(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initRecentsList();
}
private void initRecentsList() {
scroller = new Scroller(getContext());
setClipToPadding(false);
gestureDetector = new GestureDetector(getContext(), this);
}
public void setOnRecentEventListener(OnRecentEventListener listener) {
mListener = listener;
}
public RecentsAdapter getAdapter() {
return adapter;
}
public void setAdapter(RecentsAdapter adapter) {
this.adapter = adapter;
initChildren();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (adapter == null)
return;
if (childTouchRect == null) childTouchRect = new Rect[getChildCount()];
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).layout(0, 0, getWidth() - getPaddingLeft() - getPaddingRight(), getWidth() - getPaddingLeft() - getPaddingRight());
if (childTouchRect[i] == null) childTouchRect[i] = new Rect();
}
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mListener != null) {
mListener.onConfigurationChanged();
}
}
private void initChildren() {
removeAllViews();
for (int i = 0; i < adapter.getCount(); i++) {
final View card = View.inflate(getContext(), R.layout.material_recents_card, null);
TextView title = (TextView) card.findViewById(R.id.materialrecents_recentTitle);
title.setText(adapter.getTitle(i));
android.widget.ImageView icon = (android.widget.ImageView) card.findViewById(R.id.materialrecents_recentIcon);
Drawable drawable = adapter.getIcon(i);
if (drawable == null) {
icon.setVisibility(View.GONE);
} else {
icon.setImageDrawable(drawable);
}
View header = card.findViewById(R.id.materialrecents_recentHeader);
header.setBackgroundColor(adapter.getHeaderColor(i));
card.findViewById(R.id.materialrecents_recentContent).setBackgroundColor(adapter.getViewColor(i));
addView(card, i, generateDefaultLayoutParams());
/*final int finalI = i;
@Override
public void onClick(View view) {
if (onItemClickListener != null)
onItemClickListener.onItemClick(card, finalI);
}
});*/
}
}
private void layoutChildren() {
int width = getWidth() - getPaddingLeft() - getPaddingRight();
int height = getHeight() - getPaddingTop() - getPaddingBottom();
float topSpace = Math.abs(height - width) ;
for (int i = 0; i < getChildCount(); i++) {
final View currentChild = getChildAt(i);
int y = (int) (topSpace * Math.pow(2, (i * (width) - scroll) / (float) (width)));
float scale = (float) (-Math.pow(2, -y / topSpace / 10.0f) + 19.0f / 10);
childTouchRect[i].set(getPaddingLeft(), y + getPaddingTop(), (int) (scale * (getPaddingLeft() + getWidth() - getPaddingLeft() - getPaddingRight())), (int) (scale * (y + getPaddingTop() + width)));
currentChild.layout(0, 0, width, width); //getWidth() - getPaddingLeft() - getPaddingRight());
ViewHelper.setTranslationX(currentChild, getPaddingLeft());
ViewHelper.setTranslationY(currentChild, y + getPaddingTop());
ViewHelper.setScaleX(currentChild, scale);
ViewHelper.setScaleY(currentChild, scale);
}
}
private int getMaxScroll() {
return (getChildCount() - 1) * (getWidth() - getPaddingLeft() - getPaddingRight());
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (isFirst) {
scroll = getMaxScroll();
layoutChildren();
}
super.dispatchDraw(canvas);
isFirst = false;
if (verticalScrolling)
layoutChildren();
}
/*
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
for (int i = getChildCount() - 1;i >= 0; i--) { // TEST!
MotionEvent e = MotionEvent.obtain(event);
event.setAction(MotionEvent.ACTION_CANCEL);
e.offsetLocation(-childTouchRect[i].left, -childTouchRect[i].top);
getChildAt(i).dispatchTouchEvent(e);
}
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
forceFinished();
}
for (int i = getChildCount() - 1;i >= 0; i--) {
if (childTouchRect[i].contains((int) event.getX(), (int) event.getY())) {
MotionEvent e = MotionEvent.obtain(event);
e.offsetLocation(-childTouchRect[i].left, -childTouchRect[i].top);
if (getChildAt(i).dispatchTouchEvent(e))
break;
}
}
return true;
}*/
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return getAdapter() != null & gestureDetector.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (!verticalScrolling)
tracker.addMovement(event);
break;
case MotionEvent.ACTION_UP:
if (!verticalScrolling && scrolledChild != -1) {
tracker.computeCurrentVelocity(1000, ViewConfiguration.get(getContext()).getScaledMaximumFlingVelocity());
if (Math.abs(tracker.getXVelocity()) < ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity()) {
ViewHelper.setTranslationX(getChildAt(scrolledChild), getPaddingLeft());
layoutChildren();
}
}
tracker.clear();
tracker.recycle();
}
return event.getAction() == MotionEvent.ACTION_DOWN || getAdapter() != null & gestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent motionEvent) {
forceFinished();
verticalScrolling = false;
tracker = VelocityTracker.obtain();
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
if (mListener == null) return true;
for (int i = getChildCount() - 1;i >= 0; i--) {
if (childTouchRect[i].contains((int) event.getX(), (int) event.getY())) {
mListener.onItemClick(i);
break;
}
}
return true;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float v, float v2) {
int deltaX = (int) (motionEvent2.getX() - motionEvent.getX());
if (!verticalScrolling && Math.abs(deltaX) > Math.abs(motionEvent.getY() - motionEvent2.getY())) {
if (horizontalFlinging) {
scrolledChild = -1;
return false;
}
for (int i = getChildCount() - 1; i >= 0; i--) {
if (childTouchRect[i].contains((int) motionEvent.getX(), (int) motionEvent.getY())) {
scrolledChild = i;
ViewHelper.setTranslationX(getChildAt(i), deltaX);
return true;
}
}
return false;
}
verticalScrolling = true;
scroll = (int) Math.max(0, Math.min(scroll + v2, getMaxScroll()));
postInvalidate();
return false;
}
@Override
public void onLongPress(MotionEvent event) {
if (mListener == null)
return;
for (int i = getChildCount() - 1;i >= 0; i--) {
if (childTouchRect[i].contains((int) event.getX(), (int) event.getY())) {
mListener.onItemLongClick(i);
break;
}
}
}
void startScrolling(float initialVelocity) {
scroller.fling(0, scroll, 0, (int) initialVelocity, 0,
0, Integer.MIN_VALUE, Integer.MAX_VALUE);
postInvalidate();
}
@Override
public void computeScroll() {
if (scroller.isFinished())
return;
if (scroller.computeScrollOffset()) {
final int newScroll = Math.max(0, Math.min(scroller.getCurrY(), getMaxScroll()));
if (newScroll != scroll) {
scroll = newScroll;
postInvalidate();
}
}
}
boolean isFlinging() {
return !scroller.isFinished();
}
void forceFinished() {
if (!scroller.isFinished()) {
scroller.forceFinished(true);
}
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float velocityX, float velocityY) {
forceFinished();
int deltaX = (int) (motionEvent2.getX() - motionEvent.getX());
if (verticalScrolling || Math.abs(deltaX) <= Math.abs(motionEvent.getY() - motionEvent2.getY())) {
verticalScrolling = true;
startScrolling(-velocityY * 2);
return true;
}
if (horizontalFlinging) return true;
for (int i = getChildCount() - 1;i >= 0; i--) {
if (childTouchRect[i].contains((int) motionEvent.getX(), (int) motionEvent.getY())) {
horizontalFlinging = true;
final int finalI = i;
long duration = 250000 / (long) Math.abs(velocityX); // You can adjust the value by yourself.
if (deltaX * velocityX <= 0) {
ViewPropertyAnimator.animate(getChildAt(finalI)).setDuration(duration).translationX(getPaddingLeft()).start();
horizontalFlinging = false;
break;
}
ViewPropertyAnimator.animate(getChildAt(i)).setDuration(duration).setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
ViewPropertyAnimator.animate(getChildAt(finalI)).setDuration(100).translationX(getPaddingLeft()).setListener(new Animator.AnimatorListener(){
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
horizontalFlinging = false;
ViewPropertyAnimator.animate(getChildAt(finalI)).setListener(null);
if (mListener != null) mListener.onItemSwiped(finalI);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
}).translationX(deltaX > 0 ? getWidth() : -getWidth()).start();
break;
}
}
return true;
}
}
|
Java
|
UTF-8
| 701
| 1.867188
| 2
|
[] |
no_license
|
package com.songm.dormrepair.fragment.myorder;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.songm.dormrepair.fragment.myorder.utils.ShowOrderListUtils;
/**
* Created by neokree on 16/12/14.
* 审核通过
*/
public class ExaminePassFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return new ShowOrderListUtils(inflater, 2).view();
}
}
|
Java
|
UTF-8
| 1,751
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package jpuppeteer.cdp.client.entity.indexeddb;
/**
* Key range.
* experimental
*/
public class KeyRange {
/**
* Lower bound.
*/
private jpuppeteer.cdp.client.entity.indexeddb.Key lower;
/**
* Upper bound.
*/
private jpuppeteer.cdp.client.entity.indexeddb.Key upper;
/**
* If true lower bound is open.
*/
private Boolean lowerOpen;
/**
* If true upper bound is open.
*/
private Boolean upperOpen;
public void setLower (jpuppeteer.cdp.client.entity.indexeddb.Key lower) {
this.lower = lower;
}
public jpuppeteer.cdp.client.entity.indexeddb.Key getLower() {
return this.lower;
}
public void setUpper (jpuppeteer.cdp.client.entity.indexeddb.Key upper) {
this.upper = upper;
}
public jpuppeteer.cdp.client.entity.indexeddb.Key getUpper() {
return this.upper;
}
public void setLowerOpen (Boolean lowerOpen) {
this.lowerOpen = lowerOpen;
}
public Boolean getLowerOpen() {
return this.lowerOpen;
}
public void setUpperOpen (Boolean upperOpen) {
this.upperOpen = upperOpen;
}
public Boolean getUpperOpen() {
return this.upperOpen;
}
public KeyRange(jpuppeteer.cdp.client.entity.indexeddb.Key lower, jpuppeteer.cdp.client.entity.indexeddb.Key upper, Boolean lowerOpen, Boolean upperOpen) {
this.lower = lower;
this.upper = upper;
this.lowerOpen = lowerOpen;
this.upperOpen = upperOpen;
}
public KeyRange(Boolean lowerOpen, Boolean upperOpen) {
this.lower = null;
this.upper = null;
this.lowerOpen = lowerOpen;
this.upperOpen = upperOpen;
}
public KeyRange() {
}
}
|
Java
|
UTF-8
| 1,713
| 2.546875
| 3
|
[] |
no_license
|
/**
*
*/
package it.ogeo.rest;
import it.ogeo.model.Person;
import it.ogeo.persistence.FakeDb;
import java.util.Collection;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* @author micheleorsi
*
*/
@Path("/hosting/people")
@Produces({ MediaType.APPLICATION_JSON+"; charset=utf-8" })
public class HostingResource {
private Logger log = Logger.getLogger(HostingResource.class.getName());
@GET
public Collection<Person> getPeople() {
Collection<Person> listToReturn = FakeDb.peopleNeedHostingTable.values();
return listToReturn;
}
@POST
@Consumes({ "application/x-www-form-urlencoded; charset=utf-8" })
public String askPersonHost(@FormParam("cellNumber") String cellNumber,
@FormParam("email") String email,
@FormParam("latitude") Double latitude,
@FormParam("longitude") Double longitude,
@FormParam("name") String name) {
log.info("ask person host");
Person person = new Person(0, latitude, longitude, name, email, cellNumber);
person.setId(FakeDb.personId);
FakeDb.peopleTable.put(FakeDb.personId, person);
FakeDb.peopleNeedHostingTable.put(FakeDb.personId, person);
FakeDb.personId++;
return "{\"msg\":\"ok, now you are in queue to get a bed "+name+"\"}";
}
@POST
@Path("/{personId}")
public String personHosted(@PathParam("personId") int personId) {
log.info("removed person hosted");
FakeDb.peopleNeedHostingTable.remove(personId);
return "{\"msg\":\"the person "+personId+" has now a host\"}";
}
}
|
Swift
|
UTF-8
| 690
| 2.796875
| 3
|
[] |
no_license
|
//
// DataCache.swift
// SwiftFlickrSearch
//
// Created by suraj poudel on 24/8/19.
// Copyright © 2019 suraj poudel. All rights reserved.
//
import Foundation
import UIKit
class DataCache:NSObject{
static let shared = DataCache()
private(set) var cache:NSCache<AnyObject,AnyObject> = NSCache()
func getImageFromCache(key:String)->UIImage?{
if(self.cache.object(forKey: key as AnyObject) != nil){
return self.cache.object(forKey: key as AnyObject) as? UIImage
}else{
return nil
}
}
func saveImageToCache(key:String,image:UIImage){
self.cache.setObject(image, forKey: key as AnyObject)
}
}
|
C#
|
UTF-8
| 1,048
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
using Akrual.DDD.Utils.Application.Messaging;
namespace Akrual.DDD.Utils.Application.UseCaseFunctions
{
/// <summary>
/// Every application class should basically receive an input data from the presentation layer and return
/// an output to the presentation layer. So it should implement this interface
/// </summary>
/// <typeparam name="TInputModel">InputModel</typeparam>
/// <typeparam name="TOutputModel">OutputModel</typeparam>
public interface IUseCaseFunction<in TInputModel, out TOutputModel>
where TInputModel : IInputModel
where TOutputModel : IOutputModel
{
/// <summary>
/// Every application class should basically receive an input data from the presentation layer and return
/// an output to the presentation layer.
/// </summary>
/// <param name="input">Input model from the presentation layer</param>
/// <returns>Output model to the presentation layer</returns>
TOutputModel Execute(TInputModel input);
}
}
|
C#
|
UTF-8
| 738
| 2.65625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RSS_DB
{
public class Element
{
public string ProductName { get; set; }
public byte Status { get; set; }
public double Cost { get; set; }
public int Quantity { get; set; }
public double Result { get; set; }
public DateTime StatusDate { get; set; }
public Element(string name, byte status, double cost, int quan, double res, DateTime datest)
{
ProductName = name;
Status = status;
Cost = cost;
Quantity = quan;
Result = res;
StatusDate = datest;
}
}
}
|
C++
|
UTF-8
| 1,083
| 3.125
| 3
|
[] |
no_license
|
#include"Solutions.h"
// need to find the dimension of the matrix first
// use four paramters to 'PIN' the matrix
// only two caes there: left null or left with just one element
vector<vector<int>> p59::generateMatrix(int n) {
vector <vector<int>> ans(n, vector<int>(n, 0));
int top = 0, left = 0, right = n - 1, bottom = n - 1;
int num = 0;
while (top < bottom && left < right) { // left inclusive, right exclusive
for (int i = left; i < right; i++) ans[top][i] = ++num;
for (int i = top; i < bottom; i++) ans[i][right] = ++num;
for (int i = right; i > left; i--) ans[bottom][i] = ++num;
for (int i = bottom; i > top; i--) ans[i][left] = ++num;
top++;
bottom--;
left++;
right--;
}
if (n % 2 == 1) {
ans[n / 2][n / 2] = ++num;
}
return ans;
}
void p59::test() {
vector<vector<int>> ans = generateMatrix(3);
//vector<vector<int>> matrix2;
for (vector<vector<int>>::iterator i = ans.begin(); i != ans.end(); i++) {
cout << " [ ";
for (int j = 0; j < (*i).size(); j++) {
cout << (*i)[j] << " ";
}
cout << " ] " << endl;
}
cout << endl;
}
|
Markdown
|
UTF-8
| 717
| 2.953125
| 3
|
[] |
no_license
|
# eBtn
An Arduino library to create buttons and handle events using callbacks.
The library handle the following events:
- press
- release
- longPress
Please, see https://github.com/t3db0t/Button
for a better solution
Patrick
**Usage**
eBtn btn = eBtn(btnPin);
btn.on("press",pressFunc);
btn.on("release",releaseFunc);
btn.on("long",longPressFunc);
...
void pressFunc(){
//do something here
}
void releaseFunc(){
//do something else here
}
void longPressFunc(){
//do something usefull here
}
// Note that not all input Pins can handle interrupt, check model.
// Pins 2 and 3 are availables for that on Arduino Nano and Pro Micro.
|
JavaScript
|
UTF-8
| 804
| 3.25
| 3
|
[] |
no_license
|
$(document).ready(function() {
var checkboxes = [];
$('ul.checkboxes li').each(function(index) {
if ($(this).attr('role') == 'checkbox') {
checkboxes[index] = new checkbox($(this));
}
});
}); // end ready()
// Function toggleState() is a member function to toggle a checkbox state. This function sets the
// aria-checked property and changes the box image to display the new box state.
//
// @return N/A
//
checkbox.prototype.toggleState = function() {
var $img = this.$id.find('img');
if (this.$id.attr('aria-checked') == 'true') {
this.$id.attr('aria-checked', 'false');
$img.attr('src', '../checkbox-unchecked-black.png');
}
else {
this.$id.attr('aria-checked', 'true');
$img.attr('src', '../checkbox-checked-black.png');
}
} // end toggleState()
|
C++
|
UTF-8
| 1,189
| 3.921875
| 4
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int num1,num2,num3,n,fact=1,c;
printf("-------Menu-------");
printf("\n 1.Factorial of a number");
printf("\n 2.Prime or not");
printf("\n 3.Even or odd");
printf("\n 4.Exit");
printf("Enterr the choice :");
scanf("%d",&n);
switch(n)
{
case 1:
printf("Enter the number :");
scanf("%d",&num1);
for(int i=1;i<=num1;i++)
fact=fact*i;
printf("Factorial of %d is %d",num1,fact);
break;
case 2:
printf("Enter the number :");
scanf("%d",&num2);
for (c = 2;c<= num2-1;c++)
{
if ( num2%c == 0 )
{
printf("%d is not prime.\n",num2);
break;
}
}
if ( c == num2)
printf("%d is prime.\n", num2);
break;
case 3:
printf("Enterr the number :");
scanf("%d",&num3);
if((num3%2)==0)
{
printf("Number is even");
}
else
{
printf("Number is odd");
}
case 4:
printf("Exit");
default:
printf("Entered choice is invalid please choose from the menu ");
}
}
|
Swift
|
UTF-8
| 1,569
| 3.015625
| 3
|
[] |
no_license
|
//
// RayTests.swift
// ray tracer unit tests
//
// Created by Christopher Paterson on 03/09/2018.
// Copyright © 2018 Christopher Paterson. All rights reserved.
//
import XCTest
class RayTests: XCTestCase {
func testCreateAndQueryRay() {
let origin = Point(x: 1, y: 2, z: 3)
let direction = Vector(x: 4, y: 5, z: 6)
let r = Ray(origin: origin, direction: direction)
XCTAssert(r.origin == origin)
XCTAssert(r.direction == direction)
}
func testComputePointFromDistance() {
let r = Ray(origin: Point(x: 2, y: 3, z: 4), direction: Vector(x: 1, y: 0, z: 0))
XCTAssert(r.position(atTime: 0) == Point(x: 2, y: 3, z: 4))
XCTAssert(r.position(atTime: 1) == Point(x: 3, y: 3, z: 4))
XCTAssert(r.position(atTime: -1) == Point(x: 1, y: 3, z: 4))
XCTAssert(r.position(atTime: 2.5) == Point(x: 4.5, y: 3, z: 4))
}
func testTranslatingARay() {
let r = Ray(origin: Point(x: 1, y: 2, z: 3), direction: Vector(x: 0, y: 1, z: 0))
let m = Transform.translate(x: 3, y: 4, z: 5)
let r2 = r * m
XCTAssert(r2.origin == Point(x: 4, y: 6, z: 8))
XCTAssert(r2.direction == Vector(x: 0, y: 1, z: 0))
}
func testScalingARay() {
let r = Ray(origin: Point(x: 1, y: 2, z: 3), direction: Vector(x: 0, y: 1, z: 0))
let m = Transform.scale(x: 2, y: 3, z: 4)
let r2 = r * m
XCTAssert(r2.origin == Point(x: 2, y: 6, z: 12))
XCTAssert(r2.direction == Vector(x: 0, y: 3, z: 0))
}
}
|
C#
|
UTF-8
| 1,568
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2014-2020 DataStax Inc.
// Copyright (c) 2020, Rafael Almeida (ralmsdevelper)
// Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information.
using System;
using System.Collections.Generic;
namespace Scylla.Net.Collections
{
internal interface IThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
TValue GetOrAdd(TKey key, TValue value);
bool TryRemove(TKey key, out TValue value);
TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory);
TValue AddOrUpdate(
TKey key,
Func<TKey, TValue> addValueFactory,
Func<TKey, TValue, TValue> updateValueFactory);
/// <summary>
/// Calls <paramref name="updateValueFactory"/> and updates an existing key
/// only if <paramref name="compareFunc"/> returns true.
/// </summary>
/// <param name="key">Key used to fetch/update values in the dictionary.</param>
/// <param name="compareFunc">Parameters are the key and the existing value. Returned bool determines
/// whether <paramref name="updateValueFactory"/> is called and the map is updated.</param>
/// <param name="updateValueFactory">Factory that will be invoked to modify the existing value.
/// The existing value will be replaced with the output from this factory.</param>
TValue CompareAndUpdate(
TKey key,
Func<TKey, TValue, bool> compareFunc,
Func<TKey, TValue, TValue> updateValueFactory);
}
}
|
C++
|
UTF-8
| 14,270
| 2.703125
| 3
|
[] |
no_license
|
#include "api.h"
#include "classes.h"
#include <iostream>
#include <sys/stat.h>
#include <string>
#include <sqlite3.h>
db_communicator::db_communicator(unsigned int players){
//lets name the dbs -> poker_db_X.db
struct stat buffer;
db_name = "/home/fivosts/poker_db_" + std::to_string(players) + ".db";
bool file_exists = (stat(db_name.c_str(), &buffer) == 0 ? true : false);
// std::cout << "File exists? " << file_exists << std::endl;
//if db does not exist, create it. Else just connect with it.
if(!file_exists){
if (sqlite3_open(db_name.c_str(), &db_conn) != SQLITE_OK){
std::cout << sqlite3_errmsg(db_conn) << std::endl;
exit(1);
}
else {
std::cout << db_name << " created" << std::endl;
}
// if (!prepare_stage_write("CREATE TABLE HAND (ID integer, Hand text, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
// sqlite3_close(db_conn);
// exit(1);
// }
// if (!prepare_stage_write("CREATE TABLE FLOP (ID integer, Hand text, Table_cards text, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
// sqlite3_close(db_conn);
// exit(1);
// }
// if (!prepare_stage_write("CREATE TABLE TURN (ID integer, Hand text, Table_cards text, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
// sqlite3_close(db_conn);
// exit(1);
// }
// if (!prepare_stage_write("CREATE TABLE RIVER (ID integer, Hand text, Table_cards text, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
// sqlite3_close(db_conn);
// exit(1);
// }
if (!prepare_stage_write("CREATE TABLE HAND (ID integer, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
sqlite3_close(db_conn);
exit(1);
}
if (!prepare_stage_write("CREATE TABLE FLOP (ID integer, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
sqlite3_close(db_conn);
exit(1);
}
if (!prepare_stage_write("CREATE TABLE TURN (ID integer, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
sqlite3_close(db_conn);
exit(1);
}
if (!prepare_stage_write("CREATE TABLE RIVER (ID integer, Encounters integer, Wins integer, PRIMARY KEY (ID))")){
sqlite3_close(db_conn);
exit(1);
}
}
else{
if (sqlite3_open(db_name.c_str(), &db_conn) != SQLITE_OK){
std::cout << sqlite3_errmsg(db_conn) << std::endl;
sqlite3_close(db_conn);
exit(1);
}
else{
std::cout << db_name << " connected successfully" << std::endl;
}
}
}
db_communicator::~db_communicator(){
int rc = sqlite3_close(db_conn);
if (rc != SQLITE_OK){
std::cout << "Error closing the database: " << rc << " " << sqlite3_errstr(rc) << std::endl;
}
std::cout << db_name << " disconnected successfully" << std::endl;
}
bool db_communicator::prepare_stage_write(const char *command){
sqlite3_prepare_v2(db_conn, command, -1, &db_stmt, NULL);
unsigned int status = sqlite3_step(db_stmt);
while (!((status == SQLITE_DONE) || (status == SQLITE_OK))){
switch(status){
case SQLITE_BUSY:
status = sqlite3_step(db_stmt);
break;
case SQLITE_DONE:
break;
case SQLITE_OK:
break;
default:{
std::cout << "Error code on write staging: " << status << ": " << sqlite3_errstr(status) << std::endl;
sqlite3_reset(db_stmt);
return false;
break;
}
}
}
if (sqlite3_finalize(db_stmt) != SQLITE_OK){
std::cout << "Error code on finalizing: " << status << ": " << sqlite3_errstr(status) << std::endl;
sqlite3_reset(db_stmt);
}
return true;
}
const unsigned char *db_communicator::prepare_stage_read(const char *command){
const unsigned char *query;
sqlite3_prepare_v2(db_conn, command, -1, &db_stmt, NULL);
unsigned int status = sqlite3_step(db_stmt);
while(!((status == SQLITE_DONE) || (status == SQLITE_OK) || (status == SQLITE_ROW))){
switch(status){
case SQLITE_BUSY:
status = sqlite3_step(db_stmt);
break;
default:{
std::cout << "Error code on read staging: " << status << ": " << sqlite3_errstr(status) << std::endl;
sqlite3_reset(db_stmt);
return (const unsigned char*)"error";
}
}
}
query = sqlite3_column_text(db_stmt, 1);
if (sqlite3_finalize(db_stmt) != SQLITE_OK){
std::cout << "Error code on finalizing: " << status << ": " << sqlite3_errstr(status) << std::endl;
sqlite3_reset(db_stmt);
}
return query;
}
void db_communicator::store_to_db(const game * const &poker_game){
//find a way to calculate IDs
std::vector<card> hand_cards;
std::vector<card> table_cards;
std::vector<card> concatenated_cards;
std::string command;
long long unsigned int id = 0;
const unsigned char *query;
for (unsigned int i = 0; i < poker_game->player_number; i++){
//store to hand db
hand_cards = poker_game->player_list[i].get_hand();
id = calculate_card_vector_id(hand_cards);
// command = "SELECT * FROM HAND WHERE ID = " + std::to_string(id);
// query = prepare_stage_read(command.c_str());
// if (query == (const unsigned char*)"error"){
if (false){
sqlite3_close(db_conn);
std::cout << "something went wrong" << std::endl;
exit(1);
}
else{
// if (query == 0){ //new entry
// command = "INSERT INTO HAND (ID, Encounters, Wins) VALUES ("
// + std::to_string(id) + ", "
// + "1, "
// + std::to_string(poker_game->player_list[i].is_winner()) + ")";
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
// else{ //update old entry
// // std::cout << "Entry already exists " << (const char*)query << std::endl;
// command = "UPDATE HAND SET Encounters = Encounters + 1, Wins = Wins + "
// + std::to_string(poker_game->player_list[i].is_winner());
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
}
//store to flop db
table_cards = poker_game->dealer->get_flop();
// concatenated_cards = hand_cards.insert(hand_cards.end(), table_cards.begin(), table_cards.end());
concatenated_cards = hand_cards;
concatenated_cards.insert(concatenated_cards.end(), table_cards.begin(), table_cards.end());
id = calculate_card_vector_id(concatenated_cards);
command = "SELECT * FROM FLOP WHERE ID = " + std::to_string(id);
query = prepare_stage_read(command.c_str());
if (query == (const unsigned char*)"error"){
sqlite3_close(db_conn);
std::cout << "something went wrong" << std::endl;
exit(1);
}
else{
// if (query == 0){ //new entry
// command = "INSERT INTO FLOP (ID, Hand, Table_cards, Encounters, Wins) VALUES ("
// + std::to_string(id) + ", '"
// + [](const std::vector<card> &player){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = player.begin(); it != player.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(hand_cards) + "', '"
// + [](const std::vector<card> &flop){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = flop.begin(); it != flop.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(table_cards) + "', "
// + "1, "
// + std::to_string(poker_game->player_list[i].is_winner()) + ")";
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
// else{ //update old entry
// // std::cout << "Entry already exists " << (const char*)query << std::endl;
// command = "UPDATE FLOP SET Encounters = Encounters + 1, Wins = Wins + "
// + std::to_string(poker_game->player_list[i].is_winner());
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
if (query == 0){ //new entry
command = "INSERT INTO FLOP (ID, Encounters, Wins) VALUES ("
+ std::to_string(id) + ", "
+ "1, "
+ std::to_string(poker_game->player_list[i].is_winner()) + ")";
// std::cout << command <<std::endl;
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
else{ //update old entry
// std::cout << "Entry already exists " << (const char*)query << std::endl;
command = "UPDATE FLOP SET Encounters = Encounters + 1, Wins = Wins + "
+ std::to_string(poker_game->player_list[i].is_winner());
// std::cout << command <<std::endl;
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
}
//store to turn db
table_cards.push_back(poker_game->dealer->get_turn());
sort_vector(table_cards);
concatenated_cards.erase(concatenated_cards.begin() + 2, concatenated_cards.end());
concatenated_cards.insert(concatenated_cards.end(), table_cards.begin(), table_cards.end());
id = calculate_card_vector_id(concatenated_cards);
command = "SELECT * FROM TURN WHERE ID = " + std::to_string(id);
query = prepare_stage_read(command.c_str());
if (query == (const unsigned char*)"error"){
sqlite3_close(db_conn);
std::cout << "something went wrong" << std::endl;
exit(1);
}
else{
// if (query == 0){ //new entry
// command = "INSERT INTO TURN (ID, Hand, Table_cards, Encounters, Wins) VALUES ("
// + std::to_string(id) + ", '"
// + [](const std::vector<card> &player){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = player.begin(); it != player.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(hand_cards) + "', '"
// + [](const std::vector<card> &flop){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = flop.begin(); it != flop.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(table_cards) + "', "
// + "1, "
// + std::to_string(poker_game->player_list[i].is_winner()) + ")";
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
// else{ //update old entry
// // std::cout << "Entry already exists " << (const char*)query << std::endl;
// command = "UPDATE TURN SET Encounters = Encounters + 1, Wins = Wins + "
// + std::to_string(poker_game->player_list[i].is_winner());
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
if (query == 0){ //new entry
command = "INSERT INTO TURN (ID, Encounters, Wins) VALUES ("
+ std::to_string(id) + ", "
+ "1, "
+ std::to_string(poker_game->player_list[i].is_winner()) + ")";
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
else{ //update old entry
// std::cout << "Entry already exists " << (const char*)query << std::endl;
command = "UPDATE TURN SET Encounters = Encounters + 1, Wins = Wins + "
+ std::to_string(poker_game->player_list[i].is_winner());
// std::cout << command <<std::endl;
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
}
//store to river db
table_cards.push_back(poker_game->dealer->get_river());
sort_vector(table_cards);
concatenated_cards.erase(concatenated_cards.begin() + 2, concatenated_cards.end());
concatenated_cards.insert(concatenated_cards.end(), table_cards.begin(), table_cards.end());
id = calculate_card_vector_id(concatenated_cards);
command = "SELECT * FROM RIVER WHERE ID = " + std::to_string(id);
query = prepare_stage_read(command.c_str());
if (query == (const unsigned char*)"error"){
sqlite3_close(db_conn);
std::cout << "something went wrong" << std::endl;
exit(1);
}
else{
// if (query == 0){ //new entry
// command = "INSERT INTO RIVER (ID, Hand, Table_cards, Encounters, Wins) VALUES ("
// + std::to_string(id) + ", '"
// + [](const std::vector<card> &player){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = player.begin(); it != player.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(hand_cards) + "', '"
// + [](const std::vector<card> &flop){
// std::string hand_card;
// for (std::vector<card>::const_iterator it = flop.begin(); it != flop.end(); it++){
// hand_card += card_values[(*it).value] + card_colour[(*it).colour];
// }
// return hand_card;
// }(table_cards) + "', "
// + "1, "
// + std::to_string(poker_game->player_list[i].is_winner()) + ")";
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
// else{ //update old entry
// // std::cout << "Entry already exists " << (const char*)query << std::endl;
// command = "UPDATE RIVER SET Encounters = Encounters + 1, Wins = Wins + "
// + std::to_string(poker_game->player_list[i].is_winner());
// // std::cout << command <<std::endl;
// if (!prepare_stage_write(command.c_str())){
// sqlite3_close(db_conn);
// exit(1);
// }
// }
if (query == 0){ //new entry
command = "INSERT INTO RIVER (ID, Encounters, Wins) VALUES ("
+ std::to_string(id) + ", "
+ "1, "
+ std::to_string(poker_game->player_list[i].is_winner()) + ")";
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
else{ //update old entry
command = "UPDATE RIVER SET Encounters = Encounters + 1, Wins = Wins + "
+ std::to_string(poker_game->player_list[i].is_winner());
if (!prepare_stage_write(command.c_str())){
sqlite3_close(db_conn);
exit(1);
}
}
}
}
return;
}
|
Python
|
UTF-8
| 11,451
| 2.875
| 3
|
[] |
no_license
|
"""
Importing everything here instead of in functions
to import once and speed up REST calls
"""
import pandas as pd
import numpy as np
import pandas.tseries.offsets as pdo
#import pickle
import json
# from sklearn import preprocessing
# from sklearn.cluster import AgglomerativeClustering
from math import radians, cos, sin, asin, sqrt
#from time import time
from random import shuffle
pd.options.mode.chained_assignment = None
commute_distance = 0
def query_db_convert_id(reader, collection, id_cols=None,
sort_col=None, method=None, _filter={},
username=None, sensor=None,
min_date=None, max_date=None, include_max_date=False):
if not method:
df = reader.get_dataframe(collection=collection, filter_args=_filter).sort_values(sort_col)
elif method == "unrolled":
df = reader.get_dataframe_unrolled(collection=collection, filter_args=_filter).sort_values(sort_col)
elif method == "pivoted":
df = reader.get_dataframe_pivoted(collection=collection, username=username, sensor=sensor,
min_date=min_date, max_date=max_date, include_max_date=include_max_date).sort_index()
if method != "pivoted":
for col in id_cols:
df.ix[:,col] = df.ix[:,col].map(str)
return df
# helper in converting dataframe to json array
def make_lat_long(row):
if row["GPS Latitude"] != None:
return {
"date":str(row.name).replace("T", " "),
"latitude":row["GPS Latitude"],
"longitude":row["GPS Longitude"]
}
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees, AKA Latitude / Longitude)
All args must be of equal length.
"""
if type(lon1) != float:
lon1 = lon1.astype(float)
lat1 = lat1.astype(float)
lon2 = lon2.astype(float)
lat2 = lat2.astype(float)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(np.radians,[lon1, lat1, lon2, lat2])
#haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
miles = 3956 * c # Radius of earth in miles. Use 6370 for kilometers
return miles
def set_distance(gps_data, json_array):
"""
Calculate the distance a user has traveled over a given date range. Involves all modes of transportation,
and is calculated using Great-circle distance.
"""
hourly_distances = [('Date', 'Distance')]
#Use haversine function to get distances between all GPS points
dist_traveled = haversine(gps_data['GPS Longitude'].shift(), gps_data['GPS Latitude'].shift(),
gps_data.ix[1:, 'GPS Longitude'], gps_data.ix[1:, 'GPS Latitude'])
dist_grouped = dist_traveled.groupby(pd.Grouper(freq='1H')).sum()
for ts, dist in dist_grouped.iteritems():
h = "{0:02}-{1:02}-{2:02} {3:02}:{4:02}:{5:02}".format(
ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second
)
if np.isnan(dist):
dist = 0
hourly_distances.append((h, dist))
json_array.append({"total_distance": dist_traveled.sum()})
json_array.append({"hourly_distances":hourly_distances})
def get_locs(user_data, user_name, json_array):
global commute_distance
#ts = time()
#print "START get_locs:", ts
locs = json.load(open("data/locations.txt", "r"))[user_name]
#print 109, "get_locs", ":" * 10, (time()-ts)
commute_distance = haversine(locs["home"]["long"], locs["home"]["lat"],
locs["work"]["long"], locs["work"]["lat"])
json_array.append(locs)
ud = user_data[['GPS Latitude','GPS Longitude']]
ud.reset_index(inplace=True)
def loc_dist(df):
d_h = haversine(df["GPS Longitude"], df["GPS Latitude"],
locs["home"]["long"], locs["home"]["lat"])
d_w = haversine(df["GPS Longitude"], df["GPS Latitude"],
locs["work"]["long"], locs["work"]["lat"])
if not (d_h < 0.25 or d_w < 0.25):
loc = "other"
elif d_h == min(d_h, d_w):
loc = "home"
else:
loc = "work"
return loc
ud["dist"] = ud.apply(loc_dist, axis=1)
#print 131, "get_locs", ":" * 10, (time()-ts)
home = ud[ud.dist == "home"]
work = ud[ud.dist == "work"]
other = ud[ud.dist == "other"]
home = home.groupby(lambda x: home['index'][x].day).agg({"index": lambda i: (max(i)-min(i)).total_seconds()})
work = work.groupby(lambda x: work['index'][x].day).agg({"index": lambda i: (max(i)-min(i)).total_seconds()})
other = other.groupby(lambda x: other['index'][x].day).agg({"index": lambda i: (max(i)-min(i)).total_seconds()})
#print 136, "get_locs", ":" * 10, (time()-ts)
seconds_home = np.sum(home["index"])
seconds_work = np.sum(work["index"])
seconds_other = np.sum(other["index"])
seconds_total = seconds_home + seconds_work + seconds_other
percent_home = round(100*(float(seconds_home) / seconds_total), 2)
percent_work = round(100*(float(seconds_work) / seconds_total), 2)
percent_other = round(100*(float(seconds_other) / seconds_total), 2)
json_array.append({"percent_home":percent_home, "percent_work":percent_work, "percent_other":percent_other})
def animal_riding_time():
animals = ['bear','tortoise','kangaroo','pig','unicorn','cheetah','human','cow', 'train']
shuffle(animals)
the_animal = animals[0]
animal_speeds = {
'bear': 35.0, 'tortoise': 0.2, 'kangaroo': 43.0, 'pig': 10.0,
'unicorn': 567.0, 'cheetah': 75.0, 'human': 3.1, 'cow': 25.0, 'train': 17.0
}
speed = animal_speeds[the_animal]
commute_time = (commute_distance / speed) * 60
return {
"speed": round(speed,2),
"time": round(commute_time,2),
"distance": round(commute_distance,2),
"animal": the_animal
}
def get_activity_percents(reader):
import pickle
# import numpy as np
import preprocess_data as pdata
pkl = pickle.load(open("data/pickle_glen_C_032617.p", "rb"))
glen24th = reader.get_dataframe_pivoted(
collection="iphone", username="glen",
sensor=["Acceleration", "Magnetometer"], commute=True,
min_date="2017-03-24 00:00:00", max_date="2017-03-25 00:00:00")
glen24th = pdata.Preprocess_Data(glen24th)
glen24th.Norm()
data = glen24th.Feature_additions()
X = glen24th.load_data_test()
activity_labels = {
0:"driving", 1:"elevator", 2:"standing",
3:"train", 4:"train", 5:"walking"}
pred = np.vectorize(lambda x: activity_labels[x])(pkl.predict(X))
df = pd.DataFrame({"date":data.index, "label":pred})
df["hm"] = df["date"].apply(lambda x: "{0}{1}".format(x.hour, x.minute))
df = df.groupby(["label", "hm"]).agg({"date": lambda i: (max(i)-min(i)).total_seconds()})
# date actually = seconds.
df = df.reset_index().groupby("label").sum().reset_index()
df.columns = ["label", "seconds"]
total_seconds = np.sum(df.seconds)
activity_percents = {}
def set_percents(x):
activity_percents[x.label] = round(x.seconds/total_seconds*100,2)
df.apply(set_percents, axis=1)
return activity_percents
# def get_locs(reader, user_data, user_name, json_array):
# """
# Predict clusters from cluster
# """
# ts = time()
# print "START get_locs:", ts
# H_model = get_model(user_name)
# print 106, "get_locs", ":" * 10, (time()-ts)
# H_data = user_data[['GPS Altitude','GPS Latitude','GPS Longitude']]
# print 108, "get_locs", ":" * 10, (time()-ts)
# preprocess = preprocessing.scale(H_data)
# print 110, "get_locs", ":" * 10, (time()-ts)
# clusters = H_model.fit_predict(H_data)
# print 112, "get_locs", ":" * 10, (time()-ts)
# H_data.reset_index(inplace=True)
# print 114, "get_locs", ":" * 10, (time()-ts)
# H_data["ymdh"] = H_data["index"].apply(lambda t: "{year}{month}{day}{hour}".format(
# year=t.year, month=t.month, day=t.day, hour=t.hour
# ))
# print 119, "get_locs", ":" * 10, (time()-ts)
# H_data["hour"] = H_data["index"].apply(lambda t: t.hour)
# print 121, "get_locs", ":" * 10, (time()-ts)
# H_data["cluster"] = pd.Series(clusters)
# print 123, "get_locs", ":" * 10, (time()-ts)
# H_data.loc[:,"GPS Latitude"] = H_data["GPS Latitude"].astype(float)
# H_data.loc[:,"GPS Longitude"] = H_data["GPS Longitude"].astype(float)
# H_data.loc[:,"GPS Altitude"] = H_data["GPS Altitude"].astype(float)
# print 127, "get_locs", ":" * 10, (time()-ts)
# get_label_latlongs(H_data, json_array)
# print 129, "get_locs", ":" * 10, (time()-ts)
# def get_label_latlongs(df, json_array):
# ts = time()
# print "START get_label_latlongs:", ts
# df_grouped = df.groupby(["cluster", "hour"]).median()
# zero = df_grouped.loc[0,:]; one = df_grouped.loc[1,:]
# zero_full = df[df.cluster==0]; one_full = df[df.cluster==1]
# labels = {"home":{},"work":{}}
# home=None; work=None
# home_full=None; work_full=None
# print 142, "get_label_latlongs", ":" * 10, (time()-ts)
# gb = df.groupby(["cluster"]).agg(
# {"hour": lambda x: float(((0 <= x) & (x < 6)).sum())/((0 <= x) & (x < 24)).sum()}
# )
# home_idx = gb[gb["hour"] == max(gb["hour"])].index[0]
# print 149, "get_label_latlongs", ":" * 10, (time()-ts)
# if home_idx != 0:
# (home, work) = (one, zero)
# (home_full, work_full) = (one_full, zero_full)
# else:
# (home, work) = (zero, one)
# (home_full, work_full) = (zero_full, one_full)
# print 159, "get_label_latlongs", ":" * 10, (time()-ts)
# set_loc_percents(home_full, work_full, json_array)
# print 163, "get_label_latlongs", ":" * 10, (time()-ts)
# min_home = home.loc[home.index == min(home.index),:]
# min_work = work.loc[work.index == work.index[len(work.index)/2],:]
# print 168, "get_label_latlongs", ":" * 10, (time()-ts)
# labels["home"]["lat"] = float(min_home["GPS Latitude"])
# labels["home"]["long"] = float(min_home["GPS Longitude"])
# labels["work"]["lat"] = float(min_work["GPS Latitude"])
# labels["work"]["long"] = float(min_work["GPS Longitude"])
# print 175, "get_label_latlongs", ":" * 10, (time()-ts)
# print labels
# json_array.append(labels)
# print 179, "get_label_latlongs", ":" * 10, (time()-ts)
# def get_model(username):
# filename = "data/hclust_{0}.p".format(username)
# return pickle.load(open(filename, "rb" ))
# def set_loc_percents(home, work, json_array):
# home = home.groupby(lambda x: home['index'][x].day).agg({"index": lambda i: (max(i)-min(i)).total_seconds()})
# work = work.groupby(lambda x: work['index'][x].day).agg({"index": lambda i: (max(i)-min(i)).total_seconds()})
# # datediff_home = max(home["index"]) - min(home["index"])
# # datediff_work = max(work["index"]) - min(work["index"])
# seconds_home = np.sum(home["index"])
# seconds_work = np.sum(work["index"])
# seconds_total = seconds_home + seconds_work
# percent_home = round(100*(float(seconds_home) / seconds_total), 2)
# percent_work = round(100*(float(seconds_work) / seconds_total), 2)
# json_array.append({"percent_home":percent_home, "percent_work":percent_work})
|
Markdown
|
UTF-8
| 24,460
| 2.703125
| 3
|
[] |
no_license
|
<title>暗器使</title>
<meta name="GENERATOR" content="WinCHM">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<br>
<br>无论是在武侠,魔幻世界,甚至多元宇宙,使用投掷类武器的总是少数。在战斗中,威力不及火器,处于劣势地位的投掷武器,仅仅是作为量产的爆炸性质消耗品,或者独门的战斗风格技术而被使用。
<br>主神选取了三个代表性的魔幻与特异本质的暗器使用者,并把他们的技术统一整合。
<br>三个暗器使分别代表:
<br>体流:通过三次元甚至四次元的急停,瞬动,配合暗器的使用的格斗技。是短,中距离搏杀的技巧。
<br>技流:通过花样的魔术技巧,将猎物玩弄于掌心之间的狩猎技艺,大多是干扰技,也有决定性质的伤害技。
<br>器流:如果威力不及火器的话,就加强道具的威力吧,以此做出的,十分让人头疼的重投掷道具,更多,更强,更远,这就是器流的全部了。
<br>一名暗器使需要选择他的战斗风格,在获得暗器使训练时,他必须在三条路线中选择一条,不得变更。但是他也可以重复购买此称号,来学习其他两个流派的战斗风格。
<br>他所选择的流派也会同时影响他的技能树。
<br>
<br>暗器的定义:一切分类为投掷武器的物品与所有的操具(但不包括临时武器)。
<br>
<br>D级:
<br>通用:例无虚发
<br>格言:“小李飞刀,例无虚发”
<br>------------------------江湖传说。
<br>效果:你的所有投掷武器高速增加3点。
<br>
<br>体流:
<br>弹反:消耗1点内力或斗气,配合丝线,投掷道具命中30米内的敌人之后,可以以迅捷动作做一次力量+运动的检定,敌人需要进行一次相同的检定对抗。若你在这次对抗中胜出,你可以顺着丝线移动,或者将他顺着丝线拉扯一定距离,该距离等同于你在检定中胜出数×10米或者所用丝线长度中较低者。
<br>你可以使用自动吸附式丝线工具,或者其他ST允许的道具来使用这个技巧。特殊地,你使用的自动吸附式丝线工具若是以此方式使用的话,可以循环使用。
<br>自动吸附式丝线工具
<br>20点数
<br>由吸盘,极为柔韧的蜘蛛丝和卷扬机组成的工具,可以装在手腕上,手指一按开关便可弹射出去,吸附在被投掷武器命中的人体上,蜘蛛丝长达30米,可以承受200公斤的重量,不可以循环使用。
<br>技流:
<br>速符「Luminous Ricochet」(闪光弹跳)
<br>消耗一点魔力,一场战斗可以使用一次,若你使用投掷武器给对方造成了目眩(例如闪光弹),你可以以一个移动动作用手雷/炸弹等无支线爆炸物进行一次追加投掷。在这次追加投掷中,对方的反射检定受到等同于其承受的目眩点数的减值。
<br>器流:
<br>起爆符制造
<br>暗器使制造一枚炸弹是一个以分钟作为起点的长动作,用智力+手艺:制造暗器(或者手艺:制造起爆符)判定,一分钟判定一次,满足10成功就能制造成功。
<br>起爆符:购买价格15点,外观是一个黄色的符纸,单独投掷是附加在一个圆球上,单独使用等同于手雷。
<br>能够在10米范围内造成5L火焰伤害,以反射检定抵消。
<br>如果附着在投掷武器上命中对手,则可以以一个标准动作引爆,此时起爆符的反射豁免受到攻击成功数的减值。但对方可以消耗一个迅捷动作,将起爆符连同投掷道具一起扯下来。
<br>当你的暗器使称号达到B时,可以用迅捷动作引爆附着在投掷武器上的起爆符。
<br>
<br>C级:
<br>"何为暗器,暗中使用,克敌制胜的特殊武器方为暗器。如果敌人已知你要使用它,那么他就不再是暗器,而是明器。"
<br>-------------------------------唐门六训之一。
<br>通用:暗器精通
<br>你的暗器大师专长提高1级,最高到2级,且你取出的暗器并不仅仅限于便携暗器,这可能是投枪或者铁球等等。此外,你所进行的短点射/长点射/连射不限于便携暗器。
<br>体流:
<br>虚空而来的猎犬 :
<br>当你投掷武器命中对手的时候,你可以消耗消耗1点内力或斗气,以一个移动动作瞬移到他的背后。这在视觉上虽然看起来是空间跳跃效果,但实际上只是超高速的移动而已。因此,如果这片区域在空间上是封闭的,则会撞到这个阻碍物上并停止移动(比如没有可以让自身通过的缝隙的监狱铁牢)。
<br>这次移动的距离不能超过你的移动速度。
<br>在这次攻击之后,你可以投掷敏捷+隐蔽:潜藏对抗敌人的感知+洞察:侦查,成功的话,针对你的下次攻击,他陷入措手不及状态(C级)。
<br>技流:
<br>时符「Stopwatch」(计秒表)
<br>标准动作投掷时,消耗3魔力,自由动作,你可以将你的投掷武器进入【预置】模式。
<br>进入预设模式的投掷武器不会飞出,也不会因为定时一类的效果爆炸,而是诡异的停留在半空。
<br>当你在之后的回合使用迅捷动作宣言“Stopwatch“后,【预置】模式的投掷武器随即朝预定方位飞出。
<br>你所能延迟的回合为最多2回合,即你可以在第三回合,将前两轮的飞刀和第三次的飞刀一起射出,判定三次攻击。
<br>当对方移动出预置攻击的,那一次攻击自动失败,以此类推。你也可以在预设的回合(两回合)内消耗一个移动动作把所有【预置】状态下的武器拿下来。
<br>器流:
<br>操具--巨形投掷。
<br>只要满足投掷武器的条件,器流的操作使可以兑换加大型号的图纸。
<br>在力量满足的条件下,投掷道具的体积每增加1,力量需求增加1,威猛增加1,伤害增加1L,价格提升500点,投掷道具的体积上限为使用者的体型,这与正常的武器体积规则不同。
<br>但是...因为不能熟练操纵,没有暗器使称号的人使用这些武器要有-10dp的减值。
<br>比如一个1体积的小型标枪,价格为10点,伤害为2L。6力量6体型的器流的暗器使可以制造6体积的巨形标枪,价格为2510点,伤害为7L,拥有6威猛。飞镖则变成风魔手里剑等等。
<br>爆炸物品无法用此方式增强。
<br>
<br>B级
<br>通用:
<br>之所以还在用暗器的原因,是因为暗器比明器好用,之所以放弃暗器的原因,是因为权势是天下最厉害的暗器。
<br>------------------------------------------------兵器谱。
<br>投掷训练
<br>你的运动技能提升3级。
<br>
<br>体流:
<br>风转的影舞叶
<br>若你的一次投掷攻击未取得任何成功数,只有一次机会,你可以甩动暗器上连接的蜘蛛丝,以原本的DP进行一次追击。
<br>针对这次攻击,视为一次近战攻击。
<br>现在开始,你可以以一个自由动作,将连接蜘蛛丝的武器与蜘蛛丝回收。
<br>技流:
<br>时符「Silver Acute 360」(银之锐角360度)
<br>你可以选择一下两种方式使用这个招式。
<br>1,整轮动作,你连射的投掷武器需在12把以上且规格相同。
<br>你可以选择支付12魔力,这些投掷武器会飞行到你射程范围的最外围围成一个圆环;接着你的射程范围内出现银色的时针和分针,进行一次扫荡。在你的射程范围以内的敌人受到19L的力场范围伤害,反射减免。
<br>2,标准动作,你连射的投掷武器需在12把以上且规格相同。
<br>你可以选择支付12魔力,这些投掷武器会飞行到你射程范围的最外围围成一个圆环;接着,这十二把武器在无形的时针圈以内来回弹射。你对这个圆环范围内的所有人(不分敌我)各进行一次单发投掷攻击,每有一个目标,则DP-1。
<br>器流:操具:千之千本。
<br>漫天的武器纷纷炸开。
<br>进行一次投掷攻击,这次攻击的方式须为消耗10把或更多武器的连射攻击,将连射武器的数量作为增强加值加在攻击检定上。此外,直到下一个你的回合开始时你获得连射武器数量的掩蔽加值。以此方式获得的DP和掩蔽防御加值上限皆为称号等级*2。
<br>单个武器的价格必须在15点以上,以此法消耗的武器不能被回收。
<br>
<br>A级:
<br>天下的暗器共有三百六十余种,但其中最成功、最可怕的就是孔雀翎。
<br>从外表看来,孔雀翎是个由纯金铸成、闪闪发光的圆筒,上面有两道枢纽,按下枢纽,筒里的暗器便飞射而出,据说这些暗器发出来时,美丽得就像孔雀开屏一样,辉煌灿烂,然而,就在你被这种惊人的生灵感动得目瞪神迷时,它已经要了你的性命。
<br>------------------------------------------------------------------------《孔雀翎》
<br>通用:飞行道具增强
<br>你在投掷武器时再获得+16DP增强加值。
<br>
<br>体流:
<br>雾夜的杀人鬼。
<br>当你的攻击命中后,你可以立即追加一次对于目标的投掷攻击,但在此次攻击检定中承受上一次攻击所获得成功数的减值。
<br>技流:
<br>伤符「Inscribe Red Soul」(铭刻于红魂)
<br>以一个移动动作使用,你可以选定你进行的上一次投掷攻击,投掷智力+感知,判定的成功数由你分配给对方的【剧痛】【耳鸣】【恶心】【眩晕】【亢奋】。对方可以分别对每种异常点数进行一次强韧检定来抵消不良点数。你可以如此分配的点数最多不能超过你选中攻击的最终伤害数的两倍,且单项不超过你攻击的成功数。这视为一个魔幻本质的诅咒效果(A级)。
<br>器流:操具:双升龙。
<br>前提:操具-卷轴
<br>现在,通过一个标准动作解放两个卷轴,你从卷轴的投射可以射出任意数量的飞行道具。
<br>你可以以连射的投掷方式,在你的敏感范围内进行火力压制,其伤害等于你投掷出道具中伤害最高者加上你投掷道具数量的加值。一次投掷10~100枚道具获得伤害+3,100~999枚获得伤害+10,1000枚以上伤害+15。
<br>你无法通过这种方式召唤出海量暗器来压死对手或者在宇宙中造出小星球,除非另有能力能让你这么做。
<br>
<br>技能树
<br>通用
<br>D级:
<br>D+500
<br>精巧投掷
<br>即使是学徒,也知道暗器射到眼睛里比射到肉里更好。
<br>效果:投掷攻击部位的减值降低1/称号等级。
<br>同时,你可以用敏捷代替力量进行重武器的投掷计算。
<br>
<br>C级:
<br>C+1000
<br>流星一条。
<br>中东神话中阿拉什的绝技,燃烧自己一切换取的究极太阳光芒。
<br>效果:标准动作,使用任意点内力、斗气或魔力(但是不能混合使用),在投掷攻击中使用,每1能量+1高速与1破甲。
<br>在你使用这个招式后,立刻获得消耗能量的疲乏点数,不可豁免,可以进入到毁灭后果。只有进行一次长休息才能完全移除。
<br>
<br>B级:
<br>B+2000
<br>命运之矛。
<br>长枪的投掷技术。
<br>效果:所有枪型,圆形,长形的武器,只要符合空气动力学(有刺击与钝击的功能)都可以在你手中作为投掷武器使用,所属专业都为枪/矛,附加重投掷特性,并额外获得武器体积的破甲,上限为4,这不与武器本身的破甲叠加,基础射程单位为力量*10。
<br>
<br>
<br>体流:
<br>体流的所有技能都限定为匕首投掷,即使用分类为匕首的武器才能使用体流技能。
<br>D级
<br>D+500
<br>连翔之刃
<br>无论你们是爱人,或是交易,总不能让可爱的小姐一个人下地狱。
<br>匕首在穿透第一个人的胸部时如此说道。
<br>效果:你所使用的投掷武器命中一个人之后,可以折返攻击第二个人。这个能力如同【贯穿】,但轨迹不必为直线,也无须承受减值。你在一次攻击中只能使用一次这个效果。
<br>
<br>DD+750
<br>迷走凶刃
<br>我呢,喜欢你背对我的样子,如果你不愿意,那只好让我来帮你。
<br>效果:当你拌摔敌人成功后,你可以选择不是击倒而是向上击飞你的敌人你对抗胜出数/米。
<br>若如此做,你可以使用一个迅捷动作,投掷一枚匕首攻击飞空中的人,目标若没有飞行能力则视为C级的措手不及。
<br>
<br>C级
<br>DD+750
<br>驱逐之风,回转之刹。
<br>靠近我的话,会死,我们两个其中之一,所以,暂时远离。
<br>在对方接近的时候,射出投掷道具将其击退。
<br>效果:消耗3点内力或斗气,以一个标准动作,视为一次不附带能量和招式的普通投掷攻击。若这次攻击造成了伤害,对方将会被巨大的力量击退等同于你造成伤害的米数,对方可以力量+运动对抗。
<br>特别的,你可以用反射动作来使用这个能力,但你会失去下一个标准动作。这会正常的打断目标进行的动作。
<br>
<br>C+1000
<br>黄道十二宫
<br>需求:暗器大师3级。
<br>多么美丽的星星啊,多么美丽的你,或许应该知道,没有什么能阻挡我。
<br>向前方丢出十二把小刀,贯穿一切的弹幕。
<br>效果:标准动作,消耗3点内力或斗气,并进行一次投掷攻击。这次攻击视为进行了连射,额外+12破甲,并获得【超级贯穿】效果。
<br>
<br>C+1000
<br>悲剧之韦伯
<br>韦伯,你的名字,还记得你的甜心吗,现在,悲剧将要开始。
<br>迅速的后跳,并散出六枚匕首。
<br>效果:迅捷/反射动作使用,消耗3点内力或斗气,向后跳跃移动不超过你运动等级的距离,并在你的射程范围内选择一名敌人,对其射出六枚匕首。这些匕首不会造成伤害,不过本回合视为已对敌人攻击了6次。
<br>
<br>B级
<br>B+2000
<br>具现的憎恶
<br>善意即是恶意,鲜红的颜色永远是最令人兴奋的
<br>效果:当你承受了因亢奋状态带来的减值时,对于你造成伤害的目标,他承受如同你承受亢奋点数的剧痛,可叠加。
<br>
<br>B+2000
<br>逆行的时钟-满月之狂人
<br>对于我而言,你的时间永久的定格在了六秒之前。
<br>效果:每场景或遭遇一次,你在战斗开始(投掷先攻后)进行如下选择其一:
<br>1、放弃下一个整轮动作,将其转化为一个四回合内可以以反射动作使用的标准动作。
<br>2、放弃下一个标准动作,将其转化为一个四回合内可以以反射动作使用的移动动作。
<br>3、放弃下一个移动动作,将其转化为一个四回合内可以随时使用的迅捷动作。
<br>每回合一次,你可以将本回合的两个迅捷动作合成一个移动动作,或将本回合的两个移动动作合成一个标准动作。
<br>
<br>A级
<br>A+4000
<br>十六解体
<br>发现尸体的时候,地狱一般的场景。
<br>效果:你对陷入措手不及的目标攻击时,增加11个附加成功,这是技艺加值。
<br>你对无助目标宣言致命一击时,造成的一半伤害转化为恶性。
<br>
<br>A+4000
<br>月浸食-拿督斯的呼唤
<br>绿色黄色的液体中,唯独少了红色。
<br>效果:每场景或遭遇一次,在战斗开始(投掷先攻后),你以一个自由动作受到X点不可吸收减免的恶性伤害,在这场战斗或遭遇中获得额外+Xdp的增强加值。此时,你用来连接暗器的丝线会透出隐隐红光。当你投掷攻击命中时,连接的蜘蛛丝会引导别人的鲜血献给拿督斯。每次造成恶性伤害,你都可以将等同于你造成的恶性伤害/2的生命槽恢复为完好。
<br>
<br>技流:
<br>D级
<br>D+500
<br>光速「C.ricochet」(光速跃迁)
<br>闪光投掷中
<br>你在购买暗器的同时购买这个强化。
<br>这个暗器视为进行了物品改造,同时这个技艺不会为你提供属性点。
<br>第一次购买时,获得【回力】特性,并且在命中后可以造成1点不可抵消的目眩。第二次购买时,若你投掷时支付1点魔力,此暗器视为获得【能量武器】特性。
<br>
<br>C级
<br>C+1000
<br>时符「Changeling Magic」(变换魔术)
<br>互换位置中
<br>当你的投掷攻击对对方造成伤害时,可以消耗一点魔力,进行一次反射检定与对方的反射检定对抗。若你胜出,你可以与其互换位置。若对方是自愿则无需对抗。这是一个C级、时空来源的效果。
<br>
<br>C+1000
<br>伤魂「Soul Sculpture」(灵魂雕塑)
<br>机器人拆除中
<br>你可以选择特殊的攻击方式。
<br>当对方拥有灵魂而且拥有硬度的时候,你可以无视12点硬度进行攻击。在本次攻击中,你可以选择不造成伤害但是扣除相当于成功数部分的护甲;若护甲防御归零,则护甲上的DR也会被归零。被扣除的硬度和天生防御将持续一个场景。
<br>
<br>C+1000
<br>奇术「Eternal Meek」(永恒的温柔)
<br>完美潇洒的女仆
<br>将你的投掷变为符卡攻击
<br>以一个自由动作宣言使用这个招数,你的投掷攻击不会带来伤害,而是转化成等量的魅惑效果,意志抵消,可以叠加。直到你宣言放弃魅惑之前,你对他所造成的后续伤害全部变为魅惑效果。但不会累计为毁灭性后果。
<br>直到你宣言放弃魅惑之前,每次你的投掷攻击都会额外消耗1点魔力。
<br>
<br>CC+1500
<br>时符「Private Vision」(个人幻影)
<br>飞刀幻影中。
<br>支付1点魔力,当你投掷攻击的时候,会分出两个幻影同时攻击。
<br>对方的基础防御-4,若在计算后对方基础防御为0,则其格挡防御也只有一半生效。这是一个B级幻象来源的效果。
<br>
<br>B级
<br>B+2000
<br>时符「Private Square」(个人空间)
<br>女仆瞬移中
<br>每场景一次,消耗3点魔力和一个反射动作,你可以与在你敏感范围内的投掷道具互换位置。若你的置换目标是投掷出去的,你立刻出现在道具一倍基础射程单位上的任何一点,且该攻击无效;若你是将投掷道具以「时符」效果固定在空中,你与该道具互换位置,且该招式立刻结束;你亦可以选择攻击后掉在地上或者插在他人身上的道具,此时你会出现在置换目标的1米以内,若是你选择插在他人身上的道具,则下次对此人进行攻击视为B级措手不及。这是一个B级、时空来源的效果。
<br>
<br>B+2000
<br>女仆秘技「控制Doll」(控制人偶)
<br>人偶对决中
<br>消耗5点魔力,并进行一次投掷攻击。若本次攻击成功对对方造成伤害,你可以强行用魔力的丝线如同控制人偶一样控制对方。对方进行一次意志检定,难度为他在此次攻击中所承受的伤害。若对方失败,则在此回合被你控制。你需消耗一个动作令对方做出同级别的动作(例如花费移动动作操控对方移动,标准动作操控对方攻击等),对方会仿佛提线木偶一般,只能进行僵硬的基本动作——例如跳跃、不附带能量和招式的普通攻击、躺下等。每个回合对方都可以再与你对抗一次,成功数累计。
<br>无论如何,这个控制效果将在3回合后结束,且每遭遇对一个人只能生效一次。这是一个B级附身来源的支配效果。
<br>
<br>A级
<br>A+4000
<br>时符「The World」(咲夜的世界)
<br>The World!
<br>一场战斗一次,支付30点魔力,你强制冻结时间。你视为获得了两个对于所有人的突袭轮,但你或你造成的任何结果皆无法直接影响到其他生物。这是一个A级、时空来源的时间静止效果。
<br>
<br>器流:
<br>D级:
<br>特殊:所有操具系列的道具,如果别人使用,会因为不熟练而受到-10dp的减值,不进行检定的无法使用。其分类均为投掷武器,如果有学习价格和购买价格,学习后可以自造。
<br>特殊:购买操具视为物品不会带来自由属性点,但是学习制作方式会带来自由属性点。
<br>
<br>操具-卷轴
<br>购买价格:D+500(特殊地,在购买它时,你就视为学习了制作它,但你无法将你制作或购买的卷轴交给别人使用)
<br>你获得1立方米空间的卷轴,用于装下你的所有投掷道具。
<br>具现在手里是一个移动动作。
<br>可以支付差价让卷轴升级
<br>支付D后,容积扩大10倍,具现是迅捷动作。
<br>再支付D后,容积再扩大10倍(然而只能装分类为投掷武器的物品),具现是自由动作。
<br>只能装分类为暗器的物品,装进去的东西视同进入主神空间自己的房间内,且无法装入活物。
<br>特殊:再支付D后,容积再扩大10倍,不限于投掷道具。
<br>更名为:通灵术·时空间仓库。
<br>卷轴被毁坏需要重新找一张两米长,半米宽的白纸,两个小时画上专属符印。
<br>
<br>操具-芭蕉扇。
<br>购买价格:300点。
<br>学习价格:D+500
<br>这是一个扇形的投掷道具。
<br>伤害为2L,基础射程单位为40米,但是每次攻击时,你可以选择如下类型中的一种:火焰/冰冻/腐蚀/音波/电流,将造成的伤害改为对应类型的能量伤害。
<br>
<br>C级:
<br>DD+750
<br>手里剑影分身之术。
<br>复制你的手里剑,做一次感知+学识:解读判定。
<br>每1成功数可以将无支线的物体复制1个
<br>3成功数可以将D支线的物体复制一个,以此类推。
<br>在投掷的同时,以自由动作复制并一起射出。若你在同时复制和射出的物体在3个以上,获得“短点射”效果;在5个以上时,获得“长点射”效果;在10个以上时,获得连射效果。
<br>
<br>操具-极大铁球
<br>购买价格:C+1000
<br>学习价格:C+1000
<br>这是一个10L,10体积,8破甲,8威猛的巨形铁球。
<br>使用的时候需要整轮动作进行回旋投掷。
<br>操具使按照投掷使用则无力量要求。
<br>也可以作为近战武器使用.....需要拥有专业:异种武器(铁球)。
<br>拥有【眩晕】特性。
<br>在使用15次后就会毁坏。
<br>
<br>B级:
<br>升龙
<br>B+2000
<br>以一个标准动作,进行一次跳跃检定,并停留在半空,卷轴围绕着你旋转。
<br>此时,你获得运动等级的全伤害减免,但每回合会消耗10点内力或斗气。
<br>消耗的能量需要你在开始时选定,一旦选定无法更改。
<br>在此状态下,你的卷轴持续解放且不可被损毁,其中的道具视为无支线的道具无限,但每次你只能召出等同于你最大投掷数量的道具。
<br>
<br>操具-地团太
<br>购买价格:B+2000
<br>学习价格:B+2000
<br>改为18L,25体积,16破甲,16威猛的带刺铁球。
<br>当你力量不足时,你可以使用10张起爆符引爆才能将其投掷成功,没有减值,引爆是包含在你投掷动作中的。
<br>以这种攻击方式进行的投掷攻击改为伤害20L、半径10米的范围攻击,以敏捷+运动豁免。
<br>在使用15次后就会毁坏。
<br>
<br>A级:
<br>天锁灾
<br>A+4000
<br>你在使用升龙或者双升龙的过程中,可以在其中衔接5条锁链,长度为你的最大投掷距离。以一个迅捷动作,你可以对最多五人进行擒抱,使用投掷攻击检定代替擒抱检定。若在你的攻击中受到了伤害,则无须进行接触攻击检定,且对方只能以力量+肉搏对抗你的擒抱检定。
<br>若你擒抱成功,对方在防御上失去对你的一切掩蔽、闪避和格挡加值,并陷入擒抱状态。特殊地,你并不视为处于擒抱状态中,也无法对对方进一步进行压制。
|
PHP
|
UTF-8
| 1,582
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: chuch
* Date: 7/17/2017
* Time: 10:43 PM
*/
use App\Album;
use Illuminate\Database\Seeder;
class AlbumTableSeeder extends Seeder
{
public function run()
{
DB::table('albums')->delete();
Album::create(array(
'artist_id'=> 1,
'name' => 'The Dark Side of the Moon',
'genre' => 'Rock',
'picture'=> 'img/darkside.jpg',
));
Album::create(array(
'artist_id'=> 1,
'name' => 'The Wall',
'genre' => 'Rock',
'picture'=> 'img/thewall.jpg',
));
Album::create(array(
'artist_id'=> 2,
'name' => 'Let It Bleed',
'genre' => 'Rock',
'picture'=> 'img/letitbleed.jpg',
));
Album::create(array(
'artist_id'=> 3,
'name' => 'Kind of Blue',
'genre' => 'Jazz',
'picture'=> 'img/kindofblue.jpg',
));
Album::create(array(
'artist_id'=> 4,
'name' => 'John Coltrane',
'genre' => 'Jazz',
'picture'=> 'img/bluetrain.jpg',
));
Album::create(array(
'artist_id'=> 5,
'name' => 'Electric Mud',
'genre' => 'Blues',
'picture'=> 'img/electricmud.jpg',
));
Album::create(array(
'artist_id'=> 6,
'name' => 'The Best of Litle Walter',
'genre' => 'Blues',
'picture'=> 'img/bestofthewalter.jpg',
));
}
}
|
Go
|
UTF-8
| 4,406
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package client
import (
"bytes"
"context"
"github.com/redresseur/loggerservice/utils/ioutils"
"github.com/redresseur/loggerservice/utils/sturcture"
"io"
"io/ioutil"
"os"
"runtime"
"sync/atomic"
"time"
)
var(
gChannelIO *channelIO
)
// 还要再封装一层
// 用channel封装一层
type channelIO struct {
// 加一个大的缓存队列
io *structure.Queue
ctx context.Context
realWriter io.Writer
writerType LoggerType
buffer *bytes.Buffer
module string
redirect *atomic.Value
cancel func()
}
func NewChannelIO(writer io.Writer, module string)*channelIO{
ch := channelIO{}
ch.ctx, ch.cancel = context.WithCancel(gSdkCtx)
// 设置缓存4096
ch.io = structure.New()
ch.realWriter = writer
ch.buffer = bytes.NewBuffer(nil)
ch.module = module
ch.redirect = &atomic.Value{}
ch.redirect.Store(false)
ch.writerType = gLoggerType
go ch.worker()
return &ch
}
func (ch *channelIO)Write(p []byte) (n int, err error) {
ch.io.Push(p)
ch.io.SingleUP(false)
return len(p), nil
}
// 当grpc切换到本地的时候,
// 不断的轮训,尝试切换回来
func (ch *channelIO)switchBack(){
// realType := ch.writerType
for true {
timer := time.After(gGrpcHeartTime)
select {
case <-ch.ctx.Done():
return
case <-timer:
if gGrpcConnection == nil || !gGrpcConnIsUseFul.Load().(bool){
continue
}
newWrite, err := operatorGrpc(ch.module)
if err != nil{
continue
}
// 日志暂存在内存
ch.redirect.Store(true)
// 切换write
oldWriter := ch.realWriter
// 首先将缓存在本地的数据读取出来
if ch.writerType == LoggerLocal{
fd, _ := oldWriter.(*ioutils.FileMutexIO)
// 定位到文档起点
fd.Sync()
fd.Seek(0, 0)
// TODO: 此处将来要优化,数据太大写入容易崩溃
if data, err := ioutil.ReadAll(fd); err == nil{
newWrite.Write(data)
}
defer func() {
fd.Close()
os.Remove(fd.Path())
}()
}
// 切换到新的write上
ch.realWriter = newWrite
ch.redirect.Store(false)
ch.io.SingleUP(true)
ch.writerType = LoggerGrpc
return
}
}
}
// TODO: 后面加了配置监督可能会用到这个接口
func (ch *channelIO)reopen(){
// 重新打开一个接口
// 如果打开失败
switch ch.writerType {
case LoggerGrpc:
// 转存本地
newWriter, err := openLogger(ch.module)
if err == nil{
ch.realWriter = newWriter
// 先从重定向状态中切换过来
// 然后发出信号
ch.redirect.Store(false)
ch.io.SingleUP(true)
}else {
ch.writerType = LoggerLocal
// 尝试切换回来
go ch.switchBack()
ch.reopen()
}
case LoggerLocal:
// 直接打印到控制台
var err error
if ch.realWriter, err = operatorLocal(ch.module); err != nil{
ch.writerType = LoggerStd
ch.reopen()
}else {
ch.redirect.Store(false)
ch.io.SingleUP(true)
}
case LoggerStd:
ch.realWriter = os.Stdout
ch.redirect.Store(false)
ch.io.SingleUP(true)
}
}
func (ch *channelIO)readAll()[]byte{
res := []byte{}
for true {
data, isOK := ch.io.Pop().([]byte)
if data == nil || !isOK{
break
}
res = append(res, data ...)
}
return res
}
func (ch *channelIO)worker(){
runtime.LockOSThread()
defer runtime.UnlockOSThread()
for true{
select{
case _, isOK := <- ch.io.Single() :
if !isOK{
return
}
//ch.buffer.Write(data)
//应该无脑写内存
data := ch.readAll()
// 有可能读出空数据
if len(data) == 0{
ch.io.SingleDown()
continue
}
if ch.redirect.Load().(bool){
ch.buffer.Write(data)
ch.io.SingleDown()
continue
}
// TODO: 为了防止写数据过大,此处应该分块处理比较好
if buffData := ch.buffer.Bytes(); len(buffData) != 0{
data = append(buffData, data...)
ch.buffer = bytes.NewBuffer(nil)
}
if _ , err := ch.realWriter.Write(data); err!= nil{
// 如果写入错误,就暂时缓存在内存中
ch.buffer.Write(data)
ch.redirect.Store(true)
ch.reopen()
}
ch.io.SingleDown()
case <-ch.ctx.Done():
return
}
}
}
func (ch* channelIO)Close(){
ch.cancel()
// 写入残留数据
data := ch.buffer.Bytes()
if qData := ch.readAll(); qData != nil{
data = append(data, qData...)
}
if len(data) > 0{
ch.realWriter.Write(data)
}
ch.io.Close()
if fd, isOK := ch.realWriter.(*ioutils.FileMutexIO); isOK{
fd.Sync()
fd.Close()
}
}
|
JavaScript
|
UTF-8
| 288
| 3.015625
| 3
|
[] |
no_license
|
ready(function(){
affichage(document.querySelectorAll('.rubrique')[0].id)
});
function affichage(id) {
var blocks = document.querySelectorAll('.rubrique');
for (var i=0;i<blocks.length;i++){
blocks[i].style.display= "none";
}
document.getElementById(id).style.display = 'block';
}
|
TypeScript
|
UTF-8
| 842
| 2.515625
| 3
|
[] |
no_license
|
import { Unknown } from './UnknownParam';
import { InfraSettings } from './Settings';
export class DataStoreSizeCal {
private unknown = new Unknown();
private settings: InfraSettings;
constructor(settings: InfraSettings) {
this.settings = settings;
}
datastoreSize(): number {
const monthDays = 30.44 * this.settings.historicPerfData;
const result =
this.settings.datastoreQty *
((96 * 7 + 13 * monthDays) * 10 + (48 * 7 + 2 * monthDays) * 2) *
this.unknown.unknownParamExtended;
return result;
}
datastoreSizet(): number {
const monthDays = 30.44 * this.settings.historicPerfData;
const result =
this.settings.datastoreQty *
((288 * 7 + 13 * monthDays) * 10 +
(48 * 7 + 2 * monthDays) * 2) *
this.unknown.unknownParamExtended;
return result;
}
}
|
Java
|
UTF-8
| 3,480
| 2.34375
| 2
|
[] |
no_license
|
package com.swpu.sharebook.service.impl;
import com.swpu.sharebook.entity.UserRole;
import com.swpu.sharebook.mapper.RoleMapper;
import com.swpu.sharebook.service.RoleService;
import com.swpu.sharebook.shiro.util.UserUtil;
import com.swpu.sharebook.util.Tools;
import com.swpu.sharebook.util.returnvalue.ResponseResult;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
@Resource
private RoleMapper roleMapper;
@Override
public ResponseResult getDontAudientRole() {
//1:获取用户的数据
List<UserRole> userNameAndRoleNames=roleMapper.getUserNameAndRoleName();
return ResponseResult.SUCCESS(userNameAndRoleNames);
}
@Override
public ResponseResult updateOrDelete(Integer id, boolean flag) {
if(Tools.isNull(id)){
return ResponseResult.ERROR(601,"用户升级的角色不能为空");
}
UserRole userRole=roleMapper.getUserRoleById(id);
if (Tools.isNull(userRole)) {
return ResponseResult.ERROR(602, "没有对应的用户申请授权");
}
if(userRole.getTId()==0){
return ResponseResult.ERROR(603,"已经升级完成了");
}
int temp=userRole.getTId();
//将用户升级的tid置为0
userRole.setTId(0);
roleMapper.alertTid(userRole);
if (flag) {
//增加用户字段
userRole.setDate(new Date());
userRole.setTId(temp);
roleMapper.addUserRole(userRole);
return ResponseResult.SUCCESSM("权限升级成功");
}
return ResponseResult.SUCCESSM("拒绝成功");
}
@Override
public ResponseResult upToIncreaseRole(UserRole userRole) {
//用户申请
if(Tools.isNull(userRole.getId())){
return ResponseResult.ERROR(611,"id不能为空");
}
if(Tools.isNull(userRole.getTId())){
return ResponseResult.ERROR(612,"角色id是必填项");
}
//包含了需要更新的角色就不能进行申请
//查询该用户是否有该角色
//当前用户i设置进去
if(userRole.getTId()>=4){
return ResponseResult.ERROR(613,"超出您所能够申请的角色范围了");
}
Integer uId=UserUtil.getUserId();
userRole.setUId(uId);
List<UserRole> userRole1s= roleMapper.getRoleListByIdAndUserId(userRole);
int temp=1;
for(int i=0;i<userRole1s.size();i++){
//求目前用户的最大值
if(userRole1s.get(i).getRId()==userRole.getTId()){
return ResponseResult.ERROR(614,"您已经成为了这个角色,请不要重复操作");
}
if(userRole1s.get(i).getRId()>temp){
temp=userRole1s.get(i).getRId();
}
if(userRole1s.get(i).getTId()==userRole.getTId()){
return ResponseResult.ERROR(615,"您已经申请过了,请等待管理员审核");
}
}
//最后两部是
if(temp<userRole.getTId()&&(temp+1)==userRole.getTId()) {
roleMapper.alertTid(userRole);
return ResponseResult.SUCCESSM("等待管理员审核");
}else{
return ResponseResult.ERROR(617,"您的选择误,请重新操作");
}
}
}
|
Markdown
|
UTF-8
| 5,622
| 3.28125
| 3
|
[] |
no_license
|
# Django REST Framework & Docker
A Beginner’s Guide to Docker
- With Docker it doesn’t matter if you are using a Mac, Windows, or Linux computer anymore. The entire development environment is isolated: programming language, software packages, databases, and more.
- With Docker we now longer have to mess around with virtual environments. We can faithfully reproduce a production environment locally. And Docker can be shared among team members so everyone is working on the same setup. Wins all around.
## Linux Containers
- Docker is really just Linux containers which are a type of virtualization.
- Virtualization has its roots at the beginning of computer science when large, expensive mainframe computers were the norm. How could multiple programmers use the same single machine? The answer was virtualization and specifically virtual machines which are complete copies of a computer system from the operating system on up.
- If you rent space on a cloud provider like AWS they are typically not providing you with a dedicated piece of hardware. Instead you are probably sharing a physical server with hundreds or even thousands of other clients.
- What’s the downside to a virtual machine? Size and speed. A typical guest operating system can easily take up 700MB of size. So if one physical server supports three virtual machines, that’s at least 2.1GB of disk space taken up along with separate needs for CPU and memory resources.
## Containers vs Virtual Environments
- If you are a Python programmer (like me) a common question at this point is, what about virtual environments? How do they differ from containers?
- Virtual environments are used to isolate Python software packages locally. We can create an isolated box for individual projects so one can use Python 2.7 and Django 1.5 while another can use Python 3.5 and Django 2.1 on the same computer. Virtual environments are great.
- But…virtual environments can only isolate Python packages. They still rely on a global, system-level installation of Python albeit they can refer to the proper version. So when we use Python 2.7 in a project, we’re pointing to an installation of Python 2.7 on the computer itself, not actually within the virtual environment.
- Also we can’t run a production database or other services within virtual environments so compared to Docker containers they are far more limited.
## Install Docker
- Docker Compose is an additional tool that is automatically included with Mac and Windows downloads of Docker. However if you are on Linux, you will need to add it manually. You can do this by running the command sudo pip install docker-compose after your Docker installation is complete.
- To confirm Docker installed correctly we can run our first command docker run hello-world
## Images and Containers
Images and containers are the two fundamental concepts to grasp when you start with Docker. An image is a snapshot in time of what a project contains. A container is a running instance of the image.
When we ran hello-world we used an official Docker image. We did not have to create the image ourself. But typically we will create custom images and we do so using a Dockerfile. We also will use docker-compose.yml files to run the containers.
## A baking analogy we can use here is as follows:
- A Dockerfile is the recipe for a cake
- An image is a snapshot of the recipe at a given time
- A docker-compose.yml says how to make the cake
-And the container is the actual, baked cake
## Conclusion
- Docker is a way to run Linux containers
- Containers are a lightweight alternative to Virtual Machines
- Dockerfile is a list of instructions for creating an image
- Images are made up of one or more layers
- Containers are a running instance of an image
- docker-compose.yml controls how to run the container
- Containers are stateless and ephemeral in nature. We can link the local filesystem via volumes but things become more - complex with databases
## Library Website and API
Django REST Framework works alongside the Django web framework to create web APIs. We cannot build a web API with only Django Rest Framework; it always must be added to a project after Django itself has been installed and configured.
The most important takeaway is that Django creates websites containing webpages, while Django REST Framework creates web APIs which are a collection of URL endpoints containing available HTTP verbs that return JSON.
To illustrate these concepts, we will build out a basic Library website with traditional Django and then extend it into a web API with Django REST Framework.
The files have the following roles:
init.py is a Python way to treat a directory as a package; it is empty
asgi.py stands for Asynchronous Server Gateway Interface and is a new option in Django 3.0+
settings.py contains all the configuration for our project
urls.py controls the top-level URL routes
wsgi.py stands for Web Server Gateway Interface and helps Django serve the eventual web pages
manage.py executes various Django commands such as running the local web server or creating a new app.
admin.py is a configuration file for the built-in Django Admin app
apps.py is a configuration file for the app itself
the migrations/ directory stores migrations files for database changes
models.py is where we define our database models
tests.py is for our app-specific tests
views.py is where we handle the request/response logic for our web app
A serializer : translates data into a format that is easy to consume over the internet, typically JSON, and is displayed at an API endpoint
|
Python
|
UTF-8
| 53
| 3.0625
| 3
|
[] |
no_license
|
name = raw_input('input name')
print 'name is ', name
|
Java
|
UTF-8
| 2,143
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package smsfrompc.com.smsfrompc.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import smsfrompc.com.smsfrompc.Activities.HistoryActivity;
import smsfrompc.com.smsfrompc.Entities.Classes.Contact;
import smsfrompc.com.smsfrompc.Entities.Classes.HistoryMessage;
import smsfrompc.com.smsfrompc.Managers.TimeDisplayManager;
import smsfrompc.com.smsfrompc.R;
public class HistoryListAdapter extends ArrayAdapter<HistoryMessage> {
private Context mContext;
int mResource;
public HistoryListAdapter(@NonNull Context context, int resource, @NonNull List<HistoryMessage> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
String recipientName = getItem(position).getRecipientName();
String recipientNumber = getItem(position).getRecipientNumber();
String delayTime = getItem(position).getDelayTime();
String scheduleFormat = getItem(position).getScheduleFormat();
String date = getItem(position).getDate();
String text = getItem(position).getText();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView tvName = convertView.findViewById(R.id.nameTextView);
TextView tvNumber = convertView.findViewById(R.id.numberTextView);
TextView tvDelay = convertView.findViewById(R.id.delayTimeTextView);
TextView tvDate = convertView.findViewById(R.id.dateTextView);
tvName.setText(recipientName);
tvNumber.setText(recipientNumber);
tvDelay.setText(TimeDisplayManager.transformSecondsToUserSetFormat(delayTime));
tvDate.setText(date);
return convertView;
}
}
|
Shell
|
UTF-8
| 988
| 3.84375
| 4
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
#!/usr/bin/env bash
# Starts a GCS cluster, runs scripts, then deletes the cluster.
# The cluster is only deleted if all the scripts run successfully, to allow for debugging.
# The cluster will automatically be deleted in any case after 3 hours.
if [ -z "$GCS_CLUSTER" ]; then
echo "Please set the GCS_CLUSTER environment variable to the name of the cluster you would like to start."
exit 1
fi
# Create cluster
gcloud beta dataproc clusters create "$GCS_CLUSTER" \
--zone us-central1-a \
--master-machine-type n1-standard-4 \
--master-boot-disk-size 1000 \
--num-workers ${NUM_WORKERS:-10} \
--worker-machine-type n1-standard-16 \
--worker-boot-disk-size 2000 \
--image-version 1.3 \
--max-age 3h \
--project broad-gatk-collab
# Run scripts
for script in "$@"
do
eval "$script" || (echo "Script $script returned exit status $?, exiting. NOT deleting cluster immediately." && exit 1)
done
# Delete cluster
gcloud dataproc clusters delete --quiet "$GCS_CLUSTER"
|
Java
|
UTF-8
| 1,043
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package mod.badores.ore;
import cpw.mods.fml.relauncher.Side;
import mod.badores.util.FakePlayerDetection;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import java.util.List;
/**
* @author diesieben07
*/
public class Wannafite extends AbstractOre {
private static final DamageSource wannafiteDamage = new DamageSource("badores.wannafite");
@Override
protected void addOreDrops(World world, int x, int y, int z, int meta, int fortune, List<ItemStack> drops) {
drops.add(new ItemStack(Items.iron_sword, 1, rand.nextInt(100) + 100));
}
@Override
public void onHarvest(EntityPlayer miner, World world, int x, int y, int z, Side side, boolean isIngotBlock) {
if (FakePlayerDetection.isFakePlayer(miner)) return;
miner.attackEntityFrom(wannafiteDamage, 4);
}
@Override
public String getName() {
return "wannafite";
}
}
|
C
|
UTF-8
| 321
| 3.65625
| 4
|
[] |
no_license
|
#include<stdio.h>
#include<math.h>
int main()
{
double i;
for(i=1.0; i<101.0; i++)
{
printf("The Square root of %lf is %lf\n",i,sqrt(i));
printf("Whole Number part: %d",(int)sqrt(i));
printf("Fractional part: %lf\n",sqrt(i)-(int)sqrt(i));
printf("\n");
}
return 0;
}
|
Markdown
|
UTF-8
| 188
| 2.671875
| 3
|
[] |
no_license
|
# simple-shop
Simple shop is a basic beginner level JAVA application , which uses mysql as its database<br>
# Requirements <br>
JAVA compiler<br>
MYSQL <br>
Any IDE(Netbeans is preferred)
|
Python
|
UTF-8
| 2,355
| 2.859375
| 3
|
[] |
no_license
|
import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
class Mymodel(keras.Model):
def __init__(self):
super(Mymodel, self).__init__()
self.CRNN = keras.Sequential([
## CNN layers
keras.layers.Conv2D(filters=64, kernel_size=3,activation='relu', padding='same'),
keras.layers.MaxPool2D(),
keras.layers.Conv2D(filters=64, kernel_size=3,activation='relu',padding='same'),
keras.layers.MaxPool2D(),
keras.layers.Conv2D(filters=64, kernel_size=3,activation='relu',padding='same'),
keras.layers.MaxPool2D(),
keras.layers.Conv2D(filters=64, kernel_size=3,activation='relu',padding='same'),
keras.layers.MaxPool2D(),
keras.layers.Reshape(target_shape=(2*10, 64)),
## RNN layers
keras.layers.LSTM(128, return_sequences=False),
## fully conected layers
keras.layers.Dense(10, activation='softmax')
])
def call(self,x):
return self.CRNN(x)
def load_dataset(path):
X = []
for i in range(1,10):
data = np.load(path+'dataX'+ str(i) +'.npz')
X.append(data['arr'])
Y = np.load(path+'dataY.npz')
Y = np.array(Y['arr'])
X1 = X[0]
for i in range(1,len(X)):
X1 = np.concatenate((X1,X[i]))
return X1,Y
if __name__ == '__main__':
X,Y=load_dataset('data/')
print(X.shape, Y.shape)
## shuffle the datasets, makes train better
idx = np.arange(8732)
np.random.shuffle(idx)
## [0,6986) train 80% ; [6986,8732) test 20%
Xs,Ys = X[idx],Y[idx]
trainX, testX = Xs[0:6986],Xs[6986:8732]
trainY, testY = Ys[0:6986],Ys[6986:8732]
print(trainX.shape, trainY.shape)
print(testX.shape, testY.shape)
# reshape the train data
trainX = trainX.reshape((-1,40,173,1))
testX = testX.reshape((-1,40,173,1))
print(trainX.shape, testX.shape)
## build the model
model=Mymodel()
model.compile(optimizer=keras.optimizers.Adam(),
loss = keras.losses.CategoricalCrossentropy(),
metrics=['accuracy'])
## fit the model
model.fit(trainX, trainY, batch_size=64, epochs=10)
## test the model
model.evaluate(testX,testY)
|
PHP
|
UTF-8
| 5,109
| 2.6875
| 3
|
[] |
no_license
|
<?php
require_once __DIR__ . '/../services/__require__.php';
require_once __DIR__ . '/../models/__require__.php';
require_once __DIR__ . '/Service.php';
/**
* @property User $user
* @property AppData $data
*
* @property WalkerData $walkerData;
* @property UserData $userData;
* @property UserMessages $userMessages;
* @property DogData $dogData;
*/
class App
{
protected ?PDO $db;
protected static array $routes = [
];
public function __construct(array $routes = [])
{
session_start();
$this->db = connect_database();
$this->getUser();
self::$routes = $routes;
}
// region User Data
protected ?User $_user = null;
protected ?UserInfo $_userInfo = null;
public function getUser(): User
{
if ($this->_user !== null) return $this->_user;
$this->_user = new User([
"role" => "guest",
]);
if (isset($_SESSION['logged-in-user']))
{
$userId = $_SESSION['logged-in-user'];
$user = $this->userData->getUserById($userId);
if (!$user) unset($_SESSION['logged-in-user']);
$user->info = $this->userData->getUserInfo($user);
$this->_user = $user;
}
return $this->_user;
}
// endregion
// region App Data
protected ?AppData $_data = null;
public function getData(): AppData
{
if ($this->_data !== null) return $this->_data;
$this->_data = new AppData([
// TODO
]);
return $this->_data;
}
// endregion
// region Services
protected array $_classes = [];
public function getClass(string $className): Service
{
if (isset($this->_classes[$className])) return $this->_classes[$className];
$class = ucfirst($className);
$this->_classes[$className] = new $class($this, $this->db);
return $this->_classes[$className];
}
// endregion
// region API
public function action($actionName)
{
http_response_code(500);
if (!isset(self::$routes[$actionName])) return $this->respond([
"error" => "Akció nincs definiálva!"
]);
$action = self::$routes[$actionName];
$className = $action[0];
$method = $action[1];
$handler = new $className($this, $this->db);
$response = $handler->$method($_REQUEST);
$this->respond($response);
}
public function respond($data): string
{
$data = json_decode(json_encode($data), true);
$json = json_encode($data);
header('Content-Type: application/json; charset=utf-8');
$status = 204;
if (sizeof($data) > 0) $status = 200;
if (isset($data['error'])) $status = 500;
http_response_code($status);
echo $json;
return $json;
}
// endregion
// region Frontend
protected static string $currentView;
public function parseView($viewName, $params = []): string
{
$viewName = trim($viewName, '/');
$currentView = str_replace('/', '-', $viewName);
if (!isset(self::$currentView)) self::$currentView = $currentView;
$currentView = self::$currentView;
$this->_data = new AppData([
"viewName" => $currentView,
]);
$viewPath = realpath(__DIR__ . "/../views");
$userType = ($this->user->role ?? 'guest');
$viewFileOptions[] = "{$viewPath}/roles/$userType/$viewName.php";
if ($userType !== 'guest')
$viewFileOptions[] = "{$viewPath}/roles/user/$viewName.php";
$viewFileOptions[] = "{$viewPath}/$viewName.php";
$data = $this->getData();
$app = $this;
extract($params);
@ob_start();
$viewRendered = false;
foreach ($viewFileOptions as $viewFile)
if (file_exists($viewFile)) {
$viewRendered = true;
include $viewFile;
break;
}
if (!$viewRendered)
{
$this->_data = new AppData([
"viewName" => $currentView,
"siteType" => 'error',
]);
/** @noinspection PhpIncludeInspection */
include "{$viewPath}/error.php";
}
$compiledView = ob_get_contents();
@ob_end_clean();
return $compiledView;
}
public function renderPage($viewName)
{
$viewName = trim($viewName, '/');
$currentView = str_replace('/', '-', $viewName);
self::$currentView = $currentView;
echo $this->parseView($viewName);
}
public function render($viewName)
{
echo $this->parseView($viewName);
}
// endregion
// region Helpers
public function __get(string $name)
{
switch ($name) {
case "user":
return $this->getUser();
case "data":
return $this->getData();
default:
return $this->getClass($name);
}
}
// endregion
}
|
Markdown
|
UTF-8
| 3,593
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
# Last.fm Top 10 Album Image Generator [](http://stillmaintained.com/yesdevnull/Lastfm-Album-Image-Generator)
By Dan Barrett - [yesdevnull.net/lastfm](http://yesdevnull.net/lastfm)
Easily get images for a top 10 list for your Last.fm profile.
## What It Is?
I'm using this on my website to generate [Last.fm](http://www.last.fm) album artwork - you can see it on [my profile here](http://last.fm/user/yesdevnull).
Originally, my image generator was a pretty rushed job and didn't look very pretty. I started using Laravel recently and decided to port my code over to Laravel, with the goal of open sourcing this codebase.
I have limited the code to max out at the first 10 albums from the Last.fm API, but if you know what you're doing, you can modify it to pull down much more.
## What It Does
By providing your Last.fm username and the album number in a query string you'll get the image returned.
```
?user=yourusername&num=1
```

You can also get a link returned instead of an image so you can have a URL that will redirect users to the Last.fm album page. To do this, add the variable `type` with the value `link` - or `&type=link`.
## Generator

If you enter the address `/generator` you'll land on an HTML form where you can enter your Last.fm username and get the BBCode required for Last.fm's profile page.
## Requires
* PHP 5.4 or greater
While this codebase is based on Laravel 4 ([laravel/framework](https://github.com/laravel/framework)), you'll also need a few other libraries. While these are listed in the `composer.json` file, you'll find the list below:
* [laravel/framework](https://github.com/laravel/framework)
* [intervention/image](https://github.com/Intervention/image)
* [nesbot/carbon](https://github.com/briannesbitt/Carbon)
* [pda/pheanstalk](https://github.com/pda/pheanstalk)
* [guzzle/guzzle](https://github.com/guzzle/guzzle)
* [phpunit/phpunit](https://github.com/sebastianbergmann/phpunit)
* [whatthejeff/nyancat-phpunit-resultprinter](https://github.com/whatthejeff/nyancat-phpunit-resultprinter)
You'll also need to be running [Beanstalkd](http://kr.github.io/beanstalkd/), a simple, fast work queue system if you want to use the queuing system in Laravel. If you don't have it installed and working, the queue system will process straight away, rather than being a proper queue system...
## Getting It Running
Once you've pulled down the codebase, it's important to do a few things. First off, using composer you should install the rest of the dependancies:
```
composer update
```
Or `php composer.phar update` if Composer isn't in your bin path.
Next, you should run
```
php artisan key:generate
```
This will change the application key, as each installation should have a different, unique key. Composer should hopefully do this already for you, but there's no harm in running it again.
You may also find that you need to change the default Queue driver in `app/config/queue.php` to `sync` if you're not using Beanstalkd.
## Unit Testing
I've written some tests, but it's my first time doing unit tests and using PHPUnit. In its current state, there are 21 tests and 77 assertions, and all should pass. I also spent some time making sure it's __mostly__ compliant with PSR-1 and PSR-2. As my codebase isn't namespaced, PHP_CodeSniffer will freak out a bit.
|
JavaScript
|
UTF-8
| 2,978
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
import {encodeForAjax} from './utils.js';
window.addEventListener('load', function() {
let form = document.getElementById('search_form');
form.onsubmit = function() {
let date1 = document.querySelector('input[name="start_date"]').value;
let date2 = document.querySelector('input[name="end_date"]').value;
let guests = document.querySelector('input[name="sleeps"]').value;
let parts = window.location.search.substr(1).split("&");
let $_GET = {};
for (let i = 0; i < parts.length; i++) {
let temp = parts[i].split("=");
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
let property_id = $_GET['property'];
let request = new XMLHttpRequest();
request.open("post", "../actions/action_check_reservation.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.onload = checkReservation;
request.send(encodeForAjax({
"property": property_id,
"start": date1,
"end": date2,
"guests": guests
}));
return false;
};
let start_date = document.querySelector('input[name="start_date"]');
start_date.onchange = function(event) {
let end_date = document.querySelector('input[name="end_date"]');
let new_end_date = addDays(event.target.value, 1);
end_date.min = new_end_date;
if(end_date.value <= event.target.value) {
end_date.value = new_end_date;
}
};
});
function checkReservation() {
let response;
try {
response = JSON.parse(this.responseText);
} catch(e) {
console.log("Error parsing");
return false;
}
let dates=document.querySelectorAll('input[type="date"]');
if(response.exists) {
dates.forEach(element => {
element.style.borderColor = "red";
});
}
if(response.over_limit) {
document.querySelector('input[name="sleeps"]').style.borderColor = "red";
}
if(!response.exists) {
dates.forEach(element => {
element.style.borderColor = null;
});
}
if(!response.over_limit) {
document.querySelector('input[name="sleeps"]').style.borderColor = null;
}
if(!response.exists && !response.over_limit) {
let form = document.getElementById('search_form');
form.submit();
return true;
}
return false;
}
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return formatDate(result);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
|
Python
|
UTF-8
| 466
| 3.765625
| 4
|
[] |
no_license
|
import sys
values = input("Digite um sequencia de numeros separado por espaço:")
values_list = values.split(" ")
invalid_value = ""
final_value = 0
for value in values_list:
if not value.isdigit():
invalid_value = value
else:
final_value += int(value)
if invalid_value != "":
print(
f"Erro ao somar valores, {invalid_value} é um valor inválido",
file=sys.stderr,
)
else:
print(f"Final value: {final_value}")
|
Markdown
|
UTF-8
| 2,444
| 3.75
| 4
|
[] |
no_license
|
# Tic Tac Toe
### Contributors:
- [Christina Cook](https://github.com/christina-cook)
### Technologies Used:
- JavaScript
- HTML
- CSS
### Overview
The main learning goals of this project centered around solidifying and demonstrating an understanding of local storage, event delegation, and DRY JavaScript. There was a strong emphasis on creating a data model before manipulating/displaying data on the DOM. The end goal was to build a functional tic tac toe game as a front-end application.

### Code Architecture
The JavaScript for this project was divided into three separate files. The player.js file contains the Player class which stores the data for each player in addition to methods for saving and retrieving data from local storage. The game.js file contains the primary data model for the application, including the Game class and all the methods used to play each game. The main.js file is responsible for all DOM related manipulation and connects all three files together in order to display everything on the page.
### Instructions:
Playing Tic Tac Toe is easy! To play, each player takes a turn placing a token on the board by clicking an empty square. Once you get three tokens in a row, you win! If the game ends in a draw (nobody wins), the game is a tie. We keep track of your wins for you, which you'll see displayed to the left and right of the board. Feel free to end a game or close the page at any time. When you come back to play, your number of wins will still be there!

### Wins:
- Through this project, I gained a better understanding of local storage and manipulating the DOM using a data model.
- I learned how to refactor code to make it more dynamic so that I could reuse blocks of code instead of having a lot of repeats.
- I gained a better understanding of flex box and learned how to utilize grid in the CSS design.
- I was able to break down a complex problem and devise my own plan that in the end resulted in a fully-functional game!
### Challenges:
- Thinking data model first and DOM second was a confusing concept at first, but I learned how to get the two to work together in the end.
- The game's functionality itself had its ups and downs. I often found that once I got one feature to work, another would break. I used the console in the dev tools a lot to figure out and fix bugs.
|
Java
|
UTF-8
| 599
| 2.390625
| 2
|
[] |
no_license
|
package window.view.components.buttons;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import org.kordamp.ikonli.javafx.FontIcon;
import window.Theme;
public class AcceptButton extends Button {
public AcceptButton(Pane rootPane) {
FontIcon icon = new FontIcon();
icon.setIconLiteral("anto-check");
icon.setIconSize(Theme.ICON_SIZE);
icon.setIconColor(Theme.COLOR_BLUE);
this.setMinWidth(Theme.BTN_WIDTH);
this.setText("Принять");
this.setGraphic(icon);
rootPane.getChildren().add(this);
}
}
|
Java
|
UTF-8
| 1,140
| 2.203125
| 2
|
[] |
no_license
|
package com.decode.skapaBooking;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.decode.objects.Pago;
import com.decode.objects.Usuario;
public class TestPago {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetCantidad() {
Usuario usuarioA = new Usuario("Paco","paco@gmail.com","123");
Usuario usuarioB = new Usuario("Lucia","lucia@gmail.com","323");
Pago Pago1= new Pago(50,usuarioA,usuarioB);
assertEquals(Pago1.getCantidad(),50,0);
}
@Test
public void testGetUsuarioEmisor() {
Usuario usuarioA = new Usuario("Paco","paco@gmail.com","123");
Usuario usuarioB = new Usuario("Lucia","lucia@gmail.com","323");
Pago Pago1= new Pago(50,usuarioA,usuarioB);
assertEquals(Pago1.getUsuarioEmisor(),usuarioA);
}
@Test
public void testGetUsuarioReceptor() {
Usuario usuarioA = new Usuario("Paco","paco@gmail.com","123");
Usuario usuarioB = new Usuario("Lucia","lucia@gmail.com","323");
Pago Pago1= new Pago(50,usuarioA,usuarioB);
assertEquals(Pago1.getUsuarioReceptor(),usuarioB);
}
}
|
C#
|
UTF-8
| 520
| 2.78125
| 3
|
[] |
no_license
|
using System;
namespace Bdf
{
[Serializable]
public class BdfException : Exception
{
public BdfException():base()
{ }
public BdfException(string message)
: base(message)
{
}
public BdfException(string message, Exception innerException)
: base(message, innerException)
{
}
public BdfException(string format, params object[] args)
: base(string.Format(format, args))
{ }
}
}
|
Python
|
UTF-8
| 235
| 3.65625
| 4
|
[] |
no_license
|
import string
x,y,z= "apple" , "orange" ,"limon"
basket = x + y + z
print(basket)
print(basket.split('e',3))
n = 5
print([basket[i:i+n] for i in range(0, len(basket), n)])
basket = x +" "+ y+" " + z
print(basket)
print(basket.split())
|
Rust
|
UTF-8
| 13,750
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
#[macro_use]
mod macros;
test!(
basic_toplevel,
"@media foo {\n a {\n color: red;\n }\n}\n",
"@media foo {\n a {\n color: red;\n }\n}\n"
);
error!(
no_params,
"@media {\n a {\n color: red;\n }\n}\n", "Error: Expected identifier."
);
test!(
basic_nested,
"a {\n @media foo {\n color: red;\n }\n}\n",
"@media foo {\n a {\n color: red;\n }\n}\n"
);
test!(empty_body, "@media (min-width: 2px) {}", "");
test!(
newlines_are_not_emitted_for_child_styles,
"a {
@media screen {
b {
color: red;
}
c {
color: green;
}
}
}",
"@media screen {\n a b {\n color: red;\n }\n a c {\n color: green;\n }\n}\n"
);
test!(
multiple_identifiers_in_query,
"@media not screen {
a {
color: red;
}
}",
"@media not screen {\n a {\n color: red;\n }\n}\n"
);
test!(
multiple_identifiers_in_query_second_is_and,
"@media print and (foo: 1 2 3) {
a {
color: red;
}
}",
"@media print and (foo: 1 2 3) {\n a {\n color: red;\n }\n}\n"
);
test!(
single_identifier_inside_parens,
"@media (color) {a {color: red;}}",
"@media (color) {\n a {\n color: red;\n }\n}\n"
);
test!(
quoted_colon_in_parens,
"@media screen and (\":\") {
a {
color: red;
}
}",
"@media screen and (:) {\n a {\n color: red;\n }\n}\n"
);
test!(
multiline_comments_everywhere,
"@media/**/foo/**/and/**/(/**/bar/**/)/**/{
a {
color: red;
}
}",
"@media foo and (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
comparison_in_query,
"@media (100px < 400px) {
a {
interpolation: in-parens
}
}",
"@media (100px < 400px) {\n a {\n interpolation: in-parens;\n }\n}\n"
);
test!(
interpolated_comparison_in_query,
"@media (#{100px < 400px}) {
a {
interpolation: in-parens
}
}",
"@media (true) {\n a {\n interpolation: in-parens;\n }\n}\n"
);
test!(
single_eq_in_query,
"@media (height=600px) {
a {
b: c
}
}
",
"@media (height = 600px) {\n a {\n b: c;\n }\n}\n"
);
test!(
double_eq_in_query,
"@media (height==600px) {
a {
b: c
}
}
",
"@media (false) {\n a {\n b: c;\n }\n}\n"
);
test!(
newline_emitted_for_different_toplevel_rulesets,
"@media print {
a {
color: red;
}
b {
color: green;
}
}",
"@media print {\n a {\n color: red;\n }\n b {\n color: green;\n }\n}\n"
);
test!(
removes_media_if_all_children_are_blank,
"@media foo {
a {}
}",
""
);
test!(
correct_order_of_children_when_merging,
"@media (foo) {
@media (bar) {
a {
color: red;
}
}
a {
color: red;
}
}",
"@media (foo) and (bar) {\n a {\n color: red;\n }\n}\n@media (foo) {\n a {\n color: red;\n }\n}\n"
);
test!(
newline_emitted_before_media_when_following_ruleset,
"a {
color: red;
}
@media print {
a {
color: red;
}
}",
"a {\n color: red;\n}\n\n@media print {\n a {\n color: red;\n }\n}\n"
);
test!(
no_newline_emitted_between_two_media_rules,
"@media print {
a {
color: red;
}
}
@media print {
a {
color: red;
}
}",
"@media print {\n a {\n color: red;\n }\n}\n@media print {\n a {\n color: red;\n }\n}\n"
);
test!(
no_newline_emitted_between_two_media_rules_when_in_same_ruleset,
"a {
@media foo {
color: red;
}
@media bar {
color: green;
}
}",
"@media foo {\n a {\n color: red;\n }\n}\n@media bar {\n a {\n color: green;\n }\n}\n"
);
test!(
allows_interpolated_at_rule,
"@#{media} (true) {
a {
color: red;
}
}",
"@media (true) {\n a {\n color: red;\n }\n}\n"
);
test!(
no_newline_between_two_media_following_ruleset,
"a {
color: red;
}
@media (min-width: 0px) {
a {
color: red;
}
}
@media (min-width: 0px) {
a {
color: red;
}
}",
"a {\n color: red;\n}\n\n@media (min-width: 0px) {\n a {\n color: red;\n }\n}\n@media (min-width: 0px) {\n a {\n color: red;\n }\n}\n"
);
test!(
no_newline_after_media_after_ruleset,
"a {
color: red;
}
@media (min-width: 0px) {
b {
color: red;
}
}
d {
color: red;
}",
"a {\n color: red;\n}\n\n@media (min-width: 0px) {\n b {\n color: red;\n }\n}\nd {\n color: red;\n}\n"
);
test!(
no_newline_after_media_when_outer,
"@media (min-width: 0px) {
b {
color: red;
}
}
d {
color: red;
}",
"@media (min-width: 0px) {\n b {\n color: red;\n }\n}\nd {\n color: red;\n}\n"
);
test!(
newline_after_media_when_inner,
"a {
@media (max-width: 0px) {
color: red;
}
}
a {
color: red;
}",
"@media (max-width: 0px) {\n a {\n color: red;\n }\n}\n\na {\n color: red;\n}\n"
);
test!(
nested_media_with_compatible_queries,
"@media (foo) {
@media (bar) {
a {
color: red;
}
}
}",
"@media (foo) and (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
nested_media_with_incompatible_queries,
"@media foo {
@media bar {
a {
color: red;
}
}
}",
""
);
test!(
removes_media_if_all_children_are_placeholder,
"@media foo {
%a {
color: red;
}
}",
""
);
test!(
plain_import_inside_media_is_not_moved_to_top,
r#"@media foo {
a {
color: red;
}
@import "foo.css";
}"#,
"@media foo {\n a {\n color: red;\n }\n @import \"foo.css\";\n}\n"
);
error!(
media_feature_missing_closing_paren,
"@media foo and (bar:a", "Error: expected \")\"."
);
error!(
media_feature_missing_curly_brace_after_hash,
"@media foo and # {}", "Error: expected \"{\"."
);
error!(
// note: dart-sass gives error "Expected expression"
nothing_after_not_in_parens,
"@media (not", "Error: Expected whitespace."
);
error!(
nothing_after_and,
"@media foo and", "Error: Expected whitespace."
);
error!(nothing_after_or, "@media foo or", r#"Error: expected "{"."#);
error!(
no_parens_after_and,
"@media foo and bar {
a {
color: red;
}
}",
"Error: expected media condition in parentheses."
);
test!(
query_starts_with_interpolation,
"@media #{foo} {
a {
color: red;
}
}",
"@media foo {\n a {\n color: red;\n }\n}\n"
);
test!(
query_is_parens_with_comma,
"@media (foo, bar) {
a {
color: red;
}
}",
"@media (foo, bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_is_parens_with_space_before_comma,
"@media (foo , bar) {
a {
color: red;
}
}",
"@media (foo, bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_and_first_has_no_parens,
"@media foo and (bar) {
a {
color: red;
}
}",
"@media foo and (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_comma_separated_list_both_parens,
"@media (foo), (bar) {
a {
color: red;
}
}",
"@media (foo), (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_comma_separated_list_both_parens_space_before_paren,
"@media (foo) , (bar) {
a {
color: red;
}
}",
"@media (foo), (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_comma_separated_list_loud_comments,
"@media /**/foo/**/,/**/bar/**/ {
a {
color: red;
}
}",
"@media foo, bar {\n a {\n color: red;\n }\n}\n"
);
test!(
query_not_paren,
"@media not (color) {
a {
color: red;
}
}",
"@media not (color) {\n a {\n color: red;\n }\n}\n"
);
test!(
many_parens,
"@media (((color))) {
a {
color: red;
}
}",
"@media (((color))) {\n a {\n color: red;\n }\n}\n"
);
test!(
many_parens_around_and,
"@media ((screen and (color))) {
a {
color: red;
}
}",
"@media ((color)) {\n a {\n color: red;\n }\n}\n"
);
test!(
newline_between_media_rules_declared_at_root_inside_each,
"@each $a in 1 2 3 {
a {
@media foo {
b {
color: $a;
}
}
color: foo;
}
}",
"a {\n color: foo;\n}\n@media foo {\n a b {\n color: 1;\n }\n}\n\na {\n color: foo;\n}\n@media foo {\n a b {\n color: 2;\n }\n}\n\na {\n color: foo;\n}\n@media foo {\n a b {\n color: 3;\n }\n}\n"
);
test!(
newline_between_media_rules_declared_at_root_inside_each_with_preceding_style_rule,
"@each $a in 1 2 {
a {
color: red;
}
@media foo {
a {
color: $a;
}
}
}",
"a {\n color: red;\n}\n\n@media foo {\n a {\n color: 1;\n }\n}\na {\n color: red;\n}\n\n@media foo {\n a {\n color: 2;\n }\n}\n"
);
test!(
no_newline_between_media_rules_when_invisble_rule_between,
"a {}
@media (min-width: 5px) {
a {
color: 1;
}
}
a {}
@media (min-width: 5px) {
a {
color: 1;
}
}",
"@media (min-width: 5px) {\n a {\n color: 1;\n }\n}\n@media (min-width: 5px) {\n a {\n color: 1;\n }\n}\n"
);
test!(
two_media_rules_in_content_block,
"@mixin foo() {
@content;
}
@include foo {
@media foo {
a {
color: red;
}
}
@media foo {
b {
color: red;
}
}
}",
"@media foo {\n a {\n color: red;\n }\n}\n@media foo {\n b {\n color: red;\n }\n}\n"
);
test!(
splits_child_nodes_when_preceding_media,
"@media (foo) {
@media (prefers-reduced-motion: reduce) {
a {
transition: none;
}
}
a {
color: red;
}
a {
color: red;
}
}",
"@media (foo) and (prefers-reduced-motion: reduce) {\n a {\n transition: none;\n }\n}\n@media (foo) {\n a {\n color: red;\n }\n}\n@media (foo) {\n a {\n color: red;\n }\n}\n"
);
test!(
doesnt_split_child_nodes_when_trailing_media,
"@media (foo) {
a {
color: red;
}
a {
color: red;
}
@media (prefers-reduced-motion: reduce) {
a {
transition: none;
}
}
}",
"@media (foo) {\n a {\n color: red;\n }\n a {\n color: red;\n }\n}\n@media (foo) and (prefers-reduced-motion: reduce) {\n a {\n transition: none;\n }\n}\n"
);
test!(
#[ignore = "our is_invisible_check inside css tree is flawed here"]
doesnt_split_child_nodes_when_leading_but_invisible_media,
"@media (foo) {
@media (prefers-reduced-motion: reduce) {}
a {
color: red;
}
a {
color: red;
}
}",
"@media (foo) {\n a {\n color: red;\n }\n a {\n color: red;\n }\n}\n"
);
test!(
media_has_url_in_parens,
"@media (url) {
a {
color: red;
}
}",
"@media (url) {\n a {\n color: red;\n }\n}\n"
);
test!(
#[ignore = "our is_invisible_check inside css tree is flawed here"]
media_does_not_split_when_child_rule_has_invisible_media,
"@media (min-width: 1px) {
.first {
font-weight: 100;
@media (min-width: 2px) {}
}
.second {
font-weight: 200;
}
}",
"@media (min-width: 1px) {\n .first {\n font-weight: 100;\n }\n .second {\n font-weight: 200;\n }\n}\n"
);
test!(
escaped_nullbyte_in_query,
r#"@media (min-width:\0) {
a {
color: red;
}
}"#,
"@media (min-width: \\0 ) {\n a {\n color: red;\n }\n}\n"
);
test!(
simple_unmergeable,
"a {
@media a {
@media b {
color: red;
}
}
}",
""
);
test!(
query_is_identifier_and_not_parens,
"@media screen and not (foo) {
a {
color: red;
}
}",
"@media screen and not (foo) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_is_identifier_identifier_and_parens,
"@media only screen and (foo) {
a {
color: red;
}
}",
"@media only screen and (foo) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_is_paren_and_paren,
"@media (foo) and (bar) {
a {
color: red;
}
}",
"@media (foo) and (bar) {\n a {\n color: red;\n }\n}\n"
);
test!(
query_is_paren_or_paren,
"@media (foo) or (bar) {
a {
color: red;
}
}",
"@media (foo) or (bar) {\n a {\n color: red;\n }\n}\n"
);
error!(
media_query_has_quoted_closing_paren,
r#"@media ('a)'w) {
a {
color: red;
}
}"#,
"Error: expected no more input."
);
error!(
empty_query_after_resolving_interpolation,
"@media #{null} {}", "Error: Expected identifier."
);
|
Markdown
|
UTF-8
| 514
| 2.71875
| 3
|
[] |
no_license
|
使用early-stopping策略确定迭代次数
问:什么是early-stopping策略?
答:early-stopping策略是指当验证数据集的准确率达到饱和时停止迭代。
问:怎样算达到饱和?
答:例如最近10次迭代的准确率都没有提升。
问:为什么是10次?
10是一个经验数字。一开始可以稍微小一点。到后面应该适当调大。
早期不需要使用early-stoping策略停止迭代,因为需要overfitting的结果来调正则化参数。
|
Java
|
UTF-8
| 4,125
| 2.4375
| 2
|
[] |
no_license
|
package com.assignment.payroll.generator.render;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import com.assignment.payroll.generator.utils.CustomDateTimeModule;
import com.assignment.payroll.view.payslip.EmpPayslip;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Class responsible to generate employee payslip based on the {@link RenderType} types.
*
* @author Allwyn
*
*/
@Component("employeePayslipRenderer")
public class EmployeePayslipRenderer implements PayslipRenderer
{
private static Logger logger = LoggerFactory.getLogger(EmployeePayslipRenderer.class);
@Value(value = "classpath:output/json")
private Resource jsonOutputResource;
@Override
public void render(List<EmpPayslip> payslips, RenderType renderType) throws UnsupportedRenditionException, PayslipRendererException {
switch (renderType)
{
case CONSOLE:
renderOutputToConsole(payslips);
break;
case JSON_FILE:
renderOutputToJsonFile(payslips);
break;
default:
throw new UnsupportedRenditionException("Unsupported Render Type: " + renderType);
}
}
public void renderOutputToConsole(List<EmpPayslip> payslips) throws PayslipRendererException
{
if (payslips == null || payslips.isEmpty())
throw new PayslipRendererException("Cannot Render Employee Payslip(s)as object is null or empty.");
for (EmpPayslip payslip : payslips)
{
logger.info("Pay Period [{} - {}]", payslip.getPayPeriod().getStart(), payslip.getPayPeriod().getEnd());
logger.info("\tName: \t{} {}", payslip.getEmployee().getFirstName(), payslip.getEmployee().getLastName());
logger.info("\tGross Income: \t{}", payslip.getGrossIncome());
logger.info("\tIncome Tax: {}", payslip.getIncomeTax());
logger.info("\tNet Income: \t{}", payslip.getNetIncome());
logger.info("\tSuper Amount: \t{}", payslip.getSuperAmount());
logger.info("\n");
}
}
public void renderOutputToJsonFile(List<EmpPayslip> payslips) throws PayslipRendererException
{
if (payslips == null || payslips.isEmpty())
throw new PayslipRendererException("Cannot Render Employee Payslip(s)as object is null or empty.");
// generate output based on the given render type
logger.info("===******=== Rendering Payslip to File as JSON ===******===");
//final String location = "./output/json/";
String outputLoc = null;
try {
outputLoc = System.getProperty("json.output.home", jsonOutputResource.getURL().getPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String fileName = EmpPayslip.class.getSimpleName().toLowerCase();
writeObjectToJsonFile(payslips, outputLoc, fileName);
}
private static <T> void writeObjectToJsonFile(T objectToWrite, String location, String fname) throws PayslipRendererException
{
FileWriter fw = null;
BufferedWriter bw = null;
try {
// convert to json message
File file = new File(location + File.separator, fname + ".json");
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new CustomDateTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.writer().withoutAttribute("payStartDate");
mapper.writeValue(bw, objectToWrite);
logger.info("*** Generated OUTPUT to: {}.json", location + File.separator + fname);
}
catch (Exception e)
{
throw new PayslipRendererException("Error while rendering output to JSON file", e);
}
finally
{
if (bw != null)
try
{
fw.close();
}
catch (IOException e) {}
}
}
}
|
PHP
|
UTF-8
| 4,817
| 2.78125
| 3
|
[] |
no_license
|
<?php
/**
* Competency ACL implementation
*
* This is not yet used throughout the entire competency module, but it's a
* start at least.
*/
class competencyAcl {
/**
* User currently logged in
* @var array User record
*/
protected $user;
/**
* Constructor
*/
public function __construct() {
$this->user = atkGetUser();
}
/**
* Returns the profile id for the current user
* @return integer Profile id
*/
public function getProfile() {
$db = atkGetDb();
$query = $db->createQuery();
$query->addTable("competency_profile_person");
$query->addField("profile_id");
$query->addCondition("person_id='" . $db->escapeSQL($this->user['id']) . "'");
return $db->getValue($query->buildSelect(), 0);
}
/**
* Returns selectable employees
* @param array $fields Fields to include in the records
* @return array Selectable employees (indexed array of records)
*/
public function getSelectableEmployees(array $fields) {
$db = atkGetDb();
$query = $db->createQuery();
$query->addTable('person');
$query->addJoin('competency_profile_person', '', "person.id=competency_profile_person.person_id", true);
$query->addCondition("role='employee'");
$query->addCondition("status='active'");
$query->addOrderBy('firstname');
foreach($fields as $field) {
$query->addField($field);
}
$competencyNode = atkGetNode('competency.competencymatch');
if (!$competencyNode->allowed('show_all_users')) {
$profileQuery = $db->createQuery();
$profileQuery->addTable('competency_profile_privilege');
$profileQuery->addCondition("profile_id='" . $db->escapeSQL($this->getProfile()) . "'");
$profileQuery->addField('manages_profile_id');
$conditions = array();
$conditions[] = "id='" . $db->escapeSQL($this->user['id']) . "'";
$conditions[] = "competency_profile_person.profile_id IN (" . $profileQuery->buildSelect() . ")";
if ($competencyNode->allowed('show_own_team')) {
$conditions[] = "supervisor='" . $db->escapeSQL($this->user['id']) . "'";
}
$query->addCondition('(' . implode(' OR ', $conditions) . ')');
}
return $db->getRows($query->buildSelect());
}
/**
* Check if we're allowed to add or remove competencies for a user
* @param integer $userId
* @return boolean True if allowed
*/
public function allowCompetencyChange($userId) {
if ($this->user['id'] == $userId) {
return false;
}
$competencyNode = atkGetNode('competency.competencymatch');
if ($competencyNode->allowed('add')) {
return true;
} else {
$db = atkGetDb();
$query = $db->createQuery();
$query->addTable('competency_profile_person', 'manager');
$query->addJoin('competency_profile_privilege', 'privilege', 'manager.profile_id=privilege.profile_id', true);
$query->addJoin('competency_profile_person', 'employee', 'privilege.manages_profile_id=employee.profile_id', true);
$query->addCondition("manager.person_id='" . $db->escapeSQL($this->user['id']) . "'");
$query->addCondition("employee.person_id='" . $db->escapeSQL($userId) . "'");
$query->addField('COUNT(1)', 'allowed');
$allowed = $db->getValue($query->buildSelect());
return ($allowed == 1);
}
}
/**
* Check if we're allowed to set the profile for a user
* @param integer $userId
* @return boolean True if allowed
*/
public function allowSetProfile($userId) {
if ($this->user['id'] == $userId) {
return false;
}
$competencyNode = atkGetNode('competency.competencymatch');
if ($competencyNode->allowed('add')) {
if ($competencyNode->allowed('show_all_users')) {
return true;
} elseif ($competencyNode->allowed('show_own_team')) {
$db = atkGetDb();
$query = $db->createQuery();
$query->addTable('person');
$query->addCondition("id='" . $db->escapeSQL($userId) . "'");
$query->addCondition("supervisor='" . $db->escapeSQL($this->user['id']) . "'");
$query->addCondition("role='employee'");
$query->addCondition("status='active'");
$query->addField('COUNT(1)', 'allowed');
$allowed = $db->getValue($query->buildSelect());
return ($allowed == 1);
}
}
return false;
}
}
|
Java
|
UTF-8
| 3,001
| 2.609375
| 3
|
[] |
no_license
|
package cn.jly.hadoop.mapreduce;
import cn.jly.hadoop.hdfs.BaseConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
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.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
/**
* 统计输入文件中每一行的第一个单词相同的行数
* 输入
* banzhang ni hao
* xihuan hadoop banzhang
* banzhang ni hao
* xihuan hadoop banzhang
*
* @author lanyangji
* @date 2021/4/21 上午 9:33
* @packageName cn.jly.hadoop.mapreduce
* @className Mr04KeyValueTextInputFormat
*/
public class Mr04KeyValueTextInputFormatDriver extends BaseConfig {
public static void main(String[] args) throws Exception {
init();
final Configuration configuration = new Configuration();
// 配置k v分隔符
configuration.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, " ");
final Job job = Job.getInstance(configuration);
job.setJarByClass(Mr04KeyValueTextInputFormatDriver.class);
job.setMapperClass(KvTextMapper.class);
job.setReducerClass(KvTextReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.setInputPaths(job, new Path("E:\\kvtext\\input"));
FileOutputFormat.setOutputPath(job, new Path("E:\\kvtext\\output"));
// 设置inputFormat为KeyValueTextInputFormat
job.setInputFormatClass(KeyValueTextInputFormat.class);
final boolean result = job.waitForCompletion(true);
System.out.println(result ? 0 : 1);
}
/**
* mapper
*/
public static class KvTextMapper extends Mapper<Text, Text, Text, IntWritable> {
private final IntWritable v = new IntWritable(1);
@Override
protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
context.write(key, v);
}
}
/**
* reducer
*/
public static class KvTextReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private final IntWritable v = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
v.set(sum);
context.write(key, v);
}
}
}
|
PHP
|
UTF-8
| 765
| 2.609375
| 3
|
[] |
no_license
|
<?php
/**
* @author Duc Nguyen <ducntq@gmail.com>
* @link https://github.com/ducntq/Element
* @copyright Copyright © 2013-2013 GL Software
* @license https://github.com/ducntq/Element/License
*/
/**
* Controller class file
*
* Controller is a class that has no real actual code, but merely
* exists to help provide people with an understanding as to how the
* various PHPDoc tags are used.
*
* @package Element
* @since 0.1
*/
namespace Element\Web;
class Controller {
public $layout = 'main';
public $defaultAction = 'index';
public $pageTitle;
private $_id;
private $_action;
function __construct($id, $action = ''){
$this->_id = $id;
$this->_action = !empty($action) ? $action : $this->defaultAction;
}
}
|
Markdown
|
UTF-8
| 2,886
| 3.59375
| 4
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
# Brutetime
Let's say that you have something that you want to keep secret from yourself or a friend for a fixed period of time. At the time of this writing, there aren't any encryption methods that only allow decryption after a certain period of time. How then do we solve this issue?
Well, current encryption methods are only viable because there aren't machines powerful enough to brute force all possible keys in a reasonable amount of time.
Therefore, we can keep a secret from ourselves for a period of time by encrypting the value with a random key. This key should only be strong enough to withstand a brute force attack for an approximate amount of time given finite computing power.
## Disclaimer
I am not a cryptographer, do not use this for securing important data. No warranty is provided.
The purpose of this tool is to make it difficult, not impossible, for you to access your own or your friend's secret.
You may want to use a password manager such as LastPass or KeePass etc to secure your data.
## Installing
Simply clone the repo and install dependencies:
```
git clone https://github.com/si13b/brutetime.git
cd brutetime
npm install
```
It is expected that you already have NodeJS >= v6.0 installed.
## Usage
If you run the program incorrectly, you will get the usage message below.
```
Usage: brutetime [options] encrypt|decrypt
--size - Size in bits of the random key (roughly; 24bit <15m, 26bit <1h, 30bit <6h, 32bit <1w)
```
Test with different key sizes to find the approximate brute force time that you desire. The values will vary wildly depending on the computing power available.
NOTE: Decryption could take significantly less than the estimated maximum, if the key is in the lower bound of values.
### Encrypting a value
For example;
```
node brutetime.js encrypt mysecret123 --size 24
```
Results in:
```
# ENCRYPTING
* Encrypted Text: 3b50e6340e5477a5ba8ff4456d53a456
* Key size: 20bits
```
Keep the Encrypted Text (ciphertext) safe for later decryption. KeePass or LastPass is good for this.
You may want to clear your terminal history at this point to avoid secret retrieval via reverse lookup etc.
### Decrypting (brute forcing) a value
Using the ciphertext from the previous example:
```
node brutetime.js decrypt 3b50e6340e5477a5ba8ff4456d53a456 --size 24
```
The script will attempt to determine the random key via brute force method. It will give an estimate of how long this will take.
NOTE: The brute force method requires computing power. Expect higher CPU usage and operating temperatures for the duration of the decryption.
## Ideas
* Accuracy of decryption time could be increased by generating multiple random keys and splitting the secret up into separately encrypted parts.
* User interface
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
|
Java
|
UTF-8
| 849
| 2.09375
| 2
|
[] |
no_license
|
package com.podtube.repositories;
import com.podtube.common.UserRole;
import com.podtube.models.User;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface UserRepository
extends CrudRepository<User, Integer> {
//Admin findAllUsers
List<User> findAllByUserRoleEquals(UserRole userRole);
//Admin and Normal user, Find by user role and id
User findByIdEqualsAndUserRoleEquals(int userId, UserRole userRole);
//Admin login
User findUserByUsernameEqualsAndPasswordEqualsAndUserRoleEquals(String username,
String password,
UserRole userRole);
//Register User
User findUserByUsernameEquals(String username);
//Get by id
User findByIdEquals(int id);
long countAllByUserRoleEquals(UserRole userRole);
}
|
C#
|
UTF-8
| 583
| 2.921875
| 3
|
[] |
no_license
|
// Listing of CalcService.cs
using System;
using System.ServiceModel;
using System.Text;
namespace WCFCalcLib
{
public class CalcService : ICalcService
{
public double Add(double a, double b)
{
return (a + b);
}
public double Subtract(double a, double b)
{
return (a - b);
}
public double Multiply(double a, double b)
{
return (a * b);
}
public double Divide(double a, double b)
{
return ((b == 0) ? 0 : (a / b));
}
}
}
|
Markdown
|
UTF-8
| 2,800
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
## 两数相加
这道题难度是 medium ,AC 后我觉得完全没有昨天的 Easy 好做,开始怀疑 LeetCode 是不是搞错了哈哈。做的过程没有感觉到有多困难,但是最后输出 finalNode 的时候只丢出来了最后一个节点,突然想起来这是因为一直都在让 finalNode = finalNode.next ,然后开始陷入纠结中,稍微找到了点思路,肯定要用一个中间 node 去记录当前链,然后把每次生成的新节点添加到中间 node 上去,最后再把中间 node 每次都赋值给 finalNode 。但是这样也有问题,维护这几个 node 的成本太大,差点没绕晕我。
最后还是看了参考答案,整体框架跟我写的都是一致的,只不过在我最纠结的地方,参考答案居然用的是一个新 node 等于了 finalNode,最后直接 return finalNode , finalNode 根本就不参与这其中的计算,突然觉得这个方法好棒!因为 finalNode 始终都是新 node 的头,不管后续新 node 怎么去变换都不会改变,因为链表头已经被 finalNode 抓住了!
### AC Code
```swift
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
// 判断是否为空
if l1 == nil && l2 != nil {
return l2
} else if l1 != nil && l2 == nil {
return l1
} else if (l1 == nil && l2 == nil) {
return nil
} else {
var finalNode = ListNode(0)
var tempNode = l1
var otherNode = l2
var currentNode = finalNode
while true {
// 判断当前是否为空
if tempNode != nil {
currentNode.val += (tempNode?.val)!
}
if otherNode != nil {
currentNode.val += (otherNode?.val)!
}
tempNode = tempNode?.next
otherNode = otherNode?.next
if currentNode.val - 10 >= 0 {
currentNode.val = currentNode.val - 10
currentNode.next = ListNode(1)
currentNode = currentNode.next!
} else {
if tempNode == nil && otherNode == nil {
break
}
currentNode.next = ListNode(0)
currentNode = currentNode.next!
}
}
return finalNode
}
}
}
```
|
JavaScript
|
UTF-8
| 1,421
| 2.515625
| 3
|
[] |
no_license
|
/**
* Created by nant on 2014/7/28.
*/
exports.version = '0.1';
exports.name = 'localstorage';
exports.module = function(pagetimeline, callback){
var browser = pagetimeline.model.browser;
var timeout = pagetimeline.getParam( 'timeout' );
var domreadytimeout = pagetimeline.model.domreadyTimeout;
browser.onLoadEventFired( function(res){
setTimeout( function(){
calculate();
}, timeout );
} );
browser.onDomContentEventFired( function(res){
setTimeout( function(){
if( !pagetimeline.model.afteronload ){
calculate();
}
}, domreadytimeout );
} );
callback( false, {message:'add localstorage module done!'} );
function calculate(){
var funcStr = storageSize.toString() + ';storageSize()';
browser.evaluate( funcStr, function(err, res){
if( !err && res.result && res.result.value ){
pagetimeline.setMetric( 'localstorage_size', ( res.result.value / 1024 ).toFixed( 2 ) + 'KB' );
}
} );
}
function storageSize(){
var numKeys = function(storage){
if( "undefined" != typeof(storage.length) ){
return storage.length;
}else{
len = 0;
for( var key in storage ){
len++;
}
return len;
}
}
var storage = localStorage;
var numkeys = numKeys( storage );
var bytes = 0;
for( var i = 0; i < numkeys; i++ ){
var key = storage.key( i );
var val = storage.getItem( key );
bytes += key.length + val.length;
}
return bytes;
}
}
|
Python
|
UTF-8
| 282
| 2.828125
| 3
|
[] |
no_license
|
import pandas as pd
course=pd.read_csv("Data/course.csv")
course_new=course[(course.course_type=="专业必修")|(course.course_type=="公共必修")|(course.course_type=="公共选修")|(course.course_type=="专业选修")]
course_new.to_csv("course_new.csv",encoding="utf-8")
|
Python
|
UTF-8
| 4,175
| 3.1875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 10:10:31 2018
@author: yuxi
"""
import torch
def guassian_kernel(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
'''
将源域数据和目标域数据转化为核矩阵,即上文中的K
Params:
source: 源域数据(n * len(x))
target: 目标域数据(m * len(y))
kernel_mul:
kernel_num: 取不同高斯核的数量
fix_sigma: 不同高斯核的sigma值
Return:
sum(kernel_val): 多个核矩阵之和
'''
n_samples = int(source.size()[0])+int(target.size()[0])# 求矩阵的行数,一般source和target的尺度是一样的,这样便于计算
total = torch.cat([source, target], dim=0)#将source,target按列方向合并
#将total复制(n+m)份
total0 = total.unsqueeze(0).expand(int(total.size(0)), int(total.size(0)), int(total.size(1)))
#将total的每一行都复制成(n+m)行,即每个数据都扩展成(n+m)份
total1 = total.unsqueeze(1).expand(int(total.size(0)), int(total.size(0)), int(total.size(1)))
#求任意两个数据之间的和,得到的矩阵中坐标(i,j)代表total中第i行数据和第j行数据之间的l2 distance(i==j时为0)
L2_distance = ((total0-total1)**2).sum(2)
#调整高斯核函数的sigma值
if fix_sigma:
bandwidth = fix_sigma
else:
bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)
#以fix_sigma为中值,以kernel_mul为倍数取kernel_num个bandwidth值(比如fix_sigma为1时,得到[0.25,0.5,1,2,4]
bandwidth /= kernel_mul ** (kernel_num // 2)
bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)]
#高斯核函数的数学表达式
kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list]
#得到最终的核矩阵
return sum(kernel_val)#/len(kernel_val)
def mmd_rbf(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
'''
计算源域数据和目标域数据的MMD距离
Params:
source: 源域数据(n * len(x))
target: 目标域数据(m * len(y))
kernel_mul:
kernel_num: 取不同高斯核的数量
fix_sigma: 不同高斯核的sigma值
Return:
loss: MMD loss
'''
batch_size = int(source.size()[0])#一般默认为源域和目标域的batchsize相同
kernels = guassian_kernel(source, target,
kernel_mul=kernel_mul, kernel_num=kernel_num, fix_sigma=fix_sigma)
#根据式(3)将核矩阵分成4部分
XX = kernels[:batch_size, :batch_size]
YY = kernels[batch_size:, batch_size:]
XY = kernels[:batch_size, batch_size:]
YX = kernels[batch_size:, :batch_size]
loss = torch.mean(XX + YY - XY -YX)
return loss#因为一般都是n==m,所以L矩阵一般不加入计算
#%%
import random
SAMPLE_SIZE = 3
buckets = 5
#第一种分布:对数正态分布,得到一个中值为mu,标准差为sigma的正态分布。mu可以取任何值,sigma必须大于零。
plt.subplot(1,2,1)
plt.xlabel("random.lognormalvariate")
mu = -0.6
sigma = 0.15#将输出数据限制到0-1之间
res1 = [random.lognormvariate(mu, sigma) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res1, buckets)
#第二种分布:beta分布。参数的条件是alpha 和 beta 都要大于0, 返回值在0~1之间。
plt.subplot(1,2,2)
plt.xlabel("random.betavariate")
alpha = 1
beta = 10
res2 = [random.betavariate(alpha, beta) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res2, buckets)
plt.savefig('data.jpg')
plt.show()
#%%
diff_1 = []
for i in range(5):
diff_1.append([random.lognormvariate(mu, sigma) for _ in range(1, SAMPLE_SIZE+1)])
diff_2 = []
for i in range(5):
diff_2.append([random.betavariate(alpha, beta) for _ in range(1, SAMPLE_SIZE+1)])
from torch.autograd import Variable
#参数值见上段代码
#分别从对数正态分布和beta分布取两组数据
X = torch.Tensor(diff_1)
Y = torch.Tensor(diff_2)
X,Y = Variable(X), Variable(Y)
print (mmd_rbf(X,Y))
|
Java
|
UTF-8
| 707
| 1.726563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.xmlcml.norma.cproject;
import java.io.File;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test;
import org.xmlcml.cmine.files.CContainer;
import org.xmlcml.cmine.files.CProject;
import org.xmlcml.norma.NormaFixtures;
import org.xmlcml.norma.InputTest;
public class ResultsJSONTest {
private static final Logger LOG = Logger.getLogger(ResultsJSONTest.class);
static {
LOG.setLevel(Level.DEBUG);
}
@Test
public void testSplitAndNormalize() {
CContainer cProject = new CProject(new File(NormaFixtures.TEST_MISC_DIR, "cproject"));
File file = cProject.getAllowedChildFile(CProject.EUPMC_RESULTS_JSON);
}
}
|
Java
|
UTF-8
| 1,318
| 1.945313
| 2
|
[] |
no_license
|
package com.ezdi.audioplayer.solr;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan
@EnableSolrRepositories("com.mscharhag.solr.repository")
// @PropertySource(value ={"classpath:solr.properties"} )
@Component
public class SolrServiceUtil {
@Value("${solr.server.url}")
private String solrURL;
@Value("${solr.service}")
private String solrService;
@Value("${solr.handler}")
private String solrHandler;
@Bean
public SolrServer solrServer() {
return new HttpSolrServer(solrURL + "/" + solrService);
}
@Bean(name = "SolrTemplate")
public SolrTemplate solrTemplate(SolrServer server) throws Exception {
SolrTemplate solrTemplate = new SolrTemplate(solrServer());
System.out.println("solr server created :- " + solrTemplate);
return solrTemplate;
}
}
|
C++
|
UTF-8
| 8,154
| 3.375
| 3
|
[] |
no_license
|
#ifndef _LIST_H_
#define _LIST_H_
#include "Node.h"
#include <algorithm>
template<typename T>
class List {
public:
List() {
init();
}
~List() {
clear();
delete head;
delete tail;
}
void insert(const T& x) {
}
void erase(T& x) {
}
void clear(PtrToList L) {
while (!empty())
pop_front();
}
int size() const {
return _size;
}
bool empty() const {
return size() == 0;
}
T& front() {
}
T& back() {
}
void push_front(const T& x) {
}
void push_back(const T& x) {
}
void pop_front() {
}
void pop_back() {
}
void reverse();
Node<T>* find(const ElemType key);
void print();
void Print_Lots(const PtrToList L, const PtrToList P);
void Swap_With_Next(const PtrToList L, const PtrToNode X);
PtrToList Intersect(const PtrToList L1, const PtrToList L2);
void merge(List<T>& L);
private:
int _size;
Node<T>* _head;
Node<T>* _tail;
}; // List
struct Node {
ElemType data;
struct Node* next;
};
struct List {
int size;
struct Node head;
};
PtrToList List_Create() {
PtrToList L = malloc(sizeof(struct List));
if (L != NULL) {
L->size = 0;
L->head.next = NULL;
} else {
perror("malloc():");
exit(FAILURE);
}
return L;
}
void List_Destroy(PtrToList L) {
if (L != NULL) {
List_Clear(L);
free(L);
L = NULL;
}
}
void List_Clear(PtrToList L) {
if (L != NULL) {
PtrToNode p = L->head.next;
L->head.next = NULL;
PtrToNode tmp;
while (p != NULL) {
tmp = p->next;
free(p);
p = tmp;
}
L->size = 0;
}
}
void List_Insert(PtrToList L, PtrToNode X, int P) {
if ((L != NULL) && (P >= 0) && (P <= L->size)) {
if (X != NULL) {
PtrToNode tmp = malloc(sizeof(struct Node));
if (tmp != NULL) {
memcpy(tmp, X, sizeof(struct Node));
}
PtrToNode cur = &L->head;
for (int i = 0; i < P; ++i) {
cur = cur->next;
}
tmp->next = cur->next;
cur->next = tmp;
++(L->size);
}
}
}
void List_Delete(PtrToList L, int P) {
if ((L != NULL) && (P >= 0) && (P < L->size)) {
PtrToNode cur = &L->head;
for (int i = 0; i < P; ++i) {
cur = cur->next;
}
PtrToNode tmp = cur->next;
cur->next = tmp->next;
tmp->next = NULL;
free(tmp);
--(L->size);
}
}
void Push_Front(PtrToList L, PtrToNode X) {
List_Insert(L, X, 0);
}
void Push_Back(PtrToList L, PtrToNode X) {
List_Insert(L, X, L->size);
}
void Pop_Front(PtrToList L) {
List_Delete(L, 0);
}
void Pop_Back(PtrToList L) {
List_Delete(L, L->size-1);
}
void List_Reverse(PtrToList L) {
if (L != NULL) {
PtrToNode start = &L->head;
PtrToNode cur = L->head.next;
start->next = NULL; // 摘下原链表的头结点
PtrToNode tmp;
while (cur != NULL) {
tmp = cur;
cur = cur->next;
tmp->next = start->next; // 头插法
start->next = tmp;
}
}
}
void List_Get(const PtrToList L, const int P, PtrToNode X) {
if ((L != NULL) && (P >= 0) && (P < L->size)) {
PtrToNode cur = &L->head;
for (int i = 0; i < P; ++i) {
cur = cur->next;
}
memcpy(X, cur->next, sizeof(struct Node));
}
}
// int List_Find(const PtrToList L, const ElemType e) {
// int ret = -1;
// if (L != NULL) {
// PtrToNode cur = &L->head;
// for (int i = 0; i < L->size; ++i, cur = cur->next) {
// if (!memcmp(&e, &cur->next->data, sizeof(cur->data))) {
// ret = i;
// //break; // 不需要
// }
// }
// }
//
// return ret;
// }
int List_Find(const PtrToList L, const ElemType e) {
int ret = -1;
if (L != NULL) {
PtrToNode cur = &L->head;
for (int i = 0; i < L->size; ++i, cur = cur->next) {
if (!memcmp(&e, &cur->next->data, sizeof(ElemType))) {
PtrToNode tmp = cur->next;
cur->next = tmp->next;
tmp->next = L->head.next;
L->head.next = tmp;
break; // 改变cur后,可能导致 i < L->size 满足条件时, cur->next 已经为空
ret = 0;
}
// printf("*\n");
}
}
return ret;
}
int List_Size(const PtrToList L) {
int ret = -1;
if (L != NULL) {
ret = L->size;
}
return ret;
}
int List_Empty(const PtrToList L) {
return L->head.next == NULL;
}
void List_Print(PtrToList L) {
PtrToNode tmp = L->head.next;
while (tmp != NULL) {
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
void Print_Lots(const PtrToList L, const PtrToList P) { // O(n)
int steps = 0;
PtrToNode Ppos = P->head.next;
PtrToNode Lpos = L->head.next;
while (Lpos != NULL && Ppos != NULL) {
if (Ppos->data == steps++) {
printf("%d ", Lpos->data);
Ppos = Ppos->next;
}
Lpos = Lpos->next;
}
printf("\n");
}
void Swap_With_Next(const PtrToList L, const PtrToNode X) {
if (L != NULL && X != NULL) {
PtrToNode before = &(L->head);
PtrToNode after = &(L->head);
while (before->next != NULL) {
}
if (before->next->data == X->data) {
after = X->next;
before->next = after;
X->next = after->next;
after->next = X;
}
after = after->next;
before = before->next;
}
}
PtrToList Intersect(const PtrToList L1, const PtrToList L2) {
PtrToList L = malloc(sizeof(struct List));
L->head.next = NULL;
if (L1 != NULL && L2 != NULL) {
PtrToNode pos1 = L1->head.next;
PtrToNode pos2 = L1->head.next;
PtrToNode cur = &(L->head);
while (pos1 != NULL && pos2 != NULL) {
if (pos1->data == pos2->data) {
PtrToNode tmp = malloc(sizeof(struct Node));
tmp->data = pos1->data;
tmp->next = NULL;
cur->next = tmp;
cur = cur->next;
} else if (pos1->data > pos2->data) {
pos2 = pos2->next;
} else if (pos1-> data < pos2->data) {
pos1 = pos1->next;
}
}
}
return L;
}
PtrToList Union(const PtrToList L1, const PtrToList L2) {
PtrToList L = malloc(sizeof(struct List));
L->head.next = NULL;
if (L1 != NULL && L2 != NULL) {
PtrToNode pos1 = L1->head.next;
PtrToNode pos2 = L1->head.next;
PtrToNode cur = &(L->head);
PtrToNode tmp, e;
while (pos1 != NULL && pos2 != NULL) {
if (pos1->data == pos2->data) {
e = pos1;
pos1 = pos1->next;
pos2 = pos2->next;
} else if (pos1->data < pos2->data){
e = pos1;
pos1 = pos1->next;
} else if (pos2->data < pos1->data){
e = pos2;
pos2 = pos2->next;
}
tmp = malloc(sizeof(struct Node));
tmp->data = e->data;
tmp->next = NULL;
cur->next = tmp;
cur = cur->next;
}
while (pos1 != NULL) {
tmp = malloc(sizeof(struct Node));
tmp->data = pos1->data;
tmp->next = NULL;
cur->next = tmp;
cur = cur->next;
pos1 = pos1->next;
}
while (pos2 != NULL) {
tmp = malloc(sizeof(struct Node));
tmp->data = pos2->data;
tmp->next = NULL;
cur->next = tmp;
cur = cur->next;
pos2 = pos2->next;
}
}
return L;
}
#endif
|
Java
|
UTF-8
| 454
| 1.710938
| 2
|
[] |
no_license
|
package com.wufumall.example.b.dao;
import org.springframework.stereotype.Repository;
import com.wufumall.example.b.model.TxExampleB;
@Repository
public interface TxExampleBMapper {
int deleteByPrimaryKey(Long id);
int insert(TxExampleB record);
int insertSelective(TxExampleB record);
TxExampleB selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(TxExampleB record);
int updateByPrimaryKey(TxExampleB record);
}
|
Java
|
UTF-8
| 10,916
| 2.15625
| 2
|
[] |
no_license
|
package cn.hexing.dlms.protocol.comm;
import android.os.SystemClock;
import cn.hexing.EventMsg;
import cn.hexing.HexStringUtil;
import cn.hexing.iComm.AbsCommAction;
import cn.hexing.dlms.IHexListener;
import cn.hexing.model.CommPara;
import com.android.SerialPort.SerialPort;
import org.greenrobot.eventbus.EventBus;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author 王昌豹
* @version 1.0
* 光电通讯类
* 光电头与表通讯,300波特率握手再转高波特率
* Copyright (c) 2016
* 杭州海兴电力科技
*/
public class CommOpticalSerialPort extends AbsCommAction {
private final static String TAG = CommOpticalSerialPort.class.getSimpleName();
FileDescriptor mfd;
private OutputStream mOutputStream;
private InputStream mInputStream;
private SerialPort mSerialPort = new SerialPort();
private int stopBit;
private char parity;
private int dataBit;
private int baudRate;
private String uartpath;
// 第一字节接收超时时间
// 字节与字节之间超时时间
private static boolean delay_occurZJ = false;
private Timer timer = new Timer();
private TimerTask timerTask;
private IHexListener listener;
private static boolean aOpenStatus = false;
public void addListener(IHexListener listener) {
this.listener = listener;
}
@Override
public boolean openDevice(CommPara cpara) {
// 停止位
stopBit = cpara.Sbit;
// 校验位
parity = cpara.Pty;
// 数据位
dataBit = cpara.DBit;
// 波特率
baudRate = cpara.BRate;
// 串口名
uartpath = cpara.ComName;
try {
mSerialPort = new SerialPort();
mfd = mSerialPort.open(uartpath, baudRate, dataBit, parity, stopBit);
mOutputStream = mSerialPort.getOutputStream(mfd);
mInputStream = mSerialPort.getInputStream(mfd);
aOpenStatus = true;
} catch (Exception ex) {
EventBus.getDefault().post(new EventMsg("OpenPort failed:" + uartpath+","+baudRate+","+dataBit+","+parity+","+stopBit));
return false;
}
EventBus.getDefault().post(new EventMsg("OpenPort:" + uartpath+","+baudRate+","+dataBit+","+parity+","+stopBit));
return true;
}
@Override
public boolean closeDevice() {
try {
if (mSerialPort != null) {
aOpenStatus = false;
mSerialPort.Close();
}
} catch (Exception ex) {
return false;
}
EventBus.getDefault().post(new EventMsg("ClosePort:" + uartpath+","+baudRate+","+dataBit+","+parity+","+stopBit));
return true;
}
@Override
public byte[] receiveBytToCallback(int waitT, int byteLen) {
byte[] rtnByt = new byte[600];
byte[] rBuffer = new byte[600];
byte[] byteData = new byte[0];
delay_occurZJ = false;
int size;
int index = 0;
startTimer(waitT);
try {
while (!delay_occurZJ) {
if (mInputStream.available() > 0) {
size = mInputStream.read(rBuffer);// 刚开始为-1
if (size > 0) {
for (int i = 0; i < size; i++) {
rtnByt[index] = rBuffer[i];
index++;
}
if (index >= byteLen) {
delay_occurZJ = true;
break;
}
/**
* 验证是否 8D0A 结束
* 握手帧和波特率 该标志作为结束
*/
if (index > 1 && rtnByt[index - 1] == 0x0a) {
if ((rtnByt[index - 2] & 0xff) == 0x8d) {
delay_occurZJ = true;
//System.out.println(TAG + "||满足8D0A结束");
break;
}
}
/**
* 正常 以 7E开头 7E结束 byte[] 下标2 代表字节长度
*/
//System.out.println(TAG + "||" + (rtnByt[index - 1] & 0xff) + "||" + ((rtnByt[index - 1] & 0xff) == 0x7e));
if (index > 1 && (rtnByt[index - 1] & 0xff) == 0x7e) {
byteData = Arrays.copyOf(rtnByt, index);
if (byteData.length > 2) {
int hexLen = byteData[2] & 0xff;
int recLen = (byteData.length - 2) & 0xff;
//System.out.println(TAG + "||" + hexLen + "||" + recLen);
if (hexLen == recLen) {
delay_occurZJ = true;
// System.out.println(TAG + "||满足7E开头7E结束");
break;
}
}
}
}
}
}
if (index > 0) {
byteData = Arrays.copyOf(rtnByt, index);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
stopTimer();
}
return byteData;
}
@Override
public byte[] receiveByt(int SleepT, int witT) {
return receiveByt(SleepT, witT, 0);
}
@Override
public byte[] receiveByt(int SleepT, int WaitT, int byteLen) {
byte[] rtnByt = new byte[600];
byte[] rBuffer = new byte[600];
byte[] byteData = new byte[0];
delay_occurZJ = false;
int size;
int Index = 0;
SystemClock.sleep(SleepT);
startTimer(WaitT);
try {
while (!delay_occurZJ) {
if (mInputStream.available() > 0) {
size = mInputStream.read(rBuffer);// 刚开始为-1
if (size > 0) {
for (int i = 0; i < size; i++) {
rtnByt[Index] = rBuffer[i];
Index++;
}
if (byteLen > 0 && Index >= byteLen) {
delay_occurZJ = true;
System.out.println(TAG + "||满足字节size结束");
break;
}
/**
* 验证是否 8D0A 或 0D0A 结束
* 握手帧和波特率 该标志作为结束
*/
if (Index > 1 && rtnByt[Index - 1] == 0x0a) {
if ((rtnByt[Index - 2] & 0xff) == 0x8d) {
delay_occurZJ = true;
//System.out.println(TAG + "||满足8D0A结束");
break;
} else if ((rtnByt[Index - 2] & 0xff) == 0x0d) {
delay_occurZJ = true;
//System.out.println(TAG + "||满足0D0A结束");
break;
}
}
/**
* 正常 以 7E开头 7E结束 byte[] 下标2 代表字节长度
*/
if (Index > 1 && (rtnByt[Index - 1] & 0xff) == 0x7e) {
byteData = Arrays.copyOf(rtnByt, Index);
if (byteData.length > 2) {
int hexLen = byteData[2] & 0xff;
int recLen = (byteData.length - 2) & 0xff;
//System.out.println(TAG + "||" + hexLen + "||" + recLen);
if (hexLen == recLen) {
delay_occurZJ = true;
//System.out.println(TAG + "||满足7E开头7E结束");
break;
}
}
}
}
}
}
if (Index > 0) {
byteData = Arrays.copyOf(rtnByt, Index);
String res = HexStringUtil.bytesToHexString(byteData);
System.out.println("Rec:" + res);
EventBus.getDefault().post(new EventMsg("Rec:" + res));
}
} catch (Exception ex) {
System.out.println("Error:" + ex.getMessage());
} finally {
stopTimer();
}
return byteData;
}
@Override
public boolean sendByt(byte[] sndByte) {
// TODO Auto-generated method stub
boolean result = false;
if (!aOpenStatus) {
return false;
}
try {
mOutputStream.write(sndByte, 0, sndByte.length);// write(sndByte);
result = true;
String res = HexStringUtil.bytesToHexString(sndByte);
System.out.println("Send:" + res);
EventBus.getDefault().post(new EventMsg("Send:" + res));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public void setBaudRate(int baudRate) {
//mSerialPort.close();
this.baudRate = baudRate;
mfd = mSerialPort.open(uartpath, this.baudRate, dataBit, parity, stopBit);
mOutputStream = mSerialPort.getOutputStream(mfd);
mInputStream = mSerialPort.getInputStream(mfd);
}
@Override
public void setBaudRate(int baudRate, char parity, int dataBit, int stopBit) {
// mSerialPort.close();
this.baudRate = baudRate;
mfd = mSerialPort.open(uartpath, this.baudRate, dataBit, parity, stopBit);
mOutputStream = mSerialPort.getOutputStream(mfd);
mInputStream = mSerialPort.getInputStream(mfd);
}
public void startTimer(final int time) {
stopTimer();
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
delay_occurZJ = true;
}
};
timer.schedule(timerTask, time);
}
/**
* 停止 定时器
*/
private void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
}
}
|
C++
|
UTF-8
| 1,823
| 2.8125
| 3
|
[] |
no_license
|
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<stdio.h>
#include<winsock2.h>
#include<io.h>
#include<iostream>
#include<fstream>
using namespace std;
#pragma comment(lib,"ws2_32") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
//char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.");
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8888);
//Connect to remote server
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
/*//Send some data
message = "GET Image";
if (send(s, message, strlen(message), 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");*/
// receive the image
FILE *picture;
char *buffer;
char *sizec;
char *nc;
nc = new char[1];
int a, size=0;
recv(s, nc, 1, 0);
int n = nc[0] - '0';
sizec = new char[n];
recv(s, sizec, n, 0);
for (int i = 0; i < n; i++)
{
a = sizec[i] - '0';
size =size*10+a;
}
buffer = new char[size];
picture = fopen("copy1.png", "wb");
int offset = 0;
while (size > offset)
{
int amount = recv(s, buffer + offset, size - offset, 0);
if (amount <= 0)
{
cout << "Error: " << WSAGetLastError() << endl;
break;
}
else
{
offset += amount;
}
}
fwrite(buffer, 1, size, picture);
fclose(picture);
puts("Image received\n");
system("copy1.png");
getchar();
closesocket(s);
WSACleanup();
return 0;
}
|
Python
|
UTF-8
| 340
| 3.03125
| 3
|
[] |
no_license
|
n=int(input())
l=[]
jump=False
for i in range(n):
l.append(list(map(int,input().split())))
for i in range(n):
for j in range(i+1,n):
if l[i][0]<l[j][0]:
if l[i][1]>l[j][1]:
print("Happy Alex")
jump=True
break
if jump:
break
else:
print("Poor Alex")
|
Java
|
UTF-8
| 1,814
| 2.3125
| 2
|
[] |
no_license
|
package by.verdeth.servlets;
import by.verdeth.dao.bookDao.BookDaoImplSingleton;
import by.verdeth.dao.genreDao.GenreDaoImplSingleton;
import by.verdeth.models.Book;
import by.verdeth.models.Genre;
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.util.List;
@WebServlet ("/author")
public class AuthorServlet extends HttpServlet {
@Override
public void init(){
try
{
//DriverManagerDataSource dataSource;
//CreateDataSource createDataSource = new CreateDataSource();
// dataSource = CreateDataSource.getInstance().getDriverManagerDataSource();
//authorDao = new AuthorDaoJdbcImpl(dataSource);
// genreDao = new GenreDaoJdbcImpl(dataSource);
// bookDao = new BookDaoJdbcImpl(dataSource);
}
catch (Exception ex)
{
throw new IllegalStateException(ex);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("id")== null)
{
req.getServletContext().getRequestDispatcher("/about").forward(req,resp);
}
Integer idAuthor = Integer.valueOf(req.getParameter("id"));
List<Genre> genres = GenreDaoImplSingleton.getInstance().getGenreDao().findAll();
req.setAttribute("genresFromServer", genres);
List<Book> books = BookDaoImplSingleton.getInstance().getBookDao().findAllByIdAuthor(idAuthor);
req.setAttribute("booksAuthorFromServer", books);
req.getServletContext().getRequestDispatcher("/jsp/author.jsp").forward(req,resp);
}
}
|
C#
|
UTF-8
| 1,814
| 2.828125
| 3
|
[] |
no_license
|
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
namespace Smasher.JobLib
{
public class JobManager
{
public JobManager ()
{
mQueueLocker = new object();
mJobQueue = new Queue<Job>();
}
public void EnqueueJob (Job job)
{
lock (mQueueLocker)
{
mJobQueue.Enqueue(job);
Monitor.Pulse(mQueueLocker);
}
}
/// <summary>
/// Starts the main loop.
/// </summary>
/// <param name='primary'>
/// (Mandatory) Primary Job Consumer, this is the one that will have priority on Job consuption
/// (e.g. local machine consumer).
/// </param>
/// <param name='secundary'>
/// (Optional) Lower priority consumer.
/// </param>
/// <remarks>
/// THIS BLOCKS EXECUTION! Execute in a thread if you don't want to block the main thread!
/// Tweak the consumer score to achieve the best performance.
/// </remarks>
public void Start (IJobConsumer primary, IJobConsumer secundary)
{
Debug.Assert(primary != null);
if (primary == null)
throw new ArgumentNullException("You have to set the primary consumer!");
while (true)
{
Job nextJob;
lock (mQueueLocker)
{
while (mJobQueue.Count == 0)
Monitor.Wait(mQueueLocker);
nextJob = mJobQueue.Dequeue();
}
// We can't get here without Dequeueing at least once!
if (nextJob == null)
break;
IJobConsumer nextConsumer = null;
while (nextConsumer == null)
{
if (primary.HasAvailableWorkers)
{
nextConsumer = primary;
}
else if (secundary != null && secundary.HasAvailableWorkers)
{
nextConsumer = secundary;
}
}
nextConsumer.Consume(nextJob);
}
}
private readonly object mQueueLocker;
private Queue<Job> mJobQueue;
}
}
|
JavaScript
|
UTF-8
| 1,456
| 3.6875
| 4
|
[] |
no_license
|
// 二叉搜索树--测试用例
// Binary Search Tree -- test cases
// https://www.jianshu.com/p/ce4f46cd9372
// const BinarySearchTree = require('./01-binary-search-tree.js')
import BinarySearchTree from './01-binary-search-tree.js'
// console.log('BinarySearchTree', BinarySearchTree)
describe('BST 算法', () => {
let tree = new BinarySearchTree()
test('insert and getRoot method', () => {
tree.insert(20) // root
tree.insert(12)
tree.insert(16)
tree.insert(30)
expect(tree.getRoot().key).toBe(20)
})
// 中序遍历-从最小到最大的顺序访问所有节点
test('中序遍历 inOrderTraverse', () => {
let printNode = (value) => {
if (value === 12) {
expect(12).toBe(value)
} else if (value == 16) {
expect(16).toBe(value)
} else if (value == 20) {
expect(20).toBe(value)
} else if (value == 30) {
expect(30).toBe(value)
}
}
tree.inOrderTraverse(printNode)
})
})
describe('BST 二叉树算法2', () => {
let tree = new BinarySearchTree()
let arr = [33, 44, 22, 11, 99]
arr.map(item => {
tree.insert(item)
})
test('getRoot 根节点 key', () => {
expect(tree.getRoot().key).toBe(33)
})
test('使用 BST 排序, inOrderTraverse', () => {
let arr = []
let printNode = (value) => {
arr.push(value)
}
tree.inOrderTraverse(printNode)
expect([11, 22, 33, 44, 99]).toEqual(arr)
})
})
|
C
|
UTF-8
| 2,808
| 3.53125
| 4
|
[] |
no_license
|
/**
* C program to solve the two-dimensional Poisson equation on
* a unit square using one-dimensional eigenvalue decompositions
* and fast sine transforms.
*
* Einar M. Rønquist
* NTNU, October 2000
* Revised, October 2001
* Revised by Eivind Fonn, February 2015
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <mpi.h>
#define PI 3.14159265358979323846
#define true 1
#define false 0
typedef double real;
typedef int bool;
// Function prototypes
void transpose(real **bt, real **b, int *nrows, int *displ, int size, int rank);
real *mk_1D_array(size_t n, bool zero);
real **mk_2D_array(size_t n1, size_t n2, bool zero);
int main(int argc, char **argv)
{
if (argc < 2) {
printf("Usage:\n");
printf(" poisson n\n\n");
printf("Arguments:\n");
printf(" n: the problem size (must be a power of 2)\n");
}
// The number of grid points in each direction is n+1
// The number of degrees of freedom in each direction is n-1
int n = atoi(argv[1]);
size_t m=6;
real **b = mk_2D_array(m, m, false);
real **bt = mk_2D_array(m, m, false);
int i,j;
//Initalise MPI
int rank, size;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
//distribute rows
int part = m/size;
int *nrows = calloc(size, sizeof(int));
for (size_t i = 0; i < size; i++){
nrows[i] = part;
}
//'leftover' columns
int leftover = m % size;
for (size_t i = 1; i <= leftover; i++)
nrows[size - i]++;
//Calculate displacment vector for call to MPI_Alltoallv
int *displ = calloc(size+1, sizeof(int));
displ[0] = 0;
for (size_t i = 1; i < size+1; i++)
displ[i] = displ[i-1] + nrows[i-1];
//Print matrix b
printf("b=\n");
for(i=0; i<m; i++){
for(j=0; j<m; j++){
b[i][j]=(i)*m + (j+1);
printf("%f ",b[i][j]); }
printf("\n");
}
transpose(bt, b, m);
//Print matrix bt
printf("bt= \n");
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("%f ",bt[i][j]);
}
printf("\n");
}
MPI_Finalize();
return 0;
}
//Transpose function
void transpose(real **bt, real **b, size_t m)
{
for (size_t i = 0; i < m; i++) {
for (size_t j = 0; j < m; j++) {
bt[i][j] = b[j][i];
}
}
}
//Generate array-function
real *mk_1D_array(size_t n, bool zero)
{
if (zero) {
return (real *)calloc(n, sizeof(real));
}
return (real *)malloc(n * sizeof(real));
}
real **mk_2D_array(size_t n1, size_t n2, bool zero)
{
real **ret = (real **)malloc(n1 * sizeof(real *));
if (zero) {
ret[0] = (real *)calloc(n1 * n2, sizeof(real));
}
else {
ret[0] = (real *)malloc(n1 * n2 * sizeof(real));
}
for (size_t i = 1; i < n1; i++) {
ret[i] = ret[i-1] + n2;
}
return ret;
}
|
Java
|
UTF-8
| 1,573
| 1.882813
| 2
|
[] |
no_license
|
package com.example.avrwizard;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class GeneratedProgram extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generated_program);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
);
JSONEngine json = (JSONEngine) getApplicationContext();
Button btnBack = (Button) findViewById(R.id.btnback);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
backtoselectboard();
}
});
TextView codeFunction = (TextView) findViewById(R.id.codeFunction);
TextView codeMain = (TextView) findViewById(R.id.codeMain);
codeFunction.setText(json.getFunctionCode());
codeMain.setText(json.getMainCode());
}
private void backtoselectboard(){
Intent intent = new Intent(this, selectMenu.class);
startActivity(intent);
}
}
|
TypeScript
|
UTF-8
| 1,118
| 2.53125
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Token} from '../../models/Token';
import {tap} from "rxjs/operators";
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class TokenService {
BASE_URL = 'http://localhost:8080/api/'
constructor(private http: HttpClient) { }
getTokenForLoginHttp(login: any): Observable<Token>{
return this.http.post<Token>(this.BASE_URL+'auth/login',login);
}
getTokenForRefreshHttp(){
// @ts-ignore
let token: Token = {
refresh_token: <any>this.getRefreshTokenFromStorage()
};
return this.http.post<Token>(this.BASE_URL+'auth/refresh', token).pipe(
tap((data)=>{
this.saveTokenInStorage(JSON.stringify(data));
})
);
}
saveTokenInStorage(token: any): void {
localStorage.setItem('token', token);
}
getTokenFromStorage(): string | null {
return localStorage.getItem('token');
}
getRefreshTokenFromStorage(): string | null {
return "Bearer "+JSON.parse(<string>localStorage.getItem('token'))["refresh_token"];
}
}
|
PHP
|
UTF-8
| 2,170
| 3.578125
| 4
|
[] |
no_license
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ejercicio 02 - Parte 01</title>
</head>
<body>
<!--
Cada línea representa la política y la contraseña que debe cumplirla. La política de
contraseñas indica el número mínimo y el número máximo de veces que se debe repetir la
letra que hay a continuación. Así pues, “1-3 a” significa que la contraseña debe de contener
la letra “a” un mínimo de 1 y un máximo de 3 veces. Siguiendo esta norma, en el ejemplo
anterior hay un total de 2 contraseñas válidas.
-->
<?php
$path = "input.txt.txt";
if(file_exists($path)){
$array = explode("\n", file_get_contents($path));
$contValido = 0;
$contNoValido = 0;
foreach($array as $lineas){
echo "<pre/>";print_r($lineas);
$array2 = preg_split("/[\s-]+/", $lineas);
$min = $array2[0];
$max = $array2[1];
$letraClave = substr($array2[2], 0, -1);
$cadena = $array2[3];
$veces = substr_count($cadena, $letraClave);
echo "La letra clave aparece " . $veces . " veces " . "\n";
if(($veces < $max && $veces > $min) || $veces == $min || $veces == $max){
echo "La contraseña es válida " . "\n";
$contValido++;
}
else{
echo "La contraseña no es válida " . "\n";
$contNoValido++;
}
}
echo "\n";
echo "¿Cuántas contraseñas válidas hay en tu input? " . "\n";
echo "Hay " . $contValido . " contraseñas válidas " . "\n";
echo "Hay " . $contNoValido . " contraseñas no válidas " . "\n";
}
else{
echo "El fichero no existe";
}
?>
</body>
</html>
|
Markdown
|
UTF-8
| 17,240
| 3.109375
| 3
|
[] |
no_license
|
- I can’t afford to have thoughts in my head about me that God doesn’t have in His.
- Royalty is my identity. Servanthood is my assignment. Intimacy with God is my life source.
- Don’t let your past dictate your future.
- We owe the world an encounter with God.
- Great faith doesn’t come out of great effort, but out of great surrender.
- Faith doesn’t deny a problems existence. It denies it a place of influence.
- A culture of honor is celebrating who a person is without stumbling over who they’re not.
- You know your mind is renewed when the impossible looks logical.
- The ‘renewed’ mind is the canvas on which the Spirit of God can paint.
- Rule with the heart of a servant. Serve with the heart of a king.
- Transformed people transform cities.
- The only true worship is extreme worship, and only extreme worship brings extreme results – transformation.
- It is INCONSISTENT to have Jesus pay a price for healing and for us to believe it is not Gods intention to heal.
- When you’re willing to do what you’re unqualified to do, that’s what qualifies you.
- No one has ever overdosed on encouragement.
- I will not lower the standard of the Bible to my level of experience.
- What is the will of God? On earth as it is in heaven. If it doesn’t exist there, it’s not supposed to exist here. If it does exist there, it’s supposed to exist here.
- The most simple way to stay encouraged is to feed your heart on what He is doing, not on what He hasn’t done. If you can’t see what He is doing, feed on what He has done in the past.
- When we pursue kingdom principles above His presence, we are looking for the kingdom without a king.
- Evangelism, in its purist form, is an overflow of worship.
- Complaining proves nothing but that you can hear the voice of the Devil.
- Perfectionism is the counterfeit of excellence. Excellence is Kingdom, while perfectionism is religion. What ever you do, do it with all you might, and as unto the Lord. That is excellence.
- Jesus is the most normal Christian in the Bible.
- Gifts are free, but maturity is expensive.
- The way you silence fear is to give attention to faith.
- Sacrifice is a step beyond convenience.
- A private victory leads to a public victory and a corporate blessing, because God turns His face toward those who will demonstrate character when no one is looking.
- Whenever God restores something, He restores it to a place greater than it was before.
- I try to live in such a way that nothing gets bigger than my awareness of God presence on my life.
- You won’t have to watch what you say if you watch what you think.
- A heart of faith is anchored in the unseen.
- The journey makes things valuable not the title. Learn to enjoy and value the process of what God is doing.
- To have divine favor on your life means you’ll attract extraordinary opposition.
- Through radical generosity, we are awakening in people an in built divine consciousness of His goodness.
- We need to remain childlike. Children don’t dream of being insignificant.
- Many Christians miss out on God encounters because they are satisfied with good theology.
- When I live out of discipline, I’m admired – When I live out of passion, I’m contagious.
- Live in such a way that unless God shows up what you’re attempting to do is bound to fail. This is the nature of the Gospel.
- Sometimes our breakthrough begins when we refuse to be impressed with the size of our problem.
- If you don’t live by the praise of men you won’t die by their criticism.
- You have authority over every storm you can sleep in.
- People of excellence will always be brought before people of influence.
- In His mercy, God gives us the level of revelation that our character is prepared to handle.
- We have been given the privilege to host this presence. The Holy Spirit is in me for my sake but he is upon me for yours.
- Jesus didn’t accomplish everything so that you could accomplish nothing.
- The walk of Faith is to live according to the revelation we have received, in the midst of the mysteries we can’t explain.
- True humility is not in the absence of confidence but strength restrained.
- In order to have a peace that surpasses all understanding, you have to give up your right to understand.
- Your shadow will always release whatever overshadows you.
- The transfiguration was a physical illustration of what the renewed mind looks like in the spiritual.
- Radical obedience always gives priority to what God has said over what He hasn’t said.
- It is abnormal for a Christian not to have an appetite for the impossible. It has been written into our spiritual DNA to hunger for the impossibilities around us to bow at the name of Jesus.
- Jesus ruined every funeral he attended including his own.
- Much of today’s church relies more on a book the early church didn’t have, than the Holy Spirit they did.
- We don’t believe because we understand. We understand because we believe.
- As a forgiven son, I am justified, cleansed, washed clean. This is a greater reality than my sinful past.
- God wants people to meet Him when they meet us.
- Responding to truth will keep you safe. Reacting to error will only create another error.
- You can redefine your external world by an internal experience with the love of God.
- A powerless church has nothing for the devil to counterfeit.
- Once you’ve left the concept of family, you’ve left the concept of kingdom.
- Faith is not the result of striving. It is the result of surrender.
- While it takes at least two to reconcile, it only takes one to forgive.
- Whatever you gain through self promotion you’ll have to sustain through self promotion. When our promotion comes from God, He sustains it.
- One of the side effects of losing intimacy with God is that at some point we stop doing ministry out of imagination and we begin doing it out of memory.
- There’s something amazing about unbelief – it is able to fulfill its own expectations. Unbelief is safe because it takes no risk and almost always gets what it expects. Then, after a person gets the answer for their unbelief, they can say, I told you so.
- Anything you think you know about about God, that you can’t find in the person of Jesus, you have reason to question.
- Those who think their intellect will keep them from deception are already deceived.
- Jesus is interested in changing cultures, not just putting bodies in chairs.
- All fruit grows through abiding, not striving.
- There’s something about valuing people not because they value you, but because you can see God in them.
- Anyone who knows who God made them to be will never try to be someone else.
- Grace is the atmosphere created by love that makes faith the only reasonable response.
- We are not relevant when we mirror secular culture. We are relevant when we are what they long to be.
- Living in regret will become your biggest regret.
- Bible study without Bible experience is pointless.
- It’s a great tragedy when the Bible is interpreted by those who are not in love.
- When Jesus performed miracles, he wasn’t demonstrating what God can do, but what God can do through a man.
- Divine favor causes you to rise to the top in your sphere of influence, and the reality is that favor can be recognized more easily is your start at the bottom.
- Faith is not opposed to the mind. It’s superior to the mind which is why the renewed mind enhances faith.
- The enemy lies to make the problems we face appear larger than the solutions we carry.
- For those without fire, any fire is strange fire.
- Jesus is returning for a bride whose body is in equal proportion to her head.
- Part of our problem is this: we are accustomed only to doing things for God that are not impossible.
- If we rejoice in the acts of God without discovering His ways, we’ll question who He is when He doesn’t do what we’ve asked.
- In the old, sin contaminates. In the new, righteousness contaminates. It’s a different day.
- Jesus took what I deserved so I could get what He deserved.
- If you engage with the Holy spirit because you want to merely be effective in ministry, then you’re developing professional intimacyand what do we call people who are intimate as a profession?
- My history shouts the power of the blood of Jesus. My presence demonstrates the absolute love, affection and purpose of God for my life. My future is drawing me into a hope-filled life that has a purpose of saying, ‘on earth as it is in Heaven.’
- God will never violate His Word, but He doesn’t seem to mind violating our understanding of His Word.
- Some people need a theology of an angry God to justify their anger against sinners.
- Jesus did not live in reaction to the devil. He lived in response to the Father.
- Our assignment is to see the dominion of God realized into people’s lives. It is not an overpowering control, it is a life-giving, liberating experience with the almighty God, who is an ultimate, perfect Father who loves to bring liberty and freedom to His people.
- Any revelation from God’s Word that does not lead us to an encounter with God only serves to make us more religious. The Church cannot afford ‘form without power,’ for it creates Christians without purpose.
- So Jesus came and modelled a lifestyle of power and purity because the power of the Spirit of God was on him. He was trying to show those of us who would follow what life would be like in someone who had no sin and was completely empowered by the Spirit of God.
- God is the ultimate steward. He even turns our tears into the seeds of a hope filled future.
- The best way to prepare yourself for your own miracle is to rejoice in somebody else’s.
- Oftentimes what you see cancels out what you perceive.
- We must dream so big that without the support that comes through favor with God and man, we could never accomplish what is in our hearts.
- Our mandate is simple: raise up a generation that can openly display the raw power of God.
- Corporate greed is killing America, and that’s what we battling at Boeing.
- Grace does not overlook sin, it empowers righteousness!
- Obedience is not measured by our ability to obey laws and principles, obedience is measured by our response to God’s voice.
- We don’t have the capacity to exaggerate God’s goodness. We can distort it, or even misrepresent it, but we can never exaggerate it.
- My responsibility is to obey, to surrender my heart and to yield myself to the will of God. It is in the process of obedience that we gain understanding. You can’t get the peace that passes understanding until you give up your right to understand.
- The favor of God does not bless self-promotion.
- Most closed heavens for the Christian are between his ears. Believing a lie empowers the liar.
- We always become like the one we worship!
- God doesn’t have to try to do supernatural things. He is supernatural. He would have to try to not be. If He is invited to a situation, we should expect nothing but supernatural invasion.
- Doesn’t it honor Him more when His children no longer see themselves only as sinners saved by grace, but now as heirs of God? Isn’t it a greater form of humility to believe Him when He says we are precious in His sight when we don’t feel very precious?
- Fear is just faith in the wrong person.
- God set the standard for giving love that demands nothing in return.
- Nothing compares with the satisfaction of pleasing the heart of our heavenly Father.
- I think the law as it is today probably does prohibit an off-reservation casino, but there is uniqueness to Turtle Mountain and there is uniqueness to the state, and these things need to be looked at.
- Every loss is temporary. Every victory is eternal.
- Our identity sets the tone for all we do and become. Christians who live out of who they really are cannot be crippled by the opinions of others. They don’t work to fit into other people’s expectations, but burn with the realization of who the Father. says they are.
- The devil considers all misplaced trust as devil worship, for he hides himself in its shadows.
- Abiding in peace makes us a threat to any storm.
- Unbelief is safe, because it takes no risk and almost always gets what it expects.
- I cannot live in mediocrity, content with merely knowing that there is more of God to experience and explore -and then do nothing about it. Truths that are not experienced are, in effect, more like theories than truths. Whenever God reveals truth to us He is inviting us into a divine encounter.
- In my own pursuit of God, I often became preoccupied with ME! It was easy to think that being constantly aware of my faults and weakness was humility. It’s not! If I’m the main subject, talking incessantly about my weaknesses, I have entered into the most subtle form of pride.
- Just because you are going to Heaven doesn’t mean you have Heaven established in you. Success is Heaven on earth.
- The kingdom of God must never be reduced to talk, ideas and principles. The kingdom of God is power.
- Skills can be taught. It’s tough to teach heart. Talent is fairly common.
- Serving reconnects people to purpose. Serving someone else’s dream empowers not just us, but them.
- The Bible was meant to be read by those in love. It’s sad when it’s not.
- Fear looks like wisdom to those without risk.
- Presence always wins out over principles.
- Because God is better than we think we have to change the way we think.
- It’s in the environment of worship that we learn things that go way beyond what our intellect can grasp.
- Faith is generated in the atmosphere of experiencing truth.
- Passion produces the best discipline.
- Beware ‘good’ main characters who have a limited repertory of culturally acceptable feelings, while your evil bastards have a full range of vivid, passionate feelings.
- Faith must rise beyond the recognised norm into a lifestyle that accurately represents the victorious Son of God.
- Religion idolizes concepts and avoids personal experience.
- The way you think either expresses or undermines faith.
- What you know will keep you from what you need to know if you don’t remain a novice.
- Automatically thinking ‘everything that happens is God’s will’ is a lazy way to live. We live in a war. Jesus wasn’t fighting the Father’s will when He raised the dead.
- Our assignment has never been about what we can do for God, but what can God do through us.
- When you keep it within the walls, it dies. When you take it out where Jesus intended it to be, it happens.
- Compromise is the door through which deception enters.
- If you live cautiously, your friends will call you wise. You just won’t move many mountains.
- If you make history with God, He’ll make history with you.
- Our faith can only go as far as our awareness of Gods goodness.
- I’m not a good faster. My friends have visions of God, I have visions of hamburgers. The only time I watch the Food Channel is when I’m fasting. It’s pitiful. We did a 40 day fast. I bought 29 cookbooks. I don’t cook, but the pictures! I bought a deep-fryer and we don’t eat deep-fried food!
- Heaven invades earth when there is agreement here to what exists there. Honestly, that’s how it happens.
- It is unnatural for a Christian not to have an appetite for the impossible.
- People who refuse to step out and be used by God become the critics of those who do. Risk takers, the ones who thrill the heart of God, become the targets of those who never fail because they seldom try.
- Who I am in Christ is amazing. Who Christ is in me is the real story. It is beyond amazing.
- The ability to embrace mystery is what attracts revelation.
- An area of life that does not have hope is under a lie.
- The best way to honor past accomplishments is by building on top of their breakthroughs.
- America should meet its obligations in the form of Social Security, Medicare, our ability to pay our military, legally binding legislation that allows unemployment compensation, the judiciary, the federal court system, the federal prison system, all those kinds of things have to be paid for.
- Don’t rely on leaders to do things you’re equipped to do yourself.
- God is not pre-occupied with sin, He’s already dealt with it.
- Our refusal to fear reminds the devil that he is finished!
- My destiny is to go to heaven, my responsibility is to bring heaven.
- Some unanswered prayers are only because God doesn’t want to do something for us. He wants to do something through us.
- The mind is either at war with God or it is being renewed. There is no middle ground.
- Christianity was never meant to be defined by its disciplines, but by its passions.
- Every miracle brings the release of glory.
- The biggest enemy to prayer is praying for something you already have.
- We all remember things, it’s what we remember that determines how we live.
- Leaders who lack passion cost everyone who follows.
- I finally discovered something – it’s all about Jesus.
165 quotes
|
Java
|
UTF-8
| 746
| 3.6875
| 4
|
[] |
no_license
|
package linkedlist.practice;
class Node{
int data;
Node next;
Node(int data){
this.data= data;
next=null;
}
}
public class LinkedListPractice {
static Node head;
public static void main(String[] args) {
//linkedListPractice.push(1);
// linkedListPractice.printList();
push(1);
push(2);
push(3);
push(4);
push(5);
printList();
}
public static void push(int data){
Node node = new Node(data);
node.next = head;
head = node;
}
public static void printList()
{
Node n = head;
while (n != null) {
System.out.println(n.data + " ");
n = n.next;
}
}
}
|
Java
|
UTF-8
| 4,217
| 2.921875
| 3
|
[] |
no_license
|
package com.hap.trip.util;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hap.trip.R;
import com.hap.trip.TripApplication;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
public class DateUtil {
private static final String DATE_SEARCH_FORMAT = "YYYY-MM-dd";
private static final String DATE_FLIGHT_FORMAT = "YYYY-MM-dd'T'HH:mm";
private static final String DATE_SELECTED_FORMAT = "EEE, MM dd";
/**
* This is going to return the date in the format {YYY-MM-dd}, which will be helping us to create the
* search of the flight calling the api
* This is something that is not going to be displayed to the user
*
* @param date - the date in milliseconds
* @return the date in the format {YYY-MM-dd}
*/
public static String getFormattedSearchDate(@Nullable final Long date) {
if (date == null) {
return null;
}
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_SEARCH_FORMAT, Locale.US);
return simpleDateFormat.format(new Date(date));
}
public static String getTimeDifference(final String departAt, final String arriveAt) {
if (TextUtils.isEmpty(departAt) || TextUtils.isEmpty(arriveAt)) {
return null;
}
try {
final Date departDate = new SimpleDateFormat(DATE_FLIGHT_FORMAT, Locale.US).parse(departAt);
final Date arriveDate = new SimpleDateFormat(DATE_FLIGHT_FORMAT, Locale.US).parse(arriveAt);
final long diffInMillis = arriveDate.getTime() - departDate.getTime();
int minutes = (int) ((diffInMillis / (1000 * 60)) % 60);
int hours = (int) ((diffInMillis / (1000 * 60 * 60)) % 24);
return TripApplication.getInstance().getResources().getString(R.string.flight_result_time_format_3, hours, minutes);
} catch (ParseException e) {
return null;
}
}
private static Calendar getCalendarFromDate(@Nullable final String date) {
if (date == null) {
return null;
}
try {
final Date date1 = new SimpleDateFormat(DATE_FLIGHT_FORMAT, Locale.US).parse(date);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
return calendar;
} catch (ParseException e) {
return null;
}
}
/**
* This is receiving a date from the api response, this date will be in the format {YYY-MM-dd'T'HH:mm}
* and we will return only the time in the format {HH:mm}
*
* @param date - the date in the format {YYY-MM-dd'T'HH:mm}
* @return the time in the format {HH:mm}
*/
public static String getFormattedTime(@Nullable final String date) {
if (date == null) {
return null;
}
final Calendar calendar = DateUtil.getCalendarFromDate(date);
if (calendar == null) {
return null;
}
final String hour = calendar.get(Calendar.HOUR_OF_DAY) > 10
? String.valueOf(calendar.get(Calendar.HOUR_OF_DAY))
: "0".concat(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)));
final String minute = calendar.get(Calendar.MINUTE) > 10
? String.valueOf(calendar.get(Calendar.MINUTE))
: "0".concat(String.valueOf(calendar.get(Calendar.MINUTE)));
return TripApplication.getInstance().getResources().getString(R.string.flight_result_time_format, hour, minute);
}
/**
* This is going to receive a date in milliseconds, and will return a date in the format {EEE, MM dd}
* which will be displayed to the user
*
* @param date - the date in milliseconds
* @return the date in the format {EEE, EE dd}
*/
public static String getSelectedDateFormatted(final long date) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_SELECTED_FORMAT, Locale.getDefault());
return dateFormat.format(new Date(date));
}
}
|
C++
|
UTF-8
| 1,225
| 3.40625
| 3
|
[] |
no_license
|
/** @file StackL.cpp */
#include <iostream>
#include "StackA.h" // header file
Stack::Stack()
{
max = 4;
top = 0;
size = 0;
array = StackItemType[max];
} // end default constructor
Stack::Stack(const Stack& aStack)
{
} // end copy constructor
Stack::~Stack()
{
delete [] array;
} // end destructor
bool Stack::isEmpty() const
{
return(size == 0);
} // end isEmpty
void Stack::push(const StackItemType& newItem)
{
if(size == max)
{
StackItemType *oldArray = array;
array = new StackItemType[2*max];
for(int index = 0; index < size; ++index)
array[index] = oldArray[index];
delete [] oldArray
}
array[top] = newItem;
++size;
++top;
} // end push
void Stack::pop()
{
if(size < 0)
{
--top;
--size;
}
else
cout << "Empty Stack"
} // end pop
void Stack::pop(StackItemType& stackTop)
{
if(size < 0)
{
stackTop = array[top];
--top;
--size;
}
} // end pop
void Stack::getTop(StackItemType& stackTop)
{
} // end getTop
void Stack::display()
{
cout << "Items (from top to bottom):" << endl;
for(int tempTop = top; temptop =; --index)
{
cout << array << " ";
}
} // end display
// End of implementation file.
|
Python
|
UTF-8
| 514
| 2.578125
| 3
|
[] |
no_license
|
import cv2
import numpy as np
img = cv2.imread("img/bingbing_is_mine.jpg")
kernel = np.ones((5,5),np.uint8)
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(5,5),0)
imgCanny = cv2.Canny(imgBlur,50,100)
imgDialation = cv2.dilate(imgCanny,kernel,iterations=1)
imgEroded = cv2.erode(imgDialation,kernel,iterations=1)
cv2.imshow("imgBefore",imgCanny)
cv2.imshow("imgAfter1",imgDialation)
cv2.imshow("imgAfter2",imgEroded)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Markdown
|
UTF-8
| 2,226
| 3.328125
| 3
|
[] |
no_license
|
# exerciciosJavaLista1
Lista de exercicios simples em java, envolvendo funções, expressões aritméticas e lógica
**Exercicio 1**: Faça uma função para calcular o volume de um cubo.
**Exercicio 2**: Um posto de abastecimento vende uma mistura de combustível composta de 75% de gasolina e 25% de álcool. Faça uma função para determinar o preço do litro da mistura, considerando o preço do litro da gasolina e do álcool.
**Exercicio 3**:Faça um função que receba os valores a, b e c de uma expressão matemática na forma a.x + b = c e calcule o valor de x.
**Exercicio 4**: Faça uma função para determinar a quantidade de cédulas em reais (1, 2, 5, 10, 50, 100) para realizar o troco de uma compra em uma loja. Considere que o valor da compra e do pagamento são números inteiros.
**Exercicio 5**: Sabe-se que um galpão possui as dimensões descritas por comprimento x largura x altura. O dono do galpão pretende pintar as paredes internas e externas com uma mesma cor e precisa decidir a tinta a ser utilizada baseado nas diferentes opções de preço. Para selecionar a tinta, recebeu um catálogo de preço com as informações por galão (5 litros) e
o total de metros quadrados que a tinta cobrirá por galão. Como pode realizar somente a compra por galão, faça uma função para que ele possa testar individualmente todas as opções do catálogo e descobrir a quantidade de galões e o valor a pagar selecionada uma tinta específica.
**Exercicio 6**: Faça uma função para verificar se duas palavras são iguais.
**Exercicio 7**: Faça uma função para determinar se um valor inteiro positivo é par.
**Exercicio 8**: Faça uma função para verificar se o uso de álcool compensa mais que o uso de gasolina. Se sim, deve-se retornar true, se não, deve-se retornar false. Sabe-se que álcool compensa se o valor do litro do álcool for abaixo de 70% do valor do litro da gasolina.
**Exercicio 9**: Faça uma função para verificar se um triângulo é retângulo, considerando que a entrada são os três lados de um triângulo em ordem crescente de valor.
**Exercicio 10**: Faça uma função para determinar se um retângulo pode ser desenhado dentro de uma circunferência.
|
JavaScript
|
UTF-8
| 3,523
| 3.421875
| 3
|
[] |
no_license
|
var vp=document.getElementById("villaplatzi"); //llamar al id creado en .html
var papel = vp.getContext("2d"); //donde se dibujara
//objeto con varios atributos
var fondo= {
url: "tile.png",
cargaOK: false //para verificar el cargado de imagen y que no se sobrepongan
};
var vaca = {
url: "vaca.png",
cargaOK: false
};
var cerdo = {
url: "cerdo.png",
cargaOK: false
};
//origen de coordenadas imagen cerdo para mever por teclado
var x_c=100;
var y_c=100;
var pollo = {
url: "pollo.png",
cargaOK: false
};
//controla la cantidad de imagenes que cargara de un mismo tipo
var cantidad = aleatorio(0,10);
//llamar al Objeto para crear imagen de fondo
fondo.imagen = new Image(); //instancia de una clase
//carga la fuente de la imagen fondo
fondo.imagen.src= fondo.url;
//evento que permitira dibujar el mapa/fondo
fondo.imagen.addEventListener("load",cargarMapa);
vaca.imagen = new Image();
vaca.imagen.src=vaca.url;
vaca.imagen.addEventListener("load",cargarVaca);
cerdo.imagen = new Image();
cerdo.imagen.src=cerdo.url;
cerdo.imagen.addEventListener("load",cargarCerdo);
document.addEventListener("keydown",dibujarTeclado); //evento para detectar que se clickea boton
pollo.imagen = new Image();
pollo.imagen.src=pollo.url;
pollo.imagen.addEventListener("load",cargarPollo);
//funciones para cargar las imagenes antes de dibujar
function cargarMapa()
{
fondo.cargaOK = true;
dibujar(); //para dibujar despues de cargar
}
function cargarVaca()
{
vaca.cargaOK = true;
dibujar(); //para dibujar despues de cargar
}
function cargarCerdo()
{
cerdo.cargaOK = true;
dibujar(); //para dibujar despues de cargar
}
function cargarPollo()
{
pollo.cargaOK = true;
dibujar(); //para dibujar despues de cargar
}
//funcion para dibujar todo y mostrar por pantalla
function dibujar()
{
if (fondo.cargaOK) //se quito == true porque igual funciona
{
papel.drawImage(fondo.imagen,0,0);
}
if (vaca.cargaOK) //se quito == true porque igual funciona
{
//dibujar v vacas
for(v=0 ; v<cantidad ;v ++)
{
//coordenadas para dibujar en diferentes lugares
var x = aleatorio(0,6);// el segundo numero de rango deberia ser menor del resultado de restar tamaños: 500(total_fondo) - 80(total_vaca)
var y = aleatorio(0,6);
x= x * 60; //para que la imagen no se sobreponga con otra del mismo tipo
y= y* 60;
//dibuja una imagene en las coordenadas indicadas
papel.drawImage(vaca.imagen,x,y);
}
}
if (pollo.cargaOK)
{
papel.drawImage(pollo.imagen,300,300);
}
if (cerdo.cargaOK)
{
papel.drawImage(cerdo.imagen,x_c,y_c);
}
}
function aleatorio(min,max)
{
//funcion que genera numeros aleatorios entre dos valores.
var resultado;
resultado = Math.floor(Math.random() * (max - min + 1)) + min;
return resultado;
}
function dibujarTeclado(evento)
{
//keyCode: obtine el codigo ascci de la tecla presionada
var movimiento = 50; //cantidad de pixeles que se agregara
//objeto creado con el keycode para detectar teclas
var teclas = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
}
switch(evento.keyCode){
case teclas.LEFT:
console.log("Izquierda");
x_c = x_c - movimiento;
dibujar();
break;
case teclas.UP:
console.log("arriba");
y_c = y_c - movimiento;
dibujar();
break;
case teclas.RIGHT:
console.log("derecha");
x_c=x_c + movimiento;
dibujar();
break;
case teclas.DOWN:
console.log("abajo");
y_c = y_c + movimiento;
dibujar();
break;
default:
console.log("Otra tecla");
}
}
|
C#
|
UTF-8
| 2,116
| 2.96875
| 3
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System.Collections.Generic;
namespace Sqloogle.Libs.NLog.Targets
{
/// <summary>
/// Writes log messages to an ArrayList in memory for programmatic retrieval.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/Memory_target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Memory/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Memory/Simple/Example.cs" />
/// </example>
[Target("Memory")]
public sealed class MemoryTarget : TargetWithLayout
{
/// <summary>
/// Initializes a new instance of the <see cref="MemoryTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public MemoryTarget()
{
Logs = new List<string>();
}
/// <summary>
/// Gets the list of logs gathered in the <see cref="MemoryTarget" />.
/// </summary>
public IList<string> Logs { get; private set; }
/// <summary>
/// Renders the logging event message and adds it to the internal ArrayList of log messages.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
var msg = Layout.Render(logEvent);
Logs.Add(msg);
}
}
}
|
JavaScript
|
UTF-8
| 721
| 3
| 3
|
[] |
no_license
|
class Obstacle {
constructor(x,y,obstacleimg){
this.x = x
this.y = y
this.scale = 0.1;
this.body = createSprite(this.x,this.y,50,50)
this.body.addImage(obstacleimg);
this.body.scale = this.scale;
this.body.visible = false;
this.body.isStatic = false;
}
display(){
this.body.visible = true;
}
size(){
this.scale = 0.26;
this.body.scale = this.scale;
}
sizefood(){
this.scale = 0.04;
this.body.scale = this.scale;
}
sizearc(){
this.scale = 0.09;
this.body.scale = this.scale;
}
invisible(){
this.body.visible = false;
}
}
|
Shell
|
UTF-8
| 624
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
# Usage for V8: sh build-linux.sh -DV8_DIR=${HOME}/v8
# Usage for Node: sh build-linux.sh -DNODE_DIR=${HOME}/node
JAVET_VERSION=1.0.0
rm -rf build
mkdir build
cd build
mkdir -p ../../src/main/resources
mkdir -p ../../build/libs
cmake ../ -DJAVET_VERSION=${JAVET_VERSION} "$@" \
&& make -j4 \
&& execstack -c libjavet-*-linux-x86_64.v.${JAVET_VERSION}.so \
&& strip --strip-unneeded -R .note -R .comment libjavet-*-linux-x86_64.v.${JAVET_VERSION}.so
if [ $? -eq 0 ]; then
cp -f *.so ../../src/main/resources
cp -f *.a ../../build/libs
echo Build Completed
else
echo Build Failed
fi
cd ../
|
Python
|
UTF-8
| 193
| 3.65625
| 4
|
[] |
no_license
|
estudante_texto = input('Quantos alunos são? ')
estudante_pizza_int = int (estudante_texto)
nPizzas = int (estudante_pizza_int/1.5) + 1
print("Iremos precisar de ", nPizzas , " pizzas")
|
Java
|
UHC
| 1,034
| 2.359375
| 2
|
[] |
no_license
|
package bank;
public class BankMessage {
public static final String MSG_HELLO = " ȯմϴ";
public static final String MSG_SELECT_MENU = " ּ\n 1. 2.ܾȸ 3.Ա 4. 0. \n";
public static final String MSG_CREATE_ACCOUNT_RESIDENTREGISTRATIONNUMBER = " ֹεϹȣ Էּ :";
public static final String MSG_GET_ACCOUNT_NUMBER = " ȣ %dԴϴ\n";
public static final String MSG_INPUT_ACCOUNT_NUMBER = " ȣ Էϼ\n";
public static final String MSG_CANNOT_FIND_ACCOUNT = " ¸ ã ϴ\n";
public static final String MSG_CURRENT_BALANCE = " ܾ : %d";
public static final String MSG_SET_AMOUNT = " Ա ݾ \n";
public static final String MSG_ERROR_INT = " Է ߸Ǿϴ. ٽԷּ\n";
public static final String MSG_INPUTMISMATCHEXCEPTION = " ƴ ԷµǾϴ. \n";
}
|
Java
|
GB18030
| 552
| 3.34375
| 3
|
[] |
no_license
|
package hotel;
/*
* 徭
* Աһ,ûVIP
* Լн
* */
public class Manager extends Employee{
public Manager() {
super();
}
public Manager(String name, String id, double money) {
super(name, id);
this.money = money;
}
//影
private double money;
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
//д
public void work(){
System.out.println(", ˭ҷ˭");
}
}
|
Python
|
UTF-8
| 626
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
"""
Nozomi
URL Parameter Module
author: hugh@blinkybeach.com
"""
from typing import Any
from nozomi.ancillary.immutable import Immutable
class URLParameter:
"""A single URL parameter, e.g. beep=boop"""
def __init__(
self,
key: str,
value: Any
) -> None:
assert isinstance(key, str)
if isinstance(value, bool):
value = str(value).lower()
str(value) # provoke error early
self._key = key
self._value = value
return
key: str = Immutable(lambda s: s._key)
def __str__(self) -> str:
return self._key + '=' + str(self._value)
|
Python
|
UTF-8
| 1,049
| 3.3125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/2 14:23
# @Author : liuhu
# @File : split_and_compare_version.py
# @Software: PyCharm
# @github :https://github.com/Max-Liuhu
# old_version= '3.4.3.0105'
old_version= '3.4.3.c'
new_version= '3.4.5.0908'
def compare_version(old_version,new_version):
"""
:param old_version: str,'3.4.3.0105'
:param new_version:str,'3.4.5.0908'
:return: if new version bigger than old version,return True ,or False
"""
old_version_split_list = old_version.strip().split('.')
print old_version_split_list
new_version_split_list = new_version.strip().split('.')
print new_version_split_list
compare_value_list=zip(new_version_split_list,old_version_split_list)
print compare_value_list
print len(compare_value_list)
for new_value,old_value in compare_value_list:
if int(new_value) > int(old_value):
return True
else:
continue
return False
if compare_version(old_version,new_version):
print 'ok'
|
TypeScript
|
UTF-8
| 320
| 3.15625
| 3
|
[] |
no_license
|
/**
* Runs Array.map asyncronously.
*
* @param list The array to map
* @param executor The function to run for each
*/
export const asyncMap = async <T, K>(
list: T[],
executor: (element: T, index: number, array: T[]) => Promise<K>
): Promise<K[]> => {
return Promise.all(list.map(executor))
}
// {asyncMap}
|
Markdown
|
UTF-8
| 4,330
| 2.75
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Neonio Theme for Grav

# Built on:
* Bootstrap
# Features:
* HTML5 and CSS3
* Fully Responsive
* Attractive and modern design
* Little effects thats let your layout looks super sexy
# Installation
Installing the Neonio theme can be done in one of two ways. The GPM (Grav Package Manager) installation method enables you to quickly and easily install the theme with a simple terminal command, while the manual method enables you to do so via a zip file.
The theme by itself is useful, but you may have an easier time getting up and running by installing a skeleton. The [Neonio Site Skeleton](https://github.com/getgrav/grav-skeleton-neonio-site) is a self-contained repository for a complete site which includes: sample content, configuration, theme, and plugins.
## GPM Installation (Preferred)
The simplest way to install this theme is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm) through your system's Terminal (also called the command line). From the root of your Grav install type:
bin/gpm install Neonio
This will install the Neonio theme into your `/user/themes` directory within Grav. Its files can be found under `/your/grav/site/user/themes/Neonio`.
## Manual Installation
To install this theme, just download the zip version of this repository and unzip it under `/your/grav/site/user/themes`. Then, rename the folder to `Neonio`. You can find these files either on [GitHub](https://github.com/getgrav/grav-theme-Neonio) or via [GetGrav.org](http://getgrav.org/downloads/themes).
You should now have all the theme files under
/your/grav/site/user/themes/Neonio
>> NOTE: This theme is a modular component for Grav which requires the [Cookies-Policy](https://github.com/giansi/grav-plugin-cookies-policy), [Error](https://github.com/getgrav/grav-theme-error) and [Problems](https://github.com/getgrav/grav-plugin-problems) plugins.
# Updating
As development for the Neonio theme will not continue yet, new versions may become available in future. I've not so much time to bring new features or improve things, so please share your customizations or fork this project. Updating Neonio is easy, and can be done through Grav's GPM system, as well as manually.
## GPM Update (Preferred)
The simplest way to update this theme is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm). You can do this with this by navigating to the root directory of your Grav install using your system's Terminal (also called command line) and typing the following:
bin/gpm update Neonio
This command will check your Grav install to see if your Boxify theme is due for an update. If a newer release is found, you will be asked whether or not you wish to update. To continue, type `y` and hit enter. The theme will automatically update and clear Grav's cache.
## Manual Update
Manually updating Neonio is pretty simple. Here is what you will need to do to get this done:
* Delete the `your/site/user/themes/Neonio` directory.
* Download the new version of the Boxify theme from either [GitHub](https://github.com/getgrav/grav-theme-Neonio) or [GetGrav.org](http://getgrav.org/downloads/themes).
* Unzip the zip file in `your/site/user/themes` and rename the resulting folder to `Neonio`.
* Clear the Grav cache. The simplest way to do this is by going to the root Grav directory in terminal and typing `bin/grav clear-cache`.
> Note: Any changes you have made to any of the files listed under this directory will also be removed and replaced by the new set. Any files located elsewhere (for example a YAML settings file placed in `user/config/themes`) will remain intact.
# Setup
If you want to set Promdia as the default theme, you can do so by following these steps:
* Navigate to `/your/grav/site/user/config`.
* Open the **system.yaml** file.
* Change the `theme:` setting to `theme: Neonio`.
* Save your changes.
* Clear the Grav cache. The simplest way to do this is by going to the root Grav directory in Terminal and typing `bin/grav clear-cache`.
Once this is done, you should be able to see the new theme on the frontend. Keep in mind any customizations made to the previous theme will not be reflected as all of the theme and templating information is now being pulled from the **Neonio** folder.
|
JavaScript
|
UTF-8
| 9,642
| 3.203125
| 3
|
[] |
no_license
|
/**
* This script is responsible for initializing all radio buttons and text fields
* with the appropriate onClick or onSubmit functions. Each of these functions
* responds to user click by saving the appropriate values in localStorage. This
* has all been moved into its own script to prevent clutter in the HTML file.
*/
/**
* Function is responsible for launching modal based on parameters. The button calling the function
* will pass an identifying value.
*/
function initEdit(type, step){
if(type === 'oxygen'){
if(step === 'init'){
launchModal("Oxygen Initiated At", "Oxygen_Supplementation_Initiated", "Oxygen_Supplementation_History", "initiated" );
}
else{
launchModal("Oxygen Stopped At","Oxygen_Supplementation_Stopped", "Oxygen_Supplementation_History", "Stopped" );
}
}
else if(type === 'bag'){
if(step === 'init'){
launchModal("Bag Initiated At","Bag_Mask_Initiated", "Bag_Mask_History", "initiated");
}
else{
launchModal("Bag Stopped At","Bag_Mask_Stopped", "Bag_Mask_History", "Stopped");
}
}
else if(type === 'lma'){
if(step === 'init'){
launchModal("LMA Initiated At","LMA_Initiated", "LMA_History", "initiated");
}
else if (step === 'achieved') {
launchModal("LMA Achieved At","LMA_Achieved", "LMA_History", "achieved");
}
else{
launchModal("LMA Removed At","LMA_Stopped", "LMA_History", "Removed");
}
}
else if(type === 'ett'){
if(step === 'init'){
launchModal("ETT Initiated At","ETT_Initiated", "ETT_History", "initiated");
}
else if (step === 'achieved') {
launchModal("ETT Achieved At","ETT_Achieved", "ETT_History", "achieved");
}
else{
launchModal("ETT Removed At","ETT_Stopped", "ETT_History", "Removed");
}
}
else if(type === 'diffAirway'){
if(step === 'init'){
launchModal("Difficult Airway Initiated At","Difficult_Airway_Initiated", "Difficult_Airway_History", "initiated");
}
else if (step === 'achieved') {
launchModal("Difficult Airway Achieved At","Difficult_Airway_Achieved", "Difficult_Airway_History", "achieved");
}
else{
launchModal("Difficult Airway Removed At","Difficult_Airway_Stopped", "Difficult_Airway_History", "Removed");
}
}
else{
if(step === 'init'){
launchModal("Surgical Airway Initiated At","Surgical_Airway_Initiated", "Surgical_Airway_History", "initiated");
}
else if (step === 'achieved') {
launchModal("Surgical Airway Achieved At","Surgical_Airway_Achieved", "Surgical_Airway_History", "achieved");
}
else{
launchModal("Surgical Airway Removed At","Surgical_Airway_Stopped", "Surgical_Airway_History", "Removed");
}
}
}
/**
* Reads the time stamp from user input fields and returns it to be saved in the database
* @returns {string}
*/
function fetchTimeModal(){
var hour = Math.round(parseInt(document.getElementById('hourStamp').value, 10));
var min = Math.round(parseInt(document.getElementById('minuteStamp').value, 10));
var sec =Math.round(parseInt(document.getElementById('secondStamp').value, 10));
var timeStamp = hour.toString(10) + "hr " + min.toString(10) + "min " + sec.toString(10) + "sec";
return timeStamp;
}
/**
* Launches the time stamp edit modal and sets up corresponding buttons
*
* @param modalTitle
* @param step
*/
function launchModal(modalTitle, step, historyKey, historyValue) {
var min = Math.round((parseInt(localStorage.getItem('total_seconds_main'),10))/60);
var sec = Math.round((parseInt(localStorage.getItem('total_seconds_main'),10))%60);
var hour = 0;
if(min < 1){
min = 0;
}
if(min >= 60){
hour = Math.round(min/60);
min = Math.round(min%60);
}
var saveBtn = document.getElementById('saveTime');
saveBtn.onclick = function(){
var timeStamp = fetchTimeModal();
setItemAjax(step, timeStamp);
updateAirwayHistory(historyKey, historyValue, timeStamp)
$("#timeModal").modal('hide');
}
document.getElementById('time-title').innerHTML = modalTitle;
document.getElementById('hourStamp').value = hour;
document.getElementById('minuteStamp').value = min;
document.getElementById('secondStamp').value = sec;
$("#timeModal").modal();
}
/**
* Because these will require pop-up modals to prompt further information they need their own
* onclick functions
*/
function ettModal() {
var saveBtn = document.getElementById('saveETT');
document.getElementById('ett-title').innerHTML = "Enter The Following";
$("#ettModal").modal();
saveBtn.onclick = function () {
var rr = (document.getElementById('ettRR').value).toString(10);
var depth = (document.getElementById('ettDepth').value).toString(10);
var display = "ETT Depth: " + depth + "cm RR: " + rr;
localStorage.setItem("ETT_Display", display);
setItemAjax('ETT_RR', rr);
setItemAjax('ETT_Depth', depth);
setItemAjax('ETT_Initiated', getCurrentTime());
updateAirwayHistory('ETT_History', 'achieved', ' At ' + getCurrentTime() + ' with RR of ' + rr + ' and depth of ' + depth + 'cm')
$("#ettModal").modal('hide');
}
}
function bagMaskModal() {
var saveBtn = document.getElementById('saveBag');
document.getElementById('bag-title').innerHTML = "Enter The Following";
$("#bagMaskModal").modal();
saveBtn.onclick = function () {
var time = getCurrentTime();
var rr = (document.getElementById('bagMaskRR').value).toString(10);
var display = "Bag Mask RR: " + rr;
localStorage.setItem("BagMask_Display", display);
setItemAjax('Bag_Mask_RR', rr);
setItemAjax('Bag_Mask_Initiated', time);
updateAirwayHistory('Bag_Mask_History', 'initiated', ' At ' + time + ' with a RR of ' + rr);
$("#bagMaskModal").modal('hide');
}
}
function ivfModal() {
var saveBtn = document.getElementById('saveIVF');
document.getElementById('ivf-title').innerHTML = "Enter The Following";
$("#ivfModal").modal();
saveBtn.onclick = function () {
var time = getCurrentTime();
var ivf_prev = parseInt(localStorage.getItem('IVF'),10);
var ivf_added = parseInt(document.getElementById('ivfAmount').value,10);
var ivf_new = (ivf_prev + ivf_added);
var display = "IVF: " + ivf_new.toString(10) + " mL/kg";
localStorage.setItem('IVF_Display', display);
localStorage.setItem('IVF', ivf_new.toString(10));
setItemAjax('IVF_Total', ivf_new.toString(10));
updateIVFHistory('IVF_History', ivf_added.toString(10), time);
$("#ivfModal").modal('hide');
}
}
function diffAirwayModal() {
var saveBtn = document.getElementById('saveDiffAirway');
document.getElementById('diffAirway-title').innerHTML = "Enter The Following";
$("#diffAirwayModal").modal();
saveBtn.onclick = function () {
var time = getCurrentTime();
var adjunct = document.getElementById('adjunct').value;
var display = "Difficult Airway: " + adjunct;
localStorage.setItem('DiffAirway_Display', display);
setItemAjax('Difficult_Airway_Adjunct', adjunct);
updateAirwayHistory('Difficult_Airway_History', 'initiated', ' At ' + time + ' using ' + adjunct);
$("#diffAirwayModal").modal('hide');
}
}
/**
* Gets the current time stamp and returns it in a "displayable" format
* @returns {string}
*/
function getCurrentTime(){
var min = Math.round((parseInt(localStorage.getItem('total_seconds_main'),10))/60);
var sec = Math.round((parseInt(localStorage.getItem('total_seconds_main'),10))%60);
var hour = 0;
var timeStamp = " ";
if(min < 1){
min = 0;
}
if(min >= 60){
hour = Math.round(min/60);
min = Math.round(min%60);
}
if(hour !== 0){
timeStamp = hour.toString(10) + "hr " + min.toString(10) + "min " + sec.toString(10) + "sec";
}
else{
timeStamp = min.toString(10) + "min " + sec.toString(10) + "sec";
}
return timeStamp;
}
function setItemAjax(step, value){
$.ajax(
{
type:"POST",
url: "/setItem/",
data:{
'key': step,
'value': value,
},
success: function( data )
{}
})
}
function recordAbnormality(inputId, modelName) {
var abnormality = document.getElementById(inputId).value;
document.getElementById(inputId).value = ' ';
$.ajax(
{
type:"POST",
url: "/setItem/",
data:{
'key': modelName,
'value': abnormality,
},
success: function( data )
{}
})
}
function updateAirwayHistory(historyKey, step, timeStamp){
$.ajax({
type:"POST",
url: '/updateAirwayHistory/',
data: {
'historyKey': historyKey,
'step': step,
'timeStamp': timeStamp
},
success: function( data ) {
}
});
}
function updateIVFHistory(historyKey, value, timeStamp){
$.ajax({
type:"POST",
url: '/updateHistoryUnknown/',
data: {
'historyKey': historyKey,
'value': value,
'timeStamp': timeStamp
},
success: function( data ) {
}
});
}
|
Java
|
UTF-8
| 9,670
| 1.78125
| 2
|
[] |
no_license
|
/**
*/
package com.mimacom.ddd.pub.proto.impl;
import com.mimacom.ddd.pub.proto.ProtoDocumentSegment;
import com.mimacom.ddd.pub.proto.ProtoPackage;
import com.mimacom.ddd.pub.proto.PublicationClass;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Document Segment</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.mimacom.ddd.pub.proto.impl.ProtoDocumentSegmentImpl#getName <em>Name</em>}</li>
* <li>{@link com.mimacom.ddd.pub.proto.impl.ProtoDocumentSegmentImpl#getTitle <em>Title</em>}</li>
* <li>{@link com.mimacom.ddd.pub.proto.impl.ProtoDocumentSegmentImpl#isOptional <em>Optional</em>}</li>
* <li>{@link com.mimacom.ddd.pub.proto.impl.ProtoDocumentSegmentImpl#getParent <em>Parent</em>}</li>
* </ul>
*
* @generated
*/
public abstract class ProtoDocumentSegmentImpl extends MinimalEObjectImpl.Container implements ProtoDocumentSegment {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The default value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected static final String TITLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected String title = TITLE_EDEFAULT;
/**
* The default value of the '{@link #isOptional() <em>Optional</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isOptional()
* @generated
* @ordered
*/
protected static final boolean OPTIONAL_EDEFAULT = false;
/**
* The cached value of the '{@link #isOptional() <em>Optional</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isOptional()
* @generated
* @ordered
*/
protected boolean optional = OPTIONAL_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ProtoDocumentSegmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ProtoPackage.Literals.PROTO_DOCUMENT_SEGMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return this.eClass().getName().toLowerCase();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getTitle() {
return title;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTitle(String newTitle) {
String oldTitle = title;
title = newTitle;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ProtoPackage.PROTO_DOCUMENT_SEGMENT__TITLE, oldTitle, title));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isOptional() {
return optional;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOptional(boolean newOptional) {
boolean oldOptional = optional;
optional = newOptional;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ProtoPackage.PROTO_DOCUMENT_SEGMENT__OPTIONAL, oldOptional, optional));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PublicationClass getParent() {
if (eContainerFeatureID() != ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT) return null;
return (PublicationClass)eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PublicationClass basicGetParent() {
if (eContainerFeatureID() != ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT) return null;
return (PublicationClass)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetParent(PublicationClass newParent, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newParent, ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParent(PublicationClass newParent) {
if (newParent != eInternalContainer() || (eContainerFeatureID() != ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT && newParent != null)) {
if (EcoreUtil.isAncestor(this, newParent))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newParent != null)
msgs = ((InternalEObject)newParent).eInverseAdd(this, ProtoPackage.PUBLICATION_CLASS__SEGMENTS, PublicationClass.class, msgs);
msgs = basicSetParent(newParent, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT, newParent, newParent));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetParent((PublicationClass)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
return basicSetParent(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
return eInternalContainer().eInverseRemove(this, ProtoPackage.PUBLICATION_CLASS__SEGMENTS, PublicationClass.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__NAME:
return getName();
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__TITLE:
return getTitle();
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__OPTIONAL:
return isOptional();
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
if (resolve) return getParent();
return basicGetParent();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__TITLE:
setTitle((String)newValue);
return;
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__OPTIONAL:
setOptional((Boolean)newValue);
return;
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
setParent((PublicationClass)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__TITLE:
setTitle(TITLE_EDEFAULT);
return;
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__OPTIONAL:
setOptional(OPTIONAL_EDEFAULT);
return;
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
setParent((PublicationClass)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__NAME:
return NAME_EDEFAULT == null ? getName() != null : !NAME_EDEFAULT.equals(getName());
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__TITLE:
return TITLE_EDEFAULT == null ? title != null : !TITLE_EDEFAULT.equals(title);
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__OPTIONAL:
return optional != OPTIONAL_EDEFAULT;
case ProtoPackage.PROTO_DOCUMENT_SEGMENT__PARENT:
return basicGetParent() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (title: ");
result.append(title);
result.append(", optional: ");
result.append(optional);
result.append(')');
return result.toString();
}
} //ProtoDocumentSegmentImpl
|
TypeScript
|
UTF-8
| 1,844
| 3.65625
| 4
|
[
"Apache-2.0"
] |
permissive
|
import curryN from './curryN';
import reduce from '../array/reduce';
import pluck from '../array/pluck';
import map from '../array/map';
interface ConvergeAfterFn {
(...args: any[]): any;
}
interface ConvergeArgFn {
(...args: any[]): any;
}
interface Converge {
(after: ConvergeAfterFn, fns: ConvergeArgFn[]): ConvergeArgFn;
(after: ConvergeAfterFn): (fns: ConvergeArgFn[]) => ConvergeArgFn;
}
/**
* Accepts a converging function and a list of branching functions and returns
* a new function. The arity of the new function is the same as the arity of
* the longest branching function. When invoked, this new function is applied
* to some arguments, and each branching function is applied to those same
* arguments. The results of each branching function are passed as arguments
* to the converging function to produce the return value.
*
* @sig ((x1, x2, ...) -> z) -> [((a, b, ...) -> x1), ((a, b, ...) -> x2), ...] -> (a -> b -> ... -> z)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {Array} functions A list of functions.
* @return {Function} A new function.
* @example
*
* const average = converge(divide, [sum, length])
* average([1, 2, 3, 4, 5, 6, 7]) //=> 4
*
* const strangeConcat = converge(concat, [toUpper, toLower])
* strangeConcat("Yodel") //=> "YODELyodel"
*
* @symb converge(f, [g, h])(a, b) = f(g(a, b), h(a, b))
*/
export const converge = curryN(2, function converge(after: ConvergeAfterFn, fns: ConvergeArgFn[]) {
// @ts-ignore
const maxNumArgs = reduce((a, b) => Math.max(a, b), 0, pluck('length', fns));
return curryN(maxNumArgs, function(...args) {
return after.apply(this, map(fn => fn.apply(this, args), fns));
});
}) as Converge;
export default converge;
|
Java
|
UHC
| 933
| 2.84375
| 3
|
[] |
no_license
|
package com.kwon.db.main;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectMain {
public static void main(String[] args) {
// OracleDriver ְ : ojdbc8.jar
Connection con = null;
try {
// DBּ( DBĿ ٸ)
String url = "jdbc:oracle:thin:@192.168.0.46:1521:xe";
// Ŭ
// Class.forName("oracle.jdbc.driver.OracleDriver");
// DB Ű
// Class.forName ̹ ڹٰ ãƼ
// ڵ ã
//
con = DriverManager.getConnection(url, "kwon", "kwon");
System.out.println("");
// SQL
//
// ƿ
} catch (Exception e) {
e.printStackTrace();
} finally {
try {con.close();} catch (SQLException e) {}
}
}
}
|
C++
|
UTF-8
| 2,520
| 3.59375
| 4
|
[
"MIT"
] |
permissive
|
//
// main.cpp
// Hw9-2
// Find Substring From Dictionary (Vector of Char)
//
// Created by Tomy Hsieh on 2017/11/21.
// Copyright © 2017年 Tomy Hsieh. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// prints all English words which are contiguous substrings of inputtedWord into a file
void embeddedWords(vector<char> &dictionaryWord, vector<char> &inputtedWord);
// returns true if and only if dictionaryWord is a substring of inputtedWord
bool isSubstring(vector<char> &dictionaryWord, vector<char> &inputtedWord);
int main() {
vector<char> inputtedWord;
cout << "Enter a word: ";
char ch = cin.get();
while (ch != '\n') {
inputtedWord.push_back(ch);
ch = cin.get();
}
vector<char> dictionaryWord;
embeddedWords(dictionaryWord, inputtedWord);
}
void embeddedWords(vector<char> &dictionaryWord, vector<char> &inputtedWord) {
ifstream inFile("Dictionary.txt", ios::in);
if (!inFile) {
cout << "File could not be opened" << endl;
exit(1);
}
ofstream outFile("Word.txt", ios::out);
if (!outFile) {
cout << "File could not be saved" << endl;
exit(1);
}
while (inFile.peek() != EOF) {
char ch;
while (inFile.get(ch) && ch != '\n') {
dictionaryWord.push_back(ch);
}
//dictionaryWord.pop_back();
if (isSubstring(dictionaryWord, inputtedWord)) {
for (int i = 0; i<dictionaryWord.size(); i++) {
outFile << dictionaryWord[i];
cout << dictionaryWord[i];
}
outFile << endl;
cout << endl;
}
dictionaryWord.clear();
}
inFile.close();
outFile.close();
}
bool isSubstring(vector<char> &dictionaryWord, vector<char> &inputtedWord) {
for (int i = 0; i<inputtedWord.size(); i++) {
if (dictionaryWord[0] == inputtedWord[i]) {
if (dictionaryWord.size() == 1) {
return true;
}
else {
bool Sub = true;
for (int j = 1; j<dictionaryWord.size(); j++) {
if (i+j >= inputtedWord.size() || dictionaryWord[j] != inputtedWord[i+j]) {
Sub = false;
break;
}
}
if (Sub) {
return true;
}
}
}
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.