language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,617 | 2.703125 | 3 | [] | no_license | // <copyright file="GameTest.cs" company="Gavin Greig">
// Copyright (c) Dr. Gavin T.D. Greig, 2015.
// </copyright>
// <author>Dr. Gavin T.D. Greig</author>
// <date>2015-07-08</date>
// <summary>
// A suite of unit tests for the Game class.
// </summary>
namespace GavinGreig.OXO.UnitTest
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GavinGreig.OXO.State;
using GavinGreig.OXO.Strategies;
using GavinGreig.OXO.UnitTest.Utility;
using NUnit.Framework;
/// <summary>
/// A suite of unit tests for the Game class.
/// </summary>
[TestFixture]
public static class GameTest
{
/// <summary>
/// Tests that the game introduction segment displays correctly.
/// </summary>
[Test]
public static void GameIntroduction_DisplaysCorrectly()
{
using (ConsoleCapture theConsole = new ConsoleCapture())
{
// Arrange
string theExpectedOutput =
"***********************\r\n" +
"* Noughts and Crosses *\r\n" +
"***********************\r\n" +
"\r\n" +
"Two computer players will compete for your amusement.\r\n" +
"\r\n";
// Act
Game.DisplayGameIntroduction();
// Assert
Assert.That(theConsole.Output, Is.EqualTo(theExpectedOutput));
}
}
}
}
|
Go | UTF-8 | 821 | 3.21875 | 3 | [] | no_license | package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Item struct {
Author string `json:"author"`
Score int `json:"score"`
URL string `json:"url"`
Title string `json:"title"`
}
type response struct {
Data1 struct {
Children []struct {
Data2 Item `json:"data"`
} `json:"children"`
} `json:"data"`
}
func main() {
resp, err := http.Get("https://www.reddit.com/r/golang.json")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatal(resp.Status)
}
r := new(response)
err = json.NewDecoder(resp.Body).Decode(r)
for _, child := range r.Data1.Children {
fmt.Println(child.Data2)
fmt.Println(child.Data2.Author)
fmt.Println(child.Data2.Score)
fmt.Println(child.Data2.URL)
fmt.Println(child.Data2.Title)
}
}
|
C# | UTF-8 | 830 | 2.609375 | 3 | [] | no_license | using System;
using UnityEngine;
namespace VRSashimiTanpopo.Tanpopo
{
public class TanpopoCounter : MonoBehaviour
{
public event Action IncreasedToOne;
public event Action IncreasedToTwo;
public event Action DecreasedToZero;
public bool IsZero => count == 0;
int count;
void OnTriggerEnter(Collider collider)
{
count++;
if (count == 1)
{
IncreasedToOne?.Invoke();
}
if (count == 2)
{
IncreasedToTwo?.Invoke();
}
}
void OnTriggerExit(Collider collider)
{
count--;
if (count == 0)
{
DecreasedToZero?.Invoke();
}
}
}
}
|
Java | UTF-8 | 1,675 | 2.671875 | 3 | [] | no_license | import fillers.AbstractPdfFiller;
import fillers.implementations.CR115Filler;
import fillers.implementations.CR180Filler;
import fillers.implementations.CR181Filler;
import fillers.implementations.FW001Filler;
import fillers.implementations.FW003Filler;
import fillers.implementations.Pos040Filler;
import object.DefendantInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Driver {
public static void main(String[] args) {
String path = "Dummy Client Data.csv";
List<DefendantInfo> infos = CsvReader.processInputFile(path);
File outDir = new File(AbstractPdfFiller.FOLDER_NAME.substring(0, AbstractPdfFiller.FOLDER_NAME.length() - 1));
if (!outDir.exists()) {
outDir.mkdir();
}
List<AbstractPdfFiller> pdfFillers = initializePdfFillers();
for (AbstractPdfFiller filler : pdfFillers) {
filler.fillForm(infos.get(0));
}
}
public static List<AbstractPdfFiller> initializePdfFillers() {
List<AbstractPdfFiller> result = new ArrayList<>();
AbstractPdfFiller cr115Filler = new CR115Filler();
AbstractPdfFiller cr180Filler = new CR180Filler();
AbstractPdfFiller cr181Filler = new CR181Filler();
AbstractPdfFiller fw003Filler = new FW003Filler();
AbstractPdfFiller fw001Filler = new FW001Filler();
AbstractPdfFiller pos040Filler = new Pos040Filler();
result.add(cr115Filler);
result.add(cr180Filler);
result.add(cr181Filler);
result.add(fw001Filler);
result.add(fw003Filler);
result.add(pos040Filler);
return result;
}
}
|
Markdown | UTF-8 | 317 | 2.515625 | 3 | [] | no_license | # Times Series Forecasting
Projetos criados a partir de curso Time Series Forecasting da Udacity.
Segue o link do curso: https://www.udacity.com/course/time-series-forecasting--ud980.
Os exercícios foram feitos no Jupyter Notebook, apesar de o curso usar o Alteryx, por alinhamento com propósito de aprendizado.
|
Python | UTF-8 | 2,902 | 3.21875 | 3 | [] | no_license | import math
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return math.e ** (-x / 2) * math.sin(4 * x)
h = 0.5
def generate_points():
ret_points = []
step = 0.5
for k in np.arange(-1, 7 + 2 * step, step):
ret_points.append((k, f(k)))
return ret_points
def B(x0, h, x):
if x <= x0 - 2 * h:
return 0
elif x0 - 2 * h <= x <= x0 - h:
return 1 / 6 * (2 * h + (x - x0)) ** 3
elif x0 - h <= x <= x0:
return 2 / 3 * h ** 3 - 1 / 2 * (x - x0) ** 2 * (2 * h + (x - x0))
elif x0 <= x < x0 + h:
return 2 / 3 * h ** 3 - 1 / 2 * (x - x0) ** 2 * (2 * h - (x - x0))
elif x0 + h <= x <= x0 + 2 * h:
return 1 / 6 * (2 * h - (x - x0)) ** 3
else:
return 0
def b_matrix(n):
matrix = []
first_row = [1] + [0 for _ in range(n - 1)]
matrix.append(first_row)
last_row = first_row[::-1]
for i in range(n - 2):
row = [0 for _ in range(i)] + [1, 4, 1] + [0 for _ in range(n - 3 - i)]
matrix.append(row)
matrix.append(last_row)
return matrix
def a_matrix(n, b_matrix, x_points):
b_matrix = np.array([np.array(xi) for xi in b_matrix])
x_matrix = []
x_matrix.append([1/h**3 * f(x_points[0]), ])
for i in range(1, n - 1):
x_matrix.append([6/h**3 * f(x_points[i]), ])
x_matrix.append([1/h**3 * f(x_points[n - 1]), ])
x_matrix = np.array(x_matrix)
a = np.linalg.solve(b_matrix, x_matrix)
#print(a)
a = np.vstack((a, [2 * a[n - 1] - a[n - 2]]))
a = np.vstack(([2 * a[0] - a[1]], a))
#print(a)
# a = np.concatenate([2 * a[0] - a[1], ], a, [2 * a[n-2] - a[n-3], ])
return a
def b_spline(a_matrix, x_points):
step = 0.1
ret_points = []
n = len(x_points)
for i in range(n - 1):
xi, xj = x_points[i], x_points[i + 1]
for k in np.arange(xi, xj+2*step, step):
a1 = a_matrix[i]
a2 = a_matrix[i+1]
a3 = a_matrix[i+2]
a4 = a_matrix[i+3]
y = a1 * B(x_points[i] - h, h, k) + a2 * B(x_points[i], h, k) + \
a3 * B(x_points[i] + h, h, k) + a4 * B(x_points[i] + 2*h, h, k)
ret_points.append((k, y))
return ret_points
def main():
points = generate_points()
#points = [(1,1), (2,3), (3,2)]
xpoints = [x[0] for x in points]
ypoints = [y[1] for y in points]
n = len(points)
b = b_matrix(n)
a = a_matrix(n, b, xpoints)
print(a)
print(b)
spline_points = b_spline(a, xpoints)
xspline = [x for x, _ in spline_points]
yspline = [y for _, y in spline_points]
plt.plot(xspline, yspline, '-')
plt.plot(xpoints, ypoints, 'ro')
# plt.show()
n = len(xspline)
for i in range(n-1):
print((f(xspline[i]) - yspline[i])/2 * 100)
# plt.plot(xpoints, ypoints, 'ro')
plt.grid()
plt.show()
if __name__ == "__main__":
main()
|
PHP | UTF-8 | 5,679 | 2.609375 | 3 | [] | no_license | <?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$DEFAULT_MAX_NB_FILES = 15;
$MaxNumberOfFiles=$DEFAULT_MAX_NB_FILES;//12 would probly be the max number of files that would fit in the div
$FileIDs = array();//to be provided with an array of FileIDs that were found
if(!empty($_GET["EventID"])){
$EventID=$_GET["EventID"];
}
$key = $_GET['key'];
$isPostalCode = preg_match('/[ABCEGHJKLMNPRSTVXY][0-9][A-Z]/', $key) || preg_match('/[abceghjklmnprstvxy][0-9][a-z]/', $key) ||
preg_match('/[abceghjklmnprstvxy][0-9][A-Z]/', $key) || preg_match('/[ABCEGHJKLMNPRSTVXY][0-9][a-z]/', $key);
$isMedicard = preg_match('/\D{4}\s?\d{4}\s?\d{4}/', $key) || preg_match('/\D{4}?\d{4}?\d{4}/', $key);
include_once("/../../services/mysql/phpMySql.php");
include_once("/../../services/mysql/dbSqlToText.php");
include_once("/../../model/Finders/IncludeAllFinders.php");
$ff = new FileFinder();
$uf = new UserFinder();
$if = new FileInfoFinder();
$gf = new GlobalFinder($ff);
$data = preg_split("/ /",$key);
if ($key != ""){
//check if key is an ID
$id = intval($key);
if ($isMedicard){
$gf->setFinder($uf);
$sk = $uf->getSearchKeyByMedicard($key);
$res = $gf->find(array($sk), false);
$cntr = 0;
for ($i = 0;$i<sizeof($res);$i++){
$usr = $res[$i];
$id = $usr->id;
$FileIDs[$cntr] = $id;
$cntr++;
}
if (preg_match('/[ ]/i', $key)){
$newMedi = str_replace (" ", "", $key);
$sk = $uf->getSearchKeyByMedicard($newMedi);
$res = $gf->find(array($sk), false);
for ($i = 0;$i<sizeof($res);$i++){
$usr = $res[$i];
$id = $usr->id;
$FileIDs[$cntr] = $id;
$cntr++;
}
}
else{
$newMedi = str_replace (" ", "", $key);
$temp = substr($newMedi, 0,4);
$temp.= " " .substr($newMedi,4,4);
$temp.=" " . substr($newMedi,8,8);
$newMedi = $temp;
$sk = $uf->getSearchKeyByMedicard($newMedi);
$res = $gf->find(array($sk), false);
for ($i = 0;$i<sizeof($res);$i++){
$usr = $res[$i];
$id = $usr->id;
$FileIDs[$cntr] = $id;
$cntr++;
}
}
}
else if ($isPostalCode){ //postal code
$gf->setFinder($if);
$key = strtoupper($key);
$sk = $if->getSearchKeyByAddrPcode($key);
$res = $gf->find(array($sk), true);
$cntr = 0;
for ($i=0;$i<sizeof($res);$i++){
$fileInfo = $res[$i];
$fileId = $fileInfo->getFamilyId();
$file = new File($fileId, false);
$userId = $file->independentId;
$FileIDs[$cntr] = $userId;
$cntr++;
}
}
else{
if ($id != 0 && sizeof($data) == 1){ //an id!{
$gf->setFinder($ff);
$sk = $ff->getSearchKeyById($id);
$res = $gf->find(array($sk), false);
if (sizeof($res) > 0){
$file = $res[0];
$FileIDs[0] = $file->independentId;
}
}
else{ //not id!
if (sizeof($data) == 1){ //just first name..
$gf->setFinder($uf);
$sk = $uf->getSearchKeyByLastName($key);
$res = $gf->find(array($sk), true);
$cntr = 0;
for ($i=0;$i<sizeof($res);$i++){
$user = $res[$i];
$FileIDs[$cntr] = $user->id;
$cntr++;
}
$sk = $uf->getSearchKeyByFirstName($key);
$res = $gf->find(array($sk), true);
for ($i=0;$i<sizeof($res);$i++){
$user = $res[$i];
$FileIDs[$cntr] = $user->id;
$cntr++;
}
$gf->setFinder($if);
$sk = $if->getSearchKeyByAddrStreet($key);
$res = $gf->find(array($sk), false);
for ($i=0;$i<sizeof($res);$i++){
$fileInfo = $res[$i];
$fileInfo = $res[$i];
$fileId = $fileInfo->getFamilyId();
$file = new File($fileId, false);
$userId = $file->independentId;
$FileIDs[$cntr] = $userId;
$cntr++;
}
}
else{ //last name and first name OR ADDRESS!
if (intval($data[0]) == 0){ //firstname/lastname{
$gf->setFinder($uf);
$sk = $uf->getSearchKeyByFirstName($data[0]);
$sk2 = $uf->getSearchKeyByLastName($data[1]);
$res = $gf->find(array($sk, $sk2), true);
$cntr = 0;
for ($i=0;$i<sizeof($res);$i++){
$usr = $res[$i];
$FileIDs[$cntr] = $usr->id;
$cntr++;
}
$sk = $uf->getSearchKeyByFirstName($data[1]);
$sk2 = $uf->getSearchKeyByLastName($data[0]);
$res = $gf->find(array($sk, $sk2), true);
for ($i=0;$i<sizeof($res);$i++){
$usr = $res[$i];
$FileIDs[$cntr] = $usr->id;
$cntr++;
}
}//else address #+STREET?
else{
if ($data[1] != ""){
$streetNb = intval($data[0]);
$streetName = $data[1];
$gf->setFinder($if);
$sk = $if->getSearchKeyByAddrNumber($streetNb);
$sk2 = $if->getSearchKeyByAddrStreet($streetName);
$res = $gf->find(array($sk, $sk2), true);
$cntr = 0;
for ($i=0;$i<sizeof($res);$i++){
$fileInfo = $res[$i];
$fileId = $fileInfo->getFamilyId();
$file = new File($fileId, false);
$FileIDs[$cntr] = $file->independentId;
$cntr++;
}
}
}
}
}
}
}
//getAllFilesFromEvent
$subFolder="\\..\\..\\view\\Components\\";
include_once($subFolder."MiniFileFoundBuilder.php");
$subFolder="\\..\\..\\view\\Components\\";
include_once($subFolder."Gallery.php");
$NumOfFilesFound=sizeof($FileIDs);
$UserIDs = $FileIDs;
$toRet = "";
$toMatch = $key;
$builder = new MiniFileFoundBuilder(null, null, $EventID);
$Gallery = new Gallery($builder);
$Gallery->doSearch($FileIDs, $toMatch);
$toRet = $Gallery->getContainer()->toHTML();
/*
for($i=0; $i<$NumOfFilesFound;$i++){
$builder = new MiniFileFoundBuilder($UserIDs[$i], $toMatch, $EventID);
$toRet .=$builder->getContainer()->toHTML();
}
*/
echo $toRet;
?> |
C++ | UTF-8 | 1,756 | 3.25 | 3 | [] | no_license | //
// main.cpp
// bsearch
//
// Created by Sridhar on 21/09/12.
// Copyright (c) 2012 Sridhar. All rights reserved.
//
#include <iostream>
using namespace std;
#define null 0
typedef struct linkedlist
{
int num;
struct linkedlist *r;
struct linkedlist *l;
}dlist;
dlist *root=null;
void create()
{
dlist *new1,*temp1,*temp2;
new1=(dlist *)malloc(sizeof(dlist));
cout<<"Creating a new node"<<endl;
cout<<"enter number"<<endl;
cin>>new1->num;
new1->l=null;
new1->r=null;
if(root==null)
{
root=new1;
return;
}
temp1=root;
temp2=root;
while(temp2!=null)
{
temp1=temp2;
if(new1->num > temp1->num)
temp2=temp2->r;
if(new1->num < temp1->num)
temp2=temp2->l;
}
if(new1->num > temp1->num)
{ temp1->r=new1;
cout<<"this number added to right "<<temp1->num<<endl;
}
else
{ temp1->l=new1;
cout<<"this number added to left "<<temp1->num<<endl;
}
}
void bsearch()
{int n;
dlist *temp1,*temp2;
cout<<"enter number to search"<<endl;
cin>>n;
temp1=root;
temp2=root;
if(temp1->num==n)
{cout<<"found"<<endl;
return ;}
else
{
while(temp2!=null)
{temp1=temp2;
if(n>temp1->num)
temp2=temp2->r;
if(n<temp1->num)
temp2=temp2->l;
if(temp1->num==n)
{
cout<<"found"<<endl;
return;
}
}
if(temp2==null && temp1->num!=n)
cout<<"not found"<<endl;
}
}
int main(int argc, const char * argv[])
{int i=0;
while(i<10)
{
create();
i++;}
while(1)
bsearch();
return 0;
}
|
C++ | UTF-8 | 2,305 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
struct node
{
int n; // nr wierzcho�ka
node * next;
};
const int V = 5;
bool czy_dwudzielny(node * G[V], int colour[V]) // s - wierzcho�ek startowy
{
queue < int > Q;
for (int i = 0; i < V; i++)
colour[i] = 0;
for (int i = 0; i < V; i++)
{
if (colour[i] == 0)
{
colour[i] = 1; // wierzcho�ek startowy - na czerwono
Q.push(i); // wrzucamy wierzcho�ek do kolejki
while (!Q.empty())
{
int v = Q.front();
Q.pop();
for (node * j = G[v]; j != NULL; j = j->next)
{
int u = j->n;
if (colour[u] == colour[v]) return false;
if (colour[u] == 0)
{
colour[u] = -colour[v];
Q.push(u);
}
}
}
}
}
return true;
}
void tab_to_lists(int Gtab[V][V], node * G[V])
{
for (int i = 0; i < V - 1; i++)
{
for (int j = i + 1; j < V; j++)
{
if (Gtab[i][j] != 0)
{
cout << i << " ," << j << endl;
node * nowy1 = new node;
nowy1->n = j;
nowy1->next = NULL;
if (G[i] != NULL)
{
node * prev1 = G[i];
while (prev1->next != NULL)
prev1 = prev1->next;
prev1->next = nowy1;
}
else
{
G[i] = nowy1;
}
node * nowy2 = new node;
nowy2->n = i;
nowy2->next = NULL;
if (G[j] == NULL)
{
G[j] = nowy2;
}
else
{
node * prev2 = G[j];
while (prev2->next != NULL)
prev2 = prev2->next;
prev2->next = nowy2;
}
}
}
}
}
void tab_to_lists_skier(int Gtab[V][V], node * G[V])
{
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (Gtab[i][j] != 0)
{
cout << i << " ," << j << endl;
node * nowy1 = new node;
nowy1->n = j;
nowy1->next = NULL;
if (G[i] != NULL)
{
node * prev1 = G[i];
while (prev1->next != NULL)
prev1 = prev1->next;
prev1->next = nowy1;
}
else
{
G[i] = nowy1;
}
}
}
}
}
void main()
{
int Gt[V][V] = { { 0, 1, 1, 1, 1 },{ 0, 1, 1, 1, 1 },{ 1, 1, 0, 0, 0 },{ 1, 1, 0, 0, 0 },{ 1, 1, 0, 0, 0 } };
node * G[V];
for (int i = 0; i < V; i++)
G[i] = NULL;
tab_to_lists(Gt, G);
int colour1[V];
if (czy_dwudzielny(G, colour1)) cout << "DWUDZIELNY";
else cout << "NIE JEST DWUDZIELNY";
cout << endl;
int a;
cin >> a;
} |
C# | UTF-8 | 1,254 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PMetodosMenus
{
public partial class frmExercicio2 : Form
{
Int32 meio = 0;
string compara, primeira, segunda;
public frmExercicio2()
{
InitializeComponent();
}
private void btnIguais_Click(object sender, EventArgs e)
{
compara = (String.Compare(txtPalavra1.Text, txtPalavra2.Text, true) == 0 ? "Ahibaa" : "São diferentes");
MessageBox.Show(compara);
}
private void btnInserePala1_Click(object sender, EventArgs e)
{
meio = (txtPalavra2.Text.Length / 2);
txtPalavra2.Text = txtPalavra2.Text.Substring(0, meio) + txtPalavra1.Text +
txtPalavra2.Text.Substring(meio, txtPalavra2.Text.Length-meio);
}
private void btnAsterisco_Click(object sender, EventArgs e)
{
meio = txtPalavra1.Text.Length / 2;
txtPalavra2.Text = txtPalavra1.Text.Insert(meio, "**");
}
}
}
|
Python | UTF-8 | 683 | 2.6875 | 3 | [] | no_license | import tensorflow as tf
import numpy as np
def thoraric_surgery_learning():
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
np.random.seed(3)
tf.compat.v1.set_random_seed(3)
data_set = np.loadtxt("dataset/ThoraricSurgery.csv", delimiter=",")
x = data_set[:, 0:17]
y = data_set[:, 17]
model = Sequential()
model.add(Dense(30, input_dim=17, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x, y, epochs=100, batch_size=10)
if __name__ == "__main__":
thoraric_surgery_learning()
|
Java | UTF-8 | 9,503 | 2.875 | 3 | [] | no_license | package test;
import java.util.ArrayList;
import java.util.List;
import scheduler.MessageHandlerTerminationMessageAware;
import scheduler.MessageImpl;
import scheduler.TerminationMessage;
import scheduler.TerminationMessageProcessedException;
import scheduler.interfaces.Message;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestMessageHandlerTerminationMessageAware {
@Test
/**Description: Message in a group occurs after a TerminationMessage for that
* group.
* Expected: Should throw TerminationMessageProcessedException*/
public void test_sendMessages_messageEncounteredAfterTerminationMessageProcessed(){
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(2);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new MessageImpl(2));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(new TerminationMessage(2));
unprocessedMessages.add(new MessageImpl(2));
unprocessedMessages.add(new MessageImpl(1));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
assertEquals(TerminationMessageProcessedException.class, e.getClass());
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
verifyAllMessagesAreProcessed(processedMessages);
//only two messages should be processed
assertEquals(2, processedMessages.size());
}
@Test
/**Description: TerminationMessage for a group occurs last for that group
* Expected: no exception*/
public void test_sendMessages_terminationMessageOccursLast() {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(2));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(new TerminationMessage(2));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(5));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
fail("Exception not expected. Expected all messages to be processed");
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
verifyAllMessagesAreProcessed(processedMessages);
//all messages should be processed
assertEquals(unprocessedMessages.size(), processedMessages.size());
}
@Test
/**Description: The TerminationMessage for a group occurs first in the batch.
* Expected: TerminationMessageProcessedException after the termination
*message is processed.*/
public void test_sendMessages_terminationMessageOccursFirstInBatch () {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new TerminationMessage(2));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(2));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(5));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
//expecting TerminationMessageProcessedException
assertEquals(TerminationMessageProcessedException.class, e.getClass());
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
//expecting only the termination message to be processed
verifyAllMessagesAreProcessed(processedMessages);
assertEquals(1, processedMessages.size());
}
@Test
/**Description: The TerminationMessage for a group occurs first.
* Expected: TerminationMessageProcessedException after the termination
*message is processed. All eligible messages before this
*should be processed. */
public void test_sendMessages_terminationMessageOccursFirstForGroup () {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new TerminationMessage(2));
unprocessedMessages.add(new MessageImpl(2));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
//expecting TerminationMessageProcessedException
assertEquals(TerminationMessageProcessedException.class, e.getClass());
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
//expecting messages up to the termination message to be processed
verifyAllMessagesAreProcessed(processedMessages);
int expectedSize = unprocessedMessages.size() - 1;
assertEquals(expectedSize, processedMessages.size());
}
@Test
/**Description: No Termination message in batch
* Expected: All messages should be processed without exception*/
public void test_sendMessages_noTerminationMessage() {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(2));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
//no exception expected
fail("Exception not expected. Expected all messages to be processed");
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
//all messages should be processed
verifyAllMessagesAreProcessed(processedMessages);
assertEquals(unprocessedMessages.size(), processedMessages.size());
}
@Test
/**Description: Null message occurs in the list to be processed.
*Expected: InvalidArgumentException.*/
public void test_sendMessages_nullMessageInBatch() {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(1));
unprocessedMessages.add(null);
unprocessedMessages.add(new MessageImpl(5));
unprocessedMessages.add(new MessageImpl(2));
try{
messageHandler.sendMessages(unprocessedMessages);
} catch (Exception e) {
//expecting an IllegalArgumentException
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
/**Description: Check that empty list is correctly handled
*Expected: No exception, no messages returned. */
public void test_sendMessages_emptyList() {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
List<Message> unprocessedMessages = new ArrayList<Message> ();
try {
messageHandler.sendMessages(unprocessedMessages);
}catch (Exception e) {
fail("Exception not expected.");
}
List<Message> processedMessages = messageHandler.getProcessedMessages();
assertEquals(0, processedMessages.size());
}
@Test
/**Description: Add a processed message
*Expected: Message should be added to processed messages list */
public void test_addProcessedMessage_processedMessage() {
Message message = new MessageImpl(1);
message.completed();
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
try {
messageHandler.addProcessedMessage(message);
} catch (Exception e) {
fail("Exception not expected");
}
assertEquals(1, messageHandler.getProcessedMessages().size());
}
@Test
/**Description: Attempt to add an unprocessed message
*Expected: IllegalArgumentException */
public void test_addProcessedMessage_unprocessedMessage() {
Message message = new MessageImpl(1);
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
try {
messageHandler.addProcessedMessage(message);
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
/**Description: Attempt to add a null message
*Expected: IllegalArgumentException */
public void test_addProcessedMessage_nullMessage() {
MessageHandlerTerminationMessageAware messageHandler =
new MessageHandlerTerminationMessageAware(1);
try {
messageHandler.addProcessedMessage(null);
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
/**Description: Invalid argument in constructor.
*Expected: IllegalArgumentException
* */
public void test_constructor_invalidArgument() {
try {
new MessageHandlerTerminationMessageAware(-1);
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
/*Verifies that all Messages in the list have been processed.*/
private void verifyAllMessagesAreProcessed(List<Message> messages) {
for (Message m : messages) {
assertTrue("Found unprocessed Message " + m +
" among processed Messages!",
((MessageImpl)m).isCompleted());
}
}
}
|
Markdown | UTF-8 | 1,587 | 2.78125 | 3 | [] | no_license | # Status
[](https://www.repostatus.org/#inactive)[](https://circleci.com/gh/eapowertools/qrs-interact/)
[](https://nodei.co/npm/qrs-interact/)
## qrs-interact
QRS Interact is a simple javascript library that allows users to send queries to the Qlik Sense Repository Service.
### Getting Started
For more information and advanced usage, please reference the [wiki](https://github.com/eapowertools/qrs-interact/wiki).
#### Installing
```npm install qrs-interact```
#### Usage
To use the qrs-interact module, first you must create a new instance.
```
var <variableName> = new qrsInteract(<someHostname>);
```
Once you have initialized an instance, GET, POST, PUT, and DELETE all return promises. They can be used as follows.
```
<instanceName>.Get(<somePath>)
.then(function(result)
{
// do some work
})
.catch(function(error)
{
// catch the error
});
```
##### Example
```
var qrsInteract = require('qrs-interact');
var instance1 = new qrsInteract("abc.qlik.com");
instance1.Get('about')
.then(function(result)
{
console.log(result);
})
.catch(function(error)
{
console.log(error);
});
```
|
Python | UTF-8 | 327 | 3.59375 | 4 | [
"CC0-1.0",
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Juan Emilio Martinez Manjon
"""
from math import sqrt
cateto1 = float(input("Introduzca el primer cateto dle triangulo:"))
cateto2 = float(input("Introduzca el segundo cateto dle triangulo:"))
hipotenusa = sqrt(cateto1*cateto1 + cateto2*cateto2)
print("La hipotenusa es:",hipotenusa)
|
C | UTF-8 | 516 | 2.703125 | 3 | [] | no_license | #include "share_queue.h"
#include <stdio.h>
#define SHM_SIZE 18
int main()
{
const char *data = "hello";
const char *key_path = "/Users/zhanggx/code/share_queue/test/share_queue.key";
shm_queue_t queue;
if (shm_queue_init(&queue, key_path, SHM_SIZE))
{
perror("shm_queue_init failed");
return -1;
}
for (size_t i = 0; i < 1; ++i)
{
if (shm_queue_push(&queue, data, 5))
{
perror("shm_queue_push failed");
return -1;
}
printf("push success\n");
}
shm_queue_clear(&queue, 0);
return 0;
}
|
Java | UTF-8 | 7,174 | 1.71875 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | package com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Support.classes;
import com.runtimeconverter.runtime.nativeInterfaces.Countable;
import com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Support.classes.Arr;
import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs;
import com.runtimeconverter.runtime.classes.StaticBaseClass;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Support.classes.MessageBag;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences;
import com.runtimeconverter.runtime.references.ReferenceClassProperty;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.reflection.ReflectionClassData;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import java.lang.invoke.MethodHandles;
import com.runtimeconverter.runtime.classes.NoConstructor;
import com.runtimeconverter.runtime.tools.PackedVaradicArgs;
import com.runtimeconverter.runtime.arrays.ArrayAction;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import static com.runtimeconverter.runtime.ZVal.arrayActionR;
import static com.runtimeconverter.runtime.ZVal.toStringR;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/laravel/framework/src/Illuminate/Support/ViewErrorBag.php
*/
public class ViewErrorBag extends RuntimeClassBase implements Countable {
public Object bags = ZVal.newArray();
public ViewErrorBag(RuntimeEnv env, Object... args) {
super(env);
}
public ViewErrorBag(NoConstructor n) {
super(n);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "key")
public Object hasBag(RuntimeEnv env, Object... args) {
Object key = assignParameter(args, 0, true);
if (null == key) {
key = "default";
}
return ZVal.assign(
arrayActionR(
ArrayAction.ISSET,
new ReferenceClassProperty(this, "bags", env),
env,
key));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "key")
public Object getBag(RuntimeEnv env, Object... args) {
Object key = assignParameter(args, 0, false);
Object ternaryExpressionTemp = null;
return ZVal.assign(
ZVal.isTrue(
ternaryExpressionTemp =
Arr.runtimeStaticObject.get(env, this.bags, key))
? ternaryExpressionTemp
: new MessageBag(env));
}
@ConvertedMethod
public Object getBags(RuntimeEnv env, Object... args) {
return ZVal.assign(this.bags);
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "key")
@ConvertedParameter(
index = 1,
name = "bag",
typeHint = "Illuminate\\Contracts\\Support\\MessageBag"
)
public Object put(RuntimeEnv env, Object... args) {
Object key = assignParameter(args, 0, false);
Object bag = assignParameter(args, 1, false);
new ReferenceClassProperty(this, "bags", env).arrayAccess(env, key).set(bag);
return ZVal.assign(this);
}
@ConvertedMethod
public Object any(RuntimeEnv env, Object... args) {
return ZVal.assign(ZVal.isGreaterThan(this.count(env), '>', 0));
}
@ConvertedMethod
public Object count(RuntimeEnv env, Object... args) {
return ZVal.assign(
env.callMethod(this.getBag(env, "default"), "count", ViewErrorBag.class));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "method")
@ConvertedParameter(index = 1, name = "parameters")
public Object __call(RuntimeEnv env, Object... args) {
Object method = assignParameter(args, 0, false);
Object parameters = assignParameter(args, 1, false);
return ZVal.assign(
env.callMethod(
this.getBag(env, "default"),
new RuntimeArgsWithReferences(),
toStringR(method, env),
ViewErrorBag.class,
PackedVaradicArgs.unpack(new PackedVaradicArgs(parameters))));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "key")
public Object __get(RuntimeEnv env, Object... args) {
Object key = assignParameter(args, 0, false);
return ZVal.assign(this.getBag(env, key));
}
@ConvertedMethod
@ConvertedParameter(index = 0, name = "key")
@ConvertedParameter(index = 1, name = "value")
public Object __set(RuntimeEnv env, Object... args) {
Object key = assignParameter(args, 0, false);
Object value = assignParameter(args, 1, false);
this.put(env, key, value);
return null;
}
@ConvertedMethod
public Object __toString(RuntimeEnv env, Object... args) {
return ZVal.assign(toStringR(this.getBag(env, "default"), env));
}
public static final Object CONST_class = "Illuminate\\Support\\ViewErrorBag";
// Runtime Converter Internals
// RuntimeStaticCompanion contains static methods
// RequestStaticProperties contains static (per-request) properties
// ReflectionClassData contains php reflection data used by the runtime library
public static class RuntimeStaticCompanion extends StaticBaseClass {
private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup();
}
public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion();
private static final ReflectionClassData runtimeConverterReflectionData =
ReflectionClassData.builder()
.setName("Illuminate\\Support\\ViewErrorBag")
.setLookup(
ViewErrorBag.class,
MethodHandles.lookup(),
RuntimeStaticCompanion.staticCompanionLookup)
.setLocalProperties("bags")
.setFilename("vendor/laravel/framework/src/Illuminate/Support/ViewErrorBag.php")
.addInterface("Countable")
.get();
@Override
public ReflectionClassData getRuntimeConverterReflectionData() {
return runtimeConverterReflectionData;
}
@Override
public Object converterRuntimeCallExtended(
RuntimeEnv env,
String method,
Class<?> caller,
PassByReferenceArgs passByReferenceArgs,
Object... args) {
return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic(
this,
runtimeConverterReflectionData,
env,
method,
caller,
passByReferenceArgs,
args);
}
}
|
JavaScript | UTF-8 | 483 | 2.8125 | 3 | [] | no_license | //-------------------------Toogle imagenes de recetas------
let mostrarRecetas = document.querySelectorAll(".card-title")
let cuerpoRecetas = document.querySelectorAll(".card-body")
mostrarRecetas.forEach((mostrarReceta) => {
mostrarReceta.addEventListener("click", () => {
cuerpoRecetas.forEach((cuerpoReceta) => {
cuerpoReceta.classList.toggle('toggleCard');
console.log(mostrarReceta, cuerpoReceta)
})
})
}) |
SQL | UTF-8 | 547 | 4.125 | 4 | [] | no_license | -- DML (CRUD)
-- 1. INSERT 구문
INSERT INTO `TBL`(
`COL1`,
`COL2`
)VALUE(
'VAL1',
'VAL2'
);
-- 2. SELECT 구문
SELECT `ID`, `NAME`
FROM `TBL`
WHERE '조건';
-- 뒤에 WHERE, GROUP BY, ORDER BY 등이 온다.
-- 3. UPDATE 구문
UPDATE `TDL`
SET `COL1` = 'VAL1',
`COL2` = 'VAL2'
WHERE '조건';
-- 4. DELETE 구문
DELETE FROM `TBL`
WHERE '조건';
-- 5. 테이블 열 정보 출력
DESC MEMBER;
-- 6. column명 대체 별칭 사용하기
SELECT ID `STUDENT ID`, PWD PW, NAME `STUDENT NAME`, GENDER `남 여` FROM MEMBER;
|
Java | UTF-8 | 1,418 | 2.390625 | 2 | [] | no_license | package test.supplier;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
/**
* Тестирование поступления заказа, доставки и его завершения
*/
public class SupplierReceiveAndDeliverAndCompleteTest extends SupplierOrderTest {
private final static Logger logger
= LoggerFactory.getLogger(SupplierReceiveAndDeliverAndCompleteTest.class);
@Test
public void receiveAndDeliverAndCompleteOrder() {
logger.info("Заказ, доставка и завершение заказа");
Long supplierStorageID = 1L;
Long shopStorageID = 3L;
List<Long> productIDList = Arrays.asList(1L, 4L);
List<Integer> countList = Arrays.asList(46, 10);
Object[] parameters
= receiveOrder(supplierStorageID, shopStorageID, productIDList, countList);
Long deliveryID = (Long)parameters[0];
int productCountSum = (Integer) parameters[3];
BigDecimal productPriceSum = (BigDecimal) parameters[4];
BigDecimal shopPreviousBudget = (BigDecimal) parameters[5];
deliverOrder(deliveryID);
completeOrder(deliveryID,
shopStorageID,
productCountSum,
productPriceSum,
shopPreviousBudget);
}
}
|
Python | UTF-8 | 3,736 | 2.671875 | 3 | [
"MIT"
] | permissive | import heat as ht
from .test_suites.basic_test import TestCase
class TestStrideTricks(TestCase):
def test_broadcast_shape(self):
self.assertEqual(ht.core.stride_tricks.broadcast_shape((5, 4), (4,)), (5, 4))
self.assertEqual(
ht.core.stride_tricks.broadcast_shape((1, 100, 1), (10, 1, 5)), (10, 100, 5)
)
self.assertEqual(
ht.core.stride_tricks.broadcast_shape((8, 1, 6, 1), (7, 1, 5)), (8, 7, 6, 5)
)
# invalid value ranges
with self.assertRaises(ValueError):
ht.core.stride_tricks.broadcast_shape((5, 4), (5,))
with self.assertRaises(ValueError):
ht.core.stride_tricks.broadcast_shape((5, 4), (2, 3))
with self.assertRaises(ValueError):
ht.core.stride_tricks.broadcast_shape((5, 2), (5, 2, 3))
with self.assertRaises(ValueError):
ht.core.stride_tricks.broadcast_shape((2, 1), (8, 4, 3))
def test_sanitize_axis(self):
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4, 4), 1), 1)
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4, 4), -1), 2)
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4, 4), 2), 2)
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4, 4), (0, 1)), (0, 1))
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4, 4), (-2, -3)), (1, 0))
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4), 0), 0)
self.assertEqual(ht.core.stride_tricks.sanitize_axis((5, 4), None), None)
self.assertEqual(ht.core.stride_tricks.sanitize_axis(tuple(), 0), None)
# invalid types
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_axis((5, 4), 1.0)
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_axis((5, 4), "axis")
# invalid value ranges
with self.assertRaises(ValueError):
ht.core.stride_tricks.sanitize_axis((5, 4), 2)
with self.assertRaises(ValueError):
ht.core.stride_tricks.sanitize_axis((5, 4), -3)
with self.assertRaises(ValueError):
ht.core.stride_tricks.sanitize_axis((5, 4, 4), (-4, 1))
def test_sanitize_shape(self):
# valid integers and iterables
self.assertEqual(ht.core.stride_tricks.sanitize_shape(1), (1,))
self.assertEqual(ht.core.stride_tricks.sanitize_shape([1, 2]), (1, 2))
self.assertEqual(ht.core.stride_tricks.sanitize_shape((1, 2)), (1, 2))
# invalid value ranges
with self.assertRaises(ValueError):
ht.core.stride_tricks.sanitize_shape(-1)
with self.assertRaises(ValueError):
ht.core.stride_tricks.sanitize_shape((2, -1))
# invalid types
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_shape("shape")
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_shape(1.0)
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_shape((1, 1.0))
def test_sanitize_slice(self):
test_slice = slice(None, None, None)
ret_slice = ht.core.stride_tricks.sanitize_slice(test_slice, 100)
self.assertEqual(ret_slice.start, 0)
self.assertEqual(ret_slice.stop, 100)
self.assertEqual(ret_slice.step, 1)
test_slice = slice(-50, -5, 2)
ret_slice = ht.core.stride_tricks.sanitize_slice(test_slice, 100)
self.assertEqual(ret_slice.start, 50)
self.assertEqual(ret_slice.stop, 95)
self.assertEqual(ret_slice.step, 2)
with self.assertRaises(TypeError):
ht.core.stride_tricks.sanitize_slice("test_slice", 100)
|
C# | UTF-8 | 448 | 2.578125 | 3 | [] | no_license | using (var stream = File.Create("test.pdf"))
using (var doc = new Document())
using (var pdfWriter = PdfWriter.GetInstance(doc, stream))
{
doc.Open();
foreach (var file in ofd.SafeFileNames)
{
using (var imageStream = File.OpenRead(file))
{
var image = Image.GetInstance(imageStream);
doc.Add(image);
}
}
doc.Close();
}
|
Markdown | UTF-8 | 2,481 | 3.265625 | 3 | [
"MIT"
] | permissive | This is a brief introduction to the most used commands that you will (probably) need for navigating around the server.
### Get your current location.
```
pwd
```
### Changing directories
```
# Moving to your home directory
cd
# Moving forward
cd path/to/directory
# Moving to the parent/previous directory
cd ..
```
### List directory contents
```
# List the content of your current directory
ls
# List the content of a child directory
ls path/to/directory
# Useful flags
## List directory contents in long format and in a human-readable version.
ls -lh
## List also hidden files (preceded by a dot)
ls -a
```
### Create a new directory
```
mkdir <dir-name>
```
### Copy content from a source to a destination.
#### Copying on the same system.
```
cp <source> <dest>
```
#### Copying from a remote system to a local system (assuming that you type this command from your local machine).
```
scp ho_user@uc1.scc.kit.edu:/work/workspace/scratch/ho_user-foo-0/fox.txt /home/user/
```
#### Copying from a local system to a remote system (again, assuming that you enter this command from your local machine).
```
scp /home/user/fox.txt scp ho_user@uc1.scc.kit.edu:/work/workspace/scratch/ho_user-foo-0/
```
### Move and/or rename content.
```
# Move a file to another directory.
mv <file> path/to/directory
# Rename a file.
mv fox.txt dog.txt
```
### Remove content.
Please be **careful with this command** as purging content cannot be reversed! It is always a good idea to append the `rm` command with the `-i` (interactive, evoked for every object) or the `-I` (interactive, evoked for up to three objects) flags in order to ensure that you do not delete content unintentionally.
```
# Remove a file
rm <filename>
# Remove an empty directory
rmdir <dir-name>
# Recursively remove a directory
rm -r <dir-name>
```
### Display file output.
#### Output first/last lines of a file.
```
# Default: display the first five lines
head <file>
# Default: display the last five lines
tail <file>
# Display the first <integer> lines (also works with tail)
head -n <integer>
```
#### Show the entire file
```
less <file>
```
The `less` command opens a file that can then be browsed by pressing `j` (downwards scrolling) or `k` (upwards scrolling).
### Open the manual for a command.
(Almost) every command has its own manual entry, which can be evoked by typing `man <command>` (*e.g.* `man ls`). The manual page can be browsed in the same manner as files opened with the `less` command described above.
|
SQL | UTF-8 | 18,202 | 4.03125 | 4 | [] | no_license | WITH cte_ra_contacts
AS (SELECT
ACCT_ROLE.CUST_ACCOUNT_ROLE_ID AS CONTACT_ID,
SUBSTR (PARTY.PERSON_LAST_NAME, 1, 50) AS last_name,
SUBSTR (PARTY.PERSON_FIRST_NAME, 1, 40) AS first_name
FROM
rawdb.HZ_CUST_ACCOUNT_ROLES ACCT_ROLE
INNER JOIN
rawdb.HZ_RELATIONSHIPS REL
ON
ACCT_ROLE.PARTY_ID = REL.PARTY_ID
INNER JOIN
rawdb.HZ_ORG_CONTACTS ORG_CONT
ON
ORG_CONT.PARTY_RELATIONSHIP_ID = REL.RELATIONSHIP_ID
INNER JOIN
rawdb.HZ_PARTIES PARTY
ON
REL.SUBJECT_ID = PARTY.PARTY_ID
INNER JOIN
rawdb.HZ_CUST_ACCOUNTS ROLE_ACCT
ON
ACCT_ROLE.CUST_ACCOUNT_ID = ROLE_ACCT.CUST_ACCOUNT_ID
and ROLE_ACCT.PARTY_ID = REL.OBJECT_ID
WHERE
ACCT_ROLE.ROLE_TYPE = 'CONTACT'
and REL.SUBJECT_TABLE_NAME = 'HZ_PARTIES'
and REL.OBJECT_TABLE_NAME = 'HZ_PARTIES'
),
cte_su
AS (SELECT service_order_id, contact_id,
MAX(CASE site_use_code WHEN 'BILL_TO' THEN site_use_id ELSE NULL END)
bill_to_site_use_id,
MAX(CASE site_use_code WHEN 'SHIP_TO' THEN site_use_id ELSE NULL END)
ship_to_site_use_id,
MAX(CASE site_use_code WHEN 'SOLD_TO' THEN site_use_id ELSE NULL END)
sold_to_site_use_id,
MAX(CASE site_use_code WHEN 'BILL_TO' THEN contact_id ELSE NULL END)
bill_to_contact_id,
MAX(CASE site_use_code WHEN 'SHIP_TO' THEN contact_id ELSE NULL END)
ship_to_contact_id,
MAX(CASE site_use_code WHEN 'SOLD_TO' THEN contact_id ELSE NULL END)
sold_to_contact_id,
MAX (last_update_date) max_last_update_date
FROM
rawdb.joe_so_addresses
WHERE
site_use_code IN ('BILL_TO', 'SOLD_TO', 'SHIP_TO')
GROUP BY
service_order_id, contact_id
)
SELECT
jso.service_order_id as SERVICE_ORDER_NUMBER,
jso.description as SERVICE_ORDER_DESCRIPTION,
jso.service_order_type as SERVICE_ORDER_TYPE,
jso.assignment_type as ASSIGNMENT_TYPE,
cast(coalesce(jrs.salesrep_number) as bigint) as SALES_REP_NUMBER,
hca.account_number as ORACLE_CUSTOMER_NUMBER,
jso.order_group as ORDER_GROUP,
jso.event as EVENT_CODE,
jcl_event.meaning as EVENT_DESC,
jso.so_program as PROGRAM_CODE,
s_program.description as PROGRAM_DESC,
jso.status as STATUS,
jso.reason as REASON,
REPLACE (SUBSTR (jso.comments, 1, 750), CHR (9), CHR (32)) AS COMMENTS,
jso.sales_year as SALES_YEAR,
su.ship_to_site_use_id as SHIP_TO_ADDRESS_ID,
su.sold_to_site_use_id as SOLD_TO_ADDRESS_ID,
su.bill_to_site_use_id as BILL_TO_ADDRESS_ID,
(select last_name FROM cte_ra_contacts, rawdb.joe_so_addresses jsa RIGHT OUTER JOIN cte_su su on jsa.contact_id = su.ship_to_contact_id) as SHIP_TO_CONTACT,
jso.purchase_order_num as PURCHASE_ORDER_NUMBER,
jso.copied_from_service_order_id as COPY_FROM_SERVICE_ORDER_NUMBER,
jso.orig_system_source as ORIG_SYSTEM_SOURCE,
jso.orig_system_reference as ORIG_SYSTEM_REFERENCE,
jso.assigned_customer_service_team as ASSIGNED_CUSTOMER_SERVICE_TEAM,
jcl_team.meaning as CUSTOMER_SERVICE_TEAM_NAME,
jso.assigned_customer_service_rep as ASSIGNED_CUSTOMER_SERVICE_REP,
fu.user_name as CUSTOMER_SERVICE_REP_NAME,
date_format(jso.start_date_active, '%d-%m-%Y') as start_date_active,
date_format(jso.end_date_active, '%d-%m-%Y') as END_DATE_ACTIVE,
oa.name as AGREEMENT_NUMBER,
oa.agreement_num as AGREEMENT_NAME,
oa.agreement_type_code as AGREEMENT_TYPE_CODE,
ol.meaning as AGREEMENT_TYPE_DESC,
opl.name as AGREEMENT_PRICE_LIST,
rt.name as AGREEMENT_TERMS,
date_format(oa.start_date_active, '%d-%m-%Y') as AGREEMENT_START_DATE_ACTIVE,
date_format(oa.end_date_active, '%d-%m-%Y') as AGREEMENT_END_DATE_ACTIVE,
jso.product_offering_usage as PRODUCT_OFFERING_USAGE,
jso.pricing_method as PRICING_METHOD,
SUBSTR (jso.special_instructions, 1, 2000) as SPECIAL_INSTRUCTIONS,
jcl_pack.meaning as PACKING_METHOD,
REPLACE(jso.packing_instructions, CHR(9), CHR(32)) as PACKING_INSTRUCTIONS,
jso.ship_method_code as SHIP_METHOD_CODE,
jcl_ship.meaning as SHIP_METHOD_DESC,
REPLACE (jso.shipping_instructions, CHR (9), CHR (32)) as SHIPPING_INSTRUCTIONS,
jso.freight_terms_code as FREIGHT_TERMS,
jso.invoice_frequency as INVOICE_FREQUENCY,
REPLACE (jso.invoice_comments, CHR (9), CHR (32)) as INVOICE_COMMENTS,
jso.commission_program_code as COMMISSION_PROGRAM,
jso.primary_service_order_flag as PRIMARY_SERVICE_ORDER_FLAG,
jso.annual_roll_flag as ANNUAL_ROLL_FLAG,
jso.order_line_summarization_flag as ORDER_LINE_SUMMARIZATION_FLAG,
jso.warehouse_id as WAREHOUSE_ID,
jso.consolidated_ship_warehouse_id as CONSOLIDATED_SHIP_WAREHOUSE_ID,
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute1
ELSE
NULL
END
AS RECG_TAPE_FREQUENCIES,
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute2
ELSE
NULL
END
AS RECG_SOLICIT_FREQUENCIES,
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute3
ELSE
NULL
END
AS RECG_SHIP_FREQUENCIES,
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute4
ELSE
NULL
END
AS RECG_DOWN_SELECT,
CASE
WHEN
jso.context = 'RECG'
THEN
CASE
WHEN
jsojd.attribute5 = 'NO'
THEN
'N'
WHEN
jsojd.attribute5 = 'YES'
THEN
'Y'
ELSE
jsojd.attribute5
END
ELSE
NULL
END
AS RECG_AWARD_WO_LOGO,
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute6
ELSE
NULL
END
AS RECG_DEDICATED_800_NUMBER, /*dedicated_800_number*/
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute7
ELSE
NULL
END
AS RECG_FAX_NUMBER, /*fax_number*/
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute8
ELSE
NULL
END
AS RECG_IVR_NUMBER, /*ivr_number*/
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute9
ELSE
NULL
END
AS RECG_WEB_SITE, /*web_site*/
CASE
WHEN
jso.context = 'RECG'
THEN
jsojd.attribute10
ELSE
NULL
END
AS RECG_CRM, /*crm*/
CASE WHEN jso.order_group IN ('COMM', 'DIPL') THEN CASE WHEN STRPOS (jso.service_order_type, '-') > 0 THEN SUBSTR (jso.service_order_type, 1, (STRPOS (jso.service_order_type, '-') - 1)) ELSE jso.service_order_type END ELSE NULL END as SERVICE_ORDER_TYPE1,
CASE WHEN jso.order_group IN ('COMM', 'DIPL') THEN CASE WHEN STRPOS (jso.service_order_type, '-') > 0 THEN SUBSTR (jso.service_order_type, (STRPOS (jso.service_order_type, '-') + 1)) ELSE NULL END ELSE NULL END AS SERVICE_ORDER_TYPE2,
jso.salesrep_tx_type as SALES_REP_TRANSACTION_TYPE,
fndu.user_name as CREATED_BY,
date_format(jso.creation_date, '%d-%m-%Y %H:%i:%s') as CREATION_DATE,
so_creation.user_name as FIRST_ACTIVATED_BY,
so_creation.creation_date as FIRST_ACTIVATION_DATE,
jso.price_builder_code as PRICE_BUILDER,
CASE
WHEN
jso.context = 'DIPL'
THEN
jsojd.attribute10
ELSE
NULL
END
AS DIPL_ROLLED_FROM_SERVICE_ORDER, /*rolled_from_service_order*/
CASE
WHEN
jso.context = 'DIPL'
THEN
jsojd.attribute11
ELSE
NULL
END
AS DIPL_GROUPING, /*GROUPING*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute1
ELSE
NULL
END
as YBMS_JOB_NUMBER, /*job_number*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute2
ELSE
NULL
END
as YBMS_YEARBOOK_YEAR, /*yearbook_year*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute3
ELSE
NULL
END
as YBMS_PLANT, /*plant*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute4
ELSE
NULL
END
as YBMS_PROGRAM, /*program*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute5
ELSE
NULL
END
AS YBMS_TRIM_SIZE, /*trim_size*/
cast(
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute6
ELSE
NULL
END
as bigint) as YBMS_PAGES, /*pages*/
/*pages*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute7
ELSE
NULL
END
as YBMS_COPIES, /*copies*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute10
ELSE
NULL
END
AS YBMS_YEARTECH_ONLINE, /*yeartech_online*/
CASE
WHEN
jso.context = 'YBMS'
THEN
jsojd.attribute11
ELSE
NULL
END
as YBMS_CONTRACT_SHIP_DATE, /*contract_ship_date*/
CASE
jso.context
WHEN
'ANNC'
THEN
SUBSTR (jsojd.ATTRIBUTE2 , 1, 1)
ELSE
NULL
END
AS ANNC_WEB_CATALOG_FLAG, UPPER (REPLACE (
CASE
WHEN
jso.context = 'DIPL'
THEN
jso.attribute9
WHEN
jso.context = 'GREG'
THEN
jso.attribute10
ELSE
NULL
END
, CHR (10), CHR (32))) as GT_PO_NUMBER_REQUIRED, REPLACE (jso.attribute15, CHR (10), '') as REGALIA_EMAIL_ADDRESS, UPPER (REPLACE (
CASE
WHEN
jso.context = 'DIPL'
THEN
jso.attribute14
WHEN
jso.context = 'GREG'
THEN
jso.attribute11
ELSE
NULL
END
, CHR (10), CHR (32))) as CONTACT_NAME,
CASE
WHEN
jso.context = 'DIPL'
THEN
REPLACE (jso.attribute15, CHR (10), '')
WHEN
jso.context = 'GREG'
THEN
REPLACE (jso.attribute15, CHR (10), '')
ELSE
NULL
END
AS CONTACT_EMAIL_ADDRESS, UPPER (REPLACE (
CASE
WHEN
jso.context = 'DIPL'
THEN
jso.attribute16
WHEN
jso.context = 'GREG'
THEN
jso.attribute14
ELSE
NULL
END
, CHR (10), CHR (32))) AS CONTACT_PHONE, UPPER (REPLACE (
CASE
WHEN
jso.context = 'DIPL'
THEN
jso.attribute17
ELSE
NULL
END
, CHR (10), CHR (32))) AS CONTACT_FAX,
CASE
jso.context
WHEN
'ANNC'
THEN
jso.attribute5
END
AS SCHEDULING_OFFSET_DAYS,
CASE
WHEN
jso.context = 'DIPL'
THEN
jso.attribute12
WHEN
jso.context = 'GREG'
THEN
jso.attribute12
ELSE
NULL
END
as HOMESHIP_FLAG, jso.context as CONTEXT,
jso.attribute1 as ATTRIBUTE1,
jso.attribute2 as ATTRIBUTE2,
jso.attribute3 as ATTRIBUTE3,
jso.attribute4 as ATTRIBUTE4,
jso.attribute5 as ATTRIBUTE5,
jso.attribute6 as ATTRIBUTE6,
jso.attribute7 as ATTRIBUTE7,
jso.attribute8 as ATTRIBUTE8,
jso.attribute9 as ATTRIBUTE9,
jso.attribute10 as ATTRIBUTE10,
jso.attribute11 as ATTRIBUTE11,
jso.attribute12 as ATTRIBUTE12,
jso.attribute13 as ATTRIBUTE13,
jso.attribute14 as ATTRIBUTE14,
REPLACE (jso.attribute15, CHR (10), '') as ATTRIBUTE15,
jso.attribute16 as ATTRIBUTE16,
jso.attribute17 as ATTRIBUTE17,
jso.attribute18 as ATTRIBUTE18,
jso.attribute19 as ATTRIBUTE19,
jso.attribute20 as ATTRIBUTE20,
jso.attribute21 as ATTRIBUTE21,
jso.attribute22 as ATTRIBUTE22,
jso.attribute23 as ATTRIBUTE23,
jso.attribute24 as ATTRIBUTE24,
jso.attribute25 as ATTRIBUTE25,
jso.attribute26 as ATTRIBUTE26,
jso.attribute27 as ATTRIBUTE27,
jso.attribute28 as ATTRIBUTE28,
jso.attribute29 as ATTRIBUTE29,
jso.attribute30 as ATTRIBUTE30
FROM
rawdb.joe_service_orders jso
INNER JOIN
rawdb.joe_service_orders jsojd
ON jso.service_order_id = jsojd.service_order_id
LEFT JOIN
(
SELECT
service_order_id,
MAX(
CASE
site_use_code
WHEN
'BILL_TO'
THEN
site_use_id
ELSE
NULL
END
) bill_to_site_use_id, MAX(
CASE
site_use_code
WHEN
'SHIP_TO'
THEN
site_use_id
ELSE
NULL
END
) ship_to_site_use_id, MAX(
CASE
site_use_code
WHEN
'SOLD_TO'
THEN
site_use_id
ELSE
NULL
END
) sold_to_site_use_id, MAX(
CASE
site_use_code
WHEN
'BILL_TO'
THEN
contact_id
ELSE
NULL
END
) bill_to_contact_id, MAX(
CASE
site_use_code
WHEN
'SHIP_TO'
THEN
contact_id
ELSE
NULL
END
) ship_to_contact_id, MAX(
CASE
site_use_code
WHEN
'SOLD_TO'
THEN
contact_id
ELSE
NULL
END
) sold_to_contact_id, MAX (last_update_date) max_last_update_date
FROM
rawdb.joe_so_addresses
WHERE
site_use_code IN
(
'BILL_TO', 'SOLD_TO', 'SHIP_TO'
)
GROUP BY
service_order_id
)
su
ON jso.service_order_id = su.service_order_id
LEFT JOIN
(
SELECT
jsa.service_order_id,
MAX (com1_salesrep_id) max_salesrep_id,
MAX (GREATEST (jtaa.last_update_date, jtaa.start_date)) max_last_update_date
FROM
rawdb.jfi_territory_assignments_all jtaa
inner join
rawdb.joe_service_orders jso
ON jso.assignment_type = jtaa.assignment_type
AND jso.customer_id = jtaa.customer_id
inner join
rawdb.joe_so_addresses jsa
on jso.service_order_id = jsa.service_order_id
AND jsa.site_use_id = jtaa.site_use_id
WHERE
jsa.site_use_code = 'SOLD_TO'
GROUP BY
jsa.service_order_id
)
rep
ON jso.service_order_id = rep.service_order_id
LEFT JOIN
(
SELECT
B.AGREEMENT_ID,
B.AGREEMENT_NUM,
B.AGREEMENT_TYPE_CODE,
B.PRICE_LIST_ID,
B.TERM_ID,
B.START_DATE_ACTIVE,
B.END_DATE_ACTIVE,
T.NAME,
B.LAST_UPDATE_DATE
FROM
rawdb.OE_AGREEMENTS_TL T
INNER JOIN
rawdb.OE_AGREEMENTS_B B
ON B.AGREEMENT_ID = T.AGREEMENT_ID
WHERE
T.LANGUAGE = 'US'
)
oa
ON jso.agreement_id = oa.agreement_id
LEFT JOIN
rawdb.hz_cust_accounts hca
ON jso.customer_id = hca.cust_account_id
LEFT JOIN
rawdb.fnd_user fu
ON jso.assigned_customer_service_rep = fu.user_id
LEFT JOIN
rawdb.jfn_common_lookups jcl_event
ON jcl_event.lookup_code = jso.event
AND jcl_event.lookup_type = 'SERVICE_ORDER_EVENTS_' || jso.order_group
LEFT JOIN
rawdb.jfn_common_lookups jcl_team
ON jcl_team.lookup_code = jso.assigned_customer_service_team
AND jcl_team.lookup_type = 'CUSTOMER_SERVICE_TEAMS_' || jso.order_group
LEFT JOIN
rawdb.oe_lookups ol
ON ol.lookup_code = oa.agreement_type_code
AND ol.lookup_type = 'AGREEMENT_TYPE'
LEFT JOIN
rawdb.oe_price_lists_vl opl
ON opl.price_list_id = oa.price_list_id
LEFT JOIN
rawdb.jfn_common_lookups jcl_ship
ON jcl_ship.lookup_code = jso.ship_method_code
AND jcl_ship.lookup_type = 'FREIGHT_VENDORS'
LEFT JOIN
rawdb.jfn_common_lookups jcl_pack
ON jcl_pack.lookup_code = jso.packing_method
AND jcl_pack.lookup_type = 'PACK_METHOD'
LEFT JOIN
rawdb.jtf_rs_salesreps jrs
ON jrs.salesrep_id = rep.max_salesrep_id
LEFT JOIN
(
SELECT
B.TERM_ID,
T.NAME
FROM
rawdb.RA_TERMS_TL T,
rawdb.RA_TERMS_B B
WHERE
B.TERM_ID = T.TERM_ID
AND T.LANGUAGE = 'US'
)
rt
ON rt.term_id = oa.term_id
LEFT JOIN
rawdb.fnd_flex_values_vl s_program
ON s_program.flex_value = jso.so_program
AND s_program.flex_value_set_id = 1002715 --flex_value_set_id
LEFT JOIN
rawdb.fnd_user fndu
ON fndu.user_id = jso.created_by
LEFT JOIN
(
SELECT DISTINCT
jsoh.service_order_id,
/*use distinct because service_order_id can have exact same create date in joe_so_status_history*/
fndu1.user_name,
date_format(jsoh.creation_date, '%d-%m-%Y %H:%i:%s') creation_date
FROM
rawdb.fnd_user fndu1
RIGHT OUTER JOIN
rawdb.joe_so_status_history jsoh
on jsoh.creation_date =
(
SELECT
MIN (jsoh1.creation_date)
FROM
rawdb.joe_so_status_history jsoh1
INNER JOIN rawdb.joe_so_status_history jsoh
ON
jsoh1.service_order_id = jsoh.service_order_id
)
AND fndu1.user_id = jsoh.created_by
WHERE
jsoh.status = 'ACTIVE'
)
so_creation
ON so_creation.service_order_id = jso.service_order_id
LEFT JOIN cte_su
on cte_su.contact_id = jsa.contact_id
LEFT JOIN cte_ra_contacts
on cte_ra_contacts.CONTACT_ID = jsa.CONTACT_ID
limit 10 |
Python | UTF-8 | 343 | 2.78125 | 3 | [] | no_license | from Crypto.Cipher import DES
f = open('key.txt', 'r')
key_hex = f.readline()[:-1] # discard newline
f.close()
KEY = key_hex.decode("hex")
IV = '13245678'
a = DES.new(KEY, DES.MODE_OFB, IV)
f = open('plaintext', 'r')
plaintext = f.read()
f.close()
ciphertext = a.encrypt(plaintext)
f = open('ciphertext', 'w')
f.write(ciphertext)
f.close()
|
Markdown | UTF-8 | 1,126 | 2.90625 | 3 | [] | no_license | # Graphics Project - Conor Tighe
# A 2D game for web browser
***
This is a game where the objective is to dodge the poisonous fish for as long as possible. every time a enemy
leaves the screen you score a point, but there speed improves and the number of enemys will increase as time goes on.
***
The libary I use in this game is called createJS which includes EaselJS and SoundJS. The sprites are taken from spritebase and the collision
detection I used was licenced by MIT as its more accurate and reliable for sprites then a box of if statements.
***
Game now requires internet as local library is no longer used, The url of createJS has replaced it. Github wont allow me to remove lib for some reason.
***
## Instructions:
+ Up arrow = move up.
+ Down arrow = move down.
+ Left arrow = move left.
+ right arrow = move right.
***
## Sources:
- [Sprites](http://spritedatabase.net/)
- [Soundtrack](https://www.youtube.com/watch?v=qtFuk0Cw64k)
- [Libary](http://www.createjs.com/)
- [Collision](https://github.com/olsn/Collision-Detection-for-EaselJS)
### Software used:
+ Brackets
+ Audacity
+ Photoshop
|
Python | UTF-8 | 295 | 2.6875 | 3 | [] | no_license | import win32clipboard
win32clipboard.OpenClipboard()
try :
clip2 = win32clipboard.GetClipboardData()
print(clip2)
except TypeError:
print("Nothing in clipboard !!!")
##win32clipboard.SetClipboardText(clip2)
win32clipboard.EmptyClipboard()
win32clipboard.CloseClipboard()
|
Java | UTF-8 | 1,861 | 2.546875 | 3 | [] | no_license | package com.sw.upload;
/**
* <p>Title: �������</p>
*
* <p>Description: ��Ҫ�����Ƕ�FileUploadStatus���й��?Ϊ�ͻ����ṩ��Ӧ��
* FileUploadStatus���������һ�������ࡣ</p>
*
*/
import java.util.Vector;
public class BeanControler {
private static BeanControler beanControler = new BeanControler();
private Vector vector = new Vector();
private BeanControler() {
}
public static BeanControler getInstance() {
return beanControler;
}
/**
* ȡ����ӦFileUploadStatus�����Ĵ洢λ��
*/
private int indexOf(String strID) {
int nReturn = -1;
for (int i = 0; i < vector.size(); i++) {
FileUploadStatus status = (FileUploadStatus) vector.elementAt(i);
if (status.getUploadAddr().equals(strID)) {
nReturn = i;
break;
}
}
return nReturn;
}
/**
* ȡ����ӦFileUploadStatus�����
*/
public FileUploadStatus getUploadStatus(String strID) {
return (FileUploadStatus) vector.elementAt(indexOf(strID));
}
/**
* �洢FileUploadStatus�����
*/
public void setUploadStatus(FileUploadStatus status) {
int nIndex = indexOf(status.getUploadAddr());
if ( -1 == nIndex) {
vector.add(status);
} else {
vector.insertElementAt(status, nIndex);
vector.removeElementAt(nIndex + 1);
}
}
/**
* ɾ��FileUploadStatus�����
*/
public void removeUploadStatus(String strID){
int nIndex = indexOf(strID);
if(-1!=nIndex)
vector.removeElementAt(nIndex);
}
}
|
Java | UTF-8 | 305 | 1.75 | 2 | [] | no_license | package com.kk.think.user.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/healthcheck")
public class HealthCheck {
@GET
@Path("/test")
public Response healthCheck() {
return Response.status(200).entity("Success").build();
}
}
|
PHP | UTF-8 | 3,527 | 2.75 | 3 | [] | no_license | <?php
use Dt\Lib\Tpl;
function normalizeRow($array)
{
$output = array();
if (is_array($array) && !empty($array)) $output = $array[0];
return $output;
}
function normalizeOneList($array, $id = null)
{
$output = array();
if (is_array($array)) {
foreach ($array as $ar) {
if ($id !== null) $output[] = $ar[$id];
else $output[] = $ar[0];
}
}
return $output;
}
function makeList($arr, $class, $type, $custom = null)
{
$list = '';
foreach ($arr as $a) {
if ($custom == null) $list .= "<$type id=\"$a\" class=\"$class\">" . $a . "</$type>";
else $list .= "<$type id=\"$a\" $custom class=\"$class\">" . $a . "</$type>";
}
$list .= '';
return $list;
}
function makeIdList($arr, $class, $type, $custom = null)
{
$list = '';
foreach ($arr as $a) {
if ($custom == null) $list .= "<$type id=\"$a[0]\" class=\"$class\">" . $a[1] . "</$type>";
else $list .= "<$type id=\"$a[0]\" $custom class=\"$class\">" . $a[1] . "</$type>";
}
$list .= '';
return $list;
}
function getTemplated($templateName, $args, $loop = false)
{
$template = new Tpl;
$template->setTemplate(DIR_TPL . '/' . $templateName . '.html');
if ($loop) {
$loop = $args['loop'];
unset($args['loop']);
$template->setVars($args);
$template->setLoops($loop);
} else {
$template->setVars($args);
}
$template->compile();
return $template->getCompiled();
}
function groupArray($arr)
{
foreach ($arr as $subarr) {
foreach ((array)$subarr as $id => $value) {
if (!isset($processed[$id])) {
$processed[$id] = array();
}
$processed[$id][] = $value;
}
}
return $processed;
}
function normalizeArray($arr)
{
foreach ($arr as $subarr) {
foreach ((array)$subarr as $id => $value) {
$processed[] = $value;
}
}
return $processed;
}
function checkPermissions($dir)
{
$perms = fileperms($dir);
switch ($perms & 0xF000) {
case 0xC000: // socket
$info = 's';
break;
case 0xA000: // symbolic link
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // block special
$info = 'b';
break;
case 0x4000: // directory
$info = 'd';
break;
case 0x2000: // character special
$info = 'c';
break;
case 0x1000: // FIFO pipe
$info = 'p';
break;
default: // unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x') :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x') :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x') :
(($perms & 0x0200) ? 'T' : '-'));
echo $info;
} |
Markdown | UTF-8 | 11,428 | 2.53125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: rabbitMQ-Spring配置
categories: java spring mq
tags: java spring mq
---
* content
{:toc}
> 我的技术博客,主要是记载看过的书以及对写的好的博客文章的搬运整理,方便自己他人查看,也方便别人指出我文章中的错误,达到一起学习的目的。
> 技术永无止境
本文主要是对spring文档中项目配置的部分翻译
# Messing with RabbitMQ
这份指导会带领你配置RabbitMQ AMQP服务器,从而发布和订阅消息。
## What you'll build
你可以通过Spring AMQP‘s `RabbitTemplate`去发布消息,在POJO上面用`MessageListenerAdapter`去订阅该消息
## Build wiht Maven
创建下面的工作目录,例如,在*nix系统,可以通过命令`mkdir -p src/main/java/hello`
### pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-messaging-rabbitmq</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
Spring Boot Maven 插件提供了一下很方便的特性。
* 收集classpath上面所有的jar,然后建立一个单一的,可以运行的jar,这样子很方便去运行和传送你的服务。
* 他会查找`public static void main()`方法,去标志为运行类
* 他会提供自带的依赖解析去匹配Spring Boot依赖来设置版本数字。你可以覆盖你想要的任何版本,但是默认会使用Boot选择的版本
## Set up Rabbitmq broker
在你建立你的消息应用,你应该先设置处理接收发送信息的系统
RabbitMQ 是一个AMQP队列,可以在下面地址下载[http://www.rabbitmq.com/download.html](http://www.rabbitmq.com/download.html),你也可以通过下面命令下载
`brew install rabbitmq`
解压服务,然后使用默认设置启动它
`rabbitmq-server`
你会看到类似下面的信息
```
RabbitMQ 3.1.3. Copyright (C) 2007-2013 VMware, Inc.
## ## Licensed under the MPL. See http://www.rabbitmq.com/
## ##
########## Logs: /usr/local/var/log/rabbitmq/rabbit@localhost.log
###### ## /usr/local/var/log/rabbitmq/rabbit@localhost-sasl.log
##########
Starting broker... completed with 6 plugins.
```
如果你在本地有docker运行,你也可以通过Docker Compose去迅速启动一个RabbitMQ服务。这就是项目根目录的`docker-compose.yml`
```yml
rabbitmq:
image: rabbitmq:management
ports:
- "5672:5672"
- "15672:15672"
```
## Create a RabbitMQ message receiver
创建一个接受发布信息的接收器
`src/main/java/hello/Receiver.java`
```java
package hello;
import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
private CountDownLatch latch = new CountDownLatch(1);
public void receiveMessage(String message) {
System.out.println("Received <" + message + ">");
latch.countDown();
}
public CountDownLatch getLatch() {
return latch;
}
}
```
`Receiver`就是一个简单POJO,定义了接受消息的方法。当你注册他去结合搜消息,你可以任意命名塔。
为了方便,POJO有一个`CountDownLatch`。这样子允许提示知道消息已经被接受。在生产应用,不太会使用这种方式。
## Register the listener and send a message
Spring AMQP’s `RabbitTemplate`提供你在RabbitMQ发送接受消息的任意需求.具体来说,你需要配置
* 消息监听器容器
* 显示声明队列,交换机,已经他们的关联。
* 一个发送消息的组件去测试监听器
Spring Boot会自动创建连接工厂和`RabbitTemplate`,减少你需要写的代码。
你会使用`RabbitTemplate`去发送消息,你会将`Receiver`注册到消息监听器容器,从而接收消息。连接工厂会驱动这两个,允许他们连接到RabbitMQ服务器上面。
`src/main/java/hello/Application.java`
```java
package hello;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
final static String queueName = "spring-boot";
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("spring-boot-exchange");
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(queueName);
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
}
```
`@SpringBootApplication` is a convenience annotation that adds all of the following:
* `@Configuration` tags the class as a source of bean definitions for the application context.
* `@EnableAutoConfiguration` tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
* Normally you would add `@EnableWebMvc` for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
* @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.
The `main()` method uses Spring Boot’s `SpringApplication.run()` method to launch an application. Did you notice that there wasn’t a single line of XML? No `web.xml` file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
The bean defined in the `listenerAdapter()` method is registered as a message listener in the container defined in container(). It will listen for messages on the "spring-boot" queue. Because the Receiver class is a POJO, it needs to be wrapped in the `MessageListenerAdapter`, where you specify it to invoke `receiveMessage`
> JMS queues and AMQP queues have different semantics. For example, JMS sends queued messages to only one consumer. While AMQP queues do the same thing, AMQP producers don’t send messages directly to queues. Instead, a message is sent to an exchange, which can go to a single queue, or fanout to multiple queues, emulating the concept of JMS topics. For more, see Understanding AMQP.
The message listener container and receiver beans are all you need to listen for messages. To send a message, you also need a Rabbit template.
The `queue()` method creates an AMQP queue. The `exchange()` method creates a topic exchange. The` binding()` method binds these two together, defining the behavior that occurs when RabbitTemplate publishes to an exchange.
> Spring AMQP requires that the Queue, the TopicExchange, and the Binding be declared as top level Spring beans in order to be set up properly.
## Send a Test Message
Test messages are sent by a `CommandLineRunner`, which also waits for the latch in the receiver and closes the application context:
`src/main/java/hello/Runner.java`
```java
package hello;
import java.util.concurrent.TimeUnit;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Runner implements CommandLineRunner {
private final RabbitTemplate rabbitTemplate;
private final Receiver receiver;
private final ConfigurableApplicationContext context;
public Runner(Receiver receiver, RabbitTemplate rabbitTemplate,
ConfigurableApplicationContext context) {
this.receiver = receiver;
this.rabbitTemplate = rabbitTemplate;
this.context = context;
}
@Override
public void run(String... args) throws Exception {
System.out.println("Sending message...");
rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);
context.close();
}
}
```
The runner can be mocked out in tests, so that the receiver can be tested in isolation.
## Run the Application
The `main()` method starts that process by creating a Spring application context. This starts the message listener container, which will start listening for messages. There is a `Runner` bean which is then automatically executed: it retrieves the `RabbitTemplate` from the application context and sends a "Hello from RabbitMQ!" message on the "spring-boot" queue. Finally, it closes the Spring application context and the application ends.
## Build an executable JAR
You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:
`java -jar target/gs-messaging-rabbitmq-0.1.0.jar`
You should see the following output:
```
Sending message...
Received <Hello from RabbitMQ!>
```
|
JavaScript | UTF-8 | 4,647 | 2.71875 | 3 | [] | no_license | import React, { Component } from 'react';
import axios from 'axios';
import Container from '@material-ui/core/Container';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Board from './components/board';
import Clue from './components/clue';
import ResetConfirmation from './components/resetConfirmation';
class App extends Component {
constructor() {
super();
this.state = {
categories: [],
categoriesAndClues: {},
numberOfCategories: 5,
numberOfClues: 5,
isDisplayingClue: false,
isResetConfirmationOpen: false,
offset: 0,
roundsPlayed: 0,
selectedClue: {},
};
}
componentDidMount() {
this.resetGame();
}
asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
};
getRandomIndex = (max) => {
return Math.floor(Math.random() * Math.floor(max));
};
handleClueSelection = (domEl, clue) => {
const { categoriesAndClues } = this.state;
const categoriesAndCluesCopy = { ...categoriesAndClues };
categoriesAndCluesCopy[clue.category.id][clue.id].selected = true;
this.setState({
selectedClue: clue,
isDisplayingClue: true,
categoriesAndClues: categoriesAndCluesCopy,
});
};
handleClueDone = () => {
this.setState({ isDisplayingClue: false });
};
handleResetConfirmationOpen = () => {
const { isResetConfirmationOpen } = this.state;
this.setState({ isResetConfirmationOpen: !isResetConfirmationOpen });
};
handleTextFieldChange = (e) => {
console.log(e.target);
console.log(e.target.value);
this.setState({ [e.target.id]: e.target.value });
};
placeDailyDouble = (helperObjCategory, categories) => {
const randomCategoriesIndex = this.getRandomIndex(categories.length);
const randomCategory = helperObjCategory[categories[randomCategoriesIndex].id];
const randomClueIndex = this.getRandomIndex(Object.keys(randomCategory).length);
const randomClueId = Object.keys(randomCategory)[randomClueIndex];
const randomClue = randomCategory[randomClueId];
randomClue.isDailyDouble = true;
};
resetGame = async () => {
const { numberOfCategories, offset, roundsPlayed } = this.state;
const baseUrl = `http://jservice.io/api`;
// get categories
const categoriesUrl = `${baseUrl}/categories?count=${numberOfCategories}&offset=${offset}`;
const categoriesResult = await axios.get(categoriesUrl);
const categories = categoriesResult.data;
// get clues for each category and format categories and clues
let helperObjCategory = {};
await this.asyncForEach(categories, async (category) => {
helperObjCategory[category.id] = {};
const cluesResult = await axios.get(`${baseUrl}/clues?category=${category.id}`);
await this.asyncForEach(cluesResult.data, (clue) => {
helperObjCategory[clue.category.id] = { ...helperObjCategory[clue.category.id], [clue.id]: clue }
});
});
// place daily double at a random clue within random category
this.placeDailyDouble(helperObjCategory, categories);
// roundsPlayed and offset variables
const newRoundsPlayed = roundsPlayed + 1;
const newOffset = Number(offset) + Number(numberOfCategories);
// save categories and clues in state
this.setState({ categoriesAndClues: helperObjCategory, categories, offset: newOffset, roundsPlayed: newRoundsPlayed })
};
render() {
const { categories, categoriesAndClues, isDisplayingClue, isResetConfirmationOpen, numberOfCategories, numberOfClues, selectedClue } = this.state;
return (
<Container>
<ResetConfirmation open={isResetConfirmationOpen} handleClose={this.handleResetConfirmationOpen} resetGame={this.resetGame} />
<TextField id="numberOfCategories" type="number" label="Number of categories" value={numberOfCategories} onChange={e => this.handleTextFieldChange(e)} />
<TextField id="numberOfClues" type="number" label="Number of clues per category" value={numberOfClues} onChange={e => this.handleTextFieldChange(e)} />
<Button variant="contained" color="primary" onClick={this.handleResetConfirmationOpen}>Reset</Button>
<h3>JEOPARDY!</h3>
{isDisplayingClue ? <Clue handleClueDone={this.handleClueDone} selectedClue={selectedClue} /> : <Board categories={categories} handleClueSelection={this.handleClueSelection} numberOfClues={numberOfClues} categoriesAndClues={categoriesAndClues} />}
</Container>
)
}
}
export default App;
|
Shell | UTF-8 | 922 | 3.453125 | 3 | [] | no_license | #!/bin/bash
set -e
if command -v git >/dev/null 2>&1; then
echo "git: exists"
elif command -v apt-get >/dev/null 2>&1; then
# ubuntu
sudo apt-get install -y git-all
elif command -v /opt/local/bin/port >/dev/null 2>&1; then
# macports
sudo port clean git-core
sudo port selfupdate
sudo port install git-core +svn+bash_completion+mp_completion
sudo port -n upgrade --enforce-variants git-core +svn+bash_completion+mp_completion
else
echo "ERROR: git is not installed"
exit 1
fi
# store git user info
FIX_GIT_USER=~/term-tools/fix-git-user.sh
git config -l | grep "^user" | sed 's/^/git config --global /' | sed 's/=/ "/' | sed 's/$/"/' > $FIX_GIT_USER
# use template
cp -f ~/term-tools/config/gitconfig-template ~/term-tools/config/gitconfig
# this will fail if it already exists, so we are safe
ln $@ -s ~/term-tools/config/gitconfig ~/.gitconfig
source $FIX_GIT_USER
rm $FIX_GIT_USER
|
C++ | UTF-8 | 575 | 3.15625 | 3 | [] | no_license | #include <fstream>
using namespace std;
ifstream is ("test.in");
ofstream os ("test.out");
bool Prim(int x);
int main()
{
int n;
int a[100];
is >> n;
for(int i = 1; i <= n; ++i)
{
is >> a[i];
if(Prim(a[i]))
os << a[i] << ' ';
}
return 0;
}
bool Prim(int x)
{
int d = 3;
if(x == 1 || x == 0)
return false;
if(x == 2)
return true;
if(x % 2 == 0)
return false;
while(d*d <= x)
{
if(x % d == 0)
return false;
d+=2;
}
return true;
}
|
C# | UTF-8 | 4,638 | 2.578125 | 3 | [
"MS-PL"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
using Ogdi.InteractiveSdk.Mvc.Repository;
namespace Ogdi.InteractiveSdk.Mvc.Models.Request
{
public class RequestListModel
{
public RequestFilter Filter {get; set;}
public RequestListModel()
{
OrderBy = new OrderByInfo { Direction = SortDirection.Desc, Field = Field.Name};
PageSize = 15;
PageNumber = 1;
}
public RequestListModel(CommonListData data)
{
OrderBy = data.OrderBy;
PageSize = data.PageSize;
PageNumber = data.PageNumber;
}
public RequestListModel(OrderByInfo orderBy, int pageSize, int pageNumber)
{
OrderBy = orderBy;
PageSize = pageSize;
PageNumber = pageNumber;
}
public RequestListModel(RequestFilter filter)
{
Filter = filter;
}
public OrderByInfo OrderBy { get; set; }
public int PageSize { get; set; }
public int PageNumber { get; set; }
private int _totalPages;
public int TotalPages
{
get
{
if (!_isInitialized)
Init();
return _totalPages;
}
}
private IEnumerable<Request> _list;
private bool _isInitialized;
private void Init()
{
var result =
RequestRepository.GetRequests(String.Empty, null, null);
IOrderedEnumerable<Request> sortedResult;
if (OrderBy.Direction == SortDirection.Asc)
{
switch (OrderBy.Field)
{
case Field.Name:
sortedResult = result.OrderBy(t => t.Subject);
break;
case Field.Description:
sortedResult = result.OrderBy(t => t.Description);
break;
case Field.Status:
sortedResult = result.OrderBy(t => t.Status);
break;
case Field.Date:
sortedResult = result.OrderBy(t => t.PostedDate);
break;
case Field.Rating:
sortedResult = result.OrderBy(t => t.PositiveVotes).OrderBy(t => t.PositiveVotes - t.NegativeVotes);
break;
case Field.Views:
sortedResult = result.OrderBy(t => t.Views);
break;
default:
sortedResult = result.OrderBy(t => t.Subject);
break;
}
}
else
{
switch (OrderBy.Field)
{
case Field.Name:
sortedResult = result.OrderByDescending(t => t.Subject);
break;
case Field.Description:
sortedResult = result.OrderByDescending(t => t.Description);
break;
case Field.Status:
sortedResult = result.OrderByDescending(t => t.Status);
break;
case Field.Date:
sortedResult = result.OrderByDescending(t => t.PostedDate);
break;
case Field.Rating:
sortedResult = result.OrderByDescending(t => t.PositiveVotes).OrderByDescending(t => t.PositiveVotes - t.NegativeVotes);
break;
case Field.Views:
sortedResult = result.OrderByDescending(t => t.Views);
break;
default:
sortedResult = result.OrderByDescending(t => t.Subject);
break;
}
}
_totalPages = ((sortedResult.Count() - 1) / PageSize) + 1;
_list = sortedResult
.Select((t, i) => new { t, i })
.Where(p => (p.i < PageNumber * PageSize))
.Where(p => (p.i >= (PageNumber - 1) * PageSize))
.Select(p => p.t);
_isInitialized = true;
}
public IEnumerable<Request> List
{
get
{
if (!_isInitialized)
Init();
return _list;
}
}
}
}
|
Ruby | UTF-8 | 499 | 2.859375 | 3 | [
"MIT"
] | permissive | require 'sinatra/activerecord'
require_relative '../models/badwords'
module BanFinder
def BanFinder.find_bannable(text, group_id)
words_db = Badwords.find_by(group_id: group_id)
banned_words = Array.new
words_db.each do |i|
banned_words.push(i.word)
end
tokens = text.split(' ')
tokens.each do |t|
banned_words.each do |b|
if b.eql?(t)
# Found a banned word
return b
end
end
end
return 'NOWORDSFOUND'
end
end |
Java | GB18030 | 5,397 | 2.703125 | 3 | [] | no_license | package com.alg.scholarship.view;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import com.alg.scholarship.bean.TypesOfStudentsWithDifficulties;
import com.alg.scholarship.dao.TypesOfStudentsWithDifficultiesDao;
public class TypesOfStudentsWithDifficultiesUpdateUI extends IndexAdmin{
// student
TypesOfStudentsWithDifficulties typesOfStudentsWithDifficulties;
public TypesOfStudentsWithDifficultiesUpdateUI(String username, int typesOfStudentsWithDifficultiesid) {
super(username);
// Ϊtypeֵ
TypesOfStudentsWithDifficultiesDao typesOfStudentsWithDifficultiesDao = new TypesOfStudentsWithDifficultiesDao();
// idѯϢ
typesOfStudentsWithDifficulties = typesOfStudentsWithDifficultiesDao.findTypesOfStudentsWithDifficultiesById(typesOfStudentsWithDifficultiesid);
// ʼ
init();
}
// õ
// ʼ
Font f = new Font("", Font.BOLD, 19);
// ʼ
JLabel idla = new JLabel("id:");
JLabel typela = new JLabel(":");
JLabel healthyla = new JLabel(":");
JLabel incomela = new JLabel("ͥ:");
JLabel regionla = new JLabel(":");
JTextField id = new JTextField();
JRadioButton radioButton1 = new JRadioButton("һƶ");
JRadioButton radioButton2 = new JRadioButton("رƶ");
JTextField healthy = new JTextField();
JTextField income = new JTextField();
JRadioButton radioButton3 = new JRadioButton("ʡ");
JRadioButton radioButton4 = new JRadioButton("ʡ");
// ť
ButtonGroup btButtonGroup = new ButtonGroup();
JButton addStudentButton = new JButton("");
private void init() {
// ť
ButtonGroup btButtonGroup = new ButtonGroup();
btButtonGroup.add(radioButton1);
btButtonGroup.add(radioButton2);
ButtonGroup btButtonGroup1 = new ButtonGroup();
btButtonGroup1.add(radioButton3);
btButtonGroup1.add(radioButton4);
// id
idla.setBounds(100, 20, 100, 30);
idla.setFont(f);
//
typela.setBounds(100, 70, 100, 30);
typela.setFont(f);
//
healthyla.setBounds(100, 120, 100, 30);
healthyla.setFont(f);
//
incomela.setBounds(100, 170, 130, 30);
incomela.setFont(f);
//
regionla.setBounds(100, 220, 100, 30);
regionla.setFont(f);
// //û
// id
id.setBounds(230, 20, 240, 30);
id.setFont(f);
id.setText(String.valueOf(typesOfStudentsWithDifficulties.getId()));
//
radioButton1.setBounds(230, 70, 100, 30);
radioButton2.setBounds(330, 70, 100, 30);
//
healthy.setBounds(230, 120, 240, 30);
healthy.setFont(f);
healthy.setText(typesOfStudentsWithDifficulties.getHealthy());
// ɼ
income.setBounds(230, 170, 240, 30);
income.setFont(f);
income.setText(String.valueOf(typesOfStudentsWithDifficulties.getIncome()));
// ״̬
radioButton3.setBounds(230, 220, 100, 30);
radioButton4.setBounds(330, 220, 100, 30);
// ť
addStudentButton.setBounds(170, 290, 180, 50);
addStudentButton.setFont(f);
// Ĭ
radioButton1.setSelected(typesOfStudentsWithDifficulties.getType() == 1 ? true : false);
radioButton2.setSelected(typesOfStudentsWithDifficulties.getType() == 0 ? true : false);
radioButton3.setSelected(typesOfStudentsWithDifficulties.getType() == 1 ? true : false);
radioButton4.setSelected(typesOfStudentsWithDifficulties.getType() == 0 ? true : false);
index.add(idla);
index.add(typela);
index.add(healthyla);
index.add(incomela);
index.add(regionla);
index.add(id);
index.add(healthy);
index.add(income);
index.add(radioButton1);
index.add(radioButton2);
index.add(radioButton3);
index.add(radioButton4);
index.add(addStudentButton);
// ¼
addStudentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String idText = id.getText();
int i = Integer.parseInt(idText);
String healthyText = healthy.getText();
String incomeText = income.getText();
int m = Integer.parseInt(incomeText);
// װϢ
typesOfStudentsWithDifficulties.setId(i);
typesOfStudentsWithDifficulties.setHealthy(healthyText);
typesOfStudentsWithDifficulties.setIncome(m);
if (radioButton1.isSelected()) {
typesOfStudentsWithDifficulties.setType(1);
}
if (radioButton2.isSelected()) {
typesOfStudentsWithDifficulties.setType(2);
}
if (radioButton3.isSelected()) {
typesOfStudentsWithDifficulties.setRegion(1);
}
if (radioButton4.isSelected()) {
typesOfStudentsWithDifficulties.setRegion(2);
}
//
TypesOfStudentsWithDifficultiesDao typesOfStudentsWithDifficultiesDao = new TypesOfStudentsWithDifficultiesDao();
int i1 = typesOfStudentsWithDifficultiesDao.updateTypesOfStudentsWithDifficultiesById(typesOfStudentsWithDifficulties);
if (i1 == 1) {
// ҳת
index.setVisible(false);
// µҳ
new TypesOfStudentsWithDifficultiesUI("mkx");
}
}
});
}
}
|
SQL | UTF-8 | 126 | 3.609375 | 4 | [] | no_license | SELECT e.name, b.bonus
FROM employee e
LEFT JOIN bonus b
ON (e.empid = b.empid)
WHERE (b.bonus < 1000
OR b.bonus IS NULL) |
C | UTF-8 | 491 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
void printfile(const char *filename){
FILE *p=fopen(filename,"r");
if(p==NULL){
printf("error is %s\n", strerror(errno));
return -1;
}
char buf[1024];
while(1){
memset(buf,0,sizeof(buf));
if(fgets(buf,sizeof(buf),p)==NULL){
break;
}
printf("%s\n",buf );
}
fclose(p);
}
int main(int arg,char *args[]){
printfile("/proc/cpuinfo");
printfile("/proc/meminfo");
return 0;
} |
JavaScript | UTF-8 | 385 | 3.265625 | 3 | [] | no_license | function output(m) {
for (var i = 1; i <= m; i++) {
var a = "";
for (var j = 1; j <= m - i; j++) {
var space = " ";
a = a + space;
}
for (var k = 1; k <= 2 * i - 1; k++) {
var star = "*";
a = a + star;
}
console.log(a);
}
}
var s = process.argv[2];
var m = parseInt(s);
output(m);
|
JavaScript | UTF-8 | 746 | 2.578125 | 3 | [] | no_license | // Third Party Libaries
var _api = require('./API');
// Helper function that takes movie info and makes MovieSummary object.
// This object is used for outputing it as a element in the list
// of the movies which are discovered.
function MovieSummary(movie, quest) {
if (movie['release_date']) {
this.year = movie['release_date'].split('-')[0];
}
this.title = movie['title'];
this.id = movie['id'];
if (quest != undefined) {
this.quest = quest;
};
var api = new _api.API();
var apiConfig = api.getConfig();
this.image = apiConfig['images']['secure_base_url'] + apiConfig['images']['poster_sizes'][0] + movie['poster_path'];
};
module.exports = {
function: MovieSummary,
MovieSummary : MovieSummary
};
|
Markdown | UTF-8 | 9,098 | 3.53125 | 4 | [] | no_license |
*****NOTE: My cousin borrowed my computer one month ago for his CS assignment using his github account, but I didn't realize. So this folder might shows two coordinators, one is "edwardyang12"(he), one is "ziyanc080"(me). But all the works are done by myself, without any collaboration with him or other people. I have already explained to the professor, and he suggested me write down here to inform the TA and graders. Thanks!******************************************
# HW1 EE599 - Computing Principles for Electrical Engineers
- Plesae clone the repository, edit [README.md](README.md) to answer the questions, and fill up functions to finish the hw.
- For non-coding quesitions, you will find **Answer** below each question. Please write your answer there.
- For coding questions, please make sure that your code can run ```blaze run/test```. In this homework, you will need to fill up [cpplib.cc](src/lib/cpplib.cc), [q5_student_test.cc](tests/q5_student_test.cc), [q6_student_test.cc](tests/q6_student_test.cc), [q7_student_test.cc](tests/q7_student_test.cc) for question 5, 6, 7.
- For submission, please push your answers to Github before the deadline.
- Deadline: Friday, September 4th by 6:30 pm
- Total: 120 points. 100 points is considered full credit.
## Question 1 (10 Points. Medium)
Use proof by contradiction to prove that the FindMax function always finds the maximum value in the input vector.
```cpp
int FindMax(std::vector<int> &inputs) {
if (inputs.size() == 0) {
return -1;
}
int result = INT32_MIN;
for (auto n : inputs) {
if (n > result) {
result = n;
}
}
return result;
}
```
Answer:
Assume to the contrary, this function cannot find the maximum value.
Suppose we have a number X, which is the largest number in input vector but not founded.
When this number is sent to this for loop, and reach the if statement, since this value is greater than all others numbers, the "result" will takes the value of X.
Hence, the result takes the largest value.
But out assumption is, the result is not the largest number, which is contradictory to our proved.
SO our assumption is false. This function can find the largest number.
## Question 2 (20 Points. Medium)
What is the time complexity of the below functions?
```cpp
int Example1(int n) {
int count = 0; 1
for (int i = n; i > 0; i /= 2) { logn
for (int j = 0; j < i; j++) { logn
count += 1; 1
}
}
return count; 1
}
```
Answer:
Run Time Analysis:
For outer for loop, since i get halved every time when this loop get excuted, the execution time is O(logn)
For inner for loop, since j adds from 0 to i, the executation time is the value of i each time.
Since we think normal arithmatic operation takes O(1) to complete, we simply ignore it here.
As a result, the total complexity is O(logn*logn) = O((logn)2)
T(n) Calculation:
if n=0, T(n)=2
if n>0: T(n)=1+logn*(logn+1)+1 = O(logn*logn)
```cpp
void Example2(int a = 0, int n) {
int i = n; 1
while (i > 0) { logn
a += i; 1
i /= 2; 1
}
}
```
Answer:
Run Time Analysis:
We analyse how many times the while loop get execueted. As shown here, i is initialized to n, and get halved every time this while loop get execueted.
As a result, it get execueted log(n) times.
Since we think normal arithmatic operation takes O(1) to complete, we simply ignore it here.
As a result, the total complexity is O(logn)
T(n) Calculation:
if n=0, T(n)=1
if n>0, T(n)=1+logn*2=O(logn)
```cpp
void Example3(int n) {
int count = 0; 1
for (int i=n/2; i<=n; i++) { n/2
for (int j=1; j<=n; j = 2 * j) { logn
for (int k=1; k<=n; k = k * 2) { logn
count++; 1
}
}
}
}
```
Answer:
Run Time Analysis:
For outer loop, since i increases by 1 every time, and initializd at n/2, so it get executed n/2 times.
For 2nd outer loop, since j double every time until it reaches n, and initializes at 1, so it get executed logn times
For inner loop, the condition is similar to j, so it get executed logn times.
We think normal arithmatic operation takes O(1) to complete.
So the total complexity is O(n/2 * logn * logn) = O (nlogn*logn)
T(n) Calculation:
if n=0, T(n)=1
if n>0, T(n)=1 + n/2 * (logn * logn) = O (nlogn*logn)
```cpp
void Example4(int n) {
int count = 0; 1
for (int i=0; i<n; i++) n
for (int j=i; j< i*i; j++) i2-i
if (j%i == 0) 1
{
for (int k=0; k<j; k++) j
cout<<"*"; 1
}
}
```
Answer:
Run Time Analysis:
For outer for loop, since i increases by 1 every time, and initializes at 0, so it get executed n times.
For inner loop, since j increases by 1 every time until reaches i*i, and initializes at i, so it get execueted i2-i each time.
For the k loop, since this only execuetes when j%i==0, which happens when j is the multiple of i. So, this get execueted when j=1i, 2i, 3i,,,ii, which is i times for each i
For the k loop itself, k loop is running j times for each j, so the running time for k loop is i+2i+3i+ ... +ii = O(i3) for each i
T(n) Calculation:
if n=0, T(n)=1
n
if n>0, T(n)=1 + n + Σ( i2-i+i3 ) = O(n4)
i=0
(n4 means is n to the power of 4)
## Question 3 (10 Points. Easy)
What does it mean when we say that the Merge Sort (MS) algorithm is asymptotically more efficient than the Bubble Sort (BS) algorithm? Support your choice with an explanation.
1. MS will always be a better choice for small inputs
2. MS will always be a better choice for large inputs
3. BS will always be a better choice for small inputs
4. MS will always be a better choice for all inputs
Answer:
My answer: 4
Explanation:
For bubble sort, in the worst case, every elements need to repeadtedly pass through the whole array, and the run time is O(n2)
For merge sort, when we have 1 input, the run time is O(1). When the inputs number increase, the run time T(n)=2T(n/2)+ 𝜭 (n) = O (nlogn)
So merge sort is better for all inputs in case of run time complexity (worst case).
## Question 4 (10 Points. Easy)
Create an account on GitHub and Stack Overflow and paste the link to your profile.
Answer:
GitHub profile link:
https://github.com/ziyanc080
Stack Overflow profile link:
https://stackexchange.com/users/19489462/ziyan-chen
## Question 5 (15 Points. Easy)
Write a simple function ```std::string CPPLib::PrintIntro()``` in [cpplib.cc](src/lib/cpplib.cc) to print your name, email, and any information about you that you want (e.g. your major, your expertise, your interests, etc) and write a test using GTest for your finction in [tests/q5_student_test.cc](tests/q5_student_test.cc).
We will run your code and see your printout!
Please create your test cases and run the following command to verify the functionality of your program.
```
bazel test tests:q5_student_test
```
## Question 6 (25 Points. Medium)
Write a function ```std::vector<int> CPPLib::Flatten2DVector(const std::vector<std::vector<int>> &input)``` in [cpplib.cc](src/lib/cpplib.cc) to flatten a 2D vector into a 1D vector.
Example:\
Input: inputs = [[1, 2, 3, 4], [5, 6], [7, 8]].\
Output: result = [1, 2, 3, 4, 5, 6, 7, 8].
Write several tests using GTest for your function in [tests/q6_student_test.cc](tests/q6_student_test.cc).\
(Hint: inculde cases with empty vectors)
Please create your test cases and run the following command to verify the functionality of your program.
```
bazel test tests:q6_student_test
```
## Question 7 (30 Points. Medium)
Write a function ```double CPPLib::CalFactorial(int N)``` in [cpplib.cc](src/lib/cpplib.cc) using recursion to find the factorial of any number. Your function should accept positive numbers and return the factorial value. Further, write several tests using GTest for your function in [tests/q7_student_test.cc](tests/q7_student_test.cc) and compute the time complexity of your implementation.
*Definition of the factorial function*\
In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:
```
n ! = n x (n - 1) x (n - 2) x (n - 3) ... (3) x (2) x (1)
```
For example, 4! = 4 × 3 × 2 × 1 = 24.\
The value of 0! is 1. For negative input, please return -1.
Please create your test cases and run the following command to verify the functionality of your program.
```
bazel test tests:q7_student_test
```
For question 5, 6, 7, if you want to run all the tests at the same time , you could run
```
bazel test tests:tests
```
Answer:
|
C# | UTF-8 | 2,194 | 2.515625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFollow : MonoBehaviour
{
public Transform player;
public Rigidbody2D rb;
public GameObject bullet;
public Transform weapon, firePoint, firePoint2;
public float speed, distanceBeforeAttack, bulletForce, shootDelay;
public EnemyBehaviour behaviour;
public bool dualShooter;
private float shootTimer;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
shootTimer = shootDelay;
}
void Update()
{
if (behaviour.hostile)
{
Look();
// Is it close enough to shoot?
if (Vector2.Distance(player.position, transform.position) <= distanceBeforeAttack)
{
if (shootTimer <= 0)
{
Shoot();
shootTimer = shootDelay;
}
}
else
{
Follow();
}
}
}
void FixedUpdate()
{
shootTimer -= 0.1f;
}
void Shoot()
{
GameObject bulletObj = Instantiate(bullet, firePoint.position, Quaternion.identity);
Rigidbody2D bulletRB = bulletObj.GetComponent<Rigidbody2D>();
bulletRB.AddForce(firePoint.up * bulletForce);
if (dualShooter)
{
GameObject bulletObj2 = Instantiate(bullet, firePoint2.position, Quaternion.identity);
Rigidbody2D bulletRB2 = bulletObj2.GetComponent<Rigidbody2D>();
bulletRB2.AddForce(firePoint.up * bulletForce);
}
}
void Follow()
{
// Get vector direction towards player.
Vector2 dir = player.position - transform.position;
// Apply force in that direction.
rb.AddForce(dir.normalized * speed * Time.deltaTime);
}
void Look()
{
// Get vector direction towards player.
Vector2 dir = player.position - transform.position;
// Rotate weapon.
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
weapon.rotation = Quaternion.Euler(0, 0, angle);
}
}
|
JavaScript | UTF-8 | 1,696 | 3.515625 | 4 | [] | no_license | // Function for Increase and Decrease input value
function handleSeat(isIncrease, seat) {
const seatInput = document.getElementById(seat + "-quantity")
const seatCount = parseInt(seatInput.value)
let seatNewCount = seatCount
if (isIncrease == true) {
seatNewCount = seatCount + 1
} else if (isIncrease == false && seatCount > 0) {
seatNewCount = seatCount - 1
}
seatInput.value = seatNewCount;
calculateTotal();
}
// Function for Get input value
function getInputValue(seat) {
const seatInput = document.getElementById(seat + '-quantity');
const seatCount = parseInt(seatInput.value);
return seatCount;
}
// Function for calculate sub-total, tax and grand-total
function calculateTotal() {
const firstClassCount = getInputValue('first-class');
const economyCount = getInputValue('economy');
const totalPrice = firstClassCount * 150 + economyCount * 100;
document.getElementById('subtotal').innerText = '$' + totalPrice;
const tax = Math.round(totalPrice * 0.1);
document.getElementById('tax-amount').innerText = '$' + tax;
const grandTotal = totalPrice + tax;
document.getElementById('grand-total').innerText = '$' + grandTotal;
}
// Function for show success message
function successMessage() {
var grandTotal = document.getElementById('grand-total').innerText;
if (grandTotal !== '$0') {
document.getElementById('submit').style.display = "none";
document.getElementById('message').style.display = "block";
var x = document.getElementsByClassName("control");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
} |
Java | UTF-8 | 330 | 1.796875 | 2 | [] | no_license | package cn.design.adapter.service.impl;
import cn.design.adapter.service.AdapterOrderService;
import java.util.logging.Logger;
public class OrderService implements AdapterOrderService {
@Override
public boolean getFirstOrderByid(String id) {
System.out.println("外部请求");
return true;
}
}
|
Java | UTF-8 | 1,680 | 2.421875 | 2 | [] | no_license | package com.pps.sharpturn.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.pps.sharpturn.R;
import com.pps.sharpturn.model.SharpModel;
public class SharpBookAdapter extends BaseAdapter {
private Context mContext;
private List<SharpModel> mLists;
private LayoutInflater mLayoutInflater;
public SharpBookAdapter(Context pContext,List<SharpModel> pLists){
this.mContext=pContext;
this.mLists=pLists;
this.mLayoutInflater=LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mLists!=null?mLists.size():0;
}
@Override
public Object getItem(int position) {
return mLists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Hondler _Hondler;
if(convertView==null){
_Hondler=new Hondler();
convertView=mLayoutInflater.inflate(R.layout.book_item, null);
_Hondler.book_item_name=(TextView)convertView.findViewById(R.id.book_item_name);
_Hondler.book_item_answer=(TextView)convertView.findViewById(R.id.book_item_answer);
convertView.setTag(_Hondler);
}else {
_Hondler=(Hondler)convertView.getTag();
}
_Hondler.book_item_name.setText(mLists.get(position).getName());
_Hondler.book_item_answer.setText(mLists.get(position).getAnswer());
return convertView;
}
final class Hondler{
TextView book_item_name;
TextView book_item_answer;
}
}
|
PHP | UTF-8 | 14,488 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php
namespace PrateekKathal\SimpleCurl;
use PrateekKathal\SimpleCurl\ResponseTransformer;
class SimpleCurl
{
/**
* Config Variable
*
* @var array
*/
protected $config;
/**
* CURL Response
*
* @var array
*/
protected $response;
/**
* URL of CURL request
*
* @var string
*/
protected $url;
/**
* Headers sent in CURL Request
*
* @var array
*/
protected $headers;
/**
* SimpleCurl Constructor
*
* @param string $app
*/
public function __construct(array $config = [])
{
$this->setConfigParams($config);
$this->response = $this->url = '';
$this->headers = [];
$this->responseTransformer = new ResponseTransformer;
}
/**
* Curl GET Request
*
* @param string $url
* @param array $data
* @param array $headers
*
* @return array
*/
public function get($url, $data = [], $headers = [])
{
return $this->request('GET', $this->getFullUrl($url), $data, $this->getAllHeaders($headers));
}
/**
* Curl POST Request
*
* @param string $url
* @param array $data
* @param array $headers
* @param string $file
*
* @return array
*/
public function post($url, $data = [], $headers = [], $file = false)
{
return $this->request('POST', $this->getFullUrl($url), $data, $this->getAllHeaders($headers), $file);
}
/**
* Curl PUT Request
*
* @param string $url
* @param array $data
* @param array $headers
*
* @return array
*/
public function put($url, $data = [], $headers = [])
{
return $this->request('PUT', $this->getFullUrl($url), $data, $this->getAllHeaders($headers));
}
/**
* Curl DELETE Request
*
* @param string $url
* @param array $data
* @param array $headers
*
* @return array
*/
public function delete($url, $data = [], $headers = [])
{
return $this->request('DELETE', $this->getFullUrl($url), $data, $this->getAllHeaders($headers));
}
/**
* Get Config Variables
*
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* Return a new class with own config Variables
*
* @param array $config
*
* @return PrateekKathal/SimpleCurl/SimpleCurl
*/
public function setConfig(array $config = [])
{
return new self($config);
}
/**
* Set Config Variables
*
* @param array $config
*
* @return array
*/
public function setConfigParams($config = [])
{
$this->resetConfig();
foreach ($config as $key => $value) {
switch ($key) {
case 'connectTimeout':
case 'dataTimeout':
case 'userAgent':
case 'baseUrl':
case 'buildQuery':
case 'defaultHeaders':
case 'defaultDataKey':
case 'parseErrors':
$this->validateInputs($key, $config[$key]);
$this->config[$key] = $config[$key];
break;
default: break;
}
}
return $this->config;
}
/**
* Reset Config Variables
*
* @return SimpleCurl
*/
public function resetConfig()
{
$this->config = [
'connectTimeout' => 10,
'dataTimeout' => 30,
'userAgent' => request()->header('User-Agent'),
'baseUrl' => '',
'buildQuery' => true,
'defaultHeaders' => [],
'defaultDataKey' => '',
'parseErrors' => true,
];
return $this;
}
/**
* Set Base URL
*
* @param string $url
*
* @return SimpleCurl
*/
public function setBaseUrl($url)
{
$this->validateInputs('baseUrl', $url);
$this->config['baseUrl'] = $url;
return $this;
}
/**
* Set Default Data Key
*
* @param string $key
*/
public function setDataKey($key)
{
$this->validateInputs('defaultDataKey', $key);
$this->config['defaultDataKey'] = $key;
return $this;
}
/**
* Set Default Data Key
*
* @param string $headers
*/
public function setDefaultHeaders($headers)
{
$this->validateInputs('defaultHeaders', $headers);
$this->config['defaultHeaders'] = $headers;
return $this;
}
/**
* Set User Agent Key
*
* @param string $userAgent
*/
public function setUserAgent($userAgent)
{
$this->validateInputs('userAgent', $userAgent);
$this->config['userAgent'] = $userAgent;
return $this;
}
/**
* Set Build Query Key
*
* @param boolean $buildQuery
*/
public function setBuildQuery($buildQuery = true)
{
$this->validateInputs('buildQuery', $buildQuery);
$this->config['buildQuery'] = $buildQuery;
return $this;
}
/**
* Get Full URL
*
* @param string $url
*
* @return string
*/
private function getFullUrl($url)
{
return $this->url = $this->config['baseUrl'].$url;
}
/**
* Get Default Headers
*
* @return array
*/
private function getDefaultHeaders()
{
return $this->config['defaultHeaders'];
}
/**
* Get All Headers
*
* @param array $headers
*
* @return array
*/
public function getAllHeaders($headers)
{
return array_merge($this->config['defaultHeaders'], $headers);
}
/**
* Get Curl Result
*
* @return array
*/
public function getCurlResult()
{
return $this->response;
}
/**
* Get Response
*
* @return array
*/
public function getResponse()
{
return $this->response['result'];
}
/**
* Get Response HTTP Code
*
* @return int
*/
public function getResponseCode()
{
return $this->response['http_code'];
}
/**
* Get Response Content Type
*
* @return sting
*/
public function getResponseContentType()
{
return $this->response['content_type'];
}
/**
* Get Request Size
*
* @return sting
*/
public function getRequestSize()
{
return $this->response['request_size'];
}
/**
* Get Request URL
*
* @return string
*/
public function getRequestUrl()
{
return $this->response['url'];
}
/**
* Get Curl Error
*
* @return string
*/
public function getCurlError()
{
return $this->response['curl_error'];
}
/**
* Get Redirect Count
*
* @return int
*/
public function getRedirectCount()
{
return $this->response['redirect_count'];
}
/**
* Get Last Effective URL
*
* @return string
*/
public function getEffectiveUrl()
{
return $this->response['effective_url'];
}
/**
* Get Time Taken for the CURL Request
*
* @return float
*/
public function getTotalTime()
{
return $this->response['total_time'];
}
/**
* Get Default Data Key
*
* @return string
*/
public function getDataKey()
{
return $this->config['defaultDataKey'];
}
/**
* Check if `parseErrors` key is true
*
* @return string
*/
public function isErrorParsed()
{
return $this->config['parseErrors'];
}
/**
* GET Response as JSON
*
* @return JSON
*/
public function getResponseAsJson()
{
return $this->responseTransformer
->setResponse($this->getResponse(), $this->getDataKey(), $this->isErrorParsed())
->toJson();
}
/**
* Get Response as Array
*
* @return array
*/
public function getResponseAsArray()
{
return $this->responseTransformer
->setResponse($this->getResponse(), $this->getDataKey(), $this->isErrorParsed())
->toArray();
}
/**
* Get Response as Collection
*
* @return Collection
*/
public function getResponseAsCollection($model = null)
{
return $this->responseTransformer
->setResponse($this->getResponse(), $this->getDataKey(), $this->isErrorParsed())
->toCollection($model);
}
/**
* Get Response as Model
*
* @param string $modelName
*
* @return Model
*/
public function getResponseAsModel($modelName, $relations = [])
{
return $this->responseTransformer
->setResponse($this->getResponse(), $this->getDataKey(), $this->isErrorParsed())
->toModel($modelName, $relations);
}
/**
* Get Response as Model
*
* @param string $modelName
*
* @return LengthAwarePaginator
*/
public function getPaginatedResponse($perPage = 10)
{
return $this->responseTransformer
->setResponse($this->getResponse(), $this->getDataKey(), $this->isErrorParsed())
->toPaginated($perPage);
}
/**
* CURL Request
*
* @param string $type
* @param string $url
* @param string $data
* @param array $headers
* @param string $file
*
* @return array
*/
private function request($type, $url, $data = [], $headers = [], $file = false)
{
try {
$this->validateInputs('fullUrl', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $this->config['userAgent']);
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($type == 'POST' && !empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
} else if ($type == 'PUT' || $type == 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
}
if (!empty($file) || in_array('Content-Type: application/json', $headers)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} else if($this->config['buildQuery']) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->config['connectTimeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->config['dataTimeout']);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$requestSize = curl_getinfo($ch, CURLINFO_REQUEST_SIZE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$redirectCount = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT);
$effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
$curlError = curl_error($ch);
curl_close($ch);
$this->response = [
'http_code' => $httpCode, 'request_size' => $requestSize, 'curl_error' => $curlError,
'url' => $url, 'content_type' => $contentType, 'redirect_count' => $redirectCount,
'effective_url' => $effectiveUrl, 'total_time' => $totalTime, 'result' => $result
];
if ($httpCode == "200") {
$this->response['status'] = 'success';
} else {
$this->response['status'] = 'failed';
}
return $this;
} catch (Exception $e) {
$this->response = [
'http_code' => null, 'request_size' => null, 'curl_error' => null,
'url' => $url, 'content_type' => null, 'redirect_count' => null,
'effective_url' => null, 'total_time' => null, 'result' => $e
];
return $this;
}
}
/**
* Validate Inputs Before Sending CURL Request
*
* @param string $url
* @param array $data
* @param array $headers
*
* @return array
*/
private function validateInputs($type, $data)
{
switch ($type) {
case 'connectTimeout':
if (!is_integer($data)) {
throw new \Exception('Connect Timeout must an integer');
}
break;
case 'dataTimeout':
if (!is_integer($data)) {
throw new \Exception('Data Timeout must an integer');
}
break;
case 'userAgent':
if (!is_string($data)) {
throw new \Exception('User Agent must be a string');
}
break;
case 'baseUrl':
if (!is_string($data)) {
throw new \Exception('Base URL must be a string');
}
break;
case 'buildQuery':
if (!is_bool($data)) {
throw new \Exception('Build Query must be a boolean');
}
break;
case 'fullUrl':
if (empty($data)) {
throw new \Exception('URL must not be empty');
}
if (!is_string($data)) {
throw new \Exception('URL must be a string');
}
break;
case 'defaultHeaders':
if (!is_array($data)) {
throw new \Exception('Headers must be an array');
}
break;
case 'defaultDataKey':
if (!is_string($data)) {
throw new \Exception('Default Data Key must be a string');
}
break;
case 'parseErrors':
if (!is_bool($data)) {
throw new \Exception('Parse Errors must be a boolean');
}
break;
default:
break;
}
}
}
|
Java | UTF-8 | 8,500 | 1.953125 | 2 | [] | no_license | package com.example.wlk.zzuar.obj;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.util.SparseArray;
import com.example.wlk.zzuar.utils.Gl2Utils;
import com.example.wlk.zzuar.utils.MatrixUtils;
import com.example.wlk.zzuar.utils.ObjUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class GLGod {
private static final String TAG ="GLGod" ;
private static Context context;
private static GLGod THEGod=null;
public static boolean DEBUG=true;
/**
* 单位矩阵
*/
public static final float[] OM= MatrixUtils.getOriginalMatrix();
/**
* 程序句柄
*/
protected int mProgram;
/**
* 顶点坐标句柄
*/
protected int mHPosition;
/**
* 纹理坐标句柄
*/
protected int mHCoord;
/**
* 总变换矩阵句柄
*/
protected int mHMatrixHandler;
/**
* 默认纹理贴图句柄
*/
protected int mHTexture;
protected Resources mRes;
/**
* 顶点坐标Buffer
*/
protected FloatBuffer mVerBuffer;
/**
* 纹理坐标Buffer
*/
protected FloatBuffer mTexBuffer;
/**
* 索引坐标Buffer
*/
protected ShortBuffer mindexBuffer;
protected int mFlag=0;
//private float[] matrix= Arrays.copyOf(OM,16);
private float[] cameraMatrix =MatrixUtils.getOriginalMatrix();
private float[] projMatrix = MatrixUtils.getOriginalMatrix();
private float[] finalMatrix ;
private int textureType=0; //默认使用Texture2D0
//顶点坐标
private float pos[] = {
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, 1.0f,
1.0f, -1.0f,
};
//纹理坐标
private float[] coord={
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
};
private SparseArray<boolean[]> mBools;
private SparseArray<int[]> mInts;
private SparseArray<float[]> mFloats;
private int mHNormal;
private Map<String,VisibObj> visibobjs = new HashMap<>();
public Context getContext() {
return context;
}
public float[] getCameraMatrix() {
return cameraMatrix;
}
public void setCameraMatrix(float[] cameraMatrix) {
this.cameraMatrix = cameraMatrix;
}
public float[] getProjMatrix() {
return projMatrix;
}
public void setProjMatrix(float[] projMatrix) {
this.projMatrix = projMatrix;
}
private GLGod(Context context){
this.context = context;
this.mRes = context.getResources();
/**
* 将初始化分开进行
*/
// initGod();
}
public void initGod(){
initBuffer();
createProgramByAssetsFile("3dres/obj.vert","3dres/obj.frag");
mHNormal= GLES20.glGetAttribLocation(mProgram,"vNormal");
//打开深度检测
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
}
public synchronized static GLGod getTHEGod(Context mcontext){
if(THEGod==null){
THEGod = new GLGod(mcontext);
}
return THEGod;
}
public final void createProgramByAssetsFile(String vertex,String fragment){
createProgram(ObjUtil.uRes(mRes,vertex),ObjUtil.uRes(mRes,fragment));
}
public final void createProgram(String vertex,String fragment){
mProgram= ObjUtil.uCreateGlProgram(vertex,fragment);
mHPosition= GLES20.glGetAttribLocation(mProgram, "vPosition");
mHCoord=GLES20.glGetAttribLocation(mProgram,"vCoord");
mHMatrixHandler=GLES20.glGetUniformLocation(mProgram,"vMatrix");
mHTexture=GLES20.glGetUniformLocation(mProgram,"vTexture");
}
/**
* Buffer初始化
*/
protected void initBuffer(){
ByteBuffer a=ByteBuffer.allocateDirect(32);
a.order(ByteOrder.nativeOrder());
mVerBuffer=a.asFloatBuffer();
mVerBuffer.put(pos);
mVerBuffer.position(0);
ByteBuffer b=ByteBuffer.allocateDirect(32);
b.order(ByteOrder.nativeOrder());
mTexBuffer=b.asFloatBuffer();
mTexBuffer.put(coord);
mTexBuffer.position(0);
}
private int createTexture(Bitmap bitmap){
int[] texture=new int[1];
if(bitmap!=null&&!bitmap.isRecycled()){
//生成纹理
GLES20.glGenTextures(1,texture,0);
//生成纹理
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,texture[0]);
//设置缩小过滤为使用纹理中坐标最接近的一个像素的颜色作为需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_NEAREST);
//设置放大过滤为使用纹理中坐标最接近的若干个颜色,通过加权平均算法得到需要绘制的像素颜色
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR);
//设置环绕方向S,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_CLAMP_TO_EDGE);
//设置环绕方向T,截取纹理坐标到[1/2n,1-1/2n]。将导致永远不会与border融合
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE);
//根据以上指定的参数,生成一个2D纹理
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
return texture[0];
}
return 0;
}
protected void onUseProgram(){
GLES20.glUseProgram(mProgram);
}
/**
* 设置其他扩展数据
*/
protected void onSetExpandData(VisibObj visibobj){
//GLES20.glUniformMatrix4fv(mHMatrixHandler,1,false,matrix,0);
GLES20.glUniformMatrix4fv(mHMatrixHandler,1,false,
getFinalMatrix(visibobj.getMatrix()),0);
}
/**
* 绑定默认纹理
*/
protected void onBindTexture(VisibObj obj){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0+textureType);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,obj.getTextureId());
GLES20.glUniform1i(mHTexture,textureType);
}
public void drawObj(VisibObj visibobj){
List<Obj3D> obj = visibobj.getBindObjs();
for(Obj3D o:obj) {
onUseProgram();
onSetExpandData(visibobj);
onBindTexture(visibobj);
onDraw(o);
}
}
public float[] getFinalMatrix(float[] matrix){
finalMatrix = new float[16];
Matrix.multiplyMM(finalMatrix, 0, cameraMatrix,0 , matrix, 0);
Matrix.multiplyMM(finalMatrix, 0, projMatrix,0 , finalMatrix, 0);
return finalMatrix;
}
public void onDraw(Obj3D obj){
GLES20.glEnableVertexAttribArray(mHPosition);
GLES20.glVertexAttribPointer(mHPosition,3, GLES20.GL_FLOAT, false, 3*4,obj.vert);
GLES20.glEnableVertexAttribArray(mHNormal);
GLES20.glVertexAttribPointer(mHNormal,3, GLES20.GL_FLOAT, false, 3*4,obj.vertNorl);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,obj.vertCount);
GLES20.glDisableVertexAttribArray(mHPosition);
GLES20.glDisableVertexAttribArray(mHNormal);
}
public void clearView(){
GLES20.glClearColor(0f,0f,0f,0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
}
public void onSizeChanged(int width, int height) {
GLES20.glViewport(0,0,width,height);
Iterator<Map.Entry<String, VisibObj>> iter = getVisibobjs().entrySet().iterator();
while(iter.hasNext()){
float[] matrix = Gl2Utils.getOriginalMatrix();
Matrix.scaleM(matrix, 0, 0.8f, 0.8f * width / height, 0.8f);
iter.next().getValue().setMatrix(matrix);
}
}
public void addVisibObj(String name,VisibObj obj){
visibobjs.put(name, obj);
}
public void setVisibobjs(Map<String, VisibObj> visibobjs) {
this.visibobjs = visibobjs;
}
public Map<String, VisibObj> getVisibobjs() {
return visibobjs;
}
}
|
Python | UTF-8 | 724 | 2.796875 | 3 | [] | no_license | #!/usr/bin/env python2.7
import tika
from tika import parser
if __name__ == "__main__":
tika.initVM()
parsed = parser.from_file('Kevin_DelRosso_Resume.pdf')
metadata = parsed["metadata"]
content = parsed["content"]
print type(metadata), type(content)
print "\nMetadata"
for k, v in metadata.iteritems():
print k, v
content = content.replace(u'\u2212', "-")
content = content.replace(u'\u2022', "*")
content = content.replace(u'\u2019', "'")
print [content]
doc = ''
for c in content:
try:
doc += str(c)
except UnicodeEncodeError:
print [c]
print "unicode error"
print "\nContent"
print doc.strip()
|
Markdown | UTF-8 | 1,355 | 2.515625 | 3 | [
"MIT"
] | permissive | # passport-inventory-sync-worker
Processes inventory records, combining inventory counts with item property data. Writes combined data to separate queues for updating the Plant API and the web store. Once the process is complete an optional SNS message is sent.
## Required Environment Variables
### TASK_QUEUE_URL
This is the url (not the arn) for the SQS queue that calls this function. The URL is required to ensure that the items are deleted from the queue when the tasks are complete.
*Your Lambda fucntion must have read and delete priveleges to this queue.*
### API_BASE_URL
_Example:_ https://api.mydomain.com/v1/
This is the base url for the api from which to retrieve plant data.
### STORE_QUEUE_URL
This is the url (not the arn) for the SQS queue in which data will be placed for processing by the web store.
*Your Lambda function must have write priveleges to this queue.*
### API_QUEUE_URL
This is the url (not the arn) for the SQS queue in which data will be placed for updating the plant api.
*Your Lambda function must have write priveleges to this queue.*
### Optional Environment Variables
### NOTIFY_SNS
Value must be "true" or "false" - If omitted, defaults to false.
### SNS_TOPIC_ARN
A message will be sent to this SNS topic when processing completes.
*If used, your Lambda function must have send priveleges for this topic.* |
Java | UTF-8 | 1,230 | 2.09375 | 2 | [] | no_license | package com.huemedia.cms.model.dao.jpa;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import com.huemedia.cms.model.dao.GroupDAO;
import com.huemedia.cms.model.entity.Group;
import com.huemedia.cms.model.entity.QGroup;
import com.huemedia.cms.web.form.MasterForm;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.expr.BooleanExpression;
@Repository
public class jpaGroupDAO extends JpaMasterDAO<Group> implements GroupDAO{
@Override
EntityPath<?> path() {
// TODO Auto-generated method stub
return QGroup.group;
}
@Override
JPAQuery prepareQuerySearch(Object form) {
QGroup qGroup = (QGroup) path();
JPAQuery query = new JPAQuery(em);
query.from(qGroup);
MasterForm masterForm=(MasterForm) form;
final BooleanBuilder builder = new BooleanBuilder();
if(StringUtils.isNotEmpty(masterForm.getName())){
final BooleanExpression containsName =qGroup.name.like("%"+masterForm.getName()+"%");
builder.and(containsName);
}
query.where(builder).orderBy(qGroup.createDate.desc());
return query;
}
}
|
Markdown | UTF-8 | 1,977 | 2.765625 | 3 | [
"MIT",
"Unlicense"
] | permissive | ---
title: TechEd - Developing Manageable WCF Services
categories: .Net, IT Related
tags: TechEd, WCF
date: 2006-08-24 10:10:46 +10:00
---
![][0]
Chris and I got to the presentation room early in the morning so we could setup and make sure everything was sorted. We then went out to have a relaxed breakfast at a cafe on Darling Harbour before the session started at 8:30.
I really enjoyed the experience of presenting and just had a blast. There were 135 people registered for the session, but it is hard to know exactly how many came through the door, but we had a full room with some people having to stand. Ashman (Ashley), the technical guy for the room, was really helpful and all the gear in the room as well as the VPC server worked perfectly.
I only got hit with the demo gods once. From memory, I think something wasn't being written to the trace/message logs in one of the demos, but that was fairly minor. From a technical point of view, all the other demos went well albeit a little rushed.
<!--more-->
The presentation was well planned and on the whole I think it went well. There were a few presentation style issues that Chris and I had, but that is all stuff that is good for the experience and things that we can learn from.
It was unfortunate that we didn't get many evaluation forms filled out for the session. Of those that did submit their evaluations, the comments were very helpful for feedback. If you went to the session and want to provide any more feedback, please contact me, I would love to hear what you thought of the session (good and bad). I was able to have a really good chat to [Dave][2] (who organised the Connected Systems track) straight after the session and he was really happy with how it went.
[0]: /files/WindowsLiveWriter/TechEdDevelopingManageableWCFServices_CAE0/20060824-081415_2.jpg
[1]: /files/WindowsLiveWriter/TechEdDevelopingManageableWCFServices_CAE0/20060824-081415_thumb.jpg
[2]: http://blogs.msdn.com/davidlem/ |
Python | UTF-8 | 532 | 3.09375 | 3 | [] | no_license | def function1():
f = open("sam.txt","r")
for line in f.readlines():
print("-------")
new_line = line.replace(line,'"'+line.strip("\n")+'",'+"\n")
print(new_line)
open("sam2.txt","a").write(new_line)
# a = "aaaaaaaaaabbbbbbbbbcccccccdaldkadla"
# b = a.replace('a','N')
# print(b)
#
def function2():
f = open("sam2.txt","r")
for line in f.readlines():
print("-------")
new_line = line.replace(line,line.strip("\n").strip('",')+"\n")
print(new_line)
open("sam3.txt","a").write(new_line)
function1()
function2()
|
Markdown | UTF-8 | 12,332 | 2.59375 | 3 | [] | no_license | ---
aid: "0003"
zid: "0046"
title: 雷州糖业公司
author: 吹牛者
---
常师德半躺半靠在床上,喝了一点醒酒汤下去,人虽然晕乎乎的,却十分畅快。正待要睡觉,只见文秀悄没声的走进屋来,只穿着贴身的小褂,发髻解开梳在后面,满面桃花,杏眼含春。常师德一时呆了,不知道他这副模样来作甚。
只见文秀如同女人般的打了万福,小声道:“文秀伺候老爷就寝。”说着便上来给他宽衣解带,一双柔荑小手在他身上轻轻的按揉,千娇百媚轻声的呼唤着:“老爷——”
常师德呆了大约五秒钟,忽然全身的酒都从毛孔里散了出去,一阵凉意从脚跟直冲脑门,全身顿时起了一层鸡皮疙瘩。
“不——”他发出一声悲鸣,赶紧推开文秀,连滚带爬的从床上翻滚下来。妈妈咪呀,这是啥时代啊,佣人性骚扰主人——要是被丫鬟性骚扰也就算了,居然是个男人——文秀再漂亮,也还是个男人。
这场小小的骚动引来了一场混乱,周士翟在第一时间破门而入,见到这一场面,这位镖师也面色大变,赶紧道:“老爷请慢用。”低着头退了出去。
“不,老周,你听我解释——”常师德连鞋也没穿,赶紧追了出去,外面李标正在探头探脑,院子里也聚集起了几个镖师,拿着刀棍。
“看什么看?都回去!”周士翟不耐烦的一挥手,又赶紧对衣冠不整的常师德说,“常首长,你这样有碍观瞻啊——”
“是,是,我知道了。”他赶紧返回去穿上鞋子。
这边文同也出来了,他正在灯下起草改进糖业生产的报告书,听得嘈杂出来一看还没闹明白怎么回事,只见文秀衣衫不整,委委屈屈的从常师德的屋子里出来,他顿时起了误会,沉下了脸:
“老常,平时就知道你花心点,没想到你还有这个癖好!”文同并不歧视 GAY,但是对为了生理快感男女通吃的人可就很鄙视了。
“没有的事!”常师德急得抓耳挠腮,寻死的心都有了。明明是这死人妖企图来骚扰他,怎么大家都觉得是他在对人家的菊花图谋不轨?
“老文啊,你可要相信我们革命同志啊,你总不会不相信我吧,我们在临高可是一个宿舍的!我是什么样的人你知道啊!”
“难说的很,一旦脱离了集体,人的很多丑陋本性都会暴露出来。”
“我冤枉啊——”常师德指天画地,又是赌咒又是解释的,才算让文同勉强相信了是文秀骚扰他。这时候廖大化来了,常师德正郁闷白白背了次黑锅,不由得把廖大化也埋怨了一番。连带着把郭逸也骂了一通——怎么闹了个兔子来伺候他们。
廖大化笑道:“常师爷不必动怒。这是小子们会错了意。他们这种专门服侍大爷的孩子,白天伺候茶水起居晚上充任婢妾侍寝本是常事。昨个文掌柜说了不要买婢女,旅途上用僮仆方便,大约是这上面起了误会。既然师爷没这个意思,我好好的训斥他们一番就是。”
“啥?还有这种事情?”常师德顿时对古人的性观念有了震撼性的颠覆。
“平常的很。酸子秀才们每每背个书剑琴箱的在外游学,身边都带个小僮儿,一是出门在外使唤着方便,二来晚间耐不住了就用来泻火。朝廷里的大官们也有专门蓄养的,有那亲昵的,宠爱还胜过婢妾呢。”
“我靠,这是什么社会!”常师德忍不住骂了一句。
廖大化只在一旁赔笑,知道文秀这孩子媚上邀宠的心太盛,来个了“自荐枕席”,这下算是拍马屁拍到了马脚上。两位看来都不好男风。心中盘算着赶快寻几个丫鬟过来才行。
当夜的一场风波也就过去了。原本常师德还有些疑神疑鬼,深怕自己伟岸的形象被人取笑。后来才发觉土著们对此事根本没有八卦的兴趣,连文秀第二天也照旧若无其事的来给他送洗脸水。大概正如廖大化说得:这种事根本不算一回事。
第二天,两人继续坐轿子,由起威镖局的一干人保护着,用了差不多半个月的时间陆续巡视了名下的各个甘蔗庄和糖寮。初步把情况都了解了一番。期间旅途劳顿,风尘仆仆也不必细说,还遭遇了几次强盗的拦路抢劫,好在有起威的镖师护卫,有惊无险的都过去了。
各个庄子和糖寮的情况大同小异,有的还留下几个长工,有的干脆人去楼空。文同现在已经知道了雷州的糖业生产情况:这里是典型的庄寮结合型的。没有单纯以以加工为业的土塘寮。都是某个甘蔗田较多的蔗农或者地主开办的依附于甘蔗庄,也有蔗农们合股开办的。土糖寮以加工自己地里出产的甘蔗为主。兼顾对外加工。设备的使用率很低,所以无一不是规模小,设备简陋。
甘蔗田种植不是农村常见的租佃制,小块的土地由蔗农自种自收,农忙的时候请几个短工;大块的完全是由地主雇用长工种植管理,已经有了农业雇用劳动的雏形。
所以土地一旦易手,土地上的劳动力就全部都消失了,和一般租佃制下换地主不换佃户完全是两回事。这就对补充劳动力提出了迫切的要求。
这天一行人回到了徐闻的庄子上。正好张信作为广州站的联络员也来到了徐闻。作为雷州白糖的未来主要销售商,广州站对此也是极其重视的。
根据广州站的提议和执委会的批准,文同和常师德正式在徐闻建立了雷州糖业公司。开办糖业公司的资本由广州站调拨。徐闻城外的甘蔗庄将作为公司的总部。文同计划在徐闻进行糖业改进试点。
“能出白糖吗?”张信对这个问题十分在意,再三的询问。
“没问题,能出比广东任何一家都好的白糖。”文同对此极有信心,“不过在价格上要有优势,就得看机械部门有没有办法帮我们造设备了。”
“有英国人最近到广州了。”张信告诉他一个讯息,“他们很小心,正在寻求购买商品,白糖也是一个大宗。如果能赶在四月之前出糖,卖掉二三十吨不成问题。”
“可以,不过我要广州站给我足够的人力。”文同说,“在本地补充劳动力很困难。”
“要多少人?”
“至少得三百人。”文同的计划书里,这一批人将作为甘蔗农场和糖厂的第一批工人。每个庄子至少要补充二十名左右劳力,有糖寮的庄子还得更多一些。
“都要壮劳动力?”
“妇女和孩子也要。这样能够拘绊青壮年。再说广东福建的农家妇女都很能干,体力也好,我看不比男人差。对了,再找十名左右有养牛经验的人。”
“行。给你五百人都可以。”张信一口答应。因为移民工作的不断进行,临高的接收能力已经出现缺口。一个净化周期是 40 天,而临高的检疫营地总共也只能同时入住四百人左右。不少已经招募来的移民就只能被安置在广州,等候发运。广州站为此在郊外设立了一个类似隔离检疫区的村子,在那里进行一些初步的“净化”工作。营地里现在已经滞留了一千多人,为了防止当地官府起疑,郭逸已经在设法尽快把他们送走一些。
“五百人我怕接收不了。”文同说,“先三百人吧。这里千头万绪的事情太多,我还想再从临高要些干部来呢。”
“干部很难。”张信说,“起威的人很可靠,你可以从里面选些骨干出来当军事干部。”看到文同愕然的神情,张信补充道:“雷州这地方很乱,你这么个大糖厂主,到时候自然会有各路好汉眼红,土匪不用说了,本地的土豪起了意恐怕也是件麻烦事。要保护自己的人身和财产安全就得有武装。先拉个民兵队起来吧。武器会从临高给你补充些过来。”
“好吧。”文同想这事情就交给常师德好了——反正他会耍鬼头刀。
“我打算先在徐闻这里搞一个甘蔗组合,然后再拓展到海康、遂溪这些地方。”
“继续收买甘蔗地扩建种植园吗?”
“我是希望搞种植园的,”文同说,“现在这里的经营模式还是以小农经济为主的,种植和管理水平都太落后了。”
在半个月的旅行途中,文同对这里的甘蔗种植情况已经摸了个七七八八。小农经济下的经济作物栽培随意性很大:品种有种果蔗的,有种糖蔗的,至于田间管理,有的看得出很用心,有的则马马虎虎,完全是看天吃饭的。甚至并不适合种甘蔗的地方也有人在种甘蔗……
以甘蔗这样的经济作物来说,最好的经营模式自然是大规模种植园:把这些小片的土地合并起来,成了一个大型的甘蔗种植园。不管是采用雇工制还是奴隶制,生产效率都比现在这样的小农种植高得多。
但是收购蔗农的土地并不容易。蔗农很少有破产或者经营困难的,就算是支付那高得可怕的利息,种植蔗田依然是有利可图。没有天灾人祸的情况下想要成片兼并土地很难做到。除非穿越者操纵糖价,逼迫这些小农全部破产,再逐一收购。文同并不认同这种方案,倒不是他有多少善心,而是觉得穿越集团还没这个本事。
“我的想法是搞甘蔗组合。”文同拿出了他的方案:把生产同一种作物的种植户都组织起来,在他们的主持下统一进行技术指导使用良种,统一购买肥料,甘蔗统一制糖、统一销售。压低成本,增加收益。文同估计,这个方案会吸引不少小种植户参加。
“这个方案,第一年肯定不会有多少结果,但是时间长了,效益一出来,农民就自然愿意参加了。没办法,我们不是政府不能硬性推行,只能靠口口相传的口碑效益才能达到目的。”
“那你得扎根雷州了。”张信看了他庞大的计划,“这计划没三年五载不会出效益的,光说服这一家家的农户,还有收成之后的分红……得好一批人协助你。”
“扎根也可以么。享受下大地主的日子。”文同对自己的这个事业很有兴趣,“这边的管理人员、技术人员,我向教育委员会申请了些,能配几个配几个。不够的我还准备自己搞培训。至于说服小农加入么,能说服多少说服多少。等三五年一过,一切顺利的话我就是雷州最大的糖业供货商了,糖既多又好,到时候来个压价倾销,把市场上的收购价打得稀巴烂,不肯加入农合的全部让他们破产,我再连人带土地都收买下来好了。”
张信连连点头,想不到文同这样一个技术人员,也能使出如此毒辣的手段来。
“需要什么只管开口,广州站一定配合好。”
“我们这里只是个制糖基地,没有情报人员之类的编制,但是我很想知道海安街的具体情况,这地方被当地人叫做‘甜港’,糖都是从此地出口,街上还有不少糖行。这些潮、汕地方的商人,迟早都是我们的对手——”
“这个好说,我们会安排人在当地卧底。到时候真要正常手段搞不下来,来点不正常的就是。特侦队的人正手痒呢。”
“呵呵,最好是不要了。不过我们时间有限,不能起腻打什么商业战,快刀乱麻比较好。”
双方商定了一系列的联系方法,因为雷州不算正式的派遣站,只是个二级据点,目前没有电台配发,与临高的联系主要使用信鸽作为工具。与广州之间的联系除了使用信鸽,还可以利用起威镖局的镖路传递信件。根据执委会的指示,不到万不得已,不要轻易直接派人渡海回临高来联系——双方的直接联系要越少越好。
执委会在雷州还有盐商刘纲这条线,此人就住在海康县境内,但是执委会经过考虑还是决定双方各自单线联系,避免接触。刘纲是他们向大陆走私私盐的重要渠道,要重点保护。
|
Python | UTF-8 | 822 | 2.703125 | 3 | [] | no_license | class Benchmark:
kernels = []
def __init__(self, name, label, max_thread_count):
self.name = name
self.label = label
self.max_thread_count = max_thread_count
def __repr__(self):
return self.name + ": " + self.label + " w/ " + self.max_thread_count + " threads"
class Kernel:
def __init__(self, name, stream, priority, benchmark):
self.blocks = []
self.name = name
self.stream = stream
self.priority = priority
self.benchmark = benchmark
def __repr__(self):
return self.name + "/pri-" + str(self.priority) + "/stream-" + str(self.stream)
class Block:
def __init__(self, smid, thread_count, kernel):
self.smid = smid
self.thread_count = thread_count
self.kernel = kernel
def __repr__(self):
return "SM" + str(self.smid) + "/" + str(self.thread_count)
|
JavaScript | UTF-8 | 8,990 | 3.171875 | 3 | [] | no_license | var assert = require("assert");
var parser = require("..");
describe("parser", () => {
it("parses booleans", () => {
assert.strictEqual(
parser.parseString("true", true),
true);
assert.strictEqual(
parser.parseString("false", true),
false);
});
it("parses null", () => {
assert.strictEqual(
parser.parseString("null", true),
null);
});
it("parses numbers", () => {
assert.strictEqual(
parser.parseString("105", true),
105);
assert.strictEqual(
parser.parseString("103.995", true),
103.995);
assert.strictEqual(
parser.parseString("-10", true),
-10);
});
it("parses positive exponential notation", () => {
assert.strictEqual(
parser.parseString("105.99e5", true),
105.99e5);
assert.strictEqual(
parser.parseString("105.99e+5", true),
105.99e5);
assert.strictEqual(
parser.parseString("105.99E5", true),
105.99e5);
assert.strictEqual(
parser.parseString("105.99E+5", true),
105.99e5);
});
it("parses negative exponential notation", () => {
assert.strictEqual(
parser.parseString("105.99e-5", true),
105.99e-5);
assert.strictEqual(
parser.parseString("105.99E-5", true),
105.99E-5);
});
it("only accepts one period in numbers", () => {
assert.deepEqual(
parser.parseString("[ 10.44.55 ]", true),
[ "10.44.55" ]); // string, not number
});
it("parses strings", () => {
assert.strictEqual(
parser.parseString("\"Hello World\"", true),
"Hello World");
});
it("parses strings without quotes", () => {
assert.strictEqual(
parser.parseString("hello-world", true),
"hello-world");
});
it("parses arrays", () => {
assert.deepEqual(
parser.parseString("[10 50 449 true]", true),
[10, 50, 449, true]);
});
it("parses nested arrays", () => {
assert.deepEqual(
parser.parseString("[10 [ [ 3 7 ] 55 6]]", true),
[10, [ [3, 7 ], 55, 6]]);
});
it("parses objects", () => {
assert.deepEqual(
parser.parseString("{ foo 10 bar 555 }", true),
{ foo: 10, bar: 555 });
});
it("parses nested objects", () => {
assert.deepEqual(
parser.parseString("{ foo 10 bar { no 4 hey 33 } }", true),
{ foo: 10, bar: { no: 4, hey: 33 } });
});
it("parses arrays in objects", () => {
assert.deepEqual(
parser.parseString("{ foo 10 bar [ no 4 hey 33 ] }", true),
{ foo: 10, bar: [ "no", 4, "hey", 33 ] });
});
it("parses objects in arrays", () => {
assert.deepEqual(
parser.parseString("[ foo 10 bar { no 4 hey 33 } ]", true),
[ "foo", 10, "bar", { no: 4, hey: 33 } ]);
});
it("does not parse inline comments", () => {
assert.deepEqual(
parser.parseString("null # a comment'\"]}[{", true),
null);
assert.deepEqual(
parser.parseString("after-strings # a comment'\"]}[{", true),
"after-strings");
assert.deepEqual(
parser.parseString("[after arrays] # a comment'\"]}[{", true),
[ "after", "arrays" ]);
assert.deepEqual(
parser.parseString("{after objects} # a comment'\"]}[{", true),
{ after: "objects" });
});
it("does not parse whole line comments", () => {
assert.deepEqual(
parser.parseString("# a comment'\"]}[{\nnull", true),
null);
assert.deepEqual(
parser.parseString("# a comment'\"]}[{\nbefore-strings", true),
"before-strings");
assert.deepEqual(
parser.parseString("# a comment'\"]}[{\n[before arrays]", true),
[ "before", "arrays" ]);
assert.deepEqual(
parser.parseString("# a comment'\"]}[{\n{before objects}", true),
{ before: "objects" });
});
});
describe("interface", () => {
describe("parseFile", () => {
it("parses the example file correctly", () => {
assert.deepEqual(
parser.parseFile("test/parse-file.hcnf"),
{ foo: { bar: 55, baz: "Hello World" }, bar: 10 });
});
it("parses the example file with a root correctly", () => {
assert.deepEqual(
parser.parseFile("test/parse-file-root.hcnf", true),
[ 10, 5, "no" ]);
});
});
describe("parseConfFile", () => {
it("parses the example file correctly", () => {
assert.deepEqual(
parser.parseConfFile("test/parse-conf-file.hcnf"),
{
foo: [
{ name: "bar", baz: 10 },
{ name: "no", baz: 99 },
],
bar: [
{ name: null, a: "b" }
]
});
});
});
describe("parseConfString", () => {
it("parses the example string correctly", () => {
assert.deepEqual(
parser.parseConfString(
"foo bar { baz 10 } foo no { baz 20 }"),
{
foo: [
{ name: "bar", baz: 10 },
{ name: "no", baz: 20 },
]
});
});
});
describe("parseConf", () => {
it("throws an error if an unspecified section is given", () => {
try {
parser.parseConfString(
"general { port 8080 } general { port 8081 }",
{ general: "once" });
} catch (err) {
if (err.hconfigParseError)
return;
else
throw err;
}
throw new Error("Expected an error to be thrown");
});
it("returns sections which only exist once as an object", () => {
assert.deepEqual(
parser.parseConfString(
"general { port 8080 }",
{ general: "once" }),
{ general: { name: null, port: 8080 } });
});
it("returns sections which exist multiple times as an array", () => {
assert.deepEqual(
parser.parseConfString(
"foo { bar baz } foo { baz bar }",
{ foo: "many" }),
{
foo: [
{ name: null, bar: "baz" },
{ name: null, baz: "bar" },
]
});
});
});
});
describe("example files", () => {
it("example 1", () => {
assert.deepEqual(
parser.parseConfFile(
"test/example-1.hcnf",
{ general: "once", "virtual-host": "many" }),
{
general: {
name: null,
port: 8080,
host: "localhost",
index: [ ".html", ".htm" ],
},
"virtual-host": [
{ name: "cats.example.com", webroot: "/var/www/mycats" },
{ name: "resume.example.com", webroot: "/var/www/resume" },
],
});
});
it("example 2", () => {
assert.deepEqual(
parser.parseConfFile("test/example-2.hcnf"),
{
"virtual-host": [
{ name: "http://cats.example.com", webroot: "/var/www/mycats" },
{ name: "http://resume.example.com", webroot: "/var/www/resume" },
{
name: "https://webmail.example.com",
"ssl-cert": "/etc/ssl/example.com.pem",
"ssl-key": "/etc/ssl/example.com.key",
webroot: "/var/www/webmail",
},
]
});
});
});
describe("validation", () => {
it("disallows empty section names if desired", () => {
try {
parser.parseConfString("foo {}",
{ foo: { count: "once", props: { name: "string" } } });
} catch (err) {
if (err.hconfigParseError)
return;
else
throw err;
}
throw new Error("Expected error to be thrown");
});
it("defaults to * if specified", () => {
assert.deepEqual(
parser.parseConfString(
"foo { a 10 b hello c true }",
{ foo: { count: "once", props: { "*": "any" } } }),
{ foo: { name: null, a: 10, b: "hello", c: true } });
});
});
describe("strings", () => {
it("doesn't expand anything in single-quote strings", () => {
assert.strictEqual(
parser.parseString("'$(FOO) \\t'", true),
"$(FOO) \\t");
});
it("expands environment variables", () => {
assert.strictEqual(
parser.parseString('"$(USER)"', true),
process.env.USER);
});
it("expands escape sequences", () => {
assert.strictEqual(
parser.parseString('"\\\\\\\\ \\" \\f \\n \\r \\t \\u4444"', true),
"\\\\ \" \f \n \r \t \u4444");
});
});
describe("unquoted strings", () => {
it("doesn't expand anything in unquoted strings", () => {
assert.strictEqual(
parser.parseString("$(FOO)'\"\\n\\t", true),
"$(FOO)'\"\\n\\t");
});
it("# ends an unquoted string", () => {
assert.strictEqual(
parser.parseString("$(FOO)'\"#\\n\\tabc", true),
"$(FOO)'\"");
});
it("{ starts an object", () => {
assert.deepEqual(
parser.parseString("key{ key value }", false),
{ key: { key: "value" } });
});
it("key starts immediately after {", () => {
assert.deepEqual(
parser.parseString("key {key value }", false),
{ key: { key: "value" } });
});
it("} ends an object", () => {
assert.deepEqual(
parser.parseString("key { key value}", false),
{ key: { key: "value" } });
});
it("key ends immediately after }", () => {
assert.deepEqual(
parser.parseString("key { key value }key2 value2", false),
{ key: { key: "value" }, key2: "value2" });
});
it("[ starts an array", () => {
assert.deepEqual(
parser.parseString("key[ key value ]", false),
{ key: [ "key", "value" ] });
});
it("key starts immediately after [", () => {
assert.deepEqual(
parser.parseString("key [key value ]", false),
{ key: [ "key", "value" ] });
});
it("] ends an array", () => {
assert.deepEqual(
parser.parseString("key [ key value]", false),
{ key: [ "key", "value" ] });
});
it("key ends immediately after ]", () => {
assert.deepEqual(
parser.parseString("key [ key value ]key2 value2", false),
{ key: [ "key", "value" ], key2: "value2" });
});
});
|
C | UTF-8 | 936 | 3.484375 | 3 | [] | no_license | #include "linked_list.h"
#include <stdlib.h>
//Delete, insert, search, predecessor functions for linked list data structure.
void delete_list(list **l, player_struct *x) {
list *p, *pred;
list *search_list(), *predecessor_list();
p = search_list(*l, x);
if (p != NULL) {
pred = predecessor_list(*l, x);
if (pred == NULL)
*l = p->next;
else
pred->next = p->next;
free_player(p->player);
free(p);
}
}
void insert_list(list **l, player_struct *x) {
list *p;
p = malloc(sizeof(list));
p->player = x;
p->next = *l;
*l = p;
}
list *predecessor_list(list *l, player_struct *x) {
if ((l == NULL) || (l->next == NULL))
return NULL;
if ((l->next)->player == x)
return l;
else
return predecessor_list(l->next, x);
}
list *search_list(list *l, player_struct *x) {
if (l == NULL)
return NULL;
if (l->player == x)
return l;
return search_list(l->next, x);
}
|
PHP | UTF-8 | 2,817 | 2.65625 | 3 | [] | no_license | <?php
/**
* Copyright 2001-2015 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (GPL). If you
* did not receive this file, see http://www.horde.org/licenses/gpl.
*
* @category Horde
* @copyright 2001-2015 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
/**
* Handler to render plain text from enriched content tags (RFC 1896).
*
* @author Eric Rostetter <eric.rostetter@physics.utexas.edu>
* @category Horde
* @copyright 2001-2015 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
class IMP_Mime_Viewer_Enriched extends Horde_Mime_Viewer_Enriched
{
/**
* Return the full rendered version of the Horde_Mime_Part object.
*
* @return array See parent::render().
*/
protected function _render()
{
$ret = parent::_render();
if (!empty($ret)) {
reset($ret);
$ret[key($ret)]['data'] = $this->_IMPformat($ret[key($ret)]['data']);
}
return $ret;
}
/**
* Return the rendered inline version of the Horde_Mime_Part object.
*
* @return array See parent::render().
*/
protected function _renderInline()
{
$ret = parent::_renderInline();
if (!empty($ret)) {
reset($ret);
$ret[key($ret)]['data'] = $this->_IMPformat($ret[key($ret)]['data']);
}
return $ret;
}
/**
* Format output text with IMP additions.
*
* @param string $text The HTML text.
*
* @return string The text with extra IMP formatting applied.
*/
protected function _IMPformat($text)
{
// Highlight quoted parts of an email.
if ($GLOBALS['prefs']->getValue('highlight_text')) {
$text = implode("\n", preg_replace('|^(\s*>.+)$|', '<span class="quoted1">\1</span>', explode("\n", $text)));
$indent = 1;
while (preg_match('|>(\s?>){' . $indent . '}|', $text)) {
$text = implode("\n", preg_replace('|^<span class="quoted' . ((($indent - 1) % 5) + 1) . '">(\s*>(\s?>){' . $indent . '}.+)$|', '<span class="quoted' . (($indent % 5) + 1) . '">\1', explode("\n", $text)));
++$indent;
}
}
// Dim signatures.
if ($GLOBALS['prefs']->getValue('dim_signature')) {
$parts = preg_split('|(\n--\s*\n)|', $text, 2, PREG_SPLIT_DELIM_CAPTURE);
$text = array_shift($parts);
if (count($parts)) {
$text .= '<span class="signature">' . $parts[0] .
preg_replace('|class="[^"]+"|', 'class="signature-fixed"', $parts[1]) .
'</span>';
}
}
// Filter bad language.
return IMP::filterText($text);
}
}
|
Java | UTF-8 | 2,660 | 3.3125 | 3 | [
"MIT"
] | permissive | package ec.edu.ups.mysql.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Class ContextJDBC.
*
* Clase que permite obtener una conexión a la base de datos y asegura que si ya
* existe una conexión no la vuelva a crear utilizando el patrón de diseño
* Singleton. Además, implementa los métodos para poder enviar sentencias SQL como
* INSERT, DELETE, UPDATE y SELECT.
*
* @author Gabriel A. León Paredes
* Doctor en Tecnologías de Información
* https://www.linkedin.com/in/gabrielleonp
*
* @see https://www.arquitecturajava.com/ejemplo-de-java-singleton-patrones-classloaders/
* @version 1.0
*
*/
public class ContextJDBC {
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/jee";
private static final String USER = "root";
private static final String PASS = "gleon.123@";
private static ContextJDBC jdbc = null;
private Statement statement = null;
public ContextJDBC() {
this.connect();
}
/**
* Método connect.
*
* Realiza una conexión a la base de datos a través de jdbc
*/
public void connect() {
try {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL, USER, PASS);
this.statement = connection.createStatement();
} catch (ClassNotFoundException e) {
System.out.println(">>>WARNING (JDBC:connect)...problemas con el driver\n" + e.getMessage());
} catch (SQLException e) {
System.out.println(">>>WARNING (JDBC:connect)...problemas con la BD\n" + e.getMessage());
}
}
/**
* Método query.
*
* Realiza una sentencia SELECT a la base de datos.
*/
public ResultSet query(String sql) {
try {
return this.statement.executeQuery(sql);
} catch (SQLException e) {
System.out.println(">>>WARNING (JDBC:query): ---" + sql + "---" + e);
}
return null;
}
/**
* Método update.
*
* Realiza una sentencia INSERT, UDPDATE, DELETE, CREATE, entre otras a la base
* de datos.
*/
public boolean update(String sql) {
try {
this.statement.executeUpdate(sql);
return true;
} catch (SQLException e) {
System.out.println(">>>WARNING (JDBC:update)... actualizacion: ---" + sql + "---" + e);
return false;
}
}
/**
* Método getJDBC.
*
* Obtiene una conexión activa a la base de datos
*
* @return jdbc
*/
protected static ContextJDBC getJDBC1() {
// creación de la conexión a la base de datos solo si no ha sido creada patrón
// de diseño singleton
if (jdbc == null) {
jdbc = new ContextJDBC();
}
return jdbc;
}
}
|
JavaScript | UTF-8 | 368 | 3.28125 | 3 | [] | no_license | let count = 11;
const slideFunction = () => {
const sliderDiv = document.getElementById('slider');
sliderDiv.innerHTML = `
<img style="width: 500px" src="images/(${count}).jpg" alt="">`
}
const intervalID = setInterval(() => {
slideFunction(count);
count++;
if (count === 21) {
count = 11;
}
console.log(count);
}, 1000);
|
Markdown | UTF-8 | 3,535 | 2.78125 | 3 | [
"Unlicense"
] | permissive |
# Easing burden on telcos: Government panel mulls repayment of AGR dues over 20 years
Published at: **2019-11-04T04:50:40+00:00**
Author: **Deepshikha Sikarwar**
Original: [The Times of India](https://timesofindia.indiatimes.com/business/india-business/easing-burden-on-telecom-companies-government-panel-mulls-repayment-of-agr-dues-over-20-years/articleshow/71885921.cms)
NEW DELHI: The government panel considering relief for the telecom sector is looking at a repayment period of as much as 20 years for adjusted gross revenue (AGR) dues — with possibly an initial moratorium — based on the net present value (NPV) method to ease the burden on heavily indebted companies.
It will also consider a reduction in the total incidence of taxation to help the troubled sector and separately reach out to the regulator to consider some floor on tariffs to help with viability.
The government may not even need to waive interest and penalty on AGR dues adding up to Rs 1.3 lakh crore in case of a long payback period, although that is also being discussed.
“All options are on the table,” said a government official aware of the deliberations. “The government is keen to ensure that the telecom sector remains competitive.”
The panel, which met for the first time last week, discussed various options, including providing relief from taxes.
Another official who attended the meeting said there was a realisation that something will need to be done if the government wants a competitive telecom sector. The panel is headed by cabinet secretary Rajiv Gauba and has officials from key stakeholder ministries and departments.
AGR blow
A Supreme Court decision on October 26 backing the telecom department’s stance on including revenues from non-core items in the definition of AGR while calculating government levies, has created a crisis for the debt-ridden telecom sector. The decision means a Rs 1.3 lakh crore burden on telecom companies.
NPV Method
Bharti Airtel and Vodafone Idea will together need to pay about Rs 80,000 crore. Apart from hurting consumers, government revenues will also depend on companies remaining viable, said the official. The money has to be paid in three months. Under the NPV method, payments stretching into the future are discounted at an agreed rate — the required rate of return the government wants on the outstanding — so that the sum total of all such discounted flows is equal to the total AGR liability of the telecom companies. While government will get its dues without any loss, though over many years, the telcos will get a respite from immediate payments.
Some members of the committee were of the view that tax on the spectrum charges needed to be eased. The telcos have acquired spectrum at high cost and, in addition, face a topup of up to 30% in taxes. A reduction in goods and services tax would need the GST Council’s backing, said another official. States may have reservations on the proposal, considering lower GST collections. Besides, the tax relief will not be specific to the telcos cited above and will cover all telecom companies. “A more holistic view needs to be taken on what should be the total incidence on the sector,” said the first official cited.
The committee is also considering the need for a tariff floor to make the sector viable. It will reach out to the telecom regulator to look into the issue. There are countries that have tariff floors, said the first official, making a case for some intervention to keep the sector competitive.
|
C++ | UTF-8 | 2,195 | 3.203125 | 3 | [
"Artistic-2.0"
] | permissive | ///A tutorial about the use of Pizza & Chili index.
#include <iostream>
#include <seqan/index.h>
using namespace seqan;
template <typename TSpec>
void testPizzaChili() {
///The following code creates a Pizza & Chili index and assigns it a text.
typedef Index<String<char>, PizzaChili<TSpec> > index_t;
index_t index_pc;
indexText(index_pc) = "This is the best test with a bast jest.";
///Of course, we can access the text as usual:
::std::cout << indexText(index_pc) << ::std::endl;
///Now we may create a default finder and search for a substring. The index
///is only now created because its evaluation is lazy. Immediately after
///the index has been created, the $indexText$ is discarded to save memory.
///Notice that the results returned by the finder might not be in the order
///of their occurrence in the text.
Finder<index_t> finder(index_pc);
while (find(finder, "est"))
::std::cout << "Hit at position " << position(finder) << ::std::endl;
///We may query the text of the index. Notice that this returns a string
///without any real content. The string is lazily evaluated in order to
///save memory. Only the substring we are actually displaying will be
///loaded into memory.
/// $indexText(..)$ is a shortcut for $getFibre(.., PizzaChili_Text())$.
typename Fibre<index_t, PizzaChili_Text>::Type text = indexText(index_pc);
::std::cout << "infix(text, 12, 21): " << infix(text, 12, 21) << ::std::endl;
///We can save the index structure on disk and load it again.
///Notice, however, that not all Pizza & Chili libraries support saving
///and loading at the moment. Please refer to the documentation of the
///different @Tag.Pizza & Chili Index Tags@ for details.
save(index_pc, "pizzachili");
index_t index2;
open(index2, "pizzachili");
::std::cout << indexText(index2) << ::std::endl;
}
int main() {
::std::cout << "Test the alphabet-friendly FM index:" << ::std::endl;
testPizzaChili<PizzaChili_AF>();
::std::cout << ::std::endl << "Test the compressed compact suffix array index:" << ::std::endl;
testPizzaChili<PizzaChili_CCSA>();
return 0;
}
|
C++ | UTF-8 | 541 | 2.8125 | 3 | [
"MIT"
] | permissive | /**
* @file simpleclient.cpp
* @date 03.01.2013
* @author Peter Spiess-Knafl <dev@spiessknafl.at>
* @brief This is a simple client example.
*/
#include <iostream>
#include <jsonrpccpp/client.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
using namespace jsonrpc;
using namespace std;
int main() {
HttpClient client("http://localhost:8383");
Client c(client);
Json::Value params;
params["name"] = "Peter";
try {
cout << c.CallMethod("sayHello", params) << endl;
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
}
|
Java | UTF-8 | 1,034 | 3.15625 | 3 | [] | no_license | package com.arun.companies;
public class Kraken {
public static void main(String[] args) {
assert krakenCount(2,2) == 3;
assert krakenCount(3, 2) == 5;
}
public static int krakenCount(int m, int n) {
if (m == 0 && n == 0) {
return 0;
}
int[][] memo = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
memo[i][j] = 1;
continue;
}
int down = 0;
int right = 0;
int diag = 0;
if (j > 0) {
down = memo[i][j - 1];
}
if (i > 0) {
right = memo[i - 1][j];
}
if (j > 0 && i > 0) {
diag = memo[i - 1][j - 1];
}
memo[i][j] = down + right + diag;
}
}
return memo[m-1][n-1];
}
}
|
Java | UTF-8 | 540 | 2.125 | 2 | [] | no_license | package com.pushok.skilap.apiData;
public class CmdtyData {
public String id;
public String space;
public Double rate;
public CmdtyData() {}
public CmdtyData(String id, String space) {
this.id = id;
this.space = space;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSpace() {
return space;
}
public void setSpace(String space) {
this.space = space;
}
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
|
C# | UTF-8 | 2,557 | 2.671875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeMovement : MonoBehaviour
{
private Vector3 offset;
public GameObject player;
public GameObject center;
public GameObject up;
public GameObject Down;
public GameObject Left;
public GameObject Right;
public int step = 9;
public float speed = (float)0.01;
bool input = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (input == true)
{
if (Input.GetKey(KeyCode.UpArrow))
{
StartCoroutine(moveUp());
input = false;
}
if (Input.GetKey(KeyCode.DownArrow))
{
StartCoroutine(moveDown());
input = false;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
StartCoroutine(moveLeft());
input = false;
}
if (Input.GetKey(KeyCode.RightArrow))
{
StartCoroutine(moveRight());
input = false;
}
}
}
IEnumerator moveUp()
{
for (int i = 0; i < (90 / step); i++)
{
player.transform.RotateAround(up.transform.position, Vector3.right, step);
yield return new WaitForSeconds(speed);
}
center.transform.position = player.transform.position;
input = true;
}
IEnumerator moveDown()
{
for (int i = 0; i < (90 / step); i++)
{
player.transform.RotateAround(Down.transform.position, Vector3.left, step);
yield return new WaitForSeconds(speed);
}
center.transform.position = player.transform.position;
input = true;
}
IEnumerator moveLeft()
{
for (int i = 0; i < (90 / step); i++)
{
player.transform.RotateAround(Left.transform.position, Vector3.forward, step);
yield return new WaitForSeconds(speed);
}
center.transform.position = player.transform.position;
input = true;
}
IEnumerator moveRight()
{
for (int i = 0; i < (90 / step); i++)
{
player.transform.RotateAround(Right.transform.position, Vector3.back, step);
yield return new WaitForSeconds(speed);
}
center.transform.position = player.transform.position;
input = true;
}
}
|
Markdown | UTF-8 | 9,065 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | ---
title: mv-expand operator
description: Learn how to use the mv-expand operator to expand multi-value dynamic arrays or property bags into multiple records.
ms.reviewer: alexans
ms.topic: reference
ms.date: 03/15/2023
---
# mv-expand operator
Expands multi-value dynamic arrays or property bags into multiple records.
`mv-expand` can be described as the opposite of the aggregation operators
that pack multiple values into a single [dynamic](./scalar-data-types/dynamic.md)-typed
array or property bag, such as `summarize` ... `make-list()` and `make-series`.
Each element in the (scalar) array or property bag generates a new record in the
output of the operator. All columns of the input that aren't expanded are duplicated to all the records in the output.
## Syntax
*T* `|mv-expand` [`bagexpansion=`(`bag` | `array`)] [`with_itemindex=` *IndexColumnName*] *ColumnName* [`to typeof(` *Typename*`)`] [`,` *ColumnName* ...] [`limit` *Rowlimit*]
*T* `|mv-expand` [`bagexpansion=`(`bag` | `array`)] [*Name* `=`] *ArrayExpression* [`to typeof(`*Typename*`)`] [`,` [*Name* `=`] *ArrayExpression* [`to typeof(`*Typename*`)`] ...] [`limit` *Rowlimit*]
## Parameters
|Name|Type|Required|Description|
|--|--|--|--|
|*ColumnName*, *ArrayExpression*|string|✓|A column reference, or a scalar expression with a value of type `dynamic` that holds an array or a property bag. The individual top-level elements of the array or property bag get expanded into multiple records.<br>When *ArrayExpression* is used and *Name* doesn't equal any input column name, the expanded value is extended into a new column in the output. Otherwise, the existing *ColumnName* is replaced.|
|*Name*|string| |A name for the new column.|
|*Typename*|string|✓|Indicates the underlying type of the array's elements, which becomes the type of the column produced by the `mv-expand` operator. The operation of applying type is cast-only and doesn't include parsing or type-conversion. Array elements that don't conform with the declared type become `null` values.|
|*RowLimit*|int||The maximum number of rows generated from each original row. The default is 2147483647. `mvexpand` is a legacy and obsolete form of the operator `mv-expand`. The legacy version has a default row limit of 128.|
|*IndexColumnName*|string||If `with_itemindex` is specified, the output includes another column named *IndexColumnName* that contains the index starting at 0 of the item in the original expanded collection.|
## Returns
For each record in the input, the operator returns zero, one, or many records in the output,
as determined in the following way:
1. Input columns that aren't expanded appear in the output with their original value.
If a single input record is expanded into multiple output records, the value is duplicated
to all records.
1. For each *ColumnName* or *ArrayExpression* that is expanded, the number of output records
is determined for each value as explained in [modes of expansion](#modes-of-expansion). For each input record, the maximum number of output records is calculated. All arrays or property bags are expanded "in parallel"
so that missing values (if any) are replaced by null values. Elements are expanded into rows in the order that they appear in the original array/bag.
1. If the dynamic value is null, then a single record is produced for that value (null).
If the dynamic value is an empty array or property bag, no record is produced for that value.
Otherwise, as many records are produced as there are elements in the dynamic value.
The expanded columns are of type `dynamic`, unless they're explicitly typed
by using the `to typeof()` clause.
### Modes of expansion
Two modes of property bag expansions are supported:
* `bagexpansion=bag` or `kind=bag`: Property bags are expanded into single-entry property bags. This mode is the default mode.
* `bagexpansion=array` or `kind=array`: Property bags are expanded into two-element `[`*key*`,`*value*`]` array structures, allowing uniform access to keys and values. This mode also allows, for example, running a distinct-count aggregation over property names.
## Examples
### Single column - array expansion
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA0tJLAHCpJxUBY1EK4XMvBIdhSQrhZTKvMTczGRNXq5oXi4FIDDUgYlpRBsa6CgYGcRq6kCkjJCk1BPVdRTUk9RjgTpjeblqFHLLdFMrChLzUhSSANALFPlqAAAA" target="_blank">Run the query</a>
```kusto
datatable (a: int, b: dynamic)
[
1, dynamic([10, 20]),
2, dynamic(['a', 'b'])
]
| mv-expand b
```
**Output**
|a|b|
|---|---|
|1|10|
|1|20|
|2|a|
|2|b|
### Single column - bag expansion
A simple expansion of a single column:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA0tJLAHCpJxUBY1EK4XMvBIdhSQrhZTKvMTczGRNXq5oXi4FIDDUgYlpVCsVFOUXGCpZKSglGirpKIC5RiBukqFSraYORIMRdg1GqBqMgBp4uWJ5uWoUcst0UysKEvNSFJIAxNVM3ZQAAAA=" target="_blank">Run the query</a>
```kusto
datatable (a: int, b: dynamic)
[
1, dynamic({"prop1": "a1", "prop2": "b1"}),
2, dynamic({"prop1": "a2", "prop2": "b2"})
]
| mv-expand b
```
**Output**
|a|b|
|---|---|
|1|{"prop1": "a1"}|
|1|{"prop2": "b1"}|
|2|{"prop1": "a2"}|
|2|{"prop2": "b2"}|
### Single column - bag expansion to key-value pairs
A simple bag expansion to key-value pairs:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA22LwQqDMBBE74H8w5CTQgpNjoJfEjzsNqFINUoqYmj7742WHgqduczM7vO0FPMQUFGDPi4a3MDnSGN/qaVwUqDI6O9WPdScptmoBoqM0jiq3Ssb9ar1B7D/AfsL2AJI0UnxxLiewjZT9GC6HuneT7GllCiDsb+EbQnlfgsZLdidO42Vhpad6d7eMsidxwAAAA==" target="_blank">Run the query</a>
```kusto
datatable (a: int, b: dynamic)
[
1, dynamic({"prop1": "a1", "prop2": "b1"}),
2, dynamic({"prop1": "a2", "prop2": "b2"})
]
| mv-expand bagexpansion=array b
| extend key = b[0], val=b[1]
```
**Output**
|a|b|key|val|
|---|---|---|---|
|1|["prop1","a1"]|prop1|a1|
|1|["prop2","b1"]|prop2|b1|
|2|["prop1","a2"]|prop1|a2|
|2|["prop2","b2"]|prop2|b2|
### Zipped two columns
Expanding two columns will first 'zip' the applicable columns and then expand them:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA0tJLAHCpJxUBY1EK4XMvBIdhSQrhZTKvMTczGQdhWQ4WzOal0sBCAx1YCIa1UoFRfkFhkpWCkqJSjoKYJ4RiJekVKuJUBZtqqNgoqNgHKvJyxXLy1WjkFumm1pRkJiXopAEtAEANvW+roIAAAA=" target="_blank">Run the query</a>
```kusto
datatable (a: int, b: dynamic, c: dynamic)[
1, dynamic({"prop1": "a", "prop2": "b"}), dynamic([5, 4, 3])
]
| mv-expand b, c
```
**Output**
|a|b|c|
|---|---|---|
|1|{"prop1":"a"}|5|
|1|{"prop2":"b"}|4|
|1||3|
### Cartesian product of two columns
If you want to get a Cartesian product of expanding two columns, expand one after the other:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA0tJLAHCpJxUBY1EK4XMvBIdhSQrhZTKvMTczGQdhWQ4W5OXK5qXSwEIDHVgYhrVSgVF+QWGSlYKSolKOgpgnhGIl6RUq4lQFm2qo2AWCzQhlperRiG3TDe1oiAxL0UhCZWbDACXJubPjQAAAA==" target="_blank">Run the query</a>
```kusto
datatable (a: int, b: dynamic, c: dynamic)
[
1, dynamic({"prop1": "a", "prop2": "b"}), dynamic([5, 6])
]
| mv-expand b
| mv-expand c
```
**Output**
|a|b|c|
|---|---|---|
|1|{ "prop1": "a"}|5|
|1|{ "prop1": "a"}|6|
|1|{ "prop2": "b"}|5|
|1|{ "prop2": "b"}|6|
### Convert output
To force the output of an mv-expand to a certain type (default is dynamic), use `to typeof`:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA02MuwoCMRRE+4X8w7BVAtfCBz629TOWFHm5BkyymIu44McbC8WZZjgzjDfcbG8B0gyofI95ItgBfskmRUdwv6xG0aGpP5dc2WTu6VvJcU3YELaEnVZ/eE84EI6Ek1ai06J7IT1W4Tmb7GHbO7iAlzmUi4yZ1WcwBa7uGpJ5A3+651CdAAAA" target="_blank">Run the query</a>
```kusto
datatable (a: string, b: dynamic, c: dynamic)[
"Constant", dynamic([1, 2, 3, 4]), dynamic([6, 7, 8, 9])
]
| mv-expand b, c to typeof(int)
| getschema
```
**Output**
| ColumnName | ColumnOrdinal | DateType | ColumnType |
|---|---|---|---|
| a | 0 | System.String | string |
| b | 1 | System.Object | dynamic |
| c | 2 | System.Int32 | int |
Notice column `b` is returned as `dynamic` while `c` is returned as `int`.
### Using with_itemindex
Expansion of an array with `with_itemindex`:
> [!div class="nextstepaction"]
> <a href="https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAAytKzEtPVahQSCvKz1UwVCjJVzBRKC5JLVAw5OWqUSguzc1NLMqsAqmwVchNzE6Nz8ksLtGo0ATJ5pbpplYUJOalKJRnlmTEZ5ak5mbmpaRW2HqCSIUKAIrdlHpcAAAA" target="_blank">Run the query</a>
```kusto
range x from 1 to 4 step 1
| summarize x = make_list(x)
| mv-expand with_itemindex=Index x
```
**Output**
|x|Index|
|---|---|
|1|0|
|2|1|
|3|2|
|4|3|
## See also
* For more examples, see [Chart count of live activities over time](./samples.md#chart-concurrent-sessions-over-time).
* [mv-apply](./mv-applyoperator.md) operator.
* For the opposite of the mv-expand operator, see [summarize make_list()](makelist-aggfunction.md).
* For expanding dynamic JSON objects into columns using property bag keys, see [bag_unpack()](bag-unpackplugin.md) plugin.
|
Java | UTF-8 | 8,148 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | package ro.jademy.hm.ai;
import java.util.ArrayList;
import java.util.Scanner;
import ro.jademy.hm.main.App;
import ro.jademy.hm.repository.DataBase;
import ro.jademy.hm.ui.UserInterface;
public class RoboHangman {
Scanner keyboard = new Scanner(System.in);
UserInterface userInit = new UserInterface(keyboard);
App myApp = new App();
DataBase db = new DataBase();
String guessTheWord;
String selectedWord;
String name;
int noMistakes = 0;
// init game(ask the user for a name)
public void initGame() {
this.name = userInit.insertName();
}
// Home menu of the app
public void showMenu() {
do {
System.err.println("\n Welcome " + name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("------------------");
System.out.println("[1] Start Game");
System.out.println("[2] Rules");
System.out.println("[3] Exit\n");
int choose = keyboard.nextInt();
switch (choose) {
case 1:
hiddenWord();
think();
System.out.println("\nCongratulations!");
break;
case 2:
userInit.showTheRules(this.name);
showMenu();
case 3:
System.out.println("...Good Bye...");
break;
default:
System.err.println("Please enter a valid command!");
showMenu();
break;
}
} while (keyboard.nextInt() != 3);
}
// selected word(hidden)
public String hiddenWord() {
this.selectedWord = db.selectedWord();
guessTheWord = "";
for (int i = 0; i < selectedWord.length(); i++) {
this.guessTheWord = guessTheWord.concat("-");
}
return guessTheWord;
}
// graphic
public void showHangman(int noMistakes) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (noMistakes) {
case 0:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 1:
System.out.println(" ___________ ");
System.out.println(" | / | ");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 2:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 3:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | / ");
System.out.println(" | / ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 4:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | / \\ ");
System.out.println(" | / \\");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 5:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | /|\\ ");
System.out.println(" | / | \\");
System.out.println(" | |");
System.out.println(" | ");
System.out.println(" | ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 6:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | /|\\ ");
System.out.println(" | / | \\");
System.out.println(" | |");
System.out.println(" | / ");
System.out.println(" | / ");
System.out.println(" | ");
System.out.println("____|_______________");
break;
case 7:
System.out.println(" ___________ ");
System.out.println(" | / |");
System.out.println(" |/ _|_");
System.out.println(" | (|. .|)");
System.out.println(" | |_-_| ");
System.out.println(" | | ");
System.out.println(" | /|\\ ");
System.out.println(" | / | \\");
System.out.println(" | |");
System.out.println(" | / \\");
System.out.println(" | / \\");
System.out.println(" | ");
System.out.println("____|_______________");
break;
}
}
// all the logic
public void think() {
ArrayList<Character> usedChars = new ArrayList<Character>();
String selected = this.selectedWord;
String guess = this.guessTheWord;
StringBuilder sb = new StringBuilder(guess);
char search;
while ((guess.contains("-")) && noMistakes < 9) {
if (this.noMistakes == 8) {
System.err.println("...GAME OVER...");
this.noMistakes = 0;
showMenu();
}
// graphic
showHangman(noMistakes);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Used: " + usedChars);
System.err.println("\nThis is your word:\n" + sb + "\n");
String userInsert = keyboard.next();
usedChars.add(userInsert.charAt(0));
if (userInsert.length() == 1) {
if (selected.contains(userInsert.toLowerCase())) {
for (int i = 0; i < guess.length(); i++) {
search = selected.charAt(i);
if (search == userInsert.charAt(0)) {
sb.setCharAt(i, search);
}
}
guess = sb.toString();
} else {
this.noMistakes++;
System.out.println();
System.err.println("Bad luck...Try again! ");
}
} else {
System.err.println("Please insert only one letter at a time!");
}
}
}
}
|
C# | UTF-8 | 2,809 | 3.03125 | 3 | [] | no_license | using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CryptoCourse
{
public class Crypto
{
public static void CryptFile(string fileIn, string fileOut, SymmetricAlgorithm algo, byte[] rgbKey, byte[] rgbIv)
{
if (string.IsNullOrEmpty(fileIn))
throw new FileNotFoundException(string.Format("Неверный путь к файлу: {0}.", fileIn));
if (!File.Exists(fileIn))
throw new FileNotFoundException(string.Format("Файл '{0}' не найден.", fileIn));
const string cryptExt = ".crypt";
using (var sa = algo)
using (var fsw = File.Open(fileOut + cryptExt, FileMode.Create, FileAccess.Write))
using (var cs = new CryptoStream(fsw, sa.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
{
byte[] buff;
using (var fs = File.Open(fileIn, FileMode.Open, FileAccess.Read))
{
buff = new byte[fs.Length + sizeof(long)];
fs.Read(buff, sizeof(long), buff.Length - sizeof(long));
var i = 0;
foreach (byte _byte in BitConverter.GetBytes(fs.Length))
buff[i++] = _byte;
}
cs.Write(buff, 0, buff.Length);
cs.Flush();
}
Array.Clear(rgbKey, 0, rgbKey.Length);
Array.Clear(rgbIv, 0, rgbIv.Length);
}
public static void DecryptFile(string name, string fileIn, string fileOut, SymmetricAlgorithm algo, byte[] rgbKey, byte[] rgbIv)
{
if (string.IsNullOrEmpty(fileIn))
throw new FileNotFoundException(string.Format("Неверный путь к файлу: {0}.", fileIn));
if (!File.Exists(fileIn))
throw new FileNotFoundException(string.Format("Файл '{0}' не найден.", fileIn));
using (var sa = algo)
using (var fsr = File.Open(fileIn, FileMode.Open, FileAccess.Read))
using (var cs = new CryptoStream(fsr, sa.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Read))
{
var buff = new byte[fsr.Length];
cs.Read(buff, 0, buff.Length);
//
using (var fsw = File.Open(name + "\\decrypted_" + fileOut, FileMode.Create, FileAccess.Write))
//
{
var len = (int)BitConverter.ToInt64(buff, 0);
fsw.Write(buff, sizeof(long), len);
fsw.Flush();
}
}
Array.Clear(rgbKey, 0, rgbKey.Length);
Array.Clear(rgbIv, 0, rgbIv.Length);
}
}
}
|
TypeScript | UTF-8 | 568 | 2.59375 | 3 | [] | no_license | import genericSort from '@core/utils/genericSort';
import { GroceryItemEdit } from 'inventory/types';
import { Option } from '@core/types';
const getNameOptions = (
groceries: Record<string, GroceryItemEdit>,
targetCollection: string[]
): Option[] => {
const names: Option[] = [];
Object.entries(groceries).forEach(([id, item]) => {
if (!targetCollection.includes(id)) {
names.push({
label: item?.name,
value: id
});
}
})
return names.sort((a, b) => genericSort(a.label, b.label));
}
export default getNameOptions; |
C++ | UTF-8 | 7,885 | 3.3125 | 3 | [] | no_license | #include "assignments/ev/euclidean_vector.h"
#include <algorithm> // Look at these - they are helpful https://en.cppreference.com/w/cpp/algorithm
#include <cassert>
#include <cmath>
#include <iostream>
#include <sstream>
/*
* CONSTRUCTORS
*/
EuclideanVector::EuclideanVector(int i, double d) {
this->size_ = i;
this->magnitudes_ = std::make_unique<double[]>(this->size_);
for (std::size_t j = 0; j < this->size_; ++j) {
this->magnitudes_[j] = d;
}
}
EuclideanVector::EuclideanVector(std::vector<double>::const_iterator begin,
std::vector<double>::const_iterator end) noexcept {
this->size_ = end - begin;
this->magnitudes_ = std::make_unique<double[]>(this->size_);
auto i = 0;
for (auto it = begin; it != end ; ++it, ++i) {
this->magnitudes_[i] = *it;
}
}
EuclideanVector::EuclideanVector(const EuclideanVector& e) noexcept{
this->size_ = e.GetNumDimensions();
this->magnitudes_ = std::make_unique<double[]>(this->size_);
for (int i = 0; i < this->GetNumDimensions(); ++i) {
this->magnitudes_[i] = e[i];
}
}
EuclideanVector::EuclideanVector(EuclideanVector&& e) noexcept { this->size_ = e.GetNumDimensions();
this->magnitudes_ = std::make_unique<double[]>(this->size_);
for (int i = 0; i < this->GetNumDimensions(); ++i) {
this->magnitudes_[i] = e[i];
}
e.size_ = 0;
e.magnitudes_ = std::make_unique<double[]>(0);
}
/*
* DESTRUCTOR
*/
/*
EuclideanVector EuclideanVector::aCopy(const EuclideanVector& e) noexcept {
return EuclideanVector();
}
EuclideanVector EuclideanVector::aMove(EuclideanVector&& e) noexcept {
return <EuclideanVector&&>();
}
*/
/*
* OPERATIONS
*/
EuclideanVector& EuclideanVector::operator=(EuclideanVector e) noexcept {
this->size_ = e.GetNumDimensions();
for (int i = 0; i < e.GetNumDimensions(); ++i) {
this->magnitudes_[i] = e[i];
}
return *this;
}
EuclideanVector& EuclideanVector::operator=(EuclideanVector&& e) noexcept {
this->size_ = std::move(e.size_);
this->magnitudes_ = std::move(e.magnitudes_);
return *this;
}
double& EuclideanVector::operator[](int i) noexcept {
return this->magnitudes_[i];
}
double EuclideanVector::operator[](int i) const noexcept {
return this->magnitudes_[i];
}
EuclideanVector& EuclideanVector::operator+=(const EuclideanVector& e) {
if (this->GetNumDimensions() != e.GetNumDimensions()) {
std::ostringstream err;
err << "Dimensions of LHS(" << this->GetNumDimensions();
err << ") and RHS(" << e.GetNumDimensions() << ") do not match";
throw EuclideanVectorError(err.str());
}
for (int i = 0; i < this->GetNumDimensions(); ++i) {
this->magnitudes_[i] += e[i];
}
return *this;
}
EuclideanVector& EuclideanVector::operator-=(const EuclideanVector& e) {
if (this->GetNumDimensions() != e.GetNumDimensions()) {
std::ostringstream err;
err << "Dimensions of LHS(" << this->GetNumDimensions();
err << ") and RHS(" << e.GetNumDimensions() << ") do not match";
throw EuclideanVectorError(err.str());
}
for (std::size_t i = 0; i < this->size_; ++i) {
this->magnitudes_[i] -= e[i];
}
return *this;
}
EuclideanVector& EuclideanVector::operator*=(const double& rhs) noexcept {
for (std::size_t j = 0; j < this->size_; ++j) {
this->magnitudes_[j] *= rhs;
}
return *this;
}
EuclideanVector& EuclideanVector::operator/=(const double& rhs) {
if (rhs == 0.0) {
throw EuclideanVectorError("Invalid vector division by 0");
}
for (std::size_t j = 0; j < this->size_; ++j) {
this->magnitudes_[j] /= rhs;
}
return *this;
}
/*EuclideanVector::operator std::vector<double>() noexcept {
std::vector<double> v;
for (int i = 0; i < this->GetNumDimensions(); ++i) {
v.push_back(this->at(i));
}
return v;
}*/
EuclideanVector::operator std::list<double>() noexcept {
std::list<double> l;
for (int i = 0; i < this->GetNumDimensions(); ++i) {
l.push_back(this->at(i));
}
return l;
}
/*
* METHODS
*/
double EuclideanVector::at(int i) noexcept {
return this->magnitudes_[i];
}
int EuclideanVector::GetNumDimensions() const noexcept {
return this->size_;
}
double EuclideanVector::GetEuclideanNorm() noexcept {
double norm = 0.0;
for (std::size_t i = 0; i < this->size_; ++i) {
norm += this->at(i) * this->at(i);
}
return pow(norm, 0.5);
}
EuclideanVector EuclideanVector::CreateUnitVector() {
if (this->GetNumDimensions() == 0) {
throw EuclideanVectorError("EuclideanVector with no dimensions does not have a unit vector");
}
return *this / this->GetEuclideanNorm();
}
/*
* FRIENDS
*/
bool operator==(const EuclideanVector& lhs, const EuclideanVector& rhs) noexcept {
auto equal = false;
if (lhs.GetNumDimensions() == rhs.GetNumDimensions()) {
equal = true;
for (int i = 0; i < lhs.GetNumDimensions(); ++i) {
if (lhs[i] != rhs[i]) {
equal = false;
}
}
}
return equal;
}
bool operator!=(const EuclideanVector& lhs, const EuclideanVector& rhs) noexcept {
return !(lhs == rhs);
}
EuclideanVector operator+(const EuclideanVector& lhs, const EuclideanVector& rhs) {
if (lhs.GetNumDimensions() != rhs.GetNumDimensions()) {
std::ostringstream err;
err << "Dimensions of LHS(" << lhs.GetNumDimensions();
err << ") and RHS(" << rhs.GetNumDimensions() << ") do not match";
throw EuclideanVectorError(err.str());
}
auto size = lhs.GetNumDimensions();
std::vector<double> magnitudes;
for (int i = 0; i < size; ++i) {
magnitudes.push_back(lhs[i] + rhs[i]);
}
return EuclideanVector(magnitudes.begin(), magnitudes.end());
}
EuclideanVector operator-(const EuclideanVector& lhs, const EuclideanVector& rhs) {
if (lhs.GetNumDimensions() != rhs.GetNumDimensions()) {
std::ostringstream err;
err << "Dimensions of LHS(" << lhs.GetNumDimensions();
err << ") and RHS(" << rhs.GetNumDimensions() << ") do not match";
throw EuclideanVectorError(err.str());
}
auto size = lhs.GetNumDimensions();
std::vector<double> magnitudes;
for (int i = 0; i < size; ++i) {
magnitudes.push_back(lhs[i] - rhs[i]);
}
return EuclideanVector(magnitudes.begin(), magnitudes.end());
}
double operator*(const EuclideanVector& lhs, const EuclideanVector& rhs) {
if (lhs.GetNumDimensions() != rhs.GetNumDimensions()) {
std::ostringstream err;
err << "Dimensions of LHS(" << lhs.GetNumDimensions();
err << ") and RHS(" << rhs.GetNumDimensions() << ") do not match";
throw EuclideanVectorError(err.str());
}
auto size = lhs.GetNumDimensions();
auto dp = 0.0;
for (int i = 0; i < size; ++i) {
dp += lhs[i] * rhs[i];
}
return dp;
}
EuclideanVector operator*(const EuclideanVector& lhs, const double& rhs) noexcept {
auto size = lhs.GetNumDimensions();
std::vector<double> magnitudes;
for (int i = 0; i < size; ++i) {
magnitudes.push_back(lhs[i] * rhs);
}
return EuclideanVector(magnitudes.begin(), magnitudes.end());
}
EuclideanVector operator/(const EuclideanVector& lhs, const double& rhs) {
if (rhs == 0) {
throw EuclideanVectorError("Invalid vector division by 0");
}
auto size = lhs.GetNumDimensions();
std::vector<double> magnitudes;
for (int i = 0; i < size; ++i) {
magnitudes.push_back(lhs[i] / rhs);
}
auto ret = EuclideanVector(magnitudes.begin(), magnitudes.end());
return ret;
}
std::ostream& operator<<(std::ostream& os, const EuclideanVector& v) noexcept {
os << "[";
if (v.GetNumDimensions() > 0) {
for (int i = 0; i < v.GetNumDimensions() - 1; ++i) {
os << v[i] << " ";
}
os << v[v.GetNumDimensions() - 1] << "]";
} else {
os << "]";
}
return os;
}
|
Markdown | UTF-8 | 1,373 | 2.84375 | 3 | [] | no_license | ---
layout: post
author: Anthony
---
# Anthony-s-Blog-
Anthony's Adventures Around ISD!
title: Day 1!
date: 2021-06-8
Day 1 at KUB!!! I'm going to be here for 8 weeks and looking forward to it. This day has been pretty chill. The people here are mostly quiet and keep to them themselves. I had computer problems before but todays was something I've never seen before. First, I had a little trouble hooking up everything. I have two monitors in front of me then I learned I will be using a laptop. Ha ha I know, then I turned the laptop on and... it blue screened for over 30 minutes... :( Eventually, I had to go to the IT help desk. They were stumped too! Lastly, they called Cyber Security and "BOOM", starts working. Madison, my mentor, gets me started on this site called GitHub. This site is going to be helping me for a few weeks. It will teach some basics to coding and many other things. After that, I learned enough to write a blog. I had a little hiccups here and there, but I'm understanding more and more. This has been a nice new learning experience because I've always liked working with technology since I was young, but I've never done anything like this! It's very cool to code my own blog and look forward it to it! I have about a hour left in my day. I'll wrap it up there. I don't really know how to end off a blog... So until next time! -Anthony
|
Java | UTF-8 | 5,864 | 2.1875 | 2 | [] | no_license | package com.lph.exam_web.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lph.exam_web.common.Result;
import com.lph.exam_web.pojo.ExamPaper;
import com.lph.exam_web.service.NoticeService;
import com.lph.exam_web.vo.SetScoreVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@RestController
@CrossOrigin
@ResponseBody
@Controller
@Api(tags = "通知接口")
@RequestMapping("api/Notice")
public class NoticeController {
@Autowired
private NoticeService noticeService;
@ApiOperation("获取所有通知信息")
@GetMapping("/getAllNotice")
public Result<Object> getAllNotice(){
return noticeService.getAllNotice();
}
@ApiOperation("获取通知ID获取通知信息")
@GetMapping("/getNoticeById")
public Result<Object> getNoticeById(@RequestParam(value = "noticeId")String noticeId){
return noticeService.getNoticeById(noticeId);
}
@ApiOperation("添加通知信息")
@PostMapping("/addNotice")
public Result<Object> addNotice(@RequestParam(value = "type")String type,
@RequestParam(value = "startTime")String startTimeD,
@RequestParam(value = "endTime")String endTimeD,
@RequestParam(value = "teacherId")String teacherId,
@RequestParam(value = "courseId")String courseId){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long l_start = Long.parseLong(startTimeD);
long l_end = Long.parseLong(endTimeD);
String startTime = sdf.format(l_start);
String endTime = sdf.format(l_end);
return noticeService.addNotice(type, startTime, endTime, teacherId,courseId);
}
// 添加试卷试题
@ApiOperation("批量添加试题(生成试卷)")
@PostMapping("/addExamPaper")
public Result<Object> addExamPaper(@RequestParam(value = "list")String list){
List<ExamPaper> lists = new ArrayList<>();
JSONArray jsonArray = JSONObject.parseArray(list);
for (int i=0;i<jsonArray.size();i++){
JSONObject jsonObject = JSONObject.parseObject(jsonArray.getString(i));
ExamPaper examPaper = new ExamPaper();
examPaper.setNoticeId((String) jsonObject.get("noticeId"));
examPaper.setQuestionId((String) jsonObject.get("questionId"));
lists.add(examPaper);
}
// System.out.println(lists);
return noticeService.addExamPaper(lists);
}
// 分页获取通知
@ApiOperation("分页获取考试通知")
@GetMapping("/getNoticeByTotal")
public Result<Object> getNoticeByTotal(@RequestParam(value = "totalPage")int totalPage){
return noticeService.getNoticeByPage(totalPage);
}
// 根据编号或者课程号获取通知
@ApiOperation("根据编号或者课程号获取通知")
@GetMapping("/getNoticeByCourseIdAndNoticeIdByPage")
public Result<Object> getNoticeByCourseIdAndNoticeIdByPage(@RequestParam(value = "totalPage")int totalPage,
@RequestParam(value = "courseId",required = false)String courseId,
@RequestParam(value = "noticeId",required = false)String noticeId){
return noticeService.getNoticeByCourseIdAndNoticeIdByPage(courseId, noticeId, totalPage);
}
@ApiOperation("根据Id修改通知状态")
@PostMapping("/updateNoticeInfoById")
public Result<Object> updateNoticeInfo(@RequestParam(value = "type")int type,
@RequestParam(value = "noticeId")String noticeId){
return noticeService.updateNoticeStatus(type, noticeId);
}
// 获取考试结果
@ApiOperation("获取考试结果")
@GetMapping("/getExamResult")
public Result<Object> getExamResult(){
return noticeService.getExamResult();
}
@ApiOperation("根据通知Id获取考试情况")
@GetMapping("/getExamByNoticeId")
public Result<Object> getExamByNoticeId(@RequestParam(value = "noticeId")String noticeId){
return noticeService.getExamByNoticeId(noticeId);
}
// 修改用户的成绩
@ApiOperation("批量添加试题(生成试卷)")
@PostMapping("/setScoreByUserIdAndNoticeId")
public Result<Object> setScoreByUserIdAndNoticeId(@RequestParam(value = "list")String list){
List<SetScoreVo> lists = new ArrayList<>();
JSONArray jsonArray = JSONObject.parseArray(list);
for (int i=0;i<jsonArray.size();i++){
JSONObject jsonObject = JSONObject.parseObject(jsonArray.getString(i));
SetScoreVo s = new SetScoreVo();
s.setNoticeId((String) jsonObject.get("noticeId"));
s.setFinalscore((String) jsonObject.get("finalscore"));
s.setUserId((String) jsonObject.get("userId"));
lists.add(s);
}
return noticeService.setScoreByUserIdAndNoticeId(lists);
}
@ApiOperation("修改分数公布状态")
@PostMapping("/setScorePublic")
public Result<Object> setScorePublic(@RequestParam(value = "noticeId")String noticeId){
return noticeService.setScorePublic(noticeId);
}
@ApiOperation("根据通知Id获取试卷")
@GetMapping("/getExamResultByNoticeId")
public Result<Object> getExamResultByNoticeId(@RequestParam(value = "noticeId")String noticeId){
return noticeService.getExamResultByNoticeId(noticeId);
}
}
|
Markdown | UTF-8 | 1,089 | 2.609375 | 3 | [] | no_license | Flowspace Bakery
================
Flowspace Bakery is an artisanal digital bakery, crafting the finest digital cookies in New York City.
We don't mass produce our cookies in faceless factories. Instead, We bake cookies to order, one at a time.
Set up docker
-------------
Run docker-compose to start the Redis and PostgreSQL containers in the background.
```bash
$ docker-compose up --detach
```
Running the application
-----------------------
To run the application we have to start the Rails server and Sidekiq
```bash
bundle exec rails db:setup
bundle exec rails server
bundle exec sidekiq # In another terminal
```
Then open the browser at http://localhost:3000. HTTP Auth access is: bake / somecookies
Test Suite
----------
Like most bakeries, Flowspace Bakery has a test suite. The full suite can be run with:
```bash
$ RAILS_ENV=test bundle exec db:create
$ bundle exec rspec spec
```
Requirements
-------------
This application requires:
- Ruby 2.7.1
- Docker
- docker-compose
Similar Projects
----------------
[Momofuku milk bar](http://milkbarstore.com/)
|
Python | UTF-8 | 723 | 3.5 | 4 | [] | no_license | // Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
// Your code here along with comments explaining your approach
In this problem we have to find the maximum sum of the minimu of the pairs in the array.For this we have to sort the array first and then all the even index place digits.
# Time complexity --> o(nlogn)
# space complexity --> o(1)
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==None or len(nums)==0:
return 0
nums=sorted(nums)
total=0
for i in range(0,len(nums),2):
total=total+nums[i]
return total |
Go | UTF-8 | 2,369 | 3.234375 | 3 | [] | no_license | package picture
import (
"fmt"
"image"
"log"
"github.com/BurntSushi/graphics-go/graphics"
"github.com/fogleman/gg"
"github.com/nfnt/resize"
)
const (
backgroundPATH string = "pictures/sea.jpg"
picsPATH string = "pictures/%v.png"
)
// RepresentationShip структура для передачи нужным нам
// на репрезентации данных про корабль
type RepresentationShip struct {
Name string // имя файла нужного спрайта
X, Y int // координаты на фоне
Rotation float64 // угол поворота (по часовой)
Width, Height int // нужные нам размеры спрайта в пикселях
}
func main() {
var ships []RepresentationShip
ships = []RepresentationShip{
{
Name: "galley",
X: 125,
Y: 125,
Rotation: 0.0,
Width: 50,
Height: 50,
},
{
Name: "barge",
X: 725,
Y: 825,
Rotation: 45.0,
Width: 50,
Height: 50,
},
}
DrawShips(&ships)
}
// DrawShips ...
func DrawShips(ships *[]RepresentationShip) {
background, err := gg.LoadJPG(backgroundPATH)
if err != nil {
log.Println(err)
}
backgroundSize := background.Bounds().Size()
dc := gg.NewContext(backgroundSize.X, backgroundSize.Y)
dc.DrawImage(background, 0, 0)
for _, ship := range *ships {
dc.SetRGBA(0, 0, 0, 0.5)
sprite, err := gg.LoadPNG(fmt.Sprintf(picsPATH, ship.Name))
if err != nil {
log.Println(err)
}
if sprite.Bounds().Max.X != ship.Width && sprite.Bounds().Max.Y != ship.Height {
sprite = resize.Resize(uint(ship.Width), uint(ship.Height), sprite, resize.Lanczos3)
}
if ship.Rotation != 0.0 {
rotatedSprite := image.NewRGBA(image.Rect(0, 0, ship.Height, ship.Width))
graphics.Rotate(rotatedSprite, sprite, &graphics.RotateOptions{Angle: ship.Rotation})
dc.DrawImage(rotatedSprite, ship.X, ship.Y)
ship.X, ship.Y = ship.X+ship.Width/2, ship.Y+ship.Width/2
dc.DrawCircle(float64(ship.X), float64(ship.Y), float64(ship.Width)*2)
dc.Stroke()
} else {
dc.DrawImage(sprite, ship.X, ship.Y)
ship.X, ship.Y = ship.X+ship.Width/2, ship.Y+ship.Width/2
dc.DrawCircle(float64(ship.X), float64(ship.Y), float64(ship.Width)*2)
dc.SetLineWidth(3)
dc.Stroke()
}
}
dc.SavePNG("out.png")
}
|
PHP | UTF-8 | 7,565 | 2.953125 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of PHPDebugConsole
*
* @package PHPDebugConsole
* @author Brad Kent <bkfake-github@yahoo.com>
* @license http://opensource.org/licenses/MIT MIT
* @copyright 2014-2022 Brad Kent
* @version v3.0
*/
namespace bdk\Debug\Dump\Html;
use bdk\Debug\Dump\Html as Dumper;
/**
* build a table
*/
class Table
{
protected $debug;
protected $dumper;
protected $options;
/**
* Constructor
*
* @param Dumper $dumper html dumper
*/
public function __construct(Dumper $dumper)
{
$this->debug = $dumper->debug;
$this->dumper = $dumper;
}
/**
* Formats an array as a table
*
* @param mixed $rows array of \Traversable or Abstraction
* @param array $options options
* 'attribs' : key/val array (or string - interpreted as class value)
* 'caption' : optional caption
* 'tableInfo':
* 'columns' : list of columns info
*
* @return string
*/
public function build($rows, $options = array())
{
$this->options = \array_merge(array(
'attribs' => array(),
'caption' => '',
'onBuildRow' => null, // callable (or array of callables)
'tableInfo' => array(),
), $options);
return $this->debug->html->buildTag(
'table',
$this->options['attribs'],
"\n"
. $this->buildCaption()
. $this->buildHeader()
. $this->buildbody($rows)
. $this->buildFooter()
);
}
/**
* Builds table's body
*
* @param array $rows array of arrays or Traverssable
*
* @return string
*/
protected function buildBody($rows)
{
$tBody = '';
$this->options['onBuildRow'] = \is_callable($this->options['onBuildRow'])
? array($this->options['onBuildRow'])
: (array) $this->options['onBuildRow'];
foreach ($rows as $k => $row) {
$rowInfo = \array_merge(
array(
'class' => null,
'key' => null,
'summary' => null,
),
isset($this->options['tableInfo']['rows'][$k])
? $this->options['tableInfo']['rows'][$k]
: array()
);
$html = $this->buildRow($row, $rowInfo, $k);
$tBody .= $html;
}
$tBody = \str_replace(' title=""', '', $tBody);
return '<tbody>' . "\n" . $tBody . '</tbody>' . "\n";
}
/**
* Build table caption
*
* @return string
*/
private function buildCaption()
{
$caption = \htmlspecialchars((string) $this->options['caption']);
if (!$this->options['tableInfo']['class']) {
return $caption
? '<caption>' . $caption . '</caption>' . "\n"
: '';
}
$class = $this->dumper->valDumper->markupIdentifier(
$this->options['tableInfo']['class'],
false,
'span',
array(
'title' => $this->options['tableInfo']['summary'] ?: null,
)
);
$caption = $caption
? $caption . ' (' . $class . ')'
: $class;
return '<caption>' . $caption . '</caption>' . "\n";
}
/**
* Builds table's tfoot
*
* @return string
*/
protected function buildFooter()
{
$haveTotal = false;
$cells = array();
foreach ($this->options['tableInfo']['columns'] as $colInfo) {
if (isset($colInfo['total']) === false) {
$cells[] = '<td></td>';
continue;
}
$totalVal = $colInfo['total'];
if (\is_float($totalVal)) {
$totalVal = \round($totalVal, 6);
}
$cells[] = $this->dumper->valDumper->dump($totalVal, array('tagName' => 'td'));
$haveTotal = true;
}
if (!$haveTotal) {
return '';
}
return '<tfoot>' . "\n"
. '<tr><td> </td>'
. ($this->options['tableInfo']['haveObjRow'] ? '<td> </td>' : '')
. \implode('', $cells)
. '</tr>' . "\n"
. '</tfoot>' . "\n";
}
/**
* Returns table's thead
*
* @return string
*/
protected function buildHeader()
{
$labels = array();
foreach ($this->options['tableInfo']['columns'] as $colInfo) {
$label = $colInfo['key'];
if (isset($colInfo['class'])) {
$label .= ' ' . $this->dumper->valDumper->markupIdentifier($colInfo['class']);
}
$labels[] = $label;
}
return '<thead>' . "\n"
. '<tr>'
. ($this->options['tableInfo']['indexLabel']
? '<th class="text-right">' . $this->options['tableInfo']['indexLabel'] . '</th>'
: '<th> </th>')
. ($this->options['tableInfo']['haveObjRow']
? '<th> </th>'
: '')
. '<th scope="col">' . \implode('</th><th scope="col">', $labels) . '</th>'
. '</tr>' . "\n"
. '</thead>' . "\n";
}
/**
* Returns table row
*
* @param mixed $row should be array or object abstraction
* @param array $rowInfo row info / meta
* @param string|int $rowKey row key
*
* @return string
*/
protected function buildRow($row, $rowInfo, $rowKey)
{
$str = '';
$rowKey = $rowInfo['key'] ?: $rowKey;
$rowKeyParsed = $this->debug->html->parseTag($this->dumper->valDumper->dump($rowKey));
$str .= '<tr>';
/*
Output key
*/
$str .= $this->debug->html->buildTag(
'th',
$this->debug->arrayUtil->mergeDeep($rowKeyParsed['attribs'], array(
'class' => array('t_key', 'text-right'),
'scope' => 'row',
)),
$rowKeyParsed['innerhtml']
);
/*
Output row's classname
*/
if ($this->options['tableInfo']['haveObjRow']) {
$str .= $rowInfo['class']
? $this->dumper->valDumper->markupIdentifier($rowInfo['class'], false, 'td', array(
'title' => $rowInfo['summary'] ?: null,
))
: '<td class="t_undefined"></td>';
}
/*
Output values
*/
foreach ($row as $v) {
$str .= $this->dumper->valDumper->dump($v, array('tagName' => 'td'));
}
$str .= '</tr>' . "\n";
return $this->onBuildRow($str, $row, $rowInfo, $rowKey);
}
/**
* Call any onBuildRow callbacks
*
* @param string $html built row
* @param mixed $row should be array or object abstraction
* @param array $rowInfo row info / meta
* @param string|int $rowKey row key
*
* @return string html fragment
*/
private function onBuildRow($html, $row, $rowInfo, $rowKey)
{
foreach ($this->options['onBuildRow'] as $callable) {
if (\is_callable($callable)) {
$html = $callable($html, $row, $rowInfo, $rowKey);
}
}
return $html;
}
}
|
Python | UTF-8 | 1,676 | 3.5 | 4 | [] | no_license | #Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.
# - For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name.
#If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.
# - For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.
#If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.
# - For example, "m.y+name@email.com" will be forwarded to "my@email.com".
#It is possible to use both of these rules at the same time.
#Given an array of strings emails where we send one email to each email[i], return the number of different addresses that actually receive mails.
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
receives_emails = 0
if len(emails) > 100 or len(emails) < 1:
return 0
for i in range(len(emails)):
if len(emails[i]) > 100 or len(emails[i]) < 1:
return 0
email_s = emails[i].split('@')
local = email_s[0]
domain = email_s[1]
if (domain.count('.') == 1) and ('+' not in domain) and (local[0] != '+'):
receives_emails += 1
return receives_emails
#Time complexity: O(n), where n is the total content of emails
#Space complexity: O(n)
|
Java | UTF-8 | 194 | 1.65625 | 2 | [
"Apache-2.0"
] | permissive | package com.inventario.microservice.user.service;
import org.springframework.http.ResponseEntity;
public interface IEmployeeService {
public abstract ResponseEntity<?> delete(String id);
}
|
C# | UTF-8 | 8,861 | 2.765625 | 3 | [
"MIT"
] | permissive | namespace MSTranslate
{
using MSTranslate.ExtensionMethods;
using MSTranslate.Interfaces;
using MSTranslate.Service;
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Net;
using System.Security;
/// <summary>
/// Connects to a Microsoft Azure Web service to translate strings from one language into another.
/// </summary>
public class Translator : ITranslator
{
#region fields
private List<ILanguageCode> mLangList = null;
#endregion fields
#region constructor
/// <summary>
/// Standard class constructor
/// </summary>
public Translator()
{
}
#endregion constructor
#region properties
/// <summary>
/// Returns an alphabetically ordered List of language objects that represent
/// languages and their language code supported by this service.
/// </summary>
List<ILanguageCode> ITranslator.LanguageList
{
get
{
if (mLangList == null)
{
var bcp47 = new Codes();
var list = new List<ILanguageCode>();
foreach (var item in bcp47.list)
{
var cultureLanguage = item as CultureLanguage;
if (cultureLanguage != null)
{
// add a copy of this and avoid its sub-items
list.Add(new CultureLanguage(cultureLanguage));
foreach (var clItem in cultureLanguage.list)
{
list.Add(new CultureLanguage(clItem.langCode, clItem.lang, clItem.country));
}
}
else
{
var country = item as Country;
if (country != null)
{
foreach (var countryItem in country.list)
{
// add a copy of this
list.Add(new CultureLanguage(countryItem.name,
countryItem.language,
countryItem.country));
}
}
}
}
mLangList = list.OrderBy(l => l.Bcp47_LangCode).ToList();
}
return mLangList;
}
}
#endregion properties
#region methods
/// <summary>
/// Creates an object that keeps login information for MS Translate API service
/// </summary>
/// <param name="uri"></param>
/// <param name="appKey"></param>
/// <returns></returns>
Interfaces.ILoginCredentials ITranslator.CreateLoginCredentials(Uri uri,
SecureString user,
SecureString password)
{
return new LoginCredentials
(
// this is the service root uri for the Microsoft Translator service
//new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/"),
//
// this is the Account Key generated for an app (not all characters are real key characters)
// "oHMSFuynxyzp26KOmysK7WMF2DakuBkF2BhPFSNQP/g"
uri, user, password
);
}
/// <summary>
/// Get translated text from Bing Translator service.
/// </summary>
/// <param name="textToTranslate">Text to translate.</param>
/// <param name="fromLang">Language to translate from.</param>
/// <param name="toLang">Language to translate to.</param>
/// <returns>Translated text.</returns>
List<string> ITranslator.GetTranslatedText(string textToTranslate,
string fromLang,
string toLang,
ILoginCredentials login)
{
if (login == null)
return null;
// the TranslatorContainer gives us access to the Microsoft Translator services
MSTranslate.Service.TranslatorContainer tc = new MSTranslate.Service.TranslatorContainer(login.TranslationServiceUri);
// Give the TranslatorContainer access to your subscription
tc.Credentials = new NetworkCredential(SecureStringExtensionMethod.ConvertToUnsecureString(login.User),
login.Password);
try
{
// Generate the query
DataServiceQuery<Translation> translationQuery = tc.Translate(textToTranslate, toLang, fromLang);
// Call the query and get the results as a List
var translationResults = translationQuery.Execute().ToList();
// Verify there was a result
if (translationResults.Count() <= 0)
return new List<string>();
// In case there were multiple results, pick the first one
var translationResult = translationResults.First();
List<string> ret = new List<string>();
for (int i = 0; i < translationResults.Count(); i++)
{
ret.Add(translationResult.Text);
}
return ret;
}
catch (Exception exc)
{
throw new Exception(string.Format("Translation text:'{0}', toLang: '{1}', fromLang '{2}'", textToTranslate, toLang, fromLang), exc);
}
}
/// <summary>
/// Checks basic parameters of translation to make sure known error are dealt with in advance.
/// </summary>
/// <param name="TranslationServiceUri"></param>
/// <param name="user"></param>
/// <param name="password"></param>
/// <param name="sourceFileLanguage"></param>
/// <param name="targetFileLanguage"></param>
/// <param name="destination"></param>
/// <param name="cts"></param>
/// <returns>Return null if everythings OK. Returns an error object describing a problem
/// if a pre-requisite parameter is not as required.</returns>
ITranslatorError ITranslator.Check(string translationServiceUri,
SecureString user,
SecureString password,
string sourceFileLanguage,
string targetFileLanguage,
ProcessDestination destination,
System.Threading.CancellationTokenSource cts)
{
if (IsNullOrEmpty(user) == true)
return TranslatorError.GetErrorObject(TranslateErrorCode.Missing_Login_AuthenticationParameter);
if (IsNullOrEmpty(password) == true)
return TranslatorError.GetErrorObject(TranslateErrorCode.Missing_Login_AuthenticationParameter);
try
{
// Check if Uri appears to be formatted well and generate error if not.
new Uri(translationServiceUri);
}
catch
{
return TranslatorError.GetErrorObject(TranslateErrorCode.Missing_URI_AuthenticationParameter);
}
return null;
}
/// <summary>
/// Returns true if secure string appears to be empty, otherwise false.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private bool IsNullOrEmpty(SecureString s)
{
if (s == null)
return true;
if (s.Length == 0)
return true;
return false;
}
/// <summary>
/// Returns true if secure string appears to be empty, otherwise false.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private bool IsNullOrEmpty(Uri s)
{
if (s == null)
return true;
if (string.IsNullOrEmpty(s.AbsolutePath) == true)
return true;
return false;
}
#endregion methods
}
}
|
PHP | UTF-8 | 788 | 2.71875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: victorsecuring
* Date: 23.12.16
* Time: 12:18 PM
*/
namespace zaboy\res\Di\Example\ExtendedIC;
use zaboy\res\Di\InsideConstruct;
class SimpleDependency
{
protected $simpleStringA;
public $simpleNumericB;
private $simpleArrayC;
public function __construct($simpleStringA = 'simpleStringA',
$simpleNumericB = 2.4,
$simpleArrayC = [0 => 'simpleArrayC'])
{
InsideConstruct::initMyServices();
}
/**
* @return mixed
*/
public function getSimpleStringA()
{
return $this->simpleStringA;
}
/**
* @return mixed
*/
public function getSimpleArrayC()
{
return $this->simpleArrayC;
}
} |
C# | UTF-8 | 1,363 | 4.0625 | 4 | [] | no_license | using System;
namespace MovieList
{
class Program
{
static void Main(string[] args)
{
//this is a list of type MovieDatabase
MovieDatabase MovieL = new MovieDatabase();
bool keepGoing = true;
do
{
MovieL.PrintListOfMoviesByCategory();
keepGoing = Continue();
}
while (keepGoing == true);
}
public static bool Continue()
{
string input = GetUserInput("Would you like to continue ? y/n");
if(input == "y")
{
return true;
}
else if(input == "n")
{
Console.WriteLine("Have a nice day!");
return false;
}
else
{
Console.WriteLine("I am sorry! I don't understand that!");
return Continue();
}
}
//Method taking in the user answer, and then assigns it to the continue method to then do its job
private static string GetUserInput(string prompt)
{
Console.WriteLine(prompt);
string userAnswer = Console.ReadLine().ToLower();
return userAnswer;
}
}
}
|
JavaScript | UTF-8 | 1,012 | 2.53125 | 3 | [] | no_license | const songApi = require('./api/songApi');
const calorieApi = require('./api/calorieApi');
const recipeApi = require('./api/recipeApi');
const tvApi = require('./api/tvApi');
var getSongApi = function(type) {
return async function(ctx) {
const obj = ctx.query
let res = await songApi[type](obj);
ctx.body = res.data;
}
}
var getCalorieApi = function(type) {
return async function(ctx) {
const obj = ctx.query
let res = await calorieApi[type](obj);
ctx.body = res.data;
}
}
var getRecipeApi = function(type) {
return async function(ctx) {
const obj = ctx.query
let res = await recipeApi[type](obj);
ctx.body = res.data;
}
}
var getTvApi = function() {
return async function(ctx) {
const obj = ctx.query
let res = await tvApi(obj);
ctx.body = res.data;
}
}
module.exports = {
getSongApi,
getCalorieApi,
getRecipeApi,
getTvApi
}; |
Java | UTF-8 | 884 | 2.578125 | 3 | [] | no_license | package edu.kit.tm.cm.scdm.vehicle.domain.model;
import lombok.Getter;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
@Getter
public class StaticVehicleData {
private final String vin;
private final String tag;
private final VehicleType type;
private final String model;
private final int seats;
private final int tankCapacity;
public StaticVehicleData(String vin) {
this.vin = vin;
this.tag = (RandomStringUtils.randomAlphabetic(1, 4) + "-" + RandomStringUtils.randomAlphabetic(1, 3)
+ "-" + RandomStringUtils.randomNumeric(1, 5)).toUpperCase();
this.type = VehicleType.randomType();
this.model = RandomStringUtils.randomAlphanumeric(5, 10);
this.seats = RandomUtils.nextInt(2, 8);
this.tankCapacity = RandomUtils.nextInt(40, 70);
}
}
|
Swift | UTF-8 | 1,744 | 2.703125 | 3 | [
"MIT"
] | permissive | //
// MapOfBarnetViewController.swift
// Speak Out!
//
// Created by admin on 08/06/2017.
// Copyright © 2017 Samuel Benke Calabresi. All rights reserved.
//
import UIKit
class MapOfBarnetViewController: UITableViewController {
var locations = [Location]()
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
locations = Location.loadAllVacationSpots()
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HelpfulLocationCell", for: indexPath) as! HelpfulLocationCell
let vacationSpot = locations[indexPath.row]
cell.nameLabel.text = vacationSpot.name
cell.locationNameLabel.text = vacationSpot.locationName
cell.thumbnailImageView.image = UIImage(named: vacationSpot.thumbnailName)
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let selectedCell = sender as? UITableViewCell, let selectedRowIndex = tableView.indexPath(for: selectedCell)?.row, segue.identifier == "showLocationViewController" else {
fatalError("sender is not a UITableViewCell or was not found in the tableView, or segue.identifier is incorrect")
}
let location = locations[selectedRowIndex]
let detailViewController = segue.destination as! LocationInfoViewController
detailViewController.location = location
}
}
|
Python | UTF-8 | 1,648 | 2.984375 | 3 | [] | no_license | import pytest #导入pytest
def setup_module():
"""在整个模块用例测试开始前执行"""
print("----->setup_module")
def teardown_module():
"""在整个模块用例测试结束后执行"""
print("----->teardown_module")
def setup_function():
"""在每一个外部的用例测试开始前执行"""
print("----->setup_function")
def teardown_function():
"""在每一个外部的用例测试结束后执行"""
print("----->teardown_function")
def test_a():
"""以test开头的测试函数"""
print("----->test_a")
assert 1 #断言成功
def test_b():
print('----->test_b')
assert 'e' in 'et'
class Test_hh:
def setup(self):
"""无论是否在类中,每个用例开始前都执行"""
print("----->setup")
def teardown(self):
"""无论是否在类中,每个用例开始前都执行"""
print("----->teardown")
def setup_class(self):
"""在整个类中用例测试开始前执行"""
print("----->setup_class")
def teardown_class(self):
"""在整个类中用例测试结束后执行"""
print("----->teardown_class")
def setup_method(self):
"""在每一个类中的用例测试开始前执行"""
print("----->setup_method")
def teardown_method(self):
"""类中的用例测试结束后执行"""
print("----->teardown_method")
def test_c(self):
print('----->test_c')
assert 'e' in 'et'
def test_d(self):
print('----->test_d')
assert 'e' in 'et'
if __name__ == "__main__":
pytest.main(["-s",'-v',"test_fixture.py"]) |
JavaScript | UTF-8 | 1,030 | 3.953125 | 4 | [] | no_license | function destroyer(arr) {
//use arguments to take item [1] and above and create a new array from this
var myArgs = [];
for (i=1; i<arguments.length; i++) {
myArgs.push(arguments[i]);
}
//return an array (myArgs) that takes 2nd item and after from arr; for ([1,2], 3, 4, 5), takes item 3, 4 & 5;
//make the filter function
//test each item from myArgs with the currentItem (thisItem)
function filterer(thisItem) {
for (j=0; j<myArgs.length; j++) {
if (thisItem == myArgs[j]) { //if the current item is equals to myArg
console.log("drop");
return false; //return false will drop it from the array.
}
else { // if the current item is not equals to the value of MyArg, do nothing for now. ie dont drop.
console.log("do nothing");
}
}
console.log("keep");
return true; // then return the remaining value as true.
}
var filteredNumbers = arr.filter(filterer);
console.log("return final " + filteredNumbers);
return filteredNumbers;
}
|
Python | UTF-8 | 1,995 | 4.3125 | 4 | [] | no_license | import math
first_num=50 #first number in integer
second_num=25 #second number in integer
float_a=30.25 #first number in float
float_b=25.50 #second number in float
#perform different Mathematical Computations
print("Different Mathematical Computations")
print("-------------------------------------")
print("Addition of ",first_num," and ",second_num," is:",first_num+second_num)
print("Subtraction of ",first_num," and ",second_num," is:",first_num-second_num)
print("Multiplication of ",first_num," and ",second_num," is:",first_num*second_num)
print("Remainder of ",first_num," and ",second_num," is:",first_num%second_num)
print("Exponential of ",first_num," and ",second_num," is:",first_num**second_num)
print("Floor Division of ",first_num," and ",second_num," is:",first_num//second_num)
print("Division of ",first_num," and ",second_num," is:",first_num/second_num)
print("Floor Division of ",float_a," and ",float_b," is:",float_a//float_b)
print("Division of ",float_a," and ",float_b," is:",float_a/float_b)
print()
#Operation of scientific Calculator
print("Operation of Scientific Calculator")
print("-------------------------------------")
#ceil
print("Ceil of ",float_a," is:",math.ceil(float_a))
#floor
print("Floor of ",float_a," is:",math.floor(float_a))
#fabs
print("Absolute of -42.58 is:",math.fabs(-42.58))
#exp
print("Exp of 8 is:",math.exp(8))
print('Log base 2 of',first_num, ':', math.log2(first_num))
print('Log base 10 of',first_num, ':', math.log10(first_num))
print('2 power of 5 :', math.pow(2,5))
print('Square root of 25 :', math.sqrt(25))
x = 45
print('Sin of 45 : ',math.sin(x))
print('Cos of 45 : ',math.cos(x))
print('Tan of 45 : ',math.tan(x))
print('Angle x from radians to degrees : ', math.degrees(x))
print('Angle x from degrees to radians : ', math.radians(x))
print('Pi Value : ',math.pi)
print('Constant Value : ', math.e)
print('\nNAME : ANNA HARIPRASAD')
print('REGD NO : 19X51A0503')
|
Java | UTF-8 | 282 | 2.234375 | 2 | [] | no_license | package builder.examples.email;
import java.util.Optional;
public class Sender extends CommonModule{
public Sender() {
super.moduleName = "发件人";
}
@Override
public String showInfo(String info) {
return Optional.ofNullable(info).orElse("sender : nicky@qq.com \n");
}
}
|
Markdown | UTF-8 | 914 | 3.078125 | 3 | [] | no_license | # FlipCards
A React-Native mobile app using Redux to handle data.
The `_DATA.js` file represents a fake database and methods that let you access the data.
This mobile app presents the user with a list of decks to study several topics. Each deck contains a number of cards, which can be flipped to view the answer.
The user can asses his/her knowledge based on the hidden answers and make a self-evaluation by answering a quiz, which display the results at the end of it. There's also the option to add a new deck and to add new cards to each deck.
### To install
1. Clone or download this repo
2. Install the dependencies:
```sh
$ npm install -or- yarn
```
3. Start the server:
```sh
$ npm start -or- yarn start
```
4. Open http://localhost:3000 to view it in the browser.
Or: To build the app for production to the build folder:
```sh
$ npm run build -or- yarn build
```
|
Rust | UTF-8 | 1,941 | 2.578125 | 3 | [
"CC0-1.0",
"Apache-2.0"
] | permissive | use crate::currency::{CurrencyDenom, DecCoin};
use nym_config::defaults::DenomDetails;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/Account.ts")
)]
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct Account {
pub client_address: String,
pub base_mix_denom: String,
// this should get refactored to just use a String, but for now it's fine as it reduces headache
// for others
pub display_mix_denom: CurrencyDenom,
}
impl Account {
pub fn new(client_address: String, mix_denom: DenomDetails) -> Self {
Account {
client_address,
base_mix_denom: mix_denom.base.to_owned(),
display_mix_denom: mix_denom.display.parse().unwrap_or_default(),
}
}
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/AccountWithMnemonic.ts")
)]
#[derive(Serialize, Deserialize)]
pub struct AccountWithMnemonic {
pub account: Account,
pub mnemonic: String,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/AccountEntry.ts")
)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AccountEntry {
pub id: String,
pub address: String,
}
#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
#[cfg_attr(
feature = "generate-ts",
ts(export_to = "ts-packages/types/src/types/rust/Balance.ts")
)]
#[derive(Serialize, Deserialize)]
pub struct Balance {
pub amount: DecCoin,
pub printable_balance: String,
}
impl Balance {
pub fn new(amount: DecCoin) -> Self {
Balance {
printable_balance: amount.to_string(),
amount,
}
}
}
|
Java | UTF-8 | 11,170 | 1.976563 | 2 | [] | no_license | package com.resmenu.activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.resmenu.Database.Entity.MyCart;
import com.resmenu.Database.Entity.OrderTable;
import com.resmenu.Database.Entity.UserTable;
import com.resmenu.Database.RestaurentMenuDatabase;
import com.resmenu.POJO.MenuItem;
import com.resmenu.R;
import com.resmenu.adapters.AdapterSubCat;
import com.resmenu.adapters.MyCartAdapter;
import com.resmenu.constants.ApiUrls;
import com.resmenu.customViews.CustomButton;
import com.resmenu.customViews.CustomTextView;
import com.resmenu.interfaces.DataTransfer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.resmenu.activity.MainActivity.ACCESS_TOKEN;
import static com.resmenu.activity.MainActivity.PREF_NAME;
public class MyCartActivity extends AppCompatActivity implements DataTransfer {
private RecyclerView mRecyclerViewCart;
private MyCartAdapter myCartAdapter;
private List<MyCart> myCartArrayList;
RestaurentMenuDatabase restaurentMenuDatabase;
private CustomButton mBtnPproceedtopay;
private CustomButton mBtnContinueorde;
private CustomTextView mTvNoItems, mTvTotalAMount;
private RequestQueue mRequestQueue;
private String accesstoken;
private ProgressDialog progressDialog;
private CustomTextView txtToolbarTital;
private ImageView imgSearch,imgCart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
accesstoken = prefs.getString(ACCESS_TOKEN, null);
txtToolbarTital=findViewById(R.id.toolbar_title);
txtToolbarTital.setText("My Order");
imgSearch=findViewById(R.id.ibsearch);
imgCart=findViewById(R.id.ibmycart);
imgCart.setVisibility(View.GONE);
imgSearch.setVisibility(View.GONE);
mBtnPproceedtopay = findViewById(R.id.btn_proceedtopay);
mBtnContinueorde = findViewById(R.id.btn_continueorder);
mTvTotalAMount = findViewById(R.id.tv_amount);
mTvNoItems = findViewById(R.id.tv_no_items);
mRecyclerViewCart = findViewById(R.id.recycler_virw_cart);
myCartArrayList = new ArrayList<>();
getDatabaseList();
mBtnContinueorde.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mBtnPproceedtopay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submitOrder();
}
});
}
private void getDatabaseList() {
restaurentMenuDatabase = RestaurentMenuDatabase.getInstance(this);
myCartArrayList = restaurentMenuDatabase.myCartDao().getAll();
if (myCartArrayList.size() == 0 && myCartArrayList.isEmpty()) {
mTvNoItems.setVisibility(View.VISIBLE);
mBtnPproceedtopay.setEnabled(false);
mBtnContinueorde.setEnabled(true);
} else {
myCartAdapter = new MyCartAdapter(this, myCartArrayList, restaurentMenuDatabase, this);
mRecyclerViewCart.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewCart.setAdapter(myCartAdapter);
}
}
@Override
public void setValues(double total) {
mTvTotalAMount.setText("" + total);
}
public void submitOrder() {
mRequestQueue = Volley.newRequestQueue(this);
final StringRequest request = new StringRequest(Request.Method.POST, ApiUrls.mUrlSubmitOrder, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
progressDialog.dismiss();
RestaurentMenuDatabase menuDatabase;
Log.e("sadddsasasa", "" + s.toString());
try {
JSONObject object = new JSONObject(s);
Boolean sucess_code = object.getBoolean("Status");
String msg = object.getString("Message");
if (sucess_code.equals(true)) {
copyValuesToDatabase(myCartArrayList);
AlertDialog.Builder builder = new AlertDialog.Builder(MyCartActivity.this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent=new Intent(MyCartActivity.this,TablesActivity.class);
startActivity(intent);
finish();
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Log.e("saddd", volleyError.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
params.put("Authorization", "Bearer " + accesstoken);
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
JSONObject jsonObject = new JSONObject();
/* try {
jsonObject.put("TotalAmmount", Double.parseDouble(mTvTotalAMount.getText().toString()));
jsonObject.put("tableId",Activity_WaiterLanding.tableNO);
jsonObject.put("orderBy",Activity_WaiterLanding.waiterID);
jsonObject.put("customerEmailId",Activity_WaiterLanding.email);
jsonObject.put("MobileNumber","9808982015");
jsonObject.put("CustomerName",Activity_WaiterLanding.Cu_name);
} catch (JSONException e) {
e.printStackTrace();
}*/
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < myCartArrayList.size(); i++) {
JSONObject jsonObject1 = new JSONObject();
try {
double diss = 0.0;
jsonObject1.put("ItemId", myCartArrayList.get(i).getItemID() + "");
jsonObject1.put("CategoryId", "");
jsonObject1.put("TableId", myCartArrayList.get(i).getTableNo() +"");
// jsonObject1.put("ItemName",myCartArrayList.get(i).getMenuName()+"");
jsonObject1.put("WaiterId", Activity_WaiterLanding.waiterID + "");
jsonObject1.put("Quantity", myCartArrayList.get(i).getItemQuantity() + "");
/* UserTable userTable = new UserTable();
userTable.setItemId(myCartArrayList.get(i).getId()+"");
userTable.setItemQuantity(myCartArrayList.get(i).getItemQuantity());
userTable.setMenuName(myCartArrayList.get(i).getMenuName());
userTable.setMenuPrice(myCartArrayList.get(i).getMenuPrice());
restaurentMenuDatabase.myUserTableDao().insert(userTable);*/
Log.e("zaaaaaaaaaaaaaaaaaaaaaaaaaaa",myCartArrayList.get(i).getWaiterId() + "/////////"+myCartArrayList.get(i).getItemID() + "///////"+myCartArrayList.get(i).getTableNo() +"XXXXXXXXX"+myCartArrayList.get(i).getMenuName()+"444 "+myCartArrayList.get(i).getItemQuantity() + "");
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject1);
}
try {
jsonObject.put("Items", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("xxxxxxxxxxxxxx", "" + jsonObject.toString());
String str = jsonObject.toString();
return str.getBytes();
}
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
mRequestQueue.add(request);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please Wait....");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
}
private void copyValuesToDatabase(List<MyCart> myCartArrayList) {
SharedPreferences mSharedeSharedPreferences = getSharedPreferences("restaurant", MODE_PRIVATE);
for (int i = 0; i < myCartArrayList.size(); i++) {
OrderTable userTable = new OrderTable();
userTable.setTableNo(mSharedeSharedPreferences.getInt("table_no",0));
userTable.setItemId("" + myCartArrayList.get(i).getItemID());
userTable.setItemQuantity(myCartArrayList.get(i).getItemQuantity());
userTable.setMenuName(myCartArrayList.get(i).getMenuName());
userTable.setMenuPrice(myCartArrayList.get(i).getMenuPrice());
userTable.setTableStatus(true);
userTable.setWaiterId(Activity_WaiterLanding.waiterID);
userTable.setUserName(Activity_WaiterLanding.Cu_name);
userTable.setMobileNo(Activity_WaiterLanding.mobile);
userTable.setUserEmail(Activity_WaiterLanding.email);
restaurentMenuDatabase.myOrderDao().insert(userTable);
}
restaurentMenuDatabase.myCartDao().deleteAll();
myCartArrayList.clear();
}
}
|
Java | UTF-8 | 228 | 2.125 | 2 | [] | no_license | package com.dal.entities;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class Contact {
@PrimaryKey(autoGenerate = true)
public int id;
public String name;
public String phone;
}
|
C# | UTF-8 | 1,842 | 3.0625 | 3 | [
"MIT"
] | permissive | using System.Collections.Generic;
using EcommerceDDD.Domain.SeedWork;
namespace EcommerceDDD.Domain.SharedKernel;
public class Currency : ValueObject<Currency>
{
public string Code { get; }
public string Symbol { get; }
public static Currency USDollar => new Currency("USD", "$");
public static Currency CanadianDollar => new Currency("CAD", "CDN$");
public static Currency Euro => new Currency("EUR", "€");
public Currency(string code, string symbol)
{
if (string.IsNullOrWhiteSpace(code))
throw new BusinessRuleException("Code cannot be null or whitespace.");
if (string.IsNullOrWhiteSpace(symbol))
throw new BusinessRuleException("Symbol cannot be null or whitespace.");
Code = code;
Symbol = symbol;
}
public static Currency FromCode(string code)
{
if (string.IsNullOrWhiteSpace(code))
throw new ArgumentNullException(nameof(code));
return code switch
{
"USD" => new Currency(USDollar.Code, USDollar.Symbol),
"CAD" => new Currency(CanadianDollar.Code, CanadianDollar.Symbol),
"EUR" => new Currency(Euro.Code, Euro.Symbol),
_ => throw new BusinessRuleException($"Invalid code {code}")
};
}
public static List<string> SupportedCurrencies()
{
return new List<string>() { USDollar.Code, Euro.Code, CanadianDollar.Code };
}
protected override bool EqualsCore(Currency other)
{
return Code == other.Code && Symbol == other.Symbol;
}
protected override int GetHashCodeCore()
{
unchecked
{
int hashCode = Code.GetHashCode();
hashCode = (hashCode * 397) ^ Symbol.GetHashCode();
return hashCode;
}
}
private Currency() { }
} |
Java | UTF-8 | 5,673 | 2.0625 | 2 | [] | no_license | package com.tekitsolutions.remindme.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.ReminderApp;
import java.util.List;
import androidx.recyclerview.widget.RecyclerView;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.CATEGORY_ID;
public class ReminderListAdapter extends RecyclerView.Adapter<ReminderListAdapter.MyViewHolder> {
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private String repeatText = "", repeatIntervalType, repeatType, repeatEndDate, repeatDays;
private int favorite = 0, repeatInterval, repeatCount;
private Context context;
private List<Reminder> reminderList;
private DatabaseAdapter dbAdapter;
private Reminder reminder;
public ReminderListAdapter(Context context, List<Reminder> reminderList, AdapterInterface listener, HamburgerMenuInterface menuInterface) {
this.context = context;
this.reminderList = reminderList;
this.listener = listener;
this.menuInterface = menuInterface;
this.dbAdapter = ReminderApp.getInstance().adapter;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_reminder_list, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
reminder = reminderList.get(position);
holder.tvTitle.setText(reminder.getTitle());
holder.tvTime.setText(reminder.getDueDate() + " " + reminder.getAlarmTime());
if (reminder.getCategoryId() > 0) {
General general = dbAdapter.getCategoryById(CATEGORY_ID, reminder.getCategoryId()).get(0);
holder.ivReminder.setImageResource(general.getIcon());
}
if (reminder.getRepeat() == 1) {
repeatIntervalType = reminder.getRepeatIntervalType();
repeatInterval = reminder.getRepeatInterval();
repeatType = reminder.getRepeatType();
repeatText = "Every " + repeatInterval + " " + repeatIntervalType;
if (repeatType.equals("End Date") || repeatType.equals("अंतिम तिथि")) {
repeatEndDate = reminder.getRepeatEndDate();
if (repeatEndDate != null) {
repeatText += " Until" + " " + repeatEndDate;
}
}
if (repeatIntervalType.equals("week") || repeatIntervalType.equals("सप्ताह")) {
repeatDays = reminder.getRepeatDays();
repeatText += " & " + repeatDays;
}
} else {
repeatText = "No Repeat";
}
holder.tvRepeat.setText(repeatText);
if (reminder.getFavoriteId() == 1) {
holder.toggleButton.setChecked(true);
} else {
holder.toggleButton.setChecked(false);
}
holder.toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
favorite = 1;
} else {
favorite = 0;
}
if (listener != null) {
listener.onClickFavorite(favorite, reminder.getReminderId());
}
}
});
}
@Override
public int getItemCount() {
return reminderList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tvTitle, tvTime, tvRepeat;
private ImageView ivReminder, ivNotification, hamburgerMenu;
private ToggleButton toggleButton;
public MyViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tv_title);
tvTime = itemView.findViewById(R.id.tv_time);
tvRepeat = itemView.findViewById(R.id.tv_repeat);
ivReminder = itemView.findViewById(R.id.iv_reminder);
/* ivNotification = itemView.findViewById(R.id.iv_notification);*/
toggleButton = itemView.findViewById(R.id.toggleButton);
hamburgerMenu = itemView.findViewById(R.id.hamburger_menu);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// menuInterface.onClickListItem(getAdapterPosition());
listener.onClickReminderList(getAdapterPosition());
}
});
hamburgerMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (menuInterface != null) {
menuInterface.onClickHamburger(getAdapterPosition());
}
}
});
}
}
}
|
C++ | UTF-8 | 774 | 2.828125 | 3 | [] | no_license | #ifndef REKD_ICONTAINER_H_
#define REKD_ICONTAINER_H_
#include <vector>
#include "Error.h"
namespace Rekd2D
{
namespace Core
{
class IContainer
{
public:
/// <summary>
/// Adds a container. Can only succeed.
/// </summary>
/// <param name="container">Container to be added</param>
virtual Error AddContainer(IContainer* container);
/// <summary>
/// Removes a specified container.
/// </summary>
/// <param name="container">Container to remove</param>
virtual Error RemoveContainer(IContainer* container);
/// <summary>
/// Removes a container at slot id
/// </summary>
/// <param name="id">Slot ID</param>
virtual Error RemoveContainer(int id);
protected:
std::vector<IContainer*> m_Containers;
};
}
}
#endif |
Java | UTF-8 | 2,932 | 2.390625 | 2 | [] | no_license | package com.example.demo.util;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Component
public class Timer {
Logger logger = LoggerFactory.getLogger(this.getClass());
private AtomicInteger loopCounter = new AtomicInteger();
@Autowired
private StopWatch watch;
@Value("${spring.task.name}")
private String taskNamePrefix;
@Value("${spring.task.fixedDelay1}")
private String fixedDelay1;
@Value("${spring.task.fixedDelay2}")
private String fixedDelay2;
@Value("${spring.task.fixedDelay3}")
private String fixedDelay3;
@Value("${spring.task.fixedDelay4}")
private String fixedDelay4;
@Value("${spring.task.fixedDelay5}")
private String fixedDelay5;
@PostConstruct
public void init() {
watch.start();
}
@Scheduled(fixedDelayString = "${spring.task.fixedDelay1}")
public void tick1() throws InterruptedException{
watch.stop();
logger.info(watch.prettyPrint());
String taskName = taskNamePrefix + " "+ fixedDelay1 + "-" + String.valueOf(loopCounter.getAndIncrement());
watch.start(taskName);
}
@Scheduled(fixedDelayString = "${spring.task.fixedDelay2}")
public void tick2() throws InterruptedException{
watch.stop();
logger.info(watch.prettyPrint());
String taskName = taskNamePrefix + " "+ fixedDelay2 + "-" + String.valueOf(loopCounter.getAndIncrement());
watch.start(taskName);
}
@Scheduled(fixedDelayString = "${spring.task.fixedDelay3}")
public void tick3() throws InterruptedException{
watch.stop();
logger.info(watch.prettyPrint());
String taskName = taskNamePrefix + " "+ fixedDelay3 + "-" + String.valueOf(loopCounter.getAndIncrement());
watch.start(taskName);
}
@Scheduled(fixedDelayString = "${spring.task.fixedDelay4}")
public void tick4() throws InterruptedException{
watch.stop();
logger.info(watch.prettyPrint());
String taskName = taskNamePrefix + " "+ fixedDelay4 + "-" + String.valueOf(loopCounter.getAndIncrement());
watch.start(taskName);
}
@Scheduled(fixedDelayString = "${spring.task.fixedDelay5}")
public void tick5() throws InterruptedException{
watch.stop();
logger.info(watch.prettyPrint());
String taskName = taskNamePrefix + " "+ fixedDelay5 + "-" + String.valueOf(loopCounter.getAndIncrement());
watch.start(taskName);
}
@Bean
public StopWatch watch() {
return new StopWatch();
}
} |
Java | UTF-8 | 2,439 | 2.625 | 3 | [] | no_license | package com.facebook.javatest.actions;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitActions
{
private static final Logger LOGGER = LogManager.getLogger(SearchActions.class);
private WebDriver driver;
public void setWebDriver(WebDriver driver)
{
this.driver = driver;
}
public WebElement waitForElement(By locator, int seconds)
{
try
{
LOGGER.debug("Waiting for visibility of an element: {}", locator);
WebElement element = (new WebDriverWait(driver, seconds))
.until(ExpectedConditions.visibilityOfElementLocated(locator));
LOGGER.debug("Element appeared!");
return element;
}
catch (TimeoutException e)
{
LOGGER.warn("Failed to wait for visibility of an element: {}", locator);
return null;
}
}
public boolean waitForElementDisappear(By locator, int seconds)
{
try
{
LOGGER.debug("Waiting for an element to disappear: {}", locator);
Boolean disappeared = (new WebDriverWait(driver, seconds))
.until(ExpectedConditions.invisibilityOfElementLocated(locator));
LOGGER.debug("Element disappeared!");
return disappeared;
}
catch (TimeoutException e)
{
LOGGER.debug("Failed for an element to disappear: {}, {}", locator, e.getMessage());
return false;
}
}
public List<WebElement> waitForElements(By locator, int seconds)
{
try
{
LOGGER.debug("Waiting for presence of elements: {}", locator);
List<WebElement> elements = (new WebDriverWait(driver, seconds))
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(locator));
LOGGER.debug("Elements appeared!");
return elements;
}
catch (TimeoutException e)
{
LOGGER.warn("Failed to wait for presence of elements: {}", locator);
return null;
}
}
}
|
Python | UTF-8 | 1,046 | 2.953125 | 3 | [] | no_license | '''
Created on Apr 9, 2016
@author: david
'''
#f=open("exampleB.txt")
#f=open("B-small-attempt0.in")
f=open("B-large.in")
T=int(f.readline())
P=[]
for i in range(T):
s = f.readline().strip()
P.append(s)
def rev(o):
if o=='+': return '-'
return '+'
def is_ok(s):
p='0'
nt = []
for i,c in enumerate(s):
if c>=p:
p=c
continue
return False
return True
def repair(n):
n -= 1
r = ''
while n>0 and not is_ok(str(n)):
r += '9'
n //= 10
n -= 1
if n == 0: return r
return str(n)+r
def solve(ss):
p='0'
nt = []
for i,c in enumerate(ss):
if c>=p:
p=c
nt.append(c)
continue
return repair(int(''.join(nt)))+'9'*len(ss[i:])
else:
return ss
fRes = open("res.txt", "w")
case=0
for s in P:
print(s)
case+=1
sol = solve(s)
print("Case #{}: {}".format(case,sol))
fRes.write("Case #{}: {}\n".format(case,sol))
fRes.close() |
Markdown | UTF-8 | 1,984 | 2.875 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: ''<Method1> ' и ' <метод2> ' не могут перегружать друг друга, так как они отличаются только типами возврата'
ms.date: 07/20/2015
f1_keywords:
- bc30301
- vbc30301
helpviewer_keywords:
- BC30301
ms.assetid: 5adc442b-9671-4d93-add8-42929b1a09b9
ms.openlocfilehash: 5826938a8f50c0c2d042f5aa3f5b12f523ec97f6
ms.sourcegitcommit: 3d5d33f384eeba41b2dff79d096f47ccc8d8f03d
ms.translationtype: MT
ms.contentlocale: ru-RU
ms.lasthandoff: 05/04/2018
---
# <a name="39ltmethod1gt39-and-39ltmethod2gt39-cannot-overload-each-other-because-they-differ-only-by-return-types"></a>'<Method1> ' и ' <метод2> ' не могут перегружать друг друга, так как они отличаются только типами возврата
Предпринята попытка перегрузки одного метода другим, отличающимся от первого только типом возврата. При перегрузке любые две версии метода должны отличаться списками аргументов; для различения методов вы можете использовать только списки аргументов.
**Идентификатор ошибки:** BC30301
## <a name="to-correct-this-error"></a>Исправление ошибки
- Убедитесь, что методы отличаются списками аргументов.
## <a name="see-also"></a>См. также
[Перегрузка процедур](../../visual-basic/programming-guide/language-features/procedures/procedure-overloading.md)
[Вопросы, связанные с перегрузкой процедур](../../visual-basic/programming-guide/language-features/procedures/considerations-in-overloading-procedures.md)
|
Java | UTF-8 | 1,136 | 2.96875 | 3 | [] | no_license | package io.server;
import io.executePool.TimeServerHandlerExecutePool;
import io.handler.TimeServerHandler;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 伪异步IO server
*/
public class TimeServer2 {
public static void main(String[] args) throws IOException {
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
ServerSocket server = null;
try {
server = new ServerSocket(port);
System.out.println("The time server is start in port:" + port);
Socket socket = null;
TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(
50, 10000);//创建IO线程池
while (true){
socket = server.accept();
singleExecutor.execute(new TimeServerHandler(socket));
}
} finally {
if(server != null){
System.out.println("The time server close");
server.close();
server = null;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.