language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,651 | 2.90625 | 3 | [] | no_license | using System;
using System.Diagnostics;
using System.Threading;
namespace BasicLib.Util{
public class Logger{
public static LogLevel loglevel = LogLevel.Info;
private static string Prefix { get { return string.Format(" [P{0}-T{1}] ", Process.GetCurrentProcess().Id, Thread.CurrentThread.ManagedThreadId); } }
public static void Debug(string className, string message){
if (loglevel >= LogLevel.Debug){
Console.Out.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(DEBUG) - " + className + ": " + message);
}
}
public static void Info(string className, string message){
if (loglevel >= LogLevel.Info){
Console.Out.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(INFO) - " + className + ": " + message);
}
}
public static void Error(string className, string message){
if (loglevel >= LogLevel.Error){
Console.Error.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(ERROR) - " + className + ": " + message);
}
}
public static void Error(string className, Exception ex){
if (loglevel >= LogLevel.Error){
Console.Error.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(ERROR) - " + className + ": " + ex + "\n" +
ex.StackTrace);
}
}
public static void Warn(string className, string message){
if (loglevel >= LogLevel.Warn){
Console.Out.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(WARN) - " + className + ": " + message);
}
}
public static void Warn(string className, Exception ex){
if (loglevel >= LogLevel.Warn){
Console.Out.WriteLine(DateTime.Now.ToUniversalTime() + Prefix + "(WARN) - " + className + ": " + ex);
}
}
}
} |
PHP | UTF-8 | 2,393 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of bit3/git-php.
*
* (c) Tristan Lins <tristan@lins.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package bit3/git-php
* @author Aaron Rubin <aaron@arkitech.net>
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author Sven Baumann <baumann.sv@gmail.com>
* @copyright 2014-2022 Tristan Lins <tristan@lins.io>
* @license https://github.com/bit3/git-php/blob/master/LICENSE MIT
* @link https://github.com/bit3/git-php
* @filesource
*/
namespace Bit3\GitPhp\Command;
/**
* Merge command builder.
*/
class MergeCommandBuilder implements CommandBuilderInterface
{
use CommandBuilderTrait;
/**
* {@inheritDoc}
*/
protected function initializeProcessBuilder()
{
$this->arguments[] = 'merge';
}
/**
* Add the quiet option to the command line.
*
* @return MergeCommandBuilder
*/
public function quiet()
{
$this->arguments[] = '--quiet';
return $this;
}
/**
* Add the strategy option to the command line with the given strategy.
*
* @param string $strategy Strategy to use when merging.
*
* @return MergeCommandBuilder
*/
public function strategy($strategy)
{
$this->arguments[] = '--strategy=' . $strategy;
return $this;
}
/**
* Build the command and execute it.
*
* @param null|string $branchOrTreeIsh Name of the branch or tree.
*
* @param null $path Path to which check out.
*
* @param null|string $_ More optional arguments to append to the command.
*
* @return mixed
*
* @SuppressWarnings(PHPMD.ShortVariableName)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @SuppressWarnings(PHPMD.CamelCaseParameterName)
*/
public function execute($branchOrTreeIsh = null, $path = null, $_ = null)
{
if ($branchOrTreeIsh) {
$this->arguments[] = $branchOrTreeIsh;
}
$paths = \func_get_args();
\array_shift($paths);
if (\count($paths)) {
$this->arguments[] = '--';
foreach ($paths as $path) {
$this->arguments[] = $path;
}
}
return $this->run();
}
}
|
Java | UTF-8 | 2,531 | 2.515625 | 3 | [] | no_license | /**
* 文件名:WyxMenuServiceImpl.java</br>
* @file WyxMenuServiceImpl.java</br>
* 描述: </br>
* 开发人员:zhanghs </br>
* 创建时间: 2014-7-28
*/
package com.cndatacom.industry.service.impl;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.cndatacom.industry.bean.RetailHotel;
import com.cndatacom.industry.dao.IRetailHotelDao;
import com.cndatacom.industry.service.IRetailHotelService;
/**
* 类名: RetailHotelServiceImpl</br>
* 包名:com.cndatacom.industry.service.impl </br>
* 描述: 酒店管理service</br>
* 发布版本号:1.0</br>
* 开发人员: lbw</br>
* 创建时间: 2014-9-15
*/
@Service("retailHotelService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
public class RetailHotelServiceImpl implements IRetailHotelService{
Logger log = LoggerFactory.getLogger(getClass());
@Resource(name="retailHotelDao")
private IRetailHotelDao retailHotelDao;
/**
* 方法名:saveRetailHotel</br>
* 详述:保存酒店信息</br>
* 开发人员:lbw</br>
* 创建时间:2014-9-15</br>
* @param retailHotel
* @return
* @throws Exception
*/
@Override
public void saveRetailHotel(RetailHotel retailHotel) {
if(null != retailHotel.getId()){
RetailHotel oldRetailHotel = this.retailHotelDao.getAndInitEntity(retailHotel.getId());
if(oldRetailHotel!=null){
oldRetailHotel.setHotelName(retailHotel.getHotelName());
oldRetailHotel.setAddress(retailHotel.getAddress());
oldRetailHotel.setMeno(retailHotel.getMeno());
oldRetailHotel.setPhone(retailHotel.getPhone());
oldRetailHotel.setIntroduce(retailHotel.getIntroduce());
oldRetailHotel.setInstallation(retailHotel.getInstallation());
this.retailHotelDao.save(oldRetailHotel);
}
}else{
this.retailHotelDao.save(retailHotel);
}
}
/**
* 方法名:getRetailInfo</br>
* 详述:根据useriD酒店信息</br>
* 开发人员:lbw</br>
* 创建时间:2014-9-15</br>
* @param userId
* @return
* @throws Exception
*/
@Override
public RetailHotel getRetailInfo(Long userId) {
return this.retailHotelDao.findUniqueBy("userId", userId);
}
}
|
C++ | UTF-8 | 1,649 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <deque>
using namespace std;
void printq(deque<int> d);
int main() {
int num = 0;
int cards = 0;
int card = 0;
cin >> num;
deque<int> deck;
for(int i = 0; i<num; i++) {
cin >> cards;
for(int j = 0; j<cards; j++) {
deck.push_back(0);
}
for(int j = 1; j<=cards; j++) {
for(int k = 1; k<=j; k++) {
card = deck.front();
deck.pop_front();
deck.push_back(card);
if(card != 0) {
k--;
}
}
while(true) {
if(deck.front() == 0) {
deck.pop_front();
deck.push_back(j);
break;
}else {
card = deck.front();
deck.pop_front();
deck.push_back(card);
}
}
}
// printq(deck);
while(deck.size() >1) {
card = deck.front();
deck.pop_front();
if(deck.front() == 1) {
deck.push_front(card);
break;
}
deck.push_front(card);
deck.push_back(deck.front());
deck.pop_front();
}
while(!deck.empty()) {
cout << deck.front() << ' ';
deck.pop_front();
}
cout << endl;
}
}
void printq(deque<int> d) {
for(int i = 0; i<d.size(); i++) {
cout << d.front() << ' ';
d.push_back(d.front());
d.pop_front();
}
cout << endl;
}
|
Markdown | UTF-8 | 375 | 2.546875 | 3 | [] | no_license | #AES
[高级加密标准(AES)](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) 的JavaScript实现
##感谢及参考
- [@李松](https://github.com/SongLee24) 的 [博客](http://songlee24.github.io/blog/2014/12/13/aes-encrypt/)
- [HTML5 FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
- [写文件](http://stackoverflow.com/a/21016088) |
Python | UTF-8 | 2,765 | 2.6875 | 3 | [] | no_license | import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.calibration import calibration_curve
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LogisticRegression
class Calibrator:
ISOTONIC_REGRESSION = "isotonic_regression"
PLATT_SCALING = "platt_scaling"
def __init__(self, num_bins=10, model_type=None):
self.num_bins = num_bins
if model_type == self.ISOTONIC_REGRESSION:
self.model = IsotonicRegression()
else:
self.model = LogisticRegression()
def _get_bin_sizes(self, y_prob, num_bins):
bins = np.linspace(0., 1. + 1e-8, num_bins +1)
# 告诉每个概率属于哪一个区间
bin_indies = np.digitize(y_prob, bins) - 1
# 计算每个区间的样本个数
bin_sizes = np.bincount(bin_indies, minlength=len(bins))
# 跳过空的区间
bin_sizes = [i for i in bin_sizes if i != 0]
return bin_sizes
def plot_reliability_diagrams(self, truth_label, pred_prob, label, output_path):
truth_label, pred_prob = calibration_curve(truth_label, pred_prob, self.num_bins)
plt.figure(figsize=(10, 10))
plt.gca()
plt.plot([0, 1], [0, 1], color="r", linestyle=":", label="Prefect Calibration")
plt.plot(pred_prob, truth_label, label=label)
plt.ylabel("Accuracy", fontsize=16)
plt.xlabel("Confidence", fontsize=16)
plt.grid(True, color="b")
plt.legend(fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
save_path = os.path.join(output_path, "{}.png".format(label))
plt.savefig(fname=save_path, format="png")
def cal_ece(self, truth_label, pred_prob, bin_sizes):
ece = np.float32(0)
total_samples = sum(bin_sizes)
for m in range(len(bin_sizes)):
ece = ece + (bin_sizes[m] / total_samples) * np.abs(truth_label[m] - pred_prob[m])
return ece.item()
def fit(self, truth_label, pred_prob):
bin_sizes = self._get_bin_sizes(pred_prob, self.num_bins)
uncalibrated_ece = self.cal_ece(truth_label, pred_prob, bin_sizes)
expanded_pred_prob = np.expand_dims(pred_prob, axis=1)
self.model.fit(expanded_pred_prob, truth_label)
calibrated_prob = self.model.predict_proba(expanded_pred_prob)
bin_sizes = self._get_bin_sizes(calibrated_prob.flatten(), self.num_bins)
calibrated_ece = self.cal_ece(truth_label, calibrated_prob.flatten(), bin_sizes)
return uncalibrated_ece, calibrated_ece
def calibrate(self, pred_prob):
expanded_pred_prob = np.expand_dims(pred_prob, axis=1)
return self.model.predict_proba(expanded_pred_prob)
|
Java | UTF-8 | 1,633 | 3.375 | 3 | [
"MIT"
] | permissive | package com.groupname.game.entities.powerups;
import com.groupname.framework.graphics.Sprite;
import com.groupname.framework.math.Vector2D;
import com.groupname.game.entities.Player;
import java.util.Objects;
/**
* HeartPowerUp is an PowerUp that give life to the player.
* The amount of life it gives is controllable.
*/
public class HeartPowerUp extends PowerUp {
private final int hearts;
/**
* The constructor of the object.
*
* @param sprite the sprite of the object.
* @param position the position of the object.
* @param hearts the amount of life it gives the player.
*/
public HeartPowerUp(Sprite sprite, Vector2D position, int hearts) {
super(sprite, position);
if(hearts <= 0){
throw new NullPointerException();
}
this.hearts = hearts;
}
/**
* Method that give life to the player when collecting the object.
*
* @param player the player that collects the object.
*/
@Override
public void onCollect(Player player) {
super.onCollect(player);
int newHitpoints = player.getHitPoints() + hearts;
if(newHitpoints > player.getMaxHitpoints()) {
newHitpoints = player.getMaxHitpoints();
}
player.setHitPoints(newHitpoints);
}
/**
* Returns the String representation of this instance.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return super.toString() +
"HeartPowerUp{" +
"hearts=" + hearts +
'}';
}
}
|
Java | UTF-8 | 744 | 2.921875 | 3 | [] | no_license | import java.util.Scanner;
public class Phantichthuasonguyento {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int test=sc.nextInt();
for(int t=1;t<=test;t++)
{
long n =sc.nextLong();
System.out.print("Test "+t+": ");
for(int i=2;i<=n;i++)
{
if(n%i==0)
{
int dem=0;
while(n%i==0)
{
dem++;
n/=i;
}
System.out.print(i+"("+dem+") ");
}
}
System.out.println("");
}
sc.close();
}
}
|
Java | UTF-8 | 775 | 2.90625 | 3 | [] | no_license | package edu.neumont.learnignChess.model;
import java.util.Enumeration;
import edu.neumont.learningChess.api.Location;
public class Knight extends ChessPiece {
public static final String NAME = "Knight";
private static final int WORTH = 3;
private static Adjustment[] knightAdjustments = {
new Adjustment(2,1),
new Adjustment(2,-1),
new Adjustment(-2,1),
new Adjustment(-2,-1),
new Adjustment(1,2),
new Adjustment(-1,2),
new Adjustment(1,-2),
new Adjustment(-1,-2)
};
public Knight() {
super(WORTH);
}
public String getName() {
return NAME;
}
public Enumeration<Location> getLegalMoves(ChessBoard board) {
MoveEnumeration moves = new MoveEnumeration(board, location);
moves.addAdjustments(knightAdjustments);
return moves;
}
}
|
Markdown | UTF-8 | 937 | 2.671875 | 3 | [] | no_license | # Article L2325-14
Dans les entreprises d'au moins trois cents salariés, le comité d'entreprise se réunit au moins une fois par mois sur
convocation de l'employeur ou de son représentant.
Dans les entreprises de moins de trois cents salariés, le comité se réunit au moins une fois tous les deux mois.
Le comité peut tenir une seconde réunion à la demande de la majorité de ses membres.
Lorsque l'employeur est défaillant, et à la demande d'au moins la moitié des membres du comité, celui-ci peut être convoqué
par l'inspecteur du travail et siéger sous sa présidence.
**Nota:**
**Liens relatifs à cet article**
**Codifié par**:
- Ordonnance n°2007-329 du 12 mars 2007
**Modifié par**:
- Loi n°2015-994 du 17 août 2015 - art. 22
**Cité par**:
- Code du travail - art. L2323-7 (VD)
- Code du travail - art. R2323-32 (V)
**Anciens textes**:
- Code du travail - art. L434-3 (AbD)
|
Shell | UTF-8 | 207 | 3.3125 | 3 | [] | no_license | #!/bin/bash
echo "{"
while [ $# -gt 0 ] ;
do
echo -n " \"$(basename "$1" | sed -e 's/\./_/g' -e 's/_sum$//')\": \"$(cat "$1")\""
shift
if [ $# -gt 0 ] ; then echo -n "," ; fi
echo ""
done
echo "}"
|
C++ | UTF-8 | 1,721 | 3.828125 | 4 | [] | no_license | /* Declare any non-required functions above main.
* The duty of main here is to interact with the user, take in input, and manage wrapping output and runtime.
* Remember, if you are considering putting something in main or a function, double check the specifications.
* Each function should only do what it is specified to do, and no more.
*/
#include "maze.h"
int main()
{
int rows; //variable declaration for rows
int row; //variable declaration for pass by reference row
int col; //varaibel declaration for pass by reference col
int cases = 0; //cases starts at 0
//runs while the row is not equal to 0
// terminates the program when rows are equal to zero
while(rows != 0)
{
string* array = NULL; //intializing the pointer array to null
cin >> rows; //gets the input from the user
if(rows != 0)//if row is not equal to zero
{
cin.ignore(); //discard any newlines
array = build_matrix(rows); //calls in the build_matrix function
fill_matrix(array, rows); //calls the fill_matrix function
find_start(array, rows, row, col); //calls the find_start function
//if not find_exit, then outputs the no solution message
if(!find_exit(array, row, col))
cout << "Map "<< cases << " -- No solution found: " << endl;
else //is found the exit, then outputs the following message
cout << "Map " << cases << " -- Solution found:" << endl;
//Puts the starting point
array[row][col] = 'N';
print_matrix(array, rows); //prints the solved maze
cases++; //increments the cases
delete_matrix(array); //deletes the matrix array
}
cout << endl; //puts space in the outputs
}
return 0;
}
|
Java | UTF-8 | 367 | 1.5625 | 2 | [
"BSD-3-Clause"
] | permissive | /*
* This software is provided "AS IS" without a warranty of any kind.
* You use it on your own risk and responsibility!!!
*
* This file is shared under BSD v3 license.
* See readme.txt and BSD3 file for details.
*
*/
package kendzi.josm.kendzi3d.jogl.model.lod;
public enum LOD {
LOD1,
LOD2,
LOD3,
LOD4,
LOD5;
// toPropertitesName
}
|
Java | UTF-8 | 4,406 | 2.3125 | 2 | [] | no_license | package pl.lodz.sda;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.log4j.Logger;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.apache.log4j.Logger.getLogger;
public class MongoDBConnector implements MongoDBConnectorApi{
final static Logger logger = getLogger(MongoDBConnector.class);
private PropertiesLoader propertiesLoader = new PropertiesLoader();
private MongoClient client;
private void prepareConfiguration() {
ServerAddress address = new ServerAddress(propertiesLoader.getHost(), propertiesLoader.getPort());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
MongoCredential credential = MongoCredential.createCredential(propertiesLoader.getUser(),
propertiesLoader.getSchema(), propertiesLoader.getPass().toCharArray());
credentials.add(credential);
client = new MongoClient(address, credentials);
}
private void init() {
try {
propertiesLoader.init();
prepareConfiguration();
} catch (IOException e) {
logger.error(e);
}
}
private MongoDatabase connect() {
init();
return client.getDatabase(propertiesLoader.getSchema());
}
public FindIterable<Document> findDocuments(String collectionName,
Bson filter,
Bson projection) {
MongoCollection<Document> collection = toMongoCollection(collectionName);
return collection.find(filter).projection(projection);
}
public AggregateIterable<Document> aggregateDocuments(String collectionName,
List<Bson> pipeline) {
MongoCollection<Document> collection = toMongoCollection(collectionName);
return collection.aggregate(pipeline);
}
private MongoCollection<Document> toMongoCollection(String collectionName) {
MongoDatabase connect = connect();
return connect.getCollection(collectionName);
}
//
//
// public static void main(String[] args) throws IOException {
//
// MongoCollection<Document> documentCollection = database.getCollection("grades");
// /*student_id: {
// $gt: 100
// }*/
// // budowanie strasznego bsona
// Document bson = new Document().append("student_id",
// new Document().append("$gt", 100));
//
// logger.info("nasz bson: " + bson.toJson());
//
// FindIterable<Document> documents = documentCollection.
// find(bson).
// projection(
// new Document().
// append("student_id", 1)
// .append("_id", 0));
// MongoCursor<Document> iterator = documents.iterator();
//
// JsonWriterSettings.Builder withIndents =
// JsonWriterSettings.builder().indent(true);
//
// while (iterator.hasNext()) {
// logger.info("Nasz dokument: " + iterator.next().
// toJson(withIndents.build()));
// }
// iterator.close();
//
// // korzystanie z MongoDB Api
// FindIterable<Document> documentsThroughMongoDbApi =
// documentCollection.find(
// gt("student_id", 100));
//// logger.info());
//
// }
/**
* 1. Dodać logowanie i pisać junity
* 2. Dodać kolekcję do bazy danych
* https://www.mkyong.com/mongodb/java-mongodb-insert-a-document/
* 3. Wyświetlić liczbę dokumentów w kolekcji
* 4. Identyfikatory studentów większe od 100
* 5. Oceny studentów większe o id > 100 z
* typem oceny = exam
* 6. Wyświetl identyfikatory studentów ze średnią
* 7. Posortuj wyświetlone powyżej identyfikatory
* 8. Zupdatuj wszystkie oceny z egzaminu o 1 jeżeli zawierają się w przedziale 10 - 20
* https://docs.mongodb.com/manual/reference/operator/update/max/#up._S_max
*/
}
|
C++ | UTF-8 | 1,411 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <cctype>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
/*
char ch;
while ( (ch = cin.get()) != '@' ) {
if ( isdigit(ch) ) {
continue;
}
if ( islower(ch) ) {
ch = toupper(ch);
}
else if ( isupper(ch) ) {
ch = tolower(ch);
}
cout << ch;
}
double donation[10];
double sum = 0;
int i = 0;
for ( ; i < 10; i++ ) {
if ( cin >> donation[i] ) {
sum += donation[i];
continue;
}
break;
}
int bigger = 0;
double avg = sum / i;
for (int j = 0; j < i; j++) {
if ( avg < donation[j] )
bigger++;
}
cout << "avg=" << avg << ",bigger=" << bigger << endl;
*/
ifstream inFile;
inFile.open("xxx.txt");
if ( !inFile.is_open() ) {
cout << "open file xxx.txt fail!" << endl;
cout << "EXIT!" << endl;
exit(EXIT_FAILURE);
}
char ch;
int cnt = 0;
while ( inFile.get(ch) ) {
cnt++;
}
if ( inFile.eof() ) {
cout << "Read end the tail!" << endl;
}
else if ( inFile.fail() ) {
cout << "Read unexpected char!" << endl;
}
else {
cout << "unknown reason!" << endl;
}
inFile.close();
cout << "char cnt:" << cnt << endl;
return 0;
} |
C++ | UTF-8 | 3,519 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int N, M, result, islandCnt, edgeCnt;
int map[11][11];
int dist[7][7];
int edge[1000][3]; // s, d, l
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
void input()
{
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
scanf("%d", &map[i][j]);
}
}
}
void checkIsland()
{
islandCnt = 0;
int q[1000][2];
int front, rear;
front = rear = 0;
bool visitedmap[11][11] = { {false,}, };
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (map[i][j] != 0 && !visitedmap[i][j]) {
islandCnt++;
q[front % 1000][0] = i;
q[front % 1000][1] = j;
front++;
while (front != rear) {
int a = q[rear][0];
int b = q[rear][1];
rear++;
visitedmap[a][b] = true;
map[a][b] = islandCnt;
for (int k = 0; k < 4; k++)
{
int c = a + dx[k];
int d = b + dy[k];
if (c >= 0 && c < N && d >= 0 && d < M)
{
if (map[c][d] != 0 && !visitedmap[c][d])
{
q[front % 1000][0] = c;
q[front % 1000][1] = d;
front++;
}
}
}
}
}
}
}
}
bool checkBorder(int x, int y)
{
for (int i = 0; i < 4; i++)
{
if (x + dx[i] >= 0 && x + dx[i] < N && y + dy[i] >= 0 && y + dy[i] < M)
{
if (map[x + dx[i]][y + dy[i]] == 0) {
return true;
}
}
}
return false;
}
int getMinDist(int s, int d)
{
int minDist = 999;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (map[i][j] == s && checkBorder(i,j)) {
//dfs로 d지점 찾기
for (int k = 0; k < 4; k++)
{
int mdist = 0;
int a = i + dx[k];
int b = j + dy[k];
while (a >= 0 && a < N && b >= 0 && b < M) {
if (map[a][b] != 0 && map[a][b] != d) break;
mdist++;
if (map[a][b] == d && checkBorder(a, b))
{
if (mdist > 2 && minDist > mdist) {
minDist = mdist;
}
break;
}
a += dx[k];
b += dy[k];
}
}
}
}
}
if (minDist == 999) return 0;
return minDist - 1;
}
void getDist()
{
edgeCnt = 0;
for (int i = 1; i <= islandCnt; i++)
{
for (int j = 1; j <= islandCnt; j++)
{
if (i != j && dist[i][j] == 0) {
dist[i][j] = dist[j][i] = getMinDist(i, j);
if (dist[i][j] != 0)
{
edge[edgeCnt][0] = i;
edge[edgeCnt][1] = j;
edge[edgeCnt][2] = dist[i][j];
edgeCnt++;
}
}
}
}
}
int kruscal()
{
int parent[7];
int sum = 0;
for (int i = 1; i <= islandCnt; i++)
{
parent[i] = i;
}
for (int i = 0; i < edgeCnt - 1; i++)
{
int k = i;
for (int j = k; j < edgeCnt; j++)
{
if (edge[i][2] > edge[j][2])
{
for (int l = 0; l < 3; l++)
{
int tmp = edge[i][l];
edge[i][l] = edge[j][l];
edge[j][l] = tmp;
}
}
}
}
for (int i = 0; i < edgeCnt; i++)
{
int a = edge[i][0];
int b = edge[i][1];
if (parent[a] != parent[b])
{
sum += edge[i][2];
if (parent[a] < parent[b]) {
int tmp = parent[b];
for (int j = 1; j <= islandCnt; j++) {
if (parent[j] == tmp) parent[j] = parent[a];
}
}
else {
int tmp = parent[a];
for (int j = 1; j <= islandCnt; j++) {
if (parent[j] == tmp) parent[j] = parent[b];
}
}
}
}
for (int i = 1; i <= islandCnt; i++)
{
if (parent[i] != 1) return -1;
}
return sum;
}
void solve()
{
checkIsland();
getDist();
result = kruscal();
}
void output()
{
printf("%d\n", result);
}
int main()
{
input();
solve();
output();
}
|
C | UTF-8 | 522 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h> /* strtoll */
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX 100
int main (){
int input_char1 [20];
input_char1[0] = 5;
input_char1[1] = 8;
input_char1[2] = 12;
int input_char2 [20];
input_char1[0] = 14;
input_char1[1] = 22;
input_char1[2] = 30;
pid = fork();
if(pid > 0){ //parent
}
else if(pid <0){
printf("error");
}
else { //child
while(input_char1 != '\0'){
}
}
} |
Shell | UTF-8 | 1,958 | 3.75 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/bash
# Arguments: two input arrays of matched tile files (names without path, only extension) of the same length and indices
# Mactched tiles, both arrays have the same length and element order
A_array=()
B_array=()
IFS=',' read -r -a A_array <<< "$1"
IFS=',' read -r -a B_array <<< "$2"
AB_size=${#A_array[@]}
echo $A_array
for ((AB_i=0; AB_i < AB_size; AB_i++)); do
A_without_path=${A_array[AB_i]}
B_without_path=${B_array[AB_i]}
A_without_ext="${A_without_path%.*}"
B_without_ext="${B_without_path%.*}"
# Elements of both arrays should be stored in the same order
# a test on matching filenames is therefore not needed
# if [ ${B_without_ext/_NW/""} == $A_without_ext ]; then
mkdir "export_tiles/$A_without_ext"
# Adjust the config file for each matched tile pair
settings_tiles_location="settings_tiles/$A_without_ext.txt"
cp "settings/Config_Tiles.txt" "$settings_tiles_location"
sed -i "s/OLD_CITY_MODEL_LOCATION=/OLD_CITY_MODEL_LOCATION=2016\/LOD1-Nordrhein-Westfalen\/$A_without_path/g" "$settings_tiles_location"
sed -i "s/NEW_CITY_MODEL_LOCATION=/NEW_CITY_MODEL_LOCATION=2018\/LOD1-Nordrhein-Westfalen\/$B_without_path/g" "$settings_tiles_location"
sed -i "s/DB_LOCATION=neo4jDB_tiles\//DB_LOCATION=neo4jDB_tiles\/$A_without_ext\//g" "$settings_tiles_location"
sed -i "s/LOG_LOCATION=logs_tiles\/Default.log/LOG_LOCATION=logs_tiles\/$A_without_ext.log/g" "$settings_tiles_location"
sed -i "s/EXPORT_LOCATION=export_tiles\//EXPORT_LOCATION=export_tiles\/$A_without_ext\//g" "$settings_tiles_location"
# Execute change detection for this tile pair
echo -------- matching tiles: [$A_without_ext] -- [$B_without_ext]
java -Xms4g -Xmx4g -XX:+UseG1GC -jar citygml-change-detection-transactions.jar -SETTINGS="$settings_tiles_location" >console_backup/logs_tiles/$A_without_ext.txt 2>&1
# java -Xms4g -Xmx4g -XX:+UseG1GC -jar citygml-change-detection-transactions.jar -SETTINGS="$settings_tiles_location"
done
|
C++ | UTF-8 | 1,651 | 3.15625 | 3 | [] | no_license | //
// Created by liang on 2020/6/11.
//
#include <iostream>
#include <string>
#include <vector>
#include "FileManager.h"
using namespace std;
CommandEnum lookUp(const string &str) {
for (auto &i : Command)
if (str == i.str)
return i.command;
return ERROR;
}
int main() {
/*初始化*/
fileInit();
bool flag = true;
CommandEnum command;
string line;
while (flag) {
printf(">>> ");
/*读取命令并切割*/
getline(cin, line);
commandLine = split(line, " ");
/*寻找切割除的第一个字符串对应的命令*/
command = lookUp(commandLine[0]);
switch (command) {
case EXIT:
exit();
flag = false;
break;
case CD:
cd();
break;
case MKDIR:
mkdir();
break;
case RMDIR:
rmdir();
break;
case TOUCH:
touch();
break;
case RM:
rm();
break;
case PWD:
pwd();
break;
case LS:
ls();
break;
case READ:
read();
break;
case WRITE:
write();
break;
case RENAME:
rename();
break;
case ERROR:
default:
printf("\033[31mNo such command!\033[0m\n");
break;
}
commandLine.clear();
}
} |
Java | UTF-8 | 6,720 | 2.9375 | 3 | [] | no_license | package src.utils;
import src.models.payment.Schedule;
import java.util.Calendar;
import java.util.Scanner;
public class Utils {
public static Scanner scan = new Scanner(System.in);
public static int readInt() {
int x = scan.nextInt();
scan.nextLine();
return x;
}
public static double readDouble() {
double x = scan.nextDouble();
scan.nextLine();
return x;
}
public static String readString() {
String x = scan.nextLine();
return x;
}
public static int readCommand() {
System.out.println("\nPara obter uma lista com os comandos, digite 0");
System.out.println("Digite um comando:\n");
return readInt();
}
public static String readName() {
System.out.println("Nome do funcionario:");
return readString();
}
public static String readAddress() {
System.out.println("Endereço do funcionario:");
return readString();
}
public static int readEmployeeType() {
System.out.println("Digite o tipo de funcionario a ser cadastrado:");
System.out.println("[1] - Horista");
System.out.println("[2] - Assalariado");
System.out.println("[3] - Comissionado");
return readInt();
}
public static int readFromSyndicate() {
System.out.println("O funcionário pertence ao sindicato?");
System.out.println("[0] - Não");
System.out.println("[1] - Sim");
return readInt();
}
public static int readId() {
System.out.println("Id do funcionario:");
return readInt();
}
public static int readHours() {
System.out.println("Digite a quantidade de horas trabalhadas:");
return readInt();
}
public static double readSale() {
System.out.println("Digite o valor da venda:");
return readDouble();
}
public static double readPercentage() {
System.out.println("Digite o percentual destinado ao funcionario:");
return readDouble();
}
public static double readServiceCharge() {
System.out.println("Digite o valor da taxa de serviço:");
return readDouble();
}
public static double readSalary() {
System.out.println("Digite o salario do funcionário:");
return readDouble();
}
public static int readPaymentType() {
System.out.println("Digite o tipo de pagamento do funcionário:");
System.out.println("[1] - Cheque pelos correios");
System.out.println("[2] - Cheque em mãos");
System.out.println("[3] - Depósito em conta bancária");
return readInt();
}
public static int readUndoRedo() {
System.out.println("[0] - Undo");
System.out.println("[1] - Redo");
return readInt();
}
public static Calendar readDate() {
System.out.println("Digite o dia:");
int day = readInt();
System.out.println("Digite o mês:");
int month = readInt();
month--;
System.out.println("Digite o ano:");
int year = readInt();
Calendar x = Calendar.getInstance();
x.set(Calendar.YEAR, year);
x.set(Calendar.MONTH, month);
x.set(Calendar.DAY_OF_MONTH, day);
return x;
}
public static Schedule readPaymentSchedule() {
System.out.println("Digite o tipo de agenda de pagamento");
String payment_schedule = readString();
return parsePaymentSchedule(payment_schedule);
}
public static Schedule parsePaymentSchedule(String str) {
String[] parsed = str.split(" ");
Schedule payment_schedule = new Schedule();
if (parsed.length == 2 && parsed[0].equals("mensal")) {
payment_schedule.setTimeGap(parsed[0]);
if (parsed[1].equals("$")) {
payment_schedule.setDay(50);
} else {
payment_schedule.setDay(Integer.parseInt(parsed[1]));
}
} else if (parsed.length == 3 && parsed[0].equals("semanal")) {
payment_schedule.setTimeGap(parsed[0]);
payment_schedule.setDay(Integer.parseInt(parsed[1]));
payment_schedule.setWeekDay(parsed[2]);
}
return payment_schedule;
}
public static boolean printHelp() {
System.out.println("[0] - Ajuda");
System.out.println("[1] - Adicionar empregado");
System.out.println("[2] - Remoção de um empregado");
System.out.println("[3] - Lançar um cartão de ponto");
System.out.println("[4] - Lançar uma resultado venda");
System.out.println("[5] - Lançar uma taxa de serviço");
System.out.println("[6] - Alterar detalhes de um empregado");
System.out.println("[7] - Rodar folha de pagamento");
System.out.println("[8] - Undo");
System.out.println("[9] - Mudar agenda de pagamento");
System.out.println("[10] - Adicionar agenda de pagamento");
System.out.println("[11] - Exibir empregados");
System.out.println("[12] - Sair da aplicação");
return true;
}
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static boolean compareDates(Calendar a, Calendar b) {
if (a.get(Calendar.YEAR) != b.get(Calendar.YEAR)) {
return (a.get(Calendar.YEAR) > b.get(Calendar.YEAR));
}
if (a.get(Calendar.MONTH) != b.get(Calendar.MONTH)) {
return (a.get(Calendar.MONTH) > b.get(Calendar.MONTH));
}
if (a.get(Calendar.DAY_OF_MONTH) != b.get(Calendar.DAY_OF_MONTH)) {
return (a.get(Calendar.DAY_OF_MONTH) > b.get(Calendar.DAY_OF_MONTH));
}
return true;
}
public static int dateDiff(Calendar a, Calendar b) {
int diff = 0;
while (compareDates(a, b) == false) {
a.add(Calendar.DAY_OF_MONTH, 1);
diff++;
}
a.add(Calendar.DAY_OF_MONTH, -diff);
return diff;
}
public static boolean LastBussinessDay(Calendar a) {
if (a.get(Calendar.DAY_OF_MONTH) == Calendar.SATURDAY || a.get(Calendar.DAY_OF_MONTH) == Calendar.SUNDAY) {
return false;
}
int added = 1;
int month = a.get(Calendar.MONTH);
a.add(Calendar.DAY_OF_MONTH, 1);
while (a.get(Calendar.DAY_OF_MONTH) == Calendar.SATURDAY || a.get(Calendar.DAY_OF_MONTH) == Calendar.SUNDAY) {
added++;
a.add(Calendar.DAY_OF_MONTH, 1);
}
int new_month = a.get(Calendar.MONTH);
a.add(Calendar.DAY_OF_MONTH, -added);
return (month != new_month);
}
}
|
JavaScript | UTF-8 | 343 | 3.765625 | 4 | [] | no_license | /**
* @description returns number of numbers
* that can be represented as difference of squares
* @param {number} n end of range [1...n]
* @return {number}
* @example squares(4) -> 3
*/
export function squares(n) {
let counter = 0;
for (let i = 1; i <= n; ++i) {
if (i % 4 !== 2) {
++counter;
}
}
return counter;
}
|
C++ | UTF-8 | 1,403 | 4.25 | 4 | [] | no_license | // Display the sum of a vector of numbers
// Display the difference between adjacent numbers in said vector
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <vector>
int main()
{
int numOfInts = 0;
std::cout << "Please enter the number of values you want to sum:\n";
std::cin >> numOfInts;
if (numOfInts < 1)
std::cerr << "You need to enter atleast 1 positive integer.\n";
else
{
std::vector<double> values;
std::vector<double> differences;
double tempValue = 0;
std::cout << "Please enter some values (enter '|' to stop):\n";
while (std::cin >> tempValue)
values.push_back(tempValue);
if (values.size() != numOfInts)
std::cerr << "You must enter " << numOfInts << " values.\n";
else
{
double sum = 0;
for (int i = 0; i < values.size(); ++i)
sum += values[i];
// display the sum of values
std::cout << "The sum of these " << numOfInts << " values ( ";
for (int i = 0; i < values.size(); ++i)
std::cout << values[i] << " ";
std::cout << ") is " << sum << "." << std::endl;
}
// calculate the difference between adjacent values in the values vector
for (int i = 0; i < values.size() - 1; ++i)
differences.push_back(fabs(values[i] - values[i + 1]));
// display the differences
std::cout << "The differences between the values are:\n";
for (double x : differences)
std::cout << x << std::endl;
}
}
|
C | UTF-8 | 548 | 3.8125 | 4 | [] | no_license | /**
*
* Bubble sort
* C file
*
* by Cherepanov Aleksei (PI-171)
*
* mrneumann888@gmail.com
*
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bubble_sort.h"
void bubble_sort(char **array, int length)
{
int i;
int j;
for (i = 0; i < length - 1; i++)
{
for (j = 0; j < length - i - 1; j++)
{
if (strcmp(array[j], array[j + 1]) > 0)
{
char* swap_char = array[j];
array[j] = array[j + 1];
array[j + 1] = swap_char;
}
}
}
}
|
TypeScript | UTF-8 | 990 | 2.71875 | 3 | [
"MIT"
] | permissive | /* eslint-disable @typescript-eslint/explicit-function-return-type */
import { MessageEmbed } from 'discord.js';
import { Extendable, ExtendableStore } from 'klasa';
export default class extends Extendable {
private description: string;
public addField: any
constructor(store: ExtendableStore, file: string[], directory: string) {
super(store, file, directory, {
appliesTo: [MessageEmbed]
});
}
public addBetterField(title?: string, content?: string, extraSpace = false) {
this.description = this.description || '';
this.description += `${extraSpace ? '\n' : ''}\n**${title}:** ${content}`;
return this;
}
public addFieldDef(title?: string, content?: string) {
title = title || '\u200B';
content = content || '\u200B';
return this.addField(title, content);
}
}
declare module 'discord.js' {
interface MessageEmbed {
addBetterField(title?: string, content?: string, extraSpace?: boolean): this;
addFieldDef(title?: string, content?: string): this;
}
}
|
C++ | UTF-8 | 975 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
//https://programmers.co.kr/learn/courses/30/lessons/42860
int solution(string name) {
int answer = 0;
string str = name;
int num = 0;
size_t length = name.length();
for (int i = 0; i <length; ++i)
{
str[i] = 'A';
}
while (true)
{
str[num] = name[num];
char a = name[num];
if ('Z' + 1 - a < a - 'A')
{
answer += 'Z' + 1 - a;
}
else
{
answer += a - 'A';
}
if (str == name)
break;
for (int i = 1; i < length; i++)
{
if (name[(num + i) % length] != str[(num + i) % length])
{
num = (num + i) % length;
answer += i;
break;
}
else if (name[(num + length - i) % length] != str[(num + length - i) % length])
{
num = (num + length - i) % length;
answer += i;
break;
}
}
}
return answer;
}
int main()
{
solution("JEROEN");
return 0;
} |
C++ | UTF-8 | 2,920 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef NEO_PATTERNS_H
#define NEO_PATTERNS_H
#include <Adafruit_NeoPixel.h>
// Pattern types supported:
enum pattern { NONE, RAINBOW_CYCLE, THEATER_CHASE, COLOR_WIPE, SCANNER, FADE };
// Patern directions supported:
enum direction { FORWARD, REVERSE };
// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns: public Adafruit_NeoPixel
{
public:
// Member Variables:
pattern ActivePattern; // which pattern is running
direction Direction; // direction to run the pattern
unsigned long Interval; // milliseconds between updates
unsigned long lastUpdate; // last update of position
uint32_t Color1, Color2; // What colors are in use
uint16_t TotalSteps; // total number of steps in the pattern
uint16_t Index; // current step within the pattern
void (* OnComplete)(); // Callback on completion of pattern
// Constructor - calls base-class constructor to initialize strip
NeoPatterns(uint16_t pixels, uint8_t pin);
void Complete();
// Update the pattern
void Update();
// Increment the Index and reset at the end
void Increment();
// Follwing two are same for all options bellow
// interval : number of milliseconds between updates, which determines the speed of the pattern.
// dir : [optional] FORWARD/REVERSE
void RainbowCycle(uint8_t interval, direction dir = FORWARD);
void RainbowCycleUpdate();
// color : color to 'wipe' across the strip.
void ColorWipe(uint32_t color, uint8_t interval, direction dir = FORWARD);
void ColorWipeUpdate();
// color1 and color2 : foreground and background colors of the pattern.
void TheaterChase(uint32_t color1, uint32_t color2, uint8_t interval, direction dir = FORWARD);
void TheaterChaseUpdate();
// color : color of the scanning pixel.
void Scanner(uint32_t color1, uint8_t interval);
void ScannerUpdate();
// color1 : starting color
// color2 : ending color
// steps : how many steps it should take to get from color1 to color2.
void Fade(uint32_t color1, uint32_t color2, uint16_t steps, uint8_t interval, direction dir = FORWARD);
void FadeUpdate();
// Red(), Blue() and Green() functions.
// These are the inverse of the Neopixel Color() function.
// They allow us to extract the Red, Blue and Green components of a pixel color.
uint8_t Red(uint32_t color);
uint8_t Green(uint32_t color);
uint8_t Blue(uint32_t color);
// Return color, dimmed by 75% (e.g. used by scanner)
uint32_t DimColor(uint32_t color);
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos);
// Reverse direction of the pattern
void Reverse();
// Set all pixels to a color (synchronously)
void ColorSet(uint32_t color);
};
#endif /* ifndef NEO_PATTERNS_H */
|
Java | UTF-8 | 23,220 | 2.265625 | 2 | [] | no_license | package com.example.yitier910e.myapplication2;
import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.github.chrisbanes.photoview.PhotoView;
import com.github.chrisbanes.photoview.PhotoViewAttacher;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
// Variable permettant d'acceder aux différents boutons.
//----------------------------------------
private Button resetButton;
private Button undoButton;
private Button applyButton;
// Variable permettant d'acceder aux différentes TextView
//----------------------------------------
private TextView effectText;
private TextView valueText;
//Variable permettant d'acceder aux différentes SeekBar
//----------------------------------------
private SeekBar sb1;
private SeekBar sb2;
private SeekBar sb3;
//Variable permettant de gérer l'affichage et les effets appliqué à l'image
//----------------------------------------
private PhotoView imView;
private Effects effect;
PhotoViewAttacher mAttacher;
private Item currentEffect=Item.NULL;
//Variable permettant de gérer la sauvegarde/le chargement et la prise de photo
//----------------------------------------
private BitmapFactory.Options o;
public Uri file;
public static final int PHOTO = 1;
public static final int GALLERY = 2;
private String mCurrentPhotoPath;
/**
* Fonction qui permet de détecter quand on clique sur le bouton "apply" et appel la fonction apply.
*/
private View.OnClickListener applyButtonListener = new View.OnClickListener() {
public void onClick(View v) {
applyButton.refreshDrawableState();
apply();
}
};
/**
* Fonction qui permet de détecter quand on clique sur le bouton "undo" et appel la fonction undo.
*/
private View.OnClickListener undoButtonListener = new View.OnClickListener() {
public void onClick(View v) {
effect.undo(undoButton);
imView.setImageBitmap(effect.getBmp());
}
};
/**
* Fonction qui permet de détecter quand on clique sur le bouton "reset" et appel la fonction reset
*/
private View.OnClickListener resetButtonListener = new View.OnClickListener() {
public void onClick(View v) {
effect.reset();
imView.setImageBitmap(effect.getBmp());
}
};
/**
* Permet de créer un ficher image dans le répertoire courant.Le nom du fichier sera généré en fonction de l'heure courante afin d'éviter
* qu'il y ait des doublons.
* @return retourne un fichier contenant une image
* @throws IOException
*/
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
// Le chemin est stocké dans une variable globale
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
/**
* Fonction qui permet d'ouvrir la galerie afin de sélectionner la photo à afficher dans l'appli
*/
private void dispatchOpenGalleryIntent() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY);
}
/**
* Permet de créer un fichier lors de la prise d'une photo
*/
private void dispatchTakePictureIntent() {
//Initialisation de l'Intent permettant de prendre une photo
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
//Permet d'associer un chemin d'accès à l'URI
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.yitier910e.myapplication2.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, PHOTO);
}
}
}
/**
* Fonction qui permet d'ajouter une photo à la galerie
*/
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
/**
*Fonction permettant de calculer un coefficient pour réduire la photo.
*
* @param options contient les options permetant de récup
* @param reqWidth définit la largeur de l'image que l'on souhaite à l'arrivé
* @param reqHeight définit la longueur de l'image que l'on souahite à l'arrivé
* @return retourne le coefficient de rétrécissement à appliquer à la photo.
*/
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// récupération de la taille de l'image de la photo qu'on souhaite réduire
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// on cherche la plus grande puissance de 2 qui divise la largeur ou la longueur à la taille souhaiter
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
*
* @param path chemin absolue du fichier à transformer en bitmap
* @param reqWidth largeur de la bitmap souhaité
* @param reqHeight longueur de la bitmap souhaité
* @param op options à passer en paramètre
* @return retourne la bitmap contenant l'image souhaité
*/
public static Bitmap decodeSampledBitmapFromFile(String path,
int reqWidth, int reqHeight, BitmapFactory.Options op) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// calcul du coefficient réducteur
op.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// réduction de l'image grace à l'option "op" contenant le fameux coefficient
Bitmap temp = BitmapFactory.decodeFile(path, op);
return temp;
}
/**
* Fonction permettant de sauver une bitmap en fichier
*/
private void letsSave(){
Save savefile = new Save();
savefile.SaveImage(this,effect.getBmp());
}
/**
*Fonction qui permet de mettre la bitmap dans l'imageView en prennant en compte les options afin de pouvoir la modifier
*/
private void setPic() {
effect.loadBmp(decodeSampledBitmapFromFile(mCurrentPhotoPath,377,358, o));
imView.setImageBitmap(effect.getBmp());
}
/**
* Fonction principale des Intent qui permet de traiter les différents appel d'intent
* Ceux ci sont gérés par la valeur du requestCode et du resultCode.
* Cette fonction est appelée après l'utilisation de l'intent
*
* Si elle est appelée par une prise de photo elle ajoute la photo à la galerie et l'affiche dans la PhotoView.
* Si elle est appelée par l'ouverture d'une image, elle affiche la photo dans la PhotoView
*
* @param requestCode Code permettant de déterminer par quelle fonction celle-ci est appelé. les valeurs valable de requestCode sont 0 ou 1
* @param resultCode Code permettant de déterminer si l'intent s'est terminé normalement ou pas.
* @param data Contient les informations stocké dans l'intent
*
*/
@Override
/**
*
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case (PHOTO):
galleryAddPic();
setPic();
letsSave();
break;
case (GALLERY):
Uri photoUri = data.getData();
if (photoUri != null) {
try {
effect.loadBmp(MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri));
imView.setImageBitmap(effect.getBmp());
} catch (Exception e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
else {
}
}
//
/**
* Fonction extrêmement important qui permet de demander les permissions nécessaires afin d'enregistrer les images et de les ouvrir.
*
*/
private void checkPermissions() {
int apiLevel = Build.VERSION.SDK_INT;
String[] permissions;
if (apiLevel < 16) {
permissions = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
} else {
permissions = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
}
ActivityCompat.requestPermissions(this,permissions, 0);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
/**
* Fonction appelé à l'ouverture de l'application afin d'initialisé toutes les variables qui le nécessite ainsi que les divers boutons, seekbar, PhotoView et TextView
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView = (PhotoView) findViewById(R.id.imgView);
mAttacher=new PhotoViewAttacher(imView);
resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(resetButtonListener);
applyButton = (Button) findViewById(R.id.applyButton);
applyButton.setOnClickListener(applyButtonListener);
applyButton.setEnabled(false);
effectText=(TextView) findViewById(R.id.effectId);
valueText=(TextView) findViewById(R.id.valueId);
undoButton = (Button) findViewById(R.id.undoButton);
undoButton.setOnClickListener(undoButtonListener);
undoButton.setEnabled(false);
sb1= (SeekBar)findViewById(R.id.seekBar);
sb1.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
int valueInt;
float valueFloat;
switch (currentEffect){
case MONOCOLOR:
valueText.setBackgroundColor(Color.rgb(sb1.getProgress(),sb2.getProgress(),sb3.getProgress()));
break;
case LUMINOSITY:
valueFloat =(float)(sb1.getProgress()-255)/255*100;
valueText.setText(valueFloat+ " %" );
break;
case MOYENNE:
valueInt = sb1.getProgress()*2+1;
valueText.setText(valueInt+ "X"+valueInt );
break;
case GAUSSIENNE:
valueInt= sb1.getProgress()*2+1;
valueText.setText(valueInt+"X"+valueInt );
break;
case EXPOSITION:
valueFloat = (float)sb1.getProgress()/100;
if (valueFloat > 1) {
valueFloat = 5 * (valueFloat - 1) + 1;
}
valueText.setText("Coeff : "+valueFloat );
break;
case CARTOON:
valueText.setText("nombre de tour "+sb1.getProgress() );
break;
case CONTRAST:
valueText.setText("Min : "+sb1.getProgress()+ "\nMax : "+sb2.getProgress() );
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
sb2= (SeekBar)findViewById(R.id.seekBar2);
sb2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(currentEffect == Item.MONOCOLOR){
valueText.setBackgroundColor(Color.rgb(sb1.getProgress(),sb2.getProgress(),sb3.getProgress()));
}
else if (currentEffect == Item.CONTRAST){
valueText.setText("Min : "+sb1.getProgress()+ "\nMax : "+sb2.getProgress() );
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
sb3= (SeekBar)findViewById(R.id.seekBar3);
sb3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(currentEffect == Item.MONOCOLOR){
valueText.setBackgroundColor(Color.rgb(sb1.getProgress(),sb2.getProgress(),sb3.getProgress()));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
o = new BitmapFactory.Options();
o.inMutable = true;
o.inScaled=true;
effect=new Effects(BitmapFactory.decodeResource(getResources(),R.drawable.lena,o),this);
imView.setImageBitmap(effect.getBmp());
mAttacher.update();
checkPermissions();
}
/**
* Permet de modifier et de changer le menu.
* @param menu
* @return
*/
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_styley,menu);
return true;
}
/**
*Permet de selectionner les effets ou les fonctions de prise de photo/charger une image/sauvegarder une image.
* Cette fonction gère l'affichage des SeekBars qui peuvent être utilisés pour les divers effets, elle gère aussi l'activation des boutons undo et apply suivant s'ils peuvent être utilisé ou pas
*
* @param item
* @return
*/
public boolean onOptionsItemSelected(MenuItem item){
sb1.setVisibility(View.INVISIBLE);
sb2.setVisibility(View.INVISIBLE);
sb3.setVisibility(View.INVISIBLE);
sb1.setBackgroundColor(Color.WHITE);
sb2.setBackgroundColor(Color.WHITE);
sb3.setBackgroundColor(Color.WHITE);
valueText.setText("");
switch(item.getItemId()){
case R.id.grayId:
currentEffect=Item.GRAY;
break;
case R.id.sepiaId :
currentEffect=Item.SEPIA;
break;
case R.id.expoId:
sb1.setVisibility(View.VISIBLE);
sb1.setMax(200);
sb1.setProgress(100);
valueText.setText("Coeff: 1");
currentEffect=Item.EXPOSITION;
break;
case R.id.contourId:
currentEffect=Item.SOBEL;
break;
case R.id.laplaceId:
currentEffect=Item.LAPLACE;
break;
case R.id.luminId:
sb1.setVisibility(View.VISIBLE);
sb1.setMax(510);
sb1.setProgress(255);
valueText.setText("0 %");
currentEffect=Item.LUMINOSITY;
break;
case R.id.contrastId:
currentEffect=Item.CONTRAST;
sb1.setVisibility(View.VISIBLE);
sb2.setVisibility(View.VISIBLE);
sb1.setMax(255);
sb2.setMax(255);
sb1.setProgress(0);
sb2.setProgress(255);
break;
case R.id.monoId:// on peut changer la couleur en replaçant Color.RED par celle que l'on souhaite
currentEffect=Item.MONOCOLOR;
sb1.setVisibility(View.VISIBLE);
sb2.setVisibility(View.VISIBLE);
sb3.setVisibility(View.VISIBLE);
sb1.setMax(255);
sb2.setMax(255);
sb3.setMax(255);
sb1.setProgress(128);
sb2.setProgress(128);
sb3.setProgress(128);
sb1.setBackgroundColor(Color.RED);
sb2.setBackgroundColor(Color.GREEN);
sb3.setBackgroundColor(Color.BLUE);
break;
case R.id.moyenneId: // a tester que sur la première image parce qu'elle est suffisament petit pour voir l'effet (image urbex)
currentEffect=Item.MOYENNE;
sb1.setVisibility(View.VISIBLE);
sb1.setMax(8);
sb1.setProgress(0);
valueText.setText("1X1");
break;
case R.id.equalId:
currentEffect=Item.EQUALISATOR;
break;
case R.id.gaussId:
currentEffect=Item.GAUSSIENNE;
sb1.setVisibility(View.VISIBLE);
sb1.setProgress(0);
sb1.setMax(8);
valueText.setText("1X1");
break;
case R.id.photoId:
dispatchTakePictureIntent();
break;
case R.id.loadId:
dispatchOpenGalleryIntent();
break;
case R.id.saveId:
letsSave();
break;
case R.id.cartoonId:
currentEffect=Item.CARTOON;
sb1.setVisibility(View.VISIBLE);
sb1.setMax(7);
sb1.setProgress(2);
break;
default:
return false;
}
if(currentEffect!=Item.NULL) {
applyButton.setEnabled(true);
effectText.setText(currentEffect.name());
}
valueText.setBackgroundColor(Color.WHITE);
return true;
}
/**
*Fonction mère du programme qui permet de lancer les divers algorithmes de traitement d'image. Ceux-ci sont selectionner en fonction de la valeur de l'enum currentEffect.
* Celui-ci est déterminé suivant l'item selectionné dans le menu.
*/
public void apply(){
effect.update(undoButton);
switch (currentEffect){
case CONTRAST:
if (sb1.getProgress() < sb2.getProgress()) {
effect.applyTableHSV(effect.contrast(sb1.getProgress(), sb2.getProgress()));
}
else{ Toast.makeText(this,"Il faut un minimum plus petit que le maximum",Toast.LENGTH_SHORT).show();}
break;
case GRAY:
effect.toGreyRS(this);
break;
case SEPIA:
effect.toSepiaRS(this);
break;
case CARTOON:
effect.mergeCatoon(10,sb1.getProgress());
break;
case SOBEL:
effect.sobel();
break;
case LAPLACE:
effect.toGreyRS(this);
int[][] matrix = {{0,1,0},{1,-4,1},{0,1,0}};
effect.convol(matrix);
break;
case MOYENNE:
matrix = new int[sb1.getProgress()*2+1][sb1.getProgress()*2+1];
for (int i =0; i< sb1.getProgress()*2+1;i++){
for (int j =0;j< sb1.getProgress()*2+1;j++){
matrix[i][j]=1;
}
}
effect.convol(matrix);
break;
case MONOCOLOR:
effect.toGrayExcept(Color.rgb(sb1.getProgress(),sb2.getProgress(),sb3.getProgress()));
break;
case EXPOSITION:
float temp = (float)sb1.getProgress()/100;
if (temp > 1){
temp = 5*(temp-1)+1;
}
effect.expo(temp);
break;
case GAUSSIENNE:
effect.convol(effect.ArrayGauss(sb1.getProgress()*2+1,sb1.getProgress()*sb1.getProgress()+1));
break;
case LUMINOSITY:
effect.lumin(sb1.getProgress()-255);
break;
case EQUALISATOR:
effect.applyTableHSV(effect.egalisator(effect.histoHSV()));
break;
default :
break;
}
}
}
|
C# | UTF-8 | 3,707 | 3.609375 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace cursor
{
class Program
{
static void ShowInfo(DirectoryInfo directory, int cursor) //метод, который выводит информацию об объекте
{
Console.BackgroundColor = ConsoleColor.Green; //меняет цвет фона текста
int index = 0;
foreach (FileSystemInfo fInfo in directory.GetFileSystemInfos()) //для каждого файла и папки
{
if (index == cursor)
Console.ForegroundColor = ConsoleColor.Red; //меняет цвет самого текста
index++;
if (fInfo.GetType() == typeof(FileInfo)) //определяет тип объекта , файл или папка
Console.Write("File: ");
else
Console.Write("Directory: ");
Console.WriteLine(fInfo.Name);
}
}
static void Main(string[] args)
{
int cursor = 0;
DirectoryInfo directory = new DirectoryInfo(@"C:\DELL"); //создает новый экземпляр класса DirectoryInfo
while(true)
{
Console.Clear(); //очищает окно консоли
ShowInfo(directory, cursor);
ConsoleKeyInfo pressedKey = Console.ReadKey(); //описывает функцию нажатой клавиши
if (pressedKey.Key == ConsoleKey.UpArrow)
if (cursor > 0)
cursor--;
if (pressedKey.Key == ConsoleKey.DownArrow)
if (cursor < directory.GetFileSystemInfos().Length - 1)
cursor++;
if (pressedKey.Key == ConsoleKey.Enter)
{
FileSystemInfo fs = directory.GetFileSystemInfos()[cursor];
if (fs.GetType() == typeof(DirectoryInfo))
{
directory = new DirectoryInfo(fs.FullName); //создает новый экземпляр класса diretoryinfo
}
else
{
try // пытается выполнить прописанные операции
{
Console.Clear();
StreamReader sr = new StreamReader(fs.FullName);
Console.Write(sr.ReadToEnd());
Console.ReadKey();
sr.Close();
}
catch (Exception e) //при невыполнении выше прописанных операций
{
Console.WriteLine("error");
}
}
break;
}
if (pressedKey.Key == ConsoleKey.Backspace)
{
try
{
directory = Directory.GetParent(directory.FullName); //возвращается в начальную папку
}
catch (Exception e)
{
}
}
if (pressedKey.Key == ConsoleKey.Escape)
break;
}
}
}
}
|
Python | UTF-8 | 27 | 2.921875 | 3 | [] | no_license | a = 5
b = 6
s= a+b
print(s) |
Markdown | UTF-8 | 375 | 3.078125 | 3 | [] | no_license | # distance-calculator
This program calculates distance multiple points.
**WORKING**
1. Asks the user how many points are required.
2. After getting this info, the program gets the coordinates for each point.
3. It calculates the distance and shows the result

|
Java | UTF-8 | 17,309 | 2.125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao.JDBC;
import dao.DAOException;
import dao.DAOUtil;
import static dao.DAOUtil.prepareStatement;
import dao.interfaces.OrderPurchaseIncomingReportDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Employee;
import model.OrderPurchase;
import model.OrderPurchaseIncomingReport;
/**
*
* @author Pavilion Mini
*/
public class OrderPurchaseIncomingReportDAOJDBC implements OrderPurchaseIncomingReportDAO {
// Constants ----------------------------------------------------------------------------------
private static final String SQL_FIND_BY_ID =
"SELECT ORDER_PURCHASE_INCOMING_REPORT.id, ORDER_PURCHASE_INCOMING_REPORT.report_date, ORDER_PURCHASE_INCOMING_REPORT.comments, ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID, "
+ "COMPANY.name, EMPLOYEE.id, EMPLOYEE.first_name, EMPLOYEE.last_name "
+ "FROM ORDER_PURCHASE_INCOMING_REPORT "
+ "INNER JOIN ORDER_PURCHASE ON ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID = ORDER_PURCHASE.id "
+ "INNER JOIN EMPLOYEE ON ORDER_PURCHASE_INCOMING_REPORT.EMPLOYEE_ID = EMPLOYEE.id "
+ "INNER JOIN COMPANY ON ORDER_PURCHASE.COMPANY_ID = COMPANY.id "
+ "WHERE ORDER_PURCHASE_INCOMING_REPORT.id = ?";
private static final String SQL_FIND_ORDER_PURCHASE_BY_ID =
"SELECT ORDER_PURCHASE_ID FROM ORDER_PURCHASE_INCOMING_REPORT WHERE id = ?";
private static final String SQL_FIND_EMPLOYEE_BY_ID =
"SELECT EMPLOYEE_ID FROM ORDER_PURCHASE_INCOMING_REPORT WHERE id = ?";
private static final String SQL_LIST_ORDER_BY_ID =
"SELECT ORDER_PURCHASE_INCOMING_REPORT.id, ORDER_PURCHASE_INCOMING_REPORT.report_date, ORDER_PURCHASE_INCOMING_REPORT.comments, ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID, "
+ "COMPANY.name, EMPLOYEE.id, EMPLOYEE.first_name, EMPLOYEE.last_name "
+ "FROM ORDER_PURCHASE_INCOMING_REPORT "
+ "INNER JOIN ORDER_PURCHASE ON ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID = ORDER_PURCHASE.id "
+ "INNER JOIN EMPLOYEE ON ORDER_PURCHASE_INCOMING_REPORT.EMPLOYEE_ID = EMPLOYEE.id "
+ "INNER JOIN COMPANY ON ORDER_PURCHASE.COMPANY_ID = COMPANY.id "
+ "ORDER BY ORDER_PURCHASE_INCOMING_REPORT.id";
private static final String SQL_LIST_EMPLOYEE_ORDER_BY_ID =
"SELECT ORDER_PURCHASE_INCOMING_REPORT.id, ORDER_PURCHASE_INCOMING_REPORT.report_date, ORDER_PURCHASE_INCOMING_REPORT.comments, ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID, "
+ "COMPANY.name, EMPLOYEE.id, EMPLOYEE.first_name, EMPLOYEE.last_name "
+ "FROM ORDER_PURCHASE_INCOMING_REPORT "
+ "INNER JOIN ORDER_PURCHASE ON ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID = ORDER_PURCHASE.id "
+ "INNER JOIN EMPLOYEE ON ORDER_PURCHASE_INCOMING_REPORT.EMPLOYEE_ID = EMPLOYEE.id "
+ "INNER JOIN COMPANY ON ORDER_PURCHASE.COMPANY_ID = COMPANY.id "
+ "WHERE ORDER_PURCHASE_INCOMING_REPORT.EMPLOYEE_ID = ? "
+ "ORDER BY ORDER_PURCHASE_INCOMING_REPORT.id";
private static final String SQL_LIST_ORDER_PURCHASE_ORDER_BY_ID =
"SELECT ORDER_PURCHASE_INCOMING_REPORT.id, ORDER_PURCHASE_INCOMING_REPORT.report_date, ORDER_PURCHASE_INCOMING_REPORT.comments, ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID, "
+ "COMPANY.name, EMPLOYEE.id, EMPLOYEE.first_name, EMPLOYEE.last_name "
+ "FROM ORDER_PURCHASE_INCOMING_REPORT "
+ "INNER JOIN ORDER_PURCHASE ON ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID = ORDER_PURCHASE.id "
+ "INNER JOIN EMPLOYEE ON ORDER_PURCHASE_INCOMING_REPORT.EMPLOYEE_ID = EMPLOYEE.id "
+ "INNER JOIN COMPANY ON ORDER_PURCHASE.COMPANY_ID = COMPANY.id "
+ "WHERE ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID = ? "
+ "ORDER BY ORDER_PURCHASE_INCOMING_REPORT.id";
private static final String SQL_INSERT =
"INSERT INTO ORDER_PURCHASE_INCOMING_REPORT(ORDER_PURCHASE_ID, EMPLOYEE_ID, report_date, comments) "
+ "VALUES(?, ?, ?, ?)";
private static final String SQL_UPDATE =
"UPDATE ORDER_PURCHASE_INCOMING_REPORT SET report_date = ?, comments = ? WHERE id = ?";
private static final String SQL_DELETE =
"DELETE FROM ORDER_PURCHASE_INCOMING_REPORT WHERE id = ?";
// Vars ---------------------------------------------------------------------------------------
private DAOFactory daoFactory;
// Constructors -------------------------------------------------------------------------------
/**
* Construct a OrderPurchaseIncomingReport DAO for the given DAOFactory. Package private so that it can be constructed
* inside the DAO package only.
* @param daoFactory The DAOFactory to construct this OrderPurchaseIncomingReport DAO for.
*/
OrderPurchaseIncomingReportDAOJDBC(DAOFactory daoFactory) {
this.daoFactory = daoFactory;
}
// Actions ------------------------------------------------------------------------------------
@Override
public OrderPurchaseIncomingReport find(Integer id) throws DAOException {
return find(SQL_FIND_BY_ID, id);
}
/**
* Returns the OrderPurchaseIncomingReport from the database matching the given SQL query with the given values.
* @param sql The SQL query to be executed in the database.
* @param values The PreparedStatement values to be set.
* @return The OrderPurchaseIncomingReport from the database matching the given SQL query with the given values.
* @throws DAOException If something fails at database level.
*/
private OrderPurchaseIncomingReport find(String sql, Object... values) throws DAOException {
OrderPurchaseIncomingReport mantainance_report = null;
try (
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, sql, false, values);
ResultSet resultSet = statement.executeQuery();
) {
if (resultSet.next()) {
mantainance_report = map(resultSet);
}
} catch (SQLException e) {
throw new DAOException(e);
}
return mantainance_report;
}
@Override
public OrderPurchase findOrderPurchase(OrderPurchaseIncomingReport order_purchase_incoming_report) throws IllegalArgumentException, DAOException {
if(order_purchase_incoming_report.getId() == null) {
throw new IllegalArgumentException("OrderPurchaseIncomingReport is not created yet, the OrderPurchaseIncomingReport ID is null.");
}
OrderPurchase order_purchase = null;
Object[] values = {
order_purchase_incoming_report.getId()
};
try (
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_FIND_ORDER_PURCHASE_BY_ID, false, values);
ResultSet resultSet = statement.executeQuery();
) {
if (resultSet.next()) {
order_purchase = daoFactory.getOrderPurchaseDAO().find(resultSet.getInt("ORDER_PURCHASE_ID"));
}
} catch (SQLException e) {
throw new DAOException(e);
}
return order_purchase;
}
@Override
public Employee findEmployee(OrderPurchaseIncomingReport order_purchase_incoming_report) throws IllegalArgumentException, DAOException {
if(order_purchase_incoming_report.getId() == null) {
throw new IllegalArgumentException("OrderPurchaseIncomingReport is not created yet, the OrderPurchaseIncomingReport ID is null.");
}
Employee employee = null;
Object[] values = {
order_purchase_incoming_report.getId()
};
try (
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_FIND_EMPLOYEE_BY_ID, false, values);
ResultSet resultSet = statement.executeQuery();
) {
if (resultSet.next()) {
employee = daoFactory.getEmployeeDAO().find(resultSet.getInt("EMPLOYEE_ID"));
}
} catch (SQLException e) {
throw new DAOException(e);
}
return employee;
}
@Override
public List<OrderPurchaseIncomingReport> list() throws DAOException {
List<OrderPurchaseIncomingReport> order_purchase_incoming_report = new ArrayList<>();
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_LIST_ORDER_BY_ID);
ResultSet resultSet = statement.executeQuery();
){
while(resultSet.next()){
order_purchase_incoming_report.add(map(resultSet));
}
} catch(SQLException e){
throw new DAOException(e);
}
return order_purchase_incoming_report;
}
@Override
public List<OrderPurchaseIncomingReport> listOfOrderPurchase(OrderPurchase order_purchase) throws DAOException {
if(order_purchase.getId() == null) {
throw new IllegalArgumentException("OrderPurchase is not created yet, the OrderPurchase ID is null.");
}
List<OrderPurchaseIncomingReport> order_purchase_incoming_report = new ArrayList<>();
Object[] values = {
order_purchase.getId()
};
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_LIST_ORDER_PURCHASE_ORDER_BY_ID, false, values);
ResultSet resultSet = statement.executeQuery();
){
while(resultSet.next()){
order_purchase_incoming_report.add(map(resultSet));
}
} catch(SQLException e){
throw new DAOException(e);
}
return order_purchase_incoming_report;
}
@Override
public List<OrderPurchaseIncomingReport> listOfEmployee(Employee employee) throws DAOException {
if(employee.getId() == null) {
throw new IllegalArgumentException("Employee is not created yet, the Employee ID is null.");
}
List<OrderPurchaseIncomingReport> order_purchase_incoming_report = new ArrayList<>();
Object[] values = {
employee.getId()
};
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_LIST_EMPLOYEE_ORDER_BY_ID, false, values);
ResultSet resultSet = statement.executeQuery();
){
while(resultSet.next()){
order_purchase_incoming_report.add(map(resultSet));
}
} catch(SQLException e){
throw new DAOException(e);
}
return order_purchase_incoming_report;
}
@Override
public void create(OrderPurchase order_purchase, Employee employee, OrderPurchaseIncomingReport order_purchase_incoming_report) throws IllegalArgumentException, DAOException {
if (order_purchase.getId() == null) {
throw new IllegalArgumentException("OrderPurchase is not created yet, the OrderPurchase ID is null.");
}
if(employee.getId() == null){
throw new IllegalArgumentException("Employee is not created yet, the Employee ID is null.");
}
if(order_purchase_incoming_report.getId() != null){
throw new IllegalArgumentException("OrderPurchaseIncomingReport is already created, the OrderPurchaseIncomingReport ID is not null.");
}
Object[] values = {
order_purchase.getId(),
employee.getId(),
DAOUtil.toSqlDate(order_purchase_incoming_report.getReport_date()),
order_purchase_incoming_report.getComments()
};
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_INSERT, true, values);
){
int affectedRows = statement.executeUpdate();
if (affectedRows == 0){
throw new DAOException("Creating OrderPurchaseIncomingReport failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
order_purchase_incoming_report.setId(generatedKeys.getInt(1));
} else {
throw new DAOException("Creating OrderPurchaseIncomingReport failed, no generated key obtained.");
}
}
} catch (SQLException e){
throw new DAOException(e);
}
}
@Override
public void update(OrderPurchaseIncomingReport order_purchase_incoming_report) throws IllegalArgumentException, DAOException {
if (order_purchase_incoming_report.getId() == null) {
throw new IllegalArgumentException("OrderPurchaseIncomingReport is not created yet, the OrderPurchaseIncomingReport ID is null.");
}
Object[] values = {
DAOUtil.toSqlDate(order_purchase_incoming_report.getReport_date()),
order_purchase_incoming_report.getComments(),
order_purchase_incoming_report.getId()
};
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_UPDATE, false, values);
){
int affectedRows = statement.executeUpdate();
if(affectedRows == 0){
throw new DAOException("Updating OrderPurchaseIncomingReport failed, no rows affected.");
}
} catch(SQLException e){
throw new DAOException(e);
}
}
@Override
public void delete(OrderPurchaseIncomingReport order_purchase_incoming_report) throws DAOException {
Object[] values = {
order_purchase_incoming_report.getId()
};
try(
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_DELETE, false, values);
){
int affectedRows = statement.executeUpdate();
if(affectedRows == 0){
throw new DAOException("Deleting OrderPurchaseIncomingReport failed, no rows affected.");
} else{
order_purchase_incoming_report.setId(null);
}
} catch(SQLException e){
throw new DAOException(e);
}
}
// Helpers ------------------------------------------------------------------------------------
/**
* Map the current row of the given ResultSet to an OrderPurchaseIncomingReport.
* @param resultSet The ResultSet of which the current row is to be mapped to an OrderPurchaseIncomingReport.
* @return The mapped OrderPurchaseIncomingReport from the current row of the given ResultSet.
* @throws SQLException If something fails at database level.
*/
public static OrderPurchaseIncomingReport map(ResultSet resultSet) throws SQLException{
OrderPurchaseIncomingReport order_purchase_incoming_report = new OrderPurchaseIncomingReport();
order_purchase_incoming_report.setId(resultSet.getInt("ORDER_PURCHASE_INCOMING_REPORT.id"));
order_purchase_incoming_report.setReport_date(resultSet.getDate("ORDER_PURCHASE_INCOMING_REPORT.report_date"));
order_purchase_incoming_report.setComments(resultSet.getString("ORDER_PURCHASE_INCOMING_REPORT.comments"));
order_purchase_incoming_report.setOrderpurchase_id(resultSet.getInt("ORDER_PURCHASE_INCOMING_REPORT.ORDER_PURCHASE_ID"));
//INNER JOINS
order_purchase_incoming_report.setOrderpurchase_companyname(resultSet.getString("COMPANY.name"));
order_purchase_incoming_report.setEmployee_id(resultSet.getInt("EMPLOYEE.id"));
order_purchase_incoming_report.setEmployee_employeename(resultSet.getString("EMPLOYEE.first_name") +" "+ resultSet.getString("EMPLOYEE.last_name"));
return order_purchase_incoming_report;
}
}
|
TypeScript | UTF-8 | 2,020 | 2.53125 | 3 | [
"MIT"
] | permissive | import { ChangeDetectorRef } from '@angular/core';
import { Dir } from '@angular/cdk/bidi';
export declare class TdJsonFormatterComponent {
private _changeDetectorRef;
private _dir;
/**
* Max length for property names. Any names bigger than this get trunctated.
*/
private static KEY_MAX_LENGTH;
/**
* Max length for preview string. Any names bigger than this get trunctated.
*/
private static PREVIEW_STRING_MAX_LENGTH;
/**
* Max tooltip preview elements.
*/
private static PREVIEW_LIMIT;
private _key;
private _data;
private _children;
private _open;
private _levelsOpen;
/**
* levelsOpen?: number
* Levels opened by default when JS object is formatted and rendered.
*/
levelsOpen: number;
readonly open: boolean;
/**
* key?: string
* Tag to be displayed next to formatted object.
*/
key: string;
/**
* data: any
* JS object to be formatted.
*/
data: any;
readonly children: string[];
readonly isRTL: boolean;
constructor(_changeDetectorRef: ChangeDetectorRef, _dir: Dir);
/**
* Refreshes json-formatter and rerenders [data]
*/
refresh(): void;
/**
* Toggles collapse/expanded state of component.
*/
toggle(): void;
isObject(): boolean;
isArray(): boolean;
hasChildren(): boolean;
/**
* Gets parsed value depending on value type.
*/
getValue(value: any): string;
/**
* Gets type of object.
* returns 'null' if object is null and 'date' if value is object and can be parsed to a date.
*/
getType(object: any): string;
/**
* Generates string representation depending if its an object or function.
* see: http://stackoverflow.com/a/332429
*/
getObjectName(): string;
/**
* Creates preview of nodes children to render in tooltip depending if its an array or an object.
*/
getPreview(): string;
private parseChildren();
}
|
Python | UTF-8 | 2,396 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[23]:
import matplotlib.pyplot as plt
import numpy as np
import time
from PIL import Image
# In[28]:
import numpy as np
from PIL import Image
# FUNCTION DEFINTIONS:
# تجزیه ابعاد ماتریس
def openImage(imagePath):
imOrig = Image.open(imagePath)
im = np.array(imOrig)
aRed = im[:, :, 0]
aGreen = im[:, :, 1]
aBlue = im[:, :, 2]
return [aRed, aGreen, aBlue, imOrig]
# فشرده سازی کانال ها
def compressSingleChannel(channelDataMatrix, singularValuesLimit):
uChannel, sChannel, vhChannel = np.linalg.svd(channelDataMatrix)
aChannelCompressed = np.zeros((channelDataMatrix.shape[0], channelDataMatrix.shape[1]))
k = singularValuesLimit
leftSide = np.matmul(uChannel[:, 0:k], np.diag(sChannel)[0:k, 0:k])
aChannelCompressedInner = np.matmul(leftSide, vhChannel[0:k, :])
aChannelCompressed = aChannelCompressedInner.astype('uint8')
return aChannelCompressed
# MAIN PROGRAM:
print ('*** Image Compression using SVD - a demo')
aRed, aGreen, aBlue, originalImage = openImage('image.jpg')
# image width and height:
imageWidth = 512
imageHeight = 512
#number of singular values to use for reconstructing the compressed image
singularValuesLimit = int(input("Singular Value Limit : "))
aRedCompressed = compressSingleChannel(aRed, singularValuesLimit)
aGreenCompressed = compressSingleChannel(aGreen, singularValuesLimit)
aBlueCompressed = compressSingleChannel(aBlue, singularValuesLimit)
imr=Image.fromarray(aRedCompressed,mode=None)
img=Image.fromarray(aGreenCompressed,mode=None)
imb=Image.fromarray(aBlueCompressed,mode=None)
newImage = Image.merge("RGB", (imr,img,imb))
plt.figure(figsize=(9,6))
plt.imshow(originalImage)
plt.figure(figsize=(9,6))
plt.imshow(newImage)
# originalImage.show()
# newImage.show()
# CALCULATE AND DISPLAY THE COMPRESSION RATIO
mr = imageHeight
mc = imageWidth
originalSize = mr * mc * 3
compressedSize = singularValuesLimit * (1 + mr + mc) * 3
print('original size:')
print(originalSize)
print('compressed size:')
print(compressedSize)
print('Ratio compressed size / original size:')
ratio = compressedSize * 1.0 / originalSize
print(ratio)
print('Compressed image size is ' + str( round(ratio * 100 ,2)) + '% of the original image ' )
print('DONE - Compressed the image! Over and out!')
# In[ ]:
|
Rust | UTF-8 | 4,657 | 2.765625 | 3 | [] | no_license | use crate::geo::*;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use rayon::prelude::*;
use std::{
fs::File,
io::{BufReader, Error, ErrorKind, Result},
path::Path,
};
pub struct Triangle {
pub normal: [f32; 3],
pub v1: [f32; 3],
pub v2: [f32; 3],
pub v3: [f32; 3],
pub attr_byte_count: u16,
}
impl Triangle {
pub fn new(v1: [f32; 3], v2: [f32; 3], v3: [f32; 3]) -> Triangle {
Triangle {
normal: [0., 0., 0.],
v1,
v2,
v3,
attr_byte_count: 0,
}
}
}
fn point_eq(lhs: [f32; 3], rhs: [f32; 3]) -> bool { lhs[0] == rhs[0] && lhs[1] == rhs[1] && lhs[2] == rhs[2] }
impl PartialEq for Triangle {
fn eq(&self, rhs: &Triangle) -> bool {
point_eq(self.normal, rhs.normal)
&& point_eq(self.v1, rhs.v1)
&& point_eq(self.v2, rhs.v2)
&& point_eq(self.v3, rhs.v3)
&& self.attr_byte_count == rhs.attr_byte_count
}
}
impl Eq for Triangle {}
pub struct BinaryStlHeader {
pub header: [u8; 80],
pub num_triangles: u32,
}
impl BinaryStlHeader {
pub fn new(num_triangles: u32) -> BinaryStlHeader {
BinaryStlHeader {
header: [0_u8; 80],
num_triangles,
}
}
}
pub struct BinaryStlFile {
pub header: BinaryStlHeader,
pub triangles: Vec<Triangle>,
}
impl BinaryStlFile {
pub fn new(triangles: Vec<Triangle>) -> BinaryStlFile {
let header = BinaryStlHeader::new(triangles.len() as u32);
BinaryStlFile { header, triangles }
}
pub fn to_bytes<T: WriteBytesExt>(&self, out: &mut T) -> Result<()> {
assert_eq!(self.header.num_triangles as usize, self.triangles.len());
// write the header.
out.write_all(&self.header.header)?;
out.write_u32::<LittleEndian>(self.header.num_triangles)?;
// write all the triangles
for t in &self.triangles {
write_point(out, t.normal)?;
write_point(out, t.v1)?;
write_point(out, t.v2)?;
write_point(out, t.v3)?;
out.write_u16::<LittleEndian>(t.attr_byte_count)?;
}
Ok(())
}
}
fn read_point<T: ReadBytesExt>(input: &mut T) -> Result<[f32; 3]> {
let x1 = input.read_f32::<LittleEndian>()?;
let x2 = input.read_f32::<LittleEndian>()?;
let x3 = input.read_f32::<LittleEndian>()?;
Ok([x1, x2, x3])
}
fn read_triangle<T: ReadBytesExt>(input: &mut T) -> Result<Triangle> {
let normal = read_point(input)?;
let v1 = read_point(input)?;
let v2 = read_point(input)?;
let v3 = read_point(input)?;
let attr_count = input.read_u16::<LittleEndian>()?;
Ok(Triangle {
normal,
v1,
v2,
v3,
attr_byte_count: attr_count,
})
}
fn read_header<T: ReadBytesExt>(input: &mut T) -> Result<BinaryStlHeader> {
let mut header = [0u8; 80];
match input.read(&mut header) {
Ok(n) => {
if n == header.len() {
} else {
return Err(Error::new(ErrorKind::Other, "Couldn't read STL header"));
}
},
Err(e) => return Err(e),
};
let num_triangles = input.read_u32::<LittleEndian>()?;
Ok(BinaryStlHeader { header, num_triangles })
}
pub fn read_stl<T: ReadBytesExt>(input: &mut T) -> Result<BinaryStlFile> {
// read the header
let header = read_header(input)?;
let mut triangles = Vec::new();
for _ in 0..header.num_triangles {
triangles.push(read_triangle(input)?);
}
Ok(BinaryStlFile { header, triangles })
}
pub fn stl_to_tri<P: AsRef<Path>>(filename: P) -> Result<Vec<Triangle3d>> {
let file = File::open(filename)?;
let mut buf_reader = BufReader::new(file);
let stl = read_stl(&mut buf_reader)?;
Ok(to_triangles3d(&stl))
}
fn write_point<T: WriteBytesExt>(out: &mut T, p: [f32; 3]) -> Result<()> {
for x in &p {
out.write_f32::<LittleEndian>(*x)?;
}
Ok(())
}
pub fn to_triangles3d(file: &BinaryStlFile) -> Vec<Triangle3d> {
// TODO: do I want to keep the normals? don't need them yet
file.triangles
.par_iter()
.map(|x| {
Triangle3d::new(
(x.v1[0], x.v1[1], x.v1[2]),
(x.v2[0], x.v2[1], x.v2[2]),
(x.v3[0], x.v3[1], x.v3[2]),
)
})
.collect()
}
pub fn from_triangles3d(tris: &[Triangle3d]) -> BinaryStlFile {
let triangles: Vec<_> = tris
.iter()
.map(|tri| Triangle::new(tri.p1.into(), tri.p2.into(), tri.p3.into()))
.collect();
BinaryStlFile::new(triangles)
}
|
C | UTF-8 | 331 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
main()
{
int a[10],i,big,small;
printf("enter the elements\n");
for(i=0;i<10;i++)
scanf("%d\n",&a[i]);
big=a[0];
for(i=1;i<10;i++)
{
if(a[i]>big)
big=a[i];
}
printf("big=%d\n",big);
small=a[0];
for(i=1;i<10;i++)
{
if(a[i]<small)
small=a[i];
}
printf("small=%d\n",small);
}
|
Ruby | UTF-8 | 508 | 3.84375 | 4 | [] | no_license | def echo(text)
return "#{text}"
end
def shout(text)
return "#{text.upcase}"
end
def repeat(text)
return "#{text} #{text}"
end
def repeat(text, n)
return n.times { |text| puts "#{text}" }
end
def start_of_word(text, number)
str = "#{text}"
return str[0,number]
end
def first_word(sentence)
return sentence.split.first
end
def titleize(title)
little_words = %w(end and the)
title.capitalize.gsub(/(\w+)/) do |word|
little_words.include?(word) ? word : word.capitalize
end
end
|
C# | UTF-8 | 1,576 | 2.609375 | 3 | [
"MS-PL"
] | permissive | using Ganss.XSS;
namespace Roadkill.Text.Sanitizer
{
public interface IHtmlSanitizerFactory
{
IHtmlSanitizer CreateHtmlSanitizer();
}
public class HtmlSanitizerFactory : IHtmlSanitizerFactory
{
private readonly TextSettings _textSettings;
private readonly IHtmlWhiteListProvider _htmlWhiteListProvider;
public HtmlSanitizerFactory(TextSettings textSettings, IHtmlWhiteListProvider htmlWhiteListProvider)
{
_textSettings = textSettings;
_htmlWhiteListProvider = htmlWhiteListProvider;
}
public IHtmlSanitizer CreateHtmlSanitizer()
{
if (!_textSettings.UseHtmlWhiteList)
{
return null;
}
HtmlWhiteListSettings whiteListSettings = _htmlWhiteListProvider.Deserialize();
string[] allowedTags = whiteListSettings.AllowedElements.ToArray();
string[] allowedAttributes = whiteListSettings.AllowedAttributes.ToArray();
if (allowedTags.Length == 0)
{
allowedTags = null;
}
if (allowedAttributes.Length == 0)
{
allowedAttributes = null;
}
var htmlSanitizer = new HtmlSanitizer(allowedTags, null, allowedAttributes);
htmlSanitizer.AllowDataAttributes = false;
htmlSanitizer.AllowedAttributes.Add("class");
htmlSanitizer.AllowedAttributes.Add("id");
htmlSanitizer.AllowedSchemes.Add("mailto");
htmlSanitizer.RemovingAttribute += (sender, e) =>
{
// Don't clean /wiki/Special:Tag urls in href="" attributes
if (e.Attribute.Name.ToUpperInvariant() == "HREF" && e.Attribute.Value.Contains("Special:"))
{
e.Cancel = true;
}
};
return htmlSanitizer;
}
}
}
|
Python | UTF-8 | 1,870 | 2.59375 | 3 | [] | no_license |
import cv2
import numpy as np
from helpers import Motor
from helpers import color_finder
from helpers import get_contours, find_mean, auto_canny, roi
print(cv2.__version__)
cap = cv2.VideoCapture(0)
motor = Motor()
if __name__ == "__main__":
print("Starting seek and destroy ...")
while True:
_, frame = cap.read()
print("Image Captured ...")
#print(frame.size)
red_rect = white_black = frame
#First find if a rectangular patch of red exists
red_rect = color_finder(red_rect, color="red")
#imgray = cv2.cvtColor(red_rect,cv2.COLOR_BGR2GRAY)
# ret,thresh = cv2.threshold(imgray,127,255,0)
contours, _ = get_contours(red_rect)
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# median = cv2.medianBlur(gray, 7)
# edged = auto_canny(median)
# contours, _ = get_contours(edged)
# print("Searched Contours ...")
for contour in contours:
if cv2.contourArea(contour) > 200:
position = find_mean(contour)
if position[0] < 290:
print("move_right")
motor.rightTurn()
elif position[0] <= 350 and position[0] >= 290:
print("move_forward")
motor.forwardDrive()
elif position[0] > 350:
print("move_left")
motor.leftTurn()
else:
print("stop")
motor.allStop()
x,y,w,h = cv2.boundingRect(contour)
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
# cv2.imshow('Output', median)
cv2.imshow('Red', frame)
print("Finished ...")
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
|
Python | UTF-8 | 467 | 3.359375 | 3 | [
"MIT"
] | permissive | import numpy as np
from scipy.special import logsumexp
def exp_normalize(x):
b = x.max()
y = np.exp(x - b)
return y / y.sum()
def sum_lnspace(a, b):
""" Given a = ln(p) and b=ln(q), return ln(p+q) in natural log space"""
if a > b: # ensure a is always the smallest term, so log function is on smaller.
temp = a
a = b
b = temp
ln_sum = b + np.log(np.exp(a - b) + 1)
return ln_sum
|
C++ | UTF-8 | 13,246 | 2.890625 | 3 | [] | no_license | #include "Analyst.h"
#include "Menu.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdio.h>
#include <iomanip>
#include <Windows.h>
void Analyst::write_code(std::ofstream &stream) const
{
stream << code;
}
void Analyst::print_code(std::ostream &stream) const
{
stream << code;
}
void move_bill(std::string oldpath, std::string newpath)
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if (MoveFile(oldpath.c_str(), newpath.c_str()))
return;
else
{
SetConsoleTextAttribute(h, FOREGROUND_RED);
std::cout << "GRESKA.";
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
}
}
void Analyst::read_bills()
{
stringvec str;
read_directory("Bills.", str);
std::ifstream file;
for (std::string temp : str)
{
if (temp.find(".txt") != std::string::npos || temp.find(".csv") != std::string::npos) // Provjera da li je .txt ili .csv
{
std::string localTemp = ".\\Bills\\"; // Dodavanje relativne putanje
localTemp.append(temp);
file.open(localTemp);
if (file.is_open())
{
int format = check_format(file);
file.seekg(0, std::ios::beg);
if (check_bill(file, format) == true) // Ako je racun validan
{
file.seekg(0, std::ios::beg);
read_bill(file, format);
file.close();
std::string newPath = ".\\Valide\\"; // Dodavanje relativne putanje
newPath.append(temp);
move_bill(localTemp, newPath);
}
else // Ako racun nije validan
{
file.close();
std::string newPath = ".\\Error\\"; // Dodavanje relativne putanje
newPath.append(temp);
move_bill(localTemp, newPath);
}
}
}
}
}
Analyst::Analyst(const std::string name, const std::string surname, const std::string username, const std::string pin, const int status) : User(name, surname, username, pin, status) {}
int Analyst::get_code() const
{
return code;
}
void Month_print(int k)
{
switch (k)
{
case 1: std::cout << "Januar"; break;
case 2: std::cout << "Februar"; break;
case 3: std::cout << "Mart"; break;
case 4: std::cout << "April"; break;
case 5: std::cout << "Maj"; break;
case 6: std::cout << "Jun"; break;
case 7: std::cout << "Jul"; break;
case 8: std::cout << "Avgust"; break;
case 9: std::cout << "Septembar"; break;
case 10: std::cout << "Oktobar"; break;
case 11: std::cout << "Novembar"; break;
case 12: std::cout << "Decembar"; break;
default:
break;
}
}
void ShowData(int n) // Funkcija za prikaz podataka
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
std::string name_temp, amount_temp, price_temp, total_temp, customer_temp, date_temp; // Pomocne promjenljive za prihvatanje podataka o proizvodu
struct Product //Pomocna struktura za formiranje proizvoda
{
std::string name_str, amount_str, price_str, total_str, customer_str, date_str;
double d_amount, d_price, d_total;
int day, month, year;
Product(std::string a,std::string b,std::string c,std::string d,std::string e,std::string f) : name_str(a),amount_str(b),price_str(c),total_str(d),customer_str(e),date_str(f) {}
};
struct Final_Product // Konacna forma proizvoda
{
std::string name, customer; // Naziv proizvoda i kupca, respektivno
double amount, price, total; // Kolicina, cijena, ukupno
int dd, mm, yy; // Varijable za predstavljanje datuma
Final_Product(std::string a,std::string b,double c,double d,double e,int f,int g, int h) : name(a),customer(b),amount(c),price(d),total(e),dd(f),mm(g),yy(h) {}
};
std::fstream database;
int i,p=0;
float PDV = 1.17;
std::vector<Product> AllInOne; // Prvobitni niz
AllInOne.reserve(300);
database.open("Storage.txt", std::ios::in);
if (database.is_open())
{
while (database >> amount_temp >> price_temp >> total_temp >> customer_temp >> date_temp >> name_temp)
{
AllInOne.push_back(Product(name_temp, amount_temp, price_temp, total_temp, customer_temp, date_temp)); // Citanje proizvoda iz datoteke
p++;
}
for (i = 0; i < (int)AllInOne.size(); ++i) // Konvertovanje polja
{
AllInOne[i].d_amount = std::atof(AllInOne[i].amount_str.c_str());
AllInOne[i].d_price = std::atof(AllInOne[i].price_str.c_str());
AllInOne[i].d_total = std::atof(AllInOne[i].total_str.c_str());
sscanf_s(AllInOne[i].date_str.c_str(), "%d/%d/%d", &AllInOne[i].day, &AllInOne[i].month, &AllInOne[i].year);
}
if (n == 1) // Sortira za odredjenog kupca
{
std::string wanted;
std::cout << "Unesite tacan naziv kupca:";
std::cin >> wanted;
std::vector<Final_Product> arr;
arr.reserve(300);
for (i = 0; i < (int)AllInOne.size(); ++i) // Filtrira niz po zadanom kupcu
{
if ((wanted).compare(AllInOne[i].customer_str) == 0)
arr.push_back(Final_Product(AllInOne[i].name_str, AllInOne[i].customer_str, AllInOne[i].d_amount, AllInOne[i].d_price, AllInOne[i].d_total, AllInOne[i].day, AllInOne[i].month, AllInOne[i].year));
}
if (((int)arr.size()) == 0)
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << "Trazeni kupac ne postoji u bazi podataka. Provjerite tacan naziv kupca." << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
return;
}
std::vector<Final_Product> to_print; // Konacni niz
to_print.reserve(300);
to_print.push_back(Final_Product(arr[0].name, arr[0].customer, arr[0].amount, arr[0].price, arr[0].total, arr[0].dd, arr[0].mm, arr[0].yy));
int k, j, p,sum=0;
for (k = 1; k < (int)arr.size(); ++k) // Formiranje konacnog niza
{
p = 0;
for (j = 0; j < (int)to_print.size(); ++j)
{
if ((arr[k].name).compare(to_print[j].name) == 0) // Filtriranje duplih proizvoda
{
p = 1;
to_print[j].amount += arr[k].amount;
to_print[j].total += arr[k].total;
}
}
if (p == 0)
to_print.push_back(Final_Product(arr[k].name, arr[k].customer, arr[k].amount, arr[k].price, arr[k].total, arr[k].dd, arr[k].mm, arr[k].yy));
}
std::cout << std::endl;
std::cout << "================================================" << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
std::cout << " Prikaz podataka za kupca: " << wanted << std::endl << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << std::setw(15) << std::left << "Naziv" << std::setw(12) << "Kolicina" << std::setw(12) << "Cijena" << std::setw(12) << "Ukupno" << std::setw(12) << std::endl;
std::cout << "================================================" << std::endl;
for (i = 0; i < (int)to_print.size(); ++i)
{
sum += to_print[i].total;
std::cout << std::setw(15) << std::left << to_print[i].name << std::setw(12) << to_print[i].amount << std::setw(12) << to_print[i].price << std::setw(12) << to_print[i].total << std::endl;
}
std::cout << std::endl;
std::cout << "Kupac " << wanted << " je ukupno potrosio sljedeci iznos: " << (sum*PDV) << std::endl << std::endl;
}
if (n == 2) // Sortiranje za odredjeni mjesec
{
int wanted;
std::cout << "Unesite redni broj mjeseca u godini:";
std::cin >> wanted;
std::vector<Final_Product> arr;
arr.reserve(50);
for (i = 0; i < (int)AllInOne.size(); ++i) // Filtriranje za zadani mjesec
{
if (AllInOne[i].month == wanted)
arr.push_back(Final_Product(AllInOne[i].name_str, AllInOne[i].customer_str, AllInOne[i].d_amount, AllInOne[i].d_price, AllInOne[i].d_total, AllInOne[i].day, AllInOne[i].month, AllInOne[i].year));
}
if (((int)arr.size()) == 0)
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << "U trazenom mjesecu nije bilo prometa ili ste napravili nepravilan unos."<<std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
return;
}
std::vector<Final_Product> to_print; // Konacni niz
to_print.reserve(50);
to_print.push_back(Final_Product(arr[0].name, arr[0].customer, arr[0].amount, arr[0].price, arr[0].total, arr[0].dd, arr[0].mm, arr[0].yy));
int k, j, p, sum = 0;
for (k = 1; k < (int)arr.size(); ++k) // Formiranje konacnog niza
{
p = 0;
for (j = 0; j < (int)to_print.size(); ++j)
{
if ((arr[k].name).compare(to_print[j].name) == 0) // Filtriranje duplih proizvoda
{
p = 1;
to_print[j].amount += arr[k].amount;
to_print[j].total += arr[k].total;
}
}
if (p == 0)
to_print.push_back(Final_Product(arr[k].name, arr[k].customer, arr[k].amount, arr[k].price, arr[k].total, arr[k].dd, arr[k].mm, arr[k].yy));
}
std::cout << std::endl;
std::cout << "==========================================================" << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
std::cout << " Prikaz podataka za mjesec: "; Month_print(wanted); std::cout << std::endl << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << std::setw(15) << std::left << "Naziv" << std::setw(12) << "Kolicina" << std::setw(12) << "Cijena" << std::setw(12) << "Ukupno" << std::setw(12) << "Kupac" << std::endl;
std::cout << "==========================================================" << std::endl;
for (i = 0; i < (int)to_print.size(); ++i) // Ispis i sumiranje troskova
{
sum += to_print[i].total;
std::cout << std::setw(15) << std::left << to_print[i].name << std::setw(12) << to_print[i].amount << std::setw(12) << to_print[i].price << std::setw(12) << to_print[i].total <<std::setw(12)<<to_print[i].customer<<std::endl;
}
std::cout << std::endl;
std::cout << "U " << wanted << ". mjesecu je ukupno potrosen sljedeci iznos: " << (sum*PDV) << std::endl << std::endl;
}
if (n == 3) // Sortiranje za odredjeni proizvod
{
std::string wanted;
std::cout << "Unesite tacan naziv proizvoda (Napomena: Razmaci u nazivu trebaju biti popunjeni sa '_' !): ";
std::cin >> wanted;
std::vector<Final_Product> arr;
arr.reserve(50);
for (i = 0; i < (int)AllInOne.size(); ++i) // Filtriranje za zadani proizvod
{
if ((wanted).compare(AllInOne[i].name_str) == 0)
arr.push_back(Final_Product(AllInOne[i].name_str, AllInOne[i].customer_str, AllInOne[i].d_amount, AllInOne[i].d_price, AllInOne[i].d_total, AllInOne[i].day, AllInOne[i].month, AllInOne[i].year));
}
if (((int)arr.size()) == 0)
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << "Trazeni proizvod ne postoji u bazi podataka. Provjerite da li ste unijeli tacan naziv." << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
return;
}
std::vector<Final_Product> to_print; // Konacni niz
to_print.reserve(300);
to_print.push_back(Final_Product(arr[0].name, arr[0].customer, arr[0].amount, arr[0].price, arr[0].total, arr[0].dd, arr[0].mm, arr[0].yy));
int k, j, p, sum = 0;
for (k = 1; k < (int)arr.size(); ++k) // Formiranje konacnog niza
{
p = 0;
for (j = 0; j < (int)to_print.size(); ++j)
{
if ((arr[k].customer).compare(to_print[j].customer) == 0) // Filtriranje duplih proizvoda
{
p = 1;
to_print[j].amount += arr[k].amount;
to_print[j].total += arr[k].total;
}
}
if (p == 0)
to_print.push_back(Final_Product(arr[k].name, arr[k].customer, arr[k].amount, arr[k].price, arr[k].total, arr[k].dd, arr[k].mm, arr[k].yy));
}
std::cout << std::endl;
std::cout << "================================================" << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
std::cout << " Prikaz podataka za proizvod: " << wanted << std::endl << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << std::setw(15) << std::left << "Kupac" << std::setw(12) << "Kolicina" << std::setw(12) << "Cijena" << std::setw(12) << "Ukupno" << std::endl;
std::cout << "================================================" << std::endl;
for (i = 0; i < (int)to_print.size(); ++i) // Ispis i sumiranje
{
sum += to_print[i].total;
std::cout << std::setw(15) << std::left << to_print[i].customer << std::setw(12) << to_print[i].amount << std::setw(12) << to_print[i].price << std::setw(12) << to_print[i].total << std::endl;
}
std::cout << std::endl;
std::cout << "Na proizvod " << wanted << " je ukupno potrosen sljedeci iznos: " << (sum*PDV) << std::endl << std::endl;
}
}
}
int Analyst::AnalystMenuOptions() // Meni za analititcara
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
read_bills();
char c;
do
{
print_analyst_menu();
std::cin >> c;
switch (c)
{
case '1': ShowData(1); break; // Poziva prikaz podataka za odredjenog kupca
case '2': ShowData(2); break; // Poziva prikaz podataka za odredjeni mjesec
case '3': ShowData(3); break; // Poziva prikaz podataka za odredjeni proizvod
case '4': std::cout << "Dovidjenja!" << std::endl; return 0; break;
default: SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_GREEN);
std::cout << "Nepostojeca opcija! Pokusajte ponovo" << std::endl;
SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN); break;
}
} while (true);
} |
JavaScript | UTF-8 | 7,897 | 2.671875 | 3 | [] | no_license | /*global chrome*/
import React from 'react';
import './App.css';
import MenuItem from '@material-ui/core/MenuItem';
import MenuList from '@material-ui/core/MenuList';
import Paper from '@material-ui/core/Paper';
import { makeStyles } from '@material-ui/core/styles';
import moment from 'moment';
import TimePicker from 'react-time-picker';
import DoneIcon from '@material-ui/icons/Done';
import IconButton from '@material-ui/core/IconButton';
import AddAlarmIcon from '@material-ui/icons/AddAlarm';
import AlarmOffIcon from '@material-ui/icons/AlarmOff';
import AlarmOnIcon from '@material-ui/icons/AlarmOn';
import ToggleOnOutlinedIcon from '@material-ui/icons/ToggleOnOutlined';
import ToggleOffOutlinedIcon from '@material-ui/icons/ToggleOffOutlined';
import AccessAlarmsIcon from '@material-ui/icons/AccessAlarms';
import TextField from '@material-ui/core/TextField';
class AlarmMenu extends React.Component{
constructor(props) {
super(props);
this.state = {
classes: this.makeStyles(),
alarmState:null,
currentAlarmTime:null,
setAlarmClicked:false,
timePicker:null
};
}
/**
* Orchestrates the toggling of the alarm button
*/
toggleAlarm(){
if(this.state.alarmState == true){
chrome.storage.sync.set({alarmState: false}, function() { //turning alarm off
this.setState({alarmState:false});
chrome.alarms.clear("dailyIntervalsAlarm", function (){
});
chrome.storage.sync.set({dailyIntervalsAlarmTime: null}, function(){
this.setState({currentAlarmTime:null});
}.bind(this));
}.bind(this));
}
else if(this.state.alarmState == false){
chrome.storage.sync.set({alarmState: true}, function() { //turning alarm on
this.setState({alarmState:true});
}.bind(this));
}
}
/**
*
* @param {String} time - A string in the format HH:MM
* @returns {Date} - A javascript date object
*/
convertTimetoDate(time){
let splitTime = time.split(":");
let hour = splitTime[0];
let minutes = splitTime[1];
let date = new Date();
date.setHours(hour,minutes,0,0);
return date;
}
/**
* Converts javascript dates to momentjs dates for ease of use
* @param {Date} date - A javascript date object
*/
convertDateToMoment(date){
let time = moment(date).format("hh:mm A")
return time
}
/**
* Parses the current alarm time to a more readable form or displays Alarm not Set
*/
parseCurrentAlarmTime(){
if (this.state.currentAlarmTime == null || this.state.currentAlarmTime == undefined){
return "Alarm not Set"
}
else{
let time = this.convertDateToMoment(this.state.currentAlarmTime);
return time
}
}
/**
* Orchestrates the setting of the alarm
*/
setAlarm(){
if(this.state.timePicker == undefined || this.state.timePicker == null){
alert("Please select a valid time");
}
let option = window.confirm(`Your alarm has been set for: ${this.state.timePicker} \nIs this fine?`);
if (option==true){
let time = this.convertTimetoDate(this.state.timePicker);
if(this.state.alarmState == true){
chrome.alarms.clear("dailyIntervalsAlarm", function (){}); /* Clears chrome alarm event if one already exists */
chrome.alarms.create('dailyIntervalsAlarm', { periodInMinutes: 1440 , when: Number(time)}); /* Creates chrome alarm event */
chrome.storage.sync.set({dailyIntervalsAlarmTime: Number(time)},function(){ /* Sets the intervalsAlarmTime in chrome storage */
this.setState({currentAlarmTime:time});
}.bind(this));
}
else if(this.state.alarmState == false){
chrome.storage.sync.set({dailyIntervalsAlarmTime: Number(time)},function(){ /* Sets the intervalsAlarmTime in chrome storage */
this.setState({currentAlarmTime:time});
}.bind(this));
}
this.displaySetAlarmMenuItem();
}
else{
alert("Ok, please enter your desired time");
}
}
displayTimePicker(){
this.setState({setAlarmClicked:true});
}
displaySetAlarmMenuItem(){
this.setState({setAlarmClicked:false});
}
/**
* Sets the state with the value from the time picker element as the value changes
* @param {Object} timePicker
*/
onTimePickerChange = timePicker => {
this.setState({ timePicker: timePicker.target.value });
}
componentDidMount(){
chrome.storage.sync.get('alarmState', function(result) { //Gets alarm state from chrome storage each time the extension is opened and sets it in the state
this.setState({alarmState:result.alarmState});
}.bind(this));
chrome.storage.sync.get('dailyIntervalsAlarmTime', function(result){ //Gets alarm time from chrome storage each time the extension is opened and sets it in the state
this.setState({currentAlarmTime:result.dailyIntervalsAlarmTime})
}.bind(this));
}
render(){
return (
<div>
<div className={this.state.classes.root}>
<Paper className={this.state.classes.paper}>
<MenuList>
{this.state.alarmState ?
<MenuItem id="onMenuItem" divider={true} button={false}><AlarmOnIcon style={{ color: "green" }} className="menuItemIcon"/>Alarm is ON</MenuItem>
: <MenuItem id="offMenuItem" divider={true} button={false}><AlarmOffIcon color="secondary" className="menuItemIcon"/>Alarm is OFF</MenuItem>}
<MenuItem className="menuItem" divider={true} button={false}> <AccessAlarmsIcon className="menuItemIcon"/> {this.parseCurrentAlarmTime()}</MenuItem>
<MenuItem className="menuItem" divider={true} onClick={()=>this.toggleAlarm()}>{this.state.alarmState?<ToggleOnOutlinedIcon className="menuItemIcon"/>:<ToggleOffOutlinedIcon className="menuItemIcon"/>} Toggle Alarm </MenuItem>
{this.state.setAlarmClicked ? <MenuItem className="menuItem" button={false}>
<TextField
id="time"
type="time"
//defaultValue="07:30"
className={this.state.classes.textField}
onChange={this.onTimePickerChange}
InputLabelProps={{
shrink: true,
}}
inputProps={{
step: 300, // 5 min
}}
/>
<IconButton onClick={()=>this.setAlarm()} children={<DoneIcon/>}/>
</MenuItem>
: <MenuItem className="menuItem" onClick={()=>this.displayTimePicker()}> <AddAlarmIcon className="menuItemIcon"/> Set Alarm</MenuItem>}
</MenuList>
</Paper>
</div>
</div>
);
}
/**
* Handles some of the styling for the materialui components
*/
makeStyles(){
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
fontSize:'0.85rem'
},
paper: {
marginRight: theme.spacing(2),
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200,
},
}));
return useStyles
}
}
export default AlarmMenu; |
Markdown | UTF-8 | 591 | 2.75 | 3 | [
"MIT"
] | permissive | # Graph Convolutional Network
Re-implemented for paper [Semi-Supervised Classification with Graph Convolutional Networks](https://openreview.net/pdf?id=SJU4ayYgl) in Pytorch.
## Results
|Description |Citeseer|Cora |Pubmed|
|---------------|--------|------|------|
|Renormalization|66.0 |74.1 |76.3 |
## Runing code
python train.py --dataset cora --epoch 200
## Parameters
Keep same as the original paper
## Data
Three classification tasks with a graph-structure net: citeseer, cora and pubmed. The split of training, valization and testing is the same as original paper.
|
Python | UTF-8 | 5,033 | 2.546875 | 3 | [] | no_license | from urllib.request import urlopen
import json
import requests
from io import BytesIO
import base64
import urllib
import matplotlib
from datascience import *
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
plt.style.use('fivethirtyeight')
sns.set()
sns.set_context("talk")
##############################################################################
"*** RETURNS CATEGORY ID FROM USER CATEGORY INPUT ***"
##############################################################################
def findID(category):
cats = Table().read_table("categories.csv")
return cats.where('Category', category).column('#').item(0)
##############################################################################
"*** RETURNS Condition Integer FROM USER Condition String ***"
##############################################################################
def findCondition(condition):
if condition == "New":
return 1000
return 3000
def calculate(search_term, category, condition):
##########################################################################
"*** API ***"
##########################################################################
key = 'JustinCh-SmartPri-PRD-416e5579d-aa266db1'
keywords = search_term.replace(' ', '+')
category = findID(category)
condition = findCondition(condition)
url = ("http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findCompletedItems&SERVICE-VERSION=1.7.0&SECURITY-APPNAME=JustinCh-SmartPri-PRD-416e5579d-aa266db1&RESPONSE-DATA-FORMAT=JSON&REST-PAYLOAD&keywords=" + keywords + "&categoryId=" + str(category) + "&itemFilter(0).name=Condition&itemFilter(0).value=" + str(condition) + "&itemFilter(1).name=FreeShippingOnly&itemFilter(1).value=false&itemFilter(2).name=SoldItemsOnly&itemFilter(2).value=true")
###########################################################################
"*** CLEANS UP .JSON TO PANDAS DATAFRAME ***"
###########################################################################
apiResult = requests.get(url)
listings, prices, offer, BIN = [], [], [], []
parsed = apiResult.json()
numPages = int(parsed["findCompletedItemsResponse"][0]['paginationOutput'][0]['totalPages'][0])
if numPages > 10:
numPages = 10
for page in range(1, numPages+1):
apiResult_page = requests.get(url+"&paginationInput.pageNumber=" + str(page))
parsed_page = apiResult_page.json()
for item in parsed_page["findCompletedItemsResponse"][0]["searchResult"][0]["item"]:
listings.append(item['title'][0])
prices.append(float(item['sellingStatus'][0]['convertedCurrentPrice'][0]['__value__']))
offer.append(item['listingInfo'][0]['bestOfferEnabled'][0])
BIN.append(item['listingInfo'][0]['buyItNowAvailable'][0])
###########################################################################
"*** PANDAS OPERATIONS FROM TABLE TO GRAPH ***"
###########################################################################
dataTable = pd.concat([pd.Series(listings), pd.Series(prices), pd.Series(offer), pd.Series(BIN)], axis=1)
dataTable.columns = ['Name', 'Price', 'Best Offer Enabled', "Buy It Now"]
try:
plt.figure(figsize=(8, 6))
lowLimit = np.percentile(np.array(dataTable['Price']), 2.5)
highLimit = np.percentile(np.array(dataTable['Price']), 97.5)
sns.distplot(dataTable['Price'],rug=True, norm_hist=True, color='teal')
plt.ylabel('Proportion of Sales')
plt.xlim(lowLimit, highLimit)
plt.title('Price Distribution for ' + search_term + ' Sold');
plt.savefig('dist.png')
stats = dataTable.describe()['Price']
summary = ["$" + str(round(x, 2)) for x in [stats[1], stats[2], stats[4], stats[5], stats[6]]]
figfile = BytesIO()
plt.savefig(figfile, format='png')
figfile.seek(0) # rewind to beginning of file
graph = base64.b64encode(open('dist.png', 'rb').read()).decode('utf-8').replace('\n', '')
###########################################################################
"*** RETURN DICT OF IMPORTANT INFO ***"
###########################################################################
low, high = round(min(stats[1], stats[5]), 2), round(max(stats[1], stats[5]), 2)
return {'Mean':summary[0], 'SD':summary[1], '25%':summary[2], '50%':summary[3], '75%':summary[4], 'Min':"$"+str(low), 'Max':"$"+str(high), 'Graph':graph}
except:
urllib.request.urlretrieve("https://kuwaitlifestyleblog.files.wordpress.com/2016/07/windows_bug6-100581894-primary-idge.jpg?w=608&h=405", "error.png")
error = base64.b64encode(open('error.png', 'rb').read()).decode('utf-8').replace('\n', '')
msg = 'No Matches for Search'
return {'Mean':msg, 'SD':msg, '25%':msg, '50%':msg, '75%':msg, 'Min':'N/A', 'Max':'N/A', 'Graph':error}
|
Python | UTF-8 | 985 | 2.65625 | 3 | [] | no_license | from pyrebase import initialize_app
from datetime import datetime
#Firebase credentials
config = {
"apiKey": "AIzaSyBhm88HaSINpFkJaftIQ6qi4bNLsZGc9Pc",
"authDomain": "tweetsdb-c46cf.firebaseapp.com",
"databaseURL": "https://tweetsdb-c46cf.firebaseio.com/",
"storageBucket": "tweetsdb-c46cf.appspot.com",
}
#Firebase Auth and get database method
firebase = initialize_app(config)
db = firebase.database()
def getKeywordsFromDatabase():
keywords_obj = db.child('keyword').shallow().get()
keywords = keywords_obj.val()
return keywords
def getData(keyword):
data_obj = db.child('keyword').child(keyword).get()
data = data_obj.val()['text']
data = data.split(';')
return data
def saveFeedback(feed):
data = {}
data['text'] = feed
data['date'] = str(datetime.now())
db.child("feedback").push(data)
def getFeedback():
data_obj = db.child('feedback').get()
data = data_obj.val()
res = []
for item in data:
res.append(data[item])
return res
|
SQL | UTF-8 | 5,447 | 3.53125 | 4 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 14-07-2017 a las 21:48:13
-- Versión del servidor: 10.1.21-MariaDB
-- Versión de PHP: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `practica2017`
--
DELIMITER $$
--
-- Procedimientos
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_autenticarUsuario` (`_nick` VARCHAR(30), `_contrasena` VARCHAR(30)) BEGIN
SELECT * FROM Usuario WHERE nick = _nick AND contrasena = _contrasena LIMIT 1;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_deleteUsuario` (IN `u_idUsuario` INT) BEGIN
DELETE FROM Usuario
WHERE idUsuario = u_idUsuario;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertTarea` (`_titulo` VARCHAR(30), `_descripcion` VARCHAR(30)) BEGIN
INSERT INTO Tarea(titulo, descripcion, cambios_contrasena, fecha_registro, fecha_final)
VALUES(_titulo, _descripcion, 0, NOW(), NOW(), NULL);
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertUsuario` (`_nick` VARCHAR(30), `_contrasena` VARCHAR(30)) BEGIN
INSERT INTO Usuario(nick, contrasena, cambios_contrasena, fecha_registro, fecha_modificacion, picture)
VALUES(_nick, _contrasena, 0, NOW(), NOW(), NULL);
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_selectTarea` (`_titulo` VARCHAR(30), `_descripcion` VARCHAR(30)) BEGIN
SELECT * FROM Tarea;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_selectUsuario` (`_nick` VARCHAR(30), `_contrasena` VARCHAR(30)) BEGIN
SELECT * FROM usuario;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_updateUsuario` (IN `u_idUsuario` INT, IN `user_name` VARCHAR(30), IN `passwordUser` VARCHAR(30)) BEGIN
UPDATE Usuario
SET
nick = user_name,
contrasena = passwordUser
WHERE idUsuario = u_idUsuario;
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tarea`
--
CREATE TABLE `tarea` (
`idTarea` int(11) NOT NULL,
`titulo` varchar(30) NOT NULL,
`descripcion` varchar(40) NOT NULL,
`fecha_registro` datetime NOT NULL,
`fecha_final` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `tarea`
--
INSERT INTO `tarea` (`idTarea`, `titulo`, `descripcion`, `fecha_registro`, `fecha_final`) VALUES
(1, 'laboratorio', 'matematica', '2017-07-11 00:00:00', '2017-07-21 07:15:04'),
(2, 'practica ', 'examen', '2017-07-12 00:00:00', '2017-07-18 00:00:00'),
(3, 'lectura', 'idioma', '2017-07-22 00:00:00', '2017-07-31 00:00:00');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE `usuario` (
`idUsuario` int(11) NOT NULL,
`nick` varchar(30) NOT NULL,
`contrasena` varchar(30) NOT NULL,
`cambios_contrasena` int(11) NOT NULL,
`fecha_registro` datetime NOT NULL,
`fecha_modificacion` datetime DEFAULT NULL,
`picture` text
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`idUsuario`, `nick`, `contrasena`, `cambios_contrasena`, `fecha_registro`, `fecha_modificacion`, `picture`) VALUES
(2, 'pablo', '1234', 0, '2017-07-14 11:00:17', '2017-07-14 11:00:17', NULL),
(3, 'Sam', 'zero', 0, '2017-07-14 13:31:39', '2017-07-14 13:31:39', NULL),
(4, 'juan jose', 'asfts', 0, '2017-07-14 13:32:17', '2017-07-14 13:32:17', NULL),
(5, 'fernando', 'wicho', 0, '2017-07-14 13:32:52', '2017-07-14 13:32:52', NULL);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuariotareas`
--
CREATE TABLE `usuariotareas` (
`idUsuarioTareas` int(11) NOT NULL,
`idUsuario` int(11) NOT NULL,
`idTarea` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `tarea`
--
ALTER TABLE `tarea`
ADD PRIMARY KEY (`idTarea`);
--
-- Indices de la tabla `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`idUsuario`);
--
-- Indices de la tabla `usuariotareas`
--
ALTER TABLE `usuariotareas`
ADD PRIMARY KEY (`idUsuarioTareas`),
ADD KEY `idUsuario` (`idUsuario`),
ADD KEY `idTarea` (`idTarea`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `tarea`
--
ALTER TABLE `tarea`
MODIFY `idTarea` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `usuario`
--
ALTER TABLE `usuario`
MODIFY `idUsuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `usuariotareas`
--
ALTER TABLE `usuariotareas`
MODIFY `idUsuarioTareas` int(11) NOT NULL AUTO_INCREMENT;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `usuariotareas`
--
ALTER TABLE `usuariotareas`
ADD CONSTRAINT `usuariotareas_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`),
ADD CONSTRAINT `usuariotareas_ibfk_2` FOREIGN KEY (`idTarea`) REFERENCES `tarea` (`idTarea`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
PHP | UTF-8 | 915 | 2.921875 | 3 | [] | no_license | <?php
include('../common/common.php');
/**
* Class RaceCondition
* Bad example, must not delete cache before operation!
* Clients can end up with expired data in cache
*/
class RaceCondition extends UseCase {
const KEYNAME = 'racecondition';
public function execute() {
$logger = new OutputLogger();
$cache = new VerboseCache($this->getMemcache(), $logger);
$logger->log('START');
$key = $cache->get(self::KEYNAME);
/** some code **/
if ($this->isUpdateRequest()) {
$cache->delete(self::KEYNAME);
$this->updateOperation();
$logger->log('DONE');
}
}
private function isUpdateRequest() {
return true;
}
private function updateOperation() {
/** DB Operation can take a while **/
sleep(1);
}
}
$usecase = new RaceCondition();
$usecase->execute();
|
C | UTF-8 | 1,392 | 2.796875 | 3 | [] | no_license | #include "minimization.h"
/* f: objective function, df: gradient, H: Hessian matrix H*/
void newton(
double f(gsl_vector* x, gsl_vector* df, gsl_matrix* H),
gsl_vector* x)
{
double fx, innerp; // storage
double eps = 1e-3; // error
double l = -0.2; // lambda
double a = 0.0001; // alpha
size_t n = x->size;// size
int count = 0; // safety
// allocate memory
gsl_matrix* H = gsl_matrix_calloc(n,n);
gsl_vector* df = gsl_vector_calloc(n);
gsl_vector* dx = gsl_vector_calloc(n);
gsl_vector* x_temp = gsl_vector_calloc(n);
fx = f(x, df, H); // Setting H(x), df(x) and f(x)
while(count < 30){
count++;
QR_solve(H, dx, df); // Solving H(x) ∆x = df(x) for ∆x
// backtracking to find lambda
l = -2;
gsl_blas_ddot(dx, df, &innerp); // saving ∆xT*df(x)
while (1){
l/=2;
gsl_vector_memcpy(x_temp, x); // "remember" the value of x
gsl_blas_daxpy(l, dx, x_temp); // x_temp = l*∆x + x_temp
if(f(x_temp, df, H) < fx + a*l*innerp || l < 0.02){break;}
}
gsl_blas_daxpy(l, dx, x); // x = l*∆x + x
// convergence criteria
if(gsl_blas_dnrm2(df) < eps){
printf("Converged after %d iterations.\n", count);
vector_print(x, "x");
break;
}
// safety
if(count==99){printf("count = %d\n", count);}
}
// free allocated space
gsl_matrix_free(H);
gsl_vector_free(df);
gsl_vector_free(dx);
gsl_vector_free(x_temp);
}
|
Python | UTF-8 | 914 | 2.546875 | 3 | [] | no_license | from motion_detection import motion_detection
#This the the init part of the app, the parameter will be used follows:
#gs_window : indicate the size of the Gaussian filter window, recmd : 25 for a 800*600 frame
#gs_sig : the sigma value for the Gaussian filter , no need to very large or small, default:3
#diff_thresh : the threshold for the difference of the mask , if you have a high resolution and quality(I mean stable,
#less noisy) camera, you could set it low, like 10-30, but your camera quality low as my test cam, please tune up
#default value: 100
#min_area : the min area the motion detector could detect, usually to voild the light etc, tune it up to at least 1500
#default :1500
#mod : 0 is off for the alarm by sms system, 1 is on.
gs_window = 25
gs_sig = 3
diff_thresh = 100
min_area = 1500
mod = 0
motion_detection(gs_window,gs_sig,diff_thresh,min_area,mod)
|
Java | UTF-8 | 2,617 | 2.484375 | 2 | [] | no_license | package com.baidu.pass.biometrics.base.utils;
import android.text.TextUtils;
import com.baidu.pass.biometrics.base.debug.Log;
import java.io.File;
import java.io.IOException;
public class PassBioFileUtils {
public static final String TAG = "PassBioFileUtils";
public static boolean checkAndCreadFile(File file) throws IOException {
if (file.exists()) {
return true;
}
file.getParentFile().mkdirs();
return file.createNewFile();
}
public static boolean deleteFile(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
if (!isFileExist(str)) {
return true;
}
return deleteFile(new File(str));
}
public static boolean isFileExist(String str) {
if (str == null) {
return false;
}
return new File(str).exists();
}
public static boolean write(File file, byte[] bArr) throws IOException {
return write(file, bArr, true);
}
/* JADX WARNING: Removed duplicated region for block: B:17:0x0029 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public static boolean write(java.io.File r3, byte[] r4, boolean r5) throws java.io.IOException {
/*
r0 = 0
r1 = 0
boolean r2 = r3.exists() // Catch:{ all -> 0x0027 }
if (r2 != 0) goto L_0x0012
java.io.File r2 = r3.getParentFile() // Catch:{ all -> 0x0027 }
r2.mkdirs() // Catch:{ all -> 0x0027 }
r3.createNewFile() // Catch:{ all -> 0x0027 }
L_0x0012:
boolean r2 = r3.canWrite() // Catch:{ all -> 0x0027 }
if (r2 != 0) goto L_0x0019
return r0
L_0x0019:
java.io.FileOutputStream r2 = new java.io.FileOutputStream // Catch:{ all -> 0x0027 }
r2.<init>(r3, r5) // Catch:{ all -> 0x0027 }
r2.write(r4) // Catch:{ all -> 0x0026 }
r2.close()
r3 = 1
return r3
L_0x0026:
r1 = r2
L_0x0027:
if (r1 == 0) goto L_0x002c
r1.close()
L_0x002c:
return r0
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.pass.biometrics.base.utils.PassBioFileUtils.write(java.io.File, byte[], boolean):boolean");
}
public static boolean deleteFile(File file) {
try {
return file.delete();
} catch (Exception e2) {
Log.e(e2);
return false;
}
}
}
|
Python | UTF-8 | 6,137 | 3.109375 | 3 | [] | no_license | import os
import re
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple
import pytest
CLINGO_OUTPUT_DIR = Path(__file__).parents[1] / "output"
# parse terms from atoms
term_re = re.compile(r"\(.+\)")
ix_re = re.compile(r"\sd+$")
edge_re = re.compile(r"(?:edge\()(\d+)(?:,)(\d+)")
class SearchResult:
def __init__(self, ix: int, atoms: List[str]):
self.result_number = ix
self.atoms = atoms
def __str__(self):
return f"SearchResult {self.result_number}"
@property
def atoms_count(self) -> int:
""" Returns a count of all the atoms (predicates). """
return len(self.atoms)
@property
def predicate_count_total(self) -> int:
""" Returns a count of different predicates. """
return len(set(self.atoms))
def _get_predicate_names(self):
""" Returns only the *names* of predicates (no terms). """
predicate_names = []
for atom in self.atoms:
predicate_names.append(atom.split("(")[0])
return predicate_names
@property
def predicate_counts(self) -> Dict[str, int]:
""" Returns a mapping from predicates to counts. """
predicate_counts = defaultdict(int)
for pred in self._get_predicate_names():
predicate_counts[pred] += 1
return predicate_counts
@property
def edges(self) -> List[Tuple[int]]:
""" Returns a list of all the edges, represented as tuples. """
edges = []
for atom in self.atoms:
match = edge_re.match(atom)
if match and len(match.groups()) == 2:
edges.append((int(match.groups()[0]), int(match.groups()[1])))
return edges
@property
def vertices(self) -> List[int]:
""" Returns a list of all of the vertices. """
vertices = []
for edge in self.edges:
vertices.append(edge[0])
vertices.append(edge[1])
return vertices
def _parse_search_result(sr, ix):
# split line into atoms
atoms = sr.split()
parse = SearchResult(ix, atoms)
return parse
@pytest.fixture
def clingo_output():
search_results = []
with open(os.path.join(CLINGO_OUTPUT_DIR, "output_5")) as f:
lines = f.readlines()
for i, line in enumerate(lines):
if line.startswith("Answer:"):
# 8 characters = "Answer: ", grab the result set index (ix)
ix = int(line[8:])
sr = _parse_search_result(lines[i + 1], ix)
print(f"SearchResult {sr.result_number} with edges {sr.edges}")
search_results.append(sr)
return search_results
# for a 3x3 grid
ACCEPTABLE_EDGES = [
(0, 1),
(0, 3),
(1, 0),
(1, 2),
(1, 4),
(2, 1),
(2, 5),
(3, 0),
(3, 4),
(3, 6),
(4, 3),
(4, 1),
(4, 5),
(4, 7),
(5, 4),
(5, 2),
(5, 8),
(6, 3),
(6, 7),
(7, 6),
(7, 4),
(7, 8),
(8, 7),
(8, 5),
]
def test_edge_correctness(clingo_output):
"""
A search result is incorrect if it contains edges
not from the set of incorrect edges, or if it contains
duplicate edges, or if it contains symmetrical edges.
No vertex should be included more than once, and the
result should have a single edge from the lowest-
numbered edge, and a single edge to the highest-numbered
edge.
"""
for sr in clingo_output:
for edge in sr.edges:
# test acceptable edges
assert (
edge in ACCEPTABLE_EDGES
), f"edge {edge} not in ACCEPTABLE_EDGES. Failing result was {sr}."
# test no two edges starting at the same vertex
assert (
len(list(filter(lambda e: e[0] == edge[0], sr.edges))) == 1
), f"SearchResult {sr} contains multiple edges starting at {edge[0]}!"
# test no two edges ending at the same vertex
assert (
len(list(filter(lambda e: e[1] == edge[1], sr.edges))) == 1
), f"SearchResult {sr} contains multiple edges terminating at {edge[1]}!"
# test no duplicate edges
assert len(sr.edges) == len(
set(sr.edges)
), f"SearchResult {sr} contains duplicate edges."
# test no symmetrical edges
sorted_edges = list(map(lambda tup: tuple(sorted(tup)), sr.edges))
assert len(sorted_edges) == len(
set(sorted_edges)
), f"SearchResult {sr} contains symmetrical edges."
# test there is a single valid edge from vertex 0
# there are only 2 possible valid edges from vertex 0:
# (0,1) and (0,3).
assert (0, 1) in sr.edges or (
0,
3,
) in sr.edges, f"SearchResult {sr} missing an edge from vertex 0."
assert not (
(0, 1) in sr.edges and (0, 3) in sr.edges
), f"SearchResult {sr} contains 2 edges from vertex 0!"
# test there is a single edge which terminates at
# the highest-numbered vertex in the set
greatest_vertex = max(sr.vertices)
assert (
len(list(filter(lambda e: e[1] == greatest_vertex, sr.edges))) == 1
), f"SearchResult {sr} has no edge terminating at {greatest_vertex}."
def test_edge_completeness():
pass
def generate_test_edges(n):
""" Generates a set of test edges of size n x n. """
edges = []
vertices = list(range(0, n * n))
print(f"Vertices: {vertices}")
for v in vertices:
start = v
# symmetrical incremental edges
if start + 1 in vertices and (start + 1) % n != 0:
edges.append((start, start + 1))
if start - 1 in vertices and start % n != 0:
edges.append((start, start - 1))
# edges moving 'up' or 'down' the grid
if start + n in vertices:
edges.append((start, start + n))
if start - n in vertices:
edges.append((start, start - n))
# remove dups
edges = list(set(edges))
return edges
|
Java | UTF-8 | 879 | 2.046875 | 2 | [] | no_license | package com.nokia.ices.apps.fusion.system.repository.types;
public enum SystemOperationLogOpType {
/**
* “Login”(登录应用资源)
* “Logout” (登出应用资源)
* “AddPrivilege”(用户添加和权限相关的任何信息,包括添加用户、用户组、权限、角色等)
* “DelPrivilege”(用户删除和权限相关的任何信息,包括添加用户、用户组、权限、角色等)
* “UpdatePrivilege”(用户更新和权限相关的任何信息,包括添加用户、用户组、权限、角色等)
* “View”(业务数据查阅)
* “Add”(业务数据增加)
* “Update”(业务数据更新)
* “Del”(业务数据删除)
* “Other”(其它类别)
*/
Login,Logout,AddPrivilege,DelPrivilege,UpdatePrivilege,View,Add,Update,Del,Other
}
|
Swift | UTF-8 | 1,179 | 3.5625 | 4 | [] | no_license | //
// PetProperty.swift
// VirtualPet
//
// Created by Liuqing Du on 07/05/2015.
// Copyright (c) 2015 JuneDesign. All rights reserved.
//
import Foundation
enum Sex: Int {
case Male = 0, Female
}
class PetProperty {
private let name: String
private let sex: Sex
private var birthday: NSDate
init(name: String) {
self.name = name
self.sex = Sex(rawValue: Int(arc4random()%2))!
self.birthday = NSDate()
}
init(name: String, sex: Int, birthday: NSDate) {
self.name = name
self.sex = Sex(rawValue: sex)!
self.birthday = birthday
}
func getName() -> String {
return name
}
func getSex() -> String {
switch sex {
case .Male:
return "Male"
case .Female:
return "Female"
default:
return "Unknown"
}
}
func getBirthday() -> NSDate {
return birthday
}
func getBirthdayString() -> String {
var df = NSDateFormatter()
df.dateFormat = "dd MMMM"
return df.stringFromDate(birthday)
}
}
|
Java | UTF-8 | 2,511 | 3.21875 | 3 | [
"MIT"
] | permissive | /*
* 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 tanjacksoncalendarculminating;
import java.util.ArrayList;
/**
*
* @author Jackson
*/
/**
*
*/
abstract class Entries {
/**
* The type of entry denoted by 1 for events or 2 for reminders
*/
int entryType;
/**
* The type of entry
*/
String typeName;
/**
* Name of the entry
*/
String name;
/**
* Details of the entry
*/
String details;
/**
* Start date of the entry
*/
int date;
/**
* Creates an object called entries that include all of the fields listed
* above
*
* @param entryType the type of entry reminder or event as an integer 1 or 2
* @param typeName the type of entry in string
* @param name the name of the entry
* @param details the details of the entry
* @param date the date of the entry
*/
public Entries(int entryType, String typeName, String name, String details, int date) {
this.entryType = entryType;
this.typeName = typeName;
this.name = name;
this.details = details;
this.date = date;
}
/**
* returns the start date of an entry
*
* @return the start date of the entry as an int
*/
public int getDate() {
return date;
}
/**
* returns the entry type as an int
*
* @return entry type as a 1 or a 2
*/
public int getEntryType() {
return entryType;
}
/**
* returns the name of the entry
*
* @return entry name as a string
*/
public String getName() {
return name;
}
/**
* returns the details of the entry
*
* @return String details of an
*/
public String getDetails() {
return details;
}
/**
* returns the title of event or reminder
*
* @return the type of entry name as a string
*/
public String getTypeName() {
return typeName;
}
/**
* Prints the entry in a user friendly way
*/
public abstract void print();
/**
* Prints to the txt file
*
* @return a formatted String to print in the txt file
*/
public abstract String printToTxt();
}
|
JavaScript | UTF-8 | 670 | 3.75 | 4 | [] | no_license | // Funcion Anonima Auto Invocable (cuerpo)
(function(){
console.log('Soy una funcion anonima');
})();
(function(nombre){
console.log('Yo soy una funcion anonima que recibe un parametro: '+ nombre);
})('isaac');
// Funcion Auto Invocable
(function Saludo(){
console.log('soy una funcion auto invocada');
})();
(function Saludos(nombre){
console.log('soy una funcion auto invocada con parametro '+ nombre);
})('prros');
// Funciones Flecha Auto Invocables.
(saludo=()=>{
console.log('soy una funcion flecha auto invocada');
})();
(saludos=(nombre)=>{
console.log('soy una funcion flecha auto invocada con parametro' + nombre);
})('hugo'); |
C | UTF-8 | 623 | 3.703125 | 4 | [] | no_license | //WAP to write getfloat() function which receives numeric string convert it into corresponding float and return the float
#include<stdio.h>
float getfloat(); //declaration
//driver function
int main(void){
float num;
num = getfloat();
printf("The Number you entered:\t%f\n",num);
return 0;
}
float getfloat(){
float a = 0;
int neg = 0,int count = 0;
char ch;
do{
ch = getchar();
if(ch == '\n')
continue;
else if(ch == 45)
neg = 1;
else if(ch < 48 || ch > 57){
return EOF;
}
else{
a = a*10 + (ch - 48);
}
}
while(ch != '\n');
if(neg == 1){
a *= -1;
}
return a;
} |
Java | UTF-8 | 3,039 | 2.21875 | 2 | [] | no_license | package com.example.joshuamugisha.udacitybakingapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.joshuamugisha.udacitybakingapp.R;
import com.example.joshuamugisha.udacitybakingapp.activity.DetailActivity;
import com.example.joshuamugisha.udacitybakingapp.model.Result;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class ResultAdapter extends RecyclerView.Adapter<ResultAdapter.MyViewHolder> {
private Context mContext;
private List<Result> recipeList;
private Gson gson;
private SharedPreferences sharedPreferences;
public ResultAdapter(Context mContext, List<Result> recipeList) {
this.recipeList = recipeList;
this.mContext = mContext;
sharedPreferences = mContext.getSharedPreferences("SHARED_PREFERENCES",
Context.MODE_PRIVATE);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recipe_card, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Result recipe = recipeList.get(position);
holder.name.setText(recipe.getName());
}
@Override
public int getItemCount(){
return recipeList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name;
CardView recipeCard;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.recipeName);
recipeCard = (CardView) view.findViewById(R.id.recipeCard);
view.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Result clickedDataItem = recipeList.get(pos);
gson = new Gson();
sharedPreferences.edit().putString("WIDGET_RESULT", gson.toJson(clickedDataItem)).apply();
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra("Recipe", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
|
Java | UTF-8 | 583 | 1.90625 | 2 | [] | no_license | package com.antonromanov.arnote.model.wish;
import lombok.Builder;
@Builder
public class SummEntity {
private Integer all;
private Integer priority;
private Integer allPeriodForImplementation;
private Integer priorityPeriodForImplementation;
private Integer lastSalary;
private int averageImplementationTime;
private int implemetedSummAllTime; // На сколько реализовали всего
private int implemetedSummMonth; // На сколько реализовали в этом месяце
private int littleWishes; // маленькие хотелки
}
|
C# | UTF-8 | 2,689 | 2.65625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace imageanalyzer.dotnet.model.operations
{
public interface IObserverOperationCompare
: IObserverOperation
{
void HandleCompareComplete(double percent, string filename);
}
public interface IObservableOperationCompare
{
void AddObserver(IObserverOperationCompare aHandler);
void RemoveObserver(IObserverOperationCompare aHandler);
}
public interface INotifierCompareComplete
{
void NotifyCompareComplete(double percent, string filename);
}
public class CObservableOperationCompare
: IObservableOperationCompare,
INotifierStart,
INotifierProgress,
INotifierComplete,
INotifierCompareComplete
{
public CObservableOperationCompare()
{
m_Handlers = new List<IObserverOperationCompare>();
}
public void AddObserver(IObserverOperationCompare aHandler)
{
m_Handlers.Add(aHandler);
}
public void RemoveObserver(IObserverOperationCompare aHandler)
{
m_Handlers.Remove(aHandler);
}
public void NotifyStart()
{
foreach (var lObserver in m_Handlers)
lObserver.HandleStart();
}
public void NotifyChangeProgress(double percents)
{
foreach (var lObserver in m_Handlers)
lObserver.HandleChangeProgress(percents);
}
public void NotifyComplete()
{
foreach (var lObserver in m_Handlers)
lObserver.HandleComplete();
}
public void NotifyCompareComplete(double percent, string filename)
{
foreach (var lObserver in m_Handlers)
lObserver.HandleCompareComplete(percent, filename);
}
private List<IObserverOperationCompare> m_Handlers;
}
public class CBaseObservableOperationCompare
: IObservableOperationCompare
{
public CBaseObservableOperationCompare()
{
m_Observable = new CObservableOperationCompare();
}
public void AddObserver(IObserverOperationCompare aHandler)
{
m_Observable.AddObserver(aHandler);
}
public void RemoveObserver(IObserverOperationCompare aHandler)
{
m_Observable.RemoveObserver(aHandler);
}
protected CObservableOperationCompare GetObserver()
{
return m_Observable;
}
private CObservableOperationCompare m_Observable;
}
} |
Markdown | UTF-8 | 5,099 | 2.65625 | 3 | [] | no_license | ---
description: "Recipe of Ultimate Buttermilk Fried Chicken"
title: "Recipe of Ultimate Buttermilk Fried Chicken"
slug: 796-recipe-of-ultimate-buttermilk-fried-chicken
date: 2021-07-27T04:23:24.071Z
image: https://img-global.cpcdn.com/recipes/36fe56096b909446/680x482cq70/buttermilk-fried-chicken-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/36fe56096b909446/680x482cq70/buttermilk-fried-chicken-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/36fe56096b909446/680x482cq70/buttermilk-fried-chicken-recipe-main-photo.jpg
author: Rosa Morgan
ratingvalue: 4.1
reviewcount: 30155
recipeingredient:
- "2-3 pounds chicken drumsticks"
- "2 cups all purpose flour"
- "2-4 tbs garlic powder"
- "to taste Salt pepper"
- "3 cups buttermilk"
- " Oil for frying"
- "1 tbs baking powder"
- "2 tbs minced garlic"
- "2 spoonfuls butter"
recipeinstructions:
- "Rinse chicken. Pour buttermilk in bowl. Add garlic powder, minced garlic, salt & pepper, mix. Cover & place in fridge. Let marinade for 18-24hrs."
- "Turn oil onto 6 or 7. When oil starts to get hot, place butter in oil, it should bubble & make sound. Put flower, baking powder, garlic powder & pepper in mixing bowl, mix."
- "Take chicken out of buttermilk, and place in flour. Place in oil until brown, flip."
- "Place on paper towel to soak up oil. Cook chicken in oven at 350 degrees for about 40 minutes or to your liking, flipping occasionally."
categories:
- Recipe
tags:
- buttermilk
- fried
- chicken
katakunci: buttermilk fried chicken
nutrition: 137 calories
recipecuisine: American
preptime: "PT12M"
cooktime: "PT43M"
recipeyield: "4"
recipecategory: Dinner
---

Hello everybody, hope you are having an amazing day today. Today, I will show you a way to prepare a distinctive dish, buttermilk fried chicken. One of my favorites food recipes. For mine, I am going to make it a bit tasty. This is gonna smell and look delicious.
Buttermilk Fried Chicken is one of the most well liked of current trending foods on earth. It's enjoyed by millions daily. It's simple, it is fast, it tastes yummy. They are nice and they look fantastic. Buttermilk Fried Chicken is something that I've loved my whole life.
Buttermilk Chicken Marinade - The Secret to Great Fried Chicken! Click the link below if you want to donate to PBJ. Chicken is so moist and crispy. After the buttermilk soak, dredge the chicken pieces in seasoned flour, and fry them in hot oil until This fried chicken receipe is absoultly fantastic,if you take your time get all your ingredients together.
To get started with this recipe, we have to first prepare a few components. You can cook buttermilk fried chicken using 9 ingredients and 4 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Buttermilk Fried Chicken:
1. Take 2-3 pounds chicken drumsticks
1. Take 2 cups all purpose flour
1. Make ready 2-4 tbs garlic powder
1. Prepare to taste Salt & pepper
1. Make ready 3 cups buttermilk
1. Make ready Oil for frying
1. Take 1 tbs baking powder
1. Get 2 tbs minced garlic
1. Make ready 2 spoonfuls butter
How does buttermilk fried chicken taste? Make this recipe and you'll be enjoying succulent, juicy pieces of chicken, coated in a warm, crispy and slightly spicy batter. We aim to create a space that elevates the perception of. How to make buttermilk fried chicken tenders.
<!--inarticleads2-->
##### Instructions to make Buttermilk Fried Chicken:
1. Rinse chicken. Pour buttermilk in bowl. Add garlic powder, minced garlic, salt & pepper, mix. Cover & place in fridge. Let marinade for 18-24hrs.
<img src="https://img-global.cpcdn.com/steps/e7fe6b9e9f6bef93/160x128cq70/buttermilk-fried-chicken-recipe-step-1-photo.jpg" alt="Buttermilk Fried Chicken">1. Turn oil onto 6 or 7. When oil starts to get hot, place butter in oil, it should bubble & make sound. Put flower, baking powder, garlic powder & pepper in mixing bowl, mix.
1. Take chicken out of buttermilk, and place in flour. Place in oil until brown, flip.
1. Place on paper towel to soak up oil. Cook chicken in oven at 350 degrees for about 40 minutes or to your liking, flipping occasionally.
We aim to create a space that elevates the perception of. How to make buttermilk fried chicken tenders. Begin by combining the chicken tenderloins with a mixture of buttermilk, paprika, garlic powder, cayenne pepper, and salt. This is the BEST EVER Buttermilk Fried Chicken! Super juicy and tender on the inside yet crispy on the outside and bursting with flavor!
So that's going to wrap it up for this special food buttermilk fried chicken recipe. Thank you very much for reading. I'm sure you will make this at home. There is gonna be more interesting food in home recipes coming up. Don't forget to save this page on your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
|
C | UTF-8 | 1,517 | 3.046875 | 3 | [
"MIT"
] | permissive | /*
** realloc.c for realloc in /home/aubanel_m/tek2/PSU_2016_malloc/
**
** Made by Aubanel Maxime
** Login <aubane_m@epitech.eu>
**
** Started on Sun Feb 12 21:16:18 2017 Aubanel Maxime
** Last update Sun Feb 12 22:41:35 2017 Aubanel Maxime
*/
#include "malloc.h"
void *realloc(void *ptr, size_t size)
{
t_list *new;
size_t alignSize;
if (!ptr)
return (malloc(size));
if (detect_ptr_pos(ptr) == true)
{
alignSize = align_size(size);
new = extract_block(ptr);
if (new->size < alignSize)
return (realloc_extend(new, ptr, alignSize));
else
{
if ((new->size - alignSize) > sizeof(t_list))
split_memory(new, alignSize);
}
}
return (ptr);
}
void my_memcpy(t_list *dest, t_list *src)
{
int *s;
size_t i;
int *d;
i = 0;
d = (int*)dest->data;
s = (int*)src->data;
while (i < (dest->size / 4) && i < (src->size / 4))
{
d[i] = s[i];
i++;
}
}
void *realloc_extend(t_list *list, void *ptr, size_t size)
{
t_list *tmp;
void *new_ptr;
if ((is_mergeable_next(list) == true) &&
(list->size + SIZE_HEADER + list->next->size) >= size)
{
free_merge(list);
if ((list->size - size) > sizeof(t_list))
split_memory(list, size);
}
else
{
if ((new_ptr = malloc(size)) == NULL)
return (NULL);
tmp = extract_block(new_ptr);
my_memcpy(tmp, list);
free(ptr);
return (new_ptr);
}
return (ptr);
}
|
PHP | UTF-8 | 2,168 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Event extends REST_Controller{
public function __construct(){
parent::__construct();
$this->load->model('event_model');
}
public function getSports_get(){
$data = $this->event_model->getSports();
$return = array();
foreach ($data as $sport) {
$return[] = $sport->label;
}
if(!empty($return)){
$this->response(array('result' => $return), 200);
}else{
$this->response(array('result' => 'No sports in database'));
}
}
public function create_post(){
$title = $this->post('title');
$description = $this->post('description');
$date = $this->post('date');
$latitude = $this->post('latitude');
$longitude = $this->post('longitude');
$sport = $this->post('sport');
$numberPeople = $this->post('numberPeople');
// TODO : ajouter l'auteur de l'événement dans la table join ???
$idUser = $this->post('idUser');
if($title && $description && $date && $latitude && $longitude && $sport && $idUser && $numberPeople){
$data = $this->event_model->create($title, $description, $date, $latitude, $longitude, $sport, $numberPeople, $idUser);
$this->response($data, 200);
}else{
$this->response(NULL, 400);
}
}
public function join_post(){
$idEvent = $this->post('idEvent');
$idUser = $this->post('idUser');
if($idEvent && $idUser){
$data = $this->event_model->joinEvent($idEvent, $idUser);
$this->response($data, 200);
}else{
$this->response(NULL, 400);
}
}
public function getEventsNearFrom_get(){
$latitude = $this->get('latitude');
$longitude = $this->get('longitude');
$distance = $this->get('distance');
if($latitude && $longitude && $distance){
$data = $this->event_model->getEventsNearFrom($latitude, $longitude, $distance);
$this->response($data, 200);
}else{
$this->response(NULL, 400);
}
}
public function getEventsForUser_get(){
$idUser = $this->get('idUser');
if($idUser){
$data = $this->event_model->getEventsForUser($idUser);
$this->response($data, 200);
}else{
$this->response(NULL, 400);
}
}
} |
Python | UTF-8 | 456 | 3.4375 | 3 | [] | no_license | # misc.py
import datetime
import os
def get_date():
date = datetime.datetime.now()
return date.strftime("%d") + date.strftime("%b") + date.strftime("%Y")
def rename_folder_by_size(folder_path, n):
new_name = folder_path + '_' + str(n)
os.rename(folder_path, new_name)
print('Rename the folder as ', new_name)
def get_n_files(folder_path):
for (dirpath, dirnames, filenames) in os.walk(folder_path):
return len(filenames) |
Python | UTF-8 | 428 | 3.0625 | 3 | [] | no_license | class MeetingNode:
def meetingNode(self, pHead):
if not pHead or not pHead.next:
return None
fast = pHead
slow = pHead
while fast and slow:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
slow = pHead
while slow != fast:
slow = slow.next
fast = fast.next
return slow |
C# | UTF-8 | 2,066 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using MyWeatherApplication.VO;
namespace MyWeatherApplication.UI
{
/// <summary>
/// Current Fragment for displaying hourly weather
/// </summary>
public class HourlyFragment : Fragment
{
private View view = null;
private ListView hourlyWeatherList = null;
#region Overriden Methods
/// <summary>
/// Method to initialize all the resources
/// </summary>
/// <param name="savedInstanceState"></param>
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
/// <summary>
/// Method to intialize all the elements for view creation
/// </summary>
/// <param name="inflater"></param>
/// <param name="container"></param>
/// <param name="savedInstanceState"></param>
/// <returns></returns>
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
try
{
view = inflater.Inflate(Resource.Layout.HourlyWeather, container, false);
hourlyWeatherList = view.FindViewById<ListView>(Resource.Id.lv_hourly_weather);
HourlyFragmentAdapter hourlyAdapter = new HourlyFragmentAdapter(Activity, Resource.Layout.WeatherListItem, WeatherReport.GetHourlyInstance());
hourlyWeatherList.Adapter = hourlyAdapter;
return view;
}
catch (Exception ex)
{
Toast.MakeText(Activity, GlobalConstants.ErrorMessage + ex.ToString(), ToastLength.Short);
}
return view;
}
#endregion
}
} |
C++ | UTF-8 | 5,346 | 3.328125 | 3 | [] | no_license | #ifndef RBBST_H
#define RBBST_H
#include <iostream>
#include <exception>
#include <cstdlib>
#include <algorithm>
#include <memory>
#include "bst.h"
struct KeyError { };
/**
* A special kind of node for an AVL tree, which adds the balance as a data member, plus
* other additional helper functions. You do NOT need to implement any functionality or
* add additional data members or helper functions.
*/
template <typename Key, typename Value>
class AVLNode : public Node<Key, Value>
{
public:
// Constructor/destructor.
AVLNode(const Key& key, const Value& value, std::shared_ptr<AVLNode<Key, Value>> parent);
virtual ~AVLNode();
// Getter/setter for the node's height.
char getBalance () const;
void setBalance (char balance);
void updateBalance(char diff);
std::shared_ptr<AVLNode<Key, Value>> getParent_AVL() const;
std::shared_ptr<AVLNode<Key, Value>> getLeft_AVL() const;
std::shared_ptr<AVLNode<Key, Value>> getRight_AVL() const;
protected:
// to store the balance of a given node
char balance_;
};
// -------------------------------------------------
// Begin implementations for the AVLNode class.
// -------------------------------------------------
// An explicit constructor to initialize the elements by calling the base class constructor and setting
// the color to red since every new node will be red when it is first inserted.
template<class Key, class Value>
AVLNode<Key, Value>::AVLNode(const Key& key, const Value& value, std::shared_ptr<AVLNode<Key, Value>> parent) :
Node<Key, Value>(key, value, parent), balance_(0)
{
}
// A destructor which does nothing.
template<class Key, class Value>
AVLNode<Key, Value>::~AVLNode()
{
}
// A getter for the balance of a AVLNode.
template<class Key, class Value>
char AVLNode<Key, Value>::getBalance() const
{
return balance_;
}
// A setter for the balance of a AVLNode.
template<class Key, class Value>
void AVLNode<Key, Value>::setBalance(char balance)
{
balance_ = balance;
}
// Adds diff to the balance of a AVLNode.
template<class Key, class Value>
void AVLNode<Key, Value>::updateBalance(char diff)
{
balance_ += diff;
}
// A separate getParent_AVL function other than the base class function due to covariant return types
template<class Key, class Value>
std::shared_ptr<AVLNode<Key, Value>> AVLNode<Key, Value>::getParent_AVL() const
{
return std::static_pointer_cast< AVLNode<Key, Value> >(this->parent_);
}
// Similar getLeft_AVL function
template<class Key, class Value>
std::shared_ptr<AVLNode<Key, Value>> AVLNode<Key, Value>::getLeft_AVL() const
{
return std::static_pointer_cast< AVLNode<Key, Value> >(this->left_);
}
// Similar getRight_AVL function
template<class Key, class Value>
std::shared_ptr<AVLNode<Key, Value>> AVLNode<Key, Value>::getRight_AVL() const
{
return std::static_pointer_cast< AVLNode<Key, Value> >(this->right_);
}
// -----------------------------------------------
// End implementations for the AVLNode class.
// -----------------------------------------------
template <class Key, class Value>
class AVLTree : public BinarySearchTree<Key, Value>
{
public:
void rotateLeft(std::shared_ptr<AVLNode<Key, Value>> p, std::shared_ptr<AVLNode<Key, Value>> n); //TODO
void rotateRight(std::shared_ptr<AVLNode<Key, Value>> p, std::shared_ptr<AVLNode<Key, Value>> n); //TODO
// Remember, AVL is a self-balancing BST
// Resultant tree after the insert and remove function should be a balanced tree
// Make appropriate calls to rotateLeft(...) and rotateRight(...)
// in insert and remove for balancing the height of the AVLTree
virtual void insert (const std::pair<const Key, Value> &new_item); // TODO
virtual void remove(const Key& key); // TODO
protected:
// Helper function already provided to you.
virtual void nodeSwap( std::shared_ptr<AVLNode<Key,Value>> n1, std::shared_ptr<AVLNode<Key,Value>> n2);
// Add helper functions here
// Consider adding functions like getBalance(...) given a key in the Tree
// setBalance(...) given a key to a node and balance value, etc
// You may implement a printRootAVL(...)
// using the printRoot() function from the BST implementation
};
// Pre condition: p is the parent of n
// Post condition: p is the left child of n
template<class Key, class Value>
void AVLTree<Key, Value>::rotateLeft (std::shared_ptr<AVLNode<Key, Value>> p, std::shared_ptr<AVLNode<Key, Value>> n)
{
// TODO
}
// Pre condition: p is the parent of n
// Post condition: p is the right child of n
template<class Key, class Value>
void AVLTree<Key, Value>::rotateRight (std::shared_ptr<AVLNode<Key, Value>> p, std::shared_ptr<AVLNode<Key, Value>> n)
{
// TODO
}
template<class Key, class Value>
void AVLTree<Key, Value>::insert (const std::pair<const Key, Value> &new_item)
{
// TODO
}
template<class Key, class Value>
void AVLTree<Key, Value>:: remove(const Key& key) {
// TODO
}
// Function already completed for you
template<class Key, class Value>
void AVLTree<Key, Value>::nodeSwap( std::shared_ptr<AVLNode<Key,Value>> n1, std::shared_ptr<AVLNode<Key,Value>> n2)
{
BinarySearchTree<Key, Value>::nodeSwap(n1, n2);
char tempB = n1->getBalance();
n1->setBalance(n2->getBalance());
n2->setBalance(tempB);
}
#endif
|
C# | UTF-8 | 15,156 | 2.796875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Linq;
namespace SquareTime {
class CityGrid {
private Tile[,] grid;
private float tileSize; //Todo change this
public Vector2 Size { get; private set; }
float tideLevel = 0.0f;
float timer = 0.0f;
public CityGrid(int x, int y, float tileSize) {
this.Size = new Vector2(x, y);
this.grid = new Tile[x, y];
this.tileSize = tileSize;
generateMap(4);
}
struct Diamond {
public Point top, left, right, bottom;
public Diamond(Point top, Point left, Point right, Point bottom) {
this.top = top;
this.left = left;
this.right = right;
this.bottom = bottom;
}
}
struct Square {
public Point tleft, tright, bleft, bright;
public Square(Point tleft, Point tright, Point bright, Point bleft) {
this.tleft = tleft;
this.tright = tright;
this.bright = bright;
this.bleft = bleft;
}
}
public void generateMap(float smoothness, List<List<double>> heightMap, float maxHeight = 1.0f) {
Random r = new Random();
List<Square> sq = new List<Square>();
sq.Add(new Square(new Point(0, 0), new Point((int)Size.X - 1, 0), new Point((int)Size.X - 1, (int)Size.X - 1), new Point(0, (int)Size.X - 1)));
float iter = 1;
while ((sq[0].bright.X - sq[0].bleft.X) > 1) {
List<Diamond> dias = new List<Diamond>();
foreach (Square s in sq) { //diamond step
//sort out the heightmap
Point mid = new Point((int)(((float)s.tleft.X + (float)s.tright.X) / 2f), (int)(((float)s.bright.Y + (float)s.tright.Y) / 2f));
double tLeft = heightMap[s.tleft.X][s.tleft.Y];
double tRight = heightMap[s.tright.X][s.tright.Y];
double bLeft = heightMap[s.bleft.X][s.bleft.Y];
double bRight = heightMap[s.bright.X][s.bright.Y];
double newVal = (tLeft + tRight + bLeft + bRight) / 4 + (randDouble(-maxHeight, maxHeight, r)) / (smoothness * iter);
heightMap[(int)mid.X][(int)mid.Y] = newVal;
dias.AddRange(getDiamond(s));
}
foreach (Diamond d in dias) { //square step
//FIXME
int divisor = 0;//COULD GO WRONG
double summation = 0;
if (inRange(d.top.X, heightMap.Count) && inRange(d.top.Y, heightMap.Count)) {
divisor++;
summation += heightMap[d.top.X][d.top.Y];
}
if (inRange(d.left.X, heightMap.Count) && inRange(d.left.Y, heightMap.Count)) {
divisor++;
summation += heightMap[d.left.X][d.left.Y];
}
if (inRange(d.right.X, heightMap.Count) && inRange(d.right.Y, heightMap.Count)) {
summation += heightMap[d.right.X][d.right.Y];
divisor++;
}
if (inRange(d.bottom.X, heightMap.Count) && inRange(d.bottom.Y, heightMap.Count)) {
divisor++;
summation += heightMap[d.bottom.X][d.bottom.Y];
}
double newVal = summation / divisor + (randDouble(-maxHeight, maxHeight, r)) / (smoothness * iter);
Point mid = new Point((int)((d.left.X + d.right.X) / 2f), (int)((d.top.Y + d.bottom.Y) / 2f));
heightMap[mid.X][mid.Y] = newVal;
}
//get squares
iter++;
sq = getSquares(sq, (int)iter).ToList();
}
double max = double.MinValue;
double min = double.MaxValue;
foreach (List<double> hlist in heightMap) {
foreach (double height in hlist) {
if (height > max) max = height;
if (height < min) min = height;
}
}
for (int x = 0; x < Size.X; x++) {
for (int y = 0; y < Size.Y; y++) {
grid[x, y] = new Tile(x, y, (heightMap[x][y] - min) / (max - min), this);
}
}
smoothNonDirect();
}
public void generateMap(float smoothness, float maxHeight = 1.0f) {
List<List<double>> heightMap = new List<List<double>>();
//Initalize heightmap
for (int i = 0; i < Size.X; i++) {
heightMap.Add(new List<double>());
for (int j = 0; j < Size.X; j++) {
heightMap[i].Add(0);
}
}
generateMap(smoothness, heightMap, maxHeight);
}
public void smoothNonDirect() {
foreach (Tile tile in grid) {
tile.initalizeNeighbours();
TileType t = tile.Type;
if (tile.Neighbours.Where((x) => x.Type == t).ToList().Count <= 3) {
if (tile.Neighbours.Count <= 3) {
continue;
}
tile.Height = tile.Neighbours.Where((x) => x.Type != t).Average(x => x.Height);
}
}
}
/* WORK IN PROGRESS
public void extendCity(int dir) {//0 for left 1 for up 2 for right 3 for down
List<List<double>> heightmap = new List<List<double>>();
switch (dir) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
}
}*/
public float TypeToHeight(TileType type) {//aproxmation
switch (type) {
case TileType.GRASS:
return 0.6f;
case TileType.SAND:
return 0.59f;
case TileType.WATER:
return 0.5f;
case TileType.OCEAN:
return 0.0f;
case TileType.HILL:
return 0.75f;
case TileType.MOUNTAIN:
return 0.8f;
case TileType.HIGHMOUNTAIN:
return 0.95f;
default:
return 0.0f;
}
}
public TileType heightToType(double height) {
if (height < 0.45f) return TileType.OCEAN;
if (height >= 0.45f && height < 0.55f) return TileType.WATER;
if (height >= 0.55f && height < 0.60f) return TileType.SAND;
if (height >= 0.60f && height < 0.75f) return TileType.GRASS;
if (height >= 0.75f && height < 0.85f) return TileType.HILL;
if (height >= 0.85f && height < 0.95f) return TileType.MOUNTAIN;
if (height >= 0.95f) return TileType.HIGHMOUNTAIN;
return TileType.EMPTY;
}
public Tile getTile(int x, int y) {
if (x < 0 || x >= Size.X || y < 0 || y >= Size.Y) {
return null;
}
return grid[x, y];
}
public Tile getTile(Vector2 v) {
return getTile((int)v.X, (int)v.Y);
}
private bool inRange(int pos, int max) { //come get me oracle
if (pos >= max) return false;
if (pos < 0) return false;
return true;
}
private double randDouble(double min, double max, Random rand) {
return rand.NextDouble() * (max - min) + min;
}
private Square[] getSquares(List<Square> oldSquares, int iter) {
Square[] squares = new Square[(int)Math.Pow(4, iter - 1)];
float length = (oldSquares[0].bright.X - oldSquares[0].bleft.X) / 2;
float tLength = (float)Math.Sqrt(squares.Length);
for (int s = 0; s < squares.Length; s++) {
squares[s] = new Square(new Point((int)(length * (s % tLength)), (int)((int)(s / tLength) * length)),
new Point((int)(length * (s % tLength) + length), (int)((int)(s / tLength) * length)),
new Point((int)(length * (s % tLength) + length), (int)((int)(s / tLength) * length + length)),
new Point((int)(length * (s % tLength)), (int)((int)(s / tLength) * length + length)));
}
return squares;
}
private Diamond[] getDiamond(Square sq) {
Point mid = new Point((int)(((float)sq.tleft.X + (float)sq.tright.X) / 2f), (int)(((float)sq.bright.Y + (float)sq.tright.Y) / 2f));
Diamond[] dias = new Diamond[4];
dias[0] = new Diamond(sq.tleft, new Point(mid.X - (mid.X - sq.bleft.X) * 2, mid.Y), mid, sq.bleft);
dias[1] = new Diamond(new Point(mid.X, mid.Y - 2 * (mid.Y - sq.tleft.Y)), sq.tleft, sq.tright, mid);
dias[2] = new Diamond(sq.tright, mid, new Point(mid.X + (mid.X - sq.bleft.X) * 2, mid.Y), sq.bright);
dias[3] = new Diamond(mid, sq.bleft, sq.bright, new Point(mid.X, mid.Y + 2 * (mid.Y - sq.tleft.Y)));
return dias;
}
public void initalizeMap(TileType typeToInit) {
for (int x = 0; x < Size.X; x++) {
for (int y = 0; y < Size.Y; y++) {
grid[x, y] = new Tile(x, y, TypeToHeight(typeToInit), this);
}
}
}
public Vector2 mapToWorld(Vector2 map) {
return new Vector2(map.X * tileSize, map.Y * tileSize);
}
public Vector2 worldToMap(Vector2 world) {
return new Vector2((int)Math.Floor(world.X / tileSize), (int)Math.Floor(world.Y / tileSize));
}
public void Update(double timeStep) { //in mins
}
public void Draw(SpriteBatch batch, Camera cam) {
//Calculate Drawing bounds
Vector2 minPos = worldToMap(cam.screenToWorld(Vector2.Zero));
Vector2 maxPos = worldToMap(cam.screenToWorld(new Vector2(SquareGame.viewport.Width, SquareGame.viewport.Height)));
for (int x = (int)Math.Max(minPos.X - 1, 0); x < Math.Min(maxPos.X + 1, Size.X); x++) {
for (int y = (int)Math.Max(minPos.Y - 1, 0); y < Math.Min(maxPos.Y + 1, Size.Y); y++) {
Color color;
if (grid[x, y].AttachedBuilding != null) {
if (grid[x, y].AttachedBuilding.RootTile == grid[x, y]) {
string key = (grid[x, y].AttachedBuilding.Name + ((grid[x, y].AttachedBuilding.Level > 0) ? "-level-" + grid[x, y].AttachedBuilding.Level : "") + ((grid[x, y].AttachedBuilding.Varient >= 0) ? "_" + grid[x, y].AttachedBuilding.Varient : "")).ToString();
batch.Draw(TextureBank.textureBank[ key], new Vector2(x * tileSize, y * tileSize), Color.White);
}
}
else {
switch (grid[x,y].Type) {
case TileType.EMPTY:
color = Color.Black;
break;
case TileType.GRASS:
color = Color.Green;
break;
case TileType.HILL:
color = Color.DarkGreen;
break;
case TileType.MOUNTAIN:
color = Color.Gray;
break;
case TileType.HIGHMOUNTAIN:
color = Color.White;
break;
case TileType.SAND:
color = Color.SandyBrown;
break;
case TileType.WATER:
color = Color.Blue;
break;
case TileType.OCEAN:
color = Color.DarkBlue;
break;
default:
color = Color.Black;
break;
}
batch.Draw(TextureBank.tileTexture, new Vector2(x * tileSize, y * tileSize), color);
}
}
}
}
public Tile[] findAStarPath(PathfindingNode start, PathfindingNode end) {
if (end.Name != start.Name) return null;
Heap<PathfindingNode> openSet = new Heap<PathfindingNode>((int)(Size.X * Size.Y));
start.gScore = 0;
start.hScore = start.findHScore(end);
openSet.Add(start);
List<PathfindingNode> closedSet = new List<PathfindingNode>();
while (openSet.Count > 0) {
PathfindingNode current = openSet.RemoveTop();
if (current == end) {
List<Tile> finalList = new List<Tile>();
finalList.Add(getTile(current.X, current.Y));
while (current.parent != null) {
current = current.parent;
finalList.Add(getTile(current.X, current.Y));
}
finalList.Reverse();
return finalList.ToArray();
}
closedSet.Add(current);
for (int x = current.X - 1; x <= current.X + 1; x++) {
for (int y = current.Y - 1; y <= current.Y + 1; y++) {
if ((x != current.X && y != current.Y) || x < 0 || y < 0 || x > Size.X || y > Size.Y) continue;
PathfindingNode n = grid[x, y].getNode(current.Name);
if (n == null) continue;
if (closedSet.Contains(n)) {
continue;
}
float tgScore = current.gScore + current.findGScoreInclusive(n);
if (!openSet.Contains(n) || tgScore < n.gScore) {
n.parent = current;
n.gScore = tgScore;
n.hScore = n.findHScore(end);
if (!openSet.Contains(n)) {
openSet.Add(n);
}
else {
openSet.UpdateItem(n);
}
}
}
}
}
return null;
}
}
}
|
Java | UTF-8 | 372 | 3.25 | 3 | [] | no_license | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer a = Integer.parseInt(sc.next());
int bit = 0;
for (Integer i = 0; i < a; i++) {
bit |= Integer.parseInt(sc.next());
}
System.out.println(Integer.numberOfTrailingZeros(bit));
}
} |
C | UTF-8 | 967 | 2.765625 | 3 | [] | no_license | int main()
{
int m,n,area[9][9]={0},area1[9][9]={0};
scanf("%d%d",&m,&n);
area[4][4]=m;
int i,j;
for(int t=0;t<n;t++)
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
area1[i][j]=area[i][j];
}
}
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
if(area[i][j]!=0)
{
area1[i-1][j-1]+=area[i][j];
area1[i-1][j]+=area[i][j];
area1[i-1][j+1]+=area[i][j];
area1[i][j-1]+=area[i][j];
area1[i][j]+=area[i][j];
area1[i][j+1]+=area[i][j];
area1[i+1][j-1]+=area[i][j];
area1[i+1][j]+=area[i][j];
area1[i+1][j+1]+=area[i][j];
}
}
}
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
area[i][j]=area1[i][j];
}
}
}
for(i=0;i<9;i++)
{
for(j=0;j<8;j++)
{
printf("%d ",area[i][j]);
}
printf("%d\n",area[i][8]);
}
return 0;
}
|
C++ | UTF-8 | 1,187 | 3.203125 | 3 | [] | no_license | #include <utility>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
int link(vector<string> &car, int p, char c, int s, vector<bool> &mark) {
if (p == car.size()) {
int num = pow(2, s);
for (int i = 1; i <= s+1; i++) {
num *= i;
}
return num;
}
if (c == ' ' || car[p][0] == c) {
for (int i = 0; i < car[p].size(); i++) {
char t = car[p][i];
if (c == ' ' || t == c || mark[t-'a'] == false) {
mark[t-'a'] = true;
} else {
return 0;
}
}
return link(car, p+1, car[p][car[p].size()-1], s, mark);
} else if (car[p][0] > c) {
return link(car, p, car[p][0], s+1, mark);
} else if (car[p][0] < c) {
for (int i = 0; i < car[p].size(); i++) {
char t = car[p][i];
if (mark[t-'a'])
return 0;
}
return link(car, p, car[p][0], s+1, mark);
}
return 0;
}
int main() {
int T, N;
cin >> T;
for (int i = 0; i < T; i++) {
cin >> N;
vector<string> car(N);
for (int j = 0; j < N; j++) {
cin >> car[j];
}
sort(car.begin(), car.end());
cout << "Case #" << i+1 << ": ";
vector<int> set;
vector<bool> mark(26, false);
cout << link(car, 0, ' ', 0, mark) << endl;
}
return 0;
} |
TypeScript | UTF-8 | 1,026 | 2.609375 | 3 | [] | no_license | import { TLocationData } from '@services/location/types';
import { IsString, IsUUID, MaxLength, MinLength } from 'class-validator';
export abstract class AbstractLocDataV implements TLocationData {
@IsUUID()
id: string;
@IsUUID()
id_sh: string;
@IsString()
@MaxLength(50, {
message: 'Name is too long. Max length is $constraint1 characters.'
})
@MinLength(4, {
message: 'Name is too short. Min length is $constraint1 characters.'
})
name: string;
@IsString()
@MaxLength(200, {
message: 'Description is too long. Max length is $constraint1 characters.'
})
@MinLength(4, {
message: 'Description is too short. Min length is $constraint1 characters.'
})
description: string;
@IsString()
@MaxLength(500, {
message: 'Address is too long. Max length is $constraint1 characters.'
})
@MinLength(4, {
message: 'Address is too short. Min length is $constraint1 characters.'
})
address: string;
}
|
Markdown | UTF-8 | 940 | 2.875 | 3 | [] | no_license | # Contributing to HTML Inspector
Pull requests are greatly appreciated and encouraged. If you want to get your pull request accepted, please make sure it meets a few minimum requirements:
- **Test files are required**
If you're adding a new rule or module you must add a corresponding test. Check out how the built-in rules are tested for examples.
- **Your changes must pass JSHint**
You can run JSHint from the command line via `grunt jshint`.
- **Follow the existing coding style**
Consistency is key in any project, so any changes should look like the existing code. At a minimum please do the following: (1) Use two spaces for indentation, and (2) don't use semicolons at the end of lines (I know, I'm crazy, but that's how I like it).
If you'd like to contribute but aren't sure how, take a look at the open issues in the issue tracker. There you'll find bug reports as well as feature requests; feel free to tackle either. |
Java | UTF-8 | 692 | 3.28125 | 3 | [] | no_license | package seedu.duke.data;
public class Tour {
private final String code;
private final String name;
private final float price;
public Tour(String[] values) {
code = values[0];
name = values[1];
price = Float.parseFloat(values[2]);
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
@Override
public String toString() {
return "Name: " + name + System.lineSeparator()
+ "Code: " + code + System.lineSeparator()
+ "Price per pax: $" + String.format("%.02f", price);
}
}
|
Ruby | UTF-8 | 20,076 | 3.65625 | 4 | [] | no_license | def main_menu
system("clear")
puts welcome
user_input = gets.strip
case user_input
when "1"
if User.count > 0
system("clear")
existing_user
else
puts ""
system("clear")
puts "There are no users!".light_red.on_black
main_menu
end
when "2"
system("clear")
new_user
when "3"
system("clear")
exit_message
else
system("clear")
main_menu
end
end
def welcome
system("imgcat ./lib/pic/opening.jpg")
puts ""
puts "Welcome to the World of Crafty War".black.on_red
puts "Choose your DESTINY!".light_red.on_black.blink
puts "1. Existing user".light_yellow
puts "2. New user!".light_yellow
puts "3. Exit".light_cyan.on_black
end
def exit_message
puts ""
puts "They always come back!".black.on_light_yellow
puts ""
end
def existing_user
puts ""
puts "Current users:".light_yellow
User.all.each.with_index(1) do |user, index|
puts "#{index}. #{user.name}".light_red.on_black
end
user_match = nil
while user_match.nil?
puts ""
puts "Enter your user name:".light_yellow
user_input = gets.strip
if user_input.to_i == 0
user_match = User.all.find do |user|
user_input.downcase == user.name.downcase
end
elsif user_input.to_i >= 1 && user_input.to_i <= User.count
system("clear")
user_match = User.all[user_input.to_i - 1]
end
end
existing_user_menu(user_match)
end
def new_user
puts ""
puts "Choose your user name:".light_yellow
new_user_name = gets.strip
user_match = User.all.find do |user|
new_user_name.downcase == user.name.downcase
end
if user_match
system("clear")
puts ""
puts "User #{new_user_name} already exists!".light_red.on_black
new_user
else
new_user = User.create(name: new_user_name)
system("clear")
existing_user_menu(new_user)
end
end
def existing_user_menu(user_match)
user_match.reload
puts ""
puts "Welcome #{user_match.name}".light_red.on_black
puts "1. Create new Character".light_yellow
puts "2. Choose an existing Character".light_yellow
puts "3. Main Menu".light_yellow
puts "4. Exit".light_cyan.on_black
user_input = gets.strip
case user_input
when "1"
system("clear")
character_creation(user_match)
when "2"
if user_match.characters.count > 0
system("clear")
character_menu(user_match)
else
system("clear")
puts ""
puts "You don't have any characters!".light_red.on_black
existing_user_menu(user_match)
end
when "3"
system("clear")
main_menu
when "4"
system("clear")
exit_message
else
existing_user_menu(user_match)
end
end
def character_creation(user_match)
puts ""
puts "Enter Character name:".light_yellow.on_red
new_character_name = gets.strip
character_match = Character.all.find do |character|
new_character_name.downcase == character.name.downcase
end
if character_match
system("clear")
puts ""
puts "Character #{new_character_name} already exists!".light_red.on_black
character_creation(user_match)
else
new_race = get_race
race_hp = new_race.hit_points
race_ap = new_race.attack_power
race_d = new_race.defense
system("clear")
puts ""
puts "Character - #{new_character_name}".black.on_red
puts ""
puts "Race - #{new_race.name}".light_green.on_black
system("imgcat ./lib/pic/#{new_race.picture}")
new_battle_class = get_battle_class
bc_hp = new_battle_class.hit_points
bc_ap = new_battle_class.attack_power
bc_d = new_battle_class.defense
system("clear")
puts ""
puts "Character - #{new_character_name}".black.on_red
puts ""
puts "Race - #{new_race.name}".light_green.on_black
system("imgcat ./lib/pic/#{new_race.picture}")
puts ""
puts "Class - #{new_battle_class.name}".light_green.on_black
system("imgcat ./lib/pic/#{new_battle_class.picture}")
new_profession = get_profession
system("imgcat ./lib/pic/#{new_profession.picture}")
new_hp = race_hp + bc_hp
new_ap = race_ap + bc_ap
new_d = race_d + bc_d
new_character = Character.create(name: new_character_name, race: new_race,
battle_class: new_battle_class, profession: new_profession, user: user_match,
hit_points: new_hp, attack_power: new_ap, defense: new_d)
system("clear")
display_character_stats(new_character)
character_option_menu(new_character)
end
end
def get_race
puts ""
puts "Races:".light_yellow.on_red
Race.all.each.with_index(1) do |race, index|
puts "#{index}. #{race.name}".light_cyan.on_blue
puts "Hit Points: #{race.hit_points}, Attack Power: #{race.attack_power}, Defense: #{race.defense}".light_yellow
end
race_match = nil
while race_match.nil?
puts ""
puts "Choose your Race:".light_yellow.on_red
user_input = gets.strip
if user_input.to_i == 0
race_match = Race.find_by(name: user_input.downcase.titlecase)
elsif user_input.to_i >= 1 && user_input.to_i <= Race.count
race_match = Race.all[user_input.to_i - 1]
end
end
race_match
end
def get_battle_class
puts ""
puts "Classes:".light_yellow.on_red
BattleClass.all.each.with_index(1) do |battle_class, index|
puts "#{index}. #{battle_class.name}".light_cyan.on_blue
puts "Hit Points: #{battle_class.hit_points}, Attack Power: #{battle_class.attack_power}, Defense: #{battle_class.defense}".light_yellow
end
battle_class_match = nil
while battle_class_match.nil?
puts ""
puts "Choose your Class:".light_yellow.on_red
user_input = gets.strip
if user_input.to_i == 0
battle_class_match = BattleClass.find_by(name: user_input.downcase.titlecase)
elsif user_input.to_i >= 1 && user_input.to_i <= BattleClass.count
battle_class_match = BattleClass.all[user_input.to_i - 1]
end
end
battle_class_match
end
def get_profession
puts ""
puts "Professions:".light_yellow.on_red
Profession.all.each.with_index(1) {|profession, index| puts "#{index}. #{profession.name}".light_cyan.on_blue}
profession_match = nil
while profession_match.nil?
puts ""
puts "Choose your Profession:".light_yellow.on_red
user_input = gets.strip
if user_input.to_i == 0
profession_match = Profession.find_by(name: user_input.downcase.titlecase)
elsif user_input.to_i >= 1 && user_input.to_i <= Profession.count
profession_match = Profession.all[user_input.to_i - 1]
end
end
profession_match
end
def character_menu(user_match)
puts ""
puts "Your characters:".light_yellow
user_match.characters.each.with_index(1) do |character, index|
puts "#{index}. #{character.name}".light_red.on_black
end
character_choice = get_character_name(user_match)
system("clear")
display_character_stats(character_choice)
character_option_menu(character_choice)
end
def get_character_name(user_match)
puts ""
puts "Choose your Character:".light_yellow
user_input = gets.strip
if user_input.to_i == 0
character_match = user_match.characters.find do |character|
character.name.downcase == user_input.downcase
end
if !character_match
get_character_name(user_match)
else
character_match
end
elsif user_input.to_i >= 1 && user_input.to_i <= user_match.characters.count
user_match.characters[user_input.to_i - 1]
else
get_character_name(user_match)
end
end
def character_option_menu(character_choice)
puts ""
puts "Prepare yourself for battle #{character_choice.name}!".black.on_red.blink
puts "1. Battle!".light_red.on_black
puts "2. Edit Character".light_yellow
puts "3. Display Character stats".light_yellow
puts "4. Delete Character".light_yellow
puts "5. User Menu".light_yellow
puts "6. Main Menu".light_yellow
puts "7. Exit".light_cyan.on_black
user_input = gets.strip
case user_input
when "1"
system("clear")
battle_menu(character_choice)
when "2"
system("clear")
edit_character(character_choice)
when "3"
system("clear")
display_character_stats(character_choice)
character_option_menu(character_choice)
when "4"
puts ""
puts "Are you sure? y/n".light_red.on_black
if gets.strip.downcase == "y"
character_choice.destroy
system("clear")
existing_user_menu(character_choice.user)
else
system("clear")
character_option_menu(character_choice)
end
when "5"
system("clear")
existing_user_menu(character_choice.user)
when "6"
system("clear")
main_menu
when "7"
system("clear")
exit_message
else
system("clear")
character_option_menu(character_choice)
end
end
def edit_character(character_choice)
character_choice.reload
system("clear")
display_character_stats(character_choice)
puts ""
puts "1. Change Name".light_yellow
puts "2. Change Race".light_yellow
puts "3. Change Battle Class".light_yellow
puts "4. Change Profession".light_yellow
puts "5. Return to Character Menu".light_yellow
user_input = gets.strip
case user_input
when "1"
system("clear")
update_name(character_choice)
edit_character(character_choice)
when "2"
system("clear")
race_update = get_race
rhp_update = race_update.hit_points + character_choice.battle_class.hit_points
rap_update = race_update.attack_power + character_choice.battle_class.attack_power
rd_update = race_update.defense + character_choice.battle_class.defense
character_choice.update(race: race_update, hit_points: rhp_update, attack_power: rap_update, defense: rd_update)
edit_character(character_choice)
when "3"
system("clear")
bc_update = get_battle_class
bchp_update = bc_update.hit_points + character_choice.race.hit_points
bcap_update = bc_update.attack_power + character_choice.race.attack_power
bcd_update = bc_update.defense + character_choice.race.defense
character_choice.update(battle_class: bc_update, hit_points: bchp_update, attack_power: bcap_update, defense: bcd_update)
edit_character(character_choice)
when "4"
system("clear")
profession_update = get_profession
character_choice.update(profession: profession_update)
edit_character(character_choice)
when "5"
system("clear")
character_option_menu(character_choice)
else
edit_character(character_choice)
end
end
def update_name(character_choice)
puts ""
puts "#{character_choice.name}, enter your new name:".light_yellow
new_name = gets.strip
name_match = Character.all.find do |character|
new_name.downcase == character.name.downcase
end
if name_match
system("clear")
puts ""
puts "Character #{new_name} already exists!".light_red.on_black
update_name(character_choice)
else
character_choice.update(name: new_name)
system("clear")
character_option_menu(character_choice)
end
end
def display_character_stats(character_choice)
puts ""
puts "Character - #{character_choice.name}".black.on_red
puts ""
puts "Race - #{character_choice.race.name}".light_green.on_black
system("imgcat ./lib/pic/#{character_choice.race.picture}")
puts "Class - #{character_choice.battle_class.name}".light_green.on_black
system("imgcat ./lib/pic/#{character_choice.battle_class.picture}")
puts "Profession - #{character_choice.profession.name}".light_green.on_black
system("imgcat ./lib/pic/#{character_choice.profession.picture}")
puts "Hit Points - #{character_choice.hit_points}".light_green.on_black
puts "Attack Power - #{character_choice.attack_power}".light_green.on_black
puts "Defense - #{character_choice.defense}".light_green.on_black
end
def battle_menu(character_choice)
puts ""
puts "PREPARE FOR BATTLE!!!".light_red.on_black
puts ""
puts "A MONSTER approaches!".black.on_red
puts ""
puts "1. Fight!".light_red.on_black
puts "2. RUNNNNN".white
user_input = gets.strip
case user_input
when "1"
system("clear")
battle_opening(character_choice)
when "2"
system("clear")
character_option_menu(character_choice)
else
battle_menu(character_choice)
end
end
def battle_opening(character_choice)
monster = Monster.all.sample
weapon = weapon_select
system("clear")
puts ""
puts "Weapon - #{weapon.name}".black.on_red
puts "Damage: #{weapon.damage}, Defense: #{weapon.defense}".light_yellow
system("imgcat ./lib/pic/#{weapon.picture}")
ap = character_choice.attack_power + weapon.damage
d = character_choice.defense + weapon.defense
if d < 0
d = 0
end
puts ""
puts "Character - #{character_choice.name}".black.on_red
puts "Hit Points - #{character_choice.hit_points}".light_green.on_black
puts "Attack Power - #{ap}".light_green.on_black
puts "Defense - #{d}".light_green.on_black
battle_arena(character_choice, character_choice.hit_points, monster, monster.hit_points, weapon)
character_option_menu(character_choice)
end
def weapon_select
puts ""
puts "Weapons:".red.on_black
Weapon.all.each.with_index(1) do |weapon, index|
puts "#{index}. #{weapon.name}".black.on_red
puts "Damage: #{weapon.damage}, Defense: #{weapon.defense}".light_yellow
end
weapon_match = nil
while weapon_match.nil?
puts "Equip yourself:".red.on_black
weapon_choice = gets.strip
if weapon_choice.to_i == 0
weapon_match = Weapon.all.find {|weapon| weapon_choice.downcase == weapon.name.downcase}
elsif weapon_choice.to_i >= 1 && weapon_choice.to_i <= Weapon.count
weapon_match = Weapon.all[weapon_choice.to_i - 1]
end
end
weapon_match
end
def battle_arena(character_choice, hp, monster, monster_hp, weapon)
user_input = nil
while user_input != "1" && user_input != "2"
puts ""
puts "1. Attack".light_yellow.on_black
puts "2. Heal".light_yellow.on_black
user_input = gets.strip
end
if user_input == "1"
battle_hash = attack(character_choice, hp, monster, monster_hp, weapon)
elsif user_input == "2"
battle_hash = heal(character_choice, hp, monster, monster_hp, weapon)
end
name = character_choice.name
monster_name = monster.name
system("clear")
puts ""
puts "#{name} ".light_cyan.on_black + "attacks".light_red.on_black + " #{monster_name} for #{battle_hash[:cap]} damage!".light_cyan.on_black
puts "#{name} ".light_cyan.on_black + "heals".light_red.on_black + " for #{battle_hash[:ch]} hit points!".light_cyan.on_black
puts "BUT... #{monster_name} ".light_cyan.on_black + "blocks".light_red.on_black + " #{battle_hash[:md]} damage".light_cyan.on_black
puts "#{monster_name} ".light_cyan.on_black + "bleeds".light_red.on_black + " for #{battle_hash[:mdt]} damage".light_cyan.on_black
puts ""
puts "#{monster_name} ".black.on_light_red + "causes".light_yellow.on_light_red + " #{name} #{battle_hash[:map]} damage".black.on_light_red
puts "#{name} valiantly ".black.on_light_red + "defends".light_yellow.on_light_red + " for #{battle_hash[:cd]} damage!".black.on_light_red
if battle_hash[:cdt] >= 0
puts "#{name} ".black.on_light_red + "grunts".light_yellow.on_light_red + " for #{battle_hash[:cdt]} damage".black.on_light_red
else
puts "#{name} ".black.on_light_red + "restores".light_yellow.on_light_red + " #{battle_hash[:cdt].abs} health".black.on_light_red
end
puts ""
puts "#{name}'s remaining HP: #{battle_hash[:chp]}".light_cyan.on_black
puts "#{monster_name}'s remaining HP: #{battle_hash[:mhp]}".black.on_light_red
if battle_hash[:mhp] > 0
puts ""
puts "#{monster_name}: #{monster.monster_verbages.sample.verbage}".light_red.on_black
end
if(battle_hash[:chp] <= 0 && battle_hash[:mhp] > 0)
puts ""
puts "#{monster_name} slayed #{name}".light_red.on_black
elsif(battle_hash[:chp] > 0 && battle_hash[:mhp] <= 0)
puts ""
puts "You decimated #{monster_name}!".light_green.on_black
elsif(battle_hash[:chp] <= 0 && battle_hash[:mhp] <= 0)
puts ""
puts "You killed each other".light_white.on_black
else
battle_arena(character_choice, battle_hash[:chp], monster, battle_hash[:mhp], weapon)
end
end
def attack(character_choice, hp, monster, monster_hp, weapon)
name = character_choice.name
ap = character_choice.attack_power + weapon.damage
d = character_choice.defense + weapon.defense
if d < 0
d = 0
end
monster_name = monster.name
monster_ap = monster.attack_power
monster_d = monster.defense
c_attack = rand(0..ap)
c_defense = rand(0..d)
monster_attack = rand(0..monster_ap)
monster_defense = rand(0..monster_d)
character_damage_taken = monster_attack - c_defense
monster_damage_taken = c_attack - monster_defense
if character_damage_taken < 0
character_damage_taken = 0
end
if monster_damage_taken < 0
monster_damage_taken = 0
end
hp -= character_damage_taken
monster_hp -= monster_damage_taken
if hp < 0
hp = 0
end
if monster_hp < 0
monster_hp = 0
end
battle_hash = {}
battle_hash = {:chp => hp,
:cap => c_attack,
:cd => c_defense,
:cdt => character_damage_taken,
:ch => 0,
:mhp => monster_hp,
:map => monster_attack,
:md => monster_defense,
:mdt => monster_damage_taken}
end
def heal(character_choice, hp, monster, monster_hp, weapon)
name = character_choice.name
ap = character_choice.attack_power + weapon.damage
d = character_choice.defense + weapon.defense
if d < 0
d = 0
end
monster_name = monster.name
monster_ap = monster.attack_power
monster_d = monster.defense
heal = rand(0..(1.5*d)).round
monster_attack = rand(0..monster_ap)
monster_defense = rand(0..monster_d)
character_damage_taken = monster_attack - heal
hp -= character_damage_taken
if hp > character_choice.hit_points
hp = character_choice.hit_points
end
if hp < 0
hp = 0
end
if monster_hp < 0
monster_hp = 0
end
battle_hash = {}
battle_hash = {:chp => hp,
:cap => 0,
:cd => 0,
:cdt => character_damage_taken,
:ch => heal,
:mhp => monster_hp,
:map => monster_attack,
:md => monster_defense,
:mdt => 0}
end |
Java | UTF-8 | 1,303 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package es.source.code.Fragment;
import es.source.code.AppGlobal;
import es.source.code.R;
import es.source.code.model.Food;
import es.source.code.util.SharedPreferenceUtil;
/**
* Created by sail on 2018/10/10.
*/
public class DrinkFoodFragment extends BaseFoodFragment {
public static final String TAG = "酒水";
public static final String index = AppGlobal.Lable.DRINK_LABLE;
@Override
protected void initDataList() {
int store = 1;
int category = 3;
dataList.add(new Food("百香多多",20, store,AppGlobal.REMARK,category, false,R.drawable.food_drink_bxdd));
dataList.add(new Food("草莓香蕉奶昔",18, store,AppGlobal.REMARK,category, false,R.drawable.food_drink_cmxjnx));
dataList.add(new Food("红茶",10, store,AppGlobal.REMARK,category, false,R.drawable.food_drink_hc));
dataList.add(new Food("红枣核桃山药饮",15, store, AppGlobal.REMARK,category,false,R.drawable.food_drink_hzhtsyy));
dataList.add(new Food("玫瑰情人露",22, store,AppGlobal.REMARK,category, false,R.drawable.food_drink_mgqrl));
SharedPreferenceUtil sup = SharedPreferenceUtil.getInstance(mContext);
sup.setAllFood(category,dataList);
}
@Override
public String getFoodTag() {
return TAG;
}
}
|
SQL | UTF-8 | 2,039 | 3.25 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 23, 2018 at 11:25 AM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `blog_samples`
--
-- --------------------------------------------------------
--
-- Table structure for table `tblproduct`
--
CREATE TABLE `tblproduct` (
`id` int(8) NOT NULL,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tblproduct`
--
INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'Lego Marvel Super Heroes 2', 'Release: November 14, 2017', 'product-images/LegoMarvelSuperHeroes.jpg', 1500.00),
(2, 'Marvel Guardians of the Galaxy: The Telltale Series', 'Release: April 18, 2017', 'product-images/game.jpg', 1200.00),
(3, 'Marvel Ultimate Alliance', 'Release: October 24, 2006', 'product-images/MarvelUltimateAlliance.jpg', 1100.00),
(4, 'Marvel vs. Capcom: Infinite', 'Release: September 19, 2017', 'product-images/marvelbattlelines.jpg', 1500.00);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tblproduct`
--
ALTER TABLE `tblproduct`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `product_code` (`code`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tblproduct`
--
ALTER TABLE `tblproduct`
MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | UTF-8 | 4,654 | 2.453125 | 2 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright (c) 2004, DoodleProject
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of DoodleProject nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.doodleproject.numerics4j.series;
import net.sf.doodleproject.numerics4j.IterativeMethod;
import net.sf.doodleproject.numerics4j.iterativeMethTest;
import net.sf.doodleproject.numerics4j.exception.NumericException;
public class SeriesTest extends iterativeMethTest {
private Series sine = new Series() {
protected double getTerm(int n, double x) {
return Math.pow(-1.0, n) * Math.pow(x, 2.0 * n + 1.0) / factorial(2.0 * n + 1.0);
}
private double factorial(double n) {
double f = 1.0;
while(n > 0.0) {
f *= n;
n = n - 1.0;
}
return f;
}
};
class Test extends Series {
public Test() {
super();
}
public Test(int iterations, double error) {
super(iterations, error);
}
protected double getTerm(int n, double x) {
return 0;
}
}
protected IterativeMethod createIterativeMethod() {
return sine;
}
public void testConstructor() {
testConstructorFailure(-1, 1.0);
testConstructorFailure( 0, 1.0);
testConstructorFailure( 1, Double.NaN);
testConstructorFailure( 1, Double.NEGATIVE_INFINITY);
testConstructorFailure( 1, -1.0);
testConstructorFailure( 1, 0.0);
testConstructorSuccess( 1, 1.0);
testConstructorSuccess( 1, Double.POSITIVE_INFINITY);
}
private void testConstructorSuccess(int iterations, double error) {
try {
Test s = new Test(iterations, error);
assertEquals(iterations, s.getMaximumIterations());
assertEquals(error, s.getMaximumRelativeError(), 0.0);
} catch (IllegalArgumentException ex) {
fail("Valid constructor values.");
}
}
private void testConstructorFailure(int iterations, double error) {
try {
new Test(iterations, error);
fail("Invalid constructor values.");
} catch (IllegalArgumentException ex) {
// success
}
}
public void testEvaluate() throws NumericException {
testEvaluateSuccess(Math.PI / 2.0, 1.0);
testEvaluateSuccess(Double.NaN, Double.NaN);
}
private void testEvaluateSuccess(double x, double expected) throws NumericException {
assertRelativelyEquals(expected, sine.evaluate(x), sine.getMaximumRelativeError());
}
private void testEvaluateFailure(double x, Class exception) throws NumericException {
try {
sine.evaluate(x);
fail();
} catch (NumericException ex) {
if (!exception.equals(ex.getClass())) {
throw ex;
}
} catch (RuntimeException ex) {
if (!exception.equals(ex.getClass())) {
throw ex;
}
}
}
}
|
C | UTF-8 | 4,405 | 2.6875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<signal.h>
#include<sys/ipc.h>
#include<errno.h>
#include<sys/shm.h>
#include<time.h>
#include<pthread.h>
#include<arpa/inet.h>
#define PORT 2333
#define SIZE 1024
#define SIZE_SHMADD 2048
#define BACKLOG 3
int sockfd;
int fd[BACKLOG];
int i = 0;
/*********套接字描述符*******/
int get_sockfd() {
struct sockaddr_in server_addr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "Socket error:%s\n\a", strerror(errno));
exit(1);
} else {
printf("Socket successful!\n");
}
/* sockaddr结构 */
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
/*绑定服务器的ip和服务器端口号*/
if (bind(sockfd, (struct sockaddr * )(&server_addr), sizeof(struct sockaddr)) == -1) {
fprintf(stderr, "Bind error:%s\n\a", strerror(errno));
exit(1);
} else {
printf("Bind successful!\n");
}
/* 设置允许连接的最大客户端数 */
if (listen(sockfd, BACKLOG) == -1) {
fprintf(stderr, "Listen error:%s\n\a", strerror(errno));
exit(1);
} else {
printf("Listening.....\n");
}
return sockfd;
}
/*创建共享存储区*/
int shmid_create() {
int shmid;
if ((shmid = shmget(IPC_PRIVATE, SIZE_SHMADD, 0777)) < 0) {
perror("shmid error!");
exit(1);
} else printf("shmid success!\n");
return shmid;
}
int main(int argc, char * argv[]) {
char shmadd_buffer[SIZE_SHMADD], buffer[SIZE];
struct sockaddr_in client_addr;
int sin_size;
pid_t ppid, pid;
int new_fd;
int shmid;
char * shmadd;
time_t timep = time(0);
/***********共享内存**************/
shmid = shmid_create();
//映射共享内存
shmadd = shmat(shmid, 0, 0);
/*****创建套接字描述符***********/
int sockfd = get_sockfd();
/*循环接收客户端*/
while (1) {
/* 服务器阻塞,直到客户程序建立连接 */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)( &client_addr), &sin_size)) == -1) {
fprintf(stderr, "Accept error:%s\n\a", strerror(errno));
exit(1);
} else {
printf("Accept successful!\n");
}
fd[i++] = new_fd;
printf("\n已连接了客户端%d : %s:%d \n", i, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
/*把界面发送给客户端*/
memset(buffer, 0, SIZE);
strcpy(buffer, "\n——————————————————Welecom come char ———————————————————————\n");
send(new_fd, buffer, SIZE, 0);
//创建子进程客户端
ppid = fork();
if (ppid == 0) {
//将加入的新客户发送给所有在线的客户端/
recv(new_fd, buffer, SIZE, 0);
strcat(buffer, " 进入了聊天室....");
for (i = 0; i < BACKLOG; i++) {
if (fd[i] != -1) {
send(fd[i], buffer, strlen(buffer), 0);
}
}
//创建子进程进行读写操作/
pid = fork();
while (1) {
if (pid > 0) {
//父进程用于接收信息/
memset(buffer, 0, SIZE);
if ((recv(new_fd, buffer, SIZE, 0)) <= 0) {
close(new_fd);
exit(1);
}
memset(shmadd, 0, SIZE_SHMADD);
strncpy(shmadd, buffer, SIZE_SHMADD);
//将缓存区的客户端信息放入共享内存里
printf(" %s\n", buffer);
}
if (pid == 0) {
//子进程用于发送信息/
sleep(1);
//先执行父进程
if (strcmp(shmadd_buffer, shmadd) != 0) {
strcpy(shmadd_buffer, shmadd);
if (new_fd > 0) {
if (send(new_fd, shmadd, strlen(shmadd), 0) == -1) {
perror("send");
}
memset(shmadd, 0, SIZE_SHMADD);
strcpy(shmadd, shmadd_buffer);
}
}
}
}
}
}
free(buffer);
close(new_fd);
close(sockfd);
return 0;
} |
Java | UTF-8 | 1,441 | 3.125 | 3 | [] | no_license | package assignment5;
import java.io.*;
import java.net.*;
import com.zpartal.commpackets.*;
public class Connection implements Runnable {
protected Socket client = null;
ObjectInputStream input;
ObjectOutputStream output;
int a = 0;
int b = 0;
ClientPacket incoming;
ServerPacket outgoing;
boolean connected=false;
public Connection(Socket client){
super();
this.client = client;
}
public void run() {
try{
input =
new ObjectInputStream(client.getInputStream());
output =
new ObjectOutputStream(client.getOutputStream());
while(true){
incoming = (ClientPacket) input.readObject();
a = incoming.getNum1();
b = incoming.getNum2();
String ClientID = incoming.getClientID();
System.out.println("Client ID: " + ClientID);
System.out.println("Recevied:"+ a + "+" + b);
System.out.println("Total:"+(a+b));
System.out.println("Swarm sending Total to client");
outgoing = new ServerPacket("Destoroyah", incoming.getNum1()+incoming.getNum2());
output.writeObject(outgoing);
}
}
catch(IOException e){
System.out.println("Client disconnected unexpectedly");
}
catch(ClassNotFoundException p){
System.out.println(p);
}
try{
output.close();
input.close();
System.out.println("Client Disconnected");
client.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
|
Python | UTF-8 | 7,434 | 3.125 | 3 | [
"MIT"
] | permissive | __author__ = 'Lab Hatter'
from panda3d.core import Vec3, Vec4, Point3
from math import sqrt, pow
def getDistance(pt1, pt2):
return sqrt(pow(pt1.x - pt2.x, 2) + pow(pt1.y - pt2.y, 2) + pow(pt1.z - pt2.z, 2))
def getDistance2d(pt1, pt2):
return sqrt(pow(pt1.x - pt2.x, 2) + pow(pt1.y - pt2.y, 2))
def makeTriangleCcw(tri):
rightVec = tri[1] - tri[0]
leftVec = tri[2] - tri[0]
if rightVec.cross(leftVec).z < 0:
tmp = tri[1]
tri[1] = tri[2]
tri[2] = tmp
return tri
# the following was an attempt to make a polygon ccw
# cntr = getCenterOfPoints3D(verts)
# if cntr == Vec3(0, 0, 0):
# cntr += .01
# q = PriorityQueue()
# for i in verts:
# ang = getTrueAngleXYBetweenPoints(cntr, i)
# q.put((ang, i))
#
# # print cntr, "makeTriangleCcw" ############### PRINT
# verts = []
# while q.qsize() != 0:
# n = q.get_nowait()
# # print n, getTrueAngleXYBetweenPoints(cntr, n[1]), "makeTriangleCcw"
# verts.append(n[1])
# raise NotImplementedError("makeTriangleCcw is not implemented")
# return verts
def triangleContainsPoint(pt, tri):
"""Takes a convex polygon and returns true, if the given point is inside the polygon"""
triangle = makeTriangleCcw([tri[0], tri[1], tri[2]])
# it needs to take the cross product of every point in the polygon and the next point
# the final point needs to take the cross product of the beginning point
triangle.append(triangle[0])
foundOutside = False
for p in range(0, len(triangle) - 1):
edgeVec = triangle[p + 1] - triangle[p]
vecToPt = pt - triangle[p]
if edgeVec.cross(vecToPt).z < 0:
# if all of the cross products show vecToPt is to the left of the edgeVec
# the point is inside the polygon
# if one is to the right, the point is outside of the polygon
foundOutside = True
break
# reverse the logic (not) because above we were looking for a point outside of the polygon
return not foundOutside
def getCenterOfPoints3D(points):
n = len(points)
x = 0
y = 0
z = 0
for i in points:
x = x + i.x
y = y + i.y
z = z + i.z
return Point3(x/n, y/n, z/n)
def getDistToLine(pt, linePt1, linePt2):
"""Given a point and two points on the line, return the distance from the point to the line."""
# http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
# TODO: change getDistToLine to take a two point list for the line like all the other line functions [pt1, pt2]
numerator = abs((linePt2.x - linePt1.x)*(linePt1.y - pt.y) - (linePt1.x - pt.x)*(linePt2.y - linePt1.y))
return numerator / sqrt((linePt2.x - linePt1.x)**2 + (linePt2.y - linePt1.y)**2)
def scaleVec3(scale, vec):
"""Multiplies a scalar by each components of a vector and returns the resulting vector."""
# print scale, vec
return Vec3(scale*vec.x, scale*vec.y, scale*vec.z)
counter = -1
def getNearestPointOnLine( pt, line, asLineSeg=False):
"""Given a point and a line represented as two points,
this returns nearest point on line to the given point. A line segment only works on the XY plane."""
lineVec = line[1] - line[0]
vecToPt = pt - line[0]
# projection of vecToPt onto lineVec
proj = scaleVec3((lineVec[0] * vecToPt[0] + lineVec[1] * vecToPt[1]) / (lineVec[0]**2 + lineVec[1]**2), lineVec)
ptOnLine = Point3(proj + line[0])
# if we want to constrain it to the line segment, set the nearest pt to the closest end of the line
# unless it's already within the segment
if asLineSeg:
# TODO: make getNearestPointOnLine()'s line segment feature work in 3D, if possible
lengthOfLine = getDistance(line[0], line[1])
# if the distance from either point on the line to the point calculated is longer than the line itself,
# then the point lies outside of the line segment
if getDistance(ptOnLine, line[1]) > lengthOfLine or\
getDistance(ptOnLine, line[0]) > lengthOfLine:
if getDistance(ptOnLine, line[0]) > getDistance(ptOnLine, line[1]):
ptOnLine = line[1]
else:
ptOnLine = line[0]
return ptOnLine
def getLeftPt(pt, ptPair):
"""Takes the center of two points then returns the left point as viewed from a third point (1st parameter)."""
midPt = getCenterOfPoints3D(ptPair)
vecToMid = midPt - pt
vecToPt1 = ptPair[0] - pt
# the point on the leftVec has a negative z in its cross product with the middle point
if vecToPt1.cross(vecToMid).z < 0:
return ptPair[0]
else:
return ptPair[1]
def makeWedge(line1, line2):
"""Makes a wedge formed by two supplied edges, and returns that wedge in the form [leftVector, rightVector]"""
# this expects a point and two lines.
# The lines are presented as two points each, and one of those must be in both lines.
shared1 = shared2 = notShared1 = notShared2 = -1
for i in range(0, 2):
if line1[i] in line2:
shared1 = i
else:
notShared1 = i
if line2[i] in line1:
shared2 = i
else:
notShared2 = i
# print "makeWedge", line1, line2
if shared1 == -1 or shared2 == -1: # redundant but Oh well.
sr = "makeWedge(): The two lines must share a point. Given points:\n" + str(line1) + "\n" + str(line2)
raise StandardError(sr)
# find which edge-end is on the left and which is on the right
lftPt = getLeftPt(line1[shared1], [line1[notShared1], line2[notShared2]])
if lftPt == line1[notShared1]:
rtPt = line2[notShared2]
else:
rtPt = line1[notShared1]
rtVec = rtPt - line1[shared1]
lftVec = lftPt - line1[shared1]
return [lftVec, rtVec]
def isPointInWedge(pt, line1, line2, inclusive=True):
"""Returns True, if the given point is inside the infinite wedge formed
by the two lines (inclusive = True considers points on the lines to be in the wedge.)"""
lftVec, rtVec = makeWedge(line1, line2)
# print "isPointInWedge pt", pt, " line1 ", line1, " line2 ", line2
# print "lftVec ", lftVec, " rtVec ", rtVec
for i in range(0, 2):
if line1[i] in line2:
shared1 = i
ptVec = pt - line1[shared1]
# right cross pt should be up. Left cross pt should be down, if the point is inside the infinite wedge.
if inclusive: # points on the edge of the wedge count as in the wedge
return rtVec.cross(ptVec).z >= 0 >= lftVec.cross(ptVec).z
else:
return rtVec.cross(ptVec).z > 0 > lftVec.cross(ptVec).z
# def doesEdgeCrossWedge(edge, wedgeSide1, wedgeSide2):
# """Returns True, if either point in the edge lies within the infinite wedge formed by the two wedge sides,
# or returns True, if the edge crosses over the infinite wedge."""
# if isPointInWedge(edge[0], wedgeSide1, wedgeSide2) or isPointInWedge(edge[1], wedgeSide1, wedgeSide2):
# return True
# # check to make sure that both points of the edge aren't behind the wedge
# # then make sure the right point is outside the right side and the left is outside the left side
|
Java | UTF-8 | 446 | 2.71875 | 3 | [] | no_license | package com.ttmdear.repositories.io.files;
import java.io.IOException;
import java.io.InputStream;
public class ReadStreamFile {
public void run() throws IOException {
InputStream inputStream = this.getClass().getResourceAsStream("/input-test.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.println((char)data);
}
inputStream.close();
}
}
|
Markdown | UTF-8 | 2,155 | 3.390625 | 3 | [
"Apache-2.0"
] | permissive | ### [303\. 区域和检索 - 数组不可变](https://leetcode-cn.com/problems/range-sum-query-immutable/description/)
Difficulty: **简单**
给定一个整数数组 _nums_,求出数组从索引 _i _到 _j _(_i_ ≤ _j_) 范围内元素的总和,包含 _i, j _两点。
**示例:**
```
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
```
**说明:**
1. 你可以假设数组不可变。
2. 会多次调用 _sumRange_ 方法。
#### Solution
Language: **全部题目**
```
时间复杂度: O(n)
空间复杂度: O(n)
状态转移方程:
dp[i] = dp[i-1] + nums[i-1]
BASE CASE
dp[0] = 0
(i, j) = dp[j+1] - dp[i]
```
### [413\. 等差数列划分](https://leetcode-cn.com/problems/arithmetic-slices/)
Difficulty: **中等**
如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。
例如,以下数列为等差数列:
```
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
```
以下数列不是等差数列。
```
1, 1, 2, 5, 7
```
数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。
如果满足以下条件,则称子数组(P, Q)为等差数组:
元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。
函数要返回数组 A 中所有为等差数组的子数组个数。
**示例:**
```
A = [1, 2, 3, 4]
返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
```
#### Solution
Language: **全部题目**
```
413. 等差数列划分
解题的关键(剪枝叶):
等差数列[0-(i-1)](增加x个子序列), => 等差数列[0-i] 增加x+1个子序列
状态转移方程:
dp[i] = dp[i-1] + 1 A[i] - A[i-1] = A[i-1] - A[i-2]
= 0 A[i] - A[i-1] != A[i-1] - A[i-2]
BASE CASE
dp[0] = 0, dp[1] = 1
最后答案 = dp数组的和
状态压缩
可以状态压缩, 当前状态只和上一个状态有关
采用方式:
递归
动态规划
状态压缩的动态规划
``` |
Java | UTF-8 | 577 | 2.640625 | 3 | [] | no_license | package com.haifeng.example.iamgeupload.message;
/**
* Toast信息类,EventBus会使用到
*/
public class ToastMessage {
private String data;
/**
* 可以保存一个int数据类型的数据
*/
private int time;
public ToastMessage(String data) {
this.data = data;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
|
Python | UTF-8 | 16,424 | 3 | 3 | [] | no_license | import argparse
import cPickle
import os
import math
import re
#Reads in the positive & negative lexicon items to a uniqued list and returns that list
def readLexicon(posLexFile, negLexFile, negation, adverbs):
posLex = open(posLexFile, "r")
negLex = open(negLexFile, "r")
entireLex = []
appendAdverbs = ["extremely", "quite", "just", "almost", "very", "too", "enough"]
for line in posLex:
if not line.startswith(";"): #gets rid of the file headers
entireLex.append(line.strip())
if negation:
entireLex.append("not_"+line.strip()) #appends not_s to lexicon if specified
if adverbs:
for adverb in appendAdverbs:
entireLex.append(adverb+"_"+line.strip()) #appends adverbs to lexicon if specified
for line in negLex:
if not line.startswith(";"):
entireLex.append(line.strip())
if negation:
entireLex.append("not_"+line.strip())
if adverbs:
for adverb in appendAdverbs:
entireLex.append(adverb+"_"+line.strip()) #appends adverbs to lexicon if specified
return list(set(entireLex)) #converting to a set removes duplicates
#trains on given training data
def train(lexicon, trainFiles, negation, adverbs):
nbData = {"positive": [], "negative": [], "totalNeg": 0, "totalPos": 0}
vocabSize = len(lexicon)
for trainfile in os.listdir(trainFiles+"neg/"):
if "cv8" not in trainfile and "cv9" not in trainfile: #skips testing files
sentiment = "negative" #To be used as a key in nbData
nbData["totalNeg"] += 1 #Updates count to be used for p(neg)
train = open(trainFiles+"neg/"+trainfile,"r")
if negation:
data = train.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = train.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = train.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon and uniques them
startVector = [0] * vocabSize
for word in tokens:
index = lexicon.index(word)
startVector[index] += 1 #Updates the index for words that occur
nbData[sentiment].append(startVector)
for trainfile in os.listdir(trainFiles+"pos/"): #Same deal for positive files
if "cv8" not in trainfile and "cv9" not in trainfile:
sentiment = "positive"
nbData["totalPos"] += 1
train = open(trainFiles+"pos/"+trainfile,"r")
if negation:
data = train.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = train.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = train.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon and uniques them
startVector = [0] * vocabSize
for word in tokens:
index = lexicon.index(word)
startVector[index] += 1
nbData[sentiment].append(startVector)
return nbData, vocabSize
#Estimates conditional probability of a word
def estimateParameter(lexicon, nbData, word, sentiment):
index = lexicon.index(word) #index in the training vector for that word
count = 0
total = len(nbData[sentiment]) #total amount of training vectors
for vector in nbData[sentiment]:
count += vector[index]
parameter = (float(count)+0.1)/(float(total)+0.1)
return parameter
#outputs top ten highest probabilities for P(word|sentiment)
def topWords(lexicon, model):
posWords = {}
negWords = {}
for word in lexicon: #estimates probabilities for every word in lexicon
posWords[word] = estimateParameter(lexicon, model, word, "positive")
negWords[word] = estimateParameter(lexicon, model, word, "negative")
#prints highest values in the dict
print "most informative positive words"
for w in sorted(posWords.items(), key=lambda x: x[1], reverse=True)[:10]:
print w[0], w[1]
print "most informative negative words"
for w in sorted(negWords.items(), key=lambda x: x[1], reverse=True)[:10]:
print w[0], w[1]
#Tests on the training files for 5.3a
def trainTest(lexicon, model, vocabSize, testFiles, negation, adverbs):
negTrials = 0 #total negative training examples
negAccuracy = 0 #negative examples classified correctly
negPrior = float(model["totalNeg"]) / (float(model["totalNeg"])+float(model["totalPos"]))
posPrior = float(model["totalPos"]) / (float(model["totalNeg"])+float(model["totalPos"]))
for testfile in os.listdir(testFiles+"neg/"):
if "cv8" not in testfile and "cv9" not in testfile:
test = open(testFiles+"neg/"+testfile,"r")
if negation:
data = test.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = test.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = test.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon
negProb = 0
posProb = 0
for word in tokens:
conditionalProbNeg = estimateParameter(lexicon, model, word, "negative")
conditionalProbPos = estimateParameter(lexicon, model, word, "positive")
negProb += math.log(conditionalProbNeg) #update the probability of (x|negative)
posProb += math.log(conditionalProbPos) #update the probability of (x|positive)
negProb = negProb + math.log(negPrior) #add the prior for the full probability
posProb = posProb + math.log(posPrior)
if negProb > posProb: #counts the correct classifications
negTrials += 1
negAccuracy += 1
else:
negTrials += 1
print "negative accuracy on training data=", float(negAccuracy) / float(negTrials)
posTrials = 0
posAccuracy = 0
for testfile in os.listdir(testFiles+"pos/"): #same thing for positive
if "cv8" not in testfile and "cv9" not in testfile:
test = open(testFiles+"pos/"+testfile,"r")
if negation:
data = test.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = test.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = test.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon
negProb = 0
posProb = 0
for word in tokens:
conditionalProbNeg = estimateParameter(lexicon, model, word, "negative")
conditionalProbPos = estimateParameter(lexicon, model, word, "positive")
negProb += math.log(conditionalProbNeg)
posProb += math.log(conditionalProbPos)
negProb = negProb + math.log(negPrior)
posProb = posProb + math.log(posPrior)
if posProb > negProb:
posTrials += 1
posAccuracy += 1
else:
posTrials += 1
print "positive accuracy on training data=", float(posAccuracy) / float(posTrials)
print "total accuracy on training data=", (float(posAccuracy) + float(negAccuracy))/(float(posTrials)+float(negTrials)), "\n"
#Exactly the same but it tests on only the testing files for 5.3b
def test(lexicon, model, vocabSize, testFiles, negation, adverbs):
negTrials = 0
negAccuracy = 0
negPrior = float(model["totalNeg"]) / (float(model["totalNeg"])+float(model["totalPos"]))
posPrior = float(model["totalPos"]) / (float(model["totalNeg"])+float(model["totalPos"]))
for testfile in os.listdir(testFiles+"neg/"):
if "cv8" in testfile or "cv9" in testfile:
test = open(testFiles+"neg/"+testfile,"r")
if negation:
data = test.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = test.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = test.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon
negProb = 0
posProb = 0
for word in tokens:
conditionalProbNeg = estimateParameter(lexicon, model, word, "negative")
conditionalProbPos = estimateParameter(lexicon, model, word, "positive")
negProb += math.log(conditionalProbNeg) #update the probability of (x|negative)
posProb += math.log(conditionalProbPos) #update the probability of (x|positive)
negProb = negProb + math.log(negPrior) #add the prior for the full probability
posProb = posProb + math.log(posPrior)
if negProb > posProb: #counts the correct classifications
negTrials += 1
negAccuracy += 1
else:
negTrials += 1
print "negative accuracy on testing data=", float(negAccuracy) / float(negTrials)
posTrials = 0
posAccuracy = 0
for testfile in os.listdir(testFiles+"pos/"): #same thing for positive
if "cv8" in testfile or "cv9" in testfile:
test = open(testFiles+"pos/"+testfile,"r")
if negation:
data = test.read()
newdata = re.sub('n\'t\s|\snot\s',' not_', data,flags=re.IGNORECASE) #replaces nots and n'ts
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
if adverbs:
data = test.read()
newdata = re.sub('\sextremely\s',' extremely_', data,flags=re.IGNORECASE) #replaces adverbs
newdata = re.sub('\squite\s',' quite_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\sjust\s',' just_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\salmost\s',' almost_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\svery\s',' very_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\stoo\s',' too_', newdata,flags=re.IGNORECASE)
newdata = re.sub('\senough\s',' enough_', newdata,flags=re.IGNORECASE)
words = newdata.split()
tokens = list(set([word for word in words if word in lexicon]))
else:
words = test.read().split()
tokens = list(set([word for word in words if word in lexicon])) #filters out words not in the lexicon
negProb = 0
posProb = 0
for word in tokens:
conditionalProbNeg = estimateParameter(lexicon, model, word, "negative")
conditionalProbPos = estimateParameter(lexicon, model, word, "positive")
negProb += math.log(conditionalProbNeg)
posProb += math.log(conditionalProbPos)
negProb = negProb + math.log(negPrior)
posProb = posProb + math.log(posPrior)
if posProb > negProb:
posTrials += 1
posAccuracy += 1
else:
posTrials += 1
print "positive accuracy on testing data=", float(posAccuracy) / float(posTrials)
print "total accuracy on testing data=", (float(posAccuracy) + float(negAccuracy))/(float(posTrials)+float(negTrials))
def main():
parser = argparse.ArgumentParser()
parser.usage = "python naiveBayes.py -lp opinion-lexicon-English/positive-words.txt -ln opinion-lexicon-English/negative-words.txt --train review_polarity/"
parser.add_argument("--train", dest="trainFiles", action="store", help="Directory should contain two other directories with positive / negative training data separated")
parser.add_argument("-lp", "--lexiconPos", dest="posLex", action="store", help="A lexicon of positive words")
parser.add_argument("-ln", "--lexiconNeg", dest="negLex", action="store", help="A lexicon of negative words")
parser.add_argument("--test", dest="test", action="store_true", default=False, help="Boolean for testing")
parser.add_argument("-tw", "--topwords", dest="topWords", action="store_true", default=False, help="Boolean for top sentiment carrying words")
parser.add_argument("-nh", "--negation", dest="negation", action="store_true", default=False, help="Boolean for negation handling")
parser.add_argument("-ah", "--adverbs", dest="adverbs", action="store_true", default=False, help="Boolean for adverb handling")
opts = parser.parse_args()
if opts.posLex and opts.negLex: #prepares the lexicon if lexicon files are given
lexicon = readLexicon(opts.posLex, opts.negLex, opts.negation, opts.adverbs)
else:
print "Please specify lexicon directory"
if opts.trainFiles: #trains model if training data is given
model,vocabSize = train(lexicon, opts.trainFiles, opts.negation, opts.adverbs)
else:
print "Please specify training file directory"
if opts.test: #tests model if testing data is given
trainTest(lexicon, model, vocabSize, opts.trainFiles, opts.negation, opts.adverbs)
test(lexicon, model, vocabSize, opts.trainFiles, opts.negation, opts.adverbs)
if opts.topWords:
topWords(lexicon, model)
main() |
Shell | UTF-8 | 1,112 | 3.609375 | 4 | [
"MIT"
] | permissive | #!/bin/bash
trap "exit" INT TERM ERR
trap "kill 0" EXIT
if [ "$1" == "help" ];
then echo "----------------------------"
echo ""
echo "Usage: ./start [install | run | help]"
echo ""
echo "'./start' will install dependencies and spin up servers"
echo "'./start install' will install dependencies but not run servers"
echo "'./start run' will run servers without installing dependencies"
echo ""
echo "Use CONTROL+C to exit the script and kill the servers"
echo ""
echo "----------------------------"
else
if [ "$1" != "run" ];
then
pip3 install virtualenv
virtualenv env
source env/bin/activate
pip3 install -r requirements.txt
npm install
fi
if [ "$1" == "install" ];
then echo ""
echo "Server not starting"
echo ""
else
echo "Server starting"
source env/bin/activate
python3 manage.py runserver &
npm run dev &
sleep 15s
echo ""
echo Servers are running! Kill servers with CONTROL+C
echo ""
wait
fi
fi
|
Java | UTF-8 | 501 | 2.984375 | 3 | [] | no_license | package cn.itcast.demo.README.day02;
import java.util.Random;
/**
* @ClassName RandomDemo1
* @Description TODO
* @Author zhangcong
* @Date 2020/11/15
**/
public class RandomDemo1 {
public static void main(String[] args) {
Random r = new Random();
// int num = r.nextInt(10);
// System.out.println(num);
for (int i = 0; i <10 ; i++) {
int num = r.nextInt(10);
System.out.println(num);
}
}
}
|
JavaScript | UTF-8 | 3,585 | 2.578125 | 3 | [] | no_license | import React, { Component } from 'react';
import {connect} from 'react-redux'
class NodeForm extends Component {
constructor(props) {
super(props);
this.state = {
noteTitle:'',
noteContent: '',
id: ''
}
}
componentDidMount(){
console.log(this.props.editItem)
if(this.props.editItem){
this.setState({
noteTitle:this.props.editItem.noteTitle,
noteContent: this.props.editItem.noteContent,
id: this.props.editItem.id
})
}
}
isChange = (event) =>{
const name = event.target.name;
const value = event.target.value;
this.setState ({
[name]: value
})
}
addData = (title, content) => {
if(this.state.id){
var editObject = {};
editObject.id = this.state.id;
editObject.noteContent = this.state.noteContent;
editObject.noteTitle = this.state.noteTitle;
this.props.editDataStore(editObject);
this.props.changeEditStatus(); // tắt form khi lưu
}else{
var item = {};
item.noteTitle = title;
item.noteContent = content;
// this.props.getData(item)
//item = JSON.stringify(item)
this.props.addDataStore(item);
}
}
printTitle = () => {
console.log(this.props.addStatus)
if(this.props.addStatus){
return <h4>Thêm mới</h4>
}else{
return <h4>Sửa ghi chú</h4>
}
}
render() {
return (
<div className="col-4">
{this.printTitle()}
<form>
<div className="form-group">
<label htmlFor="noteTite">Tiêu đề note</label>
<input defaultValue={this.props.editItem.noteTitle} onChange={(event)=>this.isChange(event)} type="text" className="form-control" name="noteTitle" id="noteTite" aria-describedby="helpIdNoteTitle" placeholder="Nhập tiêu đề" />
{/* <small id="helpIdNoteTitle" class="form-text text-muted">Help text</small> */}
</div>
<div className="form-group">
<label htmlFor="noteContent">Nội dung note</label>
<textarea onChange={(event)=>this.isChange(event)} type="text" className="form-control" name="noteContent" id="noteTite" aria-describedby="helpIdNoteTitle" placeholder="Nội dụng note" defaultValue={this.props.editItem.noteContent} />
{/* <small id="helpIdNoteTitle" class="form-text text-muted">Help text</small> */}
</div>
<button onClick={()=>this.addData(this.state.noteTitle, this.state.noteContent)} type="reset" className="btn btn-primary btn-block">Lưu</button>
</form>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return{
editItem: state.editItem,
addStatus: state.isAdd
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return{
addDataStore: (getItem) =>{
dispatch({type:'ADD_DATA', getItem})
},
editDataStore: (getItem) =>{
dispatch({type:'EDIT', getItem})
},
changeEditStatus: () =>{
dispatch({type:"CHANGE_EDIT_STATUS"})
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(NodeForm) |
C++ | UTF-8 | 702 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int countDifferentSubsequenceGCDs(vector<int>& nums) {
int curr_max = INT_MIN, ret = 0, n = nums.size();
int present[200001] = {0};
for(int i=0; i<n; i++)
{
curr_max = max(curr_max, nums[i]);
present[nums[i]]=1;
}
for(int i=1; i<=curr_max; i++)
{
int curr_gcd = 0;
for(int j=i; j<=curr_max; j+=i)
{
if(present[j]==1)
curr_gcd = gcd(curr_gcd, j);
if(curr_gcd==i)
{
ret++;
break;
}
}
}
return ret;
}
};
|
Python | UTF-8 | 7,275 | 3.25 | 3 | [] | no_license | # Team 2 rpgDriverTeam2.py
# Preliminary version 0.1
# Revision: JL 12/16/2013
# - Game Loop first draft ->MAGIC STRINGS/NUMBERS ABOUND<-
# - End of game messages
# - Tested loop
from creature import Creature
from cookieMonster import CookieMonster
from customer import Customer
import random
random.seed()
DEBUG_MODE = True
def __main__():
# create character
myName = raw_input("Please enter character name: ")
myGender = raw_input("Please enter character gender (M/F): ")
if myName == "":
myName = "Hero"
if myGender =="":
myGender ="M"
myCustomer = Customer(myName, myGender)
print str(myCustomer)
myMonster = CookieMonster()
print
print str(myMonster)
###
if DEBUG_MODE:
print "DEBUG: cust/monst HP: " + str(myCustomer.getHealth()) +\
"/" + str(myMonster.getHealth())
print "DEBUG: DEATH: " + str(myCustomer.isDead()) +\
"/" + str(myMonster.isDead())
###
print "monster found! BATTLE!!"
# while loop
while ( not myCustomer.isDead() ) and myCustomer.getLevel() < 4:
#if monster is alive
#battle round
if myMonster.getHealth() > 0:
#####
#USER TURN
#####
needInput = True
monsterHit = False
while needInput:
print ""
print "Your HP: " + str(myCustomer.getHealth()) +\
"Monster HP: " + str(myMonster.getHealth())
print ""
userIn = raw_input("would you like to (F)ight, " +\
"(R)un, or (E)xplode? ").upper()
print ""
if userIn == 'E':
print "You run up and hug the Cookie Monster, " +\
"begin to tick, and blow up, " +\
"taking it and all the thin mints with you."
myMonster.setHealth(0)
myCustomer.setHealth(0)
needInput = False
###
if DEBUG_MODE:
print "DEBUG: cust/monst HP: " + str(myCustomer.getHealth()) +\
"/" + str(myMonster.getHealth())
print "DEBUG: DEATH: " + str(myCustomer.isDead()) +\
"/" + str(myMonster.isDead())
###
elif userIn == 'R':
print "COWARD! You manage to get away, "+\
"though not with your dignity..."
myMonster.setHealth(0)
needInput = False
elif userIn == 'F':
monsterHit = True
print "You tell the Cookie Monster " +\
"you don't have any money!"
if myMonster.isHit():
dmg = myCustomer.dealsDamage()
print "You weaken the Cookie Monster's " +\
"sales pitch by " + str(dmg) + " damage!"
myMonster.takesHit(dmg)
else:
print "The Cookie Monster doesn't believe your lie " +\
"and laughs at your incompetence!"
needInput = False
else:
print "Lets try this input thing again, shall we?"
#####
#MONSTER TURN
#####
#if monster is still alive
if not myMonster.isDead():
print "The Cookie Monster tries to sell you delicious cookies!"
if myCustomer.isHit():
dmg = myMonster.dealsDamage()
print "The Cookie Monster hits your wallet for " +\
str(dmg) + " damage!"
myCustomer.takesHit(dmg)
else:
print "You start to talk about the weather, " +\
"breaking the Cookie Monster's sales pitch!"
#if monster was killed by player
elif monsterHit:
print "You chased her off crying! " +\
"\nDon't you feel like a big person!"
#get XP
myCustomer.setExperience(myMonster.getXP())
myCustomer.incrementLevel()
print "!!!LEVEL UP!!! \n*fireworks, fireworks*\n" +\
"You are now level " + str(myCustomer.getLevel())
#get cookies
cookiesDropped = myMonster.getThinMints()
if cookiesDropped > 0:
print "Wait, she dropped some cookies! " +\
"Well, would be a shame if they went to waste..."
print "\nAcquired " + str(cookiesDropped) +\
" Cookies!\n"
myCustomer.setThinMints(cookiesDropped)
#if monster is dead
else:
#regen
if myCustomer.getHealth() < myCustomer.getMaxHealth():
myCustomer.regenHealth()
#eat cookies
if myCustomer.getThinMints() != 0:
print "You have " + str(myCustomer.getThinMints()) +\
"\nand " + str(myCustomer.getHealth()) +\
"/" + str(myCustomer.getMaxHealth()) +\
"health."
userIn = eval(raw_input("How many thin mints would" +\
"you like to eat? "))
myCustomer.eatThinMints(userIn)
print "You NOW have " + str(myCustomer.getThinMints()) +\
"\nand " + str(myCustomer.getHealth()) +\
"/" + str(myCustomer.getMaxHealth()) +\
"health."
#chance to ATAMO
if myCustomer.atamo():
print "REMEMBER THE ALAMO! errr... ATAMO! " +\
"\n FULL HEAL!"
myCustomer.setHealth(myCustomer.getMaxHealth())
#chance to spawn new monster
if random.randint(1, 3) == 1:
myMonster = CookieMonster()
print "monster found! BATTLE!!"
#####
#END GAME LOOP
#DO END GAME RESULTS
#####
#end of game messages, check health and level to determine msg
print "\n"
if myCustomer.isDead():
if myMonster.isDead():
print "Well, you're in debt for the rest of your life, " +\
"but at least you took one down with you!"
else:
print "You have fallen to the seductive nature of the thin mint." +\
"Enjoy being broke and fat!"
elif myMonster.isDead():
if myCustomer.getLevel() >= 4:
print "You Win!!! You weathered the storm and " +\
"managed to keep your bank account in the black... this year!"
else:
print "Wait, you shouldn't be here!" +\
"Quick! Report this bug to the nearest girlscout!!"
print "\nGAME OVER\n"
raw_input("Press Enter to exit.")
if __name__ == '__main__':
__main__()
|
Markdown | UTF-8 | 18,483 | 4.09375 | 4 | [] | no_license | # A first splash into JavaScript
## Thinking like a programmer
One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. You need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together.
This requires a mixture of hard work, experience with the programming syntax, and practice — plus a bit of creativity. The more you code, the better you'll get at it. We can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a programmer throughout the course.
With that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.
## Example — Guess the number game
Let's imagine your boss has given you the following brief for creating this game:
> I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player should be told if they are right or wrong — and, if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.
Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:
1. Generate a random number between 1 and 100.
2. Record the turn number the player is on. Start it on 1.
3. Provide the player with a way to guess what the number is.
4. Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
5. Next, check whether it is the correct number.
6. If it is correct:
1. Display congratulations message.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
7. If it is wrong and the player has turns left:
1. Tell the player they are wrong.
2. Allow them to enter another guess.
3. Increment the turn number by 1.
8. If it is wrong and the player has no turns left:
1. Tell the player it is game over.
2. Stop the player from being able to enter more guesses (this would mess the game up).
3. Display control allowing the player to restart the game.
9. Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.
Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.
### Initial setup
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
<script>
// Your JavaScript goes here
</script>
</body>
</html>
```
### Adding variables to store our data
Let's get started. First of all, add the following lines inside your script element:
```js
let randomNumber = Math.floor(Math.random() * 100) + 1;
const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');
let guessCount = 1;
let resetButton;
```
This section of the code sets up the variables and constants we need to store the data our program will use.
Constants are used to store values that you don't want to change, and are created with the keyword `const`. In this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the HTML elements referenced stay the same.
You can assign a value to your variable or constant with an equals sign (`=`) followed by the value you want to give it.
In our example:
- The first variable — `randomNumber` — is assigned a random number between 1 and 100, calculated using a mathematical algorithm.
- The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code:
```html
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
```
- The next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
```html
<label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
```
- Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).
### Conditionals
Returning to our `checkGuess()` function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.
At this point, replace your current `checkGuess()` function with this version instead:
```js
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = '!!!GAME OVER!!!';
setGameOver();
} else {
lastResult.textContent = 'Wrong!';
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
```
This is a lot of code — phew! Let's go through each section and explain what it does.
- The first line (line 2 above) declares a variable called `userGuess` and sets its value to the current value entered inside the text field. We also run this value through the built-in `Number()` constructor, just to make sure the value is definitely a number.
- Next, we encounter our first conditional code block (lines 3–5 above). A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword
, then some parentheses, then some curly braces. Inside the parentheses we include a test. If the test returns
- Line 6 appends the current `userGuess` value onto the end of the `guesses` paragraph, plus a blank space so there will be a space between each guess shown.
- The next block (lines 8–24 above) does a few checks:
- The first `if(){ }` checks whether the user's guess is equal to the `randomNumber`set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called `setGameOver()`, which we'll discuss later.
- Now we've chained another test onto the end of the last one using an `else if(){ }` structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.
- The final block chained onto the end of this code (the `else { }`) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.
- The last three lines in the function (lines 26–28 above) get us ready for the next guess to be submitted. We add 1 to the `guessCount` variable so the player uses up their turn (`++`is an incrementation operation — increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.
### Events
At this point we have a nicely implemented `checkGuess()` function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called **event listeners**, and the blocks of code that run in response to the event firing are called **event handlers**.
Add the following line below your `checkGuess()` function:
```js
guessSubmit.addEventListener('click', checkGuess);
```
Here we are adding an event listener to the `guessSubmit` button. This is a method that takes two input values (called *arguments*) — the type of event we are listening out for (in this case `click`) as a string, and the code we want to run when the event occurs (in this case the `checkGuess()` function). Note that we don't need to specify the parentheses when writing it inside [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).
### Finishing the game functionality
Let's add that `setGameOver()` function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:
```js
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Start new game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
```
- The first two lines disable the form text input and button by setting their disabled properties to `true`. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.
- The next three lines generate a new [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) element, set its text label to "Start new game", and add it to the bottom of our existing HTML.
- The final line sets an event listener on our new button so that when it is clicked, a function called `resetGame()` is run.
Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:
```js
function resetGame() {
guessCount = 1;
const resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
```
This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:
- Puts the `guessCount` back down to 1.
- Empties all the text out of the information paragraphs.
- Removes the reset button from our code.
- Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.
- Removes the background color from the `lastResult` paragraph.
- Generates a new random number so that you are not just guessing the same number again!
**At this point you should have a fully working (simple) game — congratulations!**
All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.
### Loops
One part of the above code that we need to take a more detailed look at is the [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your [browser developer tools JavaScript console](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools) again, and enter the following:
```js
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
```
What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A `for` loop takes three input values (arguments):
1. **A starting value**: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter `i` with any name you like too, but `i` is used as a convention because it's short and easy to remember.
2. **An exit condition**: Here we have specified `i < 21` — the loop will keep going until `i` is no longer less than 21. When `i` reaches 21, the loop will no longer run.
3. **An incrementor**: We have specified `i++`, which means "add 1 to i". The loop will run once for every value of `i`, until `i` reaches a value of 21 (as discussed above). In this case, we are simply printing the value of `i` out to the console on every iteration using [`console.log()`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log).
Now let's look at the loop in our number guessing game — the following can be found inside the `resetGame()` function:
```js
let resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
```
This code creates a variable containing a list of all the paragraphs inside `<div class="resultParas">` using the [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) method, then it loops through each one, removing the text content of each.
### A small discussion on objects
Let's add one more final improvement before we get to this discussion. Add the following line just below the `let resetButton;` line near the top of your JavaScript, then save your file:
```js
guessField.focus();
```
This line uses the [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) method to automatically put the text cursor into the [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.
Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.
In this particular case, we first created a `guessField` constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:
```js
const guessField = document.querySelector('.guessField');
```
To get this reference, we used the [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) method of the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) object. `querySelector()` takes one piece of information — a [CSS selector](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors) that selects the element you want a reference to.
Because `guessField` now contains a reference to an [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is `focus()`, so we can now use this line to focus the text input:
```js
guessField.focus();
```
## Finished for now...
So that's it for building the example. You got to the end — well done! Try your final code out, or [play with our finished version here](http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game.html). If you can't get the example to work, check it against the [source code](https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html).
|
PHP | UTF-8 | 1,542 | 2.796875 | 3 | [] | no_license | <?php
namespace models;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="send_log")
*/
class SendLog
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="id")
*/
protected $usr;
/**
* @ORM\ManyToOne(targetEntity="Number", inversedBy="id")
*/
protected $num;
/**
* @ORM\Column(type="text")
* @var string
*/
protected $log_message;
/**
* @ORM\Column(type="integer")
* @var int
*/
protected $log_success;
/**
* @ORM\Column(type="integer")
*/
protected $log_created;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param string $log_message
*/
public function setLogMessage(string $log_message): void
{
$this->log_message = $log_message;
}
/**
* @param mixed $log_created
*/
public function setLogCreated($log_created): void
{
$this->log_created = $log_created;
}
/**
* @param int $log_success
*/
public function setLogSuccess(int $log_success): void
{
$this->log_success = $log_success;
}
/**
* @param mixed $usr
*/
public function setUsr($usr): void
{
$this->usr = $usr;
}
/**
* @param mixed $num
*/
public function setNum($num): void
{
$this->num = $num;
}
} |
Python | UTF-8 | 914 | 2.78125 | 3 | [] | no_license | from models import User, Post, Tag, db
from app import app
db.drop_all()
db.create_all()
User.query.delete()
user1 = User(first_name='Alan', last_name='Alda')
user2 = User(first_name='Joel', last_name='Burton', image_url='http://joelburton.com/joel-burton.jpg')
user3 = User(first_name='Jane', last_name='Smith')
post_alan1 = Post(title="Hello", content="My name is Alan Alda", author_id=1)
post_alan2 = Post(title="I am an actor", content="I was in M*A*S*H, which is an old show", author_id=1)
post_joel = Post(title="Introduction to Typescript", content="Typescript is like Javascript", author_id=2)
tag1 = Tag(name="fun")
tag2 = Tag(name="Even More")
tag3 = Tag(name="Bloop")
db.session.add(user1)
db.session.add(user2)
db.session.add(user3)
db.session.add(post_alan1)
db.session.add(post_alan2)
db.session.add(post_joel)
db.session.add(tag1)
db.session.add(tag2)
db.session.add(tag3)
db.session.commit() |
Python | UTF-8 | 807 | 2.78125 | 3 | [] | no_license | import threading
import time
'''so much resource cpu need to frequently change them so ...
maybe turn into chaos'''
g_num=0
def test1(temp):
global g_num#define g_num as global
for i in range(temp):
g_num += 1
print('---1:{}---'.format(g_num))
def test2(temp):
global g_num
for i in range(temp):
g_num += 1
print('---2:{}---'.format(g_num))
def main():
t1=threading.Thread(target=test1,args=(100000000,))
t2=threading.Thread(target=test2,args=(100000000,))
t1.start()
t2.start()
# ---main---:28622471
# ---1:126803457---
# ---2:127107718---
#turn into chaos so we need chaos cause so much resource cpu need to frequently
#change process
time.sleep(5)
print('---main---:{}'.format(g_num))
if __name__ == "__main__":
main()
|
C | UTF-8 | 9,630 | 2.859375 | 3 | [] | no_license | /*
* BIRD Library -- Formatted Output
*
* (c) 1991, 1992 Lars Wirzenius & Linus Torvalds
*
* Hacked up for BIRD by Martin Mares <mj@ucw.cz>
* Buffer size limitation implemented by Martin Mares.
*/
#include "nest/bird.h"
#include "string.h"
#include <errno.h>
#include "nest/iface.h"
/* we use this so that we can do without the ctype library */
#define is_digit(c) ((c) >= '0' && (c) <= '9')
static int skip_atoi(const char **s)
{
int i=0;
while (is_digit(**s))
i = i*10 + *((*s)++) - '0';
return i;
}
#define ZEROPAD 1 /* pad with zero */
#define SIGN 2 /* unsigned/signed long */
#define PLUS 4 /* show plus */
#define SPACE 8 /* space if plus */
#define LEFT 16 /* left justified */
#define SPECIAL 32 /* 0x */
#define LARGE 64 /* use 'ABCDEF' instead of 'abcdef' */
#define do_div(n,base) ({ \
int __res; \
__res = ((unsigned long) n) % (unsigned) base; \
n = ((unsigned long) n) / (unsigned) base; \
__res; })
static char * number(char * str, long num, int base, int size, int precision,
int type, int remains)
{
char c,sign,tmp[66];
const char *digits="0123456789abcdefghijklmnopqrstuvwxyz";
int i;
if (size >= 0 && (remains -= size) < 0)
return NULL;
if (type & LARGE)
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (type & LEFT)
type &= ~ZEROPAD;
if (base < 2 || base > 36)
return 0;
c = (type & ZEROPAD) ? '0' : ' ';
sign = 0;
if (type & SIGN) {
if (num < 0) {
sign = '-';
num = -num;
size--;
} else if (type & PLUS) {
sign = '+';
size--;
} else if (type & SPACE) {
sign = ' ';
size--;
}
}
if (type & SPECIAL) {
if (base == 16)
size -= 2;
else if (base == 8)
size--;
}
i = 0;
if (num == 0)
tmp[i++]='0';
else while (num != 0)
tmp[i++] = digits[do_div(num,base)];
if (i > precision)
precision = i;
size -= precision;
if (size < 0 && -size > remains)
return NULL;
if (!(type&(ZEROPAD+LEFT)))
while(size-->0)
*str++ = ' ';
if (sign)
*str++ = sign;
if (type & SPECIAL) {
if (base==8)
*str++ = '0';
else if (base==16) {
*str++ = '0';
*str++ = digits[33];
}
}
if (!(type & LEFT))
while (size-- > 0)
*str++ = c;
while (i < precision--)
*str++ = '0';
while (i-- > 0)
*str++ = tmp[i];
while (size-- > 0)
*str++ = ' ';
return str;
}
/**
* bvsnprintf - BIRD's vsnprintf()
* @buf: destination buffer
* @size: size of the buffer
* @fmt: format string
* @args: a list of arguments to be formatted
*
* This functions acts like ordinary sprintf() except that it checks
* available space to avoid buffer overflows and it allows some more
* format specifiers: |%I| for formatting of IP addresses (any non-zero
* width is automatically replaced by standard IP address width which
* depends on whether we use IPv4 or IPv6; |%#I| gives hexadecimal format),
* |%R| for Router / Network ID (u32 value printed as IPv4 address)
* and |%m| resp. |%M| for error messages (uses strerror() to translate @errno code to
* message text). On the other hand, it doesn't support floating
* point numbers.
*
* Result: number of characters of the output string or -1 if
* the buffer space was insufficient.
*/
int bvsnprintf(char *buf, int size, const char *fmt, va_list args)
{
int len;
unsigned long num;
int i, base;
u32 x;
char *str, *start;
const char *s;
char ipbuf[STD_ADDRESS_P_LENGTH+1];
struct iface *iface;
int flags; /* flags to number() */
int field_width; /* width of output field */
int precision; /* min. # of digits for integers; max
number of chars for from string */
int qualifier; /* 'h', 'l', or 'L' for integer fields */
for (start=str=buf ; *fmt ; ++fmt, size-=(str-start), start=str) {
if (*fmt != '%') {
if (!size)
return -1;
*str++ = *fmt;
continue;
}
/* process flags */
flags = 0;
repeat:
++fmt; /* this also skips first '%' */
switch (*fmt) {
case '-': flags |= LEFT; goto repeat;
case '+': flags |= PLUS; goto repeat;
case ' ': flags |= SPACE; goto repeat;
case '#': flags |= SPECIAL; goto repeat;
case '0': flags |= ZEROPAD; goto repeat;
}
/* get field width */
field_width = -1;
if (is_digit(*fmt))
field_width = skip_atoi(&fmt);
else if (*fmt == '*') {
++fmt;
/* it's the next argument */
field_width = va_arg(args, int);
if (field_width < 0) {
field_width = -field_width;
flags |= LEFT;
}
}
/* get the precision */
precision = -1;
if (*fmt == '.') {
++fmt;
if (is_digit(*fmt))
precision = skip_atoi(&fmt);
else if (*fmt == '*') {
++fmt;
/* it's the next argument */
precision = va_arg(args, int);
}
if (precision < 0)
precision = 0;
}
/* get the conversion qualifier */
qualifier = -1;
if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') {
qualifier = *fmt;
++fmt;
}
/* default base */
base = 10;
if (field_width > size)
return -1;
switch (*fmt) {
case 'c':
if (!(flags & LEFT))
while (--field_width > 0)
*str++ = ' ';
*str++ = (byte) va_arg(args, int);
while (--field_width > 0)
*str++ = ' ';
continue;
case 'm':
if (flags & SPECIAL) {
if (!errno)
continue;
if (size < 2)
return -1;
*str++ = ':';
*str++ = ' ';
start += 2;
size -= 2;
}
s = strerror(errno);
goto str;
case 'M':
s = strerror(va_arg(args, int));
goto str;
case 's':
s = va_arg(args, char *);
if (!s)
s = "<NULL>";
str:
len = strlen(s);
if (precision >= 0 && len > precision)
len = precision;
if (len > size)
return -1;
if (!(flags & LEFT))
while (len < field_width--)
*str++ = ' ';
for (i = 0; i < len; ++i)
*str++ = *s++;
while (len < field_width--)
*str++ = ' ';
continue;
case 'p':
if (field_width == -1) {
field_width = 2*sizeof(void *);
flags |= ZEROPAD;
}
str = number(str,
(unsigned long) va_arg(args, void *), 16,
field_width, precision, flags, size);
if (!str)
return -1;
continue;
case 'n':
if (qualifier == 'l') {
long * ip = va_arg(args, long *);
*ip = (str - buf);
} else {
int * ip = va_arg(args, int *);
*ip = (str - buf);
}
continue;
/* IP address */
case 'I':
if (flags & SPECIAL)
ipa_ntox(va_arg(args, ip_addr), ipbuf);
else {
ipa_ntop(va_arg(args, ip_addr), ipbuf);
if (field_width == 1)
field_width = STD_ADDRESS_P_LENGTH;
}
s = ipbuf;
goto str;
/* Interface scope after link-local IP address */
case 'J':
iface = va_arg(args, struct iface *);
if (!iface)
continue;
if (!size)
return -1;
*str++ = '%';
start++;
size--;
s = iface->name;
goto str;
/* Router/Network ID - essentially IPv4 address in u32 value */
case 'R':
x = va_arg(args, u32);
bsprintf(ipbuf, "%d.%d.%d.%d",
((x >> 24) & 0xff),
((x >> 16) & 0xff),
((x >> 8) & 0xff),
(x & 0xff));
s = ipbuf;
goto str;
/* integer number formats - set up the flags and "break" */
case 'o':
base = 8;
break;
case 'X':
flags |= LARGE;
case 'x':
base = 16;
break;
case 'd':
case 'i':
flags |= SIGN;
case 'u':
break;
default:
if (size < 2)
return -1;
if (*fmt != '%')
*str++ = '%';
if (*fmt)
*str++ = *fmt;
else
--fmt;
continue;
}
if (qualifier == 'l')
num = va_arg(args, unsigned long);
else if (qualifier == 'h') {
num = (unsigned short) va_arg(args, int);
if (flags & SIGN)
num = (short) num;
} else if (flags & SIGN)
num = va_arg(args, int);
else
num = va_arg(args, uint);
str = number(str, num, base, field_width, precision, flags, size);
if (!str)
return -1;
}
if (!size)
return -1;
*str = '\0';
return str-buf;
}
/**
* bvsprintf - BIRD's vsprintf()
* @buf: buffer
* @fmt: format string
* @args: a list of arguments to be formatted
*
* This function is equivalent to bvsnprintf() with an infinite
* buffer size. Please use carefully only when you are absolutely
* sure the buffer won't overflow.
*/
int bvsprintf(char *buf, const char *fmt, va_list args)
{
return bvsnprintf(buf, 1000000000, fmt, args);
}
/**
* bsprintf - BIRD's sprintf()
* @buf: buffer
* @fmt: format string
*
* This function is equivalent to bvsnprintf() with an infinite
* buffer size and variable arguments instead of a &va_list.
* Please use carefully only when you are absolutely
* sure the buffer won't overflow.
*/
int bsprintf(char * buf, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i=bvsnprintf(buf, 1000000000, fmt, args);
va_end(args);
return i;
}
/**
* bsnprintf - BIRD's snprintf()
* @buf: buffer
* @size: buffer size
* @fmt: format string
*
* This function is equivalent to bsnprintf() with variable arguments instead of a &va_list.
*/
int bsnprintf(char * buf, int size, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i=bvsnprintf(buf, size, fmt, args);
va_end(args);
return i;
}
int
buffer_vprint(buffer *buf, const char *fmt, va_list args)
{
int i = bvsnprintf((char *) buf->pos, buf->end - buf->pos, fmt, args);
buf->pos = (i >= 0) ? (buf->pos + i) : buf->end;
return i;
}
int
buffer_print(buffer *buf, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i=bvsnprintf((char *) buf->pos, buf->end - buf->pos, fmt, args);
va_end(args);
buf->pos = (i >= 0) ? (buf->pos + i) : buf->end;
return i;
}
void
buffer_puts(buffer *buf, const char *str)
{
byte *bp = buf->pos;
byte *be = buf->end;
while (bp < be && *str)
*bp++ = *str++;
if (bp < be)
*bp = 0;
buf->pos = bp;
}
|
Java | UTF-8 | 1,499 | 2.953125 | 3 | [] | no_license | package com.juwechat.wechat.queue;
import com.juwechat.wechat.utils.UserInfoUtil;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 异步获取用户信息的阻塞队列类
* @author 秋枫艳梦
* @date 2019-06-09
* */
public class UserInfoQueue {
//存放openid的阻塞队列.openid即微信推送的数据包中的FromUserName
public static BlockingQueue<String> userQueue = new LinkedBlockingDeque<>();
//监听队列的线程数量,这里我们开启15个线程去处理(并不是越多越好),提高吞吐量
public static final int THREADS = 15;
/**
* 监听阻塞队列,执行相关业务
* */
public static void startListen(){
for (int i = 0; i < THREADS; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true){
try {
String openId = userQueue.take();
String info = UserInfoUtil.getInfoById(openId);
System.out.println("获取到的用户信息:\n"+info);
//这里模拟一下即可
System.out.println("已写入数据库......");
}catch (Exception e){
}
}
}
};
new Thread(runnable).start();
}
}
}
|
C++ | UTF-8 | 1,394 | 2.953125 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | #include <gtest/gtest.h>
#include <PartialCsvParser.hpp>
using namespace PCP;
class PartialCsvParserWithOnMemoryCsvTest : public ::testing::Test {
protected:
PartialCsvParserWithOnMemoryCsvTest() {}
virtual void SetUp() {}
};
TEST_F(PartialCsvParserWithOnMemoryCsvTest, NullTerminatedString) {
const char * const csv =
"101,102\n"
"201,202\n";
Memory::CsvConfig csv_config(csv, false);
PartialCsvParser parser(csv_config);
std::vector<std::string> row;
EXPECT_FALSE((row = parser.get_row()).empty());
EXPECT_EQ(2, row.size());
EXPECT_EQ("101", row[0]);
EXPECT_EQ("102", row[1]);
EXPECT_FALSE((row = parser.get_row()).empty());
EXPECT_EQ(2, row.size());
EXPECT_EQ("201", row[0]);
EXPECT_EQ("202", row[1]);
EXPECT_TRUE((row = parser.get_row()).empty());
}
TEST_F(PartialCsvParserWithOnMemoryCsvTest, StringWithLength) {
const char * const csv =
"101,102\n"
"201,202_this_should_be_ignored\n";
Memory::CsvConfig csv_config(15UL, csv, false);
PartialCsvParser parser(csv_config);
std::vector<std::string> row;
EXPECT_FALSE((row = parser.get_row()).empty());
EXPECT_EQ(2, row.size());
EXPECT_EQ("101", row[0]);
EXPECT_EQ("102", row[1]);
EXPECT_FALSE((row = parser.get_row()).empty());
EXPECT_EQ(2, row.size());
EXPECT_EQ("201", row[0]);
EXPECT_EQ("202", row[1]);
EXPECT_TRUE((row = parser.get_row()).empty());
}
|
Java | UTF-8 | 216 | 1.578125 | 2 | [] | no_license | package com.chorlock;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
}
}
|
Markdown | UTF-8 | 2,632 | 2.796875 | 3 | [
"MIT"
] | permissive | # glob-keys [](https://www.npmjs.com/package/glob-keys) [](https://npmjs.org/package/glob-keys) [](https://travis-ci.org/jonschlinkert/glob-keys)
> Returns an array of property names exposed from a glob of javascript modules. Useful for linting, documentation, table of contents, etc.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install glob-keys --save
```
## Usage
```js
var globKeys = require('glob-keys');
```
Given the following files exist:
```js
// --foo.js--
exports.foo = function(){}
// --bar.js--
exports.bar = function(){}
// --baz.js--
exports.baz = function(){}
exports.qux = function(){}
exports.fez = function(){}
// --obj.js--
exports.abc = {};
exports.xyz = '123';
```
The following would return an array of keys exposed on all of the listed files:
```js
var keys = globKeys(['*.js']);
//=> ['bar', 'baz', 'qux', 'fez', 'foo', 'abx', 'xyz']
```
## Related projects
You might also be interested in these projects:
* [matched](https://www.npmjs.com/package/matched): Adds array support to node-glob, sync and async. Also supports tilde expansion (user home) and… [more](https://www.npmjs.com/package/matched) | [homepage](https://github.com/jonschlinkert/matched)
* [method-names](https://www.npmjs.com/package/method-names): Returns an array of names from a module. Includes all enumerable properties with function values,… [more](https://www.npmjs.com/package/method-names) | [homepage](https://github.com/jonschlinkert/method-names)
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/glob-keys/issues/new).
## Building docs
Generate readme and API documentation with [verb](https://github.com/verbose/verb):
```sh
$ npm install verb && npm run docs
```
Or, if [verb](https://github.com/verbose/verb) is installed globally:
```sh
$ verb
```
## Running tests
Install dev dependencies:
```sh
$ npm install -d && npm test
```
## Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT license](https://github.com/jonschlinkert/glob-keys/blob/master/LICENSE).
***
_This file was generated by [verb](https://github.com/verbose/verb), v, on March 25, 2016._ |
Java | UTF-8 | 3,174 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | package interlok.http.apache.credentials;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Locale;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.junit.jupiter.api.Test;
import com.adaptris.security.exc.PasswordException;
public class TestCredentialsBuilder {
@Test
public void testProviderBuilder() {
DefaultCredentialsProviderBuilder builder = new DefaultCredentialsProviderBuilder().withScopedCredentials(
new ScopedCredential().withScope(new AnyScope()).withCredentials(new UsernamePassword().withCredentials("myUser", "myPassword")));
assertNotNull(builder.build());
assertTrue(CredentialsProvider.class.isAssignableFrom(builder.build().getClass()));
}
@Test
public void testCredentialsProvider() {
DefaultCredentialsProviderBuilder builder = new DefaultCredentialsProviderBuilder().withScopedCredentials(
new ScopedCredential().withScope(new AnyScope()).withCredentials(new UsernamePassword().withCredentials("myUser", "myPassword")));
CredentialsProvider provider = builder.build();
Credentials creds = provider.getCredentials(AuthScope.ANY);
assertEquals(UsernamePasswordCredentials.class, creds.getClass());
assertEquals("myUser", creds.getUserPrincipal().getName());
assertEquals("myPassword", creds.getPassword());
}
@Test
public void testCredentialsProvider_BadPassword() throws Exception {
DefaultCredentialsProviderBuilder builder = new DefaultCredentialsProviderBuilder().withScopedCredentials(new ScopedCredential()
.withScope(new AnyScope()).withCredentials(new UsernamePassword().withCredentials("myUser", "AES_GCM:myPassword")));
assertThrows(PasswordException.class, () -> builder.build());
}
@Test
public void testConfiguredScope() {
ConfiguredScope builder = new ConfiguredScope();
builder.setHost("localhost");
builder.setPort(443);
builder.setRealm("realm");
builder.setScheme("https");
AuthScope scope = builder.build();
assertEquals("localhost", scope.getHost());
assertEquals(443, scope.getPort());
assertEquals("realm", scope.getRealm());
assertEquals("https".toUpperCase(Locale.ROOT), scope.getScheme().toUpperCase(Locale.ROOT));
}
@Test
public void testClientBuilderConfigure() throws Exception {
ClientBuilderWithCredentials builder = new ClientBuilderWithCredentials();
assertNotNull(builder.configure(HttpClients.custom()));
DefaultCredentialsProviderBuilder credsProvider = new DefaultCredentialsProviderBuilder().withScopedCredentials(
new ScopedCredential().withScope(new AnyScope()).withCredentials(new UsernamePassword().withCredentials("myUser", "myPassword")));
assertNotNull(builder.withProvider(credsProvider).configure(HttpClients.custom()));
}
} |
Python | UTF-8 | 923 | 2.78125 | 3 | [] | no_license | from socket import *
from threading import Thread
import pickle
class Client():
def __init__(self):
self.host = '127.0.0.1'
self.port = 2325
self.s = socket(AF_INET, SOCK_STREAM)
self.s.connect((self.host, self.port))
self.email = "None"
self.host2 = '127.0.0.1'
self.port2 = 2326
self.s2 = socket(AF_INET, SOCK_STREAM)
self.s2.connect((self.host2, self.port2))
def func1(self,command):
data_array = command.split(' ')
if self.email=="None":
if data_array[0]=="register" or data_array[0]=="login":
self.email=data_array[1]
self.s.send(command.encode("ascii"))
data = self.s.recv(1024)
data = pickle.loads(data)
return data
def func2(self):
while True:
data = self.s2.recv(1024)
data = pickle.loads(data)
for dat in data:
if type(dat)==str:
data_array = dat.split(' ')
if len(data_array)>2 and data_array[2]==self.email:
print (dat)
break
|
Java | UTF-8 | 85,289 | 1.8125 | 2 | [
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.program.model.pcode;
import static org.junit.Assert.*;
import java.util.Objects;
import org.junit.*;
import ghidra.program.database.ProgramDB;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.test.*;
/**
*
* This class tests the various "instruction-level" methods for modifying the pcode emitted for
* an instruction. These include flow overrides, fallthrough overrides, and various overriding
* references.
*
* In practice, it should be exceedingly rare to have multiple modifiers defined on the same
* instruction. Nonetheless, it is possible. Note that the operations introduced by flow
* overrides and fallthrough overrides are subject to further modification. Modifications
* by any overriding reference are final and cannot themselves be modified.
*
* Several tests involve delay slots. Delay slots present some complications since they
* essentially combine two instructions but the various overrides are associated with a single
* address (either via a Reference or by being a property of an Instruction).
* Note that fallthrough overrides are disabled for instructions in delay slots, and that
* flow overrides are disabled when emitting pcode for a delayslot directive.
*
* Some tests capture behavior on situations that probably don't occur in practice
* (such as a call instruction in a delay slot). Breaking such tests isn't necessarily indicative
* of an error, but should at least be investigated.
*
* Potential additional tests:
* multiple instructions in delay slots?
* crossbuilds?
* adjustment of uniques
* interpretation of inst_next
* interaction with delay slots
* analog of corner case described in testFlowOverridesAndDelaySlots
* tests with overlays?
* skeq in delay slot
* test location generation
*/
public class PcodeEmitContextTest extends AbstractGhidraHeadlessIntegrationTest {
private TestEnv env;
private Program program;
private static final String DEST_FUNC1_ADDR = "0x100100";
private static final String DEST_FUNC2_ADDR = "0x100200";
private static final String DEST_FUNC3_ADDR = "0x1000a0";
private static final String FIXME_ADDR = "0x00100300";
private static final String INDIRECT_CALL_100000 = "0x100000";
private static final String INDIRECT_JUMP_100002 = "0x100002";
private static final String ADD_R0_R0_100004 = "0x100004";
private static final String SUB_R0_R0_100006 = "0x100006";
private static final String SK_EQ_100008 = "0x100008";
private static final String ADD_R0_R0_10000a = "0x10000a";
private static final String SUB_R0_R0_10000c = "0x10000c";
private static final String SUB_R0_R0_10000e = "0x10000e";
private static final String CALL_PLUS_TWO_100010 = "0x100010";
private static final String ADD_R0_R0_100012 = "0x100012";
private static final String SUB_R0_R0_100014 = "0x100014";
private static final String CONDITIONAL_JUMP_100016 = "0x100016";
private static final String ADD_R0_R0_100018 = "0x100018";
private static final String SUB_R0_R0_10001a = "0x10001a";
private static final String CALL_FIXME_10001c = "0x10001c";
private static final String CALL_FUNC1_10001e = "0x10001e";
private static final String USER_TWO_R0_100020 = "0x100020";
private static final String CALLDS_FUNC3_100022 = "0x100022";
private static final String USER_THREE_100024 = "0x100024";
private static final String SUB_R0_R0_100026 = "0x100026";
private static final String ADD_R0_R0_100028 = "0x100028";
private static final String CALLDS_FUNC3_10002a = "0x10002a";
private static final String CALL_FUNC1_10002c = "0x10002c";
private static final String SK_EQ_10002e = "0x10002e";
private static final String USER_ONE_100030 = "0x100030";
private static final String UNCONDITIONAL_JUMP_100032 = "0x100032";
private static final String CONDITIONAL_JUMP_100034 = "0x100034";
private static final String INDIRECT_JUMP_100036 = "0x100036";
private static final String CALL_FUNC1_100038 = "0x100038";
private static final String INDIRECT_CALL_10003a = "0x10003a";
private static final String RETURN_10003c = "0x10003c";
//methods testing the flow overrides all use the same instructions
//easiest to make them fields of this class
private Instruction skeq_10002e;
private Instruction user_one_100030;
private Instruction br_100032;
private Instruction breq_100034;
private Instruction br_r0_100036;
private Instruction call_100038;
private Instruction call_r0_10003a;
private Instruction ret_10003c;
private AddressSpace defaultSpace;
private Address func1Addr;
private Address func2Addr;
private Address fixMeAddr;
private Address func3Addr;
private ReferenceManager refManager;
@Before
public void setUp() throws Exception {
program = buildProgram();
defaultSpace = program.getAddressFactory().getDefaultAddressSpace();
func1Addr = defaultSpace.getAddress(DEST_FUNC1_ADDR);
func2Addr = defaultSpace.getAddress(DEST_FUNC2_ADDR);
fixMeAddr = defaultSpace.getAddress(FIXME_ADDR);
func3Addr = defaultSpace.getAddress(DEST_FUNC3_ADDR);
refManager = program.getReferenceManager();
env = new TestEnv();
}
private ProgramDB buildProgram() throws Exception {
ToyProgramBuilder builder = new ToyProgramBuilder("notepad", true);
builder.createMemory(".text", "0x100000", 0x10000);
builder.createEmptyFunction(null, DEST_FUNC1_ADDR, 2, null);
builder.createReturnInstruction(DEST_FUNC1_ADDR);
builder.createEmptyFunction(null, DEST_FUNC2_ADDR, 2, null);
builder.createReturnInstruction(DEST_FUNC2_ADDR);
builder.createEmptyFunction("fixme", FIXME_ADDR, 2, null);
builder.createReturnInstruction(FIXME_ADDR);
builder.createEmptyFunction(null, DEST_FUNC3_ADDR, 2, null);
builder.createReturnInstruction(DEST_FUNC3_ADDR);
//testIndirectCallOverride
builder.createEmptyFunction("main", INDIRECT_CALL_100000, 0x30, null);
builder.setBytes(INDIRECT_CALL_100000, "f6 00");
//testFallthroughOverrideBranchToInstNext
builder.setBytes(INDIRECT_JUMP_100002, "f0 00");
builder.setBytes(ADD_R0_R0_100004, "c0 00");
builder.setBytes(SUB_R0_R0_100006, "c1 00");
//testFallthoughOverrideBranchToInstNext2
builder.setBytes(SK_EQ_100008, "80 00");
builder.setBytes(ADD_R0_R0_10000a, "c0 00");
builder.setBytes(SUB_R0_R0_10000c, "c1 00");
builder.setBytes(SUB_R0_R0_10000e, "c1 00");
//testFlowOverridePrimacy
builder.setBytes(CALL_PLUS_TWO_100010, "f8 02");
builder.setBytes(ADD_R0_R0_100012, "c0 00");
builder.setBytes(SUB_R0_R0_100014, "c1 00");
//testConditionalJumpOverride
builder.setBytes(CONDITIONAL_JUMP_100016, "e0 40");
builder.setBytes(ADD_R0_R0_100018, "c0 00");
builder.setBytes(SUB_R0_R0_10001a, "c1 00");
//testSimpleRefOverride
builder.setBytes(CALL_FIXME_10001c, "fa e4");
builder.setBytes(CALL_FUNC1_10001e, "f8 e2");
//testCallotherCallOverride
//testCallotherJumpOverride
builder.setBytes(USER_TWO_R0_100020, "a2 00");
//testFallthroughOverridesAndDelaySlots
//testOverridingRefAndDelaySlots
builder.setBytes(CALLDS_FUNC3_100022, "f5 7e");
builder.setBytes(USER_THREE_100024, "a3 00");
builder.setBytes(SUB_R0_R0_100026, "c1 00");
builder.setBytes(ADD_R0_R0_100028, "c0 00");
//testFlowOverridesAndDelaySlots
//testSimpleRefsAndDelaySlots
builder.setBytes(CALLDS_FUNC3_10002a, "f5 76");
builder.setBytes(CALL_FUNC1_10002c, "f8 d4");
//testBranchOverride
builder.setBytes(SK_EQ_10002e, "80 00");
builder.setBytes(USER_ONE_100030, "a1 00");
builder.setBytes(UNCONDITIONAL_JUMP_100032, "e0 47");
builder.setBytes(CONDITIONAL_JUMP_100034, "e0 40");
builder.setBytes(INDIRECT_JUMP_100036, "f0 07");
builder.setBytes(CALL_FUNC1_100038, "f8 c8");
builder.setBytes(INDIRECT_CALL_10003a, "f6 00");
builder.setBytes(RETURN_10003c, "f4 00");
builder.disassemble(INDIRECT_CALL_100000, 0x3e, false);
return builder.getProgram();
}
@After
public void tearDown() throws Exception {
env.dispose();
}
/**
* Tests that a CALL_OVERRIDE_UNCONDITIONAL reference:
* 1) converts a CALLIND op to a CALL op
* 2) changes the call target
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testIndirectCallOverride() throws AddressFormatException {
//verify the instructions needed for the test
Address indirectCallAddr = defaultSpace.getAddress(INDIRECT_CALL_100000);
Instruction indirectCall = program.getListing().getInstructionAt(indirectCallAddr);
assertNotNull(indirectCall);
assertEquals("call r0", indirectCall.toString());
PcodeOp[] unmodified = indirectCall.getPcode(false);
assertTrue(unmodified[0].getOpcode() == PcodeOp.COPY); //save return address to lr
assertTrue(unmodified[1].getOpcode() == PcodeOp.CALLIND); //indirect call
//no overrides applied, pcode should be the same whether or not overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode(true)));
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode()));
//add a non-primary CALL_OVERRIDE_UNCONDITIONAL reference
int id = program.startTransaction("test");
Reference overrideRef = refManager.addMemoryReference(indirectCallAddr, func1Addr,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(overrideRef, false);
program.endTransaction(id, true);
//no modifications to pcode since the reference is not primary
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode(true)));
//make reference primary
id = program.startTransaction("test");
refManager.setPrimary(overrideRef, true);
program.endTransaction(id, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode()));
//verify that the CALLIND op has been changed to a CALL op
//with call target func1Addr
PcodeOp[] overridden = indirectCall.getPcode(true);
assertFalse(equalPcodeOpArrays(unmodified, overridden));
assertEquals(unmodified.length, overridden.length);
assertEquals(unmodified.length, 2);
assertTrue(equalPcodeOps(unmodified[0], overridden[0]));
PcodeOp callind = unmodified[1];
PcodeOp call = overridden[1];
assertNull(callind.getOutput());
assertNull(call.getOutput());
assertTrue(callind.getOpcode() == PcodeOp.CALLIND);
assertTrue(call.getOpcode() == PcodeOp.CALL);
assertTrue(callind.getNumInputs() == 1);
assertTrue(call.getNumInputs() == 1);
assertTrue(callind.getInput(0).getAddress().isRegisterAddress());
assertTrue(call.getInput(0).getAddress().isMemoryAddress());
assertTrue(call.getInput(0).getOffset() == func1Addr.getOffset());
//add another primary CALL_OVERRIDE_UNCONDITIONAL reference
//pcode should be unmodified: override only active if exactly one primary reference
id = program.startTransaction("test");
overrideRef = refManager.addMemoryReference(indirectCallAddr, func2Addr,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(overrideRef, true);
program.endTransaction(id, true);
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode(true)));
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, indirectCall.getPcode()));
}
/**
* Tests that a fallthrough override modifies branches to the next instruction
* (e.g., from a {@code goto inst_next;}
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testFallthroughOverrideBranchToInstNext() throws AddressFormatException {
//verify the instructions needed for the test
Address indirectCallAddr = defaultSpace.getAddress(INDIRECT_JUMP_100002);
Instruction indirectJump = program.getListing().getInstructionAt(indirectCallAddr);
assertNotNull(indirectJump);
assertEquals("breq r0", indirectJump.toString());
Address addAddr = defaultSpace.getAddress(ADD_R0_R0_100004);
Instruction add = program.getListing().getInstructionAt(addAddr);
assertNotNull(add);
assertEquals("add r0,r0", add.toString());
Address subAddr = defaultSpace.getAddress(SUB_R0_R0_100006);
Instruction sub = program.getListing().getInstructionAt(subAddr);
assertNotNull(sub);
assertEquals("sub r0,r0", sub.toString());
//verify that requesting overrides when there are none is the same as not
//requesting overrides
assertTrue(equalPcodeOpArrays(indirectJump.getPcode(true), indirectJump.getPcode(false)));
/*
* verify that the fallthrough override:
* 1) changes the destination of the CBRANCH op (which is from a goto inst_next)
* 2) appends a BRANCH op with destination subAddr to the pcode for breq r0
* 3) makes no other changes
*/
PcodeOp[] unmodified = indirectJump.getPcode(false);
assertTrue(unmodified.length == 3);
assertTrue(unmodified[0].getOpcode() == PcodeOp.BOOL_NEGATE); //negate condition
assertTrue(unmodified[1].getOpcode() == PcodeOp.CBRANCH); //CBRANCH to inst_next
assertTrue(unmodified[2].getOpcode() == PcodeOp.BRANCHIND); //BRANCHIND r0
//apply a fallthrough override
int tid = program.startTransaction("test");
indirectJump.setFallThrough(subAddr);
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, indirectJump.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, indirectJump.getPcode()));
PcodeOp[] overridden = indirectJump.getPcode(true);
assertTrue(overridden.length == unmodified.length + 1);
//shouldn't change first op
assertTrue(equalPcodeOps(overridden[0], unmodified[0]));
//second op (CBRANCH to inst_next) needs destination updated
PcodeOp unmodifiedCbranch = unmodified[1];
PcodeOp modifiedCbranch = overridden[1];
assertNull(unmodifiedCbranch.getOutput());
assertNull(modifiedCbranch.getOutput());
assertTrue(unmodifiedCbranch.getOpcode() == modifiedCbranch.getOpcode());
assertTrue(unmodifiedCbranch.getNumInputs() == 2);
assertTrue(modifiedCbranch.getNumInputs() == 2);
assertTrue(unmodifiedCbranch.getInput(0).isAddress());
assertTrue(unmodifiedCbranch.getInput(0).getOffset() == addAddr.getOffset());
assertTrue(modifiedCbranch.getInput(0).isAddress());
assertTrue(modifiedCbranch.getInput(0).getOffset() == subAddr.getOffset()); //updated dest
assertEquals(unmodifiedCbranch.getInput(1), modifiedCbranch.getInput(1));
//shouldn't change third op
assertTrue(equalPcodeOps(overridden[2], unmodified[2]));
//verify appended branch
PcodeOp appendedBranch = overridden[3];
assertNull(appendedBranch.getOutput());
assertTrue(appendedBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(appendedBranch.getNumInputs() == 1);
assertTrue(appendedBranch.getInput(0).isAddress());
assertTrue(appendedBranch.getInput(0).getOffset() == subAddr.getOffset());
}
/**
* Test that a fallthrough override does *not* modify branches to inst_next2
* Test that the BRANCH op appended by a fallthrough override *is* subject to
* further modification by a JUMP_OVERRIDE_UNCONDITIONAL reference
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testFallthoughOverrideBranchToInstNext2() throws AddressFormatException {
//verify the instructions needed for the test
Address skip2Addr = defaultSpace.getAddress(SK_EQ_100008);
Instruction skip2 = program.getListing().getInstructionAt(skip2Addr);
assertNotNull(skip2);
assertEquals("skeq", skip2.toString());
Address addAddr = defaultSpace.getAddress(ADD_R0_R0_10000a);
Instruction add = program.getListing().getInstructionAt(addAddr);
assertNotNull(add);
assertEquals("add r0,r0", add.toString());
Address subAddr2 = defaultSpace.getAddress(SUB_R0_R0_10000c);
Instruction sub2 = program.getListing().getInstructionAt(subAddr2);
assertNotNull(sub2);
assertEquals("sub r0,r0", sub2.toString());
Address subAddr3 = defaultSpace.getAddress(SUB_R0_R0_10000e);
Instruction sub3 = program.getListing().getInstructionAt(subAddr3);
assertNotNull(sub3);
assertEquals("sub r0,r0", sub3.toString());
//get the pcode before the fallthrough override
PcodeOp[] beforeFallthroughOverride = skip2.getPcode(false);
assertTrue(beforeFallthroughOverride.length == 1);
assertTrue(beforeFallthroughOverride[0].getOpcode() == PcodeOp.CBRANCH); //CBRANCH to inst_next2
//verify that requesting overrides when there are none is the same as not requesting overrides
assertTrue(equalPcodeOpArrays(skip2.getPcode(true), skip2.getPcode(false)));
//apply the fallthrough override
int tid = program.startTransaction("test");
skip2.setFallThrough(subAddr3);
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(beforeFallthroughOverride, skip2.getPcode(false)));
assertTrue(equalPcodeOpArrays(beforeFallthroughOverride, skip2.getPcode()));
//get the overridden pcode
PcodeOp[] afterFallthroughOverride = skip2.getPcode(true);
assertTrue(afterFallthroughOverride.length == beforeFallthroughOverride.length + 1);
//verify that the CBRANCH to inst_next2 is *not* modified
assertTrue(beforeFallthroughOverride[0].getOpcode() == PcodeOp.CBRANCH);
assertTrue(equalPcodeOps(beforeFallthroughOverride[0], afterFallthroughOverride[0]));
//verify the appended branch
PcodeOp appendedBranch = afterFallthroughOverride[1];
assertNull(appendedBranch.getOutput());
assertTrue(appendedBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(appendedBranch.getNumInputs() == 1);
assertTrue(appendedBranch.getInput(0).isAddress());
assertTrue(appendedBranch.getInput(0).getOffset() == subAddr3.getOffset());
//create primary overriding reference and fallthrough override on add
int id = program.startTransaction("test");
Reference overrideRef = refManager.addMemoryReference(addAddr, func2Addr,
RefType.JUMP_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(overrideRef, true);
add.setFallThrough(subAddr3);
program.endTransaction(id, true);
//verify that overrideRef changes the target of the appended branch
//and makes no other changes
PcodeOp[] unmodifiedAdd = add.getPcode(false);
PcodeOp[] overriddenAdd = add.getPcode(true);
assertTrue(overriddenAdd.length == unmodifiedAdd.length + 1);
for (int i = 0; i < unmodifiedAdd.length; ++i) {
assertTrue(equalPcodeOps(unmodifiedAdd[i], overriddenAdd[i]));
}
PcodeOp overriddenBranch = overriddenAdd[overriddenAdd.length - 1];
assertTrue(overriddenBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(overriddenBranch.getInput(0).getOffset() == func2Addr.getOffset());
}
/**
* Tests that pcode ops introduced by a flow override can be affected by fallthrough overrides
* and overriding references.
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testFlowOverridePrimacy() throws AddressFormatException {
//verify the instructions needed for the test
Address callAddr = defaultSpace.getAddress(CALL_PLUS_TWO_100010);
Instruction call = program.getListing().getInstructionAt(callAddr);
assertNotNull(call);
assertEquals("call 0x00100012", call.toString());
Address addAddr = defaultSpace.getAddress(ADD_R0_R0_100012);
Instruction add = program.getListing().getInstructionAt(addAddr);
assertNotNull(add);
assertEquals("add r0,r0", add.toString());
Address subAddr = defaultSpace.getAddress(SUB_R0_R0_100014);
Instruction sub = program.getListing().getInstructionAt(subAddr);
assertNotNull(sub);
assertEquals("sub r0,r0", sub.toString());
//get unmodified Pcode
PcodeOp[] unmodified = call.getPcode(false);
assertTrue(unmodified.length == 2);
assertTrue(unmodified[0].getOpcode() == PcodeOp.COPY); //save return address to lr
assertTrue(unmodified[1].getOpcode() == PcodeOp.CALL); //perform call
//verify that requesting overrides has no effect on the pcode before any overrides
//are applied
assertTrue(equalPcodeOpArrays(call.getPcode(true), call.getPcode(false)));
//apply a CALL_OVERRIDE_UNCONDITIONAL reference and verify that it changes the
//call target
//place it on operand 0 so that the default reference to the call target
//is made not primary
int id = program.startTransaction("test");
Reference callOverrideRef = refManager.addMemoryReference(callAddr, func2Addr,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(callOverrideRef, true);
program.endTransaction(id, true);
PcodeOp[] callOverride = call.getPcode(true);
assertTrue(callOverride[1].getOpcode() == PcodeOp.CALL);
assertTrue(callOverride[1].getInput(0).getOffset() == func2Addr.getOffset());
//deactivate the call override by setting the reference to non-primary
id = program.startTransaction("test");
refManager.setPrimary(callOverrideRef, false);
program.endTransaction(id, true);
//verify that the pcode is not changed
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(true)));
//apply flow override
int tid = program.startTransaction("test");
call.setFlowOverride(FlowOverride.BRANCH);
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode()));
//verify the flow override occurred
PcodeOp[] flow = call.getPcode(true);
assertTrue(flow.length == unmodified.length);
//first op saves the return address to lr; shouldn't change
assertTrue(equalPcodeOps(unmodified[0], flow[0]));
//verify that the flow override changed the CALL to a BRANCH
//and made no other changes
PcodeOp callOp = unmodified[1];
PcodeOp branchOp = flow[1];
assertTrue(branchOp.getOpcode() == PcodeOp.BRANCH);
assertTrue(equalInputsAndOutput(branchOp, callOp));
//set the CALL_OVERRIDE_CALL reference to primary
id = program.startTransaction("test");
refManager.setPrimary(callOverrideRef, true);
program.endTransaction(id, true);
//verify that a primary CALL_OVERRIDE_CALL reference has no effect since
//the flow override has precedence
assertTrue(equalPcodeOpArrays(flow, call.getPcode(true)));
//delete callOverrideRef - no longer needed
//note: simply setting it to non-primary can cause complications later in
//this test since removing a flow override updates existing references
id = program.startTransaction("test");
refManager.delete(callOverrideRef);
program.endTransaction(id, true);
//apply fallthrough override
tid = program.startTransaction("test");
call.setFallThrough(subAddr);
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode()));
PcodeOp[] flowFallthrough = call.getPcode(true);
//verify that the first op hasn't changed
assertTrue(equalPcodeOps(unmodified[0], flowFallthrough[0]));
//verify that the target of the branch that was a call has changed
PcodeOp adjustedBranch = flowFallthrough[1];
assertTrue(Objects.equals(branchOp.getOutput(), adjustedBranch.getOutput()));
assertTrue(adjustedBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(adjustedBranch.getNumInputs() == 1);
assertTrue(adjustedBranch.getInput(0).isAddress());
assertTrue(adjustedBranch.getInput(0).getOffset() == subAddr.getOffset());
assertTrue(branchOp.getInput(0).isAddress());
assertTrue(branchOp.getInput(0).getOffset() == addAddr.getOffset());
//verify that exactly one op has been appended
assertTrue(flowFallthrough.length == unmodified.length + 1);
//verify the appended branch
PcodeOp appendedBranch = flowFallthrough[2];
assertNull(appendedBranch.getOutput());
assertTrue(appendedBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(appendedBranch.getNumInputs() == 1);
assertTrue(appendedBranch.getInput(0).isAddress());
assertTrue(appendedBranch.getInput(0).getOffset() == subAddr.getOffset());
//apply an overriding jump reference
tid = program.startTransaction("test");
Reference jumpOverrideRef = refManager.addMemoryReference(callAddr, func1Addr,
RefType.JUMP_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(jumpOverrideRef, true);
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode()));
//ref should change the appended BRANCH since the fallthrough override has precedence
//on the adjusted branch
PcodeOp[] flowFallthroughRef = call.getPcode(true);
assertEquals(flowFallthroughRef.length, unmodified.length + 1);
assertTrue(equalPcodeOps(flowFallthrough[0], flowFallthroughRef[0])); //save return address
assertTrue(equalPcodeOps(flowFallthrough[1], flowFallthroughRef[1])); //adjusted branch
PcodeOp appended = flowFallthroughRef[2]; //appended branch
assertNull(appended.getOutput());
assertTrue(appended.getOpcode() == PcodeOp.BRANCH);
assertTrue(appended.getNumInputs() == 1);
assertTrue(appended.getInput(0).isAddress());
assertTrue(appended.getInput(0).getOffset() == func1Addr.getOffset());
//remove fallthrough override
tid = program.startTransaction("test");
call.clearFallThroughOverride();
program.endTransaction(tid, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, call.getPcode()));
PcodeOp[] flowRef = call.getPcode(true);
assertTrue(flowRef.length == unmodified.length);
//first op shouldn't change
assertTrue(equalPcodeOps(flowRef[0], unmodified[0]));
//overriding jump reference should now change BRANCH from flow override
PcodeOp refBranch = flowRef[1];
assertNull(refBranch.getOutput());
assertTrue(refBranch.getOpcode() == PcodeOp.BRANCH);
assertTrue(refBranch.getNumInputs() == 1);
assertTrue(refBranch.getInput(0).isAddress());
assertTrue(refBranch.getInput(0).getOffset() == func1Addr.getOffset());
//remove flow override
tid = program.startTransaction("test");
call.setFlowOverride(FlowOverride.NONE);
program.endTransaction(tid, true);
//overriding jump ref should do nothing since it doesn't apply to CALL ops
PcodeOp[] ref = call.getPcode(true);
assertTrue(equalPcodeOpArrays(ref, unmodified));
}
/**
* Tests that a single primary JUMP_OVERRIDE_UNCONDITIONAL reference:
* 1) changes a CBRANCH op to a BRANCH op
* 2) changes the jump target
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testConditionalJumpOverride() throws AddressFormatException {
//verify the instructions needed for the test
Address condJumpAddr = defaultSpace.getAddress(CONDITIONAL_JUMP_100016);
Instruction condJump = program.getListing().getInstructionAt(condJumpAddr);
assertNotNull(condJump);
assertEquals("breq 0x0010001a", condJump.toString());
Address addAddr = defaultSpace.getAddress(ADD_R0_R0_100018);
Instruction add = program.getListing().getInstructionAt(addAddr);
assertNotNull(add);
assertEquals("add r0,r0", add.toString());
Address subAddr = defaultSpace.getAddress(SUB_R0_R0_10001a);
Instruction sub = program.getListing().getInstructionAt(subAddr);
assertNotNull(sub);
assertEquals("sub r0,r0", sub.toString());
//verify unmodified pcode
PcodeOp[] noRef = condJump.getPcode(false);
assertTrue(noRef.length == 3);
assertTrue(noRef[0].getOpcode() == PcodeOp.BOOL_NEGATE); //negate condition
assertTrue(noRef[1].getOpcode() == PcodeOp.CBRANCH); //CBRANCH to inst_next
assertTrue(noRef[2].getOpcode() == PcodeOp.BRANCH); //BRANCH to 0x10001a
//verify that requesting overrides when there are none is the same as not
//requesting overriders
assertTrue(equalPcodeOpArrays(condJump.getPcode(true), condJump.getPcode(false)));
//create non-primary overriding reference
int id = program.startTransaction("test");
Reference overrideRef = refManager.addMemoryReference(condJumpAddr, func2Addr,
RefType.JUMP_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(overrideRef, false);
program.endTransaction(id, true);
//verify that pcode is unchanged
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode()));
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode(false)));
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode(true)));
//set the reference to primary
id = program.startTransaction("test");
refManager.setPrimary(overrideRef, true);
program.endTransaction(id, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode(false)));
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode()));
PcodeOp[] overridden = condJump.getPcode(true);
//verify that the CBRANCH op has been changed and that no other ops have changed
assertTrue(overridden.length == noRef.length);
assertTrue(equalPcodeOps(noRef[0], overridden[0]));
assertNull(overridden[1].getOutput());
assertTrue(overridden[1].getOpcode() == PcodeOp.BRANCH);
assertTrue(overridden[1].getInput(0).isAddress());
assertTrue(overridden[1].getInput(0).getOffset() == func2Addr.getOffset());
//note: the 2nd input is left over from the CBRANCH op and should probably be destroyed
assertTrue(overridden[1].getNumInputs() == 2);
assertTrue(equalPcodeOps(noRef[2], overridden[2]));
//apply another primary reference, no overrides should occur
id = program.startTransaction("test");
overrideRef = refManager.addMemoryReference(condJumpAddr, func1Addr,
RefType.JUMP_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(overrideRef, true);
program.endTransaction(id, true);
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode(true)));
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode(false)));
assertTrue(equalPcodeOpArrays(noRef, condJump.getPcode()));
}
/**
* Test that simple call reference overrides (retained for backward compatibility) have
* precedence over CALL_OVERRIDE_UNCONDITIONAL reference overrides, and that neither
* override applies if the call target has a call fixup.
*
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testSimpleRefOverride() throws AddressFormatException {
//verify the instructions needed for the test
Address callFunc1Addr = defaultSpace.getAddress(CALL_FUNC1_10001e);
Instruction callFunc1 = program.getListing().getInstructionAt(callFunc1Addr);
assertNotNull(callFunc1);
assertEquals("call 0x" + func1Addr.toString(), callFunc1.toString());
PcodeOp[] unmodified = callFunc1.getPcode(false);
assertEquals(unmodified.length, 2);
assertTrue(unmodified[0].getOpcode() == PcodeOp.COPY); //save return address in lr
assertTrue(unmodified[1].getOpcode() == PcodeOp.CALL); //call op
//verify that requesting overrides when there aren't any is the same as
//not requesting overrides
assertTrue(equalPcodeOpArrays(callFunc1.getPcode(true), callFunc1.getPcode(false)));
int id = program.startTransaction("test");
Reference simpleCallRef = refManager.addMemoryReference(callFunc1Addr, func2Addr,
RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, 0);
//default reference is primary, so need to set simpleCallRef to primary to unseat it
refManager.setPrimary(simpleCallRef, true);
program.endTransaction(id, true);
//verify that nothing changes with no overrides requested
assertTrue(equalPcodeOpArrays(unmodified, callFunc1.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, callFunc1.getPcode()));
//simple call ref override
PcodeOp[] simpleRefOverride = callFunc1.getPcode(true);
//verify same number of ops
assertEquals(simpleRefOverride.length, unmodified.length);
//verify COPY op not changed
assertTrue(equalPcodeOps(unmodified[0], simpleRefOverride[0]));
//verify the call target changed
assertNull(unmodified[1].getOutput());
assertNull(simpleRefOverride[1].getOutput());
assertTrue(unmodified[1].getOpcode() == simpleRefOverride[1].getOpcode());
assertTrue(unmodified[1].getNumInputs() == simpleRefOverride[1].getNumInputs());
assertTrue(unmodified[1].getInput(0).getOffset() == func1Addr.getOffset());
assertTrue(simpleRefOverride[1].getInput(0).getOffset() == func2Addr.getOffset());
//verify that a simple reference override has precedence over a CALL_OVERRIDE_UNCONDITIONAL
Address main = defaultSpace.getAddress(INDIRECT_CALL_100000);
assertTrue(main.getOffset() == 0x100000);
id = program.startTransaction("test");
//use a different opIndex than simpleCallRef so we can verify what happens
//when both refs are primary
Reference overrideRef = refManager.addMemoryReference(callFunc1Addr, main,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(overrideRef, true);
program.endTransaction(id, true);
//verify nothing changes with no overrides requested
assertTrue(equalPcodeOpArrays(unmodified, callFunc1.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, callFunc1.getPcode()));
//verify that with overrides what you get is simpleRef
PcodeOp[] bothOverrides = callFunc1.getPcode(true);
assertTrue(equalPcodeOpArrays(simpleRefOverride, bothOverrides));
//set simpleRef to non-primary
id = program.startTransaction("test");
refManager.setPrimary(simpleCallRef, false);
program.endTransaction(id, true);
//verify that overrideRef then applies
PcodeOp[] callOverrideOps = callFunc1.getPcode(true);
assertTrue(equalPcodeOps(unmodified[0], callOverrideOps[0]));
assertTrue(callOverrideOps[1].getInput(0).getOffset() == main.getOffset());
Address callFixmeAddr = defaultSpace.getAddress(CALL_FIXME_10001c);
Instruction callFixme = program.getListing().getInstructionAt(callFixmeAddr);
assertNotNull(callFixme);
assertEquals("call 0x" + fixMeAddr.toString(), callFixme.toString());
unmodified = callFixme.getPcode(false);
//add a simple ref override on a call to a function with a call fixup
id = program.startTransaction("test");
simpleCallRef = refManager.addMemoryReference(callFixmeAddr, func2Addr,
RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, 0);
//default reference is primary; set simpleCallRef to primary to unseat it
refManager.setPrimary(simpleCallRef, true);
program.endTransaction(id, true);
//verify that nothing changes with no overrides requested
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode()));
//verify that nothing changes WITH overrides requested since "fixme" has a
//call fixup
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode(true)));
//add a CALL_OVERRIDE_UNCONDITIONAL reference on a call to a function with
//a call fixup
id = program.startTransaction("test");
overrideRef = refManager.addMemoryReference(callFixmeAddr, main,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(overrideRef, false);
program.endTransaction(id, true);
//verify that nothing changes with no overrides requested
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode()));
//verify that nothing changes WITH overrides requested since "fixme" has a
//call fixup
assertTrue(equalPcodeOpArrays(unmodified, callFixme.getPcode(true)));
}
/**
* Tests that a single primary CALLOTHER_OVERRIDE_CALL reference:
* 1) Changes the first CALLOTHER op encountered as follows:
* a) CALLOTHER op -> CALL op
* b) this new CALL op is not affected by simple reference overrides
* or CALL_OVERRIDE_UNCONDITIONAL references
* c) input 0 becomes the CALL target
* d) other inputs destroyed
* 2) Does not change subsequent CALLOTHER ops associated with the same instruction
* @throws AddressFormatException if {@code AddressSpace.getAddress()} throws it
*/
@Test
public void testCallotherCallOverride() throws AddressFormatException {
//verify the instructions need for the test
Address userTwoAddr = defaultSpace.getAddress(USER_TWO_R0_100020);
Instruction userTwo = program.getListing().getInstructionAt(userTwoAddr);
assertNotNull(userTwo);
assertEquals("user_two r0", userTwo.toString());
PcodeOp[] unmodified = userTwo.getPcode(false);
assertNull(unmodified[0].getOutput());
assertTrue(unmodified[0].getOpcode() == PcodeOp.CALLOTHER); //pcodeop_two(rs)
assertTrue(unmodified[0].getNumInputs() == 2); //callother op index, rs
assertNull(unmodified[1].getOutput());
assertTrue(unmodified[1].getOpcode() == PcodeOp.CALLOTHER); //pcodeop_three()
assertTrue(unmodified[1].getNumInputs() == 1); //callother op index
//lay down CALLOTHER_OVERRIDE_CALL ref as non-primary
int id = program.startTransaction("test");
Reference callotherOverrideRef1 = refManager.addMemoryReference(userTwoAddr, func1Addr,
RefType.CALLOTHER_OVERRIDE_CALL, SourceType.USER_DEFINED, -1);
refManager.setPrimary(callotherOverrideRef1, false);
program.endTransaction(id, true);
//nothing should change regardless of whether overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(true)));
//make the reference primary
id = program.startTransaction("test");
refManager.setPrimary(callotherOverrideRef1, true);
program.endTransaction(id, true);
//nothing should change without requesting overrides overrides
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
PcodeOp[] modified = userTwo.getPcode(true);
//first CALLOTHER op should be changed to a CALL call target as the only input
assertNull(modified[0].getOutput());
assertTrue(modified[0].getOpcode() == PcodeOp.CALL);
assertTrue(modified[0].getNumInputs() == 1);
assertTrue(modified[0].getInput(0).isAddress());
assertTrue(modified[0].getInput(0).getOffset() == func1Addr.getOffset());
//second CALLOTHER op should be unchanged
assertTrue(equalPcodeOps(modified[1], unmodified[1]));
//add a primary simple call ref
id = program.startTransaction("test");
Reference simpleCallRef = refManager.addMemoryReference(userTwoAddr, func2Addr,
RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(simpleCallRef, true);
program.endTransaction(id, true);
//verify that nothing changes when overrides are not requested
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
//verify that this reference does not change the call target
assertTrue(equalPcodeOpArrays(modified, userTwo.getPcode(true)));
//remove simpleCallRef and add a CALL_OVERRIDE_UNCONDITIONAL reference
id = program.startTransaction("test");
Reference overrideCallRef = refManager.addMemoryReference(userTwoAddr, func2Addr,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
refManager.delete(simpleCallRef);
refManager.setPrimary(overrideCallRef, true);
program.endTransaction(id, true);
//verify that nothing changes when overrides are not requested
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
//verify that this reference does not change the call target
assertTrue(equalPcodeOpArrays(modified, userTwo.getPcode(true)));
//remove overrideCallRef and add another primary CALLOTHER_OVERRIDE_CALL reference
id = program.startTransaction("test");
Reference callotherOverrideRef2 = refManager.addMemoryReference(userTwoAddr, func1Addr,
RefType.CALLOTHER_OVERRIDE_CALL, SourceType.USER_DEFINED, 0);
refManager.delete(overrideCallRef);
refManager.setPrimary(callotherOverrideRef2, true);
program.endTransaction(id, true);
//two primary references CALLOTHER_OVERRIDE_CALL references: overrides should not happen
assertTrue(equalPcodeOpArrays(userTwo.getPcode(true), unmodified));
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
}
/**
* Tests that a single primary CALLOTHER_OVERRIDE_JUMP reference:
* 1) Changes the first CALLOTHER op encountered as follows:
* a) CALLOTHER op -> BRANCH op
* b) new BRANCH op not affected by JUMP_OVERRIDE_UNCONDITIONAL references
* c) input 0 becomes the branch target
* d) other inputs untouched
* 2) Does not change subsequent CALLOTHER ops corresponding to the same instruction
* 3) Is pre-empted by a single primary CALLOTHER_OVERRIDE_CALL reference
* @throws AddressFormatException if {@code AddressSpace.getAddress()} throws it
*/
@Test
public void testCallotherJumpOverride() throws AddressFormatException {
//verify the instructions needed for the test
Address userTwoAddr = defaultSpace.getAddress(USER_TWO_R0_100020);
Instruction userTwo = program.getListing().getInstructionAt(userTwoAddr);
assertNotNull(userTwo);
assertEquals("user_two r0", userTwo.toString());
PcodeOp[] unmodified = userTwo.getPcode(false);
assertNull(unmodified[0].getOutput());
assertTrue(unmodified[0].getOpcode() == PcodeOp.CALLOTHER); //pcodeop_two(rs)
assertTrue(unmodified[0].getNumInputs() == 2); //callother op index, rs
assertNull(unmodified[1].getOutput());
assertTrue(unmodified[1].getOpcode() == PcodeOp.CALLOTHER); //pcodeop_three()
assertTrue(unmodified[1].getNumInputs() == 1); //callother op index
//lay down CALLOTHER_OVERRIDE_JUMP ref as non-primary
int id = program.startTransaction("test");
Reference callotherOverrideJump1 = refManager.addMemoryReference(userTwoAddr, func1Addr,
RefType.CALLOTHER_OVERRIDE_JUMP, SourceType.USER_DEFINED, -1);
refManager.setPrimary(callotherOverrideJump1, false);
program.endTransaction(id, true);
//nothing should change regardless of whether overrides are requested
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(true)));
//make the reference primary
id = program.startTransaction("test");
refManager.setPrimary(callotherOverrideJump1, true);
program.endTransaction(id, true);
//nothing should change without overrides
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
PcodeOp[] modified = userTwo.getPcode(true);
//verify first CALLOTHER changed to a BRANCH
assertNull(modified[0].getOutput());
assertTrue(modified[0].getOpcode() == PcodeOp.BRANCH);
assertTrue(modified[0].getNumInputs() == 2); //should probably destroy second input...
assertTrue(modified[0].getInput(0).isAddress());
assertTrue(modified[0].getInput(0).getOffset() == func1Addr.getOffset());
//verify that second CALLOTHER not changed
assertTrue(equalPcodeOps(unmodified[1], modified[1]));
//add a primary JUMP_OVERRIDE_UNCONDITIONAL reference
id = program.startTransaction("test");
Reference jumpOverrideRef = refManager.addMemoryReference(userTwoAddr, func2Addr,
RefType.JUMP_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(jumpOverrideRef, true);
program.endTransaction(id, true);
//nothing should change without overrides
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
//with overrides, jumpOverrideRef should not do anything
assertTrue(equalPcodeOpArrays(modified, userTwo.getPcode(true)));
//set a primary CALLOTHER_OVERRIDE_CALL reference at the same address
//delete jumpOverrideRef
id = program.startTransaction("test");
Reference callotherOverrideCall2 = refManager.addMemoryReference(userTwoAddr, func1Addr,
RefType.CALLOTHER_OVERRIDE_CALL, SourceType.USER_DEFINED, 0);
refManager.delete(jumpOverrideRef);
refManager.setPrimary(callotherOverrideCall2, true);
program.endTransaction(id, true);
//verify that the CALLOTHER_OVERRIDE_CALL reference has precedence
PcodeOp[] precedence = userTwo.getPcode(true);
assertNull(precedence[0].getOutput());
assertTrue(precedence[0].getOpcode() == PcodeOp.CALL);
assertTrue(precedence[0].getNumInputs() == 1);
assertTrue(precedence[0].getInput(0).isAddress());
assertTrue(precedence[0].getInput(0).getOffset() == func1Addr.getOffset());
assertTrue(equalPcodeOps(precedence[1], unmodified[1]));
//nothing should change without overrides
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
//add another primary CALL_OVERRIDE_JUMP reference and set the
//CALLOTHER_OVERRIDE_CALL ref to non-primary
id = program.startTransaction("test");
Reference callotherOverrideJump3 = refManager.addMemoryReference(userTwoAddr, func1Addr,
RefType.CALLOTHER_OVERRIDE_JUMP, SourceType.USER_DEFINED, 0);
refManager.setPrimary(callotherOverrideCall2, false);
refManager.setPrimary(callotherOverrideJump3, true);
program.endTransaction(id, true);
//verify that nothing changes, with or without requesting overrides
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode()));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(false)));
assertTrue(equalPcodeOpArrays(unmodified, userTwo.getPcode(true)));
}
// callds Rel8 { delayslot(1); lr = inst_next; call Rel8; }
/**
* Tests that fallthrough overrides:
* 1) work as expected when applied to instructions with delay slots
* 2) have no effect when applied to instructions in delay slots
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testFallthroughOverridesAndDelaySlots() throws AddressFormatException {
//verify that the test program contains the instructions for the test
Address calldsFunc3Addr = defaultSpace.getAddress(CALLDS_FUNC3_100022);
Instruction calldsFunc3 = program.getListing().getInstructionAt(calldsFunc3Addr);
assertNotNull(calldsFunc3);
assertEquals("callds 0x" + func3Addr.toString(), calldsFunc3.toString());
Address user3Addr = defaultSpace.getAddress(USER_THREE_100024);
Instruction user3 = program.getListing().getInstructionAt(user3Addr);
assertNotNull(user3);
assertEquals("_user_three", user3.toString());
Address subAddr = defaultSpace.getAddress(SUB_R0_R0_100026);
Instruction sub = program.getListing().getInstructionAt(subAddr);
assertNotNull(sub);
assertEquals("sub r0,r0", sub.toString());
Address addAddr = defaultSpace.getAddress(ADD_R0_R0_100028);
Instruction add = program.getListing().getInstructionAt(addAddr);
assertNotNull(add);
assertEquals("add r0,r0", add.toString());
//get the pcode for the callds instruction before any overrides applied
PcodeOp[] calldsUnmodified = calldsFunc3.getPcode(false);
assertTrue(calldsUnmodified.length == 3);
assertTrue(calldsUnmodified[0].getOpcode() == PcodeOp.CALLOTHER); //from delay slot
assertTrue(calldsUnmodified[1].getOpcode() == PcodeOp.COPY); //save return address to lr
assertTrue(calldsUnmodified[1].getNumInputs() == 1);
//return address should be address of instruction after instruction in delay slot
assertTrue(calldsUnmodified[1].getInput(0).getOffset() == subAddr.getOffset());
assertTrue(calldsUnmodified[2].getOpcode() == PcodeOp.CALL);
//get the pcode for the instruction in the delay slot before any overrides applied
PcodeOp[] user3Unmodified = user3.getPcode(false);
assertTrue(user3Unmodified.length == 1);
assertTrue(user3Unmodified[0].getOpcode() == PcodeOp.CALLOTHER);
//test that requesting overrides when there aren't any is the same as not requesting
//overrides
assertTrue(equalPcodeOpArrays(calldsFunc3.getPcode(false), calldsFunc3.getPcode(true)));
assertTrue(equalPcodeOpArrays(user3.getPcode(false), user3.getPcode(true)));
//apply fallthrough override on instruction in delay slot
int tid = program.startTransaction("test");
user3.setFallThrough(addAddr);
program.endTransaction(tid, true);
//verify that there are no changes if you request no overrides
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(false)));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode()));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(false)));
//verify that the fallthrough override does nothing to the instruction in the delay slot
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(true)));
//clear the fallthrough override on the instruction in the delay slot
tid = program.startTransaction("test");
user3.clearFallThroughOverride();
program.endTransaction(tid, true);
//apply fallthrough override on instruction with a delay slot
tid = program.startTransaction("test");
calldsFunc3.setFallThrough(addAddr);
program.endTransaction(tid, true);
//verify that there are no changes if you request no overrides
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(false)));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode()));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(false)));
PcodeOp[] calldsModified = calldsFunc3.getPcode(true);
//verify that a BRANCH op is appended to the pcode for callds
assertTrue(calldsModified.length == calldsUnmodified.length + 1);
for (int i = 0; i < calldsUnmodified.length; ++i) {
assertTrue(equalPcodeOps(calldsModified[i], calldsUnmodified[i]));
}
assertTrue(calldsModified[3].getOpcode() == PcodeOp.BRANCH);
assertTrue(calldsModified[3].getInput(0).isAddress());
assertTrue(calldsModified[3].getInput(0).getOffset() == addAddr.getOffset());
}
/**
* Test that CALLOTHER_CALL_OVERRIDE references:
* 1) When placed on an instruction *with* a delay slot:
* a) changes a CALLOTHER op in the pcode for the instruction with the delay slot
* b) do not change a CALLOTHER op in the pcode for the instruction in the delay slot
* when generated directly
* Note: the callds instruction in this test has the delayslot directive before
* any other pcode and does not itself contain a CALLOTHER op
* 2) When placed on an instruction *in* a delay slot
* a) do not change the pcode for the instruction with the delay slot
* b) changes a CALLOTHER op in the pcode for the instruction in the delay slot when
* generated directly
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testOverridingRefAndDelaySlots() throws AddressFormatException {
//verify that the test program contains the instructions for the test
Address calldsFunc3Addr = defaultSpace.getAddress(CALLDS_FUNC3_100022);
Instruction calldsFunc3 = program.getListing().getInstructionAt(calldsFunc3Addr);
assertNotNull(calldsFunc3);
assertEquals("callds 0x" + func3Addr.toString(), calldsFunc3.toString());
Address user3Addr = defaultSpace.getAddress(USER_THREE_100024);
Instruction user3 = program.getListing().getInstructionAt(user3Addr);
assertNotNull(user3);
assertEquals("_user_three", user3.toString());
//grab pcode for both instructions before any overrides applied
PcodeOp[] calldsUnmodified = calldsFunc3.getPcode(false);
PcodeOp[] user3Unmodified = user3.getPcode(false);
//verify that requesting overrides when there aren't any is the same as
//not requesting overrides
assertTrue(equalPcodeOpArrays(calldsFunc3.getPcode(false), calldsFunc3.getPcode(true)));
assertTrue(equalPcodeOpArrays(user3.getPcode(false), user3.getPcode(true)));
//lay down a primary CALLOTHER_OVERRIDE_CALL reference on the instruction in the delay slot
int id = program.startTransaction("test");
Reference user3OverrideRef = refManager.addMemoryReference(user3Addr, func1Addr,
RefType.CALLOTHER_OVERRIDE_CALL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(user3OverrideRef, true);
program.endTransaction(id, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(false)));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode()));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(false)));
//verify that the override doesn't change the pcode for the instruction with the delay slot
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(true)));
//verify that the override does change the pcode for the instruction in the delay slot
PcodeOp[] user3Modified = user3.getPcode(true);
assertTrue(user3Modified.length == 1);
assertNull(user3Modified[0].getOutput());
assertTrue(user3Modified[0].getOpcode() == PcodeOp.CALL);
assertTrue(user3Modified[0].getNumInputs() == 1);
assertTrue(user3Modified[0].getInput(0).isAddress());
assertTrue(user3Modified[0].getInput(0).getOffset() == func1Addr.getOffset());
//set user3OverrideRef to non-primary and create a primary CALLOTHER_OVERRIDE_CALL
//reference on callds
id = program.startTransaction("test");
refManager.setPrimary(user3OverrideRef, false);
Reference calldsOverrideRef = refManager.addMemoryReference(calldsFunc3Addr, func1Addr,
RefType.CALLOTHER_OVERRIDE_CALL, SourceType.USER_DEFINED, 0);
refManager.setPrimary(calldsOverrideRef, true);
program.endTransaction(id, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(false)));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode()));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(false)));
//verify that nothing changes for the instruction in the delay slot if overrides are requested
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(true)));
//verify that the CALLOTHER_OVERRIDE_CALL reference on callds DOES change the
//CALLOTHER op from the delay slot to a CALL in the pcode for callds
PcodeOp[] calldsModified = calldsFunc3.getPcode(true);
assertTrue(calldsModified.length == calldsUnmodified.length);
assertNull(calldsModified[0].getOutput());
assertTrue(calldsModified[0].getOpcode() == PcodeOp.CALL);
assertTrue(calldsModified[0].getNumInputs() == 1);
assertTrue(calldsModified[0].getInput(0).isAddress());
assertTrue(calldsModified[0].getInput(0).getOffset() == func1Addr.getOffset());
//verify that the rest of the pcode ops for callds are unchanged
for (int i = 1; i < calldsModified.length; ++i) {
assertTrue(equalPcodeOps(calldsModified[i], calldsUnmodified[i]));
}
//set the CALLOTHER_OVERRIDE_CALL reference on user3 to primary, so that
//both user3 and callds have primary CALLOTHER_OVERRIDE_CALL refs
id = program.startTransaction("test");
refManager.setPrimary(user3OverrideRef, true);
program.endTransaction(id, true);
//verify that nothing changes if no overrides are requested
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, calldsFunc3.getPcode(false)));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode()));
assertTrue(equalPcodeOpArrays(user3Unmodified, user3.getPcode(false)));
//verify that the CALLOTHER is changed to a CALL in the pcode for callds
assertTrue(equalPcodeOpArrays(calldsModified, calldsFunc3.getPcode(true)));
//verify that the CALLOTHER is changed to a CALL in the pcode for callds
assertTrue(equalPcodeOpArrays(user3Modified, user3.getPcode(true)));
}
/**
* Tests that flow overrides:
* 1) do not apply to pcode generated by a delayslot directive
* 2) do apply to instructions in a delay slot when their pcode is generated
* directly
* 3) do apply to pcode not generated by a delayslot directive in instructions
* with a delay slot
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testFlowOverridesAndDelaySlots() throws AddressFormatException {
//verify that the test program contains the instructions for the test
Address calldsAddr = defaultSpace.getAddress(CALLDS_FUNC3_10002a);
Instruction callds = program.getListing().getInstructionAt(calldsAddr);
assertNotNull(callds);
assertEquals("callds 0x" + func3Addr.toString(), callds.toString());
Address callAddr = defaultSpace.getAddress(CALL_FUNC1_10002c);
Instruction call = program.getListing().getInstructionAt(callAddr);
assertNotNull(call);
assertEquals("_call 0x" + func1Addr.toString(), call.toString());
//grab pcode for both instructions before any overrides applied
PcodeOp[] calldsUnmodified = callds.getPcode(false);
assertTrue(calldsUnmodified.length == 4);
assertTrue(calldsUnmodified[0].getOpcode() == PcodeOp.COPY); //from inst in delay slot
assertTrue(calldsUnmodified[1].getOpcode() == PcodeOp.CALL); //from inst in delay slot
assertTrue(calldsUnmodified[1].getInput(0).getOffset() == func1Addr.getOffset());
assertTrue(calldsUnmodified[2].getOpcode() == PcodeOp.COPY); //save ret address to lr
assertTrue(calldsUnmodified[3].getInput(0).getOffset() == func3Addr.getOffset());
assertTrue(calldsUnmodified[3].getOpcode() == PcodeOp.CALL); //call to func3
PcodeOp[] callUnmodified = call.getPcode(false);
assertTrue(callUnmodified.length == 2);
assertTrue(equalPcodeOps(callUnmodified[0], calldsUnmodified[0])); //save ret address to lr
assertTrue(equalPcodeOps(callUnmodified[1], calldsUnmodified[1])); //call to func1
//verify that pcode is the same whether or not you request overrides for the instruction
//in the delay slot
assertTrue(equalPcodeOpArrays(call.getPcode(false), call.getPcode(true)));
//this is a corner case that would probably never occur in practice
//callds has a CALL op, so a call reference, R, is created by default
//the instruction in the delay slot also has a CALL op, so when its pcode gets
//inserted into the pcode for callds the pcode emitter sees R and thinks that
//the CALL op in the delay slot should be overridden
//end result is that whether or not you request overrides matters because of a
//reference laid down automatically
PcodeOp[] cornerCase = callds.getPcode(true);
assertFalse(equalPcodeOpArrays(callds.getPcode(false), cornerCase));
assertTrue(cornerCase[0].getOpcode() == PcodeOp.COPY); //from inst in delay slot
assertTrue(cornerCase[1].getOpcode() == PcodeOp.CALL); //from inst in delay slot, overridden
assertTrue(cornerCase[1].getInput(0).getOffset() == func3Addr.getOffset());
assertTrue(cornerCase[2].getOpcode() == PcodeOp.COPY); //save ret address to lr
assertTrue(cornerCase[3].getOpcode() == PcodeOp.CALL); //call to func3
assertTrue(cornerCase[3].getInput(0).getOffset() == func3Addr.getOffset());
//flow override on instruction in delay slot
int tid = program.startTransaction("test");
call.setFlowOverride(FlowOverride.BRANCH);
program.endTransaction(tid, true);
//verify that nothing happens if no overrides are requested
assertTrue(equalPcodeOpArrays(calldsUnmodified, callds.getPcode()));
assertTrue(equalPcodeOpArrays(calldsUnmodified, callds.getPcode(false)));
assertTrue(equalPcodeOpArrays(callUnmodified, call.getPcode()));
assertTrue(equalPcodeOpArrays(callUnmodified, call.getPcode(false)));
//verify that requesting overrides on the instruction produces the same pcode
//that was produced before the override was applied
assertTrue(equalPcodeOpArrays(cornerCase, callds.getPcode(true)));
//verify that the override does apply to the instruction in the delay slot
//when its pcode is generated directly
PcodeOp[] overriddenCall = call.getPcode(true);
assertTrue(equalPcodeOps(overriddenCall[0], callUnmodified[0]));
assertTrue(overriddenCall[1].getOpcode() == PcodeOp.BRANCH);
assertTrue(equalInputsAndOutput(overriddenCall[1], callUnmodified[1]));
//remove existing flow override on call instruction
//set flow override on callds instruction
tid = program.startTransaction("test");
call.setFlowOverride(FlowOverride.NONE);
callds.setFlowOverride(FlowOverride.BRANCH);
program.endTransaction(tid, true);
//verify that pcode for instruction in delay slot is not affected by any overrides
assertTrue(equalPcodeOpArrays(call.getPcode(true), call.getPcode(false)));
assertTrue(equalPcodeOpArrays(call.getPcode(false), callUnmodified));
//verify that requesting no overrides yields the unmodified pcode
assertTrue(equalPcodeOpArrays(callds.getPcode(false), calldsUnmodified));
//verify that requesting overrides results in pcode in which the second call instruction
//(the one not in the delay slot) has been changed to a BRANCH
//verify no additional changes
PcodeOp[] overriddenCallds = callds.getPcode(true);
assertTrue(equalPcodeOps(overriddenCallds[0], calldsUnmodified[0]));
assertTrue(equalPcodeOps(overriddenCallds[1], calldsUnmodified[1]));
assertTrue(equalPcodeOps(overriddenCallds[2], calldsUnmodified[2]));
assertTrue(overriddenCallds[3].getOpcode() == PcodeOp.BRANCH);
assertTrue(equalInputsAndOutput(overriddenCallds[3], calldsUnmodified[3]));
}
//reference on the call instruction should do nothing to the call in the delay slot
//should apply when the pcode for the call is generated directly
//reference on the callds instruction should apply to the call in the delay slot
//an additional CALL_OVERRIDE_UNCONDITIONAL ref should have no effect
//but if you remove the simple ref it should take effect
//TODO: fix javadoc
/**
* note: for callds, the delayslot directive occurs before the call
* so a call in the delay slot wil end up being the first call of the callds instruction
* @throws AddressFormatException if {@code AddressSpace.getAddress throws it}
*/
@Test
public void testSimpleRefsAndDelaySlots() throws AddressFormatException {
//verify that the test program contains the instructions for the test
Address calldsAddr = defaultSpace.getAddress(CALLDS_FUNC3_10002a);
Instruction callds = program.getListing().getInstructionAt(calldsAddr);
assertNotNull(callds);
assertEquals("callds 0x" + func3Addr.toString(), callds.toString());
Address callAddr = defaultSpace.getAddress(CALL_FUNC1_10002c);
Instruction call = program.getListing().getInstructionAt(callAddr);
assertNotNull(call);
assertEquals("_call 0x" + func1Addr.toString(), call.toString());
//grab pcode for both instructions before any overrides applied
PcodeOp[] calldsUnmodified = callds.getPcode(false);
assertTrue(calldsUnmodified.length == 4);
assertTrue(calldsUnmodified[0].getOpcode() == PcodeOp.COPY); //from inst in delay slot
assertTrue(calldsUnmodified[1].getOpcode() == PcodeOp.CALL); //from inst in delay slot
assertTrue(calldsUnmodified[1].getInput(0).getOffset() == func1Addr.getOffset());
assertTrue(calldsUnmodified[2].getOpcode() == PcodeOp.COPY); //save ret address to lr
assertTrue(calldsUnmodified[3].getInput(0).getOffset() == func3Addr.getOffset());
assertTrue(calldsUnmodified[3].getOpcode() == PcodeOp.CALL); //call to func3
PcodeOp[] callUnmodified = call.getPcode(false);
assertTrue(callUnmodified.length == 2);
assertTrue(equalPcodeOps(callUnmodified[0], calldsUnmodified[0])); //save ret address to lr
assertTrue(equalPcodeOps(callUnmodified[1], calldsUnmodified[1])); //call to func1
//verify that pcode is the same whether or not you request overrides for the instruction
//in the delay slot
assertTrue(equalPcodeOpArrays(call.getPcode(false), call.getPcode(true)));
//this is the same corner case discussed in testFlowOverridesAndDelaySlots
//it demonstrates that a simple ref override on an instruction with a delay slot
//can apply to the pcode generated by the delayslot directive
PcodeOp[] cornerCase = callds.getPcode(true);
assertFalse(equalPcodeOpArrays(callds.getPcode(false), cornerCase));
assertTrue(cornerCase[0].getOpcode() == PcodeOp.COPY); //from inst in delay slot
assertTrue(cornerCase[1].getOpcode() == PcodeOp.CALL); //from inst in delay slot, overridden
assertTrue(cornerCase[1].getInput(0).getOffset() == func3Addr.getOffset());
assertTrue(cornerCase[2].getOpcode() == PcodeOp.COPY); //save ret address to lr
assertTrue(cornerCase[3].getOpcode() == PcodeOp.CALL); //call to func3
assertTrue(cornerCase[3].getInput(0).getOffset() == func3Addr.getOffset());
//apply a simple ref on the call in the delay slot
int id = program.startTransaction("test");
Reference simpleCallRef = refManager.addMemoryReference(callAddr, func1Addr,
RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, 0);
//default reference is primary; set simpleCallRef to primary to unseat it
refManager.setPrimary(simpleCallRef, true);
program.endTransaction(id, true);
//verify the pcode generated for the call instruction without overrides
assertTrue(equalPcodeOpArrays(call.getPcode(false), callUnmodified));
//verify the pcode generated for the call instruction with overrides
PcodeOp[] callModifiedSimpleRef = call.getPcode(true);
assertTrue(callModifiedSimpleRef.length == 2);
assertTrue(equalPcodeOps(callModifiedSimpleRef[0], callUnmodified[0]));
assertTrue(callModifiedSimpleRef[1].getOpcode() == PcodeOp.CALL);
assertTrue(callModifiedSimpleRef[1].getInput(0).getOffset() == func1Addr.getOffset());
//verify that nothing changes when generating the pcode for callds
assertTrue(equalPcodeOpArrays(callds.getPcode(false), calldsUnmodified));
assertTrue(equalPcodeOpArrays(callds.getPcode(true), cornerCase));
//apply a non-primary CALL_OVERRIDE_UNCONDITIONAL ref
id = program.startTransaction("test");
Reference callOverrideRef = refManager.addMemoryReference(callAddr, func2Addr,
RefType.CALL_OVERRIDE_UNCONDITIONAL, SourceType.USER_DEFINED, 0);
program.endTransaction(id, true);
//verify no effect (since simpleCallRef has precedence)
assertTrue(equalPcodeOpArrays(call.getPcode(false), callUnmodified));
assertTrue(equalPcodeOpArrays(call.getPcode(true), callModifiedSimpleRef));
assertTrue(equalPcodeOpArrays(callds.getPcode(false), calldsUnmodified));
assertTrue(equalPcodeOpArrays(callds.getPcode(true), cornerCase));
//make callOverrideRef primary
id = program.startTransaction("test");
refManager.setPrimary(callOverrideRef, true);
program.endTransaction(id, true);
//verify no effect on pcode for call when overrides not requested
assertTrue(equalPcodeOpArrays(call.getPcode(false), callUnmodified));
//verify that the call target is changed to func2addr when overrides are requested
PcodeOp[] callModifiedoverrideRef = call.getPcode(true);
assertTrue(equalPcodeOps(callModifiedoverrideRef[0], callUnmodified[0]));
assertTrue(callModifiedoverrideRef[1].getOpcode() == PcodeOp.CALL);
assertTrue(callModifiedoverrideRef[1].getInput(0).getOffset() == func2Addr.getOffset());
//verify no effect on the pcode for callds
assertTrue(equalPcodeOpArrays(callds.getPcode(false), calldsUnmodified));
assertTrue(equalPcodeOpArrays(callds.getPcode(true), cornerCase));
}
/**
* Test pcode emitted in the presence of a branch override
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testBranchOverride() throws AddressFormatException {
initializeAndVerifyFlowOverrideFuncs();
applyFlowOverride(FlowOverride.BRANCH);
//shouldn't change skeq
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(true), skeq_10002e.getPcode(false)));
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(), skeq_10002e.getPcode(false)));
//shouldn't change user_one
assertTrue(
equalPcodeOpArrays(user_one_100030.getPcode(true), user_one_100030.getPcode(false)));
assertTrue(equalPcodeOpArrays(user_one_100030.getPcode(), user_one_100030.getPcode(false)));
//shouldn't change br
assertTrue(equalPcodeOpArrays(br_100032.getPcode(true), br_100032.getPcode(false)));
assertTrue(equalPcodeOpArrays(br_100032.getPcode(), br_100032.getPcode(false)));
//shouldn't change breq
assertTrue(equalPcodeOpArrays(breq_100034.getPcode(true), breq_100034.getPcode(false)));
assertTrue(equalPcodeOpArrays(breq_100034.getPcode(), breq_100034.getPcode(false)));
//shouldn't change br r0
assertTrue(equalPcodeOpArrays(br_r0_100036.getPcode(true), br_r0_100036.getPcode(false)));
assertTrue(equalPcodeOpArrays(br_r0_100036.getPcode(), br_r0_100036.getPcode(false)));
//should change CALL to BRANCH
PcodeOp[] callUnmodified = call_100038.getPcode(false);
assertTrue(equalPcodeOpArrays(call_100038.getPcode(), callUnmodified));
PcodeOp[] callOverridden = call_100038.getPcode(true);
assertTrue(callOverridden.length == 2);
assertTrue(equalPcodeOps(callOverridden[0], callUnmodified[0]));
assertTrue(callOverridden[1].getOpcode() == PcodeOp.BRANCH);
assertTrue(equalInputsAndOutput(callOverridden[1], callUnmodified[1]));
//should change CALLIND to BRANCHIND
PcodeOp[] callindUnmodified = call_r0_10003a.getPcode(false);
assertTrue(equalPcodeOpArrays(callindUnmodified, call_r0_10003a.getPcode()));
PcodeOp[] callindOverridden = call_r0_10003a.getPcode(true);
assertTrue(callindOverridden.length == 2);
assertTrue(equalPcodeOps(callindUnmodified[0], callindOverridden[0]));
assertTrue(callindOverridden[1].getOpcode() == PcodeOp.BRANCHIND);
assertTrue(equalInputsAndOutput(callindOverridden[1], callindUnmodified[1]));
//should change RETURN to BRANCHIND
PcodeOp[] returnUnmodified = ret_10003c.getPcode(false);
assertTrue(equalPcodeOpArrays(returnUnmodified, ret_10003c.getPcode()));
PcodeOp[] returnOverridden = ret_10003c.getPcode(true);
assertTrue(returnOverridden.length == 1);
assertTrue(returnOverridden[0].getOpcode() == PcodeOp.BRANCHIND);
assertTrue(equalInputsAndOutput(returnOverridden[0], returnUnmodified[0]));
}
/**
* Tests pcode emitted in the presence of a call override
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testCallOverride() throws AddressFormatException {
initializeAndVerifyFlowOverrideFuncs();
applyFlowOverride(FlowOverride.CALL);
//shouldn't change skeq
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(true), skeq_10002e.getPcode(false)));
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(), skeq_10002e.getPcode(false)));
//shouldn't change user_one
assertTrue(
equalPcodeOpArrays(user_one_100030.getPcode(true), user_one_100030.getPcode(false)));
assertTrue(equalPcodeOpArrays(user_one_100030.getPcode(), user_one_100030.getPcode(false)));
//should change BRANCH to CALL
PcodeOp[] brUnmodified = br_100032.getPcode(false);
assertTrue(equalPcodeOpArrays(br_100032.getPcode(), brUnmodified));
PcodeOp[] brOverridden = br_100032.getPcode(true);
assertTrue(brOverridden.length == 1);
assertTrue(brOverridden[0].getOpcode() == PcodeOp.CALL);
assertTrue(equalInputsAndOutput(brOverridden[0], brUnmodified[0]));
//should change CBRANCH to BOOL_NEGATE, CBRANCH, CALL
//however, the CBRANCH in the pcode for breq is to the next instruction
//which the flow override code explicitly skips. So the final
//branch will be changed to a call
//looks like the toy language does not have an instruction with a CBRANCH
//that would be affected by a CALL override
PcodeOp[] cbranchUnmodified = breq_100034.getPcode(false);
assertTrue(equalPcodeOpArrays(cbranchUnmodified, breq_100034.getPcode()));
PcodeOp[] cbranchOverridden = breq_100034.getPcode(true);
assertTrue(cbranchOverridden.length == 3);
assertTrue(equalPcodeOps(cbranchUnmodified[0], cbranchOverridden[0]));
assertTrue(equalPcodeOps(cbranchUnmodified[1], cbranchOverridden[1]));
assertTrue(cbranchOverridden[2].getOpcode() == PcodeOp.CALL);
assertTrue(equalInputsAndOutput(cbranchOverridden[2], cbranchUnmodified[2]));
//should change BRANCHIND to CALLIND
PcodeOp[] branchindUnmodified = br_r0_100036.getPcode(false);
assertTrue(equalPcodeOpArrays(branchindUnmodified, br_r0_100036.getPcode()));
PcodeOp[] branchindOverridden = br_r0_100036.getPcode(true);
assertTrue(branchindOverridden.length == 1);
assertTrue(branchindOverridden[0].getOpcode() == PcodeOp.CALLIND);
assertTrue(equalInputsAndOutput(branchindOverridden[0], branchindUnmodified[0]));
//shouldn't change CALL
assertTrue(equalPcodeOpArrays(call_100038.getPcode(true), call_100038.getPcode(false)));
assertTrue(equalPcodeOpArrays(call_100038.getPcode(), call_100038.getPcode(false)));
//shouldn't change CALLIND
assertTrue(
equalPcodeOpArrays(call_r0_10003a.getPcode(true), call_r0_10003a.getPcode(false)));
assertTrue(equalPcodeOpArrays(call_r0_10003a.getPcode(), call_r0_10003a.getPcode(false)));
//should change RETURN to CALLIND
PcodeOp[] returnUnmodified = ret_10003c.getPcode(false);
assertTrue(equalPcodeOpArrays(returnUnmodified, ret_10003c.getPcode()));
PcodeOp[] returnOverridden = ret_10003c.getPcode(true);
assertTrue(returnOverridden.length == 1);
assertTrue(returnOverridden[0].getOpcode() == PcodeOp.CALLIND);
assertTrue(equalInputsAndOutput(returnOverridden[0], returnUnmodified[0]));
}
/**
* Tests pcode emitted in the presence of a call_return override
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testCallReturnOverride() throws AddressFormatException {
initializeAndVerifyFlowOverrideFuncs();
applyFlowOverride(FlowOverride.CALL_RETURN);
//shouldn't change skeq
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(true), skeq_10002e.getPcode(false)));
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(), skeq_10002e.getPcode(false)));
//shouldn't change user_one
assertTrue(
equalPcodeOpArrays(user_one_100030.getPcode(true), user_one_100030.getPcode(false)));
assertTrue(equalPcodeOpArrays(user_one_100030.getPcode(), user_one_100030.getPcode(false)));
//should change BRANCH to CALL, RETURN
PcodeOp[] brUnmodified = br_100032.getPcode(false);
assertTrue(equalPcodeOpArrays(br_100032.getPcode(), brUnmodified));
PcodeOp[] brOverridden = br_100032.getPcode(true);
assertTrue(brOverridden.length == brUnmodified.length + 1);
assertTrue(brOverridden[0].getOpcode() == PcodeOp.CALL);
assertTrue(equalInputsAndOutput(brOverridden[0], brUnmodified[0]));
assertTrue(brOverridden[1].getOpcode() == PcodeOp.RETURN);
//CBRANCH in this pcode is unaffected - see comment in testCallOverride()
PcodeOp[] cbranchUnmodified = breq_100034.getPcode(false);
assertTrue(equalPcodeOpArrays(cbranchUnmodified, breq_100034.getPcode()));
PcodeOp[] cbranchOverridden = breq_100034.getPcode(true);
assertTrue(cbranchOverridden.length == cbranchUnmodified.length + 1);
assertTrue(equalPcodeOps(cbranchUnmodified[0], cbranchOverridden[0]));
assertTrue(equalPcodeOps(cbranchUnmodified[1], cbranchOverridden[1]));
assertTrue(cbranchOverridden[2].getOpcode() == PcodeOp.CALL);
assertTrue(equalInputsAndOutput(cbranchOverridden[2], cbranchUnmodified[2]));
assertTrue(cbranchOverridden[3].getOpcode() == PcodeOp.RETURN);
//should change BRANCHIND to CALL, RETURN
PcodeOp[] branchindUnmodified = br_r0_100036.getPcode(false);
assertTrue(equalPcodeOpArrays(branchindUnmodified, br_r0_100036.getPcode()));
PcodeOp[] branchindOverridden = br_r0_100036.getPcode(true);
assertTrue(branchindOverridden.length == branchindUnmodified.length + 1);
assertTrue(branchindOverridden[0].getOpcode() == PcodeOp.CALLIND);
assertTrue(equalInputsAndOutput(branchindOverridden[0], branchindUnmodified[0]));
assertTrue(branchindOverridden[1].getOpcode() == PcodeOp.RETURN);
//should change CALL to CALL, RETURN
PcodeOp[] callUnmodified = call_100038.getPcode(false);
assertTrue(equalPcodeOpArrays(callUnmodified, call_100038.getPcode()));
PcodeOp[] callOverridden = call_100038.getPcode(true);
assertTrue(callOverridden.length == callUnmodified.length + 1);
assertTrue(equalPcodeOps(callUnmodified[0], callOverridden[0]));
assertTrue(equalPcodeOps(callUnmodified[1], callOverridden[1]));
assertTrue(callOverridden[2].getOpcode() == PcodeOp.RETURN);
//should change CALLIND to CALLIND, RETURN
PcodeOp[] callindUnmodified = call_r0_10003a.getPcode(false);
assertTrue(equalPcodeOpArrays(call_r0_10003a.getPcode(), callindUnmodified));
PcodeOp[] callindOverridden = call_r0_10003a.getPcode(true);
assertTrue(callindOverridden.length == callindUnmodified.length + 1);
assertTrue(equalPcodeOps(callindOverridden[0], callindUnmodified[0]));
assertTrue(equalPcodeOps(callindOverridden[1], callindUnmodified[1]));
//should change RETURN to CALLIND, RETURN
PcodeOp[] returnUnmodified = ret_10003c.getPcode(false);
assertTrue(equalPcodeOpArrays(returnUnmodified, ret_10003c.getPcode()));
PcodeOp[] returnOverridden = ret_10003c.getPcode(true);
assertTrue(returnOverridden.length == returnUnmodified.length + 1);
assertTrue(returnOverridden[0].getOpcode() == PcodeOp.CALLIND);
assertTrue(equalInputsAndOutput(returnOverridden[0], returnUnmodified[0]));
assertTrue(returnOverridden[1].getOpcode() == PcodeOp.RETURN);
}
/**
* Tests pcode emitted in the presence of a return
* @throws AddressFormatException if {@code AddressSpace.getAddress} throws it
*/
@Test
public void testReturnOverride() throws AddressFormatException {
initializeAndVerifyFlowOverrideFuncs();
applyFlowOverride(FlowOverride.RETURN);
//shouldn't change skeq
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(true), skeq_10002e.getPcode(false)));
assertTrue(equalPcodeOpArrays(skeq_10002e.getPcode(), skeq_10002e.getPcode(false)));
//shouldn't change user_one
assertTrue(
equalPcodeOpArrays(user_one_100030.getPcode(true), user_one_100030.getPcode(false)));
assertTrue(equalPcodeOpArrays(user_one_100030.getPcode(), user_one_100030.getPcode(false)));
//should change BRANCH to COPY, RETURN
PcodeOp[] brUnmodified = br_100032.getPcode(false);
assertTrue(equalPcodeOpArrays(br_100032.getPcode(), brUnmodified));
PcodeOp[] brOverridden = br_100032.getPcode(true);
assertTrue(brOverridden.length == brUnmodified.length + 1);
assertTrue(brOverridden[0].getOpcode() == PcodeOp.COPY);
assertTrue(brOverridden[1].getOpcode() == PcodeOp.RETURN);
//CBRANCH in this pcode is unaffected - see comment in testCallOverride()
PcodeOp[] cbranchUnmodified = breq_100034.getPcode(false);
assertTrue(equalPcodeOpArrays(cbranchUnmodified, breq_100034.getPcode()));
PcodeOp[] cbranchOverridden = breq_100034.getPcode(true);
assertTrue(cbranchOverridden.length == cbranchUnmodified.length + 1);
assertTrue(equalPcodeOps(cbranchUnmodified[0], cbranchOverridden[0]));
assertTrue(equalPcodeOps(cbranchUnmodified[1], cbranchOverridden[1]));
assertTrue(cbranchOverridden[2].getOpcode() == PcodeOp.COPY);
assertTrue(cbranchOverridden[3].getOpcode() == PcodeOp.RETURN);
//should change BRANCHIND to RETURN
PcodeOp[] branchindUnmodified = br_r0_100036.getPcode(false);
assertTrue(equalPcodeOpArrays(branchindUnmodified, br_r0_100036.getPcode()));
PcodeOp[] branchindOverridden = br_r0_100036.getPcode(true);
assertTrue(branchindOverridden.length == 1);
assertTrue(branchindOverridden[0].getOpcode() == PcodeOp.RETURN);
assertTrue(equalInputsAndOutput(branchindOverridden[0], branchindUnmodified[0]));
//should change CALL to COPY, RETURN
PcodeOp[] callUnmodified = call_100038.getPcode(false);
assertTrue(equalPcodeOpArrays(callUnmodified, call_100038.getPcode()));
PcodeOp[] callOverridden = call_100038.getPcode(true);
assertTrue(callOverridden.length == callUnmodified.length + 1);
assertTrue(equalPcodeOps(callOverridden[0], callUnmodified[0]));
assertTrue(callOverridden[1].getOpcode() == PcodeOp.COPY);
assertTrue(callOverridden[2].getOpcode() == PcodeOp.RETURN);
//should change CALLIND to RETURN
PcodeOp[] callindUnmodified = call_r0_10003a.getPcode(false);
assertTrue(equalPcodeOpArrays(call_r0_10003a.getPcode(), callindUnmodified));
PcodeOp[] callindOverridden = call_r0_10003a.getPcode(true);
assertTrue(callindOverridden.length == callindUnmodified.length);
assertTrue(equalPcodeOps(callindOverridden[0], callindUnmodified[0]));
assertTrue(callindOverridden[1].getOpcode() == PcodeOp.RETURN);
//shouldn't change RETURN
PcodeOp[] returnUnmodified = ret_10003c.getPcode(false);
assertTrue(equalPcodeOpArrays(returnUnmodified, ret_10003c.getPcode()));
PcodeOp[] returnOverridden = ret_10003c.getPcode(true);
assertTrue(equalPcodeOpArrays(returnOverridden, returnUnmodified));
}
private void initializeAndVerifyFlowOverrideFuncs() throws AddressFormatException {
skeq_10002e = program.getListing().getInstructionAt(defaultSpace.getAddress(SK_EQ_10002e));
assertEquals("skeq", skeq_10002e.toString());
user_one_100030 =
program.getListing().getInstructionAt(defaultSpace.getAddress(USER_ONE_100030));
assertEquals("user_one r0", user_one_100030.toString());
br_100032 = program.getListing()
.getInstructionAt(defaultSpace.getAddress(UNCONDITIONAL_JUMP_100032));
assertEquals("br 0x00100036", br_100032.toString());
breq_100034 =
program.getListing().getInstructionAt(defaultSpace.getAddress(CONDITIONAL_JUMP_100034));
assertEquals("breq 0x00100038", breq_100034.toString());
br_r0_100036 =
program.getListing().getInstructionAt(defaultSpace.getAddress(INDIRECT_JUMP_100036));
assertEquals("br r0", br_r0_100036.toString());
call_100038 =
program.getListing().getInstructionAt(defaultSpace.getAddress(CALL_FUNC1_100038));
assertEquals("call 0x00100100", call_100038.toString());
call_r0_10003a =
program.getListing().getInstructionAt(defaultSpace.getAddress(INDIRECT_CALL_10003a));
assertEquals("call r0", call_r0_10003a.toString());
ret_10003c = program.getListing().getInstructionAt(defaultSpace.getAddress(RETURN_10003c));
assertEquals("ret", ret_10003c.toString());
}
private void applyFlowOverride(FlowOverride flowOver) {
int tid = program.startTransaction("applyFlowOverride");
skeq_10002e.setFlowOverride(flowOver);
user_one_100030.setFlowOverride(flowOver);
br_100032.setFlowOverride(flowOver);
breq_100034.setFlowOverride(flowOver);
br_r0_100036.setFlowOverride(flowOver);
call_100038.setFlowOverride(flowOver);
call_r0_10003a.setFlowOverride(flowOver);
ret_10003c.setFlowOverride(flowOver);
program.endTransaction(tid, true);
}
public static boolean equalPcodeOpArrays(PcodeOp[] array1, PcodeOp[] array2) {
if (array1 == null && array2 == null) {
return true;
}
if (array1 == null || array2 == null) {
return false;
}
if (array1.length != array2.length) {
return false;
}
for (int i = 0; i < array1.length; ++i) {
if (!equalPcodeOps(array1[i], array2[i])) {
return false;
}
}
return true;
}
public static boolean equalPcodeOps(PcodeOp op1, PcodeOp op2) {
if (op1.getOpcode() != op2.getOpcode()) {
return false;
}
return equalInputsAndOutput(op1, op2);
}
//for testing modifications that can the pcode op but nothing else
public static boolean equalInputsAndOutput(PcodeOp op1, PcodeOp op2) {
if (!Objects.equals(op1.getOutput(), op2.getOutput())) {
return false;
}
if (op1.getNumInputs() != op2.getNumInputs()) {
return false;
}
for (int i = 0; i < op1.getNumInputs(); ++i) {
if (!Objects.equals(op1.getInput(i), op2.getInput(i))) {
return false;
}
}
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.