language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 792 | 2.25 | 2 | [] | no_license | package br.com.grupomult.flows.animal;
import static br.com.grupomult.constants.MessageConstants.ERROR_GET_ANIMALS_BY_ID_NOT_FOUND;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import br.com.grupomult.api.animal.models.ResponseGetAnimalsById;
import br.com.grupomult.entities.Animal;
import br.com.grupomult.exceptions.HttpNotFoundException;
public class ListAnimalsByIdLoadValidate {
@Autowired
private ListAnimalsByIdConverter converter;
public ResponseEntity<ResponseGetAnimalsById> execute(Animal animal) {
if (Optional.ofNullable(animal).isPresent()) {
return converter.execute(animal);
} else {
throw new HttpNotFoundException(ERROR_GET_ANIMALS_BY_ID_NOT_FOUND);
}
}
}
|
Java | UTF-8 | 785 | 2.328125 | 2 | [] | no_license | package schoology.stepDefinition;
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class TestBase {
public static WebDriver driver;
@Before
public void openBrowser() {
System.out.println("-----BEFORE METHOD--");
String osDriver = getOsDriver();
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+File.separator+"drivers"+File.separator+osDriver);
driver = new ChromeDriver();
driver.get("https://www.schoology.com/");
}
private String getOsDriver() {
String osName = System.getProperty("os.name").toLowerCase(); //Windows 7
if(osName.indexOf("win") >= 0) {
return "chromedriver.exe";
} else {
return "chromedriver";
}
}
} |
Python | UTF-8 | 933 | 2.765625 | 3 | [] | no_license | from icrawler.builtin import GoogleImageCrawler
import os
import csv
filePathDict = 'dogBreedsListGoogle.csv'
def loadDogDict():
with open(filePathDict,'rU') as infile:
reader = csv.reader(infile, dialect=csv.excel_tab, delimiter=';')
dogBreedDict = {str(rows[0]).zfill(3) + '.' + str(rows[1]).replace(' ', '_'): str(rows[1]) for rows in reader}
return dogBreedDict
def crawl(breedDir, breedName):
google_crawler = GoogleImageCrawler(parser_threads=2, downloader_threads=4,
storage={'root_dir': '~/dog-images/googleDogImages/' + breedDir})
google_crawler.crawl(keyword=breedName, max_num=1000,
date_min=None, date_max=None,
min_size=(300, 300), max_size=None)
if __name__ == "__main__":
dogBreedDict = loadDogDict()
for breedDir, breedName in dogBreedDict.items():
crawl(breedDir, breedName) |
Python | UTF-8 | 3,024 | 2.53125 | 3 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit test for encoding / decoding functions."""
import tensorflow as tf
from tensorflow_model_analysis.eval_saved_model import encoding
class EncodingTest(tf.test.TestCase):
def setUp(self):
self.longMessage = True # pylint: disable=invalid-name
def testEncodeDecodeKey(self):
test_cases = [
'a', 'simple', 'dollar$', '$dollar', '$do$ll$ar$', ('a'),
('a', 'simple'), ('dollar$', 'simple'), ('do$llar', 'sim$ple', 'str$'),
('many', 'many', 'elements', 'in', 'the', 'tuple'), u'unicode\u1234',
u'uni\u1234code\u2345', ('mixed', u'uni\u1234', u'\u2345\u1234'),
(u'\u1234\u2345', u'\u3456\u2345')
]
for key in test_cases:
self.assertEqual(key, encoding.decode_key(encoding.encode_key(key)))
def testEncodeDecodeTensorNode(self):
g = tf.Graph()
with g.as_default():
example = tf.compat.v1.placeholder(tf.string, name='example')
features = tf.io.parse_example(
serialized=example,
features={
'age':
tf.io.FixedLenFeature([], dtype=tf.int64, default_value=-1),
'gender':
tf.io.FixedLenFeature([], dtype=tf.string),
'varstr':
tf.io.VarLenFeature(tf.string),
'varint':
tf.io.VarLenFeature(tf.int64),
'varfloat':
tf.io.VarLenFeature(tf.float32),
u'unicode\u1234':
tf.io.FixedLenFeature([], dtype=tf.string),
})
constant = tf.constant(1.0)
sparse = tf.SparseTensor(
indices=tf.compat.v1.placeholder(tf.int64),
values=tf.compat.v1.placeholder(tf.int64),
dense_shape=tf.compat.v1.placeholder(tf.int64))
test_cases = [
example, features['age'], features['gender'], features['varstr'],
features['varint'], features['varfloat'], features[u'unicode\u1234'],
constant, sparse
]
for tensor in test_cases:
got_tensor = encoding.decode_tensor_node(
g, encoding.encode_tensor_node(tensor))
if isinstance(tensor, tf.SparseTensor):
self.assertEqual(tensor.indices, got_tensor.indices)
self.assertEqual(tensor.values, got_tensor.values)
self.assertEqual(tensor.dense_shape, got_tensor.dense_shape)
else:
self.assertEqual(tensor, got_tensor)
if __name__ == '__main__':
tf.test.main()
|
C++ | UTF-8 | 833 | 3.5625 | 4 | [] | no_license | #ifndef NTUPLE_H
#define NTUPLE_H
namespace util{
/** Template for a tuple of all-equal objects*/
template<typename T, int size>
class NTuple
{
protected:
/**Elements in the tuple */
T v[size];
public:
/** Read only reference to an element in the tuple */
const T& operator[](int pos) const {return v[pos];}
/** Read-write reference to an element in the tuple */
T& operator[](int pos) {return v[pos];}
};
/** Tuple of 2 elements */
template <typename T> class Pair : public NTuple<T,2>{};
/** Tuple of 3 elements */
template <typename T> class Triplet : public NTuple<T,3>{
public:
/** Default constructor */
Triplet(){}
/** Copy constructor from a 3 objects NTuple */
Triplet(const NTuple<T,3>& t)
{
for(int i=0;i<3;i++)
(*this)[i] = t[i];
}
};
}
#endif
|
Python | UTF-8 | 715 | 3.640625 | 4 | [] | no_license | d_point = [] # 单科成绩列表
d_node = [] # 单科学分列表
num = 0 # 输入科目数
def cal(dp=[], dn=[]): # 计算绩点的函数
sum_point_node = 0
sum_node = 0
for i in range(len(dp)):
sum_point_node += (float(dp[i])*float(dn[i]))
sum_node += float(dn[i])
return sum_point_node/sum_node
while True:
num += 1
point = input("输入第{}科绩点:".format(num))
node = input("输入第{}科的学分:".format(num))
d_point.append(point)
d_node.append(node)
print("目前绩点为:", cal(dp=d_point, dn=d_node))
# go_on = input("输入ok结束成绩输入,输入其他任意字符继续成绩输入")
# if go_on == "ok":
# break
|
Python | UTF-8 | 861 | 2.59375 | 3 | [] | no_license | import time
from block import Block
from core import *
import sys, traceback
import threading
class Miner(threading.Thread):
def __init__(self,chain,max_len,node):
super(Miner,self).__init__()
self.node = node
self.timeout_seconds = 100
self.chain = chain
self.max_len = max_len
def run(self):
i = 0
while i < self.max_len:
try:
self.mine()
i += 1
except Exception as e:
traceback.print_exc(file=sys.stdout)
return
def mine(self):
proof = proof_of_work(self.chain.last_proof,self.timeout_seconds)
print("new proof found:%d by %s" % (proof,self.node.id))
self.chain.new_block(Block(self.chain.last_proof,proof))
print("new block appended,lastest full chain is:%s at node [%s],length is %d" % (self.chain.status(),self.node.id,self.chain.length))
self.node.notify_neighbours()
return self.chain.last_proof
|
Python | UTF-8 | 2,985 | 3.703125 | 4 | [] | no_license | from woordenlijst.woordenlijst_filter import *
import random
class GameState:
def __init__(self):
self.letters = []
self.score = 0
self.word_set = set() # possible_words(self.letters)
self.guesses = set()
self.pangram_set = pangrams()
def reset_game(self):
"""
Gets a new random pangram, removes it from the pangram list and
shuffles the pangram's letters to get a new list of letters
:return: nothing as it calls a new set command
"""
new = random.sample(self.pangram_set, 1)[0]
self.pangram_set.remove(new)
new = list(new)
random.shuffle(new)
self.letters = new
self.set_words()
self.guesses = set()
def set_words(self):
"""
Gets all the possible words from woordenlijst_filter.py
using the letter array and takes all words from that list
that include the first letter of the array
"""
words = possible_words(self.letters)
self.word_set = {word for word in words if self.letters[0] in word}
def increase_score(self, word):
"""
Increases the score in 3 ways
4 letter words get 1 point
a pangram gets 14 points
any other guess gets points based on the length of the guess
:param word: correct guess
:return: list with message and score as integer
"""
if word == "all_found":
self.score += 20
return "Graat voltooid! +20"
if len(word) == 4:
self.score += 1
return ["+1", 1]
elif sorted(list(set(list(word)))) == sorted(self.letters):
self.score += len(word) + 7
return ["PANGRAM GEVONDEN! +" + str(len(word) + 7), len(word) + 7]
else:
self.score += len(word)
return ["+" + str(len(word)), len(word)]
def is_correct(self, guess):
"""
Checks if the guess is a correct guess, if not the player gets feedback
otherwise your score increases
:param guess: user input
:return: list with user feedback or call to increase_score
"""
if guess in self.guesses:
return ["Woord al gereden"]
else:
self.guesses.add(guess)
if len(guess) < 4:
return ["Woordlengte minimaal 4 letters"]
if not all(x in self.letters for x in list(guess)):
return ["Gegeven letter niet in graat"]
if not self.letters[0] in guess:
return ["Middelste letter niet gebruikt"]
if guess not in self.word_set:
return ["Gegeven woord niet gevonden"]
self.word_set.remove(guess)
return self.increase_score(guess)
def get_hint(self):
"""
Gives user hint
:return: first two letters of a unguessed word
"""
hint = random.sample(self.word_set, 1)[0]
return [hint[:2], len(hint) - 2]
|
C# | UTF-8 | 1,456 | 3.03125 | 3 | [] | no_license | using Newtonsoft.Json;
using System;
/// <summary>
/// Class which contains info about a saved contact.
/// </summary>
[Serializable]
public sealed class ContactInfo
{
/// <summary>
/// The currently active ContactsPopup.
/// </summary>
public ContactsPopup ContactsPopup { get; }
/// <summary>
/// The address of the contact.
/// </summary>
[JsonProperty]
public string ContactAddress { get; set; }
/// <summary>
/// The name of the contact.
/// </summary>
[JsonProperty]
public string ContactName { get; set; }
/// <summary>
/// The contructor to use when contructing the object from serialized text.
/// </summary>
/// <param name="contactAddress"> The address of the contact. </param>
/// <param name="contactName"> The name of the contact. </param>
[JsonConstructor]
public ContactInfo(string contactAddress, string contactName)
{
ContactAddress = contactAddress;
ContactName = contactName;
}
/// <summary>
/// The contact info
/// </summary>
/// <param name="contactsPopup"> The active ContactsPopup </param>
/// <param name="contactAddress"> The address of the contact. </param>
/// <param name="contactName"> The name of the contact. </param>
public ContactInfo(ContactsPopup contactsPopup, string contactAddress, string contactName) : this(contactAddress, contactName)
{
ContactsPopup = contactsPopup;
}
} |
C++ | UTF-8 | 227 | 3.15625 | 3 | [] | no_license | struct A {};
struct B {
explicit B(A) {}
};
struct C {
C(A a):
b(a)
{
static_assert(std::is_convertible<A, decltype(b)>, "Must be convertible.");
}
B b;
};
struct D {
D(A a):
b(implicit_cast(a))
{
}
B b;
}; |
Java | UTF-8 | 1,000 | 2.53125 | 3 | [] | no_license | package fileTransfer;
import javax.swing.text.StyledDocument;
import uMessenger.ChatClient;
public class FileSender {
public FileSender(String dir, StyledDocument doc){
ChatClient zz = new ChatClient(doc);
FilesConnection con = new FilesConnection(dir, 5077, doc);
FileSenderHandler file = new FileSenderHandler();
String fileName = file.getFileName();
con.sendString(fileName );
if(fileName.equals("NULL")){
zz.printOnScreen(" >File not selected. \n", "GRAY");
zz.printOnScreen(" >Exiting... \n", "GRAY");
} else{
zz.printOnScreen(" >File to seeeend: " + fileName, "GRAY");
FilesArray fileDumpedInArray = file.dumpFileToArray();
con.sendArray(fileDumpedInArray, 1);
zz.printOnScreen(" >File " + fileName + " sent. \n", "GRAY");
}
con.closeAllSockets();
}
}
|
C | UTF-8 | 491 | 3.109375 | 3 | [] | no_license | #include <stdio.h>
#include <signal.h>
void * thread_fun(void *arg){
int i = 0;
while(i++<3){
printf("thread loop times %d\n",i);
sleep(1);
}
return (void *)100;
}
int main(){
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
//pthread_detach(tid);
void *ret;
int err;
while(1){
err = pthread_join(tid,&ret);
if(err!=0){
fprintf(stderr,"thread %s\n",strerror(err));
}else{
fprintf(stderr,"thread exit code %d\n",(int)ret);
}
sleep(1);
}
return 0;
}
|
Python | UTF-8 | 2,836 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | """
"""
import h5py
import numpy as np
import os
from matplotlib import pyplot as plt
PWD = os.path.dirname(os.path.realpath(__file__))
def load_data():
"""
"""
train_dataset = load_train_datasets()
# print(type(train_dataset))
train_set_x_orig = np.array(train_dataset['train_set_x'][:]) # your train set features
train_set_y_orig = np.array(train_dataset['train_set_y'][:]) # your train set labels
test_dataset = load_test_datasets()
test_set_x_orig = np.array(test_dataset['test_set_x'][:]) # your test set features
test_set_y_orig = np.array(test_dataset['test_set_y'][:]) # your test set labels
classes = np.array(test_dataset['list_classes'][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
def load_train_datasets():
"""
"""
data_train_h5 = os.path.join(PWD, 'datasets', 'train_catvnoncat.h5')
train_dataset = h5py.File(data_train_h5, 'r')
return train_dataset
def load_test_datasets():
"""
"""
data_tests_h5 = os.path.join(PWD, 'datasets', 'test_catvnoncat.h5')
test_dataset = h5py.File(data_tests_h5, 'r')
return test_dataset
def load_parameters():
"""
"""
data_dir = os.path.dirname(os.path.realpath(__file__))
saved_parameters = os.path.join(data_dir, 'datasets', 'saved_parameters.npy')
print('\nloading saved parameters: {}'.format(saved_parameters))
parameters = np.load(saved_parameters).item()
return parameters
def print_mislabeled_images(classes, X, y, p):
"""
"""
a = p + y
mislabeled_indices = np.asarray(np.where(a == 1))
plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
num_images = len(mislabeled_indices[0])
for i in range(num_images):
index = mislabeled_indices[1][i]
plt.subplot(2, num_images, i + 1)
plt.imshow(X[:, index].reshape(64, 64, 3), interpolation='nearest')
plt.axis('off')
plt.title(
"Prediction: " + classes[int(p[0, index])].decode("utf-8") + " \n Class: " + classes[y[0, index]].decode(
"utf-8"))
def print_pypath():
"""
Print out Python path.
"""
import sys
print('\nPYTHONPATH')
print('.'*80)
for p in sys.path:
print(p)
print('.' * 80)
def save_parameters(parameters):
"""
"""
data_dir = os.path.dirname(os.path.realpath(__file__))
saved_parameters = os.path.join(data_dir, 'datasets', 'saved_parameters.npy')
print('\nsaving parameters: {} ...'.format(saved_parameters))
np.save(saved_parameters, parameters, allow_pickle=True, fix_imports=True)
|
C | UTF-8 | 2,251 | 3.078125 | 3 | [] | no_license | /* stringbank.c, Copyright (c) 2005 Michael C. Martin */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope thta it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Se the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stringbank.h"
#define CHUNK_SIZE (1024 - sizeof (void *) - sizeof (int))
typedef struct _stringbank_chunk {
char data[CHUNK_SIZE];
int len;
struct _stringbank_chunk *next;
} chunk;
static chunk *bank = NULL;
static void
add_chunk (void)
{
chunk *n = malloc (sizeof (chunk));
n->len = 0;
n->next = bank;
bank = n;
}
const char *
StringBank_AddString (const char *str)
{
int len = strlen (str);
chunk *x = bank;
if (len > CHUNK_SIZE)
return NULL;
while (x) {
int remaining = CHUNK_SIZE - x->len;
if (len < remaining) {
char *result = x->data + x->len;
strcpy (result, str);
x->len += len + 1;
return result;
}
x = x->next;
}
/* No room in any currently existing chunk */
add_chunk ();
strcpy (bank->data, str);
bank->len += len + 1;
return bank->data;
}
const char *
StringBank_AddOrFindString (const char *str)
{
int len = strlen (str);
chunk *x = bank;
if (len > CHUNK_SIZE)
return NULL;
while (x) {
int i = 0;
while (i < x->len) {
if (!strcmp (x->data + i, str))
return x->data + i;
while (x->data[i]) i++;
i++;
}
x = x->next;
}
/* We didn't find it, so add it */
return StringBank_AddString (str);
}
#ifdef DEBUG
void
StringBank_Dump (FILE *s)
{
chunk *x = bank;
while (x) {
int i = 0;
while (i < x->len) {
fprintf (s, "\"%s\"\n", x->data + i);
while (x->data[i]) i++;
i++;
}
x = x->next;
}
}
#endif
|
Java | UTF-8 | 215 | 2.046875 | 2 | [] | no_license | package com.cms.exceptions;
import com.cms.frameclass.StateCode;
public class DBBoonException extends CMSException {
public DBBoonException(String message) {
super(StateCode.DB_BOON, message);
}
}
|
Shell | UTF-8 | 1,392 | 3.71875 | 4 | [] | no_license | #!/bin/bash
set -x
#CMI Annapolis PACS
ipAddr1="172.16.1.3"
dbName1="pacsdbcmi"
file1="cmi_studies_annap_pacs.txt"
var1="$ipAddr1 $dbName1"
#CMI cloud instance
ipAddr2="192.168.179.12"
dbName2="pacsdbcmi"
file2="cmi_studies_cloud.txt"
var2="$ipAddr2 $dbName2"
FILES="cmi_studies_annap_pacs.txt cmi_studies_cloud.txt cmi_studies_all.txt tmp1 tmp2"
cd /home/admin/scripts/cmi/
# delete old stuff if it exists
for file in $FILES
do
if [ -e "$file" ]; then # Check if file exists.
echo "Removing $file.";
rm $file
else
echo "$file does not exist.";
fi
done
# date to use in mySQL query
YEST=$(date +%Y-%m-%d -d "yesterday")
echo $YEST
# define date span to search for mySQL studies
YEST_RANGE="\"$YEST 00:00:00\" AND \"$YEST 23:59:59\""
echo $YEST_RANGE
selectvar="select pat_id,study_datetime, study_desc,num_series,num_instances from patient,study \
where patient.pk = study.patient_fk AND study.created_time BETWEEN $YEST_RANGE \
order by pat_id;"
mysql -uroot -pdgfsty16 -h $var1 -e "$selectvar" > $file1
mysql -uroot -pdgfsty16 -h $var2 -e "$selectvar" > $file2
sort -o $file1 $file1
sort -o $file2 $file2
#sort $file1 > tmp1; cat tmp1 > $file1
#sort $file2 > tmp2; mv tmp2 > $file2
comm -3 $file1 $file2 | sort > cmi_studies_all.txt
#cat yesterday.txt | column -t -s $'\t'| mail -s "Studies from $YEST" rrosenbaum@securerad.com, pjackson@purview.net, dweissman@purview.net, cdykstra@securerad.com
exit 0
|
Ruby | UTF-8 | 852 | 3.265625 | 3 | [] | no_license | require 'pathname'
require 'io/console'
def is_directory_valid dir
bool = (File.directory?(dir))? true : false
end
def is_file_valid filename
bool = (File.file?(filename))? true : false
end
def count_bits pathname
pn = Pathname.new(pathname)
dir, basename = pn.split
set_bits_counter = 0
unset_bits_counter = 0
if is_directory_valid(dir)
if is_file_valid(pn)
File.open(pn,'r') do|file|
until file.eof?
buffer = file.readchar.to_s.unpack("B*")[0]
set_bits_counter+= buffer.count('1')
unset_bits_counter+= buffer.count('0')
end
result = "found #{set_bits_counter} bits set to 1,found #{unset_bits_counter} bits set to 0 "
end
else
error = 'Given File is not a valid File.'
end
else
error = 'Given directoory is not a valid direcotry.'
end
end
|
Java | UTF-8 | 249 | 2.390625 | 2 | [] | no_license | package com.ikea.warehouse.exceptions;
public class ObjectNotFoundException extends RuntimeException {
public ObjectNotFoundException(String objectName, long id) {
super("Cannot find Object " + objectName + " with id : " + id);
}
}
|
Java | UTF-8 | 465 | 2.859375 | 3 | [] | no_license | package mhp;
public class MhpLoopNode extends MhpNode {
public MhpNode s;
public MhpLoopNode(MhpNode s) {
this.s = s;
}
public String toString() {
String string = "Loop - (";
if (s != null)
string += s.toString();
else
string += " ";
string += ")";
return string;
}
public MhpInfo accept(MhpInfoGenerator gen){
return gen.visit(this);
}
public MhpNode accept(MhpVisitor vis, int level) {
return vis.unfold(this, level);
}
}
|
Markdown | UTF-8 | 2,497 | 2.609375 | 3 | [] | no_license | ConNextor
=========
### Description
ConNextor is a web platform to gather bright minds, spawn creativity and build projects.
(add in more!!)
### Running this application
#### Prerequisites
You need the following installed, preferably on a Linux system. _The versions are what is used during core development, use other versions at your own risk._
* **Ruby**, version 2.1.5
* **PostgreSQL**, version 9.3.5
See `docs/` for stripped-down guides to install them.
#### Installation
```bash
git clone https://github.com/tlulu/ConNextor.git # Clone this repository
cd ConNextor/ # Go to working directory
bundle install # Installs the correct gems
rake db:migrate # Import the database
rake db:seed # Seed the database
rake test # Run test suites
rails server # Start the server
```
#### Configuration
See the `config/` folder to see configuration details and make changes as you need. `database.yml` is not version controlled, so configure it to local environment.
Need some keys for OmniAuth. (will add later)
### Application Stack and Frameworks
* Frontend
* [Sass](http://sass-lang.com/) with [Compass](http://compass-style.org/), which compiles to CSS3 (with [Rails Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html)); Helps produce more readable and dynamic code, and Compass helps align the frontend to modern design patterns
* [Bootstrap](http://getbootstrap.com/) libraries for styling and formatting; Robust, small and has critical components for mobile support
* JavaScript, with libraries including [jQuery](http://jquery.com/); Powerful with a multitude of functionalities for interactive elements
* Backend
* [Ruby on Rails](http://rubyonrails.org/), see gem versions in `Gemfile`; Stable MVC framework that is easy to start because of [Rails generators](http://guides.rubyonrails.org/command_line.html#rails-generate), and has a large community to support it
* OmniAuth from [Twitter](https://dev.twitter.com/), [Facebook](https://developers.facebook.com/) and [LinkedIn](https://developer.linkedin.com/); Widely used for better security and easy login
* Operating System
* Unix-based system; Ease of development
### Styling and other
See `docs/` folder for more documentation on style, and installation of prerequisites.
|
Java | UTF-8 | 3,898 | 2.6875 | 3 | [] | no_license | package hangMan;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
public class WinScreen extends JPanel implements ActionListener{
private JPanel background;
private JPanel mainPanel;
/**
* first half of screen
*/
private JPanel imagePanel;
private JLabel imageLabel;
private ImageIcon imageIcon;
/**
* second half of screen
*/
private JPanel textPanel;
private JTextArea textArea;
private JPanel buttonPanel;
private JPanel playPanel;
private JButton playButton;
private JPanel quitPanel;
private JButton quitButton;
private JPanel blankPanel;
/**
* other classes called
*/
private HangManFrame hmf;
private Words words;
public WinScreen(HangManFrame hmf, Words words){
this.hmf=hmf;
this.words=words.copy();
playSound("sounds/fireWorks.wav");
/**
* background
*/
background=new PaintImage("images/chalkboardDefault.png");
background.setLayout(new FlowLayout());
add(background);
background.setPreferredSize(new Dimension(1024,672));
buildImagePanel();
background.add(imagePanel);
buildTextPanel();
textPanel.setPreferredSize(new Dimension(700,100));
background.add(textPanel);
/**
* mainPanel
*/
mainPanel=new JPanel(new GridLayout(2,1));
mainPanel.setOpaque(false);
background.add(mainPanel);
/**
* adding components
*/
//buildTextPanel();
//mainPanel.add(textPanel);
buildButtonPanel();
blankPanel=new JPanel();
blankPanel.setOpaque(false);
mainPanel.add(blankPanel);
mainPanel.add(buttonPanel);
}
public void buildImagePanel(){
imagePanel=new JPanel();
imagePanel.setOpaque(false);
imageIcon=new ImageIcon("images/hangManWin.png");
imageLabel=new JLabel(imageIcon);
imageLabel.setOpaque(false);
imagePanel.add(imageLabel);
}
public void buildTextPanel(){
textPanel=new JPanel();
textPanel.setOpaque(false);
/**
* building text
*/
textArea=new JTextArea();
textArea.setText("You Won!\nThe word was "+words.getGameWord()+"\nGreat job.");
//textArea.setText("You saved Jiffy from the evil\nclutches of PeterPanPenutButter!\nGood work, solider");
textArea.setBackground(Color.WHITE);
//textArea.setPreferredSize(new Dimension(500,500));
textArea.setBorder(null);
textArea.setEditable(false);
textArea.setFont(hmf.getFont(28));
textArea.setOpaque(false);
textArea.setWrapStyleWord(true);
textArea.setForeground(Color.WHITE);
textPanel.add(textArea);
}
public void buildButtonPanel(){
/**
* building buttonPanel
*/
buttonPanel=new JPanel(new FlowLayout());
buttonPanel.setOpaque(false);
/**
* building playButton
*/
playPanel=new JPanel();
playPanel.setPreferredSize(new Dimension(250,100));
playPanel.setOpaque(false);
playButton=new LetterButton("Play Again?");
playButton.addActionListener(this);
playPanel.add(playButton);
/**
* building quitButton
*/
quitPanel=new JPanel();
quitPanel.setPreferredSize(new Dimension(200,100));
quitPanel.setOpaque(false);
quitButton=new LetterButton("Quit");
quitButton.addActionListener(this);
quitPanel.add(quitButton);
/**
* adding components
*/
buttonPanel.add(playPanel);
buttonPanel.add(quitPanel);
}
public void playSound(String fileName){
try{
Clip clip=AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(fileName)));
clip.start();
}catch(Exception e){
System.out.println(e);
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(playButton)){
hmf.remove(this);
hmf.addHangManGui();
}
if(e.getSource().equals(quitButton)){
System.exit(0);
}
}
}
|
Java | UTF-8 | 2,834 | 3.359375 | 3 | [] | no_license | package color_factory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import javax.vecmath.Color3f;
public class ColorFactory {
/** The cubic bezier curve interpolates the colors. */
private CubicBezierCurve3f colorCurve = null;
/** This map collects all the registered objects. */
private Hashtable indexMap = new Hashtable();
public ColorFactory() {
if (colorCurve == null) {
// we use a cubic bezier curve for interpolation of the colors
colorCurve = new CubicBezierCurve3f();
ArrayList colors = new ArrayList();
float max = 0.9f;
float max2 = 0.9f;
float min = 0.2f;
float min2 = 0.2f;
// blue is perceived darker, thus we saturate it a little more than
// the other colors
colors.add(new Color3f(0.3f, 0.3f, 1));
colors.add(new Color3f(min, max2, max2));
colors.add(new Color3f(min2, max, min2));
colors.add(new Color3f(max2, max2, min));
colors.add(new Color3f(max, min2, min2));
colorCurve.setCoordinates(colors);
}
}
/**
* Maps a string to a certain color.
*
* @param object Description of parameter.
*
* @return <code>Color3f</code> - the color mapped to the specified char.
*/
public Color3f computeColor(Object object, float brightnessFactor) {
Float objectFloat = (Float) indexMap.get(object);
if (objectFloat == null) {
objectFloat = register(object);
}
float parameter = objectFloat.floatValue();
Color3f color = new Color3f();
color.set(colorCurve.computePoint(parameter));
color.scale(brightnessFactor);
return color;
}
/**
* Description of the method Registers a string to the static object list.
*
* @param object Description of parameter.
*/
public Float register(Object object) {
if (!indexMap.containsKey(object)) {
float parameter = 0;
int numerator = indexMap.size();
if (numerator != 0) {
int exp = (int) (Math.log(numerator) / Math.log(2));
int denominator = (int) Math.pow(2, exp);
if (numerator != denominator) {
exp++;
denominator *= 2;
}
numerator -= (denominator / 2);
numerator = 2 * numerator - 1;
parameter = numerator;
parameter /= denominator;
}
Float value = new Float(parameter);
indexMap.put(object, value);
return value;
}
return (Float) indexMap.get(object);
}
public Iterator getIndexIterator() {
return indexMap.keySet().iterator();
}
}
|
C | UTF-8 | 1,959 | 2.921875 | 3 | [] | no_license | #ifndef ARRAY_LIST_H_
#define ARRAY_LIST_H_
#include <stdlib.h>
#include "mat4.h"
#include "terrain.h"
#define DEFINE_ARRAY_LIST(T, name) \
typedef struct { \
T *data; \
int capacity; \
int length; \
} ArrayList_##name; \
ArrayList_##name *array_list_new_##name(); \
void array_list_free_##name(ArrayList_##name *data); \
void array_list_push_##name(ArrayList_##name *array, T data); \
void array_list_remove_at_##name(ArrayList_##name *array, int index); \
void array_list_grow_##name(ArrayList_##name *array); \
void array_list_grow_to_capacity_##name(ArrayList_##name *array, \
size_t size); \
void array_list_shrink_to_fit_##name(ArrayList_##name *array);
// array list of void pointers... needs a free element function pointer
typedef struct {
void **data;
void (*free_element)(void *element);
int capacity;
int length;
} ArrayList;
ArrayList *array_list_new(void (*free_element)(void *element));
void array_list_free(ArrayList *data);
void array_list_push(ArrayList *array, void *data);
void array_list_remove_at(ArrayList *array, int index);
void array_list_grow(ArrayList *array);
void array_list_grow_to_capactiy(ArrayList *array, size_t size);
void array_list_shrink_to_fit(ArrayList *array);
DEFINE_ARRAY_LIST(float, f)
DEFINE_ARRAY_LIST(int, i)
DEFINE_ARRAY_LIST(short, s)
DEFINE_ARRAY_LIST(Mat4, m4)
DEFINE_ARRAY_LIST(TerrainVertex, tv)
DEFINE_ARRAY_LIST(Vec3, v3)
#endif |
C | UTF-8 | 315 | 3.546875 | 4 | [] | no_license | #include<stdio.h>
#include<string.h>
int main()
{
char s[100],s1[100];
int i,j;
printf("Enter a string:");
gets(s);
printf("\nEnter a another string:");
gets(s1);
i=strlen(s);
for(j=0;j<strlen(s1);j++)
{
s[i]=s1[j];
i++;
}
printf("\nThe concatinated string:%s",s);
}
|
Python | UTF-8 | 769 | 3.375 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
"""temp= head # method 1
length=0
while(temp):
length=length+1
temp=temp.next
ll_length=length
ran=(int(ll_length/2))
temp= head
for i in range(ran):
temp=temp.next
return temp"""
slow=head # method 2 simultaneously move 2 pointers
fast=head
while(fast!=None and fast.next!=None):
slow=slow.next
fast=fast.next.next
return slow
|
Java | UTF-8 | 3,233 | 2.328125 | 2 | [] | no_license | package com.thelearningproject.pessoa.gui;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import com.thelearningproject.R;
import com.thelearningproject.infraestrutura.utils.Auxiliar;
import com.thelearningproject.infraestrutura.utils.ControladorSessao;
import com.thelearningproject.infraestrutura.utils.UsuarioException;
import com.thelearningproject.pessoa.dominio.Pessoa;
import com.thelearningproject.usuario.dominio.Usuario;
import com.thelearningproject.usuario.negocio.UsuarioServices;
/**
* The type Alterar email activity.
*/
public class AlterarEmailActivity extends AppCompatActivity {
private EditText alterarEmail;
private Auxiliar auxiliar = new Auxiliar();
private ControladorSessao sessao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alterar_email);
setTitle(R.string.alterarEmail);
sessao = ControladorSessao.getInstancia(this.getApplicationContext());
alterarEmail = (EditText) findViewById(R.id.emailID);
alterarEmail.setText(sessao.getPessoa().getUsuario().getEmail());
alterarEmail.setSelection(alterarEmail.getText().length());
Auxiliar.abrirTeclado(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.salvar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.salvarBtn) {
alterar();
}
Auxiliar.esconderTeclado(AlterarEmailActivity.this);
return super.onOptionsItemSelected(item);
}
private void executarAlterar(Usuario usuario) throws UsuarioException {
UsuarioServices negocioUsuario = UsuarioServices.getInstancia(getBaseContext());
negocioUsuario.alterarEmailUsuario(usuario);
Pessoa pessoa = sessao.getPessoa();
pessoa.setUsuario(usuario);
sessao.setPessoa(pessoa);
Auxiliar.criarToast(this, "E-mail atualizado com sucesso");
Intent entidade = new Intent(AlterarEmailActivity.this, ConfiguracaoActivity.class);
entidade.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(entidade);
finish();
}
/**
* Alterar.
*/
public void alterar() {
String email = alterarEmail.getText().toString();
Usuario usuario = sessao.getPessoa().getUsuario();
usuario.setEmail(email);
try {
if (validaAlterar(usuario)) {
executarAlterar(usuario);
}
} catch (UsuarioException e) {
alterarEmail.setError("E-mail já cadastrado");
}
}
private Boolean validaAlterar(Usuario usuario) {
Boolean validacao = true;
if (!auxiliar.aplicaPattern(usuario.getEmail().toUpperCase())) {
alterarEmail.setError("E-mail inválido");
validacao = false;
}
return validacao;
}
}
|
Markdown | UTF-8 | 1,260 | 3.0625 | 3 | [
"MIT"
] | permissive | # Web Share Shim
A polyfill for the WebShare API. It provides `navigator.share()` so you can share content on any device via WhatsApp, Telegram, Facebook, e-mail, and SMS.
Try the [demo](http://nimiq.github.io/web-share-shim/demo/)! The whole package is 9.6kB minified, 4kB gzipped and licensed under the MIT License.
## Usage
Open the share dialog by calling `navigator.share`:
```javascript
navigator.share({
title: 'Web Share Shim',
text: 'Check out Web Share Shim — it rocks!',
url: 'http://nimiq.github.io/web-share-shim',
})
.then( _ => console.log('Successful share'))
.catch( error => console.log('Error sharing', error));
```
Attribute | Options | Default | Description
----------|---------|---------|------------
title | String | "" | A short title of what you are sharing.
text | String | "" | A text describing what you are sharing.
url | URL as String | "" | A link to what you are sharing.
facebookId | number | "158651941570418" | ID of your facebook app if you want to support sharing to facebook on a desktop device. (default ID for demo only)
## Build source code
You need to have gulp and all dependencies installed.
```sh
npm install
npm install gulp
```
Then run `gulp` to build `web-share-shim.bundle.min.js`.
|
Java | UTF-8 | 2,410 | 2.09375 | 2 | [] | no_license | package com.example.hangtrantd.dacnpm.home;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.hangtrantd.dacnpm.R;
import com.example.hangtrantd.dacnpm.util.Api;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Copyright © 2017 Asian Tech Co., Ltd.
* Created by atHangTran on 09/10/2017.
*/
public class InforFragment extends Fragment {
private RecyclerView mRecyclerView;
private InforAdapter mAdapter;
private List<Infor> mInfors;
private static Infor mInfor;
private InforAdapter.OnClickListener mOnClick = new InforAdapter.OnClickListener() {
@Override
public void click(Integer position) {
mInfor = mInfors.get(position);
MainActivity.initFragment(new DetailInforFragment());
}
};
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_information, container, false);
mRecyclerView = view.findViewById(R.id.recyclerInfor);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
mInfors = new ArrayList<>();
getInfors();
return view;
}
public static Infor getInfor() {
return mInfor;
}
private void getInfors() {
Api.getApiService().getInfors().enqueue(new Callback<List<Infor>>() {
@Override
public void onResponse(@NonNull Call<List<Infor>> call, @NonNull Response<List<Infor>> response) {
mInfors = response.body();
if (mInfors != null) {
mAdapter = new InforAdapter(mInfors, getActivity(), mOnClick);
mRecyclerView.setAdapter(mAdapter);
}
}
@Override
public void onFailure(@NonNull Call<List<Infor>> call, @NonNull Throwable t) {
}
});
}
}
|
Java | UTF-8 | 3,532 | 2.515625 | 3 | [] | no_license | package study.wyy.datatransfer.spring.utils;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author wyaoyao
* @description
* @date 2021/1/20 15:53
*/
public class ClassUtils {
public static <T> Class<T> getGenericClassOnInterface(Class clz, Class interfaceClz, int index, Class defaultClz) {
return getGenericClassOnInterface(clz, interfaceClz, index, defaultClz, new Type[]{});
}
public static <T> Class<T> getGenericClassOnInterface(Class clz, Class interfaceClz, int index, Class defaultClz, Type[] previousTypes) {
if (clz == null) {
return defaultClz;
}
TypeVariable[] typeParameters = clz.getTypeParameters();
Map<String, Type> typeParameterMap = typeParameters.length > 0 ? new HashMap<>(typeParameters.length) : Collections.emptyMap();
for (int i = 0; i < typeParameters.length; i++) {
TypeVariable typeVariable = typeParameters[i];
typeParameterMap.put(typeVariable.getName(), previousTypes.length > i ? previousTypes[i] : null);
}
Type[] genericInterfaces = clz.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
if (genericInterface instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) genericInterface;
boolean matchInterface = interfaceClz == null || pType.getRawType().getTypeName().equalsIgnoreCase(interfaceClz.getTypeName());
if (matchInterface && pType.getActualTypeArguments().length > index) {
Type type = pType.getActualTypeArguments()[index];
if (type instanceof ParameterizedType) {
return (Class<T>) ((ParameterizedType) type).getRawType();
}
Type previousType = typeParameterMap.get(type.getTypeName());
if (previousType instanceof ParameterizedType) {
return (Class<T>) ((ParameterizedType) previousType).getRawType();
}
if (type instanceof Class) {
return (Class<T>) type;
}
if (previousType instanceof Class) {
return (Class<T>) previousType;
}
}
}
}
Type genericSuperclass = clz.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type[] types = parameterizedType.getActualTypeArguments();
return getGenericClassOnInterface(clz.getSuperclass(), interfaceClz, index, defaultClz, types);
}
return getGenericClassOnInterface(clz.getSuperclass(), interfaceClz, index, defaultClz, new Type[]{});
}
public static <A extends Annotation> A getAnnotation(Object object, Class<A> annotationClass) {
Class clazz = object.getClass();
while (clazz != null) {
//noinspection unchecked
A annotation = (A) clazz.getAnnotation(annotationClass);
if (null != annotation) {
return annotation;
} else {
clazz = clazz.getSuperclass();
}
}
return null;
}
}
|
C++ | UTF-8 | 8,572 | 3.234375 | 3 | [] | no_license | #include "lib.h"
#include "logger.h"
#include <math.h>
#include <iostream>
#include <SDL/SDL_image.h>
using namespace std;
void read_obj(const char *filename, GLfloat (*vertices)[3], GLfloat (*textures)[2], GLfloat (*normals)[3]) {
}
void matrixMultiply(float* matrix, float* vector, float* result) {
float sum;
for (int i = 0; i < 4; ++i) {
sum = 0;
for (int j = 0; j < 4; ++j) {
sum += matrix[j * 4 + i] * vector[j];
}
result[i] = sum;
}
}
void buildYRotationMatrix(float *matrix, float angle) {
matrix[0] = cos(angle);
matrix[1] = 0;
matrix[2] = -1 * sin(angle);
matrix[3] = 0;
matrix[4] = 0;
matrix[5] = 1;
matrix[6] = 0;
matrix[7] = 0;
matrix[8] = sin(angle);
matrix[9] = 0;
matrix[10] = cos(angle);
matrix[11] = 0;
matrix[12] = 0;
matrix[13] = 0;
matrix[14] = 0;
matrix[15] = 1;
}
float angleBetweenVectors(float * vector1, float * vector2) {
// Calculate the dot product
float dotProduct =
vector1[0] * vector2[0] +
vector1[1] * vector2[1] +
vector1[2] * vector2[2];
float absVector1 = sqrt(
vector1[0] * vector1[0] +
vector1[1] * vector1[1] +
vector1[2] * vector1[2]);
float absVector2 = sqrt(
vector2[0] * vector2[0] +
vector2[1] * vector2[1] +
vector2[2] * vector2[2]);
// make sure we don't divide by zero
if (absVector1 == 0 || absVector2 == 0) {
cout << "Error: Divide by zero in angleBetweenVectors-> "
<< absVector1 << ", " << absVector2 << endl;
return 0;
}
// Calculate angle and convert into degrees
float tmp = dotProduct / (absVector1 * absVector2);
if (fabs(tmp) >= 1) {
return 0;
} else {
float result = (acos(tmp) * 180.0) / PI;
if (isnan(result))
{
cout << "result: " << tmp << endl;
}
return result;
}
}
float angleInZPlane(float * vector1, float * vector2) {
// Project vectors onto x plane (saving the z-values)
float result;
float z1 = vector1[2];
float z2 = vector2[2];
// NOTE: I'm not convinced this is a good idea. It's quicker than copying the vectors
// to something on the stack, but makes this function side effect in a strange way.
vector1[2] = 0;
vector2[2] = 0;
result = angleBetweenVectors(vector1, vector2);
// Restore the z-values
vector2[2] = z1;
vector2[2] = z2;
return result;
}
float angleInPlaneZ(float * vector1, float * vector2, float * planeVector) {
float zVector[3];
zVector[0] = 0;
zVector[1] = 0;
zVector[2] = 1;
return angleInPlane(vector1, vector2, planeVector, zVector);
}
float angleInPlaneY(float * vector1, float * vector2, float * planeVector) {
float yVector[3];
yVector[0] = 0;
yVector[1] = 1;
yVector[2] = 0;
return angleInPlane(vector1, vector2, planeVector, yVector);
}
float angleInPlane(float * vector1, float * vector2, float * planeVector, float * planeVector2) {
// We need to project vector1 and vector2 onto the plane defined by
// planeVector x { 0, 1, 0 }
float tmp1[3];
float tmp2[3];
float tmpn[3];
float n[3];
float t;
float angle;
// Calculate the plane
crossProduct(planeVector, planeVector2, n);
// Check that the normal vector isn't 0
if (n[0] * n[0] + n[1] * n[1] + n[2] * n[2] == 0) {
return 0;
}
normaliseVector(n);
// Do the projection, d = 0 because the plane goes through the origin
// R = Q - (n . Q) . n
// .. first for vector1
t = dotProduct(n, vector1);
vertexMultiply(t, n, tmp1);
vertexSub(vector1, tmp1, tmp1);
// .. then for the escond one
t = dotProduct(n, vector2);
vertexMultiply(t, n, tmp2);
vertexSub(vector2, tmp2, tmp2);
// .. now we find the angle between those two
angle = angleBetweenVectors(tmp1, tmp2);
if (isnan(angle))
{
cout << "Angle is nan: " << angle << endl;
cout << tmp1[0] << " : " << tmp2[0] << endl;
return 0;
}
// We work out the sign on the angle by whether the cross product of the tmp1 and tmp2
// matches the direction of n
crossProduct(tmp1, tmp2, tmpn);
// Avoid the chance of tmp1 = tmp2
if (tmpn[0] * tmpn[0] + tmpn[1] * tmpn[1] + tmpn[2] * tmpn[2] != 0) {
normaliseVector(tmpn);
// Swap the sign of the angle if the normals dont' match
if (vertexDistance(tmpn, n) < 0.000001) angle *= -1;
}
return angle;
}
float dotProduct(float * a, float * b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
void vertexSub(float * a, float * b, float * result) {
result[0] = a[0] - b[0];
result[1] = a[1] - b[1];
result[2] = a[2] - b[2];
}
void vertexCopy(float * from, float * to) {
to[0] = from[0];
to[1] = from[1];
to[2] = from[2];
}
void crossProduct(float * a, float * b, float * result) {
float tmp[3];
tmp[0] = a[1] * b[2] - b[1] * a[2];
tmp[1] = -1 * a[0] * b[2] + b[0] * a[2];
tmp[2] = a[0] * b[1] - b[0] * a[1];
vertexCopy(tmp, result);
}
void vertexMultiply(float * a, float * b, float * result) {
result[0] = a[0] * b[0];
result[1] = a[1] * b[1];
result[2] = a[2] * b[2];
}
void vertexMultiply(float a, float * b, float * result) {
result[0] = a * b[0];
result[1] = a * b[1];
result[2] = a * b[2];
}
void vertexAdd(float * a, float * b, float * result) {
result[0] = a[0] + b[0];
result[1] = a[1] + b[1];
result[2] = a[2] + b[2];
}
float vertexDistance(float * a, float * b) {
float tmp[3];
vertexSub(b, a, tmp);
return sqrt(tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2]);
}
float vertexSquareDistance(float * a, float * b) {
float tmp[3];
vertexSub(b, a, tmp);
return tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2];
}
float vectorLength(float * a) {
return sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
}
bool normaliseVector(float * a) {
float length = vectorLength(a);
if (length == 0) return false;
a[0] /= length;
a[1] /= length;
a[2] /= length;
return true;
}
void printVector(float * a) {
cout << "{ " << a[0] << ", " << a[1] << ", " << a[2] << "}" << endl;
}
bool vectorEquals(float * a, float * b) {
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2];
}
bool colorEquals4(float * a, float * b) {
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && b[3] == a[3];
}
bool colorCopy4(float * from, float * to) {
to[0] = from[0];
to[1] = from[1];
to[2] = from[2];
to[3] = from[3];
return true;
}
void horizontalFlipSurface(SDL_Surface * surface) {
// The documentation says to lock the surface, I think this is to make sure the
// pointer to pixels doesnt' change. Probably OK, as there shouldn't me > 1 thread
// on this
SDL_LockSurface(surface);
// We use int as a 4 byte type, this is not that neat, should probably use char,
// but not sure whether memcpy is the thing to use
int tmp;
int * pixels = (int *)surface->pixels;
int width = surface->w;
int height = surface->h;
int a, b;
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height / 2; ++j) {
a = j * width + i;
b = (height - 1 - j) * width + i;
tmp = pixels[a];
pixels[a] = pixels[b];
pixels[b] = tmp;
}
}
SDL_UnlockSurface(surface);
}
void printError() {
unsigned int error = glGetError();
if (error != GL_NO_ERROR) {
cout << "OpenGL error: " << gluErrorString(error) << endl;
}
}
Vector momentDistance(Vector & a, Vector & vector, Vector & cog) {
// Get a second point
Vector n(3);
Vector tmp(3);
Vector ac(3);
float t;
float l;
// Find the closest point from origin to line defined by a -> b
// closest point = a + t(b - a)
// n = (b - a) / |b - a|
l = vector.magnitude();
// If l is 0, we set result to 0
if (l == 0) {
return Vector(0, 0, 0);
}
n = (1.0 / l) * vector;
//vertexCopy(vector, n);
//vertexMultiply(1.0 / l, n, n);
// t = (O - a) . n / |b - a|
ac = cog - a;
//vertexSub(cog, a, ac);
t = (ac * n) / l;
//t = dotProduct(ac, n) / l;
// closest point = a + t(b - a)
//vertexMultiply(t, vector, tmp);
//vertexAdd(a, tmp, tmp);
// Vector from p to cog
//vertexSub(cog, tmp, result);
return cog - (a + (t * vector));
}
|
Java | UTF-8 | 600 | 1.984375 | 2 | [] | no_license | package com.blog4android.crashreporter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class Receiver extends BroadcastReceiver {
private ReceiverSuport receiveSuport;
@Override
public void onReceive(Context context, Intent intent) {
Intent dataIntent=new Intent(context, ServiceReportCrash.class);
dataIntent.putExtra(Utilities.INTENT_KEY.SRC,Utilities.INTENT_KEY.SRC_RECEIVER);
context.startService(dataIntent);
}
}
|
Java | UTF-8 | 2,589 | 3.3125 | 3 | [] | no_license | package biblioteca;
public class Libro {
private String titulo_libro;
private String autor;
private int num_ejemplares;
private int num_ejemplares_prest;
// CONSTRUCTOR POR DEFECTO //
public Libro(){
}
// CONSTRUCTOR CON PARAMETROS //
public Libro(String titulo_libro, String autor, int num_ejemplares,
int num_ejemplares_prest){
this.titulo_libro = titulo_libro;
this.autor = autor;
this.num_ejemplares = num_ejemplares;
this.num_ejemplares_prest = num_ejemplares_prest;
}
// SETTER Y GETTER //
public void setTituloLibro(String titulo_libro){
this.titulo_libro = titulo_libro;
}
public void setAutor(String autor){
this.autor = autor;
}
public void setNumEjemplares(int num_ejemplares){
this.num_ejemplares = num_ejemplares;
}
public void setNumEjemplaresPrestados(int num_ejemplares_prest){
this.num_ejemplares_prest = num_ejemplares_prest;
}
public String getTituloLibro(){
return this.titulo_libro;
}
public String getAutor(){
return this.autor;
}
public int getNumEjemplares(){
return this.num_ejemplares;
}
public int getNumEjemplaresPrestados(){
return this.num_ejemplares_prest;
}
// METODO PRESTAMO //
public boolean prestamo(){
if(num_ejemplares > 0){
this.num_ejemplares_prest++;
this.num_ejemplares--;
System.out.println("Prestamo realizado con éxito.");
System.out.print("Disponibles: "+this.getNumEjemplares()+", ");
System.out.println("Prestados: "+this.getNumEjemplaresPrestados());
return true;
}else{
System.out.println("ERROR! No quedan libros para prestar.");
return false;
}
}
// METODO DEVOLUCION //
public boolean devolucion(){
if(num_ejemplares_prest > 0){
this.num_ejemplares_prest--;
this.num_ejemplares++;
System.out.println("Devolución realizada con éxito.");
System.out.print("Disponibles: "+this.getNumEjemplares()+", ");
System.out.println("Prestados: "+this.getNumEjemplaresPrestados());
return true;
}else{
System.out.println("ERROR! No existen libros prestados.");
return false;
}
}
}
|
Python | UTF-8 | 101 | 3.3125 | 3 | [] | no_license | num=int(input("introduzca numero: "))
if num %2 == 0:
print ("par")
else:
print ("impar") |
Python | UTF-8 | 9,895 | 2.78125 | 3 | [] | no_license | from __future__ import absolute_import, division
import argparse
import csv
import datetime
import os
from pathlib import Path
import time
import torch
from tqdm.auto import tqdm
from transformers import BertForQuestionAnswering
from dataset_korquad import KorquadDataset
from evaluate_korquad import exact_match_score, f1_score
def inference_start_end(
start_probs: torch.Tensor,
end_probs: torch.Tensor,
context_start_pos: int,
context_end_pos: int,
):
""" Inference fucntion for the start and end token position.
Find the start and end positions of the answer which maximize
p(start, end | context_start_pos <= start <= end <= context_end_pos)
Note: assume that p(start) and p(end) are independent.
Hint: torch.tril or torch.triu function would be helpful.
Arguments:
start_probs -- Probability tensor for the start position
in shape (sequence_length, )
end_probs -- Probatility tensor for the end position
in shape (sequence_length, )
context_start_pos -- Start index of the context
context_end_pos -- End index of the context
"""
assert start_probs.sum().allclose(torch.scalar_tensor(1.0))
assert end_probs.sum().allclose(torch.scalar_tensor(1.0))
### YOUR CODE HERE (~6 lines)
start_pos: int = context_start_pos
end_pos: int = context_start_pos
prob = torch.triu(
torch.ger(
start_probs[context_start_pos : context_end_pos + 1],
end_probs[context_start_pos : context_end_pos + 1],
)
)
values, indices1 = torch.max(prob, 0)
_, indices2 = torch.max(values, 0)
index_col = indices2.item()
index_row = indices1.data[index_col].item()
start_pos += index_row
end_pos += index_col
### END YOUR CODE
return start_pos, end_pos
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(
description="Train the question answering model using pre-trained BERT or MoBERT"
)
parser.add_argument(
"--pretrain",
"-p",
default=os.path.join(".", "bestmodel", "mobert"),
help="Directory of the pretrained bert model",
)
parser.add_argument(
"--output",
"-o",
default=os.path.join(".", "checkpoint", "qa"),
help="Output directory of the trained qa model",
)
parser.add_argument(
"--device",
"-d",
default="cuda" if torch.cuda.is_available() else "cpu",
help="Torch device",
)
args = parser.parse_args()
# Torch settings
torch.set_num_threads(10)
device = torch.device(args.device)
# Set the directories where the models will be saved
bert_dir = args.pretrain
qa_model_dir = os.path.join(
args.output, datetime.datetime.now().strftime("%m-%d_%H-%M-%S")
)
log_path = os.path.join(qa_model_dir, "log.csv")
# If not exist, then create directories
Path(qa_model_dir).mkdir(parents=True, exist_ok=True)
# Open the log file
log_f = open(log_path, "w")
log_writer = csv.writer(log_f)
# Hyperparameters
EPOCHS = 100
LEARNING_RATE = 2e-4
BATCH_SIZE = 32
# Generate the data loader
dataset = KorquadDataset()
train_dataset, val_dataset = torch.utils.data.random_split(
dataset, [int(len(dataset) * 0.9), len(dataset) - int(len(dataset) * 0.9)]
)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=BATCH_SIZE,
shuffle=True,
collate_fn=train_dataset.dataset.collate_fn,
num_workers=2,
)
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=BATCH_SIZE,
shuffle=False,
collate_fn=val_dataset.dataset.collate_fn,
num_workers=2,
) # shuffle is not needed for validation
# Generate question answering model using pretrained bert
model = BertForQuestionAnswering.from_pretrained(bert_dir, num_labels=2)
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
start = time.time()
for epoch in range(1, EPOCHS + 1):
total_train_loss = 0.0
total_train_em = 0.0
total_train_f1 = 0.0
# Training
model.train()
for _, (input_ids, attention_mask, token_type_ids, start_pos, end_pos) in tqdm(
enumerate(train_loader), total=len(train_loader)
):
optimizer.zero_grad()
input_ids = input_ids.to(device)
token_type_ids = token_type_ids.to(device)
attention_mask = attention_mask.to(device)
start_pos = start_pos.to(device)
end_pos = end_pos.to(device)
out = model(
input_ids=input_ids,
token_type_ids=token_type_ids,
attention_mask=attention_mask,
start_positions=start_pos,
end_positions=end_pos,
)
loss = out[0]
start_logits = out[1]
end_logits = out[2]
"""
start_ids = torch.argmax(start_logits, dim=1)
end_ids = torch.argmax(end_logits, dim=1)
"""
start_probs = torch.nn.functional.softmax(start_logits, dim=1)
end_probs = torch.nn.functional.softmax(end_logits, dim=1)
loss.backward()
optimizer.step()
num_batch = input_ids.size(0)
total_train_loss += loss.item() * num_batch
for b in range(num_batch):
start_pos_pred, end_pos_pred = inference_start_end(
start_probs[b], end_probs[b], 0, input_ids.size(1)
)
token_ids_ans = input_ids[b, start_pos[b] : end_pos[b] + 1].tolist()
token_ids_pred = input_ids[
b, start_pos_pred : end_pos_pred + 1
].tolist()
decode_ans = dataset.decode(token_ids_ans)
decode_pred = dataset.decode(token_ids_pred)
em = exact_match_score(decode_pred, decode_ans)
f1 = f1_score(decode_pred, decode_ans)
total_train_em += em
total_train_f1 += f1
avg_train_loss = total_train_loss / len(train_dataset)
avg_train_em = total_train_em / len(train_dataset)
avg_train_f1 = total_train_f1 / len(train_dataset)
# Validation
total_val_loss = 0.0
total_val_em = 0.0
total_val_f1 = 0.0
model.eval()
with torch.no_grad():
for (
input_ids,
attention_mask,
token_type_ids,
start_pos,
end_pos,
) in val_loader:
input_ids = input_ids.to(device)
token_type_ids = token_type_ids.to(device)
attention_mask = attention_mask.to(device)
start_pos = start_pos.to(device)
end_pos = end_pos.to(device)
out = model(
input_ids=input_ids,
token_type_ids=token_type_ids,
attention_mask=attention_mask,
start_positions=start_pos,
end_positions=end_pos,
)
loss = out[0]
start_logits = out[1]
end_logits = out[2]
"""
start_ids = torch.argmax(start_logits, dim=1)
end_ids = torch.argmax(end_logits, dim=1)
"""
start_probs = torch.nn.functional.softmax(start_logits, dim=1)
end_probs = torch.nn.functional.softmax(end_logits, dim=1)
num_batch = input_ids.size(0)
total_val_loss += loss.item() * num_batch
for b in range(num_batch):
start_pos_pred, end_pos_pred = inference_start_end(
start_probs[b], end_probs[b], 0, input_ids.size(1)
)
token_ids_ans = input_ids[b, start_pos[b] : end_pos[b] + 1].tolist()
"""
token_ids_pred = input_ids[
b, start_ids[b] : end_ids[b] + 1
].tolist()
"""
token_ids_pred = input_ids[
b, start_pos_pred : end_pos_pred + 1
].tolist()
decode_ans = dataset.decode(token_ids_ans)
decode_pred = dataset.decode(token_ids_pred)
em = exact_match_score(decode_pred, decode_ans)
f1 = f1_score(decode_pred, decode_ans)
total_val_em += em
total_val_f1 += f1
avg_val_loss = total_val_loss / len(val_dataset)
avg_val_em = total_val_em / len(val_dataset)
avg_val_f1 = total_val_f1 / len(val_dataset)
# Show the output
elapsed_time = time.time() - start
print(
f"[Epoch {epoch}] Elapsed time: {elapsed_time:.3f}\tAverage train loss: {avg_train_loss:.3f}\tAverage train EM: {avg_train_em:.3f}\tAverage train F1-score: {avg_train_f1:.3f}\tAverage validation loss: {avg_val_loss:.3f}\tAverage validation EM: {avg_val_em:.3f}\tAverage validation F1-score: {avg_val_f1:.3f}"
)
log_writer.writerow(
[
epoch,
elapsed_time,
avg_train_loss,
avg_train_em,
avg_train_f1,
avg_val_loss,
avg_val_em,
avg_val_f1,
]
)
log_f.flush()
bert_dir_epoch = os.path.join(qa_model_dir, str(epoch))
Path(bert_dir_epoch).mkdir(parents=True, exist_ok=True)
model.save_pretrained(bert_dir_epoch)
log_f.close()
|
Java | UTF-8 | 1,392 | 2.5625 | 3 | [] | no_license | package org.websparrow.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.websparrow.dao.StudentDao;
import org.websparrow.model.Employee;
@Controller
public class CreateController {
@Autowired
private StudentDao studentDao;
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createStudent(@RequestParam("employeeName") String name, @RequestParam("employeeDepartment") String department,
@RequestParam("employeeDesignation") String designation,@RequestParam("employeeSalary") int salary, ModelAndView mv) {
Employee student = new Employee();
student.setEmployeeName(name);
student.setEmployeeDepartment(department);
student.setEmployeeDesignation(designation);
student.setEmployeeSalary(salary);
System.out.println(student);
int counter = studentDao.create(student);
if (counter > 0) {
mv.addObject("msg", "Student registration successful.");
} else {
mv.addObject("msg", "Error- check the console log.");
}
mv.setViewName("create");
return mv;
}
}
|
Python | UTF-8 | 2,441 | 2.84375 | 3 | [] | no_license | from unittest import TestCase
from sudokudlx.sparsematrix import SparseMatrix
from sudokudlx.sudoku import SudokuPuzzle
from sudokudlx.fileutil import build_sudoku
from sudokudlx import sudoku
from copy import deepcopy
blank = sudoku.build_blank_board()
class SudokuTests(TestCase):
def testRowColToBox(self):
r,c = 0,0
box = sudoku.row_col_to_box(r,c)
assert box == 0
r,c = 8,8
box = sudoku.row_col_to_box(r,c)
assert box == 8
r,c = 4,4
box = sudoku.row_col_to_box(r,c)
assert box == 4
def testDlxRow(self):
dlxrow = sudoku.dlx_row(0,0,1)
assert len(dlxrow) == 324
assert sum(dlxrow) == 4
assert dlxrow[0] == 1
assert dlxrow[1] == 0
def testDlxRowsForSquare(self):
assert len(sudoku.dlx_rows_for_square(0,0,1)) == 1
assert len(sudoku.dlx_rows_for_square(0,0,0)) == 9
def testEncode(self):
r,c = 0,0
encoded = sudoku.encode(r,c)
assert encoded[0] == 1
assert encoded[1] == 0
def testDecode(self):
encoded = sudoku.encode(0,0)
out_r,out_c = sudoku.decode(encoded)
assert out_r == 0
assert out_c == 0
def testDlxRowToRcv(self):
dlxrow = sudoku.dlx_row(0,0,1)
r,c,v = sudoku.dlx_row_to_rcv(dlxrow)
assert 0 == r
assert 0 == c
assert 1 == v
def testSquaresToDlxRows(self):
blank_dlxrows = sudoku.squares_to_dlx_rows(blank)
assert len(blank_dlxrows) == 729
filledsquares = [[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9]]
filleddlxrows = sudoku.squares_to_dlx_rows(filledsquares)
assert len(filleddlxrows) == 81
def testSudokuPuzzle(self):
blankPuzzle = SudokuPuzzle(blank)
soln = blankPuzzle.solve()
assert soln
assert len(soln) == 9
assert len(soln[0]) == 9
def testNearWorstCase(self):
"""Test a supposedly-hard problem for sudoku solvers"""
puzzle = build_sudoku("testcases/near-worst-case")
soln = puzzle.solve()
assert soln
def testFailureForUnsolveable(self):
"""Shouldn't return a true value for an unsolvable board."""
puzzle = build_sudoku("testcases/fail")
soln = puzzle.solve()
assert not soln
|
C++ | UTF-8 | 788 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
// This method costs too much time
// int climbStairs(int n) {
// if (n < 0) {
// return 0;
// }
// if (n <= 1) {
// return 1;
// }
// return climbStairs(n-1)+climbStairs(n-2);
// }
int climbStairs(int n) {
if (n < 0) {
return 0;
}
if (n <= 1) {
return 1;
}
int pre = 1, current = 2, i = 3;
while (i <= n) {
int t = current;
current += pre;
pre = t;
i++;
}
return current;
}
};
int main() {
Solution s;
cout << s.climbStairs(5) << endl;
return 0;
}
|
C++ | UTF-8 | 719 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#define MAXN 1000
#define MAXVC 5000
#define MAXT 2000
using namespace std;
int DP[MAXT + 1];
int n,t;
typedef pair<int,int> pii;
vector<pii> rods;
int inline max(int x, int y) { return (x > y) ? x : y;};
int solve() {
DP[0] = 0;
for(int i = 1 ; i <= t; i++) {
DP[i] = 0;
for(int j = 0 ; j < n; j++) {
if(rods[j].first <= i) {
DP[i] = max(rods[j].second+DP[i-rods[j].first], DP[i]);
}
}
}
return DP[t];
}
int main(void) {
cin >> n >> t;
int a,b;
for(int i = 0 ; i < n; i++) {
cin >> a >> b;
rods.push_back(pii(a,b));
}
//sort(rods.begin(),rods.end());
cout << solve() << endl;
return 0;
}
|
C | UTF-8 | 2,039 | 3 | 3 | [
"MIT"
] | permissive | #include "header.h"
// in this file we handle cd command and related arguments
ll CD(char **args)
{
// if input is just cd
if (args[1]==NULL)
{
chdir(root);
for(int i=0; i<1024; i++)
{
prev[i] = root[i];
}
return 1;
}
if(strcmp(args[1], "-")!=0)
{
getcwd(prev, 1024);
}
// when input contains more than 1 argument (cd expects max 1)
if (args[2]!=NULL)
{
perror("Couldn't run cd command");
done[0]=':';
done[1]='(';
return 1;
}
else
{
done[0]=':';
done[1]=')';
}
if(strcmp(args[1], "-")==0)
{
char temp[1024];
getcwd(temp, 1024);
printf("%s\n", prev);
if(chdir(prev)<0)
{
perror("Path error:");
done[0]=':';
done[1]='(';
return 1;
}
else
{
done[0]=':';
done[1]=')';
}
for(int i=0; i<1024; i++)
{
prev[i] = temp[i];
}
return 1;
}
// if path given as root
if (strcmp(args[1], "~") == 0)
{
chdir(root);
for(int i=0; i<1024; i++)
{
prev[i] = root[i];
}
return 1;
}
// if path given as current directory
if (strcmp(args[1], ".") == 0)
{
return 1;
}
// if address relative to home is given
if (args[1][0] == '~')
{
char *path=(char *) malloc(1234*sizeof(char));
sprintf(path, "%s/%s", root, args[1] + 2);
if (chdir(path) < 0)
{
done[0]=':';
done[1]='(';
perror("Path error");
}
else
{
done[0]=':';
done[1]=')';
}
free(path);
return 1;
}
if (chdir(args[1]) < 0)
{
perror("Path error");
done[0]=':';
done[1]='(';
return 1;
}
else
{
done[0]=':';
done[1]=')';
}
}
|
Markdown | UTF-8 | 1,185 | 2.671875 | 3 | [] | no_license | # nrx-term
[](https://travis-ci.com/halbu/nrx-term)
`nrx-term` is a hardware-accelerated, browser-based terminal emulator for game development.
<img src="https://raw.githubusercontent.com/halbu/nrx-term/master/img/nrx1.gif" width="45%"></img> <img src="https://raw.githubusercontent.com/halbu/nrx-term/master/img/nrx2.gif" width="45%"></img>
## Motivation and goals
`nrx-term` is intended to assist in developing graphically rich roguelike games.
To this end, `nrx-term` offers:
* Hardware-accelerated rendering - render huge terminals at 60+ FPS with plenty of CPU to spare
* Out-of-the-box handling of keyboard and mouse input
* Support for true color and character rotation
* Small API surface, simple to understand and use (hopefully)
`nrx-term` is purely for terminal display and input handling, and is not opinionated about how you build your game.
## How to use
`nrx-term` is available via `npm`. Install from the command line with `npm i nrx-term`. Import it for use in your project with `import { NRXTerm } from 'nrx-term';`.
## Todo
- [ ] Better documentation
- [ ] Revisit user-facing API
|
C# | UTF-8 | 1,037 | 3.015625 | 3 | [] | no_license | using System;
using Xunit;
using System.Collections.Generic;
namespace markandtoys.tests
{
public class UnitTest1
{
[Fact]
public void Test1()
{
int n = 7, k = 50;
List<int> prices = new List<int>() { 1, 12, 5, 111, 200, 1000, 10 };
int expected = 4;
var sut = Result.maximumToys(prices, k);
Assert.Equal(expected, sut);
}
[Fact]
public void Test2()
{
int n = 4, k = 7;
List<int> prices = new List<int>() { 1, 2, 3, 4 };
int expected = 3;
var sut = Result.maximumToys(prices, k);
Assert.Equal(expected, sut);
}
[Fact]
public void Test3()
{
int n = 5, k = 15;
List<int> prices = new List<int>() { 3, 7, 2, 9, 4 };
int expected = 3;
var sut = Result.maximumToys(prices, k);
Assert.Equal(expected, sut);
}
}
}
|
Python | UTF-8 | 1,358 | 3.4375 | 3 | [] | no_license | test_data = 5
input_data = 3001330
class Elf(object):
n = 0
def __init__(self, right=None):
self.left = None
self.right = right
Elf.n += 1
self.n = Elf.n
def remove_self(self):
self.left.right = self.right
self.right.left = self.left
return self.left
def play_a_game(elves_no: int, part_two=False):
Elf.n = 0
first_elf = Elf()
last_elf = first_elf
for i in range(elves_no - 1):
new_elf = Elf(right=last_elf)
last_elf.left = new_elf
last_elf = new_elf
last_elf.left = first_elf
total_elves = elves_no
current_elf = first_elf
if part_two:
for _ in range(elves_no // 2):
current_elf = current_elf.left
else:
current_elf = current_elf.left
while total_elves > 1:
if part_two:
current_elf = current_elf.remove_self()
if total_elves % 2 == 1:
current_elf = current_elf.left
else:
current_elf = current_elf.remove_self().left
total_elves -= 1
return current_elf.n
def test():
assert play_a_game(test_data, part_two=True) == 2
def main():
test()
print('Day 19 Part 1', play_a_game(input_data))
print('Day 19 Part 2', play_a_game(input_data, part_two=True))
if __name__ == '__main__':
main()
|
JavaScript | UTF-8 | 872 | 2.578125 | 3 | [] | no_license | const throwError = require('./throwAnError');
global.console = {
log: jest.fn(),
};
describe('test try and catch', () => {
test('verify by passing an invalid json', (done) => {
const callbackFn = () => {
expect(global.console.log).toHaveBeenCalledWith('Unexpected token s in JSON at position 0');
done();
};
throwError(callbackFn, 'sdbckj');
});
test('verify by passing an empty string', (done) => {
const callbackFn = () => {
expect(global.console.log).toHaveBeenCalledWith('Unexpected end of JSON input');
done();
};
throwError(callbackFn, '');
});
test('verify the resolve', (done) => {
const callbackFn = () => {
expect(global.console.log).toHaveBeenCalledWith('SUCCESS');
done();
};
const json = JSON.stringify({ hello: 'world' });
throwError(callbackFn, json);
});
});
|
C# | UTF-8 | 463 | 2.859375 | 3 | [] | no_license | namespace ProcessorScheduling
{
public struct Task
{
public Task(int value, int deadline, int index)
{
this.Value = value;
this.Deadline = deadline;
this.Index = index;
}
public int Value { get; }
public int Deadline { get; }
public int Index { get; }
public override string ToString()
{
return this.Index.ToString();
}
}
}
|
Python | UTF-8 | 168 | 2.9375 | 3 | [] | no_license | def calcula_valor_devido(x):
y = 10000 * x * 0.12
return y
print(calcula_valor_devido(9))
'''x é o nº de meses após o emprestimo e y é o valor total pago''' |
C++ | UTF-8 | 2,168 | 2.9375 | 3 | [] | no_license | #include "MorseTranslator.h"
#include "MorseBST.h"
MorseTranslator::MorseTranslator()
{
morseBst = new morsebst::MorseBST();
}
MorseTranslator::~MorseTranslator() {
delete morseBst; // recursivelly will delete all nodes in a binary search tree
}
const char* MorseTranslator::translate2Morse(const char character){
switch (character) {
case 'a':
case 'A':
return ".-";
case 'b':
case 'B':
return "-...";
case 'c':
case 'C':
return "-.-.";
case 'd':
case 'D':
return "-..";
case 'e':
case 'E':
return ".";
case 'f':
case 'F':
return "..-.";
case 'g':
case 'G':
return "--.";
case 'h':
case 'H':
return "....";
case 'i':
case 'I':
return "..";
case 'j':
case 'J':
return ".---";
case 'k':
case 'K':
return "-.-";
case 'l':
case 'L':
return ".-..";
case 'm':
case 'M':
return "--";
case 'n':
case 'N':
return "-.";
case 'o':
case 'O':
return "---";
case 'p':
case 'P':
return ".--.";
case 'q':
case 'Q':
return "--.-";
case 'r':
case 'R':
return ".-.";
case 's':
case 'S':
return "...";
case 't':
case 'T':
return "-";
case 'u':
case 'U':
return "..-";
case 'v':
case 'V':
return "...-";
case 'w':
case 'W':
return ".--";
case 'x':
case 'X':
return "-..-";
case 'y':
case 'Y':
return "-.--";
case 'z':
case 'Z':
return "--..";
case '0':
return "-----";
case '1':
return ".----";
case '2':
return "..---";
case '3':
return "...--";
case '4':
return "....-";
case '5':
return ".....";
case '6':
return "-....";
case '7':
return "--...";
case '8':
return "---..";
case '9':
return "----.";
case ' ':
return "/";
default:
return " ";
}
}
void MorseTranslator::translate2MorseWholeString(const std::string* str, std::string* output)
{
for(std::string::const_iterator it = str->begin(); it != str->end(); ++it)
{
*output += MorseTranslator::translate2Morse(*it);
*output += ' ';
}
}
morsebst::MorseBST *MorseTranslator::getMorseBst() const
{
return morseBst;
}
|
C# | UTF-8 | 1,825 | 3.796875 | 4 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Usando_A_Calculadora.Calculadora
{
public class Calculator
{
static void Main(string[] args)
{
}
public void Calc()
{
double num1, num2;
int resul = 0;
Console.WriteLine("Digite o Primeiro Número: ");
num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Digite o Segundo Número: ");
num2 = double.Parse(Console.ReadLine());
Console.Clear();
while (resul != 5)
{
Console.WriteLine("Para Somar Digite - 1");
Console.WriteLine("Para Subtrair Digite - 2");
Console.WriteLine("Para Dividir Digite 3");
Console.WriteLine("Para Multiplicar Digite - 4");
Console.WriteLine("Para Sair Digite - 5");
Console.WriteLine(" ");
Console.WriteLine("EScolha Uma das Opções: ");
resul = int.Parse(Console.ReadLine());
if (resul == 1)
{
Console.WriteLine("Soma = {0}", num1 + num2);
}
if (resul == 2)
{
Console.WriteLine("Subtração = {0}", num1 - num2);
}
if (resul == 3)
{
Console.WriteLine("Divisão = {0}", num1 / num2);
}
if (resul == 4)
{
Console.WriteLine("Multiplicação = {0}", num1 * num2);
}
Console.ReadLine();
Console.Clear();
}
}
}
}
|
JavaScript | UTF-8 | 3,578 | 2.953125 | 3 | [] | no_license | /**************************************************************************************************************************
** Program name: CS2901 Project scrollBox.js file
** Author: Takahiro Watanabe
** Date: 05/22/18
** Description: This is the JavaScript file to create the scroll box and append to the home page of the Project website
** Source: <Title> HTML Scroll Box
** <Author> Quackit
** <Date of Retrieval> 05/22/18
** <Availability> https://www.quackit.com/html/codes/html_scroll_box.cfm
***************************************************************************************************************************/
var scrollBox = document.createElement("div");
var scrollTitle = document.createElement("h4");
var titleText = document.createTextNode("Welcome to Our Pets Website!");
scrollTitle.appendChild(titleText);
scrollBox.appendChild(scrollTitle);
var scrollP1 = document.createElement("p");
var scrollP2 = document.createElement("p");
var scrollP3 = document.createElement("p");
var scrollP4 = document.createElement("p");
var scrollP5 = document.createElement("p");
var scrollP6 = document.createElement("p");
var scrollP7 = document.createElement("p");
var text1 = "Hello!";
var text2 = "In this website, we will introduce my family’s 3 pets – 2 dogs and 1 cat – and let you download to see some photos of those animals.";
var text3 = "Please have a look at our pets' pictures below. Once you find your favorite guy, just click your favorite one's name in the navigation bar at the top. Then we will take you to that animal's special page.";
var text4 = "In each pet's page, you can see the description of these guys, which describes their basic bio information and charagers and favorites :) You can also download to see more photos of these guys!";
var text5 = "Finally, each subpage also has a link that you can click and leads to outside webpages. Those outsides webpages explain how to choose and get a dog or cat then train them.";
var text6 = "So, if you get interested in owning a dog or cat by visiting this website, you can go to those webpages to get to know how to start getting a new pet.";
var text7 = "Have fun and thank you for visiting!"
var scrollText1 = document.createTextNode(text1);
var scrollText2 = document.createTextNode(text2);
var scrollText3 = document.createTextNode(text3);
var scrollText4 = document.createTextNode(text4);
var scrollText5 = document.createTextNode(text5);
var scrollText6 = document.createTextNode(text6);
var scrollText7 = document.createTextNode(text7);
scrollP1.appendChild(scrollText1);
scrollP2.appendChild(scrollText2);
scrollP3.appendChild(scrollText3);
scrollP4.appendChild(scrollText4);
scrollP5.appendChild(scrollText5);
scrollP6.appendChild(scrollText6);
scrollP7.appendChild(scrollText7);
scrollBox.appendChild(scrollP1);
scrollBox.appendChild(scrollP2);
scrollBox.appendChild(scrollP3);
scrollBox.appendChild(scrollP4);
scrollBox.appendChild(scrollP5);
scrollBox.appendChild(scrollP6);
scrollBox.appendChild(scrollP7);
scrollBox.style.height = "100px";
scrollBox.style.width = "50%";
scrollBox.style.border = "1px solid #ccc";
scrollBox.style.background = "lightgrey";
scrollBox.style.font = "solid";
scrollBox.style.overflow = "auto";
scrollBox.style.margin = "auto";
scrollBox.style.marginTop = "50px";
scrollBox.style.marginBottom = "50px";
scrollBox.style.textAlign = "left";
scrollBox.style.verticalAlign = "middle";
scrollBox.style.alignItems = "center";
document.body.appendChild(scrollBox); |
PHP | UTF-8 | 259 | 2.5625 | 3 | [] | no_license | <?php
include('flag.php');
function welcome($arr)
{
$data = "I am looking at you %s";
foreach ($arr as $_k => $_v) {
$data = sprintf($data,$_v);
}
echo $data;
}
$arr = array($_GET['myname'],$flag);
echo welcome($arr).'<br>';
highlight_file(__FILE__); |
Markdown | UTF-8 | 613 | 3.125 | 3 | [] | no_license | # 행렬의 덧셈
[행렬의 덧셈](https://programmers.co.kr/learn/courses/30/lessons/12950)
### 1.이해
- 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한다.
### 2.계획
- 자바스크립트의 2차원 배열을 어떻게 활용해야 하는가?
- map을 이용해서 2차원 배열의 원소가 되는 1차원 배열들을 더하게 해 주는 sumMatrix 함수를 구현.
- 2차원 배열의 원소 개수만큼 for문을 돌면서 더해 준다.
### 3.실행
### 4.반성
- solution2 에서는 map을 두번 사용해서 풀 수 있도록 수정했다.
|
C# | UTF-8 | 2,026 | 2.6875 | 3 | [
"MIT"
] | permissive | using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Analysis;
using Microsoft.Diagnostics.Tracing.Analysis.GC;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Chapter6.Examples
{
/*
* Uses EventPipeEventSource for analyzing EventPipes-based trace file
* and additionally uses GLAD for high-level GCStats-like analysis.
*/
[Description("Nettrace file-based monitoring (based on EventPipes)")]
class NetTraceProviderDemo
{
static void Main(string[] args)
{
Console.Write("Collect a new trace by 'dotnet trace collect --profile gc-collect -p <PID>'");
Console.Write("Nettrace file to analyze: ");
string file = Console.ReadLine();
PrintRuntimeGCEvents(file);
}
private static void PrintRuntimeGCEvents(string file)
{
var source = new EventPipeEventSource(file);
// https://devblogs.microsoft.com/dotnet/glad-part-2/
source.NeedLoadedDotNetRuntimes();
source.AddCallbackOnProcessStart(proc =>
{
proc.AddCallbackOnDotNetRuntimeLoad(runtime =>
{
runtime.GCEnd += RuntimeOnGCEnd;
});
});
//source.Clr.All += (TraceEvent obj) => { Console.WriteLine(obj.EventName); };
try
{
source.Process();
}
// NOTE: This exception does not currently exist. It is something that needs to be added to TraceEvent.
catch (Exception e)
{
Console.WriteLine("Error encountered while processing events");
Console.WriteLine(e.ToString());
}
}
private static void RuntimeOnGCEnd(TraceProcess p, TraceGC gc)
{
Console.WriteLine($"{gc.GCGenerationName} {gc.Reason} {gc.PauseDurationMSec:F2}/{gc.DurationMSec:F2}");
}
}
}
|
PHP | WINDOWS-1252 | 411 | 3.296875 | 3 | [] | no_license | <?
class comp{
public function sum($a,$b){
return $a+$b;
}
public function prt($a,$c){
return $a*$c;
}
public function product($a,$b,$c){
$a = $this->sum($a,$b);
return $this->prt($a,$c);
}
}
$math = new comp();
echo "(5+10)*15ĽΪ".$math->product(5,10,15);
?>
|
Python | UTF-8 | 220 | 3.046875 | 3 | [] | no_license | my_dic = {'x':500, 'y':5874, 'z': 560}
max=0
min=my_dic["x"]
for dic in my_dic:
if my_dic[dic]>max:
max=my_dic[dic]
elif my_dic[dic]<min:
min=my_dic[dic]
print(max)
print(min)
#minimum and maximum |
Java | UTF-8 | 11,056 | 2.15625 | 2 | [] | no_license | package com.jphale.discount.sales;
import com.jphale.discount.user.entity.UserType;
import com.jphale.discount.sales.entity.SalesTransaction;
import com.jphale.discount.sales.repository.ISalesTransactionRepository;
import com.jphale.discount.sales.service.implementation.SalesTransactionServiceImpl;
import com.jphale.discount.user.entity.User;
import com.jphale.discount.user.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class SalesTransactionServiceBeanTest {
@Mock
private ISalesTransactionRepository iSalesTransactionRepository;
@Mock
private IUserService iUserService;
@InjectMocks
private SalesTransactionServiceImpl salesTransactionService;
@Test
public void shouldCreateSalesTransaction() {
double bill = 200;
String userType = "Employee";
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "09/22/2006";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(200, service, userType, registrationDate);
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
assertEquals(created, salesTransaction);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldDiscount30ForEmployees() throws ParseException {
double bill = 80.0; //Less than $100 so that only the user type category applies to this test
String userType = "Employee";//Employee User
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "09/22/2006";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = bill * (30.0/100.0);
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldDiscount10ForAffiliates() throws ParseException {
double bill = 80.0; //Less than $100 so that only the user type category applies to this test
String userType = "Affiliate";//Affiliate User Type
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "09/22/2006";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = bill * (10.0/100.0);
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldDiscount5ForLongTermCustomers() throws ParseException {
double bill = 80.0; //Less than $100 so that only the user type category applies to this test
String userType = "Customer";//Customer User
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "09/22/2006";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = bill * (5.0/100.0);
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldNotDiscountForNewCustomers() throws ParseException {
double bill = 80.0; //Less than $100 so that only the user type category applies to this test
String userType = "Customer";//Customer User
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "04/22/2021";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = 0;
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldDiscountForEvery100OnTheBill(){
double bill = 350.0; //More than $100
String userType = "Customer";//Customer User (So Employee and Affiliate discount do not apply
String service = "Services";//Any Service not "Grocery" for this test
String dateString = "04/22/2021";//To Ensure that percentage discount does not apply
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = ((int)(bill / 100)) * 5;
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldNotDiscountForGroceries(){
double bill = 800.0; //Less than $100
String userType = "Employee";//Employee User
String service = "Grocery";//To test if grocery does not get percentage discount
String dateString = "09/22/2006";
Date registrationDate = formatDate(dateString);
SalesTransaction salesTransaction = buildSalesTransaction(bill, service, userType, registrationDate);
double expectedDiscount = ((int)(bill / 100)) * 5;
when(iUserService.getUserByCustomerNumber(anyString())).thenReturn(this.buildUser(userType, registrationDate));
when(iSalesTransactionRepository.save(ArgumentMatchers.any(SalesTransaction.class))).thenReturn(salesTransaction);
SalesTransaction created = salesTransactionService.createSalesTransaction(salesTransaction);
double actualDiscount = created.getDiscountAmount();
assertEquals(expectedDiscount, actualDiscount);
verify(iSalesTransactionRepository).save(salesTransaction);
}
@Test
public void shouldGetAllTransactions(){
final List<SalesTransaction> expectedTransactions = generateListOfTransactions();
when(iSalesTransactionRepository.findAll()).thenReturn(expectedTransactions);
final List<SalesTransaction> actualTransactions = salesTransactionService.getAllSalesTransactions();
verify(iSalesTransactionRepository, times(1)).findAll();
assertEquals(expectedTransactions, actualTransactions);
}
private User buildUser(String userType, Date registrationDate){
User user = new User();
user.setId("1");
user.setCustomerNumber("0000001");
user.setFullName("Test User");
user.setUserType(buildUserType(userType));
user.setRegistrationDate(registrationDate);
return user;
}
private UserType buildUserType(String typeName){
UserType userType = new UserType();
userType.setId("1");
userType.setName(typeName);
return userType;
}
private SalesTransaction buildSalesTransaction(double bill, String saleCategory, String userType, Date registrationDate){
SalesTransaction salesTransaction = new SalesTransaction();
salesTransaction.setId("1");
salesTransaction.setUser(buildUser(userType, registrationDate));
salesTransaction.setBill(bill);
salesTransaction.setSaleCategory(saleCategory);
return salesTransaction;
}
private List<SalesTransaction> generateListOfTransactions(){
List<SalesTransaction> transactions = new ArrayList<>();
SalesTransaction transaction1 = buildSalesTransaction(150, "Grocery", "Customer", formatDate("09/22/2006"));
SalesTransaction transaction2 = buildSalesTransaction(150, "Furniture", "Employee", formatDate("09/22/2021"));
transactions.add(transaction1);
transactions.add(transaction2);
return transactions;
}
private Date formatDate(String date){
SimpleDateFormat dateStringFormat = new SimpleDateFormat("MM/dd/yyyy");
Date registrationDate = new Date();
try {
registrationDate = dateStringFormat.parse(date);
} catch(ParseException error) {
System.out.println(error.toString());
}
return registrationDate;
}
}
|
C++ | UTF-8 | 1,264 | 2.515625 | 3 | [] | no_license | #pragma once
#include "command.h"
#include "../shapes/shape.h"
#include <QColor>
#include <QQmlContext>
#include <memory>
#include <vector>
class PaintCommandBase : public Command
{
public:
PaintCommandBase(QImage * canvasImage, std::unique_ptr<Shape> && shape)
: canvasImage_(canvasImage)
//std::move(canvasImage->copy(shape->getBoundingRect().toAlignedRect())))
, shape_(std::move(shape))
{
}
void setUndoPoint() {
undoImage_ = *canvasImage_;
}
protected:
QImage * canvasImage_;
QImage undoImage_;
std::unique_ptr<Shape> shape_;
};
#include <QDebug>
class ShapeCommand : public PaintCommandBase
{
public:
explicit ShapeCommand(QImage * canvasImage, std::unique_ptr<Shape> && shape)
: PaintCommandBase(canvasImage, std::move(shape))
{
}
virtual void undo() override
{
// const QRect rect = shape_->getBoundingRect();
// QPainter painter(canvasImage_);
// painter.drawImage(rect, undoImage);
// canvas_->update(rect);
}
virtual void execute() override
{
QPainter painter(canvasImage_);
shape_->draw(painter);
}
virtual void restoreUndoPoint() override
{
QPainter painter(canvasImage_);
painter.drawImage(QPoint(0, 0), undoImage_);
}
};
|
C# | UTF-8 | 4,637 | 2.5625 | 3 | [] | no_license | using InternetServicesProvider.BusinessLayer.Interfaces;
using InternetServicesProvider.BusinessLayer.Services.Repository;
using InternetServicesProvider.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace InternetServicesProvider.BusinessLayer.Services
{
public class InternetProviderServices : IInternetProviderServices
{
/// <summary>
/// Creating referance variable of IInternetProviderRepository and injecting in Internet Provider Services Constructor
/// </summary>
private readonly IInternetProviderRepository _internetRepository;
public InternetProviderServices(IInternetProviderRepository internetProviderRepository)
{
_internetRepository = internetProviderRepository;
}
/// <summary>
/// Get all internet services plan from MongoDb collection
/// </summary>
/// <returns></returns>
public async Task<IEnumerable<Plan>> AllInternetPlan()
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Get Booked plan by customer Id.
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
public async Task<BookedPlan> BookedPlanByCustomerId(string customerId)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Book Internet services plan for customer, for booking plan customer must be register
/// </summary>
/// <param name="planId"></param>
/// <param name="customer"></param>
/// <returns></returns>
public async Task<BookedPlan> BookPlan(string planId, Customer customer)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// get customer by id, after customer register suscussfully.
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
public async Task<Customer> CustomerById(string customerId)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Find internet plan by plan name
/// </summary>
/// <param name="planName"></param>
/// <returns></returns>
public async Task<IEnumerable<Plan>> FindInternetPlan(string planName)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Get internet plan by Id and see the details.
/// </summary>
/// <param name="planId"></param>
/// <returns></returns>
public async Task<Plan> InternetPlanById(string planId)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Get plan list
/// </summary>
/// <returns></returns>
public IEnumerable<Plan> Plan()
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Register new complaint by customer, customer must be register first.
/// </summary>
/// <param name="complaint"></param>
/// <returns></returns>
public async Task<Complaint> RegisterComplaint(Complaint complaint)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// Register new customer for book internet plan and raise complaint.
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
public async Task<Customer> RegisterCustomer(Customer customer)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// verify customer for book internet plan and book complaint.
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
public async Task<Customer> VerifyCustomer(string customerId)
{
//do code here
throw new NotImplementedException();
}
/// <summary>
/// view complaint by complaint id and customer id
/// </summary>
/// <param name="CuCoId"></param>
/// <returns></returns>
public Task<IEnumerable<Complaint>> ViewComplaint(string CuCoId)
{
//do code here
throw new NotImplementedException();
}
}
}
|
Python | UTF-8 | 295 | 3.5 | 4 | [] | no_license | '''
price of a house is 1000, if the buyer has good_credit he has to make a dp of 10% else a dp of 20%
'''
price = 1000
good_credit = False
if good_credit:
dp = 0.1 * int(price)
print('down payment is ' + str(dp))
else:
dp = 0.2 * int(price)
print('down payment is ' + str(dp)) |
Shell | UTF-8 | 349 | 3.015625 | 3 | [] | no_license | #!/bin/bash
#
gfortran -c -g spacer.f >& compiler.txt
if [ $? -ne 0 ]; then
echo "Errors compiling spacer.f"
exit
fi
rm compiler.txt
#
gfortran spacer.o
if [ $? -ne 0 ]; then
echo "Errors linking and loading spacer.o"
exit
fi
rm spacer.o
#
chmod ugo+x a.out
mv a.out ~/binf77/$ARCH/spacer
#
echo "Program installed as ~/binf77/$ARCH/spacer"
|
C++ | UTF-8 | 770 | 2.53125 | 3 | [] | no_license | #include "iengine.h"
#include "Circle.h"
#include "Vector2.h"
#include "Utility.h"
#include "Triangle.h"
#include "Rectangle.h"
#include <cmath>
#include <stdlib.h>
using namespace std;
const Vector2 size(1920,1080);
void mousecallback(GLFWwindow* window, int button, int action, int mods);
void keycallback(GLFWwindow* window, int key, int scancode, int action, int mode);
void loop();
IEngine ei = IEngine(size.x, size.y, "Test",Color(83,134,139,26),keycallback,mousecallback,loop);
void loop(){
}
void keycallback(GLFWwindow* window, int key, int scancode, int action, int mode){
};
void mousecallback(GLFWwindow* window, int button, int action, int mods){
};
int main() {
Rectangle a(0,0,1000,1000,Color(0,0,0,0));
ei.upload(&a);
ei.start_game();
} |
C++ | UTF-8 | 690 | 2.75 | 3 | [
"MIT"
] | permissive | #include "Playground.h"
#include "Player.h"
#include "Controller.h"
void Playground::DoMove(Move* const move) {
if (move == nullptr) { return; }
this->TakeSticks(move->GetMove());
this->pMoves->push_back(move);
}
void Playground::TakeSticks(int number) {
if (number < 0) {
throw EXCEPTSWICTH("Number below zero. ");
}
if ((this->sticks - number) < this->minSticks) {
throw EXCEPTSWICTH("Not enough sticks to take.");
}
this->sticks -= number;
}
void Playground::DrawPlayground() {
Con::troller().SetPlayGround(*pMoves, sticks);
}
void Playground::PrepareNewSession() {
this->sticks = this->maxSticks;
delete this->pMoves;
this->pMoves = new Moves();
}
|
PHP | UTF-8 | 1,985 | 2.5625 | 3 | [] | no_license | <?php
session_start();
require('xmlresponse.php');
$conn = mysqli_connect('localhost', 'root', '');
mysqli_select_db($conn, 'schoolborad');
$student_id = $_GET['id'];
$school_borad = $_GET['school_board'];
$avg = "SELECT *, AVG(grade)
FROM student as s
JOIN student_grades as sg
ON s.id = sg.student_id
JOIN grades as g
ON sg.grade_id = g.id
WHERE s.id = $student_id. ";
$resultAVG = mysqli_query($conn, $avg);
$data = [];
$i = 0;
if($resultAVG){
$avgGradeStudent = mysqli_fetch_assoc($resultAVG);
}
$data = array(
'data' => [
'name' => $avgGradeStudent['name']. " " . $avgGradeStudent['last_name'],
'average' => $avgGradeStudent['AVG(grade)'],
'status' => $avgGradeStudent['AVG(grade)'] > 7 ? 'Pass' : 'Fail'
]
);
$student_grades = "SELECT * FROM grades g INNER JOIN student_grades sg ON g.id = sg.grade_id WHERE sg.student_id = '$student_id' ";
$resultGrades = mysqli_query($conn, $student_grades);
if($resultGrades) {
while($row = mysqli_fetch_assoc ($resultGrades)){
$data['data']['grades'][$i] = array(
'grade' => $row['grade']
);
$i++;
}
}
if($school_borad == 'CSM'){
echo json_encode($data);
}
if($school_borad == 'CSMB'){
//var_dump($data['data']['grades']);
$xml = new SimpleXMLElement('<xml/>');
$track = $xml->addChild('student');
$track->addChild('average', $data['data']['average']);
$track->addChild('name', $data['data']['name']);
$track->addChild('status', $data['data']['status']);
$track = $xml->addChild('grades');
foreach($data['data']['grades'] as $key => $grade){
//var_dump($grade);
$track->addChild('grade', $data['data']['grades'][$key]['grade']);
}
Header('Content-type: text/xml');
print($xml->asXML());
}
|
Markdown | UTF-8 | 2,415 | 2.859375 | 3 | [] | no_license |
# CS 487 - Team Project (Fall 2017)
Team B - Robert Judka, Mayank Bansal, Changyu Wu, Paul Myers
## mySchedule
**Class Scheduling Made Easy!**
The basic functionality of the application will allow students to plan out and create a class schedule given a list of classes they want to take. To create their class list, students will be able to query IIT’s available classes and select the ones they want to take. The application will be able to resolve any time-conflicts that may arise with the student’s classes, and if multiple schedule options are possible, the application will present them all to the student.
### Prerequisites
This guide assumes you're running a linux or compatible machine. You will need nde package manager and bower for this project, and have access to the root apache directory for being able to rewrite URL requests. Documentation for other webservers will be added in the future.
Install node on a linux machine by pasting this in your terminal
```
$ sudo apt-get update
$ sudo apt-get install nodejs
$ sudo apt-get install npm
```
Use this link for other modes of installation - [DigitalOcean - Installing npm](https://goo.gl/XYVE6q)
After installing npm, install bower by entering the following command
```
$ npm install -g bower
```
### Installation + Setup
To start setting up the dependencies, run
```
$ sudo bower install --allow-root
```
### Deployment
We need to make a .htaccess file with the following rewrite rule for pretty links and Google crawler friendly links. Copy the following code into your .htaccess file. If you can't find it, you may make one and put it in the root directory of your webserver.
```
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ cs487teamb/index.html
```
Replace `cs487teamb` with the base directory if you cloned this repository directly into your `htdocs`.
You will want to change the `<base href='/'>` link in the `index.html` page if you are installing in another location.
### Notes
* If the javascript isn't loading, then rename the js folder and refactor on the index.html page.
### Authors
* **Robert Judka** - rjudka@hawk.iit.edu
* **Mayank Bansal** - mbansal5@hawk.iit.edu
* **Changyu Wu** - cwu49@hawk.iit.edu
* **Paul Myers** - pmyers@hawk.iit.edu |
Java | UTF-8 | 5,127 | 2.46875 | 2 | [] | no_license | package ielab.hibernate;
import java.io.Serializable;
import java.security.interfaces.RSAKey;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.mysql.jdbc.EscapeTokenizer;
import com.mysql.jdbc.Statement;
/**
* 使用Hibernate编写通用数据库操作代码
*/
public class DAO {
private static final Log log = LogFactory.getLog(DAO.class);
public DAO() {
}
public Session getSession() {
// HibernateSessionFactory.beginTransaction();
// return HibernateSessionFactory.getSession();
return HibernateSessionFactory.getSessionFactory().getCurrentSession();
}
// insert方法
public void insert(Object o) {
Session session = getSession();
session.beginTransaction();
try {
session.save(o);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
// try {
// getSession().save(o);
// log.debug("save successful");
// } catch (RuntimeException re) {
// log.error("save failed", re);
// throw re;
// }
}
// delete方法
public void delete(Object o, Serializable id) {
Session session = getSession();
session.beginTransaction();
try {
o = session.get(o.getClass(), id);
if (o != null) {
session.delete(o);
}
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
// try {
// o = getSession().get(o.getClass(),id);
// if(o!=null){
// getSession().delete(o);
// }
// log.debug("delete successful");
// } catch (RuntimeException re) {
// log.error("delete failed", re);
// throw re;
// }
}
// update方法
public void update(Object o) {
Session session = getSession();
session.beginTransaction();
try {
session.update(o);
log.debug("update successful");
} catch (RuntimeException re) {
log.error("update failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
// try {
// getSession().update(o);
// log.debug("update successful");
// } catch (RuntimeException re) {
// log.error("update failed", re);
// throw re;
// }
}
// 基于HQL的通用select方法
public ArrayList selectByHOL(String o) {
Session session = getSession();
session.beginTransaction();
try {
Query query = session.createQuery(o);
List list = query.list();
log.debug("select successful");
return (ArrayList) list;
} catch (RuntimeException re) {
log.error("select failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
}
// 基于SQL的通用select方法
public ArrayList selectBySQL(String sql) throws Exception {
Session session = getSession();
session.beginTransaction();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = session.connection();
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
Hashtable ht = null;
ArrayList array = new ArrayList();
while (rs.next()) {
ht = new Hashtable();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
ht.put(rsmd.getColumnName(i + 1), rs.getObject(i + 1));
}
array.add(ht);
}
log.debug("select successful");
return array;
} catch (RuntimeException re) {
log.error("select failed", re);
session.getTransaction().rollback();
throw re;
} finally {
try {
rs.close();
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
session.getTransaction().commit();
}
}
public void executeBySQL(String sql) throws Exception {
Session session = getSession();
session.beginTransaction();
try {
Connection con = session.connection();
PreparedStatement stmt = con.prepareStatement(sql);
stmt.executeUpdate();
} catch (RuntimeException re) {
log.error("select failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
}
// 基于HQL的select方法,用于分页查询
public ArrayList selectLimitByHOL(String o, int fistR, int MaxR) {
Session session = getSession();
session.beginTransaction();
try {
Query query = session.createQuery(o);
query.setFirstResult(fistR);
query.setMaxResults(MaxR);
List list = query.list();
log.debug("select successful");
return (ArrayList) list;
} catch (RuntimeException re) {
log.error("select failed", re);
session.getTransaction().rollback();
throw re;
} finally {
session.getTransaction().commit();
}
}
}
|
Shell | UTF-8 | 229 | 2.765625 | 3 | [
"ECL-2.0"
] | permissive | #!/bin/sh
# This script was made mainly to combat Valpo's ugly XML
file=$1
# replace anything that has extra text in the ptag with '<p>'
# basically '<p lots_of_extra_stuff asdfasdfasdf >' --> '<p>'
sed "s|<p[^>]*>|<p>|" $file
|
Java | UTF-8 | 1,247 | 3.828125 | 4 | [] | no_license | package _09_facade._01_console_example;
import java.util.ArrayList;
import java.util.List;
// highest construct
public class Console {
private List<ViewPort> viewPorts = new ArrayList<>();
private int width;
private int height;
public Console(int width, int height) {
this.width = width;
this.height = height;
}
public void addViewport(ViewPort viewPort) {
viewPorts.add(viewPort);
}
// console system pseudo code
public void render() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (ViewPort port : viewPorts) {
System.out.print(port.charAt(x, y));
}
System.out.println();
}
}
}
// with façade, we should offer a high-level API to easily access low level components/constructs.
// here we do this via a factory method
public static Console newBasicConsole(int width, int height) {
Buffer buffer = new Buffer(width, height);
ViewPort viewPort = new ViewPort(buffer, width, height, 0, 0);
Console console = new Console(width, height);
console.addViewport(viewPort);
return console;
}
}
|
Java | UTF-8 | 2,220 | 2.140625 | 2 | [] | no_license | package com.crm.vtiger;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.crm.vtiger.GenericUtils.BaseClass;
import com.crm.vtiger.GenericUtils.FileUtility;
import com.crm.vtiger.GenericUtils.JavaUtility;
import com.crm.vtiger.GenericUtils.WebDriverUtility;
public class CreateOrganisation01_Test extends BaseClass {
/*static
{
System.setProperty("webdriver.chrome.driver", "C:\\HSSM40\\RMG_Project\\src\\main\\resources\\Drivers\\chromedriver.exe");
}*/
@Test
public void createOrganisation01_Test() throws InterruptedException, IOException
{
String orgName=eUtil.getExcelData("org", 1, 2);
//Navigate to organizations
driver.findElement(By.linkText("Organizations")).click();
Reporter.log("Organization Page found", true);
//Navigate to create Organisation
driver.findElement(By.xpath("//img[@title='Create Organization...']")).click();
Reporter.log("Click on create organisation", true);
driver.findElement(By.name("accountname")).sendKeys(orgName+JavaUtility.getRandomData());
Reporter.log("Create organisation with organisation name", true);
driver.findElement(By.xpath("//input[@title='Save [Alt+S]']")).click();
Reporter.log("Click on save", true);
String expData=driver.findElement(By.xpath("//span[@class='dvHeaderText']")).getText();
//Assert.assertTrue(expData.contains(orgName));
SoftAssert asrt=new SoftAssert();
asrt.assertTrue(expData.contains(orgName));
System.out.println(expData);
Reporter.log("The expected data is :"+expData, true);
//Logout
/*Actions act=new Actions(driver);
WebElement logoutImage=driver.findElement(By.xpath("//img[@src='themes/softed/images/user.PNG']"));
act.moveToElement(logoutImage).perform();
Thread.sleep(10000);
driver.findElement(By.linkText("Sign Out")).click();*/
}
}
|
Shell | UTF-8 | 702 | 3.5625 | 4 | [
"MIT"
] | permissive | #! /bin/bash
# Setup steps for local installation of DogBot Firmware
# if first argument is 1, also build the code
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#copy the sample config (individual users will replace with their own dog-specific configs)
echo "copying configuration to /home/$USER/.config/DogBot/"
mkdir -p /home/$USER/.config/DogBot
cp $DIR/../Config/*.json /home/$USER/.config/DogBot/
#set the rules for accessing USB
sudo cp $DIR/../API/src/reactai.rules /etc/udev/rules.d/
sudo udevadm control --reload-rules && udevadm trigger
BUILDARG=""
if [ $# -gt 0 ]; then
BUILDARG=$1
if [ $BUILDARG -eq 1 ]; then
echo "building project"
$DIR/buildall.sh
fi
fi
|
C# | UTF-8 | 1,763 | 2.734375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using Productores.Logic;
using Productores.BD;
namespace Productores.DA
{
public class ProductorDA
{
public static int Agregar(Productor pproductor)
{
int retorno = 0;
using (SqlConnection conn = BDConnection.obtenerCnx())
{
SqlCommand comando = new SqlCommand(String.Format("Insert into Productor (id, nombre, telefono, email) values ('{0}','{1}','{2}','{3}')",
pproductor.id, pproductor.nombre, pproductor.telefono, pproductor.email), conn);
retorno = comando.ExecuteNonQuery();
}
return retorno;
}
public static List<Productor> BuscarTodos()
{
List<Productor> lProductor = new List<Productor>();
using (SqlConnection conn = BDConnection.obtenerCnx())
{
SqlCommand comando = new SqlCommand(String.Format("Select * From Productor"), conn);
System.Data.SqlClient.SqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
Productor productor = new Productor();
productor.id = Int32.Parse(reader["id"].ToString());
productor.nombre = reader["nombre"].ToString();
productor.telefono = reader["telefono"].ToString();
productor.email = reader["email"].ToString();
productor.fincas = Int32.Parse(reader["fincas"].ToString());
lProductor.Add(productor);
}
}
return lProductor;
}
}
} |
Swift | UTF-8 | 2,069 | 3.859375 | 4 | [] | no_license |
import Foundation
/// A type that stores values for red, green and blue components of a color.
///
/// Use this type when you need a lightweight and type-safe way to store colors
/// without relying on UI frameworks like `UIKit` or `CoreGraphics`.
///
struct RGB {
/// The red component, specified as a value from 0.0 to 1.0.
///
let red: Float
/// The green component, specified as a value from 0.0 to 1.0.
///
let green: Float
/// The blue component, specified as a value from 0.0 to 1.0.
///
let blue: Float
}
extension RGB {
/// Declaring a convenience initializer in an extension keeps the
/// automatically-generated memberwize initializer.
/// https://www.hackingwithswift.com/example-code/language/how-to-add-a-custom-initializer-to-a-struct-without-losing-its-memberwise-initializer
/// Creates a new instance from a 6-digit hexadecimal representation e.g. "A0D8F4".
///
/// This initializer expects the input string to be a valid hexadecimal
/// representation of a number with exactly six digits, and terminates with
/// a fatal error if this is not the case.
///
/// Example of valid values: `fe4e57`, `FE4E57`, `748990`
/// Example of invalid values: `0xfe4e57`, `eee`, `brown`
///
init(fromHexString string: String) {
guard string.count == 6 else {
fatalError("Extracting RGB values from hexadecimal representation: invalid input: \"\(string)\". Input must be exactly 6 character long. Expected something like \"A0D8F4\".")
}
guard let number = Int(string, radix: 16) else {
fatalError("Extracting RGB values from hexadecimal representation: invalid input: \"\(string)\". Expected something like \"A0D8F4\".")
}
self.red = Float((number & 0xFF0000) >> 16) / 255.0
self.green = Float((number & 0x00FF00) >> 8) / 255.0
self.blue = Float((number & 0x0000FF) >> 0) / 255.0
}
}
|
Java | UTF-8 | 1,223 | 1.953125 | 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 it.univaq.f4i.iw.pollweb.data.model;
import java.util.List;
/**
*
* @author Pagliarini Andrea
*/
public interface Survey {
public long getId();
public void setId(long id);
public String getTitle();
public void setTitle(String title);
public String getOpeningText();
public void setOpeningText(String openingText);
public String getClosingText();
public void setClosingText(String closingText);
public List<Question> getQuestions();
public void setQuestions(List<Question> questions);
public void addQuestion(Question q);
public User getManager();
public void setManager(User manager);
public boolean isActive();
public void setActive(boolean active);
public boolean isReserved();
public List<SurveyResponse> getResponses();
public void setResponses(List<SurveyResponse> responses);
}
|
Java | UTF-8 | 5,205 | 1.523438 | 2 | [] | no_license | package kotlin.reflect.jvm.internal.impl.load.java;
/* compiled from: utils.kt */
public final class r {
/* JADX WARNING: Missing block: B:37:0x00bf, code:
if (kotlin.reflect.jvm.internal.impl.builtins.g.H(r4) != false) goto L_0x00c3;
*/
public static final kotlin.reflect.jvm.internal.impl.load.java.i a(kotlin.reflect.jvm.internal.impl.types.w r4, java.lang.String r5) {
/*
r0 = "$receiver";
kotlin.jvm.internal.h.e(r4, r0);
r0 = "value";
kotlin.jvm.internal.h.e(r5, r0);
r0 = r4.bwA();
r0 = r0.bbW();
r1 = r0 instanceof kotlin.reflect.jvm.internal.impl.descriptors.d;
r2 = 0;
if (r1 == 0) goto L_0x004d;
L_0x0017:
r0 = (kotlin.reflect.jvm.internal.impl.descriptors.d) r0;
r1 = r0.bbF();
r3 = kotlin.reflect.jvm.internal.impl.descriptors.ClassKind.ENUM_CLASS;
if (r1 != r3) goto L_0x004d;
L_0x0021:
r4 = r0.bdg();
r5 = kotlin.reflect.jvm.internal.impl.name.f.mD(r5);
r0 = "Name.identifier(value)";
kotlin.jvm.internal.h.d(r5, r0);
r0 = kotlin.reflect.jvm.internal.impl.incremental.components.NoLookupLocation.FROM_BACKEND;
r0 = (kotlin.reflect.jvm.internal.impl.incremental.components.b) r0;
r4 = r4.c(r5, r0);
r5 = r4 instanceof kotlin.reflect.jvm.internal.impl.descriptors.d;
if (r5 == 0) goto L_0x004c;
L_0x003a:
r4 = (kotlin.reflect.jvm.internal.impl.descriptors.d) r4;
r5 = r4.bbF();
r0 = kotlin.reflect.jvm.internal.impl.descriptors.ClassKind.ENUM_ENTRY;
if (r5 != r0) goto L_0x004c;
L_0x0044:
r5 = new kotlin.reflect.jvm.internal.impl.load.java.e;
r5.<init>(r4);
r2 = r5;
r2 = (kotlin.reflect.jvm.internal.impl.load.java.i) r2;
L_0x004c:
return r2;
L_0x004d:
r4 = kotlin.reflect.jvm.internal.impl.types.b.a.aU(r4);
r0 = kotlin.reflect.jvm.internal.impl.utils.g.nc(r5);
r1 = r0.component1();
r0 = r0.bbt();
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.r(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x006c;
L_0x0063:
r4 = java.lang.Boolean.parseBoolean(r5); Catch:{ IllegalArgumentException -> 0x00c2 }
r5 = java.lang.Boolean.valueOf(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x006c:
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.s(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x0079;
L_0x0072:
r5 = (java.lang.CharSequence) r5; Catch:{ IllegalArgumentException -> 0x00c2 }
r5 = kotlin.text.x.S(r5); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x0079:
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.u(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x0084;
L_0x007f:
r5 = kotlin.text.t.X(r1, r0); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x0084:
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.w(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x008f;
L_0x008a:
r5 = kotlin.text.t.Y(r1, r0); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x008f:
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.t(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x009a;
L_0x0095:
r5 = kotlin.text.t.Z(r1, r0); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x009a:
r3 = kotlin.reflect.jvm.internal.impl.builtins.g.v(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r3 == 0) goto L_0x00a5;
L_0x00a0:
r5 = kotlin.text.t.aa(r1, r0); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x00a5:
r0 = kotlin.reflect.jvm.internal.impl.builtins.g.x(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r0 == 0) goto L_0x00b0;
L_0x00ab:
r5 = kotlin.text.s.nd(r5); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x00b0:
r0 = kotlin.reflect.jvm.internal.impl.builtins.g.z(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r0 == 0) goto L_0x00bb;
L_0x00b6:
r5 = kotlin.text.s.ne(r5); Catch:{ IllegalArgumentException -> 0x00c2 }
goto L_0x00c3;
L_0x00bb:
r4 = kotlin.reflect.jvm.internal.impl.builtins.g.H(r4); Catch:{ IllegalArgumentException -> 0x00c2 }
if (r4 == 0) goto L_0x00c2;
L_0x00c1:
goto L_0x00c3;
L_0x00c2:
r5 = r2;
L_0x00c3:
if (r5 == 0) goto L_0x00cd;
L_0x00c5:
r4 = new kotlin.reflect.jvm.internal.impl.load.java.d;
r4.<init>(r5);
r2 = r4;
r2 = (kotlin.reflect.jvm.internal.impl.load.java.i) r2;
L_0x00cd:
return r2;
*/
throw new UnsupportedOperationException("Method not decompiled: kotlin.reflect.jvm.internal.impl.load.java.r.a(kotlin.reflect.jvm.internal.impl.types.w, java.lang.String):kotlin.reflect.jvm.internal.impl.load.java.i");
}
}
|
Markdown | UTF-8 | 2,289 | 3.109375 | 3 | [
"MIT"
] | permissive | ## 安装
### npm 安装
推荐使用 npm 的方式安装,它能更好地和 [webpack](https://webpack.js.org/) 打包工具配合使用。
```shell
npm i bbplus-element -S
```
### 引入 bbplus-element
你可以引入整个 bbplus-element,或是根据需要仅引入部分组件。我们先介绍如何引入完整的 bbplus-element。
#### 完整引入
在 main.js 中写入以下内容:
```javascript
import Vue from 'vue'
// element-ui
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// bbplus-element
import BbplusElementUI from 'bbplus-element'
import 'bbplus-element/lib/theme-chalk/index.css'
import App from './App.vue'
Vue.use(ElementUI)
Vue.use(BbplusElementUI)
new Vue({
el: '#app',
render: h => h(App)
})
```
以上代码便完成了 bbplus-element 的引入。需要注意的是,样式文件需要单独引入。
#### 按需引入
借助 [babel-plugin-component](https://github.com/QingWei-Li/babel-plugin-component),我们可以只引入需要的组件,以达到减小项目体积的目的。
首先,安装 babel-plugin-component:
```bash
npm install babel-plugin-component -D
```
然后,将 .babelrc 修改为:
```json
{
"presets": [
["env", {
"modules": false
}],
"stage-2"
],
"plugins": [["component", [
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
},
{
"libraryName": "bbplus-element",
"styleLibraryName": "theme-chalk"
}
]]]
}
```
接下来,如果你只希望引入部分组件,比如 SelectDatePicker 和 TablePagination,那么需要在 main.js 中写入以下内容:
```javascript
import Vue from 'vue'
import { Button, Select } from 'element-ui'
import { SelectDatePicker, TablePagination } from 'bbplus-element'
import App from './App.vue'
Vue.use(Button)
Vue.use(Select)
Vue.use(SelectDatePicker)
Vue.use(TablePagination)
new Vue({
el: '#app',
render: h => h(App)
})
```
完整组件列表和引入方式(完整组件列表以 [components.json](http://git.babybus.com/liuzhaozhi/bb-element/blob/master/components.json) 为准)
```javascript
import Vue from 'vue'
import {
SelectDatePicker,
TablePagination
} from 'bbplus-element'
Vue.use(SelectDatePicker)
Vue.use(TablePagination)
|
JavaScript | UTF-8 | 1,649 | 2.53125 | 3 | [] | no_license | import ServerActions from './actions/ServerActions';
import axios from 'axios';
const API = {
getAnimals() {
axios.get('/api/animals')
.then(res => ServerActions.receiveAnimals(res.data))
.catch(console.error);
},
getAnimal(id) {
axios.get(`/api/animals/${id}`)
.then(res => ServerActions.receiveAnimal(res.data))
.catch(console.error);
},
addAnimal(animalObj) {
axios.post(`/api/animals`, animalObj)
.then(res => ServerActions.addAnimal(res.data))
.catch(console.error);
},
removeAnimal(id) {
axios.delete(`/api/animals/${id}`)
.then(res => ServerActions.removeAnimal(res.data))
.catch(console.error);
},
getPeople() {
axios.get('/api/people')
.then(res => ServerActions.receivePeople(res.data))
.catch(console.error);
},
getPerson(id) {
axios.get(`/api/people/${id}`)
.then(res => ServerActions.receivePerson(res.data))
.catch(console.error);
},
createPerson(obj) {
axios.post('/api/people', obj)
.then(res => ServerActions.createPerson(res.data))
.catch(console.error);
},
deletePerson(id) {
axios.delete(`/api/people/${id}`)
.then(res => ServerActions.deletePerson(res.data))
.catch(console.error);
},
addOwner(animalId, personId) {
axios.put(`/api/animals/${animalId}/addOwner/${personId}`)
.then(res => ServerActions.receiveAnimal(res.data))
.catch(console.error);
},
removeOwner(animalId) {
axios.put(`/api/animals/${animalId}/removeOwner`)
.then(res => ServerActions.receiveAnimal(res.data))
.catch(console.error);
}
}
export default API;
|
C++ | UTF-8 | 3,491 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct TreapNod { //node declaration
int data;
int priority;
TreapNod* l, *r;
TreapNod(int d) { //constructor
this->data = d;
this->priority = rand() % 100;//cho ra so ngau nhien tu 1 den 100
this->l= this->r = nullptr;
}
};
void rotLeft(TreapNod* &root) { //left rotation(ham xoay trai cay nhi phan)
TreapNod* R = root->r;
TreapNod* X = root->r->l;
R->l = root;
root->r= X;
root = R;
}
void rotRight(TreapNod* &root) { //right rotation(ham xoay phai cay nhi phan)
TreapNod* L = root->l;
TreapNod* Y = root->l->r;
L->r = root;
root->l= Y;
root = L;
}
void insertNod(TreapNod* &root, int d) { //insertion(them phan tu moi cho cay)
if (root == nullptr) {
root = new TreapNod(d);
return;
}
if (d < root->data) { //neu du lieu da cho it hon thi nut goc
insertNod(root->l, d);// chen du lieu vao cay con ben trai
if (root->l != nullptr && root->l->priority > root->priority)//xoay phai neu khoa heap vi pham
rotRight(root);
} else {
insertNod(root->r, d);//nguoc lai thi chen du lieu vao cay con ben phai
if (root->r!= nullptr && root->r->priority > root->priority)//xoay trai neu khoa heap vi pham
rotLeft(root);
}
}
bool searchNod(TreapNod* root, int key) {//ham tim kiem nut
if (root == nullptr)//neu khong co key thi tra ve gia tri false
return false;
if (root->data == key)//neu co key thi tra ve gia tri true
return true;
if (key < root->data)//neu khoa nho hon goc thi tim kiem trong cay con ben trai(1)
return searchNod(root->l, key);
return searchNod(root->r, key);//nguoc lai (1)
}
void deleteNod(TreapNod* &root, int key) {//ham xoa nut
//node to be deleted which is a leaf node(ham xoa nut la)
if (root == nullptr)
return;
if (key < root->data)
deleteNod(root->l, key);
else if (key > root->data)
deleteNod(root->r, key);
//node to be deleted which has two children(nut bi xoa co 2 nut con)
else {
if (root->l ==nullptr && root->r == nullptr) {
delete root;
root = nullptr;
}
else if (root->l != nullptr && root->r != nullptr) {
if (root->l->priority < root->r->priority) {
rotLeft(root);
deleteNod(root->l, key);
} else {
rotRight(root);
deleteNod(root->r, key);
}
}
//node to be deleted has only one child(nut bi xoa co 1 nut con)
else {
TreapNod* child = (root->l)? root->l: root->r;
TreapNod* curr = root;
root = child;
delete curr;
}
}
}
void displayTreap(TreapNod *root, int space = 0, int height =10) { //display treap
if (root == nullptr)
return;
space += height;
displayTreap(root->l, space);
cout << endl;
for (int i = height; i <=space; i++)
cout << ' ';
cout << root->data << "(" << root->priority << ")";
cout << endl;
displayTreap(root->r, space);
}
int main() {
int nums[] = {7,1,6,4,3,2,8,9,10,11 };
int a = sizeof(nums)/sizeof(int);
TreapNod* root = nullptr;
srand(time(nullptr));
for(int n: nums)
insertNod(root, n);
cout << "cau truc cay Treap:\n\n";
displayTreap(root);
cout << "\nxoa node 8:\n\n";
deleteNod(root, 8);
displayTreap(root);
cout << "\nxoa node 3:\n\n";
deleteNod(root, 3);
displayTreap(root);
return 0;
}
|
Java | UTF-8 | 1,803 | 3.671875 | 4 | [] | no_license | package cq2013;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
/**
* Created by RobertPC on 7/22/2017.
*/
public class Prob04 {
//String to filePath
public static final String filePath= "inputs/2013/Prob04.in.txt";
public static void main(String[] args){
try{
//Initialize inLine
String inLine = "";
//Prepare to read file
BufferedReader br = new BufferedReader(new FileReader(filePath));
//Loop while not at end of file
while((inLine = br.readLine()) != null){
StringBuilder buf = new StringBuilder();
//Split into an array of strings
String[] tokens = inLine.split(",");
//Make int array same length of string array
int[] numbers = new int[tokens.length];
//Fill int array with parsed ints from the string array
for(int i = 0; i < tokens.length; i++){
numbers[i] = Integer.parseInt(tokens[i]);
}
//Sort that out
Arrays.sort(numbers);
//Loop through numbers
for(int i = 0; i < numbers.length; i++){
//If not last number, print number and comma
if(i != numbers.length - 1){
System.out.print(numbers[i] + ",");
} else{
//If last number, only print number and no comma
System.out.print(numbers[i]);
}
}
//Print a new line for the next inputs
System.out.println();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
|
Python | UTF-8 | 1,049 | 3.171875 | 3 | [] | no_license | # File: ScapeAlgo
import xlsxwriter
from nltk.tokenize import sent_tokenize
class ScrapeAlgo:
file = open('../../PunctuatedText/Berakhot.txt', mode='r', encoding='utf8')
file_txt = file.read()
sentences = sent_tokenize(file_txt)
workbook = xlsxwriter.Workbook('Berakhot.xlsx')
worksheet = workbook.add_worksheet('daf_1')
row = 0
column = 0
for sentence in sentences:
if sentence.find(';') != -1:
sentence = sentence.replace(';', '*;')
splitSentence = sentence.split('*')
for element in splitSentence:
worksheet.write(row, column, element)
row += 1
continue
elif sentence.find('\n') != -1:
sentence = sentence.replace('\n', '*')
splitSentence = sentence.split('*')
for element in splitSentence:
worksheet.write(row, column, element)
row += 1
continue
worksheet.write(row, column, sentence)
row += 1
workbook.close()
|
Java | UTF-8 | 3,867 | 2.59375 | 3 | [
"MIT"
] | permissive | package io.kang.unit_test.domain_unit;
import io.kang.domain.Profile;
import io.kang.domain.User;
import io.kang.enumeration.Suffix;
import io.kang.unit_test.singleton_object.domain_unit.UserUpdateSingleton;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
public class ProfileUnitTest {
private static final long ID = 1L;
private static final User USER = UserUpdateSingleton.INSTANCE.getInstance();
private static final String FILE_NAME = "PROFILE_FILE_NAME01";
private static final int FILE_SIZE = 0;
private static final byte[] FILE_BYTES = new byte[0];
private static final Suffix FILE_SUFFIX = Suffix.PNG;
private static final LocalDateTime UPLOAD_DATE = LocalDateTime.now();
@Test
public void idSetterAndGetterTesting() throws IOException {
Profile profile = new Profile();
profile.setId(ID);
long id = profile.getId();
Assert.assertEquals(id, ID);
}
@Test
public void userSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setUser(USER);
User user = profile.getUser();
Assert.assertEquals(user, USER);
}
@Test
public void fileNameSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setFileName(FILE_NAME);
String fileName = profile.getFileName();
Assert.assertEquals(FILE_NAME, fileName);
}
@Test
public void fileSizeSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setFileSize(FILE_SIZE);
int fileSize = profile.getFileSize();
Assert.assertEquals(fileSize, FILE_SIZE);
}
@Test
public void fileBytesSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setFileBytes(FILE_BYTES);
byte[] fileBytes = profile.getFileBytes();
Assert.assertEquals(fileBytes, FILE_BYTES);
}
@Test
public void fileSuffixSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setFileSuffix(FILE_SUFFIX);
Suffix fileSuffix = profile.getFileSuffix();
Assert.assertEquals(fileSuffix, FILE_SUFFIX);
}
@Test
public void uploadDateSetterAndGetterTesting() throws IOException{
Profile profile = new Profile();
profile.setUploadDate(UPLOAD_DATE);
LocalDateTime uploadDate = profile.getUploadDate();
Assert.assertEquals(uploadDate, UPLOAD_DATE);
}
@Test
public void equalsTesting() throws IOException{
Profile profile = new Profile();
profile.setId(ID);
profile.setUser(USER);
profile.setFileName(FILE_NAME);
profile.setFileBytes(FILE_BYTES);
profile.setFileSize(FILE_SIZE);
profile.setFileSuffix(FILE_SUFFIX);
profile.setUploadDate(UPLOAD_DATE);
Profile sameProfile = new Profile(ID, USER, FILE_NAME, FILE_SIZE, FILE_BYTES, FILE_SUFFIX, UPLOAD_DATE);
Assert.assertTrue(profile.equals(profile));
}
@Test
public void toStringTesting() throws IOException{
Profile profile = new Profile();
profile.setId(ID);
profile.setUser(USER);
profile.setFileName(FILE_NAME);
profile.setFileBytes(FILE_BYTES);
profile.setFileSize(FILE_SIZE);
profile.setFileSuffix(FILE_SUFFIX);
profile.setUploadDate(UPLOAD_DATE);
String string = profile.toString();
String cmpResult = String.format("Profile(id=%d, user=%s, fileName=%s, fileSize=%d, fileBytes=%s, fileSuffix=%s, uploadDate=%s)", ID, USER, FILE_NAME, FILE_SIZE, Arrays.toString(FILE_BYTES), FILE_SUFFIX, UPLOAD_DATE);
Assert.assertEquals(string, cmpResult);
}
}
|
PHP | UTF-8 | 3,566 | 2.9375 | 3 | [] | no_license | <?php
//establish MySQL connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "tugasakhir";
$db = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//print but with auto append <br>
function cetak($var)
{ echo $var."<br>"; }
//function to test variable outcomes
//automatically append <br>
function cetakvar($var)
{ echo var_dump($var)."<br>"; }
//function to calculate score
function nilai($a,$b)
{ return (($a / ($a + $b)) * 100); }
//function to calculate the amount of credits of a course
function sksmatkul($courseId)
{ global $db;
$sql = "select sks from course where id = $courseId";
$result = mysqli_query($db,$sql);
$sksmatkul = mysqli_fetch_assoc($result);
return $sksmatkul[sks];
}
//function to calculate the amount of credits taken by a student
function jumlahSKS($studentId)
{ global $db;
$sql = "select sum(sks) as sks
from student join enrollment join course
on student.id = enrollment.student_id
and course.id = enrollment.course_id
where student.id = $studentId";
$result = mysqli_query($db,$sql);
$sks = mysqli_fetch_assoc($result);
if($sks[sks] == 0)
{ return 0; }
else
{ return $sks[sks]; }
}
function scoreCumulation($studentId,$courseId)
{ global $db;
$sql = "select sum(testSession.score) as sum, course.course
from testSession join test join course
on testSession.test_id = test.id
and test.course_id = course.id
where testSession.student_id = $studentId
and course.id = $courseId";
$result = mysqli_query($db,$sql);
$scores = mysqli_fetch_assoc($result);
return $scores[sum];
}
function numberOfTests($studentId,$courseId)
{ global $db;
$sql = "select test.test
from enrollment join test
on enrollment.course_id = test.course_id
where enrollment.student_id = $studentId
and enrollment.course_id = $courseId";
$result = mysqli_query($db,$sql);
return mysqli_num_rows($result);
}
//function to calculate current course grade
function averageScore($studentId,$courseId)
{ return scoreCumulation($studentId,$courseId) / numberOfTests($studentId,$courseId); }
function courseGrade($studentId,$courseId)
{ if(numberOfTests($studentId,$courseId) == 0)
{ return 4; }
else if(averageScore($studentId,$courseId) >= 90)
{ return 4; }
else if(averageScore($studentId,$courseId) >= 80)
{ return 3.5; }
else if(averageScore($studentId,$courseId) >= 70)
{ return 3; }
else if(averageScore($studentId,$courseId) >= 60)
{ return 2; }
else if(averageScore($studentId,$courseId) >= 50)
{ return 1; }
else
{ return 0; }
}
//function to calculate GPA
function indeksPrestasi($studentId)
{ global $db;
$sql = "select course.id, course.sks
from student join enrollment join course
on student.id = enrollment.student_id
and course.id = enrollment.course_id
where student.id = $studentId";
$result = mysqli_query($db,$sql);
$course = array();
while($row = mysqli_fetch_assoc($result))
{ $course[] = $row; }
$grade = 0;
foreach($course as $course)
{ $grade += (coursegrade($studentId,$course[id]) * $course[sks]); }
return $grade / jumlahSKS($studentId);
}
?>
|
Go | UTF-8 | 3,415 | 2.546875 | 3 | [] | no_license | package handler
import (
"encoding/json"
"fmt"
"net/http"
"opa-backend/configs"
"opa-backend/utils"
"github.com/gin-gonic/gin"
)
func CreateCode(config configs.ApiConfig) gin.HandlerFunc {
return func(c *gin.Context) {
var req createCodeRequest
err := c.ShouldBindJSON(&req)
if err != nil {
fmt.Println("#### erro bind json ####")
fmt.Println(err)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
statusCode, code, err := createCode(&req, config)
if err != nil {
c.JSON(http.StatusBadRequest, code)
}
c.JSON(statusCode, code)
}
}
func createCode(orderCode *createCodeRequest, config configs.ApiConfig) (int, *createCodeResponse, error) {
method := "POST"
path := "/v2/codes"
url := config.BASEURL + path
data, err := json.Marshal(orderCode)
if err != nil {
return 0, nil, err
}
header, err := utils.GetHeader(method, path, data, config)
if err != nil {
return 0, nil, err
}
query := utils.GetQuery(config.ASSUMEMERCHANT)
statusCode, res, err := utils.DoHttpRequest(method, url, header, query, data)
if err != nil {
return 0, nil, err
}
var code createCodeResponse
err = json.Unmarshal(res, &code)
if err != nil {
return 0, nil, err
}
return statusCode, &code, nil
}
type createCodeRequest struct {
MerchantPaymentID string `json:"merchantPaymentId" validate:"required"`
Amount amount `json:"amount" validate:"required"`
OrderDescription string `json:"orderDescription,omitempty"`
OrderItems []orderRequestItem `json:"orderItems,omitempty"`
CodeType string `json:"codeType" validate:"required"`
StoreInfo string `json:"storeInfo,omitempty"`
StoreId string `json:"storeId,omitempty"`
TerminalId string `json:"terminalId,omitempty"`
RequestedAt int `json:"requestedAt,omitempty"`
RedirectUrl string `json:"redirectUrl,omitempty"`
RedirectType string `json:"redirectType,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
IsAuthorization bool `json:"isAuthorization,omitempty"`
AuthorizationExpiry int `json:"authorizationExpiry,omitempty"`
}
type createCodeResponse struct {
ResultInfo resultInfo `json:"resultInfo"`
Data createCodeResponseData `json:"data"`
}
type createCodeResponseData struct {
CodeID string `json:"codeId"`
Url string `json:"url"`
Deeplink string `json:"deeplink"`
ExpiryDate int `json:"expiryDate"`
MerchantPaymentId string `json:"merchantPaymentId"`
Amount amount `json:"amount"`
OrderDescription string `json:"orderDescription"`
OrderItems []orderItem `json:"orderItems"`
CodeType string `json:"codeType"`
StoreInfo string `json:"storeInfo"`
StoreID string `json:"storeId"`
TerminalID string `json:"terminalId"`
RequestedAt int `json:"requestedAt"`
RedirectUrl string `json:"redirectUrl"`
RedirectType string `json:"redirectType"`
IsAuthorization bool `json:"isAuthorization"`
AuthorizationExpiry int `json:"authorizationExpiry"`
}
|
JavaScript | UTF-8 | 89 | 2.90625 | 3 | [] | no_license | //12.3 3
function f() {
let obj = Object.create(null)
console.log(obj)
}
f() |
C# | UTF-8 | 650 | 2.515625 | 3 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | namespace Aperture {
/// <summary>
/// Represents a generic video frame
/// </summary>
public abstract class VideoFrame {
/// <summary>
/// Number of pixels in a scanline
/// </summary>
public int Width { get; protected set; }
/// <summary>
/// Number of scanlines
/// </summary>
public int Height { get; protected set; }
/// <summary>
/// Frame presentation time, in 100-nanosecond time units
/// </summary>
public long PresentTime { get; protected set; }
/// <summary>
/// User data
/// </summary>
public object Tag { get; set; }
}
} |
Markdown | UTF-8 | 960 | 3.234375 | 3 | [] | no_license | ---
tab-bar:
width: 700
padding: '1.5rem'
desc: |
The tab bar is used to navigate between tab pages. The tab bar uses jQuery to read the `href` to target the proper page to display, therefore the tab bar each `href` must correspond with a tab page `id`.
tab-page:
width: 700
padding: '1.5rem'
desc: |
The tab page code will vary depending on use. Each tab grouping can have up to three tab pages. Make sure to change the tab page `id` on each page beginning with `#tab-page-1` through `#tab-page-3`.
For this pattern, view the pattern code and **copy paste the html directly**. Include the outer div with classes `pad-t-2` and `pad-b-2` for consistent spacing.
---
Tabbed sections are to be used inside of a `<section>` with an appropriate `section-highlight` class. The tabbed section is used when multiple pages or categories of information are required to be displayed. Examples include product information and the checkout stages.
|
C# | UTF-8 | 795 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | using System;
namespace OpenStory.Common.Game
{
/// <summary>
/// The type of an item.
/// </summary>
[Serializable]
public enum ItemType
{
/// <summary>
/// Default value.
/// </summary>
Unknown = 0,
/// <summary>
/// The item is an equip. It does not stack with
/// other items and has a unique identifier.
/// </summary>
Equip = 1,
/// <summary>
/// The item is generic. It usually stacks with other items
/// and usually does not have a unique identifier.
/// </summary>
Item = 2,
/// <summary>
/// This item is a pet. It does not stack with other items and it has a pet identifier.
/// </summary>
Pet = 3
}
}
|
PHP | UTF-8 | 799 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $nome
* @property string $data_nascimento
* @property string $email
* @property string $foto
* @property boolean $is_active
* @property string $created_at
* @property string $updated_at
* @property CadastroDependente[] $cadastroDependentes
*/
class CadastroPessoa extends Model
{
protected $table = 'cadastro_pessoas';
/**
* @var array
*/
protected $fillable = ['nome', 'data_nascimento', 'email', 'foto', 'is_active', 'created_at', 'updated_at'];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function dependentes()
{
return $this->hasMany(CadastroDependente::class, 'pessoa_id', 'id');
}
}
|
JavaScript | UTF-8 | 414 | 2.53125 | 3 | [] | no_license |
const axios = require('axios');
module.exports = function findPost(query, s, cb) {
let url = 'https://vivacious-port.glitch.me/find/method';
axios.post(url, query)
.then(response => {
if (response.data) {
cb(response.data);
} else {
cb('no match');
}
})
.catch(function (error) {
// handle error
console.log(error);
cb();
});
//console.log(url);
} |
C++ | UTF-8 | 330 | 2.828125 | 3 | [] | no_license | #ifndef HINDEX_II_H
#define HINDEX_II_H
#include <vector>
class Solution_275
{
public:
int hIndex(std::vector<int>& citations)
{
int hindex = citations.size( );
for (int i = 0; i < citations.size( ); i++)
{
if (citations[i] < hindex)
hindex--;
else
break;
}
return hindex;
}
};
#endif // !HINDEX_II_H
|
Java | UTF-8 | 13,987 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package org.ihtsdo.buildcloud.core.service.validation.precondition;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.bind.JAXBException;
import org.ihtsdo.buildcloud.core.dao.BuildDAO;
import org.ihtsdo.buildcloud.core.entity.Build;
import org.ihtsdo.buildcloud.core.manifest.FolderType;
import org.ihtsdo.buildcloud.core.manifest.ListingType;
import org.ihtsdo.buildcloud.core.service.build.RF2Constants;
import org.ihtsdo.buildcloud.core.service.helper.ManifestXmlFileParser;
import org.ihtsdo.otf.rest.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Service;
@Service
public class ManifestCheck extends PreconditionCheck {
private static final String COMMA = ",";
private static final String HYPHEN = "_";
private static final String RELEASE_DATE_NOT_MATCHED_MSG = "The following file names specified in the manifest:%s don't have "
+ "the same release date as configured in the product:%s.";
private static final String PRESENT_IN_SNAPSHOT_BUT_NOT_IN_FULL_MSG = "The following file names specified in the Snapshot folder but not found in the Full folder: %s";
private static final String PRESENT_IN_FULL_BUT_NOT_IN_SNAPSHOT_MSG = "The following file names specified in the Full folder but not found in the Snapshot folder: %s";
private static final String INVALID_RELEASE_PACKAGE_NAME_MSG = "The package name does not follow the packaging conventions: "
+ "[x prefix if applicable]SnomedCT_[Product][Format(optional)]_[ReleaseStatus]_[Releasedate]T[Releasetime]Z";
private static final String INVALID_FILE_NAME_AGAINST_BETA_RELEASE_MSG = "The following files which specified in the manifest are required starting with x for a Beta release: %s";
private static final String INVALID_RELEASE_FILE_FORMAT_MSG = "The following file names specified in the manifest:%s don't follow naming convention:%s.";
private static final String FILE_NAME_CONVENTION = "<FileType>_<ContentType>_<ContentSubType>_<Country|Namespace>_<VersionDate>.<Extension>";
private static final String DER1 = "der1";
private static final String SCT1 = "sct1";
private static final String EMPTY_FILE_NAME_MSG = "Total number of files with no file name specified: %d";
private static final String README_FILE_NOT_FOUND_MSG = "No Readme file ends with .txt found in manifest.";
private static final String INVALID_FILES_IN_FOLDER = "Invalid files in %s folder: %s.";
private static final Logger LOGGER = LoggerFactory.getLogger(ManifestCheck.class);
@Autowired
private BuildDAO buildDAO;
@Value("${srs.release.package.pattern}")
private String releasePackagePattern;
@Override
public void runCheck(final Build build) {
try (InputStream manifestInputSteam = buildDAO.getManifestStream(build)) {
//check that a manifest file is present.
//check that the manifest conforms to the XSD and specifically, that we can find a valid root folder
final ManifestXmlFileParser parser = new ManifestXmlFileParser();
final ListingType manifestListing = parser.parse(manifestInputSteam);
final String releaseVersion = build.getConfiguration().getEffectiveTimeSnomedFormat();
if (releaseVersion != null) {
final String invalidFileNamesInFolderMsg = validateFileNamesAgainstFolder(manifestListing);
if (StringUtils.hasLength(invalidFileNamesInFolderMsg)) {
fatalError(invalidFileNamesInFolderMsg);
return;
}
if (build.getConfiguration().isBetaRelease()) {
final String invalidFileNamesAgainstBetaReleaseMsg = validateFileNamesAgainstBetaRelease(manifestListing);
if (StringUtils.hasLength(invalidFileNamesAgainstBetaReleaseMsg)) {
fatalError(invalidFileNamesAgainstBetaReleaseMsg);
return;
}
}
final String invalidFileFormatMsg = validateFileFormat(manifestListing, releaseVersion);
if (StringUtils.hasLength(invalidFileFormatMsg)) {
fail(invalidFileFormatMsg);
return;
}
final String invalidFilePresentMsg = validateManifestStructure(manifestListing);
if (StringUtils.hasLength(invalidFilePresentMsg)) {
fail(invalidFilePresentMsg);
return;
}
final String invalidReleaseVersionMsg = validateReleaseDate(manifestListing, releaseVersion);
final boolean validReleasePackageName = validatePackageName(manifestListing);
if (StringUtils.hasLength(invalidReleaseVersionMsg) || !validReleasePackageName) {
String warningMsg = "";
if (StringUtils.hasLength(invalidReleaseVersionMsg)) {
warningMsg = invalidReleaseVersionMsg;
}
if (!validReleasePackageName) {
warningMsg = StringUtils.hasLength(invalidReleaseVersionMsg) ?
warningMsg + " " + INVALID_RELEASE_PACKAGE_NAME_MSG : INVALID_RELEASE_PACKAGE_NAME_MSG;
}
warning(warningMsg);
return;
}
}
pass();
} catch (ResourceNotFoundException | JAXBException | IOException e) {
LOGGER.error("Exception thrown when validating manifest file for build:{}", build.getId());
e.printStackTrace();
fatalError("Build manifest is missing or invalid: " + e.getMessage());
}
}
private String validateManifestStructure(final ListingType manifestListing) {
List<FolderType> folderTypes = manifestListing.getFolder().getFolder();
List<String> snapshotFiles = new ArrayList<>();
List<String> fullFiles = new ArrayList<>();
for (FolderType folderType : folderTypes) {
String folderName = folderType.getName();
if (RF2Constants.SNAPSHOT.equals(folderName)) {
snapshotFiles = ManifestFileListingHelper.getFilesByFolderName(manifestListing, folderName);
} else if (RF2Constants.FULL.equals(folderName)) {
fullFiles = ManifestFileListingHelper.getFilesByFolderName(manifestListing, folderName);
}
}
if (!snapshotFiles.isEmpty() && !fullFiles.isEmpty()) {
List <String> finalFullFiles = fullFiles;
List <String> finalSnapshotFiles = snapshotFiles;
List<String> missingFilesInFullFolder = snapshotFiles.stream()
.filter(file -> !finalFullFiles.contains(file.replace("Snapshot_", "Full_").replace("Snapshot-", "Full-")))
.collect(Collectors.toList());
List<String> missingFilesInSnapshotFolder = fullFiles.stream()
.filter(file -> !finalSnapshotFiles.contains(file.replace("Full_", "Snapshot_").replace("Full-", "Snapshot-")))
.collect(Collectors.toList());
if (!missingFilesInFullFolder.isEmpty()) {
return String.format(PRESENT_IN_SNAPSHOT_BUT_NOT_IN_FULL_MSG, String.join(", ", missingFilesInFullFolder));
}
if (!missingFilesInSnapshotFolder.isEmpty()) {
return String.format(PRESENT_IN_FULL_BUT_NOT_IN_SNAPSHOT_MSG, String.join(", ", missingFilesInSnapshotFolder));
}
}
return null;
}
private String validateFileNamesAgainstBetaRelease(ListingType manifestListing) {
final StringBuilder invalidFileNameMsgBuilder = new StringBuilder();
final String zipFileName = manifestListing.getFolder().getName();
// check package name
if (StringUtils.hasLength(zipFileName) && !zipFileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX)) {
invalidFileNameMsgBuilder.append(zipFileName);
}
//check that sct2 and der2 file names starting with X
final List<String> fileNames = ManifestFileListingHelper.listAllFiles(manifestListing);
for (final String fileName : fileNames) {
if (!fileName.startsWith(RF2Constants.README_FILENAME_PREFIX)
&& !fileName.startsWith(RF2Constants.RELEASE_INFORMATION_FILENAME_PREFIX)
&& !fileName.startsWith(RF2Constants.BETA_RELEASE_PREFIX)) {
if (invalidFileNameMsgBuilder.length() > 0) {
invalidFileNameMsgBuilder.append(COMMA);
}
invalidFileNameMsgBuilder.append(fileName);
}
}
if (invalidFileNameMsgBuilder.length() > 0) {
return String.format(INVALID_FILE_NAME_AGAINST_BETA_RELEASE_MSG, invalidFileNameMsgBuilder.toString());
}
return "";
}
private String validateFileFormat(final ListingType manifestListing, final String releaseVersion) {
final StringBuilder invalidFileNameMsgBuilder = new StringBuilder();
//check that sct2 and der2 file names have got the same date as the release date/version
final List<String> fileNames = ManifestFileListingHelper.listAllFiles(manifestListing);
boolean isReadmeFound = false;
int emptyFileNameCount = 0;
for (final String fileName : fileNames) {
//check file name is not empty
if (fileName == null || fileName.trim().length() == 0) {
emptyFileNameCount++;
continue;
}
//check readme txt file
if (!isReadmeFound && fileName.startsWith(RF2Constants.README_FILENAME_PREFIX) && fileName.endsWith(RF2Constants.README_FILENAME_EXTENSION)) {
//Readme_20140831.txt
isReadmeFound = true;
continue;
}
// check RF1 and RF2 file name convention
if (fileName.startsWith(RF2Constants.SCT2) || fileName.startsWith(RF2Constants.DER2) || fileName.startsWith(SCT1) || fileName.startsWith(DER1)) {
final String[] tokens = fileName.split(RF2Constants.FILE_NAME_SEPARATOR);
if (tokens.length != 5) {
if (invalidFileNameMsgBuilder.length() > 0) {
invalidFileNameMsgBuilder.append(COMMA);
}
invalidFileNameMsgBuilder.append(fileName);
}
continue;
}
}
final StringBuilder result = new StringBuilder();
if (invalidFileNameMsgBuilder.length() > 0) {
result.append(String.format(INVALID_RELEASE_FILE_FORMAT_MSG,invalidFileNameMsgBuilder.toString(), FILE_NAME_CONVENTION));
}
if (!isReadmeFound) {
result.append(README_FILE_NOT_FOUND_MSG);
}
if (emptyFileNameCount > 0) {
result.append(String.format(EMPTY_FILE_NAME_MSG, emptyFileNameCount));
}
if (result.length() > 0) {
return result.toString();
}
return null;
}
private String validateReleaseDate(final ListingType manifestListing, final String releaseVersion) {
final StringBuilder releaseVersionMsgBuilder = new StringBuilder();
final String zipFileName = manifestListing.getFolder().getName();
if (!zipFileName.contains(releaseVersion)) {
releaseVersionMsgBuilder.append(zipFileName);
}
//check that sct2 and der2 file names have got the same date as the release date/version
final List<String> fileNames = ManifestFileListingHelper.listAllFiles(manifestListing);
for (final String fileName : fileNames) {
//check file name is not empty
if (fileName == null || fileName.trim().length() == 0) {
continue;
}
if (fileName.startsWith(RF2Constants.README_FILENAME_PREFIX) && fileName.endsWith(RF2Constants.README_FILENAME_EXTENSION)) {
if (fileName.split(RF2Constants.FILE_NAME_SEPARATOR).length >= 2) {
if (!fileName.contains(releaseVersion)) {
if (releaseVersionMsgBuilder.length() > 0) {
releaseVersionMsgBuilder.append(COMMA);
}
releaseVersionMsgBuilder.append(fileName);
}
}
continue;
}
// check RF1 and RF2 file name convention
if (fileName.startsWith(RF2Constants.SCT2) || fileName.startsWith(RF2Constants.DER2) || fileName.startsWith(SCT1) || fileName.startsWith(DER1)) {
final String[] tokens = fileName.split(RF2Constants.FILE_NAME_SEPARATOR);
if (!tokens[tokens.length - 1].contains(releaseVersion)) {
if (releaseVersionMsgBuilder.length() > 0) {
releaseVersionMsgBuilder.append(COMMA);
}
releaseVersionMsgBuilder.append(fileName);
}
continue;
}
}
final StringBuilder result = new StringBuilder();
if (releaseVersionMsgBuilder.length() > 0) {
result.append(String.format(RELEASE_DATE_NOT_MATCHED_MSG, releaseVersionMsgBuilder.toString(), releaseVersion));
}
if (result.length() > 0) {
return result.toString();
}
return null;
}
private boolean validatePackageName(ListingType manifestListing) {
String packageName = manifestListing.getFolder().getName();
Pattern pattern = Pattern.compile(this.releasePackagePattern);
Matcher matcher = pattern.matcher(packageName);
return matcher.matches();
}
private String validateFileNamesAgainstFolder(final ListingType manifestListing) {
List<FolderType> folderTypes = manifestListing.getFolder().getFolder();
final StringBuilder result = new StringBuilder();
for (FolderType folderType : folderTypes) {
String folderName = folderType.getName();
List<String> fileNames = ManifestFileListingHelper.getFilesByFolderName(manifestListing, folderName);
List<String> invalidFileNames;
if (RF2Constants.DELTA.equals(folderName)) {
invalidFileNames = getFileNamesContainsAny(fileNames, RF2Constants.SNAPSHOT + HYPHEN, RF2Constants.FULL + HYPHEN);
if (!invalidFileNames.isEmpty()) {
result.append(String.format(INVALID_FILES_IN_FOLDER, RF2Constants.DELTA, String.join(COMMA, invalidFileNames)));
}
} else if (RF2Constants.SNAPSHOT.equals(folderName)) {
invalidFileNames = getFileNamesContainsAny(fileNames, RF2Constants.DELTA + HYPHEN, RF2Constants.FULL + HYPHEN);
if (!invalidFileNames.isEmpty()) {
result.append(String.format(INVALID_FILES_IN_FOLDER, RF2Constants.SNAPSHOT, String.join(COMMA, invalidFileNames)));
}
} else if (RF2Constants.FULL.equals(folderName)) {
invalidFileNames = getFileNamesContainsAny(fileNames, RF2Constants.DELTA + HYPHEN, RF2Constants.SNAPSHOT + HYPHEN);
if (!invalidFileNames.isEmpty()) {
result.append(String.format(INVALID_FILES_IN_FOLDER, RF2Constants.FULL, String.join(COMMA, invalidFileNames)));
}
} else {
// do nothing
}
}
return result.toString();
}
private List<String> getFileNamesContainsAny(List<String> fileNames, String... patterns) {
List<String> result = new ArrayList<>();
for (String fileName : fileNames) {
if (Arrays.stream(patterns).parallel().anyMatch(fileName::contains)) {
result.add(fileName);
}
}
return result;
}
}
|
JavaScript | UTF-8 | 461 | 3.984375 | 4 | [] | no_license | function isIsogram(str){
//determines if string as no repeating letters (consecutive or not) ignoring case
letters = []
for(var i=0; i < str.length; ++i){
if (letters.includes(str[i].toLowerCase())){
console.log('Sting is not an isogram')
return false;
}
else{
letters.push(str[i].toLowerCase())
}
}
console.log('String is an isogram')
return true
}
isIsogram('heLlo') |
Python | UTF-8 | 2,394 | 2.75 | 3 | [] | no_license | import re
MonsterList = []
XML = open(".\\Mordenkainens Tome of Foes.xml")
def XMLRead(Tag, MultiOutput = 0):
XMLOutput = re.search('<'+ Tag +'>(.*)</'+ Tag +'>', XML.readline())
if XMLOutput != None:
return XMLOutput.group(1)
else:
return ""
while True:
Line = XML.readline()
if Line == " <monster>\n":
MonsterName = XMLRead("name")
MonsterSize = XMLRead("size")
MonsterTemp = XMLRead("type").split(', ')
MonsterType = MonsterTemp[0]
MonsterBook = MonsterTemp[1]
MonsterAlignment = XMLRead("alignment")
MonsterAC = XMLRead("ac")
MonsterHP = XMLRead("hp")
MonsterSpeeds = XMLRead("speed").split(', ')
MonsterSTR = XMLRead("str")
MonsterDEX = XMLRead("dex")
MonsterCON = XMLRead("con")
MonsterINT = XMLRead("int")
MonsterWIS = XMLRead("wis")
MonsterCHA = XMLRead("cha")
MonsterSaves = XMLRead("save").split(', ')
MonsterSkills = XMLRead("skill").split(', ')
MonsterResistances = XMLRead("resist")
MonsterResistances2 = re.search('(.*); (.*)', MonsterResistances)
if MonsterResistances2 == None:
if re.search('and', MonsterResistances) != None:
MonsterResistanceList = [MonsterResistances]
else:
MonsterResistanceList = (MonsterResistances).split(', ')
elif MonsterResistances2 != None:
MonsterResistanceList = (MonsterResistances2.group(1)).split(', ')
MonsterResistanceList.append(MonsterResistances2.group(2))
MonsterImmunities = XMLRead("immune")
MonsterImmunities2 = re.search('(.*); (.*)', MonsterImmunities)
if MonsterImmunities2 == None:
if re.search('and', MonsterImmunities) != None:
MonsterImmunityList = [MonsterImmunities]
else:
MonsterImmunityList = (MonsterImmunities).split(', ')
elif MonsterImmunities2 != None:
MonsterImmunityList = (MonsterImmunities2.group(1)).split(', ')
MonsterImmunityList.append(MonsterImmunities2.group(2))
MonsterList.append([MonsterName, MonsterSize, MonsterType, MonsterBook])
print(MonsterList[-1])
print(MonsterImmunityList)
elif Line == "":
break
|
C | UTF-8 | 6,695 | 3.921875 | 4 | [] | no_license | /**************************************************\
* Filename: linkedList.c *
* Author: Sue Bogar *
* Edited By: Katherine Gibson (gibsonk@seas) *
* Edited By: Wesley Zhao (weszhao@seas) *
* Date Written: 11/17/98 *
* EMail: bogar@cs.umbc.edu *
* *
* Description: This file contains the functions *
* necessary to work with a linked list. *
\**************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "karaoke.h"
#include "linkedList.h"
/********************************************
** Function: CreateNode
** Input: none
** Output: memory for a node is malloced
** and a pointer (nodePtr) to the
** memory is returned to the user
********************************************/
SINGER tempSinger;
NODEPTR CreateNode (void)
{
NODEPTR newNode;
/* get the space needed for the node */
newNode = (NODEPTR) malloc(sizeof(NODE));
if (newNode == NULL)
{
fprintf(stderr, "Out of memory in CreateNode function\n");
exit(-1);
}
/* Initialize the members */
newNode->data = tempSinger;
newNode->next = NULL;
return newNode;
}
/********************************************
** Function: SetData
** Input: a pointer to a node (NODEPTR), and
** the value to be placed into the node
** Output: none
*********************************************/
void SetData (NODEPTR temp, SINGER value)
{
temp->data = value;
}
/********************************************
* Function: Insert
* Input: a pointer to a pointer to the head of the
* linked list (headPtr)
* a pointer to the node (NODEPTR) to be
* inserted
* Output: none
********************************************/
void Insert (NODEPTR* headPtr, NODEPTR temp)
{
NODEPTR prev, curr;
/* if list is empty, temp becomes first node */
if ( *headPtr == NULL )
{
*headPtr = temp;
}
else
{
prev = NULL;
curr = *headPtr;
/* traverse the list until the end */
while (curr != NULL)
{
prev = curr;
curr = curr -> next;
}
/* insert temp at the end */
prev -> next = temp;
}
}
/********************************************
* Function: Delete
* Input: a pointer to a pointer to the head
* (headPtr) of the linked list
* an integer (target) containing the value
* of the data in the node to be deleted
* Output: integer expressing operation success
* - if found, value found in DELETED node is returned
* - if not found, error is printed and -1 is returned
********************************************/
SINGER Delete (NODEPTR* headPtr, SINGER target)
{
SINGER value;
NODEPTR prev, curr;
if (*headPtr == NULL)
{
printf ("Can't delete from an empty list\n");
return value;
}
/* if node to delete is first in list, move head */
else if (strcmp(target.name,((*headPtr)->data).name) == 0)
{
curr = *headPtr;
value = (*headPtr)->data;
*headPtr = (*headPtr)->next;
free (curr);
return value;
}
/* otherwise, traverse the list until
the end or the target value is found */
else
{
prev = *headPtr;
curr = (*headPtr)->next;
while (curr != NULL && (strcmp(target.name, (curr->data).name) != 0))
{
prev = curr;
curr = curr -> next;
}
/* found the target, not the end of the list */
if(curr != NULL)
{
/* delete the node that contains target value */
prev->next = curr->next;
value = curr->data;
free(curr);
return value;
}
else
{
printf("%s was not in the list\n", target.name);
return (tempSinger);
}
}
}
NODEPTR FindNode (NODEPTR* headPtr, char *singerName)
{
NODEPTR prev, curr;
if (*headPtr == NULL)
{
printf ("Can't find from an empty list\n");
return *headPtr;
}
/* if node to find is first in list, move head */
else if (strcmp(singerName,((*headPtr)->data).name) == 0)
{
return *headPtr;
}
/* otherwise, traverse the list until
the end or the target value is found */
else
{
prev = *headPtr;
curr = (*headPtr)->next;
while (curr != NULL && (strcmp(singerName, (curr->data).name) != 0))
{
prev = curr;
curr = curr -> next;
}
/* found the target, not the end of the list */
if(curr != NULL)
{
/* delete the node that contains target value */
return curr;
}
else
{
printf("%s was not in the list\n", singerName);
return (NULL);
}
}
}
void DestroyList(NODEPTR *headPtr){
NODEPTR prev, curr, temp;
if (*headPtr == NULL)
{
printf ("Can't delete from an empty list\n");
}
/* otherwise, traverse the list until
the end or the target value is found */
curr = (*headPtr);
while (curr != NULL){
temp = curr;
curr = curr->next;
free(temp);
}
free(*headPtr);
}
void Move(NODEPTR target, NODEPTR* fromHeadPtr, NODEPTR* toHeadPtr){
NODEPTR prev, curr;
if (*fromHeadPtr == NULL)
{
printf ("Can't traverse from an empty list\n");
}
/* if node to find is first in list, move head */
else if (strcmp((target->data).name,((*fromHeadPtr)->data).name) == 0)
{
curr = *fromHeadPtr;
*fromHeadPtr = (*fromHeadPtr)->next;
}
/* otherwise, traverse the list until
the end or the target value is found */
else
{
prev = *fromHeadPtr;
curr = (*fromHeadPtr)->next;
while (curr != NULL && (strcmp((target->data).name, (curr->data).name) != 0))
{
prev = curr;
curr = curr -> next;
}
/* found the target, not the end of the list */
if(curr != NULL)
{
/* shift the node that contains target value */
prev->next = curr->next;
curr->next = NULL;
}
else
{
printf("%s was not in the list\n", (target->data).name);
}
}
Insert(toHeadPtr, curr);
}
/********************************************
* Function: PrintList
* Input: a pointer to the head of the list
* Ouput: none
********************************************/
void PrintList (NODEPTR head)
{
NODEPTR curr;
if (head == NULL)
{
printf ("The list is empty\n");
}
else
{
curr = head;
/* traverse the list until the end */
while (curr != NULL)
{
/* print the current data item */
printf("%s ", (curr -> data).name);
/* printSinger(curr -> data); */
/* move to the next node */
curr = curr -> next;
}
printf ("\n");
}
}
|
Python | UTF-8 | 598 | 3.03125 | 3 | [] | no_license | class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
dic = {i:set() for i in range(n)}
for i, j in edges:
dic[i].add(j)
dic[j].add(i)
stack = [ dic.keys()[0] ]
visited = set()
while stack:
node = stack.pop()
if node in visited:
return False
visited.add( node )
for neighbour in dic[node]:
stack.append( neighbour )
dic[neighbour].remove(node)
dic.pop(node)
return not dic
n, edges = 5, [[0, 1], [3,4]]
n, edges = 1, []
sl = Solution()
print( sl.validTree( n, edges ) ) |
C# | UTF-8 | 300 | 2.59375 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<byte[]>();
for (int i = 0; i < 100000; i++)
{
list.Add(new byte[100000000]);
}
}
}
|
PHP | UTF-8 | 6,414 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace Getresponse\Sdk\Client\Handler;
use Getresponse\Sdk\Client\Debugger\Logger;
use Getresponse\Sdk\Client\Exception\ConnectException;
use Getresponse\Sdk\Client\Exception\ExceptionFactory;
use Getresponse\Sdk\Client\Exception\RequestException;
use Getresponse\Sdk\Client\Handler\Call\Call;
use Getresponse\Sdk\Client\Handler\Call\CallRegistry;
use Getresponse\Sdk\Client\Version;
use GuzzleHttp\Psr7\Message;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Log\NullLogger;
/**
* Class CurlRequestHandler
* @package Getresponse\Sdk\Client\Handler
*/
class CurlRequestHandler implements RequestHandler
{
const METHOD_POST = 'POST';
const METHOD_DELETE = 'DELETE';
/**
* @var Logger
*/
private $logger;
/**
* CurlRequestHandler constructor.
*/
public function __construct()
{
$this->logger = new Logger(new NullLogger());
}
/**
* @param Logger $logger
*/
public function setLogger(Logger $logger)
{
$this->logger = $logger;
}
/**
* @return Logger
*/
protected function getLogger()
{
return $this->logger;
}
/**
* @param Call $call
*/
public function send(Call $call)
{
$curlHandle = curl_init();
try {
$response = $this->parseResponse($this->sendCurlRequest($call->getRequest(), $curlHandle));
$call->setResponse($response);
} catch (ParseResponseException $e) {
$call->setException(
ExceptionFactory::exceptionFrom(
ConnectException::CODE,
$call->getRequest(),
$e->getPrevious()->getMessage(),
RequestException::getHandlerInfoFromCurlHandler($curlHandle),
Version::VERSION
)
);
} catch (RequestException $e) {
$call->setException($e);
}
$info = CurlCallInfoFactory::createFromInfo(curl_getinfo($curlHandle));
curl_close($curlHandle);
$this->getLogger()->debugCall($call, $info);
}
/**
* @param CallRegistry $callRegistry
*/
public function sendMany(CallRegistry $callRegistry)
{
$curlHandle = curl_init();
foreach ($callRegistry as $call) {
try {
$response = $this->parseResponse($this->sendCurlRequest($call->getRequest(), $curlHandle));
$call->setResponse($response);
} catch (ParseResponseException $e) {
$call->setException(
ExceptionFactory::exceptionFrom(
ConnectException::CODE,
$call->getRequest(),
$e->getPrevious()->getMessage(),
RequestException::getHandlerInfoFromCurlHandler($curlHandle),
Version::VERSION
)
);
} catch (RequestException $e) {
$call->setException($e);
}
$info = CurlCallInfoFactory::createFromInfo(curl_getinfo($curlHandle));
$this->getLogger()->debugCall($call, $info);
}
curl_close($curlHandle);
}
/**
* @return string
*/
public function getUAString()
{
$version = curl_version();
$curlVersion = (!empty($version['version'])) ? $version['version'] : '-';
return sprintf('cURL %s; PHP %s; %s; %s', $curlVersion, PHP_VERSION, PHP_OS, PHP_SAPI);
}
/**
* @param RequestInterface $request
* @param $curlHandle
* @return string
* @throws RequestException
*/
private function sendCurlRequest(RequestInterface $request, $curlHandle)
{
$this->setUpCurl($request, $curlHandle);
$response = curl_exec($curlHandle);
if (curl_errno($curlHandle) !== 0) {
throw ExceptionFactory::exceptionFrom(
ConnectException::CODE,
$request,
curl_error($curlHandle),
RequestException::getHandlerInfoFromCurlHandler($curlHandle),
Version::VERSION
);
}
return $response;
}
/**
* @param RequestInterface $request
* @param $curlHandle
*/
protected function setUpCurl(RequestInterface $request, $curlHandle)
{
$this->getLogger()->debugRequest($request);
curl_setopt($curlHandle, CURLOPT_URL, $request->getUri());
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
$headers = $request->getHeaders();
if ($request->getMethod() === self::METHOD_POST) {
$headers['Content-type'] = 'application/json';
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, (string) $request->getBody());
}
if (!$request->hasHeader('expect') && $request->getBody()->getSize() > 0) {
// prevent cURL from adding `Expect: 100-continue` automatically
$headers['Expect'] = '';
}
if ($request->getMethod() === self::METHOD_DELETE) {
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, self::METHOD_DELETE);
if ($request->getBody()->getSize() > 0) {
$headers['Content-type'] = 'application/json';
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $request->getBody());
}
}
$this->setUpHeaders($curlHandle, $headers);
}
/**
* @param string $message
* @return Response
* @throws ParseResponseException
*/
protected function parseResponse($message)
{
try {
return Message::parseResponse($message);
} catch (\InvalidArgumentException $e) {
throw ParseResponseException::create($e);
}
}
/**
* @param $curlHandle
* @param $headers
*/
private function setUpHeaders($curlHandle, $headers)
{
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array_map(function ($name, $value) {
if (is_array($value)) {
return $name . ': ' . implode(',', $value);
}
return $name . ': ' . $value;
}, array_keys($headers), $headers));
}
}
|
Java | UTF-8 | 1,964 | 2.40625 | 2 | [] | no_license | package com.example.minesweeper;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
/**
* @author Cassandra Chedjou
* */
public class AdapterScore extends RecyclerView.Adapter<AdapterScore.ViewHolder> {
private String[] name;
private String[] score;
private int bestScore;
public AdapterScore(List<String> n, List<String> secondArray, int bestScore){
name= new String[n.size()];
score= new String[secondArray.size()];
this.bestScore = bestScore;
for(int i=0; i<n.size(); i++)
{
name[i] = n.get(i);
score[i] = secondArray.get(i);
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.rowrank,parent,false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.na.setText(name[position]);
holder.sc.setText(score[position]);
if(position == bestScore){
holder.sc.setBackgroundResource(R.drawable.button_design);
}
}
@Override
public int getItemCount() {
return name.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView na, sc;
public ViewHolder(final View itemView){
super(itemView);
na = itemView.findViewById(R.id.textnam);
sc = itemView.findViewById(R.id.textsco);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
} |
Java | UTF-8 | 1,511 | 3.703125 | 4 | [] | no_license | package Encapsulation.Chalange;
public class Printer {
private int tonerLevel;
private int pagesPrinted;
private boolean duplex;
public Printer(int tonerLevel, boolean duplex) {
if(tonerLevel > -1 && tonerLevel <=100) {
this.tonerLevel = tonerLevel;
}
else
{
this.tonerLevel = -1;
}
this.duplex = duplex;
this.pagesPrinted = 0;
}
public int refill(int tonerAdded)
{
//grater than 0 and less than 100
if(tonerLevel > 0 && tonerLevel <= 100)
{
//grater than 100
if(this.tonerLevel + tonerAdded > 100)
{
//throw
return -1;
}
//done right and print outcome
this.tonerLevel += tonerAdded;
return this.tonerLevel;
}
else
{
//return int value -1 if it throws error
return -1;
}
}
public int printPage(int pages)
{
int pagesToPrint = pages;
// pages that are dublepages
if(this.duplex){
pagesToPrint /= 2;
}
System.out.println("Printing Double Pages " );
//Update Pages that are printed
this.pagesPrinted +=pagesToPrint;
//return count
return pagesToPrint;
}
//get # of pages printed
public int getPagesPrinted() {
return pagesPrinted;
}
public int getTonerLevel() {
return tonerLevel;
}
}
|
C++ | UTF-8 | 14,403 | 3.8125 | 4 | [] | no_license | //NAME : SHANTANU TYAGI
//SID : 201801015
//ASSIGNMENT : 4
//DATE : 8/4/19
//PROGRAM : Sorting Algorithms
#include<iostream>
using namespace std;
template <typename E>
class List
{
void operator = (const List&) {}
List(const List&) {}
public:
//constructors and destructors
List() {}
virtual ~List() {}
//Return the number of elements in the List
virtual int NumberOfElements() const = 0;
//Return the Location of current element
virtual int CurrentLocation() const = 0;
//Return the data of current element
virtual const E& getData() const = 0;
//clear all the data from the List
virtual void clear() = 0;
//insert a data in the List at current location
virtual void insert(const E& data) = 0;
//insert a data in the end of the List
virtual void append(const E& data) = 0;
//delete a data at the current Location
virtual E remove() = 0;
//set the current Location to the start of the List
virtual void setListLocationToStart() = 0;
//set the current Location to the end of the List
virtual void setListLocationToEnd() = 0;
//set the current Location to the element on left side
// of current element
virtual void previousElement() = 0;
//set the current Location to the element on left side
// of current element
virtual void nextElement() = 0;
//Set current Location to a new Location
virtual int setToNewLocation(int location) = 0;
virtual void printlist() = 0;
};
template <typename E>
class arrayList: public List<E>
{
int arraySize; // maximum size of the //Private Variables of ArrayList class
int currentSize; // number of data elements stored
int currentLocation; // location pointer of the list
E* dataArray; // Array for storing the data
public:
//constructors and destructors
arrayList(int size)
{
arraySize = size;
currentSize = currentLocation = 0;
dataArray = new E[arraySize];
}
~arrayList()
{
delete [] dataArray;
}
int NumberOfElements() const
{
return currentSize;
}
int CurrentLocation() const
{
return currentLocation+1;
}
const E& getData() const
{
if(currentLocation<=currentSize-1)
{
return dataArray[currentLocation];
}
else if(currentLocation>currentSize && currentLocation<=arraySize-1)
{
cout<<"No entry is made at current location."<<endl;
return 0;
}
}
void clear()
{
for(int i=0;i<currentSize;i++)
{
dataArray[i]=0;
}
currentSize = 0;
currentLocation = 0;
}
void insert(const E& data)
{
if(currentSize==arraySize)
{
cout<<"Array limit exceeded."<<endl;
}
else
{
if(dataArray[currentLocation]!=0)
{
for(int i=currentSize-1;i>=currentLocation;i--)
{
dataArray[i+1]=dataArray[i];
}
dataArray[currentLocation]=data;
currentSize++;
}
else
{
dataArray[currentLocation]=data;
currentSize++;
}
}
}
void append(const E& data)
{
int ua=0;
if(currentSize==arraySize)
{
cout<<"Entry is already made at tail of List."<<endl;
cout<<"Do you want to overwrite it ?"<<endl<<"Enter 0 for NO"<<endl<<"Enter 1 for YES"<<endl; //Giving user right to overwrite an already made entry
cin>>ua;
if(ua==1)
{
dataArray[currentSize-1]=data;
}
}
else
{
dataArray[currentSize]=data;
currentSize++;
}
}
E remove()
{
E datarem;
datarem=dataArray[currentLocation];
if(currentLocation!=currentSize-1)
{
for(int i=currentLocation;i<currentSize;i++)
{
dataArray[i]=dataArray[i+1];
}
}
else
{
dataArray[currentLocation]=0;
}
currentSize--;
return datarem;
}
void setListLocationToStart()
{
currentLocation=0;
}
void setListLocationToEnd()
{
currentLocation=currentSize-1;
}
void previousElement()
{
if(currentLocation>0)
currentLocation--;
else
cout<<"Currently you already are at the start of list."<<endl;
}
void nextElement()
{
if(currentLocation<currentSize-1)
currentLocation++;
}
int setToNewLocation(int location)
{
if(location<=currentSize)
currentLocation=location-1;
else
cout<<"Invalid Location entered."<<endl;
}
void printlist()
{
if(currentSize!=0)
{
for(int i=0;i<currentSize;i++)
{
cout<<" "<<dataArray[i];
}
cout<<"."<<endl;
}
else
{
cout<<" no elements."<<endl;
}
}
};
template <typename E>
void selectionSort(List<E>* l)
{
int minValue,temp,Imin,Ivalue;
for(int i=0;i<=l->NumberOfElements()-2;i++)
{
Imin=i;
l->setToNewLocation(i+1);
minValue=l->getData();
Ivalue=minValue;
for(int j=i+1;j<=l->NumberOfElements()-1;j++)
{
l->setToNewLocation(j+1);
if(l->getData()<minValue)
{
minValue=l->getData();
Imin=j;
}
}
if(Imin!=i)
{
l->setToNewLocation(Imin+1);
l->remove();
l->insert(Ivalue);
l->setToNewLocation(i+1);
l->remove();
l->insert(minValue);
}
}
}
template <typename E>
void bubbleSort(List<E>* l)
{
int curvalue,adjvalue;
for(int loop1=1;loop1<l->NumberOfElements();loop1++)
{
int flag=0;
for(int loop2=0;loop2<l->NumberOfElements()-1;loop2++)
{
l->setToNewLocation(loop2+1);
curvalue=l->getData();
l->nextElement();
adjvalue=l->getData();
if(curvalue>adjvalue)
{
l->remove();
l->insert(curvalue);
l->previousElement();
l->remove();
l->insert(adjvalue);
flag=1;
}
}
if(flag==0)
{
break;
}
}
}
template <typename E>
void quickSort(List<E>* l,int start, int last)
{
int pIndex;
if(start<last)
{
pIndex=Partition(l,start,last);
quickSort(l,start,pIndex-1);
quickSort(l,pIndex+1,last);
}
}
template <typename E>
int Partition(List<E>* l,int start, int last)
{
int pivot,pIndex,temp,pValue;
l->setToNewLocation(last+1);
pivot=l->getData();
pIndex=start;
for(int i=start;i<last;i++)
{
l->setToNewLocation(i+1);
temp=l->getData();
if(temp<=pivot)
{
l->setToNewLocation(pIndex+1);
pValue=l->getData();
l->setToNewLocation(i+1);
l->remove();
l->insert(pValue);
l->setToNewLocation(pIndex+1);
l->remove();
l->insert(temp);
pIndex=pIndex+1;
}
}
l->setToNewLocation(last+1);
temp=l->getData();
l->setToNewLocation(pIndex+1);
pValue=l->getData();
l->remove();
l->insert(temp);
l->setToNewLocation(last+1);
l->remove();
l->insert(pValue);
return pIndex;
}
template <typename E>
void mergeSort(List<E>* a)
{
int n,mid;
n=a->NumberOfElements();
if(n<2)
return ;
mid=n/2;
List<E>* l;
List<E>* r;
arrayList<int> al(mid);
arrayList<int> ar(n-mid);
l=&al;
r=&ar;
a->setToNewLocation(1);
for(int i=0;i<mid;i++)
{
l->insert(a->getData());
l->nextElement();
a->nextElement();
}
a->setToNewLocation(mid+1);
for(int j=mid;j<n;j++)
{
r->insert(a->getData());
r->nextElement();
a->nextElement();
}
mergeSort(l);
mergeSort(r);
Merge(l,r,a);
}
template <typename E>
void Merge(List<E>* l,List<E>* r,List<E>* a)
{
int nl,nr,i,j,k;
i=0;
j=0;
k=0;
nl=l->NumberOfElements();
nr=r->NumberOfElements();
l->setToNewLocation(1);
r->setToNewLocation(1);
a->setToNewLocation(1);
while(i<nl && j<nr)
{
if(l->getData()<=r->getData())
{
a->remove();
a->insert(l->getData());
a->nextElement();
l->nextElement();
i=i+1;
}
else
{
a->remove();
a->insert(r->getData());
a->nextElement();
r->nextElement();
j=j+1;
}
}
while(i<nl)
{
a->remove();
a->insert(l->getData());
a->nextElement();
l->nextElement();
i=i+1;
}
while(j<nr)
{
a->remove();
a->insert(r->getData());
a->nextElement();
r->nextElement();
j=j+1;
}
}
int main()
{
int size;
int uans=1;
int uans1;
int data;
cout<<"Enter size of array :"<<endl;
cin>>size;
arrayList<int> a(size);
List<int>* l;
l=&a;
while(uans==1)
{
cout<<"Do you want to perform any operation ? "<<endl<<"Enter 1 for YES"<<endl<<"Enter 0 for NO"<<endl;
cin>>uans;
if(uans==1)
{
cout<<"Choose operation you want to perform :"<<endl;
cout<<"1 : Numbers of elements in the list."<<endl<<"2 : Current location of List."<<endl;
cout<<"3 : Data at current Location."<<endl<<"4 : Clear whole data of the list."<<endl;
cout<<"5 : Insert at current location."<<endl<<"6 : Append at tail of list."<<endl;
cout<<"7 : Remove data from current location."<<endl<<"8 : Set current location to start of list."<<endl;
cout<<"9 : Set current location to end of list."<<endl<<"10 : Set current location to left of the current element."<<endl;
cout<<"11 : Set current location to right of current element."<<endl<<"12 : Set current location to a specific location."<<endl;
cout<<"13 : Print the whole List."<<endl<<"14 : Selection Sort."<<endl<<"15 : Bubble Sort"<<endl<<"16 : Quick Sort"<<endl;
cout<<"17 : Merge Sort."<<endl;
cin>>uans1;
switch(uans1)
{
case 1:
cout<<"Number of elements in list :"<<a.NumberOfElements()<<endl;
break;
case 2:
cout<<"Current Location is :"<<a.CurrentLocation()<<endl;
break;
case 3:
cout<<"Data at current location is :"<<a.getData()<<endl;
break;
case 4:
a.clear();
cout<<"Complete list is whipped out."<<endl;
break;
case 5:
{
cout<<"Enter data to be inserted :"<<endl;
cin>>data;
a.insert(data);
break;
}
case 6:
{
cout<<"Enter data to be inserted at end of list :"<<endl;
cin>>data;
a.append(data);
break;
}
case 7:
a.remove();
break;
case 8:
a.setListLocationToStart();
break;
case 9:
a.setListLocationToEnd();
break;
case 10:
a.previousElement();
break;
case 11:
a.nextElement();
break;
case 12:
{
cout<<"Enter location you want to go :"<<endl;
cin>>data ;
a.setToNewLocation(data);
break;
}
case 13:
{
cout<<"Current List contains";
a.printlist();
break;
}
case 14:
{
cout<<"Before sorting :"<<endl;
a.printlist();
selectionSort(l);
cout<<"After sorting :"<<endl;
a.printlist();
break;
}
case 15:
{
cout<<"Before Sorting :"<<endl;
a.printlist();
bubbleSort(l);
cout<<"After sorting :"<<endl;
a.printlist();
break;
}
case 16:
{
cout<<"Before Sorting :"<<endl;
a.printlist();
quickSort(l,0,a.NumberOfElements()-1);
cout<<"After sorting :"<<endl;
a.printlist();
break;
}
case 17:
{
cout<<"Before Sorting :"<<endl;
a.printlist();
mergeSort(l);
cout<<"After Sorting:"<<endl;
a.printlist();
break;
}
default :
cout<<"Invalid input entered."<<endl;
break;
}
}
}
return 0;
}
|
JavaScript | UTF-8 | 334 | 3.171875 | 3 | [] | no_license | /*
done
*/
// Negative tests to make sure the coroutine detection is not too overeager
class Greeter {
function Hello(a: int, b: int) {
print(a);
yield;
}
static function StaticHello(a: int, b: int) {
print (a);
yield;
}
}
// does nothing
var t = Greeter();
t.Hello(1, 2);
Greeter.StaticHello(1, 2);
print ("done"); |
PHP | UTF-8 | 9,097 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
// TimThumb script created by Tim McDaniels and Darren Hoyt with tweaks by Ben Gillbanks
// http://code.google.com/p/timthumb/
// MIT License: http://www.opensource.org/licenses/mit-license.php
/* Parameters allowed: */
// w: width
// h: height
// zc: zoom crop (0 or 1)
// q: quality (default is 75 and max is 100)
// HTML example: <img src="/scripts/timthumb.php?src=/images/whatever.jpg&w=150&h=200&zc=1" alt="" />
if( !isset( $_REQUEST[ "src" ] ) ) { die( "no image specified" ); }
// clean params before use
$src = clean_source( stripslashes($_REQUEST[ "src" ]) );
// set document root
$doc_root = get_document_root($src);
// get path to image on file system
$src = $doc_root . '/' . $src;
$new_width = preg_replace( "/[^0-9]+/", "", $_REQUEST[ 'w' ] );
$new_height = preg_replace( "/[^0-9]+/", "", $_REQUEST[ 'h' ] );
$new_height = $_GET['h'];
$zoom_crop = preg_replace( "/[^0-9]+/", "", $_REQUEST[ 'zc' ] );
if( !isset( $_REQUEST['q'] ) ) { $quality = 80; } else { $quality = preg_replace("/[^0-9]/", "", $_REQUEST['q'] ); }
// set path to cache directory (default is ./cache)
// this can be changed to a different location
$cache_dir = './cache';
// get mime type of src
$mime_type = mime_type( $src );
// check to see if this image is in the cache already
check_cache( $cache_dir, $mime_type );
// make sure that the src is gif/jpg/png
if( !valid_src_mime_type( $mime_type ) ) {
$error = "Invalid src mime type: $mime_type";
die( $error );
}
// check to see if GD function exist
if(!function_exists('imagecreatetruecolor')) {
$error = "GD Library Error: imagecreatetruecolor does not exist";
die( $error );
}
if(strlen($src) && file_exists( $src ) ) {
// open the existing image
$image = open_image( $mime_type, $src );
if( $image === false ) { die( 'Unable to open image : ' . $src ); }
// Get original width and height
$width = imagesx( $image );
$height = imagesy( $image );
// don't allow new width or height to be greater than the original
if( $new_width > $width ) { $new_width = $width; }
if( $new_height > $height ) { $new_height = $height; }
// generate new w/h if not provided
if( $new_width && !$new_height ) {
$new_height = $height * ( $new_width / $width );
}
elseif($new_height && !$new_width) {
$new_width = $width * ( $new_height / $height );
}
elseif(!$new_width && !$new_height) {
$new_width = $width;
$new_height = $height;
}
// create a new true color image
$canvas = imagecreatetruecolor( $new_width, $new_height );
if( $zoom_crop ) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ( $cmp_x > $cmp_y ) {
$src_w = round( ( $width / $cmp_x * $cmp_y ) );
$src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );
}
elseif ( $cmp_y > $cmp_x ) {
$src_h = round( ( $height / $cmp_y * $cmp_x ) );
$src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );
}
imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );
}
else {
// copy and resize part of an image with resampling
imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
}
// output image to browser based on mime type
show_image( $mime_type, $canvas, $quality, $cache_dir );
// remove image from memory
imagedestroy( $canvas );
} else {
if( strlen( $src ) ) { echo $src . ' not found.'; } else { echo 'no source specified.'; }
}
function show_image ( $mime_type, $image_resized, $quality, $cache_dir ) {
// check to see if we can write to the cache directory
$is_writable = 0;
$cache_file_name = $cache_dir . '/' . get_cache_file();
if( touch( $cache_file_name ) ) {
// give 666 permissions so that the developer
// can overwrite web server user
chmod( $cache_file_name, 0666 );
$is_writable = 1;
}
else {
$cache_file_name = NULL;
header( 'Content-type: ' . $mime_type );
}
if( stristr( $mime_type, 'gif' ) ) {
imagegif( $image_resized, $cache_file_name );
}
elseif( stristr( $mime_type, 'jpeg' ) ) {
imagejpeg( $image_resized, $cache_file_name, $quality );
}
elseif( stristr( $mime_type, 'png' ) ) {
imagepng( $image_resized, $cache_file_name, ceil( $quality / 10 ) );
}
if( $is_writable ) { show_cache_file( $cache_dir, $mime_type ); }
exit;
}
function open_image ( $mime_type, $src ) {
if( stristr( $mime_type, 'gif' ) ) {
$image = imagecreatefromgif( $src );
}
elseif( stristr( $mime_type, 'jpeg' ) ) {
@ini_set('gd.jpeg_ignore_warning', 1);
$image = imagecreatefromjpeg( $src );
}
elseif( stristr( $mime_type, 'png' ) ) {
$image = imagecreatefrompng( $src );
}
return $image;
}
function mime_type ( $file ) {
$os = strtolower(php_uname());
$mime_type = '';
// use PECL fileinfo to determine mime type
if( function_exists( 'finfo_open' ) ) {
$finfo = finfo_open( FILEINFO_MIME );
$mime_type = finfo_file( $finfo, $file );
finfo_close( $finfo );
}
// try to determine mime type by using unix file command
// this should not be executed on windows
if( !valid_src_mime_type( $mime_type ) && !(eregi('windows', php_uname()))) {
if( preg_match( "/freebsd|linux/", $os ) ) {
$mime_type = trim ( @shell_exec( 'file -bi $file' ) );
}
}
// use file's extension to determine mime type
if( !valid_src_mime_type( $mime_type ) ) {
$frags = split( "\.", $file );
$ext = strtolower( $frags[ count( $frags ) - 1 ] );
$types = array(
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif'
);
if( strlen( $ext ) && strlen( $types[$ext] ) ) {
$mime_type = $types[ $ext ];
}
// if no extension provided, default to jpg
if( !strlen( $ext ) && !valid_src_mime_type( $mime_type ) ) {
$mime_type = 'image/jpeg';
}
}
return $mime_type;
}
function valid_src_mime_type ( $mime_type ) {
if( preg_match( "/jpg|jpeg|gif|png/i", $mime_type ) ) { return 1; }
return 0;
}
function check_cache ( $cache_dir, $mime_type ) {
// make sure cache dir exists
if( !file_exists( $cache_dir ) ) {
// give 777 permissions so that developer can overwrite
// files created by web server user
mkdir( $cache_dir );
chmod( $cache_dir, 0777 );
}
show_cache_file( $cache_dir, $mime_type );
}
function show_cache_file ( $cache_dir, $mime_type ) {
$cache_file = get_cache_file();
if( file_exists( $cache_dir . '/' . $cache_file ) ) {
// check for updates
$if_modified_since = preg_replace( '/;.*$/', '', $_SERVER[ "HTTP_IF_MODIFIED_SINCE" ] );
$gmdate_mod = gmdate( 'D, d M Y H:i:s', filemtime( $cache_dir . '/' . $cache_file ) );
if( strstr( $gmdate_mod, 'GMT' ) ) {
$gmdate_mod .= " GMT";
}
if ( $if_modified_since == $gmdate_mod ) {
header( "HTTP/1.1 304 Not Modified" );
exit;
}
// send headers then display image
header( "Content-Type: " . $mime_type );
header( "Last-Modified: " . gmdate( 'D, d M Y H:i:s', filemtime( $cache_dir . '/' . $cache_file ) . " GMT" ) );
header( "Content-Length: " . filesize( $cache_dir . '/' . $cache_file ) );
header( "Cache-Control: max-age=9999, must-revalidate" );
header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 9999 ) . "GMT" );
readfile( $cache_dir . '/' . $cache_file );
exit;
}
}
function get_cache_file () {
static $cache_file;
if(!$cache_file) {
$frags = split( "\.", $_REQUEST['src'] );
$ext = strtolower( $frags[ count( $frags ) - 1 ] );
if(!valid_extension($ext)) { $ext = 'jpg'; }
$cachename = $_REQUEST['src'] . $_REQUEST['w'] . $_REQUEST['h'] . $_REQUEST['zc'] . $_REQUEST['q'];
$cache_file = md5( $cachename ) . '.' . $ext;
}
return $cache_file;
}
function valid_extension ($ext) {
if( preg_match( "/jpg|jpeg|png|gif/i", $ext ) ) return 1;
return 0;
}
function clean_source ( $src ) {
// don't allow off site src to be specified via http/https/ftp
if( preg_match( "/^((ht|f)tp(s|):\/\/)/i", $src ) ) {
die( "Improper src specified:" . $src );
}
//$src = preg_replace( "/(?:^\/+|\.{2,}\/+?)/", "", $src );
//$src = preg_replace( '/^\w+:\/\/[^\/]+/', '', $src );
// don't allow users the ability to use '../'
// in order to gain access to files below document root
// src should be specified relative to document root like:
// src=images/img.jpg or src=/images/img.jpg
// not like:
// src=../images/img.jpg
$src = preg_replace( "/\.\.+\//", "", $src );
return $src;
}
function get_document_root ($src) {
if( @file_exists( $_SERVER['DOCUMENT_ROOT'] . '/' . $src ) ) {
return $_SERVER['DOCUMENT_ROOT'];
}
// the relative paths below are useful if timthumb is moved outside of document root
// specifically if installed in wordpress themes like mimbo pro:
// /wp-content/themes/mimbopro/scripts/timthumb.php
$paths = array( '..', '../..', '../../..', '../../../..' );
foreach( $paths as $path ) {
if( @file_exists( $path . '/' . $src ) ) {
return $path;
}
}
}
?>
|
C | UTF-8 | 1,048 | 3.390625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void exibeVetor(int gVetor[], int n);
int insertSort(int gVetor[], int n);
void main (void)
{
int gVetor[40000];
int n = sizeof(gVetor)/sizeof(gVetor[0]);
clock_t time;
double t_time;
srand(0);
for(int i = 0; i < 40000; i++)
gVetor[i] = rand();
time = clock();
insertSort(gVetor, n);
printf("\nArray Ordenada: \n");
exibeVetor(gVetor, n);
time = clock() - time;
printf("\n");
t_time = ((double)time) / CLOCKS_PER_SEC;
printf("Tempo de execucao: %.3lf segundos\n", t_time);
}
int insertSort(int gVetor[], int n)
{
int i, j, key;
for (i = 1; i < n; i++)
{
key = gVetor[i];
j = i - 1;
while(j >= 0 && gVetor[j] > key)
{
gVetor[j + 1] = gVetor[j];
j = j - 1;
}
gVetor[j + 1] = key;
}
}
void exibeVetor(int gVetor[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ",gVetor[i]);
printf("\n");
}
|
JavaScript | UTF-8 | 1,255 | 2.59375 | 3 | [] | no_license | import React, { useState,useEffect } from 'react';
import {BrowserRouter as Router,Link,Route} from 'react-router-dom'
function Index(){
useEffect(()=>{
console.log('Index页面的--来了---');
return ()=>{
console.log('Index页面的--走了---');
}
},[])
return(
<div>
index页面
</div>
)
}
function List(){
useEffect(()=>{
console.log('list页面----来了---')
return ()=>{
console.log('list页面----走了---')
}
},[])
return(
<div>
List页面
</div>
)
}
function Example (){
const [count,setCount] = useState(0);
useEffect(() =>{
console.log(`effect ----the count is ${count}`)
})
return(
<>
<p>the num is {count}</p>
<button onClick={()=>{setCount(count+1)}}>click me </button>
<Router>
<ul>
<li><Link to="/" >首页</Link></li>
<li><Link to="/list" >列表页</Link></li>
<Route path="/" exact component={Index} />
<Route path="/list" component={List} />
</ul>
</Router>
</>
)
}
export default Example; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.