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 | 2,781 | 3.6875 | 4 | [] | no_license | package lab3.Tasks;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class TaskA implements Serializable {
private int[] arr;
public TaskA(){
int[] Arr = {0, 1, 2, 3, 4, 5, 6};
this.arr = Arr;
}
public TaskA(int[] arr){
this.arr = arr;
}
public TaskA(String in) {
String[] temp = in.split(" ");
int[] Temp = new int[temp.length];
for (int i = 0; i < temp.length; i++) {
Temp[i] = Integer.parseInt(temp[i]); // перевод чисел из string в int
}
this.arr = Temp;
}
public TaskA(TaskA temp) {
this.arr = temp.arr;
}
public void setArr(int[] arr) {
this.arr = arr;
}
public int[] getArr() {
return arr;
}
public void write(String str) throws FileNotFoundException, IOException {
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(str))) {
objectOutputStream.writeObject(this);
}
}
public TaskA read(String str) throws IOException, ClassNotFoundException {
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("taskA.out"))) {
TaskA aRestored = (TaskA) objectInputStream.readObject();
return aRestored;
}
}
public void result() {
boolean check1 = true, check2 = true;
for (int i = 0; i < arr.length-1; i++) {
if (arr[i] > arr[i+1]) { // проверка сортировки
check1 = false;
}
if (arr[i] < arr[i+1]) {
check2 = false;
}
}
if (check1 | check2) {
if (check1 & check2) {
System.out.println("Все элементы массива равны");
}
else {
if (check2) {
System.out.println("Массив упорядочен по убыванию");
}
else {
System.out.println("Массив упорядочен по возрастанию");
}
}
}
else {
System.out.println("Массив не отсортирован");
}
}
public void print() {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
|
Java | UTF-8 | 13,071 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.clerezza.templating.seedsnipe.simpleparser;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.apache.clerezza.templating.seedsnipe.datastructure.DataFieldResolver;
import org.apache.clerezza.templating.seedsnipe.datastructure.FieldDoesNotHaveDimensionException;
import org.apache.clerezza.templating.seedsnipe.datastructure.FieldIndexOutOfBoundsException;
import org.apache.clerezza.templating.seedsnipe.datastructure.InvalidElementException;
/**
* Default parser for parsing text with
* FreeMarker (http://freemarker.sourceforge.net/) style tags.
*
* <p>
* This parser takes text input from a <code>java.io.Reader</code>
* and writes text output to a <code>java.io.Writer</code>.
* </p>
*
* @author reto
* @author daniel
*/
public class DefaultParser {
private final static char[] beginCodeSection = {'$', '{'};
private final static char[] endCodeSection = {'}'};
private final static Hashtable<String, KeywordResolver> keywords = new Hashtable<String, KeywordResolver>();
private final static String errorBegin = "<!--";
private final static String errorEnd = "-->";
private Reader in;
private Writer out;
/**
* Creates and initializes a new Parser.
*
* @param in Reader from which the parser takes its input.
* @param out Writer to which the parser writes its output.
* @param dataFieldResolver data model of the input.
*/
public DefaultParser(Reader in, Writer out) {
this.in = new MultiMarkLineNumberReader(in);
this.out = out;
// add keywords and resolvers
DefaultParser.keywords.put("loop", new LoopKeywordResolver());
DefaultParser.keywords.put("if", new IfKeywordResolver());
}
/**
* Starts the parsing procedure.
*
* @see DefaultParser#perform(Writer, String[], int[])
*/
public void perform(DataFieldResolver dataFieldResolver) throws IOException {
perform(out, new String[0], new int[0], dataFieldResolver);
}
/**
* Parses the input string.
*
* <p>
* DataFields are resolved using this parser's dataFieldResolver, keyword
* resolution is delegated to a <code>KeywordResolver</code>. The input that
* is not withing a tag (keyword or datafield) is written directly to
* <code>out</code> unless it is consumed by a <code>KeywordResolver</code>.
* </p>
* <p>
* <b>NOTE:</b> For the initial start of the parsing use <code>perform()</code>
* </p>
* <p>
* The arrayPositioner holds the postions to be used for resolving
* multi-dimensional fields. E.g. in a loop construct
* <code>arrayPositioner[0]</code> will hold the iteration (starting from 0)
* of the outer most loop, <code>arrayPositioner[1]</code> holds the iteration
* of the first inner loop.
* </p>
*
* @param out the current output reader.
* @param endMarkers the currently expected endMarkers.
* @param arrayPositioner the current arrayPositioner.
* @return the reached end-marker if one has been reached, null otherwise
* (i.e. when the end of in has been reached)
*
* @see #resolve(String, Reader, Writer, DataFieldResolver, String[], int[])
*/
public String perform(Writer out, String[] endMarkers, int[] arrayPositioner,
DataFieldResolver dataFieldResolver) throws IOException {
//The position of the char in beginCodeSection[] or endCodeSection[] we
//look for when parsing for keywords.
int evaluatingSectionChangePosition = 0;
// is the next character escaped?
boolean escapedChar = false;
// is the following input part of a keyword or its parameters?
boolean writingCode = false;
StringWriter codeSection = new StringWriter(); // saves the parsed
// keyword and
// parameters.
try {
MAIN:
while (true) {
if (!writingCode) { // parsing normal text
int c = in.read();
if (c == -1) {
return null; // end of stream
}
if (escapedChar) { // the current character has been
// escaped.
if (c == beginCodeSection[0]) {
if (out != null) {
out.write(beginCodeSection[0]);
}
escapedChar = false;
continue MAIN;
}
if (c == '\\') { // backslash
if (out != null) {
out.write('\\');
}
escapedChar = false;
continue MAIN;
}
// Not a known escape sequence
escapedChar = false;
if (out != null) {
// write backslash to output so
// it remains escaped for the next interpreter.
// (e.g. \n or \t)
out.write('\\');
}
}
// possible introduction of a keyword
if (c == beginCodeSection[evaluatingSectionChangePosition]) {
evaluatingSectionChangePosition++;
if (evaluatingSectionChangePosition == beginCodeSection.length) {
// verified that the next characters
// are to be interpreted as a keyword
writingCode = true;
evaluatingSectionChangePosition = 0;
}
continue MAIN;
} else { // not a keyword introducing sequence
if (evaluatingSectionChangePosition > 0) {
// there was part of a keyword introducing sequence
// just before.
if (out != null) {
out.write(beginCodeSection, 0,
evaluatingSectionChangePosition);
}
evaluatingSectionChangePosition = 0;
}
}
// if the read character is a backslash the following
// character is not to be interpreted as normal input.
if (c == '\\') {
escapedChar = true;
continue MAIN;
}
// not escaped, not a keyword introduction, just plain
// text
if (out != null) {
out.write(c);
}
} else { // writingCode - parsing for a keyword and
// parameters
int c;
c = in.read();
if (c == -1) { // nothing could be read
return null;
}
if (c == endCodeSection[evaluatingSectionChangePosition]) {
evaluatingSectionChangePosition++;
if (evaluatingSectionChangePosition == endCodeSection.length) {
try {
String codeSectionString = codeSection.toString();
codeSection = new StringWriter();
//resolve the parsed keyword or datafield
final String reachedEndMarker = resolve(codeSectionString, in, out,
dataFieldResolver, endMarkers,
arrayPositioner);
if (reachedEndMarker != null) {
return reachedEndMarker;
}
} catch (IOException ex) {
throw new RuntimeException(ex.toString());
}
writingCode = false;
evaluatingSectionChangePosition = 0;
}
continue MAIN;
} else {
if (evaluatingSectionChangePosition > 0) { //interpret keyword as
codeSection.write(endCodeSection, 0, //normal text and write
evaluatingSectionChangePosition);
evaluatingSectionChangePosition = 0;
}
}
codeSection.write(c);
}
}
} finally {
try {
if (out != null) {
out.flush();
}
} catch (IOException ex) {
throw new RuntimeException(ex.toString());
}
}
}
/**
* Handles parsed keywords, end markers and fields.
*
* @param code the parsed keyword, end marker or field with parameters.
* @param in the current reader.
* @param out the current writer.
* @param dataFieldResolver the data model.
* @param endMarkers the current end markers.
* @param arrayPositioner the current loop variables.
* @return the reached end-marker if <code>code</code> starts with one, null otherwise
*
* @throws IOException Thrown if there is an problem with the Writer.
*/
private String resolve(String code, Reader in, Writer out,
DataFieldResolver dataFieldResolver, String[] endMarkers,
int[] arrayPositioner) throws IOException {
StringTokenizer stringTokens = new StringTokenizer(code, " \t()-\n\r");
String firstWord;
try {
firstWord = stringTokens.nextToken();
} catch (java.util.NoSuchElementException ex) {
throw new RuntimeException("Syntax error");
}
for (int i = 0; i < endMarkers.length; i++) {
if (endMarkers[i].equals(firstWord)) {
return firstWord;
}
}
if (keywords.containsKey(firstWord)) { //firstWord is a keyword
int beginParameters = code.indexOf(firstWord) + firstWord.length();
String parameters;
if (beginParameters < code.length()) {
parameters = code.substring(beginParameters); //extract parameters
} else {
parameters = "";
}
try {
//resolve the keyword with the mapped keyword resolver.
keywords.get(firstWord).resolve(this, parameters, in, out, dataFieldResolver,
arrayPositioner);
} catch (Exception ex) {
ex.printStackTrace();
out.write("<--! exception in keywordResolver: " + ex.toString() + "-->");
}
} else {
if (out != null) {
try {
Object resolvedField = dataFieldResolver.resolve(code,
arrayPositioner); //resolve a field
if (!(resolvedField instanceof Class)) {
out.write(resolvedField.toString());
}
} catch (FieldDoesNotHaveDimensionException ex) {
out.write(ex.getSolutionObtainedReducingDimensions().toString());
} catch (FieldIndexOutOfBoundsException ex) {
out.write(errorBegin + " could not resolve: " + code + " (" + ex + ") " + errorEnd);
} catch (InvalidElementException ex) {
out.write(errorBegin + " could not resolve: " + code + " (" + ex + ") " + errorEnd);
}
}
}
return null;
}
} |
Markdown | UTF-8 | 2,647 | 3.625 | 4 | [] | no_license | # 3. 힙 - 3) 이중우선순위큐
### ✨문제
> ###### 문제 설명
>
> 이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
>
> | 명령어 | 수신 탑(높이) |
> | ------ | ------------------------------ |
> | I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
> | D 1 | 큐에서 최댓값을 삭제합니다. |
> | D -1 | 큐에서 최솟값을 삭제합니다. |
>
> 이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
>
> ##### 제한사항
>
> - operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
> - operations의 원소는 큐가 수행할 연산을 나타냅니다.
> - 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
> - 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
>
> ##### 입출력 예
>
> | operations | return |
> | ------------------- | ------ |
> | [I 16,D 1] | [0,0] |
> | [I 7,I 5,I -5,D -1] | [7,5] |
#### 🎈 내 풀이
```python
import heapq
def solution(operations):
result = []
for order in operations:
a,b = order.split(" ")
if a == 'I':
heapq.heappush(result,int(b))
else:
if int(b) < 0:
heapq.heappop(result)
else:
if result != []:
result.pop()
if result == []:
return [0,0]
return [max(result),min(result)]
```
결과는 맞으나 런타임 에러가 발생한다..
#### **📚 다른 풀이**
```python
import heapq
def solution(operations):
result = []
for order in operations:
a,b = order.split(" ")
if a == 'I':
heapq.heappush(result,int(b))
elif result:
if int(b) < 0:
heapq.heappop(result)
else:
result.pop()
if result == []:
return [0,0]
return [max(result),min(result)]
```
런타임 에러가 뜨냐 안뜨냐의 차이는 바로 result가 비어있는것을 앞에서 확인해주냐, 한층 더 낮은 깊이에서 확인해주냐이었다.
앞에서 비어있는 것을 확인해줄수 있는 경우에는 한층 더 깊어지기전에 꼭 확인을 하도록 하자.
#### **🧨 고찰**
### 👍출처
|
Swift | UTF-8 | 1,133 | 2.609375 | 3 | [] | no_license | //
// TableViewCell.swift
// auto_coursework
//
// Created by Александр Пономарев on 04.05.17.
// Copyright © 2017 Alexander Ponomarev. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
var shadowed: Bool = false
override func layoutSubviews() {
super.layoutSubviews()
if self.reuseIdentifier != "no separator" {
var insets: CGFloat
insets = CGFloat(integerLiteral: Int(self.reuseIdentifier ?? "0")!)
if !shadowed {
let line = EdgeShadowLayer(forView: self, edge: .Bottom, shadowRadius: 1, toColor: UIColor(red:0.89, green:0.89, blue:0.91, alpha:1.00), fromColor: UIColor(red:0.89, green:0.89, blue:0.91, alpha:1.00), opacity: 1, insets: insets)
self.layer.addSublayer(line)
}
}
}
func setShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 0.05
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 2.0
self.clipsToBounds = false
}
}
|
Python | UTF-8 | 358 | 4.46875 | 4 | [
"MIT"
] | permissive | #Faça um programa que pergunte ao usuario o valor do produto,
#e mostre o valor final com 5% de desconto.
valorProduto = float(input('Qual o valor do produto? R$ '))
desconto = (valorProduto * 5) / 100
vFinal = valorProduto - desconto
print('O valor do produto é R${}'.format(valorProduto))
print('O novo valor com o desconto é de R${}'.format(vFinal))
|
PHP | UTF-8 | 2,362 | 2.53125 | 3 | [] | no_license | <?php
require('..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'app-top.php');
$ERROR=false;
$ERROR_MSG='';
if(isset($_REQUEST['table'])) {$table = $_REQUEST['table'];} else { $ERROR=true; $ERROR_MSG .='1;';} /* numele tabelei in care se face interogarea */
if(isset($_REQUEST['ida'])) {$ida = $_REQUEST['ida'];} else { $ERROR=true; $ERROR_MSG .='2;';} /* id archive */
if(isset($_REQUEST['filter_field'])) {$filter_field = $_REQUEST['filter_field'];} else { $ERROR=true; $ERROR_MSG .='3;';} /* campul dupa care se face filtrarea */
if(isset($_REQUEST['value'])) {$value = $_REQUEST['value'];} else { $ERROR=true; $ERROR_MSG .='4;';} /* valoarea de filtrare */
if(isset($_REQUEST['field_for_value'])) {$field_for_value = $_REQUEST['field_for_value'];} else { $ERROR=true; $ERROR_MSG .='5;';} /* campul de interogare pentru valoarea din <option value ="xxx"></option>*/
if(isset($_REQUEST['field_for_title'])) {$field_for_title = $_REQUEST['field_for_title'];} else { $ERROR=true; $ERROR_MSG .='6;';} /* campul de interogare pentru descrierea din <option >YYY</option>*/
if(isset($_REQUEST['order_value'])) {$order_value = urldecode($_REQUEST['order_value']);} else { $ERROR=true; $ERROR_MSG .='7;';} /* valoarea care defineste ordinea de afisare */
if(isset($_REQUEST['first_title'])) {$first_title = urldecode($_REQUEST['first_title']);} else { $ERROR=true; $ERROR_MSG .='8;';} /* denumirea primei inregistrari din combo */
if (!$ERROR) {
$table_name = $table;
$eval_str = "\$table_name = \$oDB->$table;";
eval($eval_str);
$query = "SELECT $field_for_value AS id, $field_for_title AS title FROM $table_name WHERE $filter_field=$value AND id_archive=$ida AND visible!=0 ORDER BY ".$order_value;
$result = $oDB->db_query($query);
echo '<option value="">'.$first_title.'</option>'."\n";
while ($result_line = $oDB->db_fetch_array($result)) {
echo '<option value="'.$result_line['id'].'">'.$result_line['title'].'</option>'."\n";
}
} else {
echo '<option value="1">Eroare: '.$ERROR_MSG.'</option>';
}
?>
|
Python | UTF-8 | 579 | 3.125 | 3 | [] | no_license | import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
# read data
# dataframe = pd.read_fwf('brain_body.txt')
dataframe = pd.read_csv('challenge_dataset.txt', sep=',',
header=None, names=['Brain', 'Body'])
# brain measurments
x_values = dataframe[['Brain']]
# body measurements
y_values = dataframe[['Body']]
# train model on data using linear regression
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)
# visualize results
plt.scatter(x_values, y_values)
plt.plot(x_values, body_reg.predict(x_values))
plt.show()
|
Java | UTF-8 | 915 | 2.046875 | 2 | [] | no_license | package com.javapai.practice.springdata;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
@Controller
public class TestSpringDataMongodb {
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void searchTest() {
Ncallrecords users = new Ncallrecords();
users.setUserId("8");
mongoTemplate.getCollection("ncallrecords");
List<Ncallrecords> list = mongoTemplate.find(new Query(Criteria.where("userId").is(users.getUserId())), Ncallrecords.class);
System.out.println("edit user mongodb:" + list);
// System.out.println(">>>"+messageResult.getData().toString());
}
}
|
Markdown | UTF-8 | 810 | 2.5625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "The worst-paying jobs for college grads boast this sneaky advantage"
posturl: https://www.washingtonpost.com/news/wonk/wp/2017/05/15/the-worst-paying-jobs-for-college-grads-boast-this-sneaky-advantage/
tags:
- Job automation
---
{% include post_info_header.md %}
I don't like these type of articles, as they focus too much on the "replacement" part, not how AI tech can make every workers life easier by making them smarter - this goes even for teachers and social workers. Especially replacing software engineers are too far fetched, there are too many realities of development this article ignores. But the fears are there, so design's role is crucial, as holistic product view has to consider the broader impact of deployed systems.
<!--more-->
{% include post_info_footer.md %}
|
C | UTF-8 | 2,197 | 3.765625 | 4 | [] | no_license | #include "pch.h"
#include <stdio.h>
#include <stdlib.h>
void wypisywanie(float tab[]);
void uzupelnianie(float tab[]);
void sortowanie(float tab[]);
float srednia(float tab[], float a);
float dodawanie(float tab[]);
float minimum(float tab[]);
float maximum(float tab[]);
float mediana(float tab[]);
void suma2(float tab[], float tab2[]);
void main()
{
float tab1[] = { 1, 2, 3, 4, 5, 6, 7, 8 , 9, 10 };
float tab2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
uzupelnianie(tab1);
wypisywanie(tab1);
printf("\n\nSuma: %g\n", dodawanie(tab1));
printf("\nSrednia: %g", srednia(tab1, dodawanie(tab1)));
printf("\n\nMin wartosc: %g", minimum(tab1));
printf("\n\nMax wartosc: %g\n\n", maximum(tab1));
float tab3[10];//w 8 N elementów
suma2(tab1, tab2, tab3);
suma2(tab1, tab2, tab3);
printf("Po dodaniu - ");
wypisywanie(tab1);
reset(tab1, tab2);
printf("\n\n");
printf("Sortowanie - ");
sortowanie(tab1);
wypisywanie(tab1);
printf("\n\nMediana: %g\n\n", mediana(tab1));
printf("\n\n");
}
void uzupelnianie(float tab[])
{
float d;
for (int i = 0; i < 10; i++)
{
printf("Podaj liczbe do tablicy: ");
scanf_s("%g", &d);
tab[i] = d;
system("cls");
}
}
void wypisywanie(float tab[])
{
printf("Tablica={");
for (int i = 0; i < 9; i++)
{
printf("%g, ", tab[i]);
}
printf("%g}", tab[9]);
}
void sortowanie(float tab[])
{
for (int i = 0; i < 10 - 1; i++)
{
for (int j = 0; j < 10 - 1 - i; j++)
{
if (tab[j] > tab[j + 1])
{
int temp = tab[j + 1];
tab[j + 1] = tab[j];
tab[j] = temp;
}
}
}
}
float dodawanie(float tab[])
{
float suma = 0;
for (int i = 0; i < 10; i++)
{
suma = suma + tab[i];
}
return suma;
}
float srednia(float tab[], float a)
{
float b = a / 10;
return b;
}
float minimum(float tab[])
{
float min = tab[0];
for (int i = 0; i < 10; i++)
{
if (tab[i] < min)
min = tab[i];
}
return min;
}
float maximum(float tab[])
{
float max = tab[0];
for (int i = 0; i < 10; i++)
{
if (tab[i] > max)
max = tab[i];
}
return max;
}
float mediana(float tab[])
{
float b = (tab[4] + tab[5]) / 2;
return b;
}
void suma2(float tab[], float tab2[])
{
for (int i = 0; i < 10; i++)
{
tab[i] += tab2[i];
}
}
|
PHP | UTF-8 | 4,170 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace CEmerson\DBSafe\CredentialsProviders;
use Aws\Exception\AwsException;
use Aws\SecretsManager\SecretsManagerClient;
use CEmerson\DBSafe\Exceptions\ErrorFetchingCredentials;
use DateInterval;
class AWSSecretsManagerCredentialsProvider extends AbstractCredentialsProvider
{
/** @var string */
private $DBIdentifier;
/** @var SecretsManagerClient */
private $secretsManagerClient;
/** @var string */
private $credentialsName;
/** @var string */
private $charset;
/** @var DateInterval */
private $expiresAfter;
private $credentials = null;
public function __construct(
string $DBIdentifier,
SecretsManagerClient $secretsManagerClient,
string $credentialsName,
string $charset = 'utf8',
?DateInterval $expiresAfter = null
) {
$this->DBIdentifier = $DBIdentifier;
$this->secretsManagerClient = $secretsManagerClient;
$this->credentialsName = $credentialsName;
$this->charset = $charset;
$this->expiresAfter = $expiresAfter;
parent::__construct();
}
public function getDBIdentifier(): string
{
return $this->DBIdentifier;
}
public function getDSN(): string
{
$this->fetchCredentials();
return $this->getDSNString(
$this->credentials->engine,
$this->credentials->host,
$this->credentials->dbname,
$this->charset,
(int) $this->credentials->port
);
}
public function getUsername(): string
{
$this->fetchCredentials();
return $this->credentials->username;
}
public function getPassword(): string
{
$this->fetchCredentials();
return $this->credentials->password;
}
public function getCacheExpiresAfter(): ?DateInterval
{
return $this->expiresAfter;
}
private function fetchCredentials(): void
{
if (is_null($this->credentials)) {
try {
$this->logger->debug("Attempting to call Secrets Manager for credentials");
$result = $this->secretsManagerClient->getSecretValue([
'SecretId' => $this->credentialsName
]);
} catch (AwsException $awsException) {
$error = $awsException->getAwsErrorCode();
$errorMessage = '';
switch ($error) {
case 'DecryptionFailureException':
$errorMessage =
": Secrets Manager can't decrypt the protected secret text using the provided AWS KMS key.";
break;
case 'InternalServiceErrorException':
$errorMessage = ": An error occurred on the server side.";
break;
case 'InvalidParameterException':
$errorMessage = ": You provided an invalid value for a parameter.";
break;
case 'InvalidRequestException':
$errorMessage =
": You provided a parameter value that is not valid for the current state of the resource.";
break;
case 'ResourceNotFoundException':
$errorMessage = ": We can't find the resource that you asked for.";
break;
}
$this->logger->error($error . $errorMessage);
throw new ErrorFetchingCredentials($error . $errorMessage,0, $awsException);
}
$this->logger->debug("Success fetching credentials - extracting from results object");
if (isset($result['SecretString'])) {
$secret = $result['SecretString'];
} else {
$secret = base64_decode($result['SecretBinary']);
}
$this->credentials = json_decode($secret);
} else {
$this->logger->debug("Credentials already fetched - skipping fetch instruction");
}
}
}
|
Java | UTF-8 | 1,790 | 2.8125 | 3 | [] | no_license | package com.zqh.midd.kafka.quickstart;
import java.util.*;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
/**
* Created by hadoop on 14-11-19.
*
* https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+Producer+Example
*/
public class TestProducer {
public static void main(String[] args) {
long events = 100;
Random rnd = new Random();
// First define properties for how the Producer finds the cluster,
// serializes the messages and if appropriate directs the message to a specific Partition.
Properties props = new Properties();
// 单机单服务
props.put("metadata.broker.list", "localhost:9092");
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("partitioner.class", "com.zqh.midd.kafka.quickstart.SimplePartitioner");
props.put("request.required.acks", "1");
ProducerConfig config = new ProducerConfig(props);
// Next you define the Producer object itself
// The first is the type of the Partition key, the second the type of the message
Producer<String, String> producer = new Producer<String, String>(config);
for (long nEvents = 0; nEvents < events; nEvents++) {
// Now build your message
long runtime = new Date().getTime();
String ip = "192.168.2." + rnd.nextInt(255);
String msg = runtime + ",www.example.com," + ip;
// Finally write the message to the Broker
// passing the IP as the partition key
KeyedMessage<String, String> data = new KeyedMessage<String, String>("test", ip, msg);
producer.send(data);
}
producer.close();
}
} |
C | UTF-8 | 9,960 | 2.53125 | 3 | [] | no_license | #include <stdlib.h>
#include <string.h>
#include <math.h>
#include "BabyX.h"
#include "tabpanel.h"
#define PI 3.1415926535897932384626433832795
typedef struct
{
BABYX *bbx;
BBX_Panel *pan;
BBX_Canvas *tabpane_can;
BBX_Canvas *left_can;
BBX_Canvas *bottom_can;
BBX_Canvas *right_can;
int Ntabs;
int current;
char **tabnames;
void(**layout)(void *ptr, int width, int height, int miny);
void **ptr;
void **objects;
int Nchildren;
int width;
int height;
} BBX_TAB;
static void bbx_tab_layout(void *ptr, int width, int height);
static void bbx_tab_drawtabpane();
static void bbx_tab_mouse(void *ptr, int action, int x, int y, int buttons);
static void drawarc(unsigned char *rgba, int width, int height, int x0, int y0, int radius, double from, double to, BBX_RGBA col);
BBX_Panel *bbx_tab(BABYX *bbx, BBX_Panel *parent)
{
BBX_Panel *pan;
BBX_TAB *tab;
tab = bbx_malloc(sizeof(BBX_TAB));
tab->bbx = bbx;
pan = bbx_panel(bbx, parent, "tab", bbx_tab_layout, tab);
tab->pan = pan;
tab->tabpane_can = 0;
tab->left_can = 0;
tab->right_can = 0;
tab->bottom_can = 0;
tab->current = -1;
tab->Ntabs = 0;
tab->tabnames = 0;
tab->layout = 0;
tab->ptr = 0;
tab->objects = 0;
tab->Nchildren = 0;
tab->width = -1;
tab->height = -1;
return pan;
}
void bbx_tab_kill(BBX_Panel *obj)
{
BBX_TAB *tab;
int i;
if (obj)
{
tab = bbx_panel_getptr(obj);
bbx_canvas_kill(tab->tabpane_can);
bbx_canvas_kill(tab->left_can);
bbx_canvas_kill(tab->right_can);
bbx_canvas_kill(tab->bottom_can);
bbx_panel_kill(tab->pan);
for (i = 0; i < tab->Ntabs; i++)
free(tab->tabnames[i]);
free(tab->tabnames);
free(tab->ptr);
free(tab->layout);
free(tab);
}
}
int bbx_tab_addtab(BBX_Panel *pan, char *name, void(*layout)(void *ptr, int width, int height, int miny), void *ptr)
{
BBX_TAB *tab = bbx_panel_getptr(pan);
tab->tabnames = bbx_realloc(tab->tabnames, (tab->Ntabs + 1) * sizeof(char *));
tab->tabnames[tab->Ntabs] = bbx_strdup(name);
tab->layout = bbx_realloc(tab->layout, (tab->Ntabs + 1) * sizeof(void(*)(void *, int, int, int)));
tab->layout[tab->Ntabs] = layout;
tab->ptr = bbx_realloc(tab->ptr, (tab->Ntabs + 1) * sizeof(void *));
tab->ptr[tab->Ntabs] = ptr;
tab->Ntabs++;
tab->current = 0;
}
int bbx_tab_showtab(BBX_Panel *pan, char *name)
{
BBX_TAB *tab = bbx_panel_getptr(pan);
int i;
int cwidth, cheight;
for (i = 0; i < tab->Ntabs; i++)
if (!strcmp(tab->tabnames[i], name))
tab->current = i;
if (!tab->tabpane_can)
return;
bbx_tab_drawtabpane(tab);
for (i = 0; i < tab->Nchildren; i++)
{
bbx_getsize(tab->bbx, tab->objects[i], &cwidth, &cheight);
bbx_setpos(tab->bbx, tab->objects[i], tab->width + 1, 0, cwidth, cheight);
}
if (tab->layout[tab->current])
(*tab->layout[tab->current])(tab->ptr[tab->current], tab->width, tab->height, 25);
}
void bbx_tab_register(BBX_Panel *pan, void *obj)
{
BBX_TAB *tab = bbx_panel_getptr(pan);
tab->objects = bbx_realloc(tab->objects, (tab->Nchildren + 1) * sizeof(void *));
tab->objects[tab->Nchildren] = obj;
tab->Nchildren++;
}
void bbx_tab_deregister(BBX_Panel *pan, void *obj)
{
BBX_TAB *tab = bbx_panel_getptr(pan);
int i;
for (i = 0; i < tab->Nchildren; i++)
if (tab->objects[i] == obj)
break;
if (i < tab->Nchildren)
{
memmove(&tab->objects[i], &tab->objects[i + 1], (tab->Nchildren - i - 1) * sizeof(void *));
tab->Nchildren--;
}
}
static void bbx_tab_layout(void *ptr, int width, int height)
{
BBX_TAB *tab = ptr;
int cwidth, cheight;
int i;
bbx_canvas_kill(tab->tabpane_can);
bbx_canvas_kill(tab->left_can);
bbx_canvas_kill(tab->right_can);
bbx_canvas_kill(tab->bottom_can);
tab->width = width;
tab->height = height;
tab->tabpane_can = bbx_canvas(tab->bbx, tab->pan, width, 25, bbx_color("grey"));
bbx_canvas_setmousefunc(tab->tabpane_can, bbx_tab_mouse, tab);
bbx_setpos(tab->bbx, tab->tabpane_can, 0, 0, width, 25);
bbx_tab_drawtabpane(tab);
tab->left_can = bbx_canvas(tab->bbx, tab->pan, 2, height - 25-2, bbx_color("light grey"));
tab->right_can = bbx_canvas(tab->bbx, tab->pan, 2, height - 25-2, bbx_color("dark grey"));
tab->bottom_can = bbx_canvas(tab->bbx, tab->pan, width, 2, bbx_color("dark grey"));
bbx_setpos(tab->bbx, tab->left_can, 0, 25, 2, height - 25 - 2);
bbx_setpos(tab->bbx, tab->right_can, width - 2, 25, 2, height - 25 - 2);
bbx_setpos(tab->bbx, tab->bottom_can, 0, height - 2, width, 2);
for (i = 0; i < tab->Nchildren; i++)
{
bbx_getsize(tab->bbx, tab->objects[i], &cwidth, &cheight);
bbx_setpos(tab->bbx, tab->objects[i], width + 1, 0, cwidth, cheight);
}
if (tab->current >= 0 && tab->current < tab->Ntabs)
{
if (tab->layout[tab->current])
(*tab->layout[tab->current])(tab->ptr[tab->current], width, height, 25);
}
}
static void bbx_tab_drawtabpane(BBX_TAB *tab)
{
unsigned char *rgba;
int width, height;
int i;
int x;
int lenx;
if (!tab->tabpane_can)
return;
rgba = bbx_canvas_rgba(tab->tabpane_can, &width, &height);
bbx_rectangle(rgba, width, height, 0, 0, width, height, bbx_color("grey"));
if (tab->current == 0)
{
bbx_line(rgba, width, height, 0, 0, 0, height - 1, bbx_color("light grey"));
bbx_line(rgba, width, height, 1, 0, 1, height - 1, bbx_color("light grey"));
}
else
{
bbx_line(rgba, width, height, 0, 2, 0, height - 1, bbx_color("light grey"));
bbx_line(rgba, width, height, 1, 2, 1, height - 1, bbx_color("light grey"));
}
x = 5;
for (i = 0; i < tab->Ntabs; i++)
{
bbx_drawutf8(rgba, width, height, x, 18, tab->tabnames[i], bbx_utf8_Nchars(tab->tabnames[i]), tab->bbx->gui_font,
bbx_color("black"));
lenx = bbx_utf8width(tab->bbx->gui_font, tab->tabnames[i], bbx_utf8_Nchars(tab->tabnames[i]));
if (tab->current != i)
{
bbx_line(rgba, width, height, x + lenx + 5, 7, x + lenx + 5, height - 1, bbx_color("light grey"));
bbx_line(rgba, width, height, x + lenx + 5 + 1, 7, x + lenx + 5 + 1, height - 1, bbx_color("dark grey"));
bbx_line(rgba, width, height, x-5, 2, x + lenx, 2, bbx_color("light grey"));
bbx_line(rgba, width, height, x-5, 3, x + lenx, 3, bbx_color("light grey"));
drawarc(rgba, width, height, x + lenx, 7, 5, -PI / 2, 0, bbx_color("light grey"));
bbx_line(rgba, width, height, x-5, height - 2, x + lenx, height - 2, bbx_color("light grey"));
bbx_line(rgba, width, height, x-5, height - 1, x + lenx, height - 1, bbx_color("light grey"));
}
else
{
bbx_line(rgba, width, height, x + lenx + 5, 5, x + lenx +5, height - 1, bbx_color("dark grey"));
bbx_line(rgba, width, height, x + lenx + 5 + 1, 5, x + lenx + 5 + 1, height - 1, bbx_color("dark grey"));
drawarc(rgba, width, height, x + lenx, 5, 5, -PI / 2, 0, bbx_color("light grey"));
bbx_line(rgba, width, height, x-5, 0, x + lenx, 0, bbx_color("light grey"));
bbx_line(rgba, width, height, x-5, 1, x + lenx, 1, bbx_color("light grey"));
}
x += lenx;
x += 10;
}
bbx_line(rgba, width, height, x-10, height - 2, width, height - 2, bbx_color("light grey"));
bbx_line(rgba, width, height, x-10, height - 1, width, height - 1, bbx_color("light grey"));
bbx_canvas_flush(tab->tabpane_can);
}
static void bbx_tab_mouse(void *ptr, int action, int x, int y, int buttons)
{
BBX_TAB *tab = ptr;
int i;
int sx, ex;
if (action == BBX_MOUSE_CLICK && (buttons & BBX_MOUSE_BUTTON1))
{
sx = 5;
for (i = 0; i < tab->Ntabs; i++)
{
ex = sx + bbx_utf8width(tab->bbx->gui_font, tab->tabnames[i], bbx_utf8_Nchars(tab->tabnames[i]));
if (x >= sx && x < ex)
{
bbx_tab_showtab(tab->pan, tab->tabnames[i]);
break;
}
sx = ex + 10;
}
}
}
static double clamprange(double theta);
static int between(double thetaa, double thetab, double theta);
static void drawarc(unsigned char *rgba, int width, int height, int x0, int y0, int radius, double from, double to, BBX_RGBA col)
{
int x = 0;
int y = radius;
int delta = 2 - 2 * radius;
int error = 0;
double thetaa, thetab;
double theta;
unsigned char red, green, blue;
red = bbx_red(col);
green = bbx_green(col);
blue = bbx_blue(col);
thetaa = clamprange(from);
thetab = clamprange(to);
while (y >= 0) {
//SetPixel(hdc,x0 + x, y0 + y,pencol);
theta = atan2(-y, x);
if (between(thetaa, thetab, theta))
{
if (y0 - y >= 0 && y0 - y < height && x0 + x >= 0 && x0 + x < width)
{
rgba[((y0 - y)*width + x0 + x) * 4] = red;
rgba[((y0 - y)*width + x0 + x) * 4 + 1] = green;
rgba[((y0 - y)*width + x0 + x) * 4 + 2] = blue;
}
}
theta = atan2(-y, -x);
if (between(thetaa, thetab, theta))
{
if (y0 - y >= 0 && y0 - y < height && x0 - x >= 0 && x0 - x < width)
{
rgba[((y0 - y)*width + x0 - x) * 4] = red;
rgba[((y0 - y)*width + x0 - x) * 4 + 1] = green;
rgba[((y0 - y)*width + x0 - x) * 4 + 2] = blue;
}
}
theta = atan2(y, x);
if (between(thetaa, thetab, theta))
{
if (y0 + y >= 0 && y0 + y < height && x0 + x >= 0 && x0 + x < width)
{
rgba[((y0 + y)*width + x0 + x) * 4] = red;
rgba[((y0 + y)*width + x0 + x) * 4 + 1] = green;
rgba[((y0 + y)*width + x0 + x) * 4 + 2] = blue;
}
}
theta = atan2(y, -x);
if (between(thetaa, thetab, theta))
{
if (y0 + y >= 0 && y0 + y < height && x0 - x >= 0 && x0 - x < width)
{
rgba[((y0 + y)*width + x0 - x) * 4] = red;
rgba[((y0 + y)*width + x0 - x) * 4 + 1] = green;
rgba[((y0 + y)*width + x0 - x) * 4 + 2] = blue;
}
}
error = 2 * (delta + y) - 1;
if (delta < 0 && error <= 0) {
++x;
delta += 2 * x + 1;
continue;
}
error = 2 * (delta - x) - 1;
if (delta > 0 && error > 0) {
--y;
delta += 1 - 2 * y;
continue;
}
++x;
delta += 2 * (x - y);
--y;
}
}
static double clamprange(double theta)
{
while (theta > PI)
theta -= 2 * PI;
while (theta < -PI)
theta += 2 * PI;
return theta;
}
static int between(double thetaa, double thetab, double theta)
{
if (thetaa < thetab && theta > thetaa && theta < thetab)
return 1;
if (thetaa > thetab && (theta > thetaa || theta < thetab) )
return 1;
return 0;
}
|
C++ | UTF-8 | 486 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int bs(int a[],int s,int e,int x)
{
if(s<=e)
{
int mid = s + (e-s)/2;
if(a[mid]==x)
return 1;
if(a[mid]<x)
return(bs(a,mid+1,e,x));
if(a[mid>x])
return(bs(a,s,mid-1,x));
}
return 0;
}
int main()
{
int n,m,i,a[1000001],x,t;
cin>>t;
while(t--)
{
cin>>n>>m;
for(i=0;i<n*m;i++)
{
cin>>a[i];
}
cin>>x;
cout<<bs(a,0,(n*m)-1,x);
cout<<"\n";
}
return 0;
}
|
Markdown | UTF-8 | 5,597 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | ## SnippetPx
### Overview
The SnippetPx module enhances the snippet experience in PowerShell by offering
a new format for Snippets: plain, ordinary ps1 files. These snippets are not
just blocks of script that could be injected into a file. They are also
invocable! This enables better reuse of commonly used pieces of script that
would not otherwise be placed into a PowerShell function, either because the
function support in PowerShell won't allow for it to be invoked properly in
the current scope, or because it isn't big enough to warrant adding another
function to the function pool.
Snippets are automatically discovered based on their inclusion in the following
folders (in the order in which they are listed):
- the current user snippets folder (Documents\WindowsPowerShell\snippets);
- the all users snippets folder (Program Files\WindowsPowerShell\snippets);
- the snippets folder in the SnippetPx module (SnippetPx\snippets);
- the snippets folder in all other modules, in the order in which they are
discovered according to the PSModulePath environment variable;
If multiple snippets with the same name exist in different folders, only the
first snippet with that name will be discovered. To guarantee uniqueness of
snippets across modules, snippets specific to a module should use a snippet name
prefixed with the module name. For example, a snippet to provision AD users in an
ActiveDirectory module could use the filename ActiveDirectory.User.Provision.ps1.
Using spaces in snippet filenames is supported, but discouraged.
Not all snippets are appropriate for use in all situations. When in doubt, consult
the documentation for the snippet to ensure it is appropriate for your use case.
### Minimum requirements
- PowerShell 3.0
### License and Copyright
Copyright 2016 Kirk Munro
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
### Installing the SnippetPx module
You can download and install the latest version of SnippetPx using any
of the following methods:
#### PowerShellGet
If you don't know what PowerShellGet is, it's the way of the future for PowerShell
package management. If you're curious to find out more, you should read this:
<a href="http://blogs.msdn.com/b/mvpawardprogram/archive/2014/10/06/package-management-for-powershell-modules-with-powershellget.aspx" target="_blank">Package Management for PowerShell Modules with PowerShellGet</a>
Note that these commands require that you have the PowerShellGet module installed
on the system where they are invoked.
```powershell
# If you don’t have SnippetPx installed already and you want to install
# it for all all users (recommended, requires elevation)
Install-Module SnippetPx
# If you don't have SnippetPx installed already and you want to install
# it for the current user only
Install-Module SnippetPx -Scope CurrentUser
# If you have SnippetPx installed and you want to update it
Update-Module
```
#### PowerShell 3.0 or Later
To install from PowerShell 3.0 or later, open a native PowerShell console (not ISE,
unless you want it to take longer), and invoke one of the following commands:
```powershell
# If you want to install SnippetPx for all users or update a version already
# installed (recommended, requires elevation for new install for all users)
& ([scriptblock]::Create((iwr -uri http://bit.ly/Install-ModuleFromGitHub).Content)) -ModuleName SnippetPx
# If you want to install SnippetPx for the current user
& ([scriptblock]::Create((iwr -uri http://bit.ly/Install-ModuleFromGitHub).Content)) -ModuleName SnippetPx -Scope CurrentUser
```
### Using the SnippetPx module
To see a list of all snippets that are available in your environment, invoke
the following command:
```powershell
Get-Snippet
```
This will return a list of all snippets that have been discovered on the
local system in the snippets folders that it found. Each snippet object will
include the name of the snippet, the path to the snippet file, a synopsis
identifying what the snippet does, a description that describes the snippet
in a little more detail, and a script block that contains the body of the
snippet.
Once you have identified a snippet that you want to invoke in one of your
scripts, you can invoke that snippet with a command like the following:
```powershell
# Import all ps1 files in the functions folder into the current scope
Invoke-Snippet -Name ScriptFile.Import -Parameters @{
Path = Join-Path -Path $PSModulePath -ChildPath functions
}
```
Some snippets are included with the SnippetsPx module, and others may be
discovered in other modules or in the current user or all user snippets
folders. It is important to note that invoking a snippet alone does not
automatically load the module in which it is contained. The module will
only be auto-loaded if the snippet itself contains a command that would
trigger the auto-loading of the module. This is worth understanding for
modules that include snippets that work with module content other than
discoverable commands.
### Command List
The SnippetPx module currently includes the following commands:
```powershell
Get-Snippet
Invoke-Snippet
``` |
Shell | UTF-8 | 846 | 4.03125 | 4 | [] | no_license | #!/bin/bash
# linux toggle led using sysfs
gpio_dir=/sys/class/gpio
echo "Linux Toggle LED"
# check options
while getopts "u" opt; do
case ${opt} in
u )
if [ $# -ne 2 ]; then
echo "Script need 1 parameter - GPIO Pin Number"
exit
fi
echo "Unexport GPIO Pin $2"
echo $2 > "$gpio_dir/unexport"
exit
;;
\? )
echo "Option -u is unexport GPIO Pin"
exit
;;
esac
done
# check parameter number
if [ $# -ne 1 ]; then
echo "Script need 1 parameter - GPIO Pin Number"
exit
fi
# check if export is done
if [ ! -d "${gpio_dir}/gpio$1" ]; then
echo "Export GPIO Pin $1"
echo $1 > "${gpio_dir}/export"
sleep 0.1
fi
# set direction
echo out > "${gpio_dir}/gpio$1/direction"
# start led toggle
while [ 1 ]
do
echo 1 > "${gpio_dir}/gpio$1/value"
sleep 0.5
echo 0 > "${gpio_dir}/gpio$1/value"
sleep 0.5
done
|
TypeScript | UTF-8 | 1,415 | 2.78125 | 3 | [
"MIT"
] | permissive | import Direction from "./direction"
import {Phone} from "./phone"
import {Mail} from "./mail"
// type Sexo="hombre"|"mujer"
export class Person{
protected nombre:string;
protected apellidos:string;
protected edad:number;
protected dni:number;
protected cumpleaños:string;
protected colorFavorito?:string;
protected sexo: string;
protected direcciones:Direction[];
protected mails:Mail[];
protected telefonos:Phone[];
protected notas?:string[];
//public o private??
//herencia
constructor(nombre:string, apellidos:string,edad:number, dni:number, cumpleaños:string,colorFavorito:string,sexo:string, direcciones:Direction[], mails:Mail[], telefonos:Phone[], notas:string[] ){
this.nombre=nombre;
this.apellidos=apellidos;
this.edad=edad;
this.dni=dni;
this.cumpleaños=cumpleaños;
this.colorFavorito=colorFavorito;
this.sexo=sexo;
this.direcciones=direcciones;
this.mails=mails;
this.telefonos=telefonos;
this.notas=notas
}
getDni():number{
return this.dni
}
setDni(dni:number){
this.dni=dni
}
setDirection(direcciones:Direction[]){
this.direcciones= direcciones;
}
setMail(mails:Mail[]){
this.mails=mails;
}
setPhone(telefonos:Phone[]){
this.telefonos=telefonos;
}
} |
C++ | UTF-8 | 3,034 | 2.875 | 3 | [] | no_license | /*
ACMICPC
문제 번호 : 17406
문제 제목 : 배열 돌리기 4
풀이 날짜 : 2020-08-12
Solved By Reamer
*/
#include <iostream>
#include <tuple>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int arr[51][51] = {0};
int tmpArr[51][51] = {0};
vector<tuple<int, int, int>> tupleV;
vector<int> perVec;
int N, M, K;
int r, c, s;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int startX, startY;
int destX, destY;
int tmpX, tmpY;
cin >> N >> M >> K;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < K; i++)
{
cin >> r >> c >> s;
tupleV.push_back(make_tuple(r, c, s));
perVec.push_back(i);
}
int minRow = 500000;
do
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
tmpArr[i][j] = arr[i][j];
}
}
for (int i = 0; i < perVec.size(); i++)
{
//회전
int x, y, z;
tie(x, y, z) = tupleV[perVec[i]];
startX = x - z;
startY = y - z;
destX = x + z;
destY = y + z;
while (startX < destX && startY < destY)
{
int way = 0;
tmpX = startX;
tmpY = startY;
int tmp = tmpArr[startX][startY];
while (true)
{
int newX = tmpX + dx[way];
int newY = tmpY + dy[way];
if (newX == startX && newY == startY)
{
break;
}
if (!(newX >= startX && newX <= destX && newY >= startY && newY <= destY))
{
way++;
newX = tmpX + dx[way];
newY = tmpY + dy[way];
}
// cout << "newx: " << newX << ", newY: " << newY << endl;
tmpArr[tmpX][tmpY] = tmpArr[newX][newY];
tmpX = newX;
tmpY = newY;
}
if (startY + 1 <= destY)
tmpArr[startX][startY + 1] = tmp;
startX++;
destX--;
startY++;
destY--;
}
}
//row탐색
for (int i = 1; i <= N; i++)
{
int sumRow = 0;
for (int j = 1; j <= M; j++)
{
sumRow += tmpArr[i][j];
}
if (sumRow < minRow)
minRow = sumRow;
}
} while (next_permutation(perVec.begin(), perVec.end()));
cout << minRow << endl;
return 0;
} |
C# | UTF-8 | 913 | 2.953125 | 3 | [] | no_license | /*
* Christian Wright
* 30JUL2021
* APA
*
* API Application
*
*/
using System;
using System.Collections.Generic;
namespace Wright_Christian_API
{
public class Artist
{
//Properties
public string ArtistID { get; }
public string ArtistName { get; }
public Artist(string artID, string artistName)
{
ArtistID = artID;
ArtistName = artistName;
}
public static bool VerifyArtistSelection(string userInput, Dictionary<string, string> artistInfomation)
{
bool artistConfirmation = false;
foreach(KeyValuePair<string, string> item in artistInfomation)
{
if(userInput == item.Key)
{
artistConfirmation = true;
break;
}
}
return artistConfirmation;
}
}
}
|
C | UTF-8 | 1,572 | 4 | 4 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include "functions.h"
void left(int a[], int N) {
int temp = a[0];
for (int i = 0; i < N - 1; i++) {
a[i] = a[i + 1];
}
a[N - 1] = temp;
}
void right(int a[], int N) {
N = N - 1;
int temp = a[N - 1];
for (int i = N - 1; i > 0; i--) {
a[i] = a[i - 1];
}
a[0] = temp;
}
void random_array(int *array) {
int num;
int flag;
for (int i = 0; i < N;) {
num = rand() % 10;
flag = 0;
for (int j = 0; j < N; j++) {
if (num == array[j]) {
flag = 1;
}
}
if (flag == 0) {
array[i] = num;
i++;
}
}
}
int get_min_value(const int *array, int min) {
min = array[0];
for (int i = 0; i < N; i++) {
if (array[i] < min){
min = array[i];
}
}
return min;
}
int get_max_value(const int *array, int max) {
max = array[0];
for (int i = 0; i < N; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
void print_array(int *array) {
for (int i = 0; i < N; i++) {
printf("%2d", array[i]);
}
}
void left_shift(int *array, int min) {
int flag = 0;
while (flag == 0) {
left(&array[0], N);
if (array[0] == min) {
flag = 1;
}
}
}
void right_shift(int *array, int max) {
int flag = 0;
while (flag == 0) {
right(&array[1], N);
if (array[N - 1] == max) {
flag = 1;
}
}
} |
Java | UTF-8 | 3,302 | 2.9375 | 3 | [] | no_license | package com.computinglife.slpa.core;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;
import org.jgrapht.graph.DefaultWeightedEdge;
import com.computinglife.slpa.entity.IntegerNode;
import com.computinglife.slpa.entity.IntegerNodeGraph;
import com.computinglife.slpa.util.GraphReader;
public class CommunityFinder {
public IntegerNodeGraph inGraph;
public CommunityFinder() {
inGraph = new IntegerNodeGraph();
}
public void updateLabels(IntegerNode currentNode) {
Set<DefaultWeightedEdge> incomingEdges = inGraph.graph.incomingEdgesOf(currentNode.id);
// 存放邻居节点发过来的label
HashMap<Integer, Integer> incomingVotes = new HashMap<Integer, Integer>();
// 当前节点的每一条入边
for (DefaultWeightedEdge edge : incomingEdges) {
// speaker
int speakerId = inGraph.graph.getEdgeSource(edge);
IntegerNode speakerNode = inGraph.nodeMap.get(speakerId);
int votedCommunity = speakerNode.speakerVote();
int votedCommunitycount = 1;
if (incomingVotes.containsKey(votedCommunity))
votedCommunitycount += incomingVotes.get(votedCommunity);
incomingVotes.put(votedCommunity, votedCommunitycount);
}
// listener rules(找出发过来出现次数最多的lable)
Iterator<Entry<Integer, Integer>> it = incomingVotes.entrySet().iterator();
int popularCommunity = -1;
int popularCommunityCount = 0;
while (it.hasNext()) {
Entry<Integer, Integer> entry = it.next();
if (entry.getValue() > popularCommunityCount) {
popularCommunity = entry.getKey();
popularCommunityCount = entry.getValue();
}
}
// 给该点的,选定label出现次数增加一
currentNode.updateCommunityDistribution(popularCommunity, 1);
}
// 迭代次数一般可以指定为100
public void SLPA(int iterations) {
for (int i = 0; i < iterations; i++) {
// For every node in the graph
for (IntegerNode node : inGraph.nodeMap) {
updateLabels(node);
}
}
}
public void initIntegerNodeGraph(String fileName) {
File f = new File(fileName);
try {
inGraph.graph = GraphReader.readGraph(f);
int nodeCount = inGraph.graph.vertexSet().size();
for (int nodeId = 0; nodeId < nodeCount; nodeId++) {
IntegerNode node = new IntegerNode(nodeId, nodeId);
node.updateCommunityDistribution(nodeId, 1);
inGraph.nodeMap.add(node);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String arg[]) {
String fileName = arg[0];
int iterations = Integer.parseInt(arg[1]);
File f = new File(fileName);
if (!f.exists()) {
System.out.println(f.getAbsolutePath() + " is not a valid file");
System.exit(1);
}
CommunityFinder cf = new CommunityFinder();
System.out.println("Reading graph input file: " + f.getAbsolutePath() + " ..");
cf.initIntegerNodeGraph(fileName);
System.out.println("Successfully initialized IntegerNodeGraph with " + cf.inGraph.getVertexCount()
+ " vertices and " + cf.inGraph.getEdgeCount() + " edges ..");
System.out.println("Invoking SLPA with " + iterations + " iterations ..");
cf.SLPA(iterations);
System.out.println("Completed SLPA");
}
}
|
Python | UTF-8 | 867 | 3.1875 | 3 | [] | no_license | #
# @lc app=leetcode id=38 lang=python3
#
# [38] Count and Say
#
# @lc code=start
class Solution:
def countAndSay(self, n: int) -> str:
countAndSayString = '1'
for i in range(1, n):
countList = []
for j in countAndSayString:
if(len(countList) == 0):
countList.append([j, 1])
continue
if(j == countList[-1][0]):
countList[-1][1] += 1
continue
if(j != countList[-1][0]):
countList.append([j, 1])
continue
countAndSayString = ''
for j in countList:
countAndSayString += str(j[1])
countAndSayString += j[0]
print(countAndSayString)
return countAndSayString
# @lc code=end
|
JavaScript | UTF-8 | 1,236 | 3.171875 | 3 | [] | no_license | var weapons = ['AK-47', 'bombs', 'machine-gun', 'laser-gun'];
var soldier = {
name: "Mark",
age: 23,
weight: 70,
weapon: weapons[3],
sayHi: function(name) {
console.log("Hello " + name);
}
};
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// var age = prompt("How old are you?");
//
// if (age < 18) {
// console.log("gtfo");
// } else if (age < 50) {
// console.log("you're a father");
// } else if (age < 80) {
// console.log("hello grandpa");
// } else {
// console.log("u r dead 2 me");
// }
// jquery
// $(document).ready(function() {
// console.log("i'm loaded");
// })
// $(document).ready(function() {
// var $heart = $(".heart");
// $heart.click(function() {
// console.log("I got clicked");
// });
// });
// $(document).ready(function() {
// var $heart = $(".heart");
// $heart.click(function() {
// if ($(this).hasClass("heart-pumping")) {
// $(this).removeClass("heart-pumping");
// } else {
// $(this).addClass("heart-pumping");
// }
// });
// });
$(document).ready(function() {
var $heart = $(".heart");
$heart.click(function() {
$(this).toggleClass("fa-heart-o heart-pumping fa-heart");
});
});
|
Ruby | UTF-8 | 917 | 2.890625 | 3 | [
"MIT"
] | permissive | class ClusterTools::WorkerPool
def initialize(expiration=180)
@expiration = expiration
@tasks = {} # :task => [host1, host2 ...]
@workers = {} # "host" => timestamp
end
def add(host, tasks)
tasks.each do |act|
add_or_update_task(host, act)
@workers[host] = Time.new
end
end
def pop(task)
loop do
wrk_ts = pull_worker(task)
return if !wrk_ts
return wrk_ts.first if !expired?(wrk_ts.last)
end
end
private
def add_or_update_task(host, act)
wrk_q = @tasks[act]
if wrk_q
idx = wrk_q.index(host)
wrk = wrk_q.delete_at(idx) if idx
wrk_q << host
else
@tasks[act] = [host]
end
end
def pull_worker(task)
wrk_q = @tasks[task]
return if !wrk_q
wrk = wrk_q.pop
ts = @workers.delete(wrk)
return [wrk, ts] if wrk && ts
end
def expired?(ts)
ts + @expiration < Time.new
end
end
|
Ruby | UTF-8 | 1,082 | 2.796875 | 3 | [] | no_license | require 'mars_one/errors'
module MarsOne
module MissionParser
class IOMissionReader
attr_accessor :io
def initialize(io)
self.io = io
end
def read_field
match_data = io.readline.match(/^(\d+)\s(\d+)$/)
raise MarsOne::InputFormatError.new('Can\'t parse field line') unless match_data
[match_data[1], match_data[2]].map(&:to_i)
end
def each_rover
return enum_for(:each_rover) unless block_given?
until io.eof?
rover_match_data = io.readline.match(/^(\-?\d+)\s(\-?\d+)\s(N|W|E|S)$/)
commands_match_data = io.readline.match(/^([A-Z]+)$/)
raise MarsOne::InputFormatError.new('Can\'t parse rover line') unless rover_match_data
raise MarsOne::InputFormatError.new('Can\'t parse rover\'s commands') unless commands_match_data
rover = [
rover_match_data[1].to_i,
rover_match_data[2].to_i,
rover_match_data[3]
]
yield rover, commands_match_data[1]
end
end
end
end
end
|
Python | UTF-8 | 645 | 2.75 | 3 | [] | no_license | #!/usr/local/bin/python3
import sys
# Check for one input argument
if len(sys.argv) != 2:
print('Usage: reindex [name of index file to reindex]')
sys.exit()
filename = str(sys.argv[1])
outfile = filename + '.reindex'
runningTotal = 0
with open(filename,'r') as ifp, open(outfile,'w') as ofp:
for line in ifp:
tokens = line.split() # break apart line by unspecified whitespaces
currentPackage= tokens[1]
lastIndex=runningTotal
runningTotal+=int(tokens[0])
# save output at end of output file
ofp.write(str(currentPackage)+','+str(lastIndex+1)+','+str(runningTotal)+'\n')
|
C++ | UTF-8 | 441 | 2.65625 | 3 | [
"MIT"
] | permissive | /*
Library for managing a sliding potentiometer
*/
#ifndef Slider_h
#define Slider_h
#include "Arduino.h"
class Slider {
public:
byte nLights;
Slider(int sliderPin, int minChangeForUpdate);
void Init();
void UpdateState();
bool GetSliderUpdate(int *newValue);
int GetValue();
void ForceUpdate();
private:
int sliderPin;
int currentValue;
int lastUpdateValue;
int minChangeForUpdate;
bool updateAvailable;
};
#endif |
SQL | UTF-8 | 4,630 | 3.34375 | 3 | [] | no_license | CREATE OR REPLACE PROCEDURE sa."CTIAWF_MONTHLY_BONUS_PRC" (
ip_run_date IN DATE,
ip_enroll_promo_code IN VARCHAR2,
ip_pend_promo_code IN VARCHAR2
)
AS
/********************************************************************************/
/* Copyright 2004 Tracfone Wireless Inc. All rights reserved */
/* */
/* NAME: CTIAWF_MONTHLY_BONUS_PRC */
/* PURPOSE: To issue monthly bonus units for CTIAWF customers */
/* FREQUENCY: */
/* PLATFORMS: Oracle 8.0.6 AND newer versions. */
/* */
/* REVISIONS: */
/* VERSION DATE WHO PURPOSE */
/* ------- ---------- ----- --------------------------------------------- */
/* 1.0 03/31/04 VAdapa Initial Revision */
/* 1.1 08/16/04 VAdapa CR3132 - Fix for MT#52765 */
/********************************************************************************/
CURSOR c_ctiawf_qual_recs
IS
SELECT sp.objid,
sp.x_service_id
FROM table_site_part sp, table_x_call_trans ct, table_x_promo_hist ph,
table_x_promotion pr
WHERE pr.objid = ph.promo_hist2x_promotion
AND ph.promo_hist2x_call_trans = ct.objid
-- AND ct.call_trans2site_part = sp.objid --CR3132
AND ct.x_service_id = sp.x_service_id --CR3132
AND sp.part_status = 'Active'
AND TRUNC (sp.install_date) < TRUNC (ip_run_date)
AND NVL (TO_CHAR (sp.cmmtmnt_end_dt, 'MON'), 'ZZZ') <> TO_CHAR (ip_run_date,
'MON')
AND pr.x_promo_code = ip_enroll_promo_code;
CURSOR c_promo_info
IS
SELECT objid,
x_revenue_type
FROM table_x_promotion
WHERE x_promo_code = ip_pend_promo_code
AND SYSDATE BETWEEN x_start_date
AND x_end_date;
r_promo_info c_promo_info%ROWTYPE;
l_recs_processed NUMBER := 0;
l_serial_num table_part_inst.part_serial_no%TYPE;
l_procedure_name VARCHAR2 (80) := 'CTIAWF_MONTHLY_BONUS_PRC';
l_action VARCHAR2 (50) := ' ';
l_err_text VARCHAR2 (4000);
l_start_date DATE := SYSDATE;
no_promo_exp EXCEPTION
;
BEGIN
l_action := 'Promo Existence Check';
OPEN c_promo_info;
FETCH c_promo_info
INTO r_promo_info;
IF c_promo_info%NOTFOUND
THEN
CLOSE c_promo_info;
RAISE no_promo_exp;
ELSE
FOR r_ctiawf_qual_recs IN c_ctiawf_qual_recs
LOOP
BEGIN
l_serial_num := r_ctiawf_qual_recs.x_service_id;
l_action := 'Insert into Table_X_Pending_Redemption';
INSERT
INTO table_x_pending_redemption(
objid,
pend_red2x_promotion,
x_pend_red2site_part,
x_pend_type
)VALUES(
seq ('x_pending_redemption'),
r_promo_info.objid,
r_ctiawf_qual_recs.objid,
r_promo_info.x_revenue_type
);
IF SQL%ROWCOUNT = 1
THEN
l_action := 'Update Table_Site_Part';
UPDATE table_site_part SET cmmtmnt_end_dt = ip_run_date
WHERE objid = r_ctiawf_qual_recs.objid;
COMMIT;
l_recs_processed := l_recs_processed + 1;
END IF;
EXCEPTION
WHEN OTHERS
THEN
l_err_text := SQLERRM;
toss_util_pkg.insert_error_tab_proc (
'Inner Block Error - When others', l_serial_num,
l_procedure_name );
END;
END LOOP;
COMMIT;
END IF;
CLOSE c_promo_info;
IF toss_util_pkg.insert_interface_jobs_fun ( l_procedure_name, l_start_date,
SYSDATE, l_recs_processed, 'SUCCESS', l_procedure_name )
THEN
COMMIT;
END IF;
EXCEPTION
WHEN no_promo_exp
THEN
toss_util_pkg.insert_error_tab_proc ( l_action, ip_pend_promo_code,
l_procedure_name, 'Promo Does Not Exist' );
WHEN OTHERS
THEN
l_err_text := SQLERRM;
toss_util_pkg.insert_error_tab_proc ( l_action, l_serial_num,
l_procedure_name );
IF toss_util_pkg.insert_interface_jobs_fun ( l_procedure_name,
l_start_date, SYSDATE, l_recs_processed, 'FAILED', l_procedure_name )
THEN
COMMIT;
END IF;
END ctiawf_monthly_bonus_prc;
/ |
Python | UTF-8 | 6,897 | 3.46875 | 3 | [] | no_license | import numpy as np
from tronproblem import *
from trontypes import CellType, PowerupType
import random, math
from queue import Queue, LifoQueue, PriorityQueue
def get_safe_actions(board, loc, has_armor):
"""
USING FOR VORONOI ONLY
FROM TRONPROBLEM, BUT TAKES INTO ACCOUNT ARMOR
Given a game board and a location on that board,
returns the set of actions that don't result in immediate collisions.
Input:
board- a list of lists of characters representing cells
loc- location (<row>, <column>) to find safe actions from
Output:
returns the set of actions that don't result in immediate collisions.
An immediate collision occurs when you run into a barrier, wall, or
the other player
"""
safe = set()
for action in {U, D, L, R}:
r1, c1 = TronProblem.move(loc, action)
if not (
board[r1][c1] == CellType.WALL
or TronProblem.is_cell_player(board, (r1, c1))
or (board[r1][c1] == CellType.BARRIER) and not(has_armor)
):
safe.add(action)
return safe
def alpha_beta_cutoff(sb, asp, tron_state, cutoff_ply, eval_func):
"""
This function should:
- search through the asp using alpha-beta pruning
- cut off the search after cutoff_ply moves have been made.
Inputs:
asp - an AdversarialSearchProblem
cutoff_ply- an Integer that determines when to cutoff the search
and use eval_func.
For example, when cutoff_ply = 1, use eval_func to evaluate
states that result from your first move. When cutoff_ply = 2, use
eval_func to evaluate states that result from your opponent's
first move. When cutoff_ply = 3 use eval_func to evaluate the
states that result from your second move.
You may assume that cutoff_ply > 0.
eval_func - a function that takes in a GameState and outputs
a real number indicating how good that state is for the
player who is using alpha_beta_cutoff to choose their action.
The eval_func we provide does not handle terminal states, so evaluate terminal states the
same way you evaluated them in the previous algorithms.
Output: an action(an element of asp.get_available_actions(asp.get_start_state()))
"""
best_move = max_move_ab_cutoff(sb, asp, tron_state, None,
float("-inf"), float("inf"), cutoff_ply, eval_func)
#print("********BEST MOVE", best_move, "\n")
return best_move[0]
def min_move_ab_cutoff(sb, asp, curr_state, move_to_here, alpha, beta, cutoff_ply, eval_func):
#assert curr_state.ptm == 1 #will be true
#print("min level", cutoff_ply, " move to here", move_to_here)
#print(TronProblem.visualize_state(curr_state, False))
if asp.is_terminal_state(curr_state):
#print(" terminal state\n")
return (move_to_here, (cutoff_ply+1)*eval_func(sb, asp, curr_state))
elif cutoff_ply == 0:
#print(" reached cutoff\n")
return (move_to_here, eval_func(sb, asp, curr_state))
else:
best_action = None
loc = curr_state.player_locs[1]
actions = get_safe_actions(curr_state.board, loc, curr_state.player_has_armor(1))
#print (" actions are ", actions)
if len(actions) == 0:
#print("min level", cutoff_ply, "NO MORE SAFE ACTIONS for player ", curr_state.ptm)
#print("move to here", move_to_here)
best_action = (move_to_here, cutoff_ply*eval_func(sb, asp, curr_state))
#print("returning ", best_action)
return best_action
for action in actions:
next_state = asp.transition(curr_state, action)
if curr_state.get_remaining_turns_speed(curr_state.ptm) > 0:
#print("player 2 (op) on speed, turns ", curr_state.get_remaining_turns_speed(curr_state.ptm))
result = min_move_ab_cutoff(sb, asp, next_state, action, alpha, beta, cutoff_ply-1, eval_func)
else:
result = max_move_ab_cutoff(sb, asp, next_state, action, alpha, beta, cutoff_ply-1, eval_func)
#print("min, result is", result)
if not(result == None):
if best_action == None:
best_action = (action, result[1]) #CHANGE HERE?
elif (result[1] < best_action[1]):
best_action = (action, result[1])
#PRUNING
if (best_action[1] <= alpha):
return best_action
if (best_action[1] < beta):
beta = best_action[1]
return best_action
def max_move_ab_cutoff(sb, asp, curr_state, move_to_here, alpha, beta, cutoff_ply, eval_func):
#print("\nmax level", cutoff_ply, " move to here", move_to_here)
#print(TronProblem.visualize_state(curr_state, False))
if asp.is_terminal_state(curr_state):
#print(" terminal state\n")
return (move_to_here, (cutoff_ply+1)*eval_func(sb, asp, curr_state))
elif cutoff_ply == 0:
#print(" reached cutoff\n")
return (move_to_here, eval_func(sb, asp, curr_state))
else:
best_action = None
loc = curr_state.player_locs[0]
actions = get_safe_actions(curr_state.board, loc, curr_state.player_has_armor(0))
#print (" actions are ", actions)
if len(actions) == 0:
#print("max level", cutoff_ply, "NO MORE SAFE ACTIONS for player ", curr_state.ptm)
best_action = (move_to_here, cutoff_ply*eval_func(sb, asp, curr_state)) #CHANGE THIS
#print("returning ", best_action)
return best_action
for action in actions: #looking at the next level
#print("action", action)
next_state = asp.transition(curr_state, action)
if curr_state.get_remaining_turns_speed(curr_state.ptm) > 0: #correct!?
#print("player 1 (op) on speed, turns ", curr_state.get_remaining_turns_speed(curr_state.ptm))
result = max_move_ab_cutoff(sb, asp, next_state, action, alpha, beta, cutoff_ply-1, eval_func)
else:
result = min_move_ab_cutoff(sb, asp, next_state, action, alpha, beta, cutoff_ply-1, eval_func)
#print("max, level", cutoff_ply, "result is", result)
if not(result == None):
if best_action == None:
best_action = (action, result[1]) #CRUCIAL CHANGE
elif (result[1] > best_action[1]): #the 1 index of tuple is the val
best_action = (action, result[1])
#PRUNING
if (best_action[1] >= beta):
return best_action
if (best_action[1] > alpha):
alpha = best_action[1]
return best_action
|
Python | UTF-8 | 33,340 | 2.796875 | 3 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import csv
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import random
random.seed(12796)
####################################################################################
################################### LOAD DATA ######################################
####################################################################################
sent1_train = []
sent2_train = []
labels_train = []
with open('hw2_data/snli_train.tsv') as train:
snli_train = csv.reader(train, delimiter = '\t')
for s1, s2, label in snli_train:
sent1_train.append(s1.split())
sent2_train.append(s2.split())
if label == 'contradiction':
labels_train.append(0)
if label == 'neutral':
labels_train.append(1)
if label == 'entailment':
labels_train.append(2)
sent1_train.pop(0)
sent2_train.pop(0)
sent1_val = []
sent2_val = []
labels_val = []
with open('hw2_data/snli_val.tsv') as val:
snli_val = csv.reader(val, delimiter = '\t')
for s1, s2, label in snli_val:
sent1_val.append(s1.split())
sent2_val.append(s2.split())
if label == 'contradiction':
labels_val.append(0)
if label == 'neutral':
labels_val.append(1)
if label == 'entailment':
labels_val.append(2)
sent1_val.pop(0)
sent2_val.pop(0)
####################################################################################
########################### LOAD FASTTEXT WORD VECTORS #############################
####################################################################################
FastText = []
with open('wiki-news-300d-1M.vec', "r") as ft:
for i, line in enumerate(ft):
if i == 0:
continue
FastText.append(line)
if i == 50000:
break
####################################################################################
############################### EMBEDDING FUNCTION ################################
####################################################################################
def build_embedding(data):
word2id = {"<pad>": 0, "<unk>": 1}
id2word = {0: "<pad>", 1: "<unk>"}
embeddings = [
np.zeros(300),
np.random.normal(0, 0.01, 300),
]
for i, line in enumerate(data, start=2):
parsed = line.split()
word = parsed[0]
array = np.array([float(x) for x in parsed[1:]])
word2id[word] = i
id2word[i] = word
embeddings.append(array)
return word2id, id2word, embeddings
word2id, id2word, embeddings = build_embedding(FastText)
MAX_SENT_LENGTH = max(max([len(sent) for sent in sent1_train]), max([len(sent) for sent in sent2_train]))
BATCH_SIZE = 32
PAD_IDX = 0
UNK_IDX = 1
####################################################################################
################################ PYTORCH DATALOADER ################################
####################################################################################
class VocabDataset(Dataset):
"""
Class that represents a train/validation/test dataset that's readable for PyTorch
Note that this class inherits torch.utils.data.Dataset
"""
def __init__(self, sent1_ls, sent2_ls, labels_ls, word2id):
"""
@param data_list: list of character
@param target_list: list of targets
"""
self.sent1_ls = sent1_ls
self.sent2_ls = sent2_ls
self.labels_ls = labels_ls
assert len(sent1_ls) == len(sent2_ls)
assert len(sent1_ls) == len(labels_ls)
self.word2id = word2id
def __len__(self):
return len(self.sent1_ls)
def __getitem__(self, key):
"""
Triggered when you call dataset[i]
"""
word_idx_1 = [
self.word2id[word] if word in self.word2id.keys() else UNK_IDX
for word in self.sent1_ls[key][:MAX_SENT_LENGTH]
]
word_idx_2 = [
self.word2id[word] if word in self.word2id.keys() else UNK_IDX
for word in self.sent2_ls[key][:MAX_SENT_LENGTH]
]
label = self.labels_ls[key]
return [word_idx_1, word_idx_2, len(word_idx_1), len(word_idx_2), label]
def vocab_collate_func(batch):
"""
Customized function for DataLoader that dynamically pads the batch so that all
data have the same length
"""
sent1_ls = []
sent2_ls = []
length_sent1_ls = []
length_sent2_ls = []
labels_ls = []
for datum in batch:
labels_ls.append(datum[4])
length_sent1_ls.append(datum[2])
length_sent2_ls.append(datum[3])
for datum in batch:
padded_vec1 = np.pad(np.array(datum[0]),
pad_width=((0,MAX_SENT_LENGTH-datum[2])),
mode="constant", constant_values=0)
sent1_ls.append(padded_vec1)
padded_vec2 = np.pad(np.array(datum[1]),
pad_width=((0,MAX_SENT_LENGTH-datum[3])),
mode="constant", constant_values=0)
sent2_ls.append(padded_vec2)
sent1_ls = np.array(sent1_ls)
sent2_ls = np.array(sent2_ls)
labels_ls = np.array(labels_ls)
return [
torch.from_numpy(np.array(sent1_ls)),
torch.from_numpy(np.array(sent2_ls)),
torch.LongTensor(length_sent1_ls),
torch.LongTensor(length_sent2_ls),
torch.LongTensor(labels_ls),
]
####################################################################################
######################## TRAIN AND VALIDATION DATALOADERS ##########################
####################################################################################
train_dataset = VocabDataset(sent1_train, sent2_train, labels_train, word2id)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
val_dataset = VocabDataset(sent1_val, sent2_val, labels_val, word2id)
val_loader = torch.utils.data.DataLoader(dataset=val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
####################################################################################
#################################### RNN MODEL #####################################
####################################################################################
class RNN(nn.Module):
def __init__(self, emb_size, hidden_size, num_layers, num_classes, vocab_size):
super(RNN, self).__init__()
self.num_layers, self.hidden_size = num_layers, hidden_size
self.embedding = nn.Embedding(vocab_size, emb_size, padding_idx=PAD_IDX)
#Implementing a Bidirectional GRU
self.rnn = nn.GRU(emb_size, hidden_size, num_layers, batch_first=True, bidirectional=True)
#Hidden Size * 4, since we have two sentences per instance and it is bidirectional
self.linear = nn.Linear(4*hidden_size, num_classes)
def init_hidden(self, batch_size):
hidden = torch.randn(self.num_layers*2, batch_size, self.hidden_size) ## time 2
return hidden
def forward(self, x1, x2, lenx1, lenx2):
x1desc_idx = np.argsort(np.array(lenx1))[::-1]
x2desc_idx = np.argsort(np.array(lenx2))[::-1]
sorted_lenx1 = (np.array(lenx1)[x1desc_idx])
sorted_lenx2 = (np.array(lenx2)[x2desc_idx])
x1order = (np.linspace(0, len(lenx1), len(lenx1), endpoint = False)).astype('int')
x2order = (np.linspace(0, len(lenx2), len(lenx2), endpoint = False)).astype('int')
batch_size1, seq_len1 = x1.size()
batch_size2, seq_len2 = x2.size()
self.hidden1 = self.init_hidden(batch_size1)
self.hidden2 = self.init_hidden(batch_size2)
embed1 = self.embedding(x1)
embed2 = self.embedding(x2)
embed1 = torch.nn.utils.rnn.pack_padded_sequence(embed1, sorted_lenx1, batch_first=True)
embed2 = torch.nn.utils.rnn.pack_padded_sequence(embed2, sorted_lenx2, batch_first=True)
x1reorder = (x1order[x1desc_idx])
x2reorder = (x2order[x2desc_idx])
reversed1 = np.argsort(x1reorder)
reversed2 = np.argsort(x2reorder)
rnn_out1, self.hidden1 = self.rnn(embed1, self.hidden1)
rnn_out2, self.hidden2 = self.rnn(embed2, self.hidden2)
rnn_out1, _ = torch.nn.utils.rnn.pad_packed_sequence(rnn_out1, batch_first=True)
rnn_out2, _ = torch.nn.utils.rnn.pad_packed_sequence(rnn_out2, batch_first=True)
rnn_out1 = rnn_out1[reversed1]
rnn_out2 = rnn_out2[reversed2]
rnn_out1 = torch.sum(rnn_out1, dim=1)
rnn_out2 = torch.sum(rnn_out2, dim=1)
full_rnn_out = torch.cat([rnn_out1, rnn_out2], dim=1)
logits = self.linear(full_rnn_out)
#ReLU
logits1 = self.linear(full_rnn_out)
return logits1
####################################################################################
############################### TEST MODEL FUNCTION ################################
####################################################################################
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for x1, x2, lenx1, lenx2, labels in loader:
x1_batch, x2_batch, lenx1_batch, lenx2_batch, label_batch = x1, x2, lenx1, lenx2, labels
outputs = F.softmax(model(x1_batch, x2_batch, lenx1_batch, lenx2_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += labels.size(0)
correct += predicted.eq(labels.view_as(predicted)).sum().item()
return (100 * correct / total)
model = RNN(emb_size=100, hidden_size=200, num_layers=1, num_classes=3, vocab_size=len(id2word))
learning_rate = 3e-4
num_epochs = 5 #Epoch size reduced to take into account size of data
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
####################################################################################
################################## TRAIN MODEL #####################################
############################### TRAINING ACCURACY ##################################
############################## VALIDATION ACCURACY #################################
####################################################################################
rnn_val_acc = []
rnn_train_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if i > 0 and i % 100 == 0:
val_acc = test_model(val_loader, model)
rnn_val_acc.append(val_acc)
train_acc = test_model(train_loader, model)
rnn_train_acc.append(train_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Validation Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
######### PLOT TRAINING AND VALIDATION ACCURACIES FOR BASELINE RNN MODEL ###########
####################################################################################
%matplotlib inline
plt.figure(figsize = (8,6))
plt.plot(rnn_val_acc, 'r', label = 'Validation Accuracy')
plt.plot(rnn_train_acc, 'b', label = 'Training Accuracy')
plt.title('Training and Validation Accuracy on RNN')
plt.xlabel('Steps')
plt.ylabel('Accuracy')
plt.legend()
####################################################################################
#################################### CNN MODEL #####################################
####################################################################################
class CNN(nn.Module):
def __init__(self, emb_size, hidden_size, num_layers, num_classes, vocab_size):
super(CNN, self).__init__()
self.num_layers, self.hidden_size, self.emb_size = num_layers, hidden_size, emb_size
self.embedding = nn.Embedding(vocab_size, emb_size, padding_idx=PAD_IDX)
self.conv1 = nn.Conv1d(emb_size, hidden_size, kernel_size=3, padding=1)
self.conv2 = nn.Conv1d(hidden_size, hidden_size, kernel_size=3, padding=1)
self.linear = nn.Linear(2*hidden_size, num_classes)
def forward(self, x1, x2, lenx1, lenx2):
batch_size1, seq_len1 = x1.size()
embed1 = self.embedding(x1)
hidden1 = self.conv1(embed1.transpose(1,2)).transpose(1,2)
hidden1 = F.relu(hidden1.contiguous().view(-1, hidden1.size(-1))).view(batch_size1, seq_len1, hidden1.size(-1))
hidden1 = self.conv2(hidden1.transpose(1,2)).transpose(1,2)
hidden1 = F.relu(hidden1.contiguous().view(-1, hidden1.size(-1))).view(batch_size1, seq_len1, hidden1.size(-1))
hidden1 = F.max_pool1d(hidden1.transpose(1,2), x1.size()[-1]).transpose(1,2)
batch_size2, seq_len2 = x2.size()
embed2 = self.embedding(x2)
hidden2 = self.conv1(embed2.transpose(1,2)).transpose(1,2)
hidden2 = F.relu(hidden2.contiguous().view(-1, hidden2.size(-1))).view(batch_size2, seq_len2, hidden2.size(-1))
hidden2 = self.conv2(hidden2.transpose(1,2)).transpose(1,2)
hidden2 = F.relu(hidden2.contiguous().view(-1, hidden2.size(-1))).view(batch_size2, seq_len2, hidden2.size(-1))
hidden2 = F.max_pool1d(hidden2.transpose(1,2), x2.size()[-1]).transpose(1,2)
full_cnn_out = torch.cat([hidden1.view(-1, hidden2.size(-1)), hidden2.view(-1, hidden2.size(-1))], 1)
logits = self.linear(full_cnn_out)
#ReLU
logits1 = self.linear(full_cnn_out)
return logits1
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for x1, x2, lenx1, lenx2, labels in loader:
x1_batch, x2_batch, lenx1_batch, lenx2_batch, label_batch = x1, x2, lenx1, lenx2, labels
outputs = F.softmax(model(x1_batch, x2_batch, lenx1_batch, lenx2_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += labels.size(0)
correct += predicted.eq(labels.view_as(predicted)).sum().item()
return (100 * correct / total)
model = CNN(emb_size=100, hidden_size=200, num_layers=1, num_classes=3, vocab_size=len(id2word))
learning_rate = 3e-4
num_epochs = 5 # Epoch size reduced to take into account size of data
# Criterion and Optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
####################################################################################
################################## TRAIN MODEL #####################################
############################### TRAINING ACCURACY ##################################
############################## VALIDATION ACCURACY #################################
####################################################################################
cnn_val_acc = []
cnn_train_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(val_loader, model)
cnn_val_acc.append(val_acc)
train_acc = test_model(train_loader, model)
cnn_train_acc.append(train_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
############################## HYPERPARAMETER TESTING ##############################
####################################################################################
# Increase hidden size to 400
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for x1, x2, lenx1, lenx2, labels in loader:
x1_batch, x2_batch, lenx1_batch, lenx2_batch, label_batch = x1, x2, lenx1, lenx2, labels
outputs = F.softmax(model(x1_batch, x2_batch, lenx1_batch, lenx2_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += labels.size(0)
correct += predicted.eq(labels.view_as(predicted)).sum().item()
return (100 * correct / total)
model = CNN(emb_size=100, hidden_size=400, num_layers=1, num_classes=3, vocab_size=len(id2word))
learning_rate = 3e-4
num_epochs = 5 # Epoch size reduced to take into account size of data
# Criterion and Optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
# Hyperparameter tuning, hidden size = 400
cnn_val_acc1 = []
cnn_train_acc1 = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(val_loader, model)
cnn_val_acc1.append(val_acc)
train_acc = test_model(train_loader, model)
cnn_train_acc1.append(train_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
%matplotlib inline
plt.figure(figsize = (8,6))
plt.plot(cnn_val_acc1, 'r', label = 'Validation Accuracy')
plt.plot(cnn_train_acc1, 'b', label = 'Training Accuracy')
plt.title('Training and Validation Accuracy on CNN (Larger Hidden Size)')
plt.xlabel('Steps')
plt.ylabel('Accuracy')
plt.legend()
####################################################################################
################################# MODEL PREDICTIONS ################################
####################################################################################
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for x1, x2, lenx1, lenx2, labels in loader:
x1_batch, x2_batch, lenx1_batch, lenx2_batch, label_batch = x1, x2, lenx1, lenx2, labels
outputs = F.softmax(model(x1_batch, x2_batch, lenx1_batch, lenx2_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += labels.size(0)
correct += predicted.eq(labels.view_as(predicted)).sum().item()
return predicted
############################### Correct Predictions ################################
#1st, 4th, and 6th pairing
print(sent1_val[0], sent2_val[0], labels_val[0]) #Predicted: Contradiction
#Premise: Three women on a stage , one wearing red shoes , black pants ,
#and a gray shirt is sitting on a prop , another is sitting on the floor ,
#and the third wearing a black shirt and pants is standing , as a gentleman in the back tunes an instrument .
#Hypothesis: There are two women standing on the stage
#Label: Contradiction
print(sent1_val[3], sent2_val[3], labels_val[3]) #Predicted: Entailment
#Premise: Man in overalls with two horses .
#Hypothesis: a man in overalls with two horses.
#Label: Entailment
print(sent1_val[5], sent2_val[5], labels_val[5]) #Predicted: Entailment
#Premise: Two people are in a green forest .
#Hypothesis: The forest is not dead .
#Label: Entailment
############################## Incorrect Predictions ################################
#2nd, 3rd, and 5th pairing
print(sent1_val[1], sent2_val[1], labels_val[1]) #Predicted: Contradiction
#Premise: Four people sit on a subway two read books , one looks at a cellphone and is wearing knee high boots .
#Hypothesis: Multiple people are on a subway together , with each of them doing their own thing .
#Label: Entailment
print(sent1_val[2], sent2_val[2], labels_val[2]) #Predicted: Neutral
#Premise: bicycles stationed while a group of people socialize .
#Hypothesis: People get together near a stand of bicycles .
#Label: Entailment
print(sent1_val[4], sent2_val[4], labels_val[4]) #Predicted: Neutral
#Premise: Man observes a wavelength given off by an electronic device .
#Hypothesis: The man is examining what wavelength is given off by the device .
#Label: Entailment
####################################################################################
################################ EVALUATING MNLI DATA ##############################
####################################################################################
sent1_mnli_val = []
sent2_mnli_val = []
labels_mnli_val = []
genres_mnli_val = []
with open('hw2_data/mnli_val.tsv') as val:
mnli_val = csv.reader(val, delimiter = '\t')
for s1, s2, label, genre in mnli_val:
sent1_mnli_val.append(s1.split())
sent2_mnli_val.append(s2.split())
genres_mnli_val.append(genre)
if label == 'contradiction':
labels_mnli_val.append(0)
if label == 'neutral':
labels_mnli_val.append(1)
if label == 'entailment':
labels_mnli_val.append(2)
genres_mnli_val.pop(0)
sent1_mnli_val.pop(0)
sent2_mnli_val.pop(0)
len(sent1_mnli_val), len(sent2_mnli_val), len(labels_mnli_val), len(genres_mnli_val)
mnli = pd.DataFrame({'sent1': sent1_mnli_val,
'sent2': sent2_mnli_val,
'labels': labels_mnli_val,
'genres': genres_mnli_val})
####################################################################################
################################# MNLI BY GENRE ####################################
####################################################################################
mnli_fiction = mnli.loc[mnli['genres'] == 'fiction']
mnli_government = mnli.loc[mnli['genres'] == 'government']
mnli_slate = mnli.loc[mnli['genres'] == 'slate']
mnli_telephone = mnli.loc[mnli['genres'] == 'telephone']
mnli_travel = mnli.loc[mnli['genres'] == 'travel']
####################################################################################
########################### TRAIN AND GENRE DATALOADERS ############################
####################################################################################
train_dataset = VocabDataset(sent1_train, sent2_train, labels_train, word2id)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
fiction_val_dataset = VocabDataset(mnli_fiction['sent1'].tolist(), mnli_fiction['sent2'].tolist(),
mnli_fiction['labels'].tolist(), word2id)
fiction_val_loader = torch.utils.data.DataLoader(dataset=fiction_val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
government_val_dataset = VocabDataset(mnli_government['sent1'].tolist(), mnli_government['sent2'].tolist(),
mnli_government['labels'].tolist(), word2id)
government_val_loader = torch.utils.data.DataLoader(dataset=government_val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
slate_val_dataset = VocabDataset(mnli_slate['sent1'].tolist(), mnli_slate['sent2'].tolist(),
mnli_slate['labels'].tolist(), word2id)
slate_val_loader = torch.utils.data.DataLoader(dataset=slate_val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
telephone_val_dataset = VocabDataset(mnli_telephone['sent1'].tolist(), mnli_telephone['sent2'].tolist(),
mnli_telephone['labels'].tolist(), word2id)
telephone_val_loader = torch.utils.data.DataLoader(dataset=telephone_val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
travel_val_dataset = VocabDataset(mnli_travel['sent1'].tolist(), mnli_travel['sent2'].tolist(),
mnli_travel['labels'].tolist(), word2id)
travel_val_loader = torch.utils.data.DataLoader(dataset=travel_val_dataset,
batch_size=BATCH_SIZE,
collate_fn=vocab_collate_func,
shuffle=True)
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for x1, x2, lenx1, lenx2, labels in loader:
x1_batch, x2_batch, lenx1_batch, lenx2_batch, label_batch = x1, x2, lenx1, lenx2, labels
outputs = F.softmax(model(x1_batch, x2_batch, lenx1_batch, lenx2_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += labels.size(0)
correct += predicted.eq(labels.view_as(predicted)).sum().item()
return (100 * correct / total)
####################################################################################
############################# OPTIMAL MODEL FOR MNLI ###############################
####################################################################################
model = CNN(emb_size=100, hidden_size=200, num_layers=1, num_classes=3, vocab_size=len(id2word))
learning_rate = 3e-4
num_epochs = 5 # Epoch size reduced to take into account size of data
# Criterion and Optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
####################################################################################
################################# FICTION GENRE ####################################
####################################################################################
best_fiction_val_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(fiction_val_loader, model)
best_fiction_val_acc.append(val_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
################################# GOVERNMENT GENRE #################################
####################################################################################
best_government_val_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(government_val_loader, model)
best_government_val_acc.append(val_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
################################### SLATE GENRE ####################################
####################################################################################
best_slate_val_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(slate_val_loader, model)
best_slate_val_acc.append(val_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
################################# TELEPHONE GENRE ##################################
####################################################################################
best_telephone_val_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(telephone_val_loader, model)
best_telephone_val_acc.append(val_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
####################################################################################
################################## TRAVEL GENRE ####################################
####################################################################################
best_travel_val_acc = []
for epoch in range(num_epochs):
for i, (x1, x2, lenx1, lenx2, labels) in enumerate(train_loader):
model.train()
optimizer.zero_grad()
# Forward pass
outputs = model(x1, x2, lenx1, lenx2)
loss = criterion(outputs, labels)
# Backward and optimize
loss.backward()
optimizer.step()
# validate every 100 iterations
if i > 0 and i % 100 == 0:
# validation accuracy
val_acc = test_model(travel_val_loader, model)
best_travel_val_acc.append(val_acc)
print('Epoch: [{}/{}], Step: [{}/{}], Val Acc: {}'.format(
epoch+1, num_epochs, i+1, len(train_loader), val_acc))
# PLOT ALL VALIDATION ACCURACIES BY GENRE
%matplotlib inline
plt.figure(figsize = (8,6))
plt.plot(best_fiction_val_acc, label = 'Fiction Validation Accuracy')
plt.plot(best_government_val_acc, label = 'Government Validation Accuracy')
plt.plot(best_slate_val_acc, label = 'Slate Validation Accuracy')
plt.plot(best_telephone_val_acc, label = 'Telephone Validation Accuracy')
plt.plot(best_travel_val_acc, label = 'Travel Validation Accuracy')
plt.legend()
plt.xlabel('Steps')
plt.ylabel('Accuracy')
plt.title('Validation Accuracy by Genre')
|
Java | UTF-8 | 374 | 1.828125 | 2 | [] | no_license | package com.james.dao;
import java.util.List;
import com.james.entity.Interview;
public interface InterviewDao {
int addInterview(Interview interview);
int deleteInterview(Integer interviewId);
int updateInterview(Interview interview);
Interview queryInterviewByUserId(Integer userId);
List<Interview> queryIVsByDeptId(Integer deptId);
}
|
Markdown | UTF-8 | 2,449 | 2.78125 | 3 | [] | no_license | # Deploying PG Applications to Heroku - 8/17/2020
After verifying that our app works, it's time to deploy to Heroku!
* Make sure the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) is installed and working.
* Specify a version of Ruby in the `Gemfile`.
* Add `puma` to the `Gemfile`.
* Run `bundle install`.
* Add a `Procfile`.
* Verify that everything is working using `heroku local`.
* Make sure that any development-specific code, such as `sinatra/reloader`, won't run in production.
* Update your code to open the database like this:
```ruby
@db = if Sinatra::Base.production?
PG.connect(ENV['DATABASE_URL'])
else
PG.connect(dbname: "todos")
end
```
* Create an application on Heroku by running `heroku apps:create` within the project's directory:
```
▶ heroku apps:create tjc-ls-185-todos
Creating ⬢ tjc-ls-185-todos... done
https://tjc-ls-185-todos.herokuapp.com/ | https://git.heroku.com/tjc-ls-185-todos.git
```
* Enable PostgreSQL for your application on Heroku:
```
▶ heroku addons:create heroku-postgresql:hobby-dev -a tjc-ls-185-todos
Creating heroku-postgresql:hobby-dev on ⬢ tjc-ls-185-todos... free
Database has been created and is available
! This database is empty. If upgrading, you can transfer
! data from another database with pg:copy
Created postgresql-triangular-59929 as DATABASE_URL
Use heroku addons:docs heroku-postgresql to view documentation
```
* If you have some code to create your database schema in `schema.sql`, you can try running the following command to do so:
```ruby
$ heroku pg:psql < schema.sql
--> Connecting to postgresql-triangular-59929
CREATE TABLE
CREATE TABLE
```
* We're using Heroku's free hobby-dev PostgreSQL database plan, which only allows for a maximum of 20 open database connections at once. If we exceed this limit, then our application will throw an error. Add the following code into your application to ensure that you don't exceed that 20 connection limit.
```ruby
# todo.rb
after do
@storage.disconnect
end
```
```ruby
# database_persistence.rb
def disconnect
@db.close
end
```
* Commit any changes you made above.
* Deploy the application to Heroku using `git push heroku master` (if you're working on a branch other than master, you'll need to use its name in this command instead).
Now if you visit your app's URL, your app should appear as a brand new app that is ready for to track your todos permanently.
|
Markdown | UTF-8 | 3,165 | 2.609375 | 3 | [] | no_license | # Homework #4
10 points
**DUE: Saturday, March 2 by 12:00pm**
For easiest viewing of these instructions, view online on Github.com or use a Markdown previewer.
### Getting Started
1. Download a ZIP file of this repository, unzip it into a folder, and then convert that folder
into your own git repository. (Alternatively, you can clone this repository and then use `git remote set-url...` to point to your remote repository instead.)
2. Create a remote repository (GitHub or BitBucket) called `mpscs52553-hw4`.
2. Follow the instructions below.
3. Commit often. Push often.
4. Add collaborators:
* GitHub: jahnagoldman, ekxue, jeffcohen
* BitBucket: jahnamcnamara, ekxue, jeffcohen
5. Make sure your final commit is timestamped before the deadline, and everything is pushed to your remote repository by the deadline.
### Instructions
This assignment is intended to provide more practice at JavaScript (ES6)
programming. Some research might be required. Watch a 5-second movie
of a sample solution in the file `hw4.mp4`.
**1. Run `npm install`**
I have included the [request](https://github.com/request/request) library
so you can make HTTP requests from a Node script. See the documentation
for example usage.
**2. Determine the (possible) date of the end of the world!**
Did you know that NASA has an API that lists all incoming
asteroids that are currently hurtling their way toward our planet?
Some of them are tiny, but some of them are huge.
Some of them miss the Earth by a wide margin, but some of them
get very close!
Your task is very simple:
1. Write a Node script that emits
the name of the largest asteroid that
is most likely to hit the Earth right before the quarter ends,
during the week of March 16, 2019 to March 23, 2019?
2. Also display the speed in miles per hour, and the distance in miles.
Documentation for the NASA API ("Neo - Feed"): https://api.nasa.gov/api.html#neows-feed
**3. Rules and hints:**
1. You can use my API key `ThEWyjBBPDnDKV2CVSqO4gRU3qjBlpkMJo06rwo8` but
if you find that's not working, you should sign up for your own:
[https://api.nasa.gov/index.html#apply-for-an-api-key]
(https://api.nasa.gov/index.html#apply-for-an-api-key).
**BEWARE that it may take a couple of days for you to be approved.**
2. Use the example data provided by NASA in their documentation to get a feel for
the kind of data you'll get back. Part of this assignment is
to give you practice at your ingenuity when faced with less-than-ideal
API data structures. For example, try running the request in your browser
to see the JSON data that will be returned.
3. You'll need to parse HTTP response body with `JSON.parse()`
4. You'll need to especially pay attention to the size of the asteroid
as well as whether it has a chance of hitting Earth. Look for
the `is_potentially_hazardous_asteroid` indicator that NASA
provides with each asteroid. Those are the ones you need to be
concerned with. __Do not consider any asteroids
that are not considered by to be potentially hazardous.__
5. When comparing the asteroid sizes, use the "maximum estimated diameter"
of each asteroid.
# mpcs52553-hw4
|
Java | UTF-8 | 1,962 | 1.914063 | 2 | [] | no_license | package android.support.v4.text;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
final class f
{
private static final String a = "ICUCompatIcs";
private static Method b;
private static Method c;
static
{
try
{
Class localClass = Class.forName("libcore.icu.ICU");
if (localClass != null)
{
b = localClass.getMethod("getScript", new Class[] { String.class });
c = localClass.getMethod("addLikelySubtags", new Class[] { String.class });
}
return;
}
catch (Exception localException)
{
Log.w("ICUCompatIcs", localException);
}
}
public static String a(String paramString)
{
try
{
if (b != null)
{
Object[] arrayOfObject = { paramString };
String str = (String)b.invoke(null, arrayOfObject);
return str;
}
}
catch (IllegalAccessException localIllegalAccessException)
{
Log.w("ICUCompatIcs", localIllegalAccessException);
return null;
}
catch (InvocationTargetException localInvocationTargetException)
{
while (true)
Log.w("ICUCompatIcs", localInvocationTargetException);
}
}
public static String b(String paramString)
{
try
{
if (c != null)
{
Object[] arrayOfObject = { paramString };
String str = (String)c.invoke(null, arrayOfObject);
return str;
}
}
catch (IllegalAccessException localIllegalAccessException)
{
Log.w("ICUCompatIcs", localIllegalAccessException);
return paramString;
}
catch (InvocationTargetException localInvocationTargetException)
{
while (true)
Log.w("ICUCompatIcs", localInvocationTargetException);
}
}
}
/* Location: C:\Users\Fernando\Desktop\Mibandesv2.3\classes-dex2jar.jar
* Qualified Name: android.support.v4.text.f
* JD-Core Version: 0.6.2
*/ |
C++ | UTF-8 | 1,141 | 3.609375 | 4 | [] | no_license |
#include "StringLinkedList.h"
#include "StringNode.h"
#include <string>
#include <iostream>
using namespace std;
StringLinkedList::StringLinkedList() // constructor
: head(NULL) {}
StringLinkedList::~StringLinkedList() // destructor
{
while (!empty())
removeFront();
}
bool StringLinkedList::empty() const // is list empty?
{ return head == NULL; }
const string &StringLinkedList::front() const // get front element
{ return head->elem; }
void StringLinkedList::addFront(const string &e) { // add to front of list
StringNode *v = new StringNode; // create new node
v->elem = e; // store data
v->next = head; // head now follows v
head = v; // v is now the head
}
void StringLinkedList::removeFront() { // remove front item
StringNode *old = head; // save current head
head = old->next; // skip over old head
delete old; // delete the old head
}
int StringLinkedList::getSize() { // get size
int i = 0;
StringNode *v = head;
while (v != NULL) {
i++; //number of elements with data. i+1 = number of nodes
v = v->next;
}
return i;
}
|
Java | UTF-8 | 1,700 | 2.796875 | 3 | [] | no_license | package com.careerguidance.model;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Career class, define university instance and attributes of a career,
* and APIs for accessing career data.
*/
public class Career extends BaseObject {
double avgSalary;
ArrayList<String> skillsRequired;
Hashtable<String, Double> gradesRequired;
ArrayList videoList;
public Career()
{
super();
avgSalary = 0.00;
skillsRequired = new ArrayList<String>();
gradesRequired = new Hashtable<String, Double>();
videoList = new ArrayList();
}
public Career(String careerName, String desc, double avgSal, ArrayList<String> reqSkills, Hashtable<String, Double> reqGrades, ArrayList vidList) {
name = careerName;
description = desc;
avgSalary = avgSal;
skillsRequired = reqSkills;
gradesRequired = reqGrades;
videoList = vidList;
}
//Getters
public double getAvgSalary() {
return avgSalary;
}
public ArrayList<String> getSkillsRequired() {
return skillsRequired;
}
public Hashtable<String, Double> getGradesRequired() {
return gradesRequired;
}
public ArrayList getVideoList() {
return videoList;
}
//Setters
public void setAvgSalary(double avgSal) {
avgSalary = avgSal;
}
public void setSkillsRequired(ArrayList<String> reqSkills) {
skillsRequired = reqSkills;
}
public void setGradesRequired(Hashtable<String, Double> reqGrades) {
gradesRequired = reqGrades;
}
public void setVideoList(ArrayList vidList) {
videoList = vidList;
}
}
|
Python | UTF-8 | 682 | 2.875 | 3 | [] | no_license | import discord
from discord.ext import commands
"""Imports"""
def get_prefix(bot, message):
prefixes = ['c', 'C']
if not message.guild:
return '?'
return commands.when_mentioned_or(*prefixes)(bot, message)
initial_extensions = ['cogs.fun',
'cogs.utility', ]
"""List of cogs"""
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension)
"""Loads your cogs"""
bot = commands.Bot(command_prefix=get_prefix, description='A secret bot!')
@bot.event
async def on_ready():
print(f'We have logged in as {client.user}'.format(client))
bot.run(TOKEN)
"""TOKEN should be your bot's token"""
|
JavaScript | UTF-8 | 1,114 | 2.734375 | 3 | [] | no_license | import React,{useState, useEffect, useReducer} from "react";
import {City, StateCode, MyAPIKey} from "../constants/constants";
const errorMessage = (err)=>{
console.log(err)
}
const apiResponse = (prev, resp)=>{
// console.log(prev)
// console.log('response is - ' + resp)
return resp
}
const langManipulation = (prev)=>{
console.log(prev)
}
const my_lang = 'ru'
export const Fetch = ()=>{
const [lang, setLang]=useReducer(langManipulation,my_lang)
const [error, setError]=useReducer(errorMessage, null)
const [response, setResponse]=useReducer(apiResponse, null)
const fetching = async ()=>{
const data = await fetch(
`https://api.openweathermap.org/data/2.5/forecast?q=${City},${StateCode}&lang=${lang}&appid=${MyAPIKey}`).
then(res=>res.json())
setResponse(data)
// console.log(weathers)
}
useEffect(()=>{
fetching().catch(setError)
},[])
useEffect(()=>{
if (error) return console.log(error)
console.log(response)
})
return null
} |
C# | UTF-8 | 765 | 2.671875 | 3 | [] | no_license | using System.Text;
using System.Threading;
using Configit.Grid;
namespace GridTestTaskProcessor {
public class NameRepeaterTaskProcessor : TaskProcessor<string, int, bool, string> {
public override string TypeKey => "NameRepeater";
public override string Name => "Name Repeater";
public override string Run( string str, int repeat, bool upperCase, CancellationToken cancellationToken, GridServices services ) {
if ( upperCase ) {
str = str.ToUpperInvariant();
}
var stringBuilder = new StringBuilder();
for (var i = 0; i < repeat; i++) {
stringBuilder.Append( str );
if (i < repeat - 1) {
stringBuilder.Append( " " );
}
}
return stringBuilder.ToString();
}
}
} |
Ruby | UTF-8 | 1,857 | 3.375 | 3 | [] | no_license | class NodeRenderer
def initialize(tree)
@tree = tree
end
def render(node = nil)
node = @tree.root if node.nil?
descendant_stats = count_descendants(node)
# All of the node's data attributes
render_attributes(node)
# How many total nodes there are in the sub-tree below this node
puts "\nTotal descendant nodes: #{descendant_stats[0]}"
# A count of each node type in the sub-tree below this node
puts "\nDescendants by name:"
render_descendants(descendant_stats[1])
end
def count_descendants(node)
queue = [node]
total = 0
types = {}
until queue.empty?
node = queue.shift
# counts number of each type of tag
node.children.each do |child|
types[child.name] ||= 0
types[child.name] += 1
queue << child
end
# sums total descendants
total = types.values.inject { |sum, value| sum += value }
end
[total, types]
end
def render_attributes(node)
puts "\nCURRENT NODE\n\n"
puts "\tName: #{node.name}"
puts "\tText: #{node.text}"
if node.classes.nil?
puts "\tClasses:"
else
puts "\tClasses: #{node.classes.join(", ")}"
end
puts "\tID: #{node.id}"
child_names = get_child_names(node)
puts "\tChildren: #{child_names}"
parent = get_parent_name(node)
puts "\tParent: #{parent}"
end
# properly renders the descendant tags
def render_descendants(name_counts)
name_counts.each { |key, value| puts "\t<#{key}> = #{value}"}
return
end
# returns names of children
def get_child_names(node)
child_names = []
node.children.each { |child| child_names << child.name }
child_names.join(", ")
end
# returns parent name
def get_parent_name(node)
parent_name = node.parent.name unless node.parent.nil?
end
end |
C# | UTF-8 | 4,713 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using COMP3351_Game_Engine;
namespace COMP3351_Engine_Demo
{
class HostileMind : Mind
{
// the change in location
private Vector2 _dLocation;
// the movement speed of the entity on x axis
private float _xSpeed;
// in air flag
private bool _inAir;
// on floor status flag
private bool _onFloor;
bool statesDeclared;
public HostileMind()
{
// set _dLocation
_dLocation = new Vector2(0, 0);
// set speed
_xSpeed = 3;
// set facing direction of the sprite
_facingDirectionX = 1;
// set mind ID
_mindID = "Hostile";
// set in Air flag to true
_inAir = true;
// set onFoor status to false
_onFloor = false;
}
/// <summary>
/// Required states are declared here to be added to game code.
/// </summary>
private void DeclareStates()
{
_stateDictionary.Add("Run", new HostileRunState(_entityUID, _animator, _audioPlayer));
_currentState = _stateDictionary["Run"];
}
/// <summary>
/// method to move the mind and entiry location to match the location of the physics component
/// </summary>
/// <returns></returns>
public override Vector2 Translate()
{
_dLocation = _physicsComponent.GetPosition() - _location;
_location += _dLocation;
return _dLocation;
}
public override bool OnNewCollision(ICollisionInput args)
{
bool rtnValue = base.OnNewCollision(args);
// on collision with HBoundary change facing direction in order to move the opposite direction
if (_collidedWith == "HBoundary" && _collidedThis == "HostileB" || _collidedWith == "HBoundary" && _collidedThis == "HostileT")
{
_facingDirectionX *= -1;
}
// on collision with another entity change facing direction in order to move the opposite direction
if (_collidedWith == "HostileB" && _collidedThis == "HostileB")
{
_facingDirectionX *= -1;
}
// Run floor collision logic
FloorCollision();
// on collisio with the base of the player and the top of this entity remove this entity from the scene
if (_collidedWith == "PlayerB" && _collidedThis == "HostileT")
{
rtnValue = true;
}
// Reset Collided with and this to null
_collidedWith = null;
_collidedThis = null;
_overlap.X = 0;
_overlap.Y = 0;
_cNormal.X = 0;
_cNormal.Y = 0;
// return rtnValue
return rtnValue;
}
private void FloorCollision()
{
// on collision with Floor change floorCollide flag to true
if (!_onFloor)
{
if (_collidedWith == "Floor" && _collidedThis == "HostileB")
{
_inAir = false;
_location.Y -= _overlap.Y;
_physicsComponent.RemoveOverlapY(-_overlap.Y);
_onFloor = true;
}
}
}
/// <summary>
/// Move behavior for the hostile
/// </summary>
private void Move()
{
//Declare a vector to store the force needed to move
Vector2 force = new Vector2(0, 0);
force.X = _xSpeed * _facingDirectionX;
// update facing direction in entity to update texture orientation
eInvertTexture(_facingDirectionX);
// apply force to the physics component to move entity
_physicsComponent.ApplyForce(force);
}
public override void Update(GameTime gameTime)
{
_gameTime = gameTime;
// update location
UpdateLocation(eGetLocation());
// Move the entity
Move();
// Update PhysicsComponent
_physicsComponent.UpdatePhysics();
eTranslate(Translate());
// Declare required states
if (!statesDeclared)
{
DeclareStates();
statesDeclared = true;
}
// Run state machine
StateMachine();
_onFloor = false;
}
}
} |
JavaScript | UTF-8 | 4,816 | 2.84375 | 3 | [] | no_license | const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const ds = require('./datastore');
const datastore = ds.datastore;
const BOAT = "Boat";
const LOAD = "LOAD";
//const URL = "http://localhost:8080";
router.use(bodyParser.json());
/************************* HELPER FUNCTIONS *************************/
//Returns true if any of the fields passed in are undefined
function missingFields(fields){
let isMissing = false
fields.forEach(field => {
if(!field){
isMissing = true
}
})
return isMissing
}
//Create boat
function post_load(weight, content, delivery_date){
var key = datastore.key([LOAD])
const new_load = {"weight": weight, "content": content, "delivery_date": delivery_date}
return datastore.save({"key": key, "data": new_load}).then(() => {return key})
}
//Get specific load
function get_load(id){
var key = datastore.key([LOAD, parseInt(id, 10)]);
return datastore.get(key)
.then ((loads) => {
const load = loads[0];
return load
})
}
//Delete load
async function delete_load(id){
const load_key = datastore.key([LOAD, parseInt(id, 10)]);
const [load] = await datastore.get(load_key)
if(!load)
return -1
//If load has a carrier, get ID, lookup boat, and update boat load
if(load.carrier){
const boat_id = load.carrier.id
const boat_key = datastore.key([BOAT, parseInt(boat_id, 10)]);
const [boat] = await datastore.get(boat_key)
ds.fromDatastore(load)
const filtered_loads = boat.loads.filter(this_load => this_load.id !== load.id)
let updated_boat = {
"name": boat.name,
"type": boat.type,
"length": boat.length
}
//Add loads attribute if there are any loads in the array
if(filtered_loads.length > 0){
updated_boat.loads = filtered_loads
}
datastore.update({"key": boat_key, "data": updated_boat})
}
datastore.delete(load_key)
return 0
}
//Get all loads, 3 per page
function get_loads(req){
var q = datastore.createQuery(LOAD).limit(3);
const results = {};
if(Object.keys(req.query).includes("cursor")){
q = q.start(req.query.cursor);
}
return datastore.runQuery(q).then( (entities) => {
//results.items = entities[0].map(ds.fromDatastore);
results.items = entities[0].map(ds.fromDatastore);
results.items.forEach(item => {
item.self = req.protocol + "://" + req.get("host") + "/loads/" + item.id
})
if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS ){
results.next = req.protocol + "://" + req.get("host") + req.baseUrl + "?cursor=" + entities[1].endCursor;
}
return results;
})
}
/****************************** ROUTES ******************************/
//Get all loads, 3 loads per page
router.get('/', function(req, res){
get_loads(req)
.then(loads => {
res.status(200).send(loads)
})
});
//Create a boat
router.post('/', function(req, res){
if(missingFields([req.body.weight, req.body.content, req.body.delivery_date]))
res.status(400).send({ "Error": "The request object is missing at least one of the required attributes" })
else {
post_load(req.body.weight, req.body.content, req.body.delivery_date)
.then( key => {
let self = req.protocol + "://" + req.get("host") + "/loads/" + key.id
let return_object = {
"id": key.id,
"weight": req.body.weight,
"content": req.body.content,
"delivery_date": req.body.delivery_date,
"self": self
}
res.status(201).send(return_object)
})
}
});
router.get('/:load_id', function(req, res){
const boats = get_load(req.params.load_id)
.then( (load) => {
if(load){
load.self = req.protocol + "://" + req.get("host") + "/loads/" + req.params.load_id
ds.fromDatastore(load)
if(typeof(load.carrier) !== 'undefined'){
//console.log(typeof(load.carrier))
load.carrier.self = req.protocol + "://" + req.get("host") + "/boats/" + load.carrier.id
}
res.status(200).json(load);
}
else {
let error = { "Error": "No load with this load_id exists" }
res.status(404).json(error)
}
});
});
router.delete('/:load_id', function(req,res){
delete_load(req.params.load_id)
.then(outcome => {
if(outcome === 0)
res.status(204).end()
else
res.status(404).send({"Error": "No load with this load_id exists"})
})
});
module.exports = router;
|
C# | UTF-8 | 1,578 | 2.546875 | 3 | [] | no_license | using GunStore;
using GunStore.Builder;
using GunStore.Decorator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GunStoreTest
{
[TestClass]
public class GunStoreDecoratorTests
{
private AbstractGun gun;
[TestInitialize]
public void Initialize()
{
gun = GunFactory.Instance.Construct(new AK47Builder());
}
[TestMethod]
public void AddSilencer()
{
gun = new Silencer(gun);
Assert.IsTrue(gun.ToString().Contains("Silencer") && gun.Value() > gun.BasePrice);
}
[TestMethod]
public void AddHolographicSight()
{
gun = new HoloSight(gun);
Assert.IsTrue(gun.ToString().Contains("Holographic sight") && gun.Value() > gun.BasePrice);
}
[TestMethod]
public void AddLaserSight()
{
gun = new LaserSight(gun);
Assert.IsTrue(gun.ToString().Contains("Laser sight") && gun.Value() > gun.BasePrice);
}
[TestMethod]
public void AddMultipleAttachments()
{
gun = new LaserSight(gun);
gun = new HoloSight(gun);
gun = new Silencer(gun);
Assert.IsTrue(gun.ToString().Contains("Laser sight")
&& gun.ToString().Contains("Holographic sight")
&& gun.ToString().Contains("Silencer")
&& gun.Value() > gun.BasePrice);
}
[TestCleanup]
public void Cleanup()
{
gun = null;
}
}
}
|
JavaScript | UTF-8 | 3,640 | 2.53125 | 3 | [] | no_license | var db = require("../db.js")
let models = {
userCreation(req, res) {
let userEmail = req.body.email
let mobileNumber = req.body.mobileNumber
userEmail = userEmail.toLowerCase()
db.User.find({}, (err, users) => {
if (err) {
res.send({ message: `unable to create user`, status: 400 })
}
else {
let userlength = users.length
let userrole = userlength == 0 ? "admin" : "user"
db.User.find({ email: userEmail }, (err, user) => {
if (err) {
res.send({ message: `unable to find user`, status: 400 })
}
else {
if (user.length > 0) {
res.send({ message: `user exists`, status: 200 })
}
else {
let newUser = new db.User({ email: userEmail, mobileNumber: mobileNumber });
newUser.save((err, user) => {
if (err) {
res.send({ message: `unable to create user`, status: 400 })
} else {
let userId = user._id
let newUserRole = new db.UserRoleSchema({ refeUserId: userId, role: userrole });
newUserRole.save((err, userCreated) => {
res.send({ message: `${userrole} created`, status: 200 })
})
}
});
}
}
})
}
})
},
listUsers(req, res) {
db.User.find({}, { isDeleted: 0 }, (err, users) => {
if (err) {
res.send({ message: `unable to create user`, status: 400 })
}
else {
res.send({ users: users, status: 200 })
}
})
},
listUserRoles(req, res) {
db.UserRoleSchema.find({}, (err, users) => {
if (err) {
res.send({ message: `unable to create user`, status: 400 })
}
else {
res.send({ users: users, status: 200 })
}
})
},
getUserRoleByEmail(req, res) {
let userEmail = req.body.email
db.User.find({ email: userEmail }, (err, user) => {
if (err) {
res.send({ message: `unable to find user`, status: 400 })
}
else {
if (user) {
console.log("user",user)
let userId = user[0]._id
db.UserRoleSchema.find({ refeUserId: userId }, (err, userRole) => {
if (err) {
res.send({ message: `unable to find user`, status: 400 })
}
else {
let obj = {
"email": user[0].email,
"mobileNumber": user[0].mobileNumber,
"role": userRole[0].role,
}
res.send({ user: obj, status: 200 })
}
})
}
else {
res.send({ message: "No user is present with this email", status: 200 })
}
}
})
}
}
module.exports = models |
Python | UTF-8 | 154 | 3.046875 | 3 | [] | no_license | import sys
biggest_num = - sys.maxsize
for num in range(3):
num = int(input())
if num > biggest_num:
biggest_num = num
print(biggest_num)
|
C++ | UTF-8 | 1,057 | 2.578125 | 3 | [] | no_license | #pragma once
#include <string>
#include <SDL.h>
#include "window.h"
#include "SDL_image.h"
#include <iostream>
#include <string>
#include "window.h"
class Sprite
{
public:
enum Flip
{
NO_FLIP = SDL_FLIP_NONE,
HORZ_FLIP = SDL_FLIP_HORIZONTAL,
VERT_FLIP = SDL_FLIP_VERTICAL
};
Sprite();
~Sprite();
void IsAnimated(bool flag);
void IsAnimationLooping(bool flag);
void SetImageCel(int column, int row);
void SetAnimationVelocity(float velocity);
void SetSpriteDimension(int width, int height);
void SetImageDimension(int columns, int rows, int width, int height);
bool Load(const std::string& filename, Window& window);
void Unload();
void Update();
void Render(int xPos, int yPos, double angle, Window& window, Flip flip = NO_FLIP);
private:
int m_imageCel;
float m_animationVelocity;
bool m_isAnimated;
bool m_isAnimationDead;
bool m_isAnimationLooping;
SDL_Texture* m_image;
SDL_Point m_dimension;
SDL_Point m_spriteDimension;
SDL_Point m_imageDimension;
};
|
Java | UTF-8 | 122 | 1.820313 | 2 | [] | no_license | package com.kharim.games.blackjack.players;
/**
* kharim
*/
public enum Seats {
ONE, TWO, THREE, FOUR, FIVE, SIX
}
|
Java | UTF-8 | 312 | 2.03125 | 2 | [] | no_license | package com.anja.task1.app.data;
import java.util.List;
/**
* Created by Anna on 29.05.2016.
*/
public interface OrderRepository {
void setSelectedOrder(Order selectedOrder);
Order getSelectedOrder();
List<Order> getOrders(Order.Status status, int amount, int offset);
void clearCache();
}
|
C++ | UTF-8 | 8,846 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <memory>
#include <atomic>
#include <mutex>
#include <initializer_list>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
#include <list>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <unordered_map>
// Boost Library Hearders
#include <boost/type_index.hpp>
using namespace std;
using boost::typeindex::type_id_with_cvr;
template<typename T>
class Base {
public :
// Base () = default;
Base (T * arg = "default") {
cout <<"Call Template Constructor : Base Class "<< endl;
length1 = strlen(arg);
string1 = new char[length1 + 1];
strcpy(string1, arg);
string1[length1 + 1] = '\0';
}
Base (const Base & rhs) {
cout <<"Call Copy Constructor : Base Class "<< endl;
length1 = rhs.length1;
string1 = new char[length1 + 1];
strcpy(string1, rhs.string1);
string1[length1 + 1] = '\0';
}
Base (Base && rhs): string1(rhs.string1), length1(rhs.length1) {
cout <<"Call Move Constructor for Normal Base Class : Base "<< endl;
rhs.string1 = nullptr;
rhs.length1 = 0;
}
Base & operator=(const Base & rhs){
cout <<"Call Assignment Operator for Normal Base Class : A "<< endl;
if (this != &rhs) {
delete[] string1;
string1 = new char[rhs.length1 + 1];
strcpy(string1, rhs.string1);
length1 = rhs.length1;
string1[length1 + 1] = '\0';
}
return *this;
}
Base & operator=(Base && rhs){
cout <<"Call Move Assignment Operator for Normal Base Class : Base "<< endl;
if (this != &rhs) {
delete[] string1;
string1 = rhs.string1;
length1 = rhs.length1;
rhs.string1 = nullptr;
rhs.length1 = 0;
}
return *this;
}
~Base() {
cout <<"Call Destructor for Normal Base Class : Base "<< endl;
delete[] string1;
}
private :
T * string1;
size_t length1;
};
template<typename T1, typename T2>
class Derived1 : virtual public Base<T1> {
public :
Derived1 (T1 * arg1, T2 * arg2) : Base<T1>(arg1) {
cout <<"Call Constructor for Template Derived1 --->> Base<T1> "<< endl;
length2 = strlen(arg2);
string2 = new char[length2 + 1];
strcpy(string2, arg2);
string2[length2 + 1] = '\0';
}
Derived1 (const Derived1 & rhs): Base<T1>(rhs) {
cout <<"Call Copy Constructor for Template Derived1 --->> Base<T1> "<< endl;
length2 = rhs.length2;
string2 = new char[length2 + 1];
strcpy(string2, rhs.string2);
string2[length2 + 1] = '\0';
}
Derived1 (Derived1 && rhs): Base<T1>(move(rhs)) {
cout <<"Call Move Constructor for Template Derived1 --->> Base<T1>"<< endl;
string2 = rhs.string2;
length2 = rhs.length2;
rhs.string2 = nullptr;
rhs.length2 = 0;
}
Derived1 & operator=(const Derived1 & rhs) {
cout <<"Call Assignment Operator for Template Derived1 Class"<< endl;
if (this != &rhs) {
Base<T1>::operator=(rhs);
delete [] string2;
string2 = new char[rhs.length2 + 1];
strcpy(string2, rhs.string2);
string2[length2 + 1] = '\0';
length2 = rhs.length2;
}
return *this;
}
Derived1 & operator=(Derived1 && rhs) {
cout <<"Call Move Assignment Operator for Template Derived1 Class"<< endl;
if (this != &rhs) {
Base<T1>::operator=(move(rhs));
delete [] string2;
string2 = rhs.string2;
length2 = rhs.length2;
rhs.string2 = nullptr ;
rhs.length2 = 0;
}
return *this;
}
~Derived1() {
cout <<"Call Desstructor for Template Derived1 "<< endl;
// ~Base<T1>::Base();
delete[] string2;
}
private :
T2 * string2;
int length2;
};
template<typename T1, typename T2>
class Derived2 : virtual public Base<T1> {
public :
Derived2 (T1 * arg1, T2 * arg2) : Base<T1>(arg1) {
cout <<"Call Constructor for Template Derived 2 --->> Base<T1> "<< endl;
length2 = strlen(arg2);
string2 = new char[length2 + 1];
strcpy(string2, arg2);
string2[length2 + 1] = '\0';
}
Derived2 (const Derived2 & rhs): Base<T1>(rhs) {
cout <<"Call Copy Constructor for Template Derived 2 --->> Base<T1> "<< endl;
length2 = rhs.length2;
string2 = new char[length2 + 1];
strcpy(string2, rhs.string2);
string2[length2 + 1] = '\0';
}
Derived2 (Derived2 && rhs): Base<T1>(move(rhs)) {
cout <<"Call Move Constructor for Template Derived 2 --->> Base<T1>"<< endl;
string2 = rhs.string2;
length2 = rhs.length2;
rhs.string2 = nullptr;
rhs.length2 = 0;
}
Derived2 & operator=(const Derived2 & rhs) {
cout <<"Call Assignment Operator for Template Derived 2 Class"<< endl;
if (this != &rhs) {
Base<T1>::operator=(rhs);
delete [] string2;
length2 = rhs.length2;
string2 = new char[rhs.length2 + 1];
strcpy(string2, rhs.string2);
string2[length2 + 1] = '\0';
}
return *this;
}
Derived2 & operator=(Derived2 && rhs) {
cout <<"Call Move Assignment Operator for Template Derived 2 Class"<< endl;
if (this != &rhs) {
Base<T1>::operator=(move(rhs));
delete [] string2;
string2 = rhs.string2;
length2 = rhs.length2;
rhs.string2 = nullptr ;
rhs.length2 = 0;
}
return *this;
}
~Derived2() {
cout <<"Call Desstructor for Template Derived 2 --->> Base<T1> "<< endl;
// ~Base<T1>::Base();
delete[] string2;
}
private :
T2 * string2;
int length2;
};
template<typename T1, typename T2, typename T3, typename T4>
class Derived3 : public Derived1<T1, T2>, Derived2<T1, T3> {
public :
Derived3 (T1 * arg1, T2 * arg2, T3 * arg3, T4 * arg4) : Derived1<T1, T2>(arg1, arg2), Derived2<T1, T3>(arg1, arg3) {
cout <<"Call Constructor for Template Derived 3--->> Derived 1, Derived 2 "<< endl;
length3 = strlen(arg3);
string3 = new char[length3 + 1];
strcpy(string3, arg3);
string3[length3 + 1] = '\0';
}
Derived3 (const Derived3 & rhs): Derived1<T1, T2>(rhs), Derived2<T1, T3>(rhs) {
cout <<"Call Copy Constructor for Template Derived 3 --->> Derived 1, Derived 2 "<< endl;
length3 = rhs.length3;
string3 = new char[length3 + 1];
strcpy(string3, rhs.string3);
string3[length3 + 1] = '\0';
}
Derived3 (Derived3 && rhs): Derived1<T1, T2>(move(rhs)), Derived2<T1, T3>(move(rhs)) {
cout <<"Call Move Constructor for Template Derived 3--->> Derived 1, Derived 2"<< endl;
string3 = rhs.string3;
length3 = rhs.length3;
rhs.string3 = nullptr;
rhs.length3 = 0;
}
Derived3 & operator=(const Derived3 & rhs) {
cout <<"Call Assignment Operator for Template Derived 3 --->> Derived 1, Derived 2 "<< endl;
if (this != &rhs) {
Derived1<T1, T2>::operator=(rhs);
Derived2<T1, T3>::operator=(rhs);
delete [] string3;
length3 = rhs.length3;
string3 = new char[rhs.length3 + 1];
strcpy(string3, rhs.string3);
string3[length3 + 1] = '\0';
}
return *this;
}
Derived3 & operator=(Derived3 && rhs) {
cout <<"Call Move Assignment Operator for Template Derived3 --->> Derived 1, Derived 2 " << endl;
if (this != &rhs) {
Derived1<T1, T2>::operator=(move(rhs));
Derived2<T1, T3>::operator=(move(rhs));
delete [] string3;
string3 = rhs.string3;
length3 = rhs.length3;
rhs.string3 = nullptr ;
rhs.length3 = 0;
}
return *this;
}
~Derived3() {
cout <<"Call Desstructor for Template Derived 3 --->> Derived 1, Derived 2 " << endl;
// ~Base<T1>::Base();
delete[] string3;
}
private :
T3 * string3;
int length3;
};
int main(int argc, char * argv[]) {
#if 0
// Here we Check for Copy Const and Assignment Operator
Derived3<char, char, char, char> obj1("pallav1", "puneet1", "Pallav1", "Puneet1");
Derived3<char, char, char, char> obj2("pallav2", "puneet2", "Pallav1", "Puneet1");
Derived3<char, char, char, char> obj3(obj2);
obj3 = obj1;
#endif
#if 1
// Here we Check for Move Const and Move Assignment Operator
Derived3<char, char, char, char> obj11("pallav1", "puneet1", "pallav1", "puneet1");
Derived3<char, char, char, char> obj22("pallav2", "puneet2", "pallav1", "puneet1");
Derived3<char, char, char, char> obj33(move(obj22));
obj33 = move(obj11);
#endif
return 0;
};
|
Python | UTF-8 | 391 | 2.53125 | 3 | [] | no_license | import sys
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table=dynamodb.Table('LAX')
da=sys.argv[1]
year=sys.argv[2]
#print (da)
#print (year)
response = table.scan(FilterExpression=Attr('DA').eq(da) & Attr('Year').eq(year), ProjectionExpression='NOP')
items = response['Items']
sum=0
for item in items:
sum+=int(item['NOP'])
print (sum) |
C++ | UTF-8 | 1,268 | 2.796875 | 3 | [] | no_license | #include <QCoreApplication>
#include <QStringList>
#include <QTextStream>
#include "arguments.h"
Arguments::Arguments()
{
QStringList argList = QCoreApplication::arguments();
QString option;
auto it = argList.begin();
++it; // Skip application name
for (; it != argList.end(); ++it)
{
QString arg = *it;
if (arg.startsWith("--"))
{
option = arg.mid(2);
}
else if (arg.startsWith('-'))
{
option = arg.mid(1);
}
else
{
mArgList[option] = arg;
option.clear();
}
if (!option.isEmpty())
mArgList.insert(option, QString());
}
}
void Arguments::print()
{
QTextStream out{stdout};
for (auto it = mArgList.begin(); it != mArgList.end(); ++it)
{
out << "key = " << it.key() << " value = " << it.value() << "\n";
}
}
void Arguments::help()
{
version();
QTextStream out{stdout};
out << endl
<< "Options:" << endl;
for (auto it = mHelp.begin(); it != mHelp.end(); ++it)
{
out << it.key() << endl
<< "\t" << it.value() << endl;
}
out << endl;
}
void Arguments::version()
{
QTextStream out{stdout};
out << QCoreApplication::applicationName() << " v"
<< QCoreApplication::applicationVersion() << endl;
}
void Arguments::addArg(const QString &arg, const QString &description)
{
mHelp.insert(arg,description);
}
|
PHP | UTF-8 | 3,521 | 2.515625 | 3 | [
"GPL-2.0-only",
"MIT"
] | permissive | <?php
class Ongkoskirim_Id_License {
function __construct($lib=""){
// supaya tidak dobel2 panggil lib
if( empty($lib) )
$this->lib = new Ongkoskirim_Id_Library();
else
$this->lib = $lib;
$this->license_url = "http://store.".$this->lib->domain."/";
$this->product_id = "oid";
$this->option_prefix = "ongkoskirim_id_";
}
function activate($license_key){
$return = array();
// API query parameters
$api_params = array(
'slm_action' => 'slm_activate',
'license_key' => $license_key,
'registered_domain' => $this->get_website_url(),
'item_reference' => $this->product_id,
);
$response = $this->remote_get($api_params);
// Check for error in the response
if (is_wp_error($response)){
$return['status'] = false;
$return['msg'] = "Cannot connect to api server.";
return $return;
}
// License data.
$license_data = json_decode(wp_remote_retrieve_body($response));
if($license_data->result == 'success'){//Success was returned for the license activation
// Uncomment the followng line to see the message that returned from the license server
//echo '<br />The following message was returned from the server: '.$license_data->message;
//Save the license key in the options table
update_option($this->option_prefix . "license_key", $license_key);
update_option($this->option_prefix . "license_status", "active");
update_option($this->option_prefix . "version_type", "1");
$return['status'] = true;
$return['msg'] = $license_data->message;
return $return;
}
else{
$return['status'] = false;
$return['msg'] = $license_data->message;
return $return;
}
}
function deactivate($license_key){
$return = array();
// API query parameters
$api_params = array(
'slm_action' => 'slm_deactivate',
'license_key' => $license_key,
'registered_domain' => $this->get_website_url(),
'item_reference' => $this->product_id,
);
$response = $this->remote_get($api_params);
// Check for error in the response
if (is_wp_error($response)){
$return['status'] = false;
$return['msg'] = "Cannot connect to api server.";
return $return;
}
// License data.
$license_data = json_decode(wp_remote_retrieve_body($response));
if($license_data->result == 'success' || $license_data->message ='The license key on this domain is already inactive'){//Success was returned for the license activation
// Uncomment the followng line to see the message that returned from the license server
//echo '<br />The following message was returned from the server: '.$license_data->message;
//Save the license key in the options table
update_option($this->option_prefix . "license_key", "");
update_option($this->option_prefix . "license_status", "deactivate");
update_option($this->option_prefix . "version_type", "0");
$return['status'] = true;
$return['msg'] = $license_data->message;
return $return;
}
else{
$return['status'] = false;
$return['msg'] = $license_data->message;
return $return;
}
}
private function get_website_url(){
$matches = array();
preg_match_all("#^.+?[^\/:](?=[?\/]|$)#", get_site_url(), $matches);
$website_url = $matches[0][0];
return $website_url;
}
private function remote_get($api_params){
// Send query to the license manager server
$query = esc_url_raw(add_query_arg($api_params, $this->license_url));
return $response = wp_remote_get($query, array('timeout' => 30, 'sslverify' => false));
}
} |
Java | UTF-8 | 897 | 2.375 | 2 | [] | no_license | package com.bonvoyage.daos;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.bonvoyage.models.Users;
import com.bonvoyage.repository.UserRepository;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private UserRepository userRepository;
@Override
public int verifyUser(String user_email, String user_password) {
//boolean b = userRepository.existsById(user_email);
/*
* boolean b = userRepository.existsById(user_password); System.out.println(b);
* return b;
*/
return userRepository.loginUser(user_email, user_password);
}
@Override
public String saveUser(Users users) {
if(userRepository.existsById(users.getUser_email())) {
return "User Already Exists";
}
else {
userRepository.save(users);
return "Saved";
}
}
}
|
C# | UTF-8 | 1,608 | 3.453125 | 3 | [] | no_license | using System;
namespace Chap02_01
{
class Program
{
static void Main(string[] args)
{
// 1바이트 = 8비트
byte a = 100;
// byte 자료형의 size는 1바이트(8bit),
// 표현 범위는 0 ~ 255, 0 ~ 2의 8승 - 1 -> 0
sbyte b = 127;
// byte 자료형의 size는 1바이트(8bit),
// 표현 범위는 -128 ~ 127, -2의 7승 ~ 2의 7승 - 1 -> 0
short c = -5;
// ushort 자료형의 size는 2바이트(16bit),
// 표현 범위는 -32768 ~ 32767, -2의 15승 ~ 2의 15승 - 1 -> 0
ushort d = 200;
// ushort 자료형의 size는 2바이트(16bit),
// 표현 범위는 0 ~ 65535, 0 ~ 2의 16승 - 1 -> 0
int e = 70000;
// int 자료형의 size는 4바이트(32bit),
// 표현 범위는 -2의 31승 ~ 2의 31승 - 1
uint f = 2500000000;
// uint 자료형의 size는 4바이트(32bit),
// 표현 범위는 0 ~ 2의 32승 - 1 ( 42억)
// long, ulong 각각 8바이트
a = 255;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}
}
// 변수, 자료형, 값 형식, 참조 형식
// 변수 : 값을 저장할 때 사용 하는 식별자
// 자료형 : 정수, 실수, 문자 및 문자열, 논리 ( 참 / 거짓 )
// 값 형식 : 스택(stack) 메모리 공간 사용
// 참조 형식 : 힙(heap) 메모리 공간 사용
|
C++ | UTF-8 | 3,101 | 3.25 | 3 | [
"MIT"
] | permissive | #ifndef _DATABASE__
#define _DATABASE__
#include <string>
#include <unordered_map>
#include "sqlite3.h"
#include <vector>
/**
* class DataBase
*
* The abstract class DataBase provide an unified
* interface for managing any king of database
* that supports key-value pair
*/
class DataBase
{
protected:
std::string _dbInstance;
public:
/**
* Open a database connection
* @param id represents the id of connection
* @return the status code of the operation, 0 if the operation was successful
*/
virtual int Open(const std::string id = {}) = 0;
/**
* Get the value associate to the given key from the database
* @param key represents a key in the database
* @return the value associate to the key if the key is present or an empty string
*/
virtual std::string Get(const std::string key) = 0;
/**
* Put a key-value pair in the database
* @param key represents a key in the database
* @param value represent the new value that should be associate to the key
* @return the previous value associate to the key
*/
virtual std::string Put(const std::string key, const std::string value) = 0;
/**
* Select a new active table for the database
* @param tableName is the name of the table that will be activate
* @return the status code of the operation, 0 if the operation was successful
*/
virtual int SelectTable(const std::string tableName) = 0;
/**
* Close a database connection
* @param id represents the id of connection
* @return the status code of the operation, 0 if the operation was successful
*/
virtual int Close(const std::string id = {}) = 0;
/**
* dbInstance return a string representing the
* type of the concrete database instace
*
* @return the db type
*/
std::string dbInstance()
{
return _dbInstance;
}
};
class SQLite : public DataBase
{
private:
typedef struct _res_data
{
std::vector<std::vector<std::string>> results;
std::string op;
_res_data(const std::string &opType) : op(opType) {}
} res_data;
sqlite3 **db = new sqlite3 *();
std::string table;
int static callback(void *data, int nCol, char **colValue, char **colNames);
int createTable(const std::string tableName);
public:
SQLite();
int Open(const std::string = "db");
std::string Get(const std::string key);
std::string Put(const std::string key, const std::string value);
int SelectTable(const std::string tableName);
int Close(const std::string = "db");
};
class InMemoryDB : public DataBase
{
private:
using dbTable = std::unordered_map<std::string, std::string>;
std::string activeTable;
std::unordered_map<std::string, dbTable> *db;
public:
InMemoryDB();
int Open(const std::string = "db");
std::string Get(const std::string key);
std::string Put(const std::string key, const std::string value);
int SelectTable(const std::string tableName);
int Close(const std::string = "db");
};
#endif |
Python | UTF-8 | 1,129 | 3 | 3 | [] | no_license | import matplotlib
matplotlib.use("TkAgg")
import pylab
import networkx as nx
n_m = 100 #number of movable things
n_n = 1 #number of non-movable things
r = 0.1
class agent:
pass
def init():
global agents
agents = []
for i in range(n_m):
ag = agent()
ag.x = pylab.random()
ag.y = pylab.random()
ag.can_move = True
ag.type = 1 #1 means that while the thing might be stuck, it was once moveable
agents.append(ag)
ag = agent()
ag.x = 0.5
ag.y = 0.5
ag.can_move = False
ag.type = 0 #0 means that the thing is and always will be of the immovable type
agents.append(ag)
def update():
global agents
for ag in agents:
if ag.can_move == True:
immovable = [nb for nb in agents if (nb.x-ag.x)**2+(nb.y-ag.y)**2 < r**2 and nb.type == 0 and nb != ag]
if len(immovable) > 0:
ag.can_move=False
else:
ag.x = pylab.random()
ag.y = pylab.random()
def observe():
global agents
pylab.cla()
pylab.plot([nb.x for nb in agents], [nb.y for nb in agents], "ko")
pylab.axis("image")
pylab.axis([0,1,0,1])
pylab.show()
import pycxsimulator
pycxsimulator.GUI().start(func=[init, observe, update])
|
C | UTF-8 | 3,149 | 2.703125 | 3 | [
"Unlicense"
] | permissive | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skunz <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/03 19:21:26 by skunz #+# #+# */
/* Updated: 2018/12/03 19:21:36 by skunz ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
int ft_getlinenb(int fd, t_info *info)
{
char buff[BUFF_SIZE + 1];
int ret;
int counter;
int i;
counter = 0;
info->linedigcount = 0;
while ((ret = read(fd, buff, BUFF_SIZE)) > 0)
{
i = -1;
buff[ret] = '\0';
while (buff[++i])
{
if (buff[i] == '\n')
counter++;
if (ft_isdigit(buff[i]) && (buff[i + 1] == ' ' ||
buff[i + 1] == '\n'))
info->linedigcount++;
}
}
info->linedigcount /= counter;
if (close(fd) == -1 || ret == -1)
return (-1);
return (counter);
}
char **ft_readmap(const char *filename, t_info *info)
{
char **map;
int fd;
int ret;
int i;
i = 0;
if ((fd = open(filename, O_RDWR)) == -1)
return (NULL);
if ((info->linecount = ft_getlinenb(fd, info)) == -1)
return (NULL);
if (!(map = malloc(sizeof(char*) * info->linecount + 1)))
return (NULL);
map[info->linecount] = NULL;
if ((fd = open(filename, O_RDWR)) == -1)
return (NULL);
while ((ret = get_next_line(fd, &map[i])) > 0)
i++;
if (ret == -1)
{
ft_free2d(map, info->linecount);
return (NULL);
}
if ((close(fd)) == -1)
return (NULL);
return (map);
}
int **ft_translate(char **map, t_info info)
{
char **new;
int **conv;
int y;
int x;
y = -1;
if (!(conv = malloc(sizeof(int*) * info.linecount)))
return (NULL);
while (++y < info.linecount)
{
x = -1;
new = ft_strsplit(map[y], ' ');
if (!(conv[y] = malloc(sizeof(int) * info.linedigcount)))
{
ft_free2d(new, y + 1);
return (NULL);
}
while (++x < info.linedigcount)
conv[y][x] = ft_atoi(new[x]);
ft_free2d(new, info.linedigcount);
}
return (conv);
}
t_point *ft_convert(int **new, t_info info, t_mod mod)
{
t_point *point;
int i;
int y;
int x;
i = -1;
y = -1;
if (!(point = malloc(sizeof(t_point) * info.linecount * info.linedigcount)))
return (NULL);
while (++y < info.linecount)
{
x = -1;
while (++x < info.linedigcount)
{
point[++i].color = ft_color(255, 255 - new[y][x] * 10,
255 - new[y][x] * 10);
point[i].x = (x - y) * cos(mod.theta_x);
point[i].y = -(new[y][x] * mod.div) + (x + y) * sin(mod.theta_y);
point[i].x *= 500 / info.linedigcount;
point[i].y *= 500 / info.linecount;
point[i].x += mod.xoffset;
point[i].y += mod.yoffset;
}
}
return (point);
}
|
C# | UTF-8 | 1,648 | 3.203125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Techcraft7_DLL_Pack.Utils
{
public static class OtherUtils
{
public static void InLineSwitch<T>(T value, Dictionary<T[], Action> cases)
{
if (cases.Any(kv => kv.Value == null))
{
throw new ArgumentNullException($"{nameof(cases)} has a null value");
}
//Add all cases to a list,
//remove all duplicates,
//if the size before we removed
//duplicates and the size after
//are not the same,
//then there were repeated cases
List<T> used = new List<T>();
cases.Select(kv => kv.Key).ToList().ForEach(l => l.ToList().ForEach(v => used.Add(v)));
int before = used.Count;
used = used.Distinct().ToList();
if (used.Count != before)
{
throw new ArgumentException("Repeated cases detected!");
}
foreach (KeyValuePair<T[], Action> kv in cases)
{
if (kv.Key.Any(v => value.Equals(v)))
{
kv.Value.Invoke();
}
}
}
public static T IgnoreException<T>(Func<T> func) where T : class
{
func = func ?? throw new ArgumentNullException(nameof(func));
try
{
return func.Invoke();
}
catch
{
return null;
}
}
public static T? IgnoreException<T>(Func<T?> func) where T : struct
{
func = func ?? throw new ArgumentNullException(nameof(func));
try
{
return func.Invoke();
}
catch
{
return null;
}
}
public static void IgnoreException(Action a)
{
a = a ?? throw new ArgumentNullException(nameof(a));
try
{
a.Invoke();
}
catch
{
//Do nothing!
}
}
}
}
|
Python | UTF-8 | 493 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python
import numpy
from sklearn import cluster, datasets
X = [
[2,4],
[3,3],[3,4],
[5,4],[5,6],[5,8],
[6,4],[6,5],[6,7],
[7,3],[7,4],
[8,2],
[9,4],
[10,6],[10,7],[10,8],
[11,5],[11,8],
[12,7],
[13,6],[13,7],
[14,6],
[15,4],[15,5] ];
print len(X)
X = numpy.array(X);
dbscan = cluster.DBSCAN(eps=2, min_samples=3)
db = dbscan.fit( X );
print dir(db)
print db.core_sample_indices_
print len(db.core_sample_indices_)
|
Java | UTF-8 | 351 | 1.5625 | 2 | [] | no_license | package com.repsly.edu.libs;
import android.app.Application;
import com.tumblr.remember.Remember;
/**
* Application cool class.
*/
public class EventApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Remember.init(getApplicationContext(), "com.example.testing.eventbusttest");
}
}
|
C | UTF-8 | 617 | 2.65625 | 3 | [] | no_license | #include<mpi.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc,char** argv){
int rank,size,epp;
int* dataSend=NULL;
int i,n;
float res;
float pie;
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank==0){
printf("Enter the value of n\n");
scanf("%d",&n);
}
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
res=0;
for(i=0;i<n/size;i++){
res+=(4/(1+(((n/size)*rank+0.5+i)/n)*(((n/size)*rank+0.5+i)/n)))/n;
}
MPI_Reduce(&res,&pie,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD);
if(rank==0){
printf("The average is : %f\n",pie);
}
MPI_Finalize();
}
|
C++ | UTF-8 | 1,282 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include "Numeros.h"
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
Numeros * num;
num = new Numeros();
int numero;
int resultado = 0;
vector <int > rango;
vector < int > primos;
int cantPrimos = 0;
clock_t start, finish; //Variables para medir el tiempo.
double time = 0; //Resultado del tiempo transcurrido
start = clock();
int primer_num = 0;
int segundo_num = 0;
int esCuadrado;
int verificar = 0;
cout << "Ingrese un numero entero" << endl;
cin >> numero;
resultado = num->verificarCuadrado(numero);
if(resultado == 1){
for (int i = 1; i <= numero; i++){
primer_num = i;
segundo_num = (i+1);
primer_num = primer_num*primer_num;
segundo_num = segundo_num*segundo_num;
printf( " Pareja de numeros cuadrados: %d %d ",primer_num , segundo_num,"/n");
primos = num->Primos(primer_num,segundo_num);
for(int i = 1; i<=primos.size();i++) {
cantPrimos++;
printf( "Numeros primos: ","/n");
num->imprimir(primos);
}
}
}else{
printf( "No es un raiz cuadrda ","/n");
}
finish = clock();
time = finish - start;
printf("Tiempo transcurrido: %f. \n", time);
return 0;
}
|
JavaScript | UTF-8 | 919 | 3.21875 | 3 | [] | no_license |
const state = {
usersBreedChoice: 'blah'
};
init();
function init(){
handleSubmit();
}
function handleSubmit(){
$('form').submit(function(event){
state.usersBreedChoice = $('.js-query').val();
$('.js-query').val('');
getDataFromAPI(state.usersBreedChoice, displayData);
//handleNextButton();
});
}
function getDataFromAPI(query, callback){
$.getJSON(`https://dog.ceo/api/breed/${query}/images/random`, function(data){
callback(data);
});
}
function displayData(data){
let view = `<img src="${data.message}" />
<button type="submit" class="js-next-btn">Next</button>`
$('.js-search-results').html(view);
handleNextButton();
}
function handleNextButton(){
$('.js-next-btn').on('click', function(data){
console.log('state is ', state.usersBreedChoice);
getDataFromAPI(state.usersBreedChoice, displayData);
});
}
// end of page
|
Java | UTF-8 | 606 | 1.96875 | 2 | [
"MIT"
] | permissive | package com.example.granny.repository;
import com.example.granny.domain.entities.Location;
import com.example.granny.domain.entities.User;
import com.example.granny.domain.entities.VerificationToken;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface LocationRepsitory extends JpaRepository<Location, Integer> {
@Query("SELECT l " +
"FROM Location l" +
" ORDER BY l.name")
List<Location> findAll();
}
|
Markdown | UTF-8 | 1,570 | 2.75 | 3 | [] | no_license | # GENOMEPERI
Python Module for handling SNP txt data
This module can read txt files created by either 23&Me or Ancestry.com
The resulting SNP_GENOME object has a list RSINDEX which can be used to call SNP data from the dictionary GENOME
SNP_GENOME objects have two dictionaries: .GENOME and .CHROMOSOME_COUNT_LOG
.GENOME is searcheable by RSID string and gives a SNP result if there is no KeyError
.CHROMOSOME_COUNT_LOG is searchable by Chromosome ID integer (see below) - if gives the total number of SNP reads at that chromosome
The object method SEQUENCEQC() evaluates the SNP_GENOME and gives a score of how many SNPS have both alleles properly read (A,T,C,or G)
The function GENOME_COMPARE() looks at two SNP_GENOMEs and scores the identity of matched RSIDs
The function CHROMOSOME_COMPARE() matches RSIDs and scores identity by chromosome
DISPLAY_CHROMOSOME_SCORES() displays the results of CHROMOSOME_COMPARE()
*Note on Chromosome ID number: All reads on Chromosome X are marked as Chromosome 23, Y is 24, and Mitochondria is 26.*
The 23&Me data I have uses strings 'X', 'Y', and 'MT' - however my datasets are both from males.
My Ancestry.com dataset uses integers 23 AND 25 for X - this is my female dataset.
SNP_GENOME objects use integers to harmonize these different formats, however all
Chromosome X reads are consolidated - a future feature could be separate X identities to determine multigeneration inheritance.
If you are using 23&Me data from a female and have more information feel free to contact me so I can have the code handle this.
|
Java | UTF-8 | 9,788 | 2.6875 | 3 | [] | no_license | package controller;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Optional;
import java.util.ArrayList;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import application.MyStage;
import javafx.animation.AnimationTimer;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
import models.Animal;
import models.BackgroundImage;
import models.Digit;
import models.Frogger;
import models.FroggerB;
import models.FroggerLife;
import models.TextButton;
import sceneFactory.ScoreFactory;
import sceneView.MainView;
/**
* this class defines the basic controls for the main game
* @author Luer Lyu
*
*/
public abstract class MainController extends Controller{
int highestScore;
boolean multi;
String fileName = "HighScore.txt";
AnimationTimer timer;
Frogger frog1;
FroggerB frog2;
MyStage background;
int yPosScore = 40;
ArrayList<FroggerLife> lives;
int livesCount = 2;
int[] highScoreList;
String[] highScoreNames;
String Name;
Digit digit_s;
Digit digit_h;
// current level of the game
public int level = 1;
public int[] prevScores = {-100,-100,-100,-100,-100};
public int scorePrev =0;
ScoreFactory scoreFactory;
TextButton pause;
TextButton resume;
BackgroundImage pausebkgd;
boolean pass = false;
/**
* constructor to get the models in the scene
* @param mainSceneView the view class which decides the look of the scene
*/
public MainController(MainView mainSceneView) {
this.timer = mainSceneView.getTimer();
this.frog1 = Frogger.getAnimal();
this.frog2 = FroggerB.getAnimal();
frog1.setDefault();
this.background = mainSceneView.getStage();
this.lives = mainSceneView.getLives();
this.highestScore = mainSceneView.getHighestScore();
this.highScoreList = mainSceneView.getScoreList();
this.highScoreNames = mainSceneView.getScoreName();
this.pause = mainSceneView.getPause();
pause();
}
/**
* bind the pause button with the pause function
*/
public void pause() {
pause.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
background.stop();
stop();
pausebkgd = new BackgroundImage("file:img/pausePage.png");
resume = new TextButton("file:img/resume.png",220,350,140);
background.add(pausebkgd);
background.add(resume);
bindButton();
}
});
}
/**
* bind the button with resume function
*/
private void bindButton() {
resume.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
background.remove(resume);
background.remove(pausebkgd);
timer.start();
background.start();
}
});
}
/**
* create a timer
*/
abstract public void createTimer();
/**
* ask user for the name input
*/
public void NamePrompt() {
background.add( new BackgroundImage("file:img/catbkgd.png") );
TextButton btn = new TextButton("file:img/continue.png",220,350,140);
setButtonAnimation(btn);
background.add(btn);
if(frog1.win()) {
background.add(new TextButton("file:img/win.png",60,40,450));
}else{
background.add(new TextButton("file:img/lose.png",85,40,400));
}
}
/**
* change the style of button when mouse hovers
* @param btn the button object
*/
public void setButtonAnimation(TextButton btn) {
btn.setOnMouseClicked(
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
buttonEvent();
}
});
btn.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
btn.changeImage("file:img/continue2.png",220,350,145);
}
});
btn.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
btn.changeImage("file:img/continue.png",220,350,140);
}
});
}
/**
* this describes the click event when button
* continue is clicked
*/
public void buttonEvent() {
while(!pass) {
TextInputDialog dialog = configureDialog();
Optional<String> result = dialog.showAndWait();
if (result.isPresent()){
Name = result.get();
checkValid(Name);
}
else {
try {
writeScore();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* configure the content of the dialog
* @return TextInputDialog the dialog been prompted
*/
public TextInputDialog configureDialog() {
TextInputDialog dialog = new TextInputDialog("e.g. aaa");
dialog.setTitle("Get Your Score On Board!");
dialog.setHeaderText("Enter Your Name");
dialog.setContentText("Please enter your name\n"
+ "if you want your score to be recorded:\n"
+"(Name must be three letters)");
return dialog;
}
/**
* check of the name input is valid or not
* @param Name represents the input string
*/
public void checkValid(String Name) {
//ensure the name entered is valid
if(Name.matches("[a-zA-Z]*")&&Name.length()==3) {
pass = true;
insertScore();
try {
writeScore();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* insert the score and name from this round to the array
* containing history score if applicable
*/
public void insertScore() {
int current = Animal.getPoints();
int temp;
String tempName;
for(int i=0;i<highScoreList.length;i++) {
//insert the current the score if applicable
if(highScoreList[i] == 0) {
highScoreList[i] = current;
highScoreNames[i] = Name;
break;
}else {
if(current>highScoreList[i]) {
temp = highScoreList[i];
tempName = highScoreNames[i];
highScoreList[i] = current;
highScoreNames[i] = Name;
current = temp;
Name = tempName;
}
}
}
}
/**
* write the array consisting of all history score to the file
* @throws IOException if the file cannot be found
*/
public void writeScore() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
for(int i =0;i<10;i++) {
printWriter.print(highScoreList[i] + "\n");
if(highScoreNames[i] == "\n"|| highScoreNames[i] == null) {
printWriter.print("aaa\n");
}else {
printWriter.print(highScoreNames[i] + "\n");
}
}
printWriter.close();
scoreFactory.init(Animal.getPoints(),multi);
}
/**
* create and start the timer, play music
*/
public void start() {
background.playMusic("music/FroggerMainSong.mp3",true);
createTimer();
timer.start();
}
/**
* stop the timer
*/
public void stop() {
timer.stop();
}
/**
* print the current highest score
* @param n current points for the game
*/
public void updateNumber(int n) {
// if new score has been created
if(highestScore < n) {
digit_h = printNumber(320,yPosScore,n,digit_h);
}else {
digit_h = printNumber(320,yPosScore,highestScore,digit_h);
}
}
/**
* print the current score on the screen
* @param x the x position of the digit
* @param y the y position of the digit
* @param n the number need to be printed
* @param digit the Digit object from the previous print representing the highest digit
* @return the Digit object on the highest weight in this round
*/
public Digit printNumber(int x, int y, int n, Digit digit) {
int shift = 0;
Digit temp = null;
if(digit != null) {
background.remove(digit);
}
if(n == 0) {
temp = new Digit(0, 30, x, y);
background.add(temp);
}
while (n > 0) {
int d = n / 10;
int k = n - d * 10;
n = d;
temp = new Digit(k, 30, x - shift, y);
background.add(temp);
shift+=30;
}
return temp;
}
/**
* update the number of lives left in this class
*/
public void updateLives() {
background.remove(lives.get(livesCount));
lives.remove(livesCount);
showAlert();
livesCount--;
}
/**
* when a round ends, an alert containing the points gained and ranking will pop up
*/
public void showAlert() {
Alert alert = new Alert(AlertType.INFORMATION);
if(livesCount>0) {
alert.setTitle("Checkout the summary for this round!");
prevScores[level-1]=Animal.getPoints()-scorePrev;
alert.setHeaderText("You Gained "+prevScores[level-1]+" points!");
sortRoundScores();
String info ="Ranking For The Scores: \n";
for(int i=0;i<level;i++) {
info+=(i+1)+": "+prevScores[i]+"\n";
}
alert.setContentText(info);
alert.show();
}
scorePrev = Animal.getPoints();
level++;
}
/**
* this function sorts the scores so far
* within the array prevScores
*/
public void sortRoundScores() {
Arrays.sort(prevScores);
//reverse the array
for(int i = 0; i < prevScores.length / 2; i++)
{
int temp = prevScores[i];
prevScores[i] = prevScores[prevScores.length - i - 1];
prevScores[prevScores.length - i - 1] = temp;
}
}
/**
* instantiate the factory to build the score scene
* @param primaryStage the stage used to display the scene
*/
public void createScoreFactory(Stage primaryStage) {
scoreFactory = new ScoreFactory(primaryStage);
}
/**
* add frog if there are multiple players
* @param multi true if there are multiple players, otherwise false
*/
public void addFrog(boolean multi) {
this.multi = multi;
if(multi) {
background.add(frog2);
}
}
}
|
C | UTF-8 | 435 | 2.890625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2021
** output_last_char
** File description:
** antman
*/
#include "my.h"
list_t *output_last_char(list_t *chars, char *file, int i)
{
infos_t info;
for (int j = 0, len = len_list(chars); j < len; j++) {
if (get_at(chars, j).c == file[i]) {
info.output = get_at(chars, j).index;
chars = add_at(chars, info, len);
break;
}
}
return (chars);
} |
Markdown | UTF-8 | 1,531 | 2.6875 | 3 | [] | no_license | # Smart Library Application
It can be use like a Book Library. Where student can Issue book and Return book easily.It is very easy application and functionalities are easily implemented. In this application, Student can easily See the available books and Issue or Return books. This project will be useful to the people who are interested in reading books.
## Getting Started
### Prerequisites
1. Windows7/Windows8/Windows10.
1. eclipse.
1. sqlite database.
1. Jtatto.
### Installing
```
Clone/Download Zip
```
```
Go to eclipse.
```
```
Open this project.
```
```
Copy the current directory.
```
```
Open javaConnect.java on src.
```
```
Edit ,and Paste the connection String And Save.
```
```
For demo data use Username : niloy and Password : 123456
```
<a href="https://imgflip.com/gif/29t893"><img src="https://i.imgflip.com/2ab1au.gif" title="made at imgflip.com"/></a>
### Modules
1. Student
1. System Admin
## Built With
* [java](https://www.java.com/en/) - The language
* [JTattoo](http://www.jtattoo.net/) - FrontEnd Framework
* [sqlite](https://www.sqlite.org/index.html) - Used Database
## Contributing
### Create a branch
1. `git checkout master` from any folder in your local `reactjs.org` repository
1. `git pull origin master` to ensure you have the latest main code
1. `git checkout -b the-name-of-my-branch` (replacing `the-name-of-my-branch` with a suitable name) to create a branch
## Authors
* **Noboranjan Dey**
## Acknowledgments
* comfortable UI.
* Best application for beginners.
* etc
|
Java | UTF-8 | 2,941 | 2.625 | 3 | [] | no_license | package client.testing.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
public class IOUtils
{
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final String DEFAULT_CHARSET = "UTF-8";
public IOUtils() {}
private static long copy(Reader paramReader, Writer paramWriter)
throws IOException
{
return copy(paramReader, paramWriter, new char['?']);
}
private static long copy(Reader paramReader, Writer paramWriter, char[] paramArrayOfChar)
throws IOException
{
long l = 0L;
for (int i = paramReader.read(paramArrayOfChar); i > 0; i = paramReader.read(paramArrayOfChar))
{
paramWriter.write(paramArrayOfChar, 0, i);
l += i;
}
return l;
}
public static String readAll(InputStream paramInputStream)
throws IOException
{
return readAll(paramInputStream, "UTF-8");
}
public static String readAll(InputStream paramInputStream, String paramString)
throws IOException
{
paramInputStream = new InputStreamReader(paramInputStream, paramString);
try
{
paramString = readAll(paramInputStream);
paramInputStream.close();
return paramString;
}
catch (Throwable paramString)
{
try
{
throw paramString;
}
catch (Throwable localThrowable)
{
if (paramString != null) {
try
{
paramInputStream.close();
}
catch (Throwable paramInputStream)
{
paramString.addSuppressed(paramInputStream);
}
} else {
paramInputStream.close();
}
throw localThrowable;
}
}
}
public static String readAll(InputStream paramInputStream, Charset paramCharset)
throws IOException
{
return readAll(paramInputStream, paramCharset.name());
}
public static String readAll(InputStreamReader paramInputStreamReader)
throws IOException
{
StringWriter localStringWriter = new StringWriter();
copy(paramInputStreamReader, localStringWriter);
return localStringWriter.toString();
}
public static void writeAll(String paramString, OutputStream paramOutputStream)
throws IOException
{
writeAll(paramString, paramOutputStream, "UTF-8");
}
public static void writeAll(String paramString1, OutputStream paramOutputStream, String paramString2)
throws IOException
{
if ((paramString1 != null) && (paramString1.length() > 0)) {
paramOutputStream.write(paramString1.getBytes(paramString2));
}
}
public static void writeAll(String paramString, OutputStream paramOutputStream, Charset paramCharset)
throws IOException
{
writeAll(paramString, paramOutputStream, paramCharset.name());
}
}
|
PHP | UTF-8 | 426 | 3.140625 | 3 | [] | no_license | <?php
$persona1='pedro';
$persona2='juan';
$_persona3='carlos';
function saludar(){
global $persona1;
echo "hola".$persona1;
}
//saludar();
$a=true;
$b=2;
$c=2.76;
$d='a';
$e=[1,2,3];
$f=new stdClass();
$g=NULL;
echo ' '.gettype($a);
echo ' '.gettype($b);
echo ' '.gettype($c);
echo ' '.gettype($d);
echo ' '.gettype($e);
echo ' '.gettype($f);
echo ' '.gettype($g);
?>
|
Shell | UTF-8 | 651 | 3.359375 | 3 | [] | no_license | #!/bin/bash
if [ $# == 0 ]
then
read -p "Enter 1st Number " n1
read -p "Enter 2nd Number " n2
echo "Sum is:"
echo `expr $n1 + $n2`
echo "Difference is:"
echo `expr $n1 - $n2`
echo 'Product is: '
echo `expr $n1 \* $n2`
if [ n2 != 0 ]
then
echo 'Division is:'
echo `expr $n1 / $n2`
fi
if [ n2 = 0 ]
then
echo 'Wrong Input'
fi
fi
if [ $# != 0 ]
then
echo 'Sum is:' `expr $1 + $2`
echo 'Product is:' `expr $1 \* $2`
echo 'Difference is:' `expr $1 - $2`
if [ $2 = 0 ]
then
echo 'Wrong input'
fi
if [ $2 != 0 ]
then
echo 'Division is:' `expr $1 / $2`
fi
echo 'Mod is: ' `expr $1 % $2`
fi
|
C++ | UTF-8 | 1,667 | 2.515625 | 3 | [] | no_license | #ifndef SKYBOX_H
#define SKYBOX_H
#ifdef __APPLE__
#include <OpenGL/gl3.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl.h> // Remove this line in future projects
#else
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Skybox
{
public:
vector<std::string> faces =
{
/*"right.jpg",
"left.jpg",
"top.jpg",
"bottom.jpg",
"front.jpg",
"back.jpg"*/
"plains-of-abraham_rt.tga",
"plains-of-abraham_lf.tga",
"plains-of-abraham_up.tga",
"plains-of-abraham_dn.tga",
"plains-of-abraham_bk.tga",
"plains-of-abraham_ft.tga"
};
const GLfloat skyboxVertices[8][3] = {
// "Front" vertices
{-250.0, -50.0, 250.0}, {250.0, -50.0, 250.0}, {250.0, 450.0, 250.0}, {-250.0, 450.0, 250.0},
// "Back" vertices
{-250.0, -50.0, -250.0}, {250.0, -50.0, -250.0}, {250.0, 450.0, -250.0}, {-250.0, 450.0, -250.0}
};
// Note that GL_QUADS is deprecated in modern OpenGL (and removed from OSX systems).
// This is why we need to draw each face as 2 triangles instead of 1 quadrilateral
const GLuint indices[6][6] = {
// Front face
{0, 1, 2, 2, 3, 0},
// Top face
{1, 5, 6, 6, 2, 1},
// Back face
{7, 6, 5, 5, 4, 7},
// Bottom face
{4, 0, 3, 3, 7, 4},
// Left face
{4, 5, 1, 1, 0, 4},
// Right face
{3, 2, 6, 6, 7, 3}
};
unsigned int cubeMapTex;
GLint uProjection, uView;
GLuint skyboxVAO, VBO, EBO;
GLint norm;
static float typeColor;
Skybox();
~Skybox();
unsigned int loadCubeMap(vector<string>);
void draw(GLint);
};
#endif
|
Java | UTF-8 | 5,240 | 1.960938 | 2 | [] | no_license | package com.jameswong.worklist.fragment;
import android.support.design.widget.NavigationView;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.jameswong.worklist.MainActivity;
import com.jameswong.worklist.R;
import com.jameswong.worklist.database.AlarmDBSupport;
import com.jameswong.worklist.models.CalendarEvent;
import com.jameswong.worklist.pager.AboutMePager;
import com.jameswong.worklist.pager.BasePager;
import com.jameswong.worklist.pager.DayPager;
import com.jameswong.worklist.pager.HomePager;
import com.jameswong.worklist.pager.WeekPager;
import com.jameswong.worklist.utils.BusProvider;
import com.jameswong.worklist.utils.CalendarManager;
import com.jameswong.worklist.utils.Events;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class ContentFragment extends BaseFragment {
@Bind(R.id.vp_content)
ViewPager vpContent;
private List<BasePager> mPageList;
private NavigationView navigationView;//菜单栏
private DrawerLayout drawerLayout;//DrawerLayout
private List<CalendarEvent> eventList;
private AlarmDBSupport support;
private HomePager homePager;
private DayPager dayPager;
private WeekPager weekPager;
private AboutMePager aboutMePager;
@Override
public View initView() {
View view = View.inflate(mActivity, R.layout.fragment_content, null);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
homePager.destroy();
}
@Override
public void initDate() {
homePager = new HomePager(mActivity);
dayPager = new DayPager(mActivity);
weekPager = new WeekPager(mActivity);
aboutMePager = new AboutMePager(mActivity);
//主界面添加数据
mPageList = new ArrayList<>();
mPageList.add(homePager);
mPageList.add(dayPager);
mPageList.add(weekPager);
mPageList.add(aboutMePager);
vpContent.setAdapter(new VpContentAdapter());
//获取侧边栏
MainActivity mainUi = (MainActivity) mActivity;
navigationView = mainUi.getNavigationView();
navigationView.setCheckedItem(R.id.schedule);
buildHomePager();
drawerLayout = mainUi.getDrawerLayout();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.schedule:
vpContent.setCurrentItem(0, false);//设置当前的页面,取消平滑滑动
buildHomePager();
BusProvider.getInstance().send(new Events.OpenHeaderView());
break;
case R.id.day:
vpContent.setCurrentItem(1, false);
dayPager.initData();
BusProvider.getInstance().send(new Events.OpenHeaderView());
break;
case R.id.week:
vpContent.setCurrentItem(2, false);
weekPager.initData();
BusProvider.getInstance().send(new Events.OpenHeaderView());
break;
case R.id.aboutMe:
vpContent.setCurrentItem(3, false);
aboutMePager.initData();
BusProvider.getInstance().send(new Events.CloseHeaderView());
break;
}
item.setChecked(true);//点击了设置为选中状态
drawerLayout.closeDrawers();
return true;
}
});
}
/**
* 主界面设置
*/
private void buildHomePager() {
homePager.initData();
BusProvider.getInstance().toObserverable().subscribe(event -> {
if (event instanceof Events.GoBackToDay) {
homePager.agenda_view.getAgendaListView().scrollToCurrentDate(CalendarManager.getInstance().getToday());
}
});
}
/**
* viewPager数据适配器
*/
class VpContentAdapter extends PagerAdapter {
@Override
public int getCount() {
return mPageList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
BasePager pager = mPageList.get(position);
container.addView(pager.mRootView);
return pager.mRootView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mPageList.get(position).mRootView);
}
}
}
|
Ruby | UTF-8 | 171 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def oxford_comma(array)
case array.size
when 1
return array.first
when 2
return array.join(' and ')
else array << "and #{array.pop}"
return array.join(', ')
end
end
|
Markdown | UTF-8 | 325 | 2.578125 | 3 | [
"MIT"
] | permissive | # manicMiner-taoSdl
This is the simplified classes diagram, which might give you a clue on how
the program is structured:

Also, in this folder you can find the a little documentation for the game,
such as the [original levels](./originalLevels) and the [original sprites](./originalSprites).
|
C# | UTF-8 | 2,223 | 2.59375 | 3 | [] | no_license | using NUnit.Framework;
using RestSharp;
using RestSharpWithSpecFlow.Model;
using System.Collections.Generic;
namespace RestSharpWithSpecFlow
{
[TestFixture]
public class Tests
{
[Test]
public void TestGetRequest()
{
var restClient = new RestClient("http://localhost:3000/");
var request = new RestRequest("posts/{postid}", Method.GET);
request.AddUrlSegment("postid", 1);
var response = restClient.Execute(request);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
var result = outputData["author"];
Assert.That(result, Is.EqualTo("typicode"), "Author is not correct");
}
[Test]
public void TestPostRequest()
{
var restClient = new RestClient("http://localhost:3000/");
var request = new RestRequest("posts/{postid}/profile", Method.POST);
request.AddJsonBody(new { name = "raju" });
request.AddUrlSegment("postid", 3);
var response = restClient.Execute(request);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
var result = outputData["name"];
Assert.That(result, Is.EqualTo("raju"), "Author is not correct");
}
// [Test]
// public void TestPostRequestWithModelClass()
// {
// var restClient = new RestClient("http://localhost:3000/");
// var request = new RestRequest("posts", Method.POST);
// request.AddJsonBody(new Posts() { id = "22", author = "Rezaul", title = "Tutorial" });
// var response = restClient.Execute(request);
// var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
// var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
// var result = outputData["author"];
// Assert.That(result, Is.EqualTo("Rezaul"), "Author is not correct");
// }
}
} |
Java | UTF-8 | 822 | 1.789063 | 2 | [] | no_license | package eg.ipvii.fotp.proxy;
import net.minecraft.item.Item;
//import eg.ipvii.fotp.tileentity.TileEntityJar;
//import eg.ipvii.fotp.tileentity.render.RendererJar;
//import net.minecraft.item.Item;
//import net.minecraftforge.client.model.ModelLoader;
//import net.minecraftforge.fml.client.registry.ClientRegistry;
public class ClientProxy implements CommonProxy {
@Override
public void registerItemRenderer(Item item, int meta, String id) {
//ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(References.MOD_ID + ":" + id, "inventory"));
}
// @Override
// public void init() {
// ModItems.registerRenders();
// ModBlocks.registerRenders();
// ClientRegistry.bindTileEntitySpecialRenderer(TileEntityJar.class, new RendererJar());
// }
}
|
Java | UTF-8 | 1,307 | 2.671875 | 3 | [] | no_license | package fr.eseo.poo.projet.artiste.vue.formes;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import fr.eseo.poo.projet.artiste.modele.Coordonnees;
import fr.eseo.poo.projet.artiste.modele.formes.Ligne;
import fr.eseo.poo.projet.artiste.vue.ihm.PanneauDessin;
public class VueLigneTest {
public VueLigneTest() {
testAffichage();
}
private void testAffichage() {
JFrame test = new JFrame("Teste Ligne");
Container content = test.getContentPane();
PanneauDessin panD = new PanneauDessin();
content.add(panD);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setBounds(500, 500, 400, 240);
Ligne ligne1 = new Ligne(new Coordonnees(40, 50), 50, 100);
Ligne ligne2 = new Ligne(new Coordonnees(100, 159), 10, -66);
Ligne ligne3 = new Ligne(new Coordonnees(340, 250), 300, 20);
ligne1.setCouleur(Color.BLUE);
ligne2.setCouleur(Color.GRAY);
ligne3.setCouleur(Color.RED);
panD.ajouterVueForme(new VueLigne(ligne1));
panD.ajouterVueForme(new VueLigne(ligne2));
panD.ajouterVueForme(new VueLigne(ligne3));
test.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new VueLigneTest();
}
});
}
}
|
C++ | UTF-8 | 2,912 | 2.890625 | 3 | [] | no_license | #include "LinearAlgebra/dense/memory_chunk_aliasing_p.hpp"
#include "LinearAlgebra/dense/matrix.hpp"
#include "LinearAlgebra/dense/matrix_view.hpp"
#include "LinearAlgebra/dense/vector.hpp"
#include "LinearAlgebra/dense/vector_view.hpp"
#include <gtest/gtest.h>
using namespace LinearAlgebra;
TEST(Memory_Chunck_Aliasing, vector)
{
Vector<int> V1(10);
Tiny_Vector<int, 4> V2;
EXPECT_FALSE(are_not_aliased_p(V1, V1));
EXPECT_TRUE(are_not_aliased_p(V1, V2));
EXPECT_TRUE(are_possibly_aliased_p(V1, V1));
EXPECT_FALSE(are_possibly_aliased_p(V1, V2));
auto V1_view_1 = create_vector_view(V1, 2, 5);
auto V1_view_2 = create_vector_view(V1.as_const(), 6, 8);
EXPECT_TRUE(are_not_aliased_p(V1_view_1, V1_view_2));
EXPECT_TRUE(are_possibly_aliased_p(V1_view_2, V1));
EXPECT_TRUE(are_possibly_aliased_p(V1, V1_view_2));
EXPECT_FALSE(are_possibly_aliased_p(V2, V1_view_2));
}
TEST(Memory_Chunck_Aliasing, matrix)
{
Matrix<int> M1(10, 10);
Tiny_Matrix<int, 4, 3> M2;
EXPECT_FALSE(are_not_aliased_p(M1, M1));
EXPECT_TRUE(are_not_aliased_p(M1, M2));
EXPECT_TRUE(are_possibly_aliased_p(M1, M1));
EXPECT_FALSE(are_possibly_aliased_p(M1, M2));
auto M1_view_1 = create_matrix_view(M1, 2, 5, 4, 6);
auto M1_view_2 = create_matrix_view(M1.as_const(), 6, 8, 4, 6);
auto M1_view_3 = create_matrix_view(M1.as_const(), 2, 5, 2, 4);
// CAVEAT: this is not a bug, they are considered aliased as the
// whole column is "stored" (leading dimension > I_size)
//
// 0 1 1 0
// 0 1 1 0
// 0 1 1 0
// 0 0 0 0
// 0 2 2 0
// 0 2 2 0
EXPECT_TRUE(are_possibly_aliased_p(M1_view_1, M1_view_2));
// Ok here as columns are different
//
// 0 0 0 0 0
// 3 3 1 1 0
// 3 3 1 1 0
// 3 3 1 1 0
// 0 0 0 0 0
// 0 0 0 0 0
EXPECT_TRUE(are_not_aliased_p(M1_view_1, M1_view_3));
EXPECT_TRUE(are_possibly_aliased_p(M1_view_2, M1));
EXPECT_TRUE(are_possibly_aliased_p(M1, M1_view_2));
EXPECT_FALSE(are_possibly_aliased_p(M2, M1_view_2));
}
// Mix of matrix and vector (->think to diagonal or row/col views)
//
TEST(Memory_Chunck_Aliasing, matrix_vector)
{
Matrix<int> M1(10, 10);
auto diagonal = create_vector_view_matrix_diagonal(M1);
Vector<double> V1(10);
EXPECT_TRUE(are_not_aliased_p(M1, V1));
EXPECT_TRUE(are_possibly_aliased_p(M1, diagonal));
}
|
Python | UTF-8 | 304 | 3.640625 | 4 | [] | no_license | def unlimied_item(*args, **keyword_args):
for key , items in keyword_args.items():
print('{} : {}'.format(key,items))
for i in args:
print(i)
unlimied_item(1,3,4,4,name='rakib',age=22)#1 to 5
unlimied_item(*[1,2,3,4])#1 to 5
print("THE elements are {} ,{} ,{}".format(*[1,2,3]))
|
Java | UTF-8 | 1,552 | 3.25 | 3 | [] | no_license | import java.io.*;
public class Printer {
private final Reader reader;
Printer(String path) throws FileNotFoundException {
reader = new FileReader(getClass().getResource(path).getFile());
}
Printer(InputStream in) {
// usato nei test, dove non si legge un file, ma si genera un input stream
reader = new InputStreamReader(in);
}
public static void main(String[] args) throws IOException {
Printer printer = new Printer("text.txt");
String outputFileName = "text.txt.copy";
PrintWriter fileOut = new PrintWriter(new FileWriter(outputFileName));
var list = printer.loadData();
System.out.println("\nPrint forward with DoNothingStrategy and Stats");
printer.printData(new StatLineWriterDecoractor(new LineForwardWriter(System.out,new DoNothingStrategy(),list),'a'));
System.out.println("\nPrint backward with UpperCaseStrategy and Stats");
printer.printData(new StatLineWriterDecoractor(new LineBackwardWriter(System.out, new UpperCaseStrategy(),list),'a'));
}
void printData(LineWriter currentLineWriter) {
currentLineWriter.printAllLines();
}
MyList<String> loadData() throws IOException {
MyList<String> myList = new MyList<>();
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
while(line != null) {
myList.addElement(line);
line = bufferedReader.readLine();
}
return myList;
}
}
|
Swift | UTF-8 | 3,676 | 2.84375 | 3 | [] | no_license | //
// ListOfPhotosViewController.swift
// Photos
//
// Created by Marat Shagiakhmetov on 05.05.2021.
//
import UIKit
import Alamofire
class ListOfPhotosViewController: UITableViewController {
var wallpapers: [Wallpaper] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 500
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
wallpapers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! WallpapersCell
let wallpaper = wallpapers[indexPath.row]
cell.configure(with: wallpaper)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension ListOfPhotosViewController {
func fetchWallpapers() {
guard let url = URL(string: URLLinks.imageURLSix.rawValue) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.wallpapers = try decoder.decode([Wallpaper].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let error {
print(error)
}
}.resume()
}
func alamofireGet() {
AF.request(URLLinks.imageURLSix.rawValue)
.validate()
.responseJSON { dataResponse in
switch dataResponse.result {
case .success(let value):
self.wallpapers = Wallpaper.getWallpapers(from: value)
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print(error)
}
}
}
func alamofirePost() {
let wallpapers = WallpaperAlamofirePost(
id: "164",
author: "Linh Nguyen",
width: 1200,
height: 800,
url: "https://unsplash.com/photos/agkblvPff5U",
downloadUrl: URLLinks.imageURLEight.rawValue
)
AF.request(URLLinks.imageURLSeven.rawValue, method: .post, parameters: wallpapers)
.validate()
.responseDecodable(of: WallpaperAlamofirePost.self) { dataResponse in
switch dataResponse.result {
case .success(let wallpapersAlamofirePost):
let wallpaper = Wallpaper(
id: wallpapersAlamofirePost.id,
author: wallpapersAlamofirePost.author,
width: wallpapersAlamofirePost.height,
height: wallpapersAlamofirePost.width,
url: wallpapersAlamofirePost.url,
downloadUrl: wallpapersAlamofirePost.downloadUrl
)
self.wallpapers.append(wallpaper)
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print(error)
}
}
}
}
|
Java | UTF-8 | 1,012 | 2.328125 | 2 | [] | no_license | package VYtrack;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
import pages.LoginPage;
import utils.BrowserUtils;
import utils.ConfigurationReader;
import utils.Driver;
public class LoginTests extends TestBase {
@Test(description = "verify that page title='Dashboard'")
public void tes01(){
//crate page object
LoginPage loginPage= new LoginPage();
// call login method
// provide username and password
String userName= ConfigurationReader.getProperty("userName");
String passWord= ConfigurationReader.getProperty("passWord");
loginPage.login(userName,passWord);
// verification
BrowserUtils.wait(10);
WebDriverWait wait= new WebDriverWait(Driver.get(),10);
wait.until( ExpectedConditions.titleIs("Dashboard"));
Assert.assertEquals(Driver.get().getTitle(),"Dashboard");
}
}
|
Java | UTF-8 | 1,185 | 2.125 | 2 | [] | no_license | /**
* Hana Project
* Copyright 2014 iRush Co.,
*
*/
package com.hanaph.gw.ea.person.service;
import java.util.List;
import java.util.Map;
import com.hanaph.gw.ea.person.vo.PersonLineVO;
/**
* <pre>
* Class Name : PersonLineService.java
* 설명 : 개인결재라인 Master Service
*
* Modification Information
* 수정일 수정자 수정 내용
* ------------ -------------- --------------------------------
* 2014. 12. 30. CHOIILJI
* </pre>
*
* @version : 1.0
* @author : CHOIILJI(choiilji@irush.co.kr)
* @since : 2014. 12. 30.
*/
public interface PersonLineService {
/**
*
* <pre>
* 1. 개요 : 개인결재라인 Master
* 2. 처리내용 : 개인결재라인 Master 리스트
* </pre>
* @Method Name : getPersonLineList
* @param paramMap
* @return
*/
public List<PersonLineVO> getPersonLineList(Map<String, String> paramMap);
/**
*
* <pre>
* 1. 개요 : 개인결재라인 Master
* 2. 처리내용 : 개인결재라인 Master 삭제
* </pre>
* @Method Name : deletePersonLine
* @param cooperationVO
* @return
*/
public int deletePersonLine(Map<String, String> paramMap);
}
|
Shell | UTF-8 | 533 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
# {{ ansible_managed }}
# Starts the Mesos master process for cluster '{{ mesos_cluster_name }}'.
ulimit {{ mesos_ulimit_options }}
MESOS_MASTER_ARGS=(
--cluster='{{ mesos_cluster_name }}'
--ip='{{ mesos_ip }}'
--log_dir='{{ mesos_log_dir }}/{{ safe_mesos_cluster_name }}/master'
--port='{{ mesos_master_port }}'
--quorum='{{ mesos_quorum_size }}'
--work_dir='{{ mesos_work_dir }}/{{ safe_mesos_cluster_name }}/master'
--zk="$(cat /etc/mesos/zk)"
)
exec /usr/sbin/mesos-master "${MESOS_MASTER_ARGS[@]}"
|
Markdown | UTF-8 | 1,504 | 2.515625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: LVM_SETTOOLTIPS message (Commctrl.h)
description: Sets the tooltip control that the list-view control will use to display tooltips. You can send this message explicitly or use the ListView\_SetToolTips macro.
ms.assetid: 5b4335a4-e9f0-4b13-b00b-516af3b60bf1
keywords:
- LVM_SETTOOLTIPS message Windows Controls
topic_type:
- apiref
api_name:
- LVM_SETTOOLTIPS
api_location:
- Commctrl.h
api_type:
- HeaderDef
ms.topic: reference
ms.date: 05/31/2018
---
# LVM\_SETTOOLTIPS message
Sets the tooltip control that the list-view control will use to display tooltips. You can send this message explicitly or use the [**ListView\_SetToolTips**](/windows/desktop/api/Commctrl/nf-commctrl-listview_settooltips) macro.
## Parameters
<dl> <dt>
*wParam*
</dt> <dd>Handle to the tooltip control to be set.</dd> <dt>
*lParam*
</dt> <dd>
Must be zero.
</dd> </dl>
## Return value
Returns the handle to the previous tooltip control.
## Requirements
| Requirement | Value |
|-------------------------------------|---------------------------------------------------------------------------------------|
| Minimum supported client<br/> | Windows Vista \[desktop apps only\]<br/> |
| Minimum supported server<br/> | Windows Server 2003 \[desktop apps only\]<br/> |
| Header<br/> | <dl> <dt>Commctrl.h</dt> </dl> |
## See also
<dl> <dt>
[**LVM\_GETTOOLTIPS**](lvm-gettooltips.md)
</dt> </dl>
|
Java | UTF-8 | 1,438 | 2.34375 | 2 | [] | no_license | package com.eshore.wbtimer.executor.common.exception;
import com.poson.ibsspub.util.MessageFormatter;
/**
* 描述:
*
* @author Yjm
* @create 2018/5/24 12:31
*/
public class CRMException extends RuntimeException
{
public CRMException(String expCode, String expDesc)
{
super(String.format("\u3010\u5F02\u5E38\u7F16\u7801\u662F\uFF1A%s\uFF1B\u5F02\u5E38\u63D0\u793A\u662F\uFF1A%s\u3011", new Object[] {
expCode != null ? expCode : "-10000", expDesc
}));
this.expCode = expCode != null ? expCode : "-10000";
this.expDesc = expDesc;
}
public CRMException(String expCode, String expDesc, Object objs[])
{
this(expCode, expDesc);
this.expDesc = MessageFormatter.arrayFormat(expDesc, objs);
}
public CRMException(String expCode, String expDesc, Throwable cause)
{
this(expCode, expDesc);
super.initCause(cause);
}
public String getExpCode()
{
return expCode;
}
public void setExpCode(String expCode)
{
this.expCode = expCode;
}
public String getExpDesc()
{
return expDesc;
}
public void setExpDesc(String expDesc)
{
this.expDesc = expDesc;
}
private static final long serialVersionUID = 4627701914295612919L;
public static final String UNKNOWN_EXCEPTION = "-10000";
private String expCode;
private String expDesc;
}
|
Swift | UTF-8 | 671 | 2.71875 | 3 | [] | no_license | //
// FlagCell.swift
// AllFlags
//
// Created by mac os on 18.06.16.
// Copyright © 2016 Khrystenko Dmytro. All rights reserved.
//
import UIKit
class FlagCell: UICollectionViewCell {
@IBOutlet weak var thumbImg: UIImageView!
@IBOutlet weak var nameLbl: UILabel!
var flag: Flag!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.cornerRadius = 5.0
}
func configureCell(flag: Flag) {
self.flag = flag
nameLbl.text = self.flag.name.capitalizedString
thumbImg.image = UIImage(named: "\(self.flag.flagsId)")
}
}
|
PHP | UTF-8 | 342 | 2.734375 | 3 | [] | no_license | <?php
namespace App\TopVotes\Exceptions;
use App\Core\Exceptions\Exception;
class TopNotFoundException extends Exception
{
/**
* TopNotFoundException constructor.
*
* @param string $top
*/
public function __construct(string $top)
{
parent::__construct("Топ '$top' не найден!");
}
}
|
PHP | UTF-8 | 2,206 | 2.515625 | 3 | [] | no_license | <?php
namespace Chobit\Service\Installer;
use Symfony\Component\Validator\Constraints;
use Chobit\Service\AbstractInstaller;
class MySQL extends AbstractInstaller {
public $configFile = 'config.php';
public $template = <<<'EOL'
<?php
// database for MySQL
$app['db.dsn'] = 'mysql:%%DATABASE%%';
$app['db.user'] = '%%USERNAME%%';
$app['db.password'] = '%%PASSWORD%%';
EOL;
public function __construct($app)
{
parent::__construct($app);
}
public function createForm($app)
{
$createForm = $app->share(function($app) {
$constraint = new Constraints\Collection(array(
'database' => new Constraints\MaxLength(array('limit'=>20)),
'username' => new Constraints\MaxLength(array('limit'=>20)),
'password' => new Constraints\MaxLength(array('limit'=>20)),
'host' => new Constraints\MaxLength(array('limit'=>20)),
'prefix' => new Constraints\MaxLength(array('limit'=>20)),
));
$form = $app['form.factory']
->createBuilder('form', array(), array('validation_constraint' => $constraint))
->add('database', 'text', array('label' => 'Database Name (MySQL):'))
->add('username', 'text', array('label' => 'User Name:'))
->add('password', 'password', array('label' => 'Password:'))
->add('host', 'text', array('label' => 'Host Name:', 'required' => false))
->add('prefix', 'text', array('label' => 'Prefix:', 'required' => false))
->getForm();
return $form;
});
return $createForm;
}
protected function createParameters($params)
{
$replaces = array(
'%%DATABASE%%' => $params['database'],
'%%USERNAME%%' => $params['username'],
'%%PASSWORD%%' => $params['password'],
);
return str_replace(array_keys($replaces), array_values($replaces), $this->template);
}
public function execInitSql()
{
$sql = file_get_contents(__DIR__.'/MySQL.sql');
R::exec($sql);
}
}
|
C++ | UTF-8 | 1,642 | 2.75 | 3 | [
"MIT"
] | permissive | /* -*- Mode: C++; indent-tabs-mode: nil -*- */
#ifndef SCHWA_CONFIG_SERIALISATION_H_
#define SCHWA_CONFIG_SERIALISATION_H_
#include <string>
#include <schwa/config/op.h>
namespace schwa {
namespace config {
class Main;
/**
* Configuration option for loading serialised config options from a file. The value for this
* option is the path to the configuration file. Configuration files can be generated using
* \ref OpSaveConfig instances.
**/
class OpLoadConfig : public Op<std::string> {
public:
OpLoadConfig(Group &group, const std::string &name="load-config", const std::string &desc="The file to load config from");
OpLoadConfig(Group &group, const std::string &name, char short_name, const std::string &desc);
virtual ~OpLoadConfig(void) { }
template <typename C>
void load_config(C &container) const;
};
/**
* Configuration option for saving the current set of configuration options to a file. The
* value for this option is the path to save the configuration file out to. Saved configuration
* files can be read by \ref OpLoadConfig instances.
**/
class OpSaveConfig : public Op<std::string> {
public:
OpSaveConfig(Group &group, const std::string &name="save-config", const std::string &desc="The file to save the config to");
OpSaveConfig(Group &group, const std::string &name, char short_name, const std::string &desc);
virtual ~OpSaveConfig(void) { }
void save_config(const Main &main) const;
};
}
}
#include <schwa/config/serialisation_impl.h>
#endif // SCHWA_CONFIG_SERIALISATION_H_
|
Java | UTF-8 | 1,794 | 2.765625 | 3 | [] | no_license | package com.example.movierecyclerview;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private List<Movie> moviesList;
//Constructor
public Adapter(List<Movie> moviesList)
{
Log.i("meee", "Constructor =");
this.moviesList = moviesList;
}
@NonNull
@Override
public Adapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.i("meee", "onCreateViewHolder");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull Adapter.MyViewHolder holder, int position) {
Log.i("meee", "onBindViewHolder position = "+position);
Movie x = moviesList.get(position);
holder.title.setText(x.getTitle());
holder.genre.setText(x.getGenre());
holder.year.setText(x.getYear());
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
Log.i("meee", "MyViewHolder interface ");
title = itemView.findViewById(R.id.title);
genre =itemView.findViewById(R.id.genre);
year = itemView.findViewById(R.id.year);
}
}
@Override
public int getItemCount() {
Log.i("meee", "getItemCount="+ moviesList.size());
return moviesList.size();
}
}
|
Python | UTF-8 | 11,214 | 2.59375 | 3 | [] | no_license | '''
Created on 8 May 2016
@author: guerec01
'''
from indexer.storage.cache import CacheStore
from indexer.storage.index import IndexStore
from urllib.parse import urlparse
from rdflib.namespace import RDF, OWL, FOAF, RDFS
from rdflib.graph import Dataset, Graph
from indexer.util.namespaces import INDEXER, PROV
from rdflib.plugins.sparql.processor import prepareQuery
import hashlib
import logging
from rdflib.term import URIRef, Literal, BNode
import uuid
import datetime
logger = logging.getLogger(__name__)
class Process(object):
'''
This class provides the higher level interface to the cache store
'''
def __init__(self, config, clean=False):
'''
Constructor
'''
# Get the base for minting URIs
self.base = config.base()
# Load the rules
self.rules = self._load_rules(config.rules())
logger.info('Loaded {} rule(s)'.format(len(self.rules)))
# Create an instance of the cache interface
self.cache_store = CacheStore(config)
# Create an instance of the proxies interface
self.index_store = IndexStore(config)
# If clean, reset the index DB
if clean:
self.index_store.reset_db()
def process(self, uri):
'''
Process one entry from the cache
'''
logger.info('Processing {}'.format(uri))
# Keep track of the starting time
start_time = Literal(datetime.datetime.now())
# Retrieve the graph
input_graph = self.cache_store.retrieve(uri)
# We define a named graph with the hash of the source. This way
# different versions of the same document will overwrite the triples
# previously generated from it
hashed_uri = hashlib.sha256(uri.encode()).hexdigest()
named_graph_base = URIRef('{}{}'.format(self.base, hashed_uri))
# Defined a number of graph URIs
named_graph_uri = named_graph_base + "#id"
prov_uri = named_graph_base + "#prov"
data_uri = named_graph_base + "#data"
activity_uri = BNode()
# Initialise the data set that will be generated from processing
# the graph.
dataset = Dataset()
# Extract a data set from applying the rules
self._apply_rules(dataset.graph(data_uri), input_graph)
logger.debug('Generated {} triples using the rules'.format(len(dataset)))
# Change the subjects and objects to use proxy URIs instead of the
# subjects and objects currently used
proxies_map = self._replace_subjects_by_proxies(dataset.graph(data_uri))
self._replace_objects_by_proxies(dataset.graph(data_uri))
# Add some more information about the collections
self._update_collections(dataset.graph(data_uri))
# Keep track of the end time
end_time = Literal(datetime.datetime.now())
# Add some provenance information
prov_graph = dataset.graph(prov_uri)
prov_graph.add((data_uri, RDF.type, PROV.Entity))
prov_graph.add((data_uri, PROV.wasDerivedFrom, URIRef(uri)))
prov_graph.add((data_uri, PROV.wasGeneratedBy, activity_uri))
prov_graph.add((activity_uri, PROV.used, URIRef(uri)))
prov_graph.add((activity_uri, PROV.startedAtTime, start_time))
prov_graph.add((activity_uri, PROV.endedAtTime, end_time))
# Describe the document we just created
default_graph = dataset.graph(named_graph_base)
default_graph.add((named_graph_base, RDF.type, FOAF.Document))
default_graph.add((named_graph_base, RDFS.label,
Literal("Outcome of the processing of <{}>".format(uri))))
default_graph.add((named_graph_base, FOAF.primaryTopic, named_graph_uri))
# Store the generated dataset in the index
ok = self.index_store.store(dataset)
# If we managed to store that data we may need to change all the
# references made to the subjects we just created a new proxy for
if ok:
self.index_store.update_uris(proxies_map)
def _replace_subjects_by_proxies(self, graph):
'''
Replace all the subjects by the equivalent proxy URI in one exists.
Then update the set of sameAs relation to keep track of the appartenance
of all those subjects to the proxy
'''
# Prepare a map of replacements
replacement = {}
for subj in graph.subjects():
logger.debug("Dealing with {}".format(subj))
# If we already dealt with this subject move on
# also skip everything that is not a URIRef
if subj in replacement or not isinstance(subj, URIRef):
continue
# Get all the things this subject is a sameAs of either as a subject
# or as an object. Combine that into a set of subjects all equivalent
# to each other. That set only considers the data available in the
# document being currently processed as passed on by "graph"
sameAsO = set([o for o in graph.objects(subj, OWL.sameAs)])
sameAsS = set([s for s in graph.subjects(OWL.sameAs, subj)])
subjects = sameAsO | sameAsS | set([subj])
logger.info("Looking for a proxy any of {}".format(subjects))
# Try first to find a proxy we just created for one of the subjects
proxy_uri = None
for subject in subjects:
if subject in replacement:
proxy_uri = replacement[subject]
# Try to find a proxy already existing for one of the subjects
if proxy_uri == None:
for subject in subjects:
if self.index_store.has_proxy(subject):
proxy_uri = self.get_proxy_uri(subject)
# If we have not found any create a new one
if proxy_uri == None:
proxy_uri = URIRef("{}{}#id".format(self.base, uuid.uuid1()))
logger.info("Created <{}>".format(proxy_uri))
else:
logger.info("Found <{}>".format(proxy_uri))
# Save the mapping
replacement[subj] = proxy_uri
# Also add an RDF statement to state that equivalence
graph.add((proxy_uri, OWL.sameAs, subj))
# In all the graphs replace the subjects by their proxy URI
for (s, p, o) in graph:
if s in replacement:
graph.remove((s, p, o))
graph.add((replacement[s], p, o))
# Return the replacement map
return replacement
def _replace_objects_by_proxies(self, graph):
'''
Replace all the objects by the equivalent proxy URI in one exists.
Contrary to what is done with the subjects we do not create a proxy
if one does not already exist. Creating such proxy will eventually
happen if the object can be crawled and indexed. In this case the
replacement will be done when this happens.
'''
# Get a proxy URI for each of the object
replacement = {}
for obj in graph.objects():
# If we already dealt with this object move on
# also skip everything that is not a URIRef
if obj in replacement or not isinstance(obj, URIRef):
continue
# Get the proxy URI if there is one
if self.index_store.has_proxy(obj):
replacement[obj] = self.get_proxy_uri(obj)
# In all the graphs replace the subjects by the proxy URI
for (s, p, o) in graph:
if o in replacement:
graph.remove((s, p, o))
graph.add((s, p, replacement[o]))
def _update_collections(self, dataset):
'''
-> every proxy is partOf the document URI that provided it
-> every proxy is partOf everything
-> every proxy is partOf the specific collections that apply to it
'''
# Add to the collection 'everything'
#self.collections.add_to_collection('everything', proxy_uri)
# Add to the collection corresponding to its type
#subject = [s for s in entity.subjects()][0]
#proxy_type = entity.value(subject, RDF.type).toPython()
#if proxy_type in self.collections.TYPE_COLLECTIONS:
# (name, label, description) = self.collections.TYPE_COLLECTIONS[proxy_type]
# if not self.collections.contains(name):
# self.collections.create(name, label, description)
# self.collections.add_to_collection(name, proxy_uri)
# Add to the collection for this source domain
#hostname = urlparse(uri).hostname
#name = hostname.replace('.', '_')
#label = hostname
#description = 'Everything with data coming from {}'.format(hostname)
#if not self.collections.contains(name):
# self.collections.create(name, label, description)
#self.collections.add_to_collection(name, proxy_uri)
pass
def _load_rules(self, rules_file_name):
# Rules are stored in hash map
rules = {}
# Load the rule base into memory
logger.debug('Loading {}'.format(rules_file_name))
g = Graph().parse(rules_file_name, format="turtle")
# Extract the namespaces from the rule base
r_ns = {}
for (ns, uri) in g.namespaces():
r_ns[ns] = uri
# Compose and prepare the SPARQL queries
for s in g.subjects(RDF.type, INDEXER.Rule):
# Extract the components of the rule
r_if = g.value(s, INDEXER['if']).toPython().replace('\t', '')
r_then = g.value(s, INDEXER['then']).toPython().replace('\t', '')
rule = 'CONSTRUCT {' + r_then + '} WHERE {' + r_if + '}'
# Pre-load the rule
rules[s.toPython()] = prepareQuery(rule, initNs=r_ns)
return rules
def _apply_rules(self, output_graph, input_graph):
'''
Execute all the processing rules against the graph passed as parameter
and return them as an array of graph.
@param output_graph: the target graph to put the result of the rules in
@param input_graph: the data graph to process in search for entities
'''
# Apply all the rules one by one
for (name, rule) in self.rules.items():
# Apply the rule, the result is an RDF graph
tmp_graph = input_graph.query(rule).graph
if len(tmp_graph) == 0:
continue
logger.debug('Found a match for {}'.format(name))
# Add the graph statements in the named graph
for st in tmp_graph:
output_graph.add(st)
tmp_graph.remove(st)
|
PHP | UTF-8 | 134 | 2.59375 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace Domain;
interface ProductStorageInterface
{
public function add(Product $product);
}
|
Python | UTF-8 | 3,446 | 2.515625 | 3 | [] | no_license | import sys
sys.path.append('/home/ubuntu/caffe-master/python')
import caffe
import os.path
import rsquared as r2
from pylab import *
#set to use CPU and not GPU
caffe.set_mode_cpu()
#check for enough arguments
if len(sys.argv) != 6 and len(sys.argv) != 7 and len(sys.argv) != 8 and len(sys.argv) != 9:
exit("Error: Incorrect number of arguments. \nUsage: net_trainer.py <file path to solver> <iterations to train> <iterations between tests> <iterations per test> <userdir> <simple> <model file path (optional)> <solverstate file path (optional)>")
#initialize the paths
solverFilePath = sys.argv[5] + '/' + sys.argv[1]
modelFilePath = ''
stateFilePath = ''
#check for relevant paths
if not os.path.isfile(solverFilePath):
exit("Error: File path to solver is invalid.")
if len(sys.argv) >= 8:
if not os.path.isfile(modelFilePath):
exit("Error: File path to model file is invalid.")
modelFilePath = sys.argv[5] + '/' + sys.argv[7]
if len(sys.argv) == 9:
if not os.path.isfile(stateFilePath):
exit("Error: File path to solverstate file is invalid.")
stateFilePath = sys.argv[5] + '/' + sys.argv[8]
#make sure ints are actually ints
try:
int(sys.argv[2])
int(sys.argv[3])
int(sys.argv[4])
except ValueError:
exit("Error: Iterations to train and iterations between tests must be integers")
#check for invalid inputs
if int(sys.argv[3]) == 0:
exit("Error: Iterations between tests must be greater than zero")
#switch between simple solver (adadelta) and complex solver (stochastic gradient descent)
if sys.argv[6] == 'true':
solver = caffe.AdaDeltaSolver(solverFilePath)
else:
solver = caffe.SGDSolver(solverFilePath)
#allow starting from a set of weights or starting from pretrained gradients and weights
if len(sys.argv) == 8:
solver.net.copy_from(modelFilePath)
solver.test_nets[0].copy_from(modelFilePath)
if len(sys.argv) == 9:
solver.restore(stateFilePath)
solver.test_nets[0].restore(stateFilePath)
#checks are over, set values from the inputs
niter = int(sys.argv[2])
test_interval = int(sys.argv[3])
trainingNum = int(niter / test_interval)
train_loss = zeros(niter)
test_loss = zeros(trainingNum)
rsquared = zeros(trainingNum)
#manually step through the iterations so we can capture some other information
for it in range(niter):
solver.step(1)
#save the training loss for iteration
train_loss[it] = solver.net.blobs['loss'].data
#if it's testing time
if it % test_interval == 0:
#run through the test net for the correct number of iterations
for test_it in range(int(sys.argv[4])):
solver.test_nets[0].forward()
print solver.test_nets[0].blobs['loss'].data
#save the test loss
test_loss[int(it / test_interval)] = solver.test_nets[0].blobs['loss'].data
#try saving the r^2
try:
rsquared[it / test_interval] = r2.calculateR2(solver.test_nets[0].blobs['innerBottom'].data, solver.test_nets[0].blobs['label'].data)
#if it fails, that means it's a categorical and we use accuracy instead
except ValueError:
rsquared[it / test_interval] = solver.test_nets[0].blobs['accuracy'].data
#save everything
np.savetxt(sys.argv[5] + '/train_loss.out', train_loss, delimiter=',')
np.savetxt(sys.argv[5] + '/test_loss.out', test_loss, delimiter=',')
np.savetxt(sys.argv[5] + '/rsquared.out', rsquared, delimiter=',')
print "\nTraining complete."
|
Java | UTF-8 | 1,914 | 2.265625 | 2 | [] | no_license | package com.mercado.mineiro.administration.common.web;
import com.mercado.mineiro.administration.common.exception.DomainException;
import com.mercado.mineiro.administration.common.base.EntityBase;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.LinkedHashMap;
import java.util.Map;
@Service
public class Responses {
@Setter
@Getter
protected String path;
public static ResponseEntity<Object> unprocessableEntity(DomainException e) {
return unprocessableEntity(e.getMessage(), new LinkedHashMap<>());
}
public static ResponseEntity<Object> unprocessableEntity(String message, Map<String, String> errors) {
var body = new LinkedHashMap<String, Object>();
body.put("message", message);
body.put("errors", errors);
return ResponseEntity.unprocessableEntity()
.body(body);
}
public static <T extends EntityBase> ResponseEntity<T> created(String path, T entity) {
var builder = UriComponentsBuilder.newInstance();
var uri = builder.path(path + "/{id}").buildAndExpand(entity.getId()).toUri();
return ResponseEntity.created(uri).body(entity);
}
public static <T> ResponseEntity<T> created(String path, Long id, T body) {
var builder = UriComponentsBuilder.newInstance();
var uri = builder.path(path).buildAndExpand(id).toUri();
return ResponseEntity.created(uri).body(body);
}
public static ResponseEntity notContent() {
return ResponseEntity.noContent().build();
}
public static <T> ResponseEntity<T> notFound() {
return ResponseEntity.notFound().build();
}
public static <T> ResponseEntity<T> ok(T body) {
return ResponseEntity.ok(body);
}
}
|
PHP | UTF-8 | 2,797 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* core/MY_Controller.php
*
* Default application controller
*
* @author JLP
* @copyright 2010-2013, James L. Parry
* ------------------------------------------------------------------------
*/
class Application extends CI_Controller {
protected $data = array(); // parameters for view components
protected $id; // identifier for our content
/**
* Constructor.
* Establish view parameters & load common helpers
*/
function __construct() {
parent::__construct();
$this->data = array();
$this->data['title'] = 'Subforum'; // our default title
$this->errors = array();
$this->data['pageTitle'] = 'welcome'; // our default page
$this->data['toggle_admin'] = "";
//Set layout options here, with preserving which layout is currently selected
$layout_options = array(
array('layout_name' => 'Standard', 'layout_view' => 'forum_1', 'is_selected' => ''),
array('layout_name' => 'Distinct', 'layout_view' => 'forum_3', 'is_selected' => ''),
array('layout_name' => 'Elaborate', 'layout_view' => 'forum_2', 'is_selected' => ''),
array('layout_name' => 'Something', 'layout_view' => 'forum_4', 'is_selected' => '')
);
$this->data['layouts'] = $layout_options;
}
/**
* Render this page
*/
function render() {
//if not logged in, display login item; if logged in, then display logout item.
//TBD: Make this occur depending on whether session values are set.
$menu_choices = $this->config->item('menu_choices');
$menu_choices['loginouturl'] = "/login";
$menu_choices['loginout'] = "Login";
$this->data['menubar'] = $this->parser->parse('_menubar', $menu_choices, true);
$this->data['content'] = $this->parser->parse($this->data['pagebody'], $this->data, true);
//set which layout is currently selected, if possible.
//This is done here because it is an element of every page with a $forum_view
//element that is set, and depends on what that element is set to.
if(isset($this->forum_view)) {
$curr_layout = $this->forum_view;
if($curr_layout != null) {
foreach($this->data['layouts'] as &$layout_option) {
if($layout_option['layout_view'] == $curr_layout)
$layout_option['is_selected'] = " selected";
}
}
}
// finally, build the browser page!
$this->data['data'] = &$this->data;
$this->parser->parse('_template', $this->data);
}
}
/* End of file MY_Controller.php */
/* Location: application/core/MY_Controller.php */ |
JavaScript | UTF-8 | 3,104 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | var M = require('mstring'),
f = require('util').format;
var id = 0;
var generateId = function() {
return id++;
}
var resetId = function() {
id = 0;
}
var clone = function(o) {
var opts = {};
for(var name in o) opts[name] = o[name];
return opts;
}
var generatePathAndObject = function(self, context) {
// Generate path
var path = 'path';
// If we are in an array
if(context.inArray && !context.inArrayIndex) {
path = f('path.slice(0).concat(["" + i])');
} else if(context.inArray && context.inArrayIndex) {
path = f('path.slice(0).concat([%s])', context.inArrayIndex);
} else if(context.path) {
path = context.path;
} else if(self.parent == null) {
path = ['["object"]'];
} else if(self.parent) {
path = f('path.slice(0).concat(["%s"])', self.field);
}
// Set the object
var objectPath = 'object';
// Do we have a custom object path generator
if(context.inArray && !context.inArrayIndex) {
objectPath = 'object[i]';
} else if(context.inArray && context.inArrayIndex) {
objectPath = f('object[%s]', context.inArrayIndex);
} else if(context.object) {
objectPath = context.object;
}
// Return the object
return {path: path, objectPath: objectPath};
}
var decorate = function(context) {
// Generate generatePath function
context.functions.push(M(function(){/***
var generatePath = function(parent) {
var args = Array.prototype.slice.call(arguments);
args.shift();
return f('%s%s', parent, args.map(function(x) {
return f('[%s]', x);
}).join(''));
}
***/}));
// Add a isRegExp function
context.functions.push(M(function(){/***
var isRegEx = function(value) {
try {
new RegExp(value);
} catch(err) {
return false;
}
return true;
}
***/}));
// Push deepCompare function
context.functions.push(M(function(){/***
var deepCompareStrict = function(a, b) {
if (typeof a !== typeof b) {
return false;
}
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
return a.every(function (v, i) {
return deepCompareStrict(a[i], b[i]);
});
}
if (typeof a === 'object') {
if (!a || !b) {
return a === b;
}
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
return aKeys.every(function (v) {
return deepCompareStrict(a[v], b[v]);
});
}
return a === b;
};
***/}));
// Push deepCompare function
context.functions.push(M(function(){/***
var testArrays = function(v, i, a) {
for (var j = i + 1; j < a.length; j++) if (deepCompareStrict(v, a[j])) {
return false;
}
return true;
}
***/}));
}
module.exports = {
generateId: generateId,
resetId: resetId,
clone: clone,
decorate: decorate,
generatePathAndObject: generatePathAndObject
} |
Markdown | UTF-8 | 10,544 | 2.671875 | 3 | [
"MIT"
] | permissive | ---
layout: default
title: Interfaccia da linea di comando per WordPress
direction: ltr
---
[WP-CLI](https://wp-cli.org/) è un insieme di strumenti da linea di comando per la gestione delle installazioni [WordPress](https://wordpress.org/). Potete aggiornare plugin, configurare installazioni multisito e molto altro, senza utilizzare un browser web.
Per rimanere aggiornati, seguite [@wpcli su Twitter](https://twitter.com/wpcli) oppure [iscrivetevi alla nostra newsletter](http://wp-cli.us13.list-manage.com/subscribe?u=0615e4d18f213891fc000adfd&id=8c61d7641e).
[](https://github.com/wp-cli/wp-cli/actions/workflows/testing.yml) [](http://isitmaintained.com/project/wp-cli/wp-cli "Average time to resolve an issue") [](http://isitmaintained.com/project/wp-cli/wp-cli "Percentage of issues still open")
Collegamenti rapidi: [Utilizzo](#utilizzo) | [Installazione](#installazione) | [Supporto](#supporto) | [Estendere](#estendere) | [Contribuire](#contribuire) | [Crediti](#crediti)
## Utilizzo
L'obiettivo di WP-CLI è quello di fornire un'interfaccia da linea di comando per le azioni che normalmente si possono effettuare attraverso l'area amministrativa. Per esempio, `wp plugin install --activate` ([doc](https://wp-cli.org/commands/plugin/install/)) vi permette di installare ed attivare un plugin di WordPress:
```bash
$ wp plugin install rest-api --activate
Installing WordPress REST API (Version 2) (2.0-beta13)
Downloading install package from https://downloads.wordpress.org/plugin/rest-api.2.0-beta13.zip...
Unpacking the package...
Installing the plugin...
Plugin installed successfully.
Activating 'rest-api'...
Success: Plugin 'rest-api' activated.
```
WP-CLI include anche dei comandi per molte operazioni che normalmente non sarebbe possibile svolgere nell'area amministrativa di WordPress. Per esempio, `wp transient delete --all` ([doc](https://wp-cli.org/commands/transient/delete/)) vi permetterà di eliminare uno o tutti i transienti:
```bash
$ wp transient delete --all
Success: 34 transients deleted from the database.
```
Per una più completa panoramica sull'utilizzo di WP-CLI, vi invitiamo a leggere la [Quick Start guide](https://wp-cli.org/docs/quick-start/).
Vi sentite già a vostro agio con le basi? Andate dritti alla [lista completa dei comandi](https://wp-cli.org/commands/) per le informazioni dettagliate su come gestire temi e plugin, importare ed esportare dati, operare ricerche e sostituzioni nel database ed altro.
## Installazione
Come metodo di installazione, raccomandiamo di scaricare il Phar. Se vi occorre, leggete la nostra documentazione sui [metodi alternativi di installazione](https://wp-cli.org/docs/installing/).
Prima di procedere con l'installazione di WP-CLI, vi preghiamo di assicurarvi che il vostro ambiente soddisfi i minimi requisiti richiesti:
- Ambiente UNIX-like (OS X, Linux, FreeBSD, Cygwin); in ambienti Windows il supporto è limitato
- PHP 5.3.29 o successivo
- WordPress 3.7 o successivo
Una volta che avrete verificato i requisiti, scaricate il file [wp-cli.phar](https://raw.github.com/wp-cli/builds/gh-pages/phar/wp-cli.phar) mediante `wget` o `curl`:
```bash
$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
```
Successivamente, controllate il suo funzionamento:
```bash
$ php wp-cli.phar --info
```
Per richiamare WP-CLI dalla linea di comando scrivendo `wp`, rendete il file eseguibile e spostatelo nel vostro PATH, ad esempio:
```bash
$ chmod +x wp-cli.phar
$ sudo mv wp-cli.phar /usr/local/bin/wp
```
Se l'installazione di WP-CLI è andata a buon fine, lanciando il comando `wp --info`, dovreste vedere qualcosa di simile:
```bash
$ wp --info
PHP binary: /usr/bin/php5
PHP version: 5.5.9-1ubuntu4.14
php.ini used: /etc/php5/cli/php.ini
WP-CLI root dir: /home/wp-cli/.wp-cli
WP-CLI packages dir: /home/wp-cli/.wp-cli/packages/
WP-CLI global config: /home/wp-cli/.wp-cli/config.yml
WP-CLI project config:
WP-CLI version: 0.25.0
```
### Aggiornamenti
Potete aggiornare WP-CLI attraverso il comando `wp cli update` ([doc](https://wp-cli.org/commands/cli/update/)), oppure ripetendo i passi descritti per l'istallazione.
Volete vivere sul filo del rasoio? Lanciate `wp cli update --nightly` per usare la versione quotidiana notturna di WP-CLI. La versione quotidiana notturna è sufficientemente stabile da essere utilizzata negli ambienti di sviluppo, e include sempre le ultime e migliori caratteristiche.
### Autocompletamento
WP-CLI inoltre mette a disposizione uno script per l'autocompletamento per Bash e ZSH. Basta scaricare [wp-completion.bash](https://github.com/wp-cli/wp-cli/raw/master/utils/wp-completion.bash) a attivarlo da `~/.bash_profile`:
```bash
source /FULL/PATH/TO/wp-completion.bash
```
Alla fine del suo utilizzo, non dimenticate di reimpostare il profilo originale digitando `source ~/.bash_profile`.
Se state usando la shell zsh, avrete bisogno di caricare ed avviare `bashcompinit` prima di impostare il profilo. Eseguite i seguenti comandi dalla vostra `.zshrc`:
```bash
autoload bashcompinit
bashcompinit
source /FULL/PATH/TO/wp-completion.bash
```
## Supporto
I manutentori e i contributori di WP-CLI sono volontari, hanno limitate disponibilità da dedicare al supporto generale. Primariamente, cercate delle risposte nelle seguenti risorse:
- [Problemi comuni e le loro soluzioni](https://wp-cli.org/docs/common-issues/)
- [Portale della documentazione](https://wp-cli.org/docs/)
- [Problemi segnalati o estinti su Github](https://github.com/wp-cli/wp-cli/issues?utf8=%E2%9C%93&q=is%3Aissue)
- [Estratti di runcommand](https://runcommand.io/excerpts/)
- [Forum di WordPress su StackExchange](http://wordpress.stackexchange.com/questions/tagged/wp-cli)
Se non trovare delle risposte in questi posti, entrate al canale `#cli` su [WordPress.org Slack organization](https://make.wordpress.org/chat/) per vedere se qualche membro della comunità può offrirvele.
Le questioni su Github servono a tracciare migliorie e i bachi dei comandi esistenti, non per il supporto generico. Prima di sottoporre un rapporto su un baco, vi preghiamo di [rileggere le nostre procedure](https://wp-cli.org/docs/bug-reports/) per fare in modo che il vostro problema sia indirizzato in modo tempestivo.
Vi preghiamo di non richiedere supporto su Twitter. Twitter non è un mezzo accettabile di supporto perché: 1) è difficile gestire una conversazione in meno di 140 caratteri, e 2) Twitter non è un luogo dove altre persone con il vostro stesso problema possano reperire facilmente la risposta tra le conversazioni.
Ricordate, libero != gratis; la licenza di software libero vi garantisce la libertà di usare e di modificare, ma non di rubare tempo altrui. Per favore, siate rispettosi, e comportatevi di conseguenza.
## Estendere
Un **comando** è una funzionalità atomica di WP-CLI. `wp plugin install` ([doc](https://wp-cli.org/commands/plugin/install/)) è un comando. `wp plugin activate` ([doc](https://wp-cli.org/commands/plugin/activate/)) è un altro.
WP-CLI supporta la dichiarazione di una qualsiasi classe richiamabile oppure una closure, come comando. Legge i dettagli attraverso la callback di PHPdoc. `WP_CLI::add_command()` ([doc](https://wp-cli.org/docs/internal-api/wp-cli-add-command/)) viene usata sia per le registrazioni dei comandi interni che per quelli di terze parti.
```php
/**
* Cancella un opzione dal database.
*
* Restituisce un errore se l'opzione non esiste.
*
* ## OPZIONI
*
* <key>
* : Key per l'opzione.
*
* ## ESEMPI
*
* $ wp option delete my_option
* Success: Opzione 'my_option' cancellata.
*/
$delete_option_cmd = function( $args ) {
list( $key ) = $args;
if ( ! delete_option( $key ) ) {
WP_CLI::error( "Non posso eliminare l'opzione '$key'. Esiste?" );
} else {
WP_CLI::success( "Opzione '$key' cancellata." );
}
};
WP_CLI::add_command( 'option delete', $delete_option_cmd );
```
WP-CLI offre dozzine di comandi. Creare nuovi comandi personalizzati è più facile di quel che sembri. Leggete il [commands cookbook](https://wp-cli.org/docs/commands-cookbook/) per sapere di più. Consultate la [documentazione delle internal API](https://wp-cli.org/docs/internal-api/) per scoprire la varietà di utili funzioni disponibili per i vostri comandi WP-CLI.
## Contribuire
Benvenuti e grazie!
Apprezziamo che vogliate prendere parte e contribuire a WP-CLI. È per merito vostro e della comunità che vi gravita attorno se WP-CLI è un grande progetto.
**Contribuire non si limita soltanto alla programmazione**
Vi incoraggiamo a contribuire nel modo che meglio rispecchia le vostre abilità, scrivendo tutorial, offrendo dimostrazioni durante i vostri incontri locali, prestare aiuto ad altri utenti riguardo le loro richieste di aiuto, o revisionando la documentazione.
Vi preghiamo di riservare un po' di tempo da dedicare alla [lettura approfondita delle linee guida](https://wp-cli.org/docs/contributing/). Seguirle dimostra il rispetto dei tempi altrui sul progetto.
## Coordinamento
WP-CLI è guidato dai seguenti individui:
* [Daniel Bachhuber](https://github.com/danielbachhuber/) - manutentore corrente
* [Cristi Burcă](https://github.com/scribu) - manutentore precedente
* [Andreas Creten](https://github.com/andreascreten) - fondatore
Leggi di più riguardo la [politica del progetto](https://wp-cli.org/docs/governance/) e guarda la [lista completa dei contributori](https://github.com/wp-cli/wp-cli/contributors).
## Crediti
Oltre alle librerie definite in [composer.json](composer.json), abbiamo adottato codice o spunti dai seguenti progetti:
* [Drush](http://drush.ws/) per... un mucchio di cose
* [wpshell](http://code.trac.wordpress.org/browser/wpshell) per `wp shell`
* [Regenerate Thumbnails](http://wordpress.org/plugins/regenerate-thumbnails/) per `wp media regenerate`
* [Search-Replace-DB](https://github.com/interconnectit/Search-Replace-DB) per `wp search-replace`
* [WordPress-CLI-Exporter](https://github.com/Automattic/WordPress-CLI-Exporter) per `wp export`
* [WordPress-CLI-Importer](https://github.com/Automattic/WordPress-CLI-Importer) per `wp import`
* [wordpress-plugin-tests](https://github.com/benbalter/wordpress-plugin-tests/) per `wp scaffold plugin-tests`
|
JavaScript | UTF-8 | 626 | 2.796875 | 3 | [] | no_license | const axios = require('axios');
const moment = require('moment');
const bangkokForecast = async () => {
// put your code here !!
let openweathermapAPI = 'https://api.openweathermap.org/data/2.5/forecast/daily?q=Bangkok,THA&cnt=7&appid=e5446373eef6128679c7fa8a1951d788&units=metric'
try {
let datas = await axios.get(openweathermapAPI)
return datas.data.list.map((data, key) => {
let date = moment(data.dt).format('YYYY-MM-DD');
return { data: date, minTemp: data.temp.min, maxTemp: data.temp.max }
})
} catch (error) {
throw new Error(error)
}
};
module.exports = { bangkokForecast };
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.