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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 1,859 | 3.765625 | 4 | [] | no_license | """
The fraction ^(49)/_(98) is a curious fraction, as an inexperienced mathematician in attempting to simplify it may
incorrectly believe that ^(49)/_(98) = ^(4)/_(8), which is correct, is obtained by canceling the 9s.
We shall consider fractions like, ^(30)/_(50) = ^(3)/_(5), to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits
in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
"""
import logging
from functools import reduce
from math import gcd
from typing import Tuple
import euler
@euler.euler_problem()
def euler033(_='n/a') -> int:
numerator, denominator = \
reduce(lambda total, element: multiply_tuples(total, element),
((a, b) for a in range(10, 100) for b in range(a + 1, 100) if test_reduction(a, b)))
return denominator // gcd(numerator, denominator)
def test_reduction(a: int, b: int) -> bool:
digits_a = a // 10, a % 10
digits_b = b // 10, b % 10
# Reject "trivial" case.
if digits_a[1] == 0 or digits_b[1] == 0:
return False
# The ratio to match
ratio = a / b
for i in range(2):
for j in range(2):
# If a digit in a matches with a digit in b, compare the ratio of two other digits with the full fraction
if digits_a[i] == digits_b[j]:
match = digits_a[1 - i] / digits_b[1 - j] == ratio
if match:
logging.debug(f'Found: {(a, b)}')
return match
return False
def multiply_tuples(x: Tuple[int, int], y: Tuple[int, int]) -> Tuple:
return tuple(z[0] * z[1] for z in zip(x, y))
if __name__ == '__main__':
euler.config_log_level(logging.DEBUG)
print(euler033())
|
Java | UTF-8 | 823 | 2.125 | 2 | [] | no_license | package ba.unsa.etf.nwt.emailservice.emailservice.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.UUID;
@Entity
@Table(name = "email_subscriptions")
@Data
@NoArgsConstructor
public class EmailSubscription {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
@NotNull(message = "Email configuration can't be null")
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "config_id", nullable = false)
private EmailConfig config;
@Column(name = "task_id", nullable = false)
@NotNull(message = "Task id can't be null")
private UUID task;
}
|
C++ | UTF-8 | 831 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* demo-rtcout.cpp
*
* Version 1.1 Updated 21/04/2020
*
* compile with "g++ demo-rtcout.cpp ../ABE_ExpanderPi.cpp -Wall -Wextra -Wpedantic -Woverflow -o demo-rtcout"
* run with "./demo-rtcout"
*
* This demo shows how to enable the clock square wave output on the RTC Pi and set the frequency
*/
#include <stdint.h>
#include <stdio.h>
#include <stdexcept>
#include <time.h>
#include <unistd.h>
#include <iostream>
#include "../ABE_ExpanderPi.h"
int main(int argc, char **argv) {
using namespace ABElectronics_CPP_Libraries;
ExpanderPi expi;
// set the frequency of the output. Options are : 1 = 1Hz, 2 = 4.096KHz, 3 = 8.192KHz, 4 = 32.768KHz
expi.rtc_set_frequency(3);
// enable the square-wave output
expi.rtc_enable_output();
(void)argc;
(void)argv;
return (0);
}
|
Java | UTF-8 | 1,338 | 1.96875 | 2 | [] | no_license | package script.theme_park.newbie_tutorial;
import script.*;
import script.base_class.*;
import script.combat_engine.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import script.base_script;
import script.library.ai_lib;
import script.library.chat;
public class nervous_guy extends script.theme_park.newbie_tutorial.tutorial_base
{
public nervous_guy()
{
}
public int OnAttach(obj_id self) throws InterruptedException
{
messageTo(self, "handleSpamming", null, rand(30, 60), false);
return SCRIPT_CONTINUE;
}
public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info mi) throws InterruptedException
{
chat.chat(self, new string_id(NEWBIE_CONVO, "nervous_guy" + rand(1, 5)));
return SCRIPT_CONTINUE;
}
public int handleSpamming(obj_id self, dictionary params) throws InterruptedException
{
obj_id player = getPlayer(self);
if (hasObjVar(player, "newbie.killedPirate"))
{
return SCRIPT_CONTINUE;
}
if ((rand(1, 10) == 1) && (isInRoom(player, "r7")))
{
chat.chat(self, new string_id(NEWBIE_CONVO, "nervous_guy" + rand(1, 5)));
}
messageTo(self, "handleSpamming", null, rand(30, 60), false);
return SCRIPT_CONTINUE;
}
}
|
Swift | UTF-8 | 1,967 | 3.609375 | 4 | [] | no_license | /*
https://leetcode.com/problems/longest-palindromic-substring/description/
*/
import UIKit
class Solution {
var array : Array<Character>!
var table : Array<Bool>!
var count : Int!
func longestPalindrome(_ s: String) -> String
{
array = Array(s)
count = array.count
table = Array<Bool>(repeating: false, count: s.count * s.count)
if count <= 1
{
return s
}
if count == 2
{
if array[0] == array[1]
{
return s
}else
{
return String(array[0])
}
}
if Array(Set(array)).count == 1
{
return s
}
var start = 0
var length = 1
//1,2
for i in 0 ..< count
{
table[i*count+i] = true
if ((i < (count - 1)) && array[i] == array[i+1])
{
start = i
length = 2
table[i*count+(i+1)] = true
}
}
// >=3
for m in 3 ... count
{
for i in 0 ... count - m
{
let j = i + m - 1
if table[(i+1)*count+j-1] && (array[i] == array[j])
{
table[i*count+j] = true
if (j-i+1) > length
{
start = i
length = j - i + 1
}
}
}
}
return s.sub(from: start, length: length)
}
}
extension String
{
func sub(from:Int,length:Int) -> String
{
return String(self[self.index(self.startIndex, offsetBy: from) ..< self.index(self.startIndex, offsetBy: from+length)])
}
}
"abcd".sub(from: 1, length: 2)
let s = Solution()
let result = s.longestPalindrome("cbbd")
print(result)
|
Markdown | UTF-8 | 2,429 | 3.140625 | 3 | [
"Apache-2.0"
] | permissive | # do-core1
The `do-core1` is a simple processor architecture, mostly for educational purposes.
It aims at being a support for system programming and computer architecture fundamentals courses.
## Instruction Set Architecture
The do-core1 [Instruction Set Architecture (ISA)](https://en.wikipedia.org/wiki/Instruction_set) is a simple [Reduced Instruction Set Computer (RISC)](https://en.wikipedia.org/wiki/Reduced_instruction_set_computer)
processor architecture, with a very limited memory model and instruction and register set.
### Registers
`do-core1` exposes **8 general purpose registers**: `R0`, `R1`, `R2`, `R3`, `R4`, `R5`, `R6`, `R7`.
It also uses one Instruction Pointer (`RIP`) register and a operation flags (`RFLAGS`) register.
All `do-core1` registers are **16 bits wide**.
### Memory Model
`do-core1` can address up to **4KiB (4096 bytes) of physical memory**.
### Instruction Set
`do-core1` is a [RISC](https://en.wikipedia.org/wiki/Reduced_instruction_set_computer) architecture and executes fixed-length
instructions of 16 bits.
The `do-core1` is a 2-operand architecture, i.e. its instruction takes at most 2 operands.
`do-core1` operands are register indexes.
A `do-core1` instruction can be split into an operation code (opcode), the first operand (op0)
and the second operand (op1). The opcode is 8 bits long, and both operands are 4 bits long:
```
do-core instruction (16 bits)
Bits |15 8|7 4|3 0|
-------------------------------------------------------------
| Opcode (bits 15-8) | op0 (bits 7-4) | op1 (bits 3-0) |
-------------------------------------------------------------
```
The `do-core1` is a [load-store](https://en.wikipedia.org/wiki/Load%E2%80%93store_architecture)
architecture and supports the following instructions:
| Opcode | Instruction | Description |
|--------|--------------|----------------------------------------------------------------------|
| `0x00` | `LD Rn, Rm` | Load the value at the memory address contained in `Rm` into `Rn` |
| `0x01` | `ST Rn, Rm` | Store the value from `Rn` into the memory address contained in `Rm` |
| `0x02` | `ADD Rn, Rm` | Add the value contained in `Rm` into `Rn` (`Rn = Rn + Rm`) |
| `0x03` | `XOR Rn, Rm` | Perform a bitwise exclusive OR between `Rn` and `Rm`(`Rn = Rn ^ Rm`) |
|
SQL | UTF-8 | 10,389 | 3.171875 | 3 | [
"MIT"
] | permissive | # ************************************************************
# Sequel Pro SQL dump
# Version 4541
#
# http://www.sequelpro.com/
# https://github.com/sequelpro/sequelpro
#
# Host: 127.0.0.1 (MySQL 5.5.5-10.4.13-MariaDB)
# Database: dss
# Generation Time: 2021-02-02 04:55:34 +0000
# ************************************************************
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
# Dump of table criterias
# ------------------------------------------------------------
DROP TABLE IF EXISTS `criterias`;
CREATE TABLE `criterias` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`atribut` enum('keuntungan','biaya') COLLATE utf8mb4_unicode_ci NOT NULL,
`weight` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `criterias_code_unique` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `criterias` WRITE;
/*!40000 ALTER TABLE `criterias` DISABLE KEYS */;
INSERT INTO `criterias` (`id`, `code`, `name`, `atribut`, `weight`, `created_at`, `updated_at`)
VALUES
(1,'K1','Jumlah Invoice','keuntungan',4,NULL,'2020-11-29 06:38:08'),
(4,'K2','Lama Berlangganan','keuntungan',3,'2020-11-29 06:38:59','2020-11-29 06:38:59'),
(5,'K3','Kelancaran Pembayaran','keuntungan',3,'2020-11-29 06:41:04','2020-11-29 06:41:04'),
(6,'K4','Jenis Pelanggan','keuntungan',2,'2020-11-29 06:41:25','2020-11-29 06:41:25');
/*!40000 ALTER TABLE `criterias` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table customer_values
# ------------------------------------------------------------
DROP TABLE IF EXISTS `customer_values`;
CREATE TABLE `customer_values` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL,
`criteria_id` int(11) NOT NULL,
`value` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `customer_values` WRITE;
/*!40000 ALTER TABLE `customer_values` DISABLE KEYS */;
INSERT INTO `customer_values` (`id`, `customer_id`, `criteria_id`, `value`, `created_at`, `updated_at`)
VALUES
(1,1,1,3,NULL,'2020-11-30 07:14:26'),
(2,1,4,3,NULL,'2020-11-30 07:14:26'),
(3,1,5,4,NULL,'2020-11-30 07:14:26'),
(4,1,6,4,NULL,'2020-11-30 07:14:26'),
(5,3,1,3,NULL,NULL),
(6,3,4,2,NULL,NULL),
(7,3,5,2,NULL,NULL),
(8,3,6,4,NULL,NULL),
(9,4,1,4,NULL,NULL),
(10,4,4,3,NULL,NULL),
(11,4,5,2,NULL,NULL),
(12,4,6,4,NULL,NULL),
(13,5,1,4,NULL,NULL),
(14,5,4,3,NULL,NULL),
(15,5,5,4,NULL,NULL),
(16,5,6,4,NULL,NULL),
(17,6,1,3,NULL,NULL),
(18,6,4,3,NULL,NULL),
(19,6,5,2,NULL,NULL),
(20,6,6,4,NULL,NULL),
(25,7,1,1,'2021-01-25 14:48:52','2021-01-29 10:23:06'),
(26,7,4,1,'2021-01-25 14:48:52','2021-01-29 10:23:06'),
(27,7,5,1,'2021-01-25 14:48:52','2021-01-29 10:23:06'),
(28,7,6,1,'2021-01-25 14:48:52','2021-01-29 10:23:06'),
(29,8,1,1,'2021-01-29 10:32:06','2021-01-29 10:32:06'),
(30,8,4,3,'2021-01-29 10:32:06','2021-01-29 10:32:06'),
(31,8,5,1,'2021-01-29 10:32:06','2021-01-29 10:32:06'),
(32,8,6,1,'2021-01-29 10:32:06','2021-01-29 10:32:06');
/*!40000 ALTER TABLE `customer_values` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table customers
# ------------------------------------------------------------
DROP TABLE IF EXISTS `customers`;
CREATE TABLE `customers` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `customers_code_unique` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `customers` WRITE;
/*!40000 ALTER TABLE `customers` DISABLE KEYS */;
INSERT INTO `customers` (`id`, `code`, `name`, `address`, `phone`, `created_at`, `updated_at`)
VALUES
(1,'A1','PT ANUGRAH CITRA','Jl Rasuna Said','021333444',NULL,'2020-11-09 06:44:59'),
(3,'A2','PT ADIPERKASA','Jl Mitra Sunter Boulevard','081233444555','2020-11-15 12:14:49','2020-11-15 12:14:49'),
(4,'A3','PT INABATA','Jl Mitra Sunter Boulevard','081233444555',NULL,NULL),
(5,'A4','PT KISCO INDONESIA','Jl Mitra Sunter Boulevard','081233444555',NULL,NULL),
(6,'A5','PT SINAR BINTANG','Jl Mitra Sunter Boulevard','081233444555',NULL,NULL),
(7,'A6','PT. YAIGS','Jl. Bengawan Solo No.24 Lumajang','0341222333','2021-01-25 14:14:59','2021-01-25 14:14:59'),
(8,'A7','PT LUMAJANG JAYA','Jl. Alun Alun Barat No.1','033488778','2021-01-29 10:31:39','2021-01-29 10:31:39');
/*!40000 ALTER TABLE `customers` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table failed_jobs
# ------------------------------------------------------------
DROP TABLE IF EXISTS `failed_jobs`;
CREATE TABLE `failed_jobs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
# Dump of table migrations
# ------------------------------------------------------------
DROP TABLE IF EXISTS `migrations`;
CREATE TABLE `migrations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `migrations` WRITE;
/*!40000 ALTER TABLE `migrations` DISABLE KEYS */;
INSERT INTO `migrations` (`id`, `migration`, `batch`)
VALUES
(1,'2014_10_12_000000_create_users_table',1),
(2,'2014_10_12_100000_create_password_resets_table',1),
(3,'2019_08_19_000000_create_failed_jobs_table',1),
(4,'2020_11_08_100729_create_customers_table',2),
(6,'2020_11_15_121950_create_criterias_table',3),
(7,'2020_11_29_064517_create_customer_values_table',4),
(8,'2021_01_29_071643_create_sub_criterias_table',5);
/*!40000 ALTER TABLE `migrations` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table password_resets
# ------------------------------------------------------------
DROP TABLE IF EXISTS `password_resets`;
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
KEY `password_resets_email_index` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
# Dump of table sub_criterias
# ------------------------------------------------------------
DROP TABLE IF EXISTS `sub_criterias`;
CREATE TABLE `sub_criterias` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`criteria_id` int(11) NOT NULL,
`value` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `sub_criterias` WRITE;
/*!40000 ALTER TABLE `sub_criterias` DISABLE KEYS */;
INSERT INTO `sub_criterias` (`id`, `criteria_id`, `value`, `name`, `created_at`, `updated_at`)
VALUES
(1,1,1,'Buruk',NULL,'2021-01-29 10:34:05'),
(2,1,3,'Cukup',NULL,NULL),
(3,1,5,'Baik',NULL,NULL),
(6,4,1,'Buruk','2021-01-29 10:02:55','2021-01-29 10:02:55'),
(7,4,3,'Cukup','2021-01-29 10:03:09','2021-01-29 10:03:09'),
(8,4,5,'Baik','2021-01-29 10:03:18','2021-01-29 10:03:18'),
(9,5,1,'Buruk','2021-01-29 10:03:36','2021-01-29 10:03:36'),
(10,5,3,'Cukup','2021-01-29 10:03:45','2021-01-29 10:03:45'),
(11,5,5,'Baik','2021-01-29 10:03:55','2021-01-29 10:03:55'),
(12,6,1,'Buruk','2021-01-29 10:04:16','2021-01-29 10:04:16'),
(13,6,3,'Cukup','2021-01-29 10:04:35','2021-01-29 10:04:35'),
(14,6,5,'Baik','2021-01-29 10:04:46','2021-01-29 10:04:46');
/*!40000 ALTER TABLE `sub_criterias` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table users
# ------------------------------------------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`)
VALUES
(1,'Administrator','admin@admin.com',NULL,'$2y$10$kqlx86zmQd/IJhAXTXgVxuyIp4QPfAKQfvGhItdymz0i9Iyx2u8e2','d0dBAKTHYfhxPV6GmOYkRQ9zREecotPXFi4QpukcYBMmGRKp66ET3PeP0dw5','2020-11-05 14:32:35','2020-11-05 14:32:35');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
PHP | UTF-8 | 1,279 | 3.390625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Service;
use Exception;
class PasteWordsService
{
private string $wordMark;
public function __construct(string $wordMark)
{
$this->wordMark = $wordMark;
}
/**
* @param string $content
* @param string $word
* @param int $wordsCount
* @return string
* @throws Exception
*/
public function paste(string $content, string $word, int $wordsCount): string
{
$explodeContent = explode(' ', $content);
$wordsInContext = count($explodeContent);
for ($count = 0; $count < $wordsCount; $count++) {
$position = random_int(0, $wordsInContext);
if (array_key_exists($position, $explodeContent)) {
$explodeContent[$position] .= ' ' . $this->markWords($word);
} else {
$explodeContent[$position - 1] .= ' ' . $this->markWords($word);
}
}
return implode(' ', $explodeContent);
}
private function markWords(string $word): string
{
if ($this->wordMark === 'bold') {
return '**' . $word . '**';
}
if ($this->wordMark === 'italics') {
return '*' . $word . '*';
}
return $word;
}
}
|
Java | UTF-8 | 399 | 1.703125 | 2 | [] | no_license | package com.msg;
import com.androidyuan.frame.base.protocal.http.RequestMsg;
import com.utils.Urls;
import java.util.Map;
/**
* Created by mac on 18/3/5.
*/
public class WXPayReqMsg extends RequestMsg {
@Override
public String getUrl() {
return Urls.m_WxPayMes;
}
public WXPayReqMsg(Map<String, String> map) {
super();
params.putAll(map);
}
}
|
Markdown | UTF-8 | 1,132 | 2.546875 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Wikipedia Turns 18
share-img: "https://upload.wikimedia.org/wikipedia/commons/2/2d/Wikipedia_Day_New_York_January_2019_014.jpg"
---
On Sunday, I attended the [Wikipedia Day](https://en.wikipedia.org/wiki/Wikipedia:Meetup/NYC/Wikipedia_Day_2019) meetup sponsored by Wikimedia NYC, in Manhattan. We were celebrating in advance of Wikipedia's birthday on January 15th.
We had bagels, cake, and a full day of lightning talks and presentations.
<img src="https://raw.githubusercontent.com/martyav/martyav.github.io/master/img/Wikipedia_Day_New_York_January_2019_014.jpg" alt="A group photo of all the attendees at Wikipedia Day" width="480px" height="auto" />
Topics covered included [systemic bias on Wikipedia](https://livestream.com/internetsociety/wikidaynyc2019/videos/185803949), [redesigning the visual editor for mobile](https://livestream.com/internetsociety/wikidaynyc2019/videos/185802718), and [the Creative Commons](https://livestream.com/internetsociety/wikidaynyc2019/videos/185804027).
You can check out all the talks and slides [here](https://livestream.com/internetsociety/wikidaynyc2019).
|
Python | UTF-8 | 890 | 3 | 3 | [] | no_license | import pandas
df = pandas.read_csv('online_retail.csv', parse_dates=['InvoiceDate'])
df = df.set_index('InvoiceDate')
print(df)
empties = df.isnull().sum()
print(empties)
df['Customer ID'].fillna(0, inplace=True)
df['Customer ID'].replace({0:'Unknown'}, inplace=True)
df['Description'].fillna(1, inplace=True)
df['Description'].replace({1:"None"}, inplace=True)
newdates = pandas.to_datetime(['12-02-2010', '10-15-2010', '03-08-2010', '11-01-2010', 'Nov 05 10 05:33:26'])
print(newdates)
#online transactions in 2011
import matplotlib.pyplot as plt
df.loc['2011', 'Quantity'].plot()
plt.title('Number of online transactions in 2011')
plt.xlabel('Year 2011')
plt.ylabel('Number of transactions')
plt.show()
df.loc['2011 - 7', 'Quantity'].plot()
plt.title('Number of online transactions in July 2011')
plt.xlabel('July 2011')
plt.ylabel('Number of transactions')
plt.show()
|
PHP | UTF-8 | 3,405 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: MR.Z < zsh2088@gmail.com >
* Date: 2017/9/18
* Time: 21:07
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Api\Service\v1\ApiService;
use Illuminate\Http\Request;
class Index {
public $api = NULL;
public function __construct() {
$this->api = ApiService::instance();
$this->api->debug = FALSE;
}
public function index(Request $request , $version , $directory , $action = 'index' ) {
//取 http 头
$header = [
'timestamp' => $request->header( 'timestamp' ) ,
'signature' => $request->header( 'signature' ) ,
'device' => $request->header( 'device' ) ,
'deviceOsVersion' => $request->header( 'device-os-version' ) ,
'appVersion' => $request->header( 'app-version' ) ,
'apiVersion' => $version ,
];
//取api
$api = $this->api;
$api->logStat( $header );
$api->log( 'headerData' , $header );
// 检查时间戳
if ( ! $this->api->validTimestamp( $header['timestamp'] ) ) {
exit( json( $api->getError( 405 ) )->send() );
}
$this->api->log( 'request ' , request()->method() );
// 取参数
$params = $request->all();
$api->log( 'params' , $params );
//取时间戳
$params['timestamp'] = $header['timestamp'];
//检查签名
if ( ! $this->api->validSignature( $params , $header['signature'] ) ) {
exit( json( $api->getError( 406 ) )->send() );
}
//合并参数
$params = array_merge( $params , $header );
$this->api->log( 'params' , $params );
// 参数错误
if ( ! is_array( $params ) || empty( $params ) ) {
exit( json( $api->getError( 400 ) )->send() );
}
$result = $this->response( $version , $directory , $action , $params );
$api->log( '请求结束' );
return json( $result );
}
/**
* 响应辅助函数
*
* @param $version
* @param $directory
* @param $action
* @param $params
*
* @return array
*/
private function response( $version , $directory , $action , $params ) {
$action = ucfirst( $action );
$version = strtolower( $version );
$class = '\\App\\Http\\Controllers\\Api\\Service\\' . $version . '\\' . $directory . '\\' . $action . 'Service';
$this->api->log( 'service file' , $class );
//检查是否存在响应文件
if ( ! class_exists( $class ) ) {
return $this->api->getError( 404 );
}
//初始化响应类
$instance = $class::instance( $params );
//检查请求方式
if ( ! $this->checkRequestMethod( $instance->allowRequestMethod ) ) {
return $this->api->getError( 408 );
}
return $instance->response();
}
/**
* 检查 请求方式是否允许
*
* @param array $allowRequestMethod
*
* @return bool
*/
private function checkRequestMethod( $allowRequestMethod = [] ) {
$requestMethod = strtolower( request()->method() );
if ( empty( $allowRequestMethod ) ) {
return FALSE;
}
return isset( $allowRequestMethod[ $requestMethod ] );
}
}
|
Swift | UTF-8 | 842 | 2.671875 | 3 | [] | no_license | //
// DogResultTableViewCell.swift
// RetrieverLeague
//
// Created by Uros Zivaljevic on 12/15/17.
// Copyright © 2017 Uros Zivaljevic. All rights reserved.
//
import UIKit
class DogResultTableViewCell: UITableViewCell {
@IBOutlet weak var positionLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(with dog: Dog, index: Int) {
nameLabel.text = dog.name
positionLabel.text = "\(index + 1)."
scoreLabel.text = String(format: "%.2f%", dog.totalScore)
}
}
|
Java | UTF-8 | 1,099 | 3.15625 | 3 | [] | no_license | public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<>();
if(n<0) return list;
list.add(0);
for(int i = 0; i < n; i++){
int size = list.size();
for(int k = size - 1; k >= 0; k--){
int highBit = 1 << i;
int oringinalBit = list.get(k);
list.add(oringinalBit | highBit);
}
}
return list;
}
}
// another method
public class Solution {
public List<Integer> grayCode(int n) {
if(n <= 0)
return new LinkedList<Integer>(Arrays.asList(0));
LinkedList<Integer> result = new LinkedList<>(Arrays.asList(0, 1));
for(int i = 2; i <= n; i++){
List<Integer> newGrayCodes = new ArrayList<>(result);
while(!result.isEmpty()) {
int currentCode = result.pollLast();
currentCode += 1 << (i - 1);
newGrayCodes.add(currentCode);
}
result.addAll(newGrayCodes);
}
return result;
}
}
|
Shell | UTF-8 | 202 | 3.0625 | 3 | [] | no_license | #!/bin/bash
script_path=$(cd `dirname $0` && pwd)/bin
cat >> ~/.bashrc <<EOF
# Dev Tools
export PATH=\$PATH:$script_path
EOF
echo Now, you could run "source ~/.bashrc" to enable it in current shell. |
Python | UTF-8 | 2,099 | 3.328125 | 3 | [] | no_license | """
Utilities for dealing with timestamps, which are represented as strings in the format YYYYMMDDhhmmss.
"""
from itertools import accumulate
def hhmmss(timestamp):
"""
Returns the substring of timestamp corresponding to the hour, minutes, and seconds.
"""
return timestamp[8:]
def yyyymmdd(timestamp):
"""
Returns the substring of timestamp corresponding to the year, month, and day.
"""
return timestamp[:8]
def allocate_dates(date_counts, proportions):
"""
Allocates dates randomly into multiple lists based on proportions.
:param date_counts: a dataframe produced by Preprocessor.count_images_per_date
:param proportions: a list of the fraction of timestamps in each category, e.g., [0.6, 0.2, 0.2]
:return a list of lists of dates
"""
# Shuffle the rows
date_counts = date_counts.sample(frac=1).reset_index(drop=True)
# Add a column showing cumulative sum of counts
date_counts['cum_count'] = date_counts['count'].cumsum()
# Determine cutoffs
total_count = date_counts['count'].sum()
cutoffs = [c * total_count for c in accumulate(proportions)]
# Take subsets based on those cutoffs
paired_cutoffs = zip([0] + cutoffs[:-1], cutoffs)
subsets = [date_counts[(lower < date_counts['cum_count']) & (date_counts['cum_count'] <= upper)]['date'] for lower, upper in paired_cutoffs]
return [list(s) for s in subsets]
def timestamp_to_photo_path(dir, timestamp):
"""
Returns the full path for the photo file for timestamp in dir.
"""
return dir + '/photos/' + yyyymmdd(timestamp) + '/' + timestamp + '_photo.jpg'
def timestamp_to_tsi_mask_path(dir, timestamp):
"""
Returns the full path for the TSI mask file for timestamp in dir.
"""
return dir + '/tsi_masks/' + yyyymmdd(timestamp) + '/' + timestamp + '_tsi_mask.png'
def timestamp_to_network_mask_path(dir, timestamp):
"""
Returns the full path for the network mask file for timestamp in dir.
"""
return dir + '/network_masks/' + yyyymmdd(timestamp) + '/' + timestamp + '_network_mask.png'
|
C# | UTF-8 | 1,249 | 3.421875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Questions.IK.Tree
{
class PostOrderWithoutRecursion
{
public static void postorderTraversal(TreeNode root)
{
if (root == null)
return;
Stack<TreeNode> s = new Stack<TreeNode>();
s.Push(root);
while (s.Count != 0)
{
var curr = s.Peek();
// left node
if (curr.left == null && curr.right == null)
{
s.Pop();
Console.Write(curr.val);
if (s.Count != 0)
{
Console.Write(" ");
}
}
else
{
if (curr.right != null)
{
s.Push(curr.right);
curr.right = null;
}
if (curr.left != null)
{
s.Push(curr.left);
curr.left = null;
}
}
}
}
}
}
|
JavaScript | UTF-8 | 482 | 3.171875 | 3 | [] | no_license | #! /usr/bin/node
"use strict"
function missingnumber(l) {
let v = new Set(l);
for (let i = 0; i <= l.length; i++) {
if (!v.has(i)) {
return i;
}
}
return 0;
}
if (missingnumber([0, 1, 3]) == 2) {
process.stdout.write("Pass");
} else {
process.stdout.write("FAIL");
}
process.stdout.write(" ");
if (missingnumber([0, 1]) == 2) {
process.stdout.write("Pass");
} else {
process.stdout.write("FAIL");
}
process.stdout.write("\n");
|
C++ | UTF-8 | 376 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, a, b, c;
int ar[3];
int max;
cin >> n >> a >> b >> c;
ar[0] = a;
ar[1] = b;
ar[2] = c;
int idx = *min_element(ar, ar + 3);
if ( idx == a || idx == b || n == 1)
{
max = min(a, b)*(n - 1);
}
else max = min(a, b) + c*(n - 2);
cout << max << endl;
return 0;
}
|
Markdown | UTF-8 | 16,865 | 3.171875 | 3 | [] | no_license | # Vocabulaire informatique
## Composantes de l'ordinateur
Selon Antidote et Larousse, l'ordinateur est « une **machine automatique de traitement numérique de l'information**, qui obéit à des programmes définissant la séquence des opérations logiques et arithmétiques à effectuer ».
Sur [Wikipédia](https://fr.wikipedia.org/wiki/Ordinateur "Lien vers l'article « Ordinateur » sur Wikipédia"), la définition met plutôt l'accent sur le fait que l'ordinateur soit un **système **:
« Un ordinateur est un **système de traitement de l'information programmable** (...) qui fonctionne par la lecture séquentielle d'un ensemble d'instructions, organisées en programmes, qui lui font exécuter des opérations logiques et arithmétiques. »

**Figure** — Périphériques d'entrée et sortie de l'ordinateur
### Carte mère et microprocesseur
La **carte mère** est la composante principale d'un ordinateur. C'est sur celle-ci que se trouve le **microprocesseur**, ou unité centrale de traitement (UCT), responsable du traitement de données, des calculs et de l'exécution des programmes. La carte mère contient plusieurs **ports de connexion** qui permettent de réunir tous les **périphériques** de l'ordinateur (mémoire, disques, cartes filles, périphériques externes, etc.).

**Figure** — Carte mère d'un ordinateur **Source :** [Wikipédia](https://fr.wikipedia.org/wiki/Carte_m%C3%A8re "Lien vers l'article « Carte mère » sur Wikipédia")
### Mémoire morte
La **mémoire morte** (ROM en anglais, pour **R**ead **O**nly **M**emory) est une puce fixée sur une carte mère, contenant les **instructions de démarrage** de l'ordinateur ainsi que certaines informations essentielles à son fonctionnement. La mémoire morte est dite **non volatile** parce que son contenu ne peut être modifié (à moins de le faire à vos risques!) et elle ne s'efface pas lorsque l'ordinateur n'est plus sous tension.

**Figure** — Puce de [mémoire morte](https://fr.wikipedia.org/wiki/Mémoire_morte "Lien vers l'article « Mémoire morte » sur Wikipédia") (ROM) sur une carte
### Mémoire vive
La **mémoire vive** (RAM en anglais, pour **R**andom **A**ccess **M**emory) est la mémoire qui contient les informations en cours de traitement par le microprocesseur. La mémoire vive est dite **volatile** parce qu'elle perd tout son contenu, advenant que l'ordinateur ne soit plus sous tension. Par exemple, pendant que vous travaillez sur un rapport dans Word, un chiffrier Excel et une présentation PowerPoint, ces documents sont disponibles et traités dans la mémoire vive. Mais attention, en cas de panne de courant, vous perdrez tout votre dur travail si vous n'avez pas enregistrés vos documents sur le disque dur!

**Figure** — Deux barrettes de mémoire vive (RAM) **Source :** [Wikipédia](https://fr.wikipedia.org/wiki/Mémoire_vive "Lien vers l'article « Mémoire vive » sur Wikipédia")
### Disque dur
Un **disque dur** est un support rigide magnétique sur lequel sont enregistrées des informations de manière permanente. C'est le principal moyen de **stockage de données** sur les ordinateurs d'aujourd'hui.
Les disques durs les plus populaires et abordables fonctionnent avec des plateaux circulaires magnétiques qui tournent à des vitesses de 5 400, 7 200 et même jusqu'à 15 000 rotations par minute (RPM). Ces disques souvent appelés par le nom de leur interface, **IDE** ou **SATA**, sont munis d'une **tête** de lecture et d'écriture qui se déplace pour trouver les données sur les **pistes** et les **secteurs** du disque (voir A, dans la figure ci-dessous). Bien que les disques durs IDE/SATA soient généralement fiables et performants, toutes ces pièces mobiles les rendent vulnérables à des bris et des pannes pouvant ultimement mener à des **pertes de données**.
Les disques durs _**S**olid **S**tate **D**rive_ (SSD) sont quant à eux fabriqués avec plusieurs puces de **mémoire Flash**, semblables à celles utilisées dans les appareils photos et les téléphones (voir B, dans la figure ci-dessous). Ces disques sont plus petits et beaucoup plus rapides que les disques mécaniques. Ils sont aussi beaucoup moins vulnérable aux bris, puisqu'ils n'ont aucune pièce amovible. Dans la dernière décennie, le rapport capacité/prix de ces disques a énormément augmenté, les rendant abordables pour les **ordinateurs portables**.
Voir aussi : [Disque dur sur Comment ça marche](http://www.commentcamarche.net/contents/740-disque-dur-externe-ou-interne "Lien vers la page « Disque dur » sur le site Comment ça marche")

**Figure** — Disques durs IDE/SATA (A) et SSD (B)
### Cartes filles
Les **cartes filles** par analogie avec la carte mère de l'ordinateur, sont des cartes spécialisées qui se branchent sur cette dernière. Il existe plusieurs types de cartes filles telles que les **cartes d'accélération vidéo**, les **cartes de son** et les **cartes réseau**.

**Figure** — Exemple de carte fille : une **carte de son** spécialisée
### Écran
Depuis les années 70, l'**écran** est le périphérique de sortie principal de l'ordinateur. C'est par lui que l'utilisateur voit le résultat de ses interactions avec la machine. L'écran affiche ce que la **carte graphique** (ou carte d'accélération vidéo) lui envoie.
Il existe plusieurs types d'écrans. Les anciens **écrans cathodiques**, lourds et encombrants, sont de moins en moins utilisés, bien que l'on en trouve encore quelques-uns dans les bureaux. Les écrans à cristaux liquides (**LCD**), au **plasma** et à diodes électroluminescentes (**DEL**) les remplacent maintenant.
### Clavier
Le **clavier** est le périphérique d'entrée principal sur un ordinateur. Bien avant la souris et les interfaces graphiques, toutes les commandes devaient être passées à l'ordinateur par le clavier. Encore aujourd'hui, c'est la façon la plus rapide et la plus efficace d'entrer des données.
Le clavier contient différents types de touches :
**Alphanumériques, accents et symboles :** ces touches servent à entrer les **lettres**, les **chiffres**, les **accents** et les **symboles** à l'aide du clavier. Certains claviers ont un **pavé numérique** à la droite, idéal pour l'entrée de données comptables ou financières.
**Touches de modification :** certaines touches permettent de modifier la valeur ou le caractère entré en appuyant simultanément sur celle-ci et sur un caractère. Par exemple, la touche **Maj** transforme toutes les lettres en majuscules. La même touche **Maj** et les chiffres de 1 à 0 permettent d'entrer les symboles : !"/$%?&\*().
La touche **AltCar**, permet d'entrer d'autres symboles. Par exemple, **AltCar+2** génère un @, essentiel à l'écriture d'une adresse courriel.
Les touches **Fn**, **Ctrl**, **Windows** et **Alt** permettent de passer des commandes à l'ordinateur en les combinant aux différents chiffres et caractères pour composer des **raccourcis clavier**. Par exemple, le raccourci **Ctrl+Z** permet d'annuler la dernière action, **Ctrl+S** de sauvegarder un document, **Win+E** d'ouvrir une fenêtre de l'explorateur Windows et **Win+D** d'afficher le bureau (D pour Desktop).
**Touches de fonctions :** les claviers standards disposent de 12 touches de fonctions allant de **F1** à **F12**. Les logiciels utilisent ces touches pour donner un accès rapide à des fonctions fréquemment utilisées. Par exemple, la touche **F1** est habituellement réservée au lancement de la **fonction d'aide**.
**Les touches de déplacements :** les **flèches** permettent de déplacer le curseur à l'écran dans leurs directions respectives. Il y a aussi des touches pour avancer ou reculer d'une page (souvent représentées par **PgAv**, **PgAr** ou un symbole de flèche hachurée). Des touches **Début** et **Fin**, parfois représentées par une flèche diagonale vers le haut à gauche et une diagonale vers le bas à droite, permettent d'atteindre plus rapidement le début ou la fin d'une ligne ou d'un document.
### Souris
La **souris** a entièrement transformé la façon d'utiliser l'ordinateur. Avec l'arrivée des interfaces graphiques (avec le MacIntosh en 1984, puis Windows par la suite), l'utilisateur peut désormais passer des commandes à l'ordinateur en dirigeant un **pointeur** vers des items de **menus** et des commandes représentées par des **icônes** puis en cliquant sur le **bouton** de la souris.
Sur les souris à deux boutons, le bouton de droite permet de faire apparaitre un **menu contextuel** permettant à l'utilisateur de voir un menu avec un nombre restreint d'options, pertinentes à sa situation actuelle.
<!-- Insérer une image de souris -->
<!--
### Autres périphériques d'entrée et de sortie
-->
## Unités de mesure en informatique
Les documents et fichiers créés sur un ordinateur occupent de l'**espace mémoire** et de l'**espace disque**. Il est donc utile de connaitre les différentes unités de mesure en informatique.
### Bit
Le **bit** est la plus petite unité d'information traitée par un ordinateur. Il s'agit d'une valeur **binaire**, soit un **0** ou un **1**. Voici quelques exemples de valeurs représentées par des bits dans le système binaire :
0 : 0<br>
1 : 1<br>
2 : 10 (puisqu'il n'y plus d'unités, on passe à la 'dizaine')<br>
3 : 11 (deux plus un)<br>
4 : 100<br>
5 : 101<br>
6 : 110<br>
7 : 111<br>
8 : 1000
### Octet
L'**octet** est un groupe de huit bits avec lequel il est possible de représenter jusqu'à 256 valeurs, soit 2 exposant 8 combinaisons possibles. Les octets peuvent être utilisés pour représenter des **caractères** comme des **lettres** et des **symboles**.
### Kilo, méga, giga, tera, etc.
Les unités de mesure ci-dessous sont utilisées pour représenter l'espace qu'occupe un fichier tant en **mémoire vive** que sur un **disque dur**, ou la capacité de ces deux dispositifs de stockage.
**Kilooctet** (Ko) : mille octets
**Mégaoctet** (Mo) : mille kilooctets, soit un million d'octets
**Gigaoctet** (Go) : mille mégaoctets, soit un milliard d'octets
**Teraoctet** (To) : mille gigaoctets, soit un billion d'octets
**Petaoctet** (Po) : mille teraoctets, soit un mille billions d'octets
**Exaoctet** (Eo) : mille petaoctets, soit... beaucoup, beaucoup d'octets!
### Mégahertz et gigahertz
Lors de l'achat d'un ordinateur personnel, on voit presque toujours une valeur exprimée en **gigahertz** (GHz). Cette valeur représente la vitesse, en cycles, de l'horloge interne du microprocesseur. Il faut savoir que pour deux ordinateurs ayant la **même architecture de microprocesseur**, celui ayant la plus haute valeur en **GHz** sera le plus rapide à traiter les données.
### Achat d'un ordinateur
À partir de vos nouvelles connaissances sur les composantes de l'ordinateur et le vocabulaire informatique, êtes-vous en mesure de mieux comprendre les **spécifications d'un ordinateur** sur un site d'achat en ligne? Allez sur le site d'un commerçant populaire pour faire quelques recherches pour un **ordinateur de bureau**, ainsi qu'un **ordinateur portable**.
Prenons par exemple, la courte description suivante :
**HP - Portatif 17-AR007CA 17,3 po, 2,7 GHz AMD A12-9720P, DD 2 To, DDR4 SDRAM 12 Go, Windows 10 Famille**
**Fabriquant :** Hewlett Packard (HP)<br>
**Type d'ordinateur :** Portable (portatif)<br>
**Modèle :** 17-AR007CA<br>
**Taille de l'écran :** 17,3 pouces<br>
**Microprocesseur :** AMD A12-9720P 2,7 gigahertz (GHz)<br>
**Disque dur :** 2 teraoctets (To)<br>
**Mémoire vive :** 12 gigaoctets (Go)<br>
**Système d'exploitation :** Windows 10 Famille
## Types de logiciels
Les **logiciels**, ou **programmes**, installables sur un ordinateur peuvent être classés en quatre grandes familles : les **systèmes d'exploitation**, les **environnements de développement**, les **logiciels d'application courante** et les **utilitaires**.
### Systèmes d'exploitation
Le **système d'exploitation** est un ensemble de programmes qui dirige l'utilisation des ressources d'un ordinateur par des logiciels applicatifs ([Wikipédia](https://fr.wikipedia.org/wiki/Système_d'exploitation "Lien vers l'article « Système d'exploitation » sur Wikipédia")). Autrement dit, le système d'exploitation (vous entendrez parfois l'expression « O. S. », de l'anglais _**O**perating **S**ystem_) est le programme (ou les milliers de petits programmes) qui **fait le lien entre l'utilisateur et le matériel** de l'ordinateur (le processeur, la mémoire, les disques durs, l'écran, le clavier, la souris et tous les autres périphériques, etc.)
C'est à travers le système d'exploitation que les autres **applications** ou logiciels (comme un **traitement de texte** ou un **chiffrier électronique**) peuvent utiliser les **ressources matérielles** de l'ordinateur.
#### Windows
Le système d'exploitation **Windows**, commercialisé par la société **Microsoft**, est de loin le système d'exploitation le plus populaire sur le marché. Il est installé sur près de 90 % des ordinateurs personnels. Voici une liste de quelques-unes des versions les plus populaires de Windows :
**Windows 3.1** (première version complète et stable)<br>
**Windows 95** (premier véritable succès commercial)<br>
**Windows NT** (version « réseau » ou d'entreprise)<br>
**Windows XP** (version stable, basée sur NT)<br>
**Windows Vista** (a connu plusieurs ratés)<br>
**Windows 7** (version stable)<br>
**Windows 8** (a connu plusieurs ratés)<br>
**Windows 10**
Ce n'est pas un oubli, il n'y a pas eu de version Windows 9. La version courante actuelle est **Windows 10**, plus légère que les précédentes en espace disque et plutôt stable pour l'instant. Croisons nos doigts!
#### macOS (ou OS X)
Le système d'exploitation **macOS** (anciennement OS X) est utilisé sur les ordinateurs **Mac** (de **MacIntosh**), commercialisés par la société **Apple**. Il est construit à partir d'une version **libre** du système d'exploitation **UNIX**, très robuste et populaire au sein des universités et des grandes entreprises, et une **interface graphique** élégante et intuitive pour l'utilisateur lui a été ajoutée. Les ordinateurs d'Apple et le système d'exploitation **OS X** représentent moins de 10 % du marché des ordinateurs personnels.
#### UNIX et Linux
Le système d'exploitation [**UNIX**](https://fr.wikipedia.org/wiki/Unix "Lien vers l'article « Unix » sur Wikipédia") est développé durant les années 70. Très robuste et stable, sa principale interface est en **ligne de commande**, c'est-à-dire que l'utilisateur passe ses commandes à l'ordinateur avec le clavier. UNIX est surtout utilisé sur des **serveurs**, dans les universités et les grandes entreprises.
Au début des années 90, l'étudiant Finlandais Linus Torvalds crée le **noyau** du système d'exploitation [**Linux**](https://fr.wikipedia.org/wiki/Linux "Lien vers l'article « Linux » sur Wikipédia"). Celui-ci est **compatible** avec UNIX, en plus d'être aussi stable et robuste. Cependant, il peut être installé sur un ordinateur personnel. Linus Torvalds publie le **code source** de Linux sous licence **GPL**. Il s'agit d'une licence qui permet d'utiliser un logiciel gratuitement (et **librement**) et même de le modifier, à la condition de le redistribuer sous les mêmes conditions. Linux est donc un **logiciel libre** et gratuit, par opposition aux **logiciels propriétaires** et payants tels que Windows et macOS.
Aujourd'hui, Linux est doté d'une interface graphique aussi évoluée que celles de Windows et macOS. Des milliers de programmes et d'applications sont disponibles librement sous licence GPL, tels que les suites bureautiques [**LibreOffice**](https://fr.libreoffice.org/ "Lien vers le site de LibreOffice.org") et **OpenOffice**. Plusieurs entreprises, villes et gouvernements prennent le virage du **logiciel libre**, afin de réduire leurs coûts en licences Windows et Microsoft Office. Il est donc sage de se familiariser avec Linux, LibreOffice et d'autres logiciels libres, puisque leur popularité augmente d'année en année.
#### iOS, Android et Windows Mobile
### Logiciels de développement
### Logiciels d'application courante
### Utilitaires
[Table des matières](SUMMARY.md)
|
C++ | UTF-8 | 472 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void)
{
double pound;
double feet;
double inch;
const double FEET_TO_INCH = 12;
const double INCH_TO_METRER = 0.0254;
const double POUND_TO_KG = 2.2;
cout << "feet: ";
cin >> feet;
cout << "inch: ";
cin >> inch;
cout << "Pound: ";
cin >> pound;
double height = feet * FEET_TO_INCH + inch * INCH_TO_METRER;
pound = pound / POUND_TO_KG;
cout << "BMI: " << pound / (height * height) << endl;
return 0;
}
|
Markdown | UTF-8 | 895 | 2.703125 | 3 | [] | no_license | ## Speech Timers
We'll use the browser's [SpeechSynthesis API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis) to create a timer that speaks to us.
[View Demo](https://4jfqj.csb.app/) - [Watch a Preview](https://learn.chrisoncode.io/courses/10-react-apps-series-a/348628-09-web-speech-and-timers/992042-00-web-speech-and-timers-preview) - [Buy the Course](https://MakeReactApps.com/?utm_source=github.com&utm_medium=readme)
[](https://learn.chrisoncode.io/courses/10-react-apps-series-a/348628-09-web-speech-and-timers/992042-00-web-speech-and-timers-preview)
### React skills used in this app
- Creating timers
- Browser SpeechSyntesis API
- Nested forms
- Custom React Hooks
- React state w/ useState()
- React effects w/ useEffect()
- Parent and child components
|
Markdown | UTF-8 | 5,001 | 3 | 3 | [] | no_license | ---
uuid: d7ff8720-2d76-11ea-baaa-d5a37c33ff66
title: 性能测试工具之wrk
s: how-to-use-wrk
date: 2020-01-02 23:45:04
tags:
categories:
coauthor: zhaopanhong
---
**wrk简介**
wrk 是一个开源的C语言编写的轻量级HTTP压测工具,支持lua脚本创建复杂测试场景,可以用很少的线程压出很大的并发量。需要注意的是wrk不支持 Windows。
**环境搭建**
mac 下运行:brew install wrk
**参数说明**
使用wrk --help 查看wrk的用法
```
Usage: wrk <options> <url>
Options:
-c, --connections <N> Connections to keep open
-d, --duration <T> Duration of test
-t, --threads <N> Number of threads to use
-s, --script <S> Load Lua script file
-H, --header <H> Add header to request
--latency Print latency statistics
--timeout <T> Socket/request timeout
-v, --version Print version details
```
-c 表示为保持连接状态的连接数, -d 表示压测时间,单位可以为60s, 1m, 1h, -t 表示执行操作的线程数,-s 表示指定lua脚本执行, -H, --header 表示为每一个HTTP请求添加HTTP头,--latency 表示压测结束打印延迟统计信息,--timeout 超时时间,默认1s
一般线程数不宜过多,核数的2到4倍足够了,多了反而因为线程切换过多造成效率降低,因为wrk不是使用每个连接一个线程的模型, 而是通过异步网络io提升并发量,所以网络通信不会阻塞线程执行,这也是wrk可以用很少的线程模拟大量网路连接的原因,而现在很多性能工具并没有采用这种方式, 而是采用提高线程数来实现高并发,所以并发量一旦设的很高, 测试机自身压力就很大,测试效果反而下降。
**基础使用**
wrk -t4 -c1000 -d30s -T30s --latency http://www.baidu.com
表示用4个线程来模拟1000个并发连接,测试持续30秒,连接超时30秒,打印出请求的延迟统计信息,输出结果为:
```
Running 30s test @ http://www.baidu.com
4 threads and 1000 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 2.43s 3.78s 27.35s 88.50%
Req/Sec 67.94 31.88 191.00 65.84%
Latency Distribution
50% 996.54ms
75% 2.57s
90% 6.95s
99% 18.54s
7994 requests in 30.09s, 124.47MB read
Socket errors: connect 0, read 12, write 0, timeout 0
Requests/sec: 265.70
Transfer/sec: 4.14MB
```
结果说明:
4 threads and 1000 connections:总共是4个线程,1000个连接
latency和Req/Sec:代表单个线程的统计数据,latency代表延迟时间,Req/Sec代表单个线程每秒完成的请求数,他们都具有平均值, 标准偏差, 最大值, 正负一个标准差占比。一般我们来说我们主要关注平均值和最大值. 标准差如果太大说明样本本身离散程度比较高. 有可能系统性能波动很大.
Latency Distribution:表示响应时间分布,说明有50%的请求在996.54ms之内,90%在6.95s之内。
7994 requests in 30.09s, 124.47MB read:在30秒之内总共有7994个请求,总共124.47读取MB的数据
Socket errors: connect 0, read 12, write 0, timeout 0:总共有12个读错误.
Requests/sec和Transfer/sec:所有线程平均每秒钟完成265.70个请求,每秒钟读取4.14MB数据量
主要关注:
- Socket errors :socket 错误的数量
- Requests/sec :每秒请求数量,可以理解为TPS
- Latency: 响应时间分布
**lua脚本的编写**
实际使用中,我们可能不会像上面一样不带任何请求头及请求参数,下面以对一个post请求进行压力测试为例,编写lua脚本如下:
```
wrk.method = "POST"
wrk.headers["Accept"] = "application/json"
wrk.headers["X-Authorization"] = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NzIzMTQwMzksIm5iZiI6MTU3MjMxNDAzOSwianRpIjoiYjRjYjFlYWQtZGZmMy00NzY2LWFhNWItN2ZjOTgyNTA3MWMzIiwiaWRlbnRpdHkiOnsib3JnIjoicm9vbWlzLTIwMTcwMzAxIn0sImZyZXNoIjpmYWxzZSwidHlwZSI6ImFjY2VzcyJ9.CM6_UKkfONH2e3KcSLIzu0eMM_jWvqLZKyanDp_16vY"
wrk.body = "{\"date_ranges\":[{\"start\":\"2019-10-01\",\"end\":\"2019-11-13\"}],\"dimensions\":[{\"name\":\"day\"}],\"metrics\":[{\"name\":\"page_view\"}],\"filters\":{\"org_code\":\"shtvu\"},\"with_empty_buckets\":true}"
```
执行命令:
wrk -d 60s -c 100 -t 4 -s ./page_view.lua "http://xxx/api/v1/analytics/analytics" --latency
表示60s内用4个线程来模拟100个并发连接打印出请求的延迟统计信息,测试结果如下:
```
4 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 438.26ms 240.12ms 1.79s 70.26%
Req/Sec 58.13 19.48 130.00 67.91%
Latency Distribution
50% 394.37ms
75% 572.89ms
90% 763.88ms
99% 1.15s
13941 requests in 1.00m, 34.65MB read
Requests/sec: 231.97
Transfer/sec: 590.34KB
```
相关链接:https://github.com/wg/wrk |
C# | UTF-8 | 3,003 | 2.703125 | 3 | [] | no_license | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GCAL.Base.Scripting
{
public class GDTextStyleCollection: IEnumerable
{
public GDNode Parent { get; set; }
private List<GDTextStyle> p_list = null;
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return p_list.GetEnumerator();
}
public GDTextStyle AddStyle(GDTextStyle node)
{
SafeList();
p_list.Add(node);
return node;
}
public bool ContainsStyle(GDStyleKey key)
{
foreach (GDTextStyle style in p_list)
{
if (style.Key == key)
return true;
}
return false;
}
public object GetValue(GDStyleKey key)
{
foreach (GDTextStyle style in p_list)
{
if (style.Key == key)
return style.Value;
}
return null;
}
public GDTextStyle SetStyle(GDStyleKey prop, object value)
{
for (int i = 0; i < Count; i++)
{
if (p_list[i].Key == prop)
{
p_list[i].Value = value;
return p_list[i];
}
}
GDTextStyle ns = new GDTextStyle();
ns.Key = prop;
ns.Value = value;
return AddStyle(ns);
}
public void RemoveStyle(GDStyleKey prop)
{
for (int i = 0; i < Count; i++)
{
if (p_list[i].Key == prop)
{
p_list.RemoveAt(i);
i--;
}
}
}
public void Remove(GDTextStyle node)
{
if (p_list == null)
return;
p_list.Remove(node);
}
public void RemoveAt(int index)
{
if (p_list == null)
return;
p_list.RemoveAt(index);
}
public GDTextStyle this[int index]
{
get
{
if (p_list == null)
return null;
return p_list[index];
}
set
{
SafeList();
p_list[index] = value;
}
}
public int Count
{
get
{
if (p_list == null)
return 0;
return p_list.Count;
}
}
private void SafeList()
{
if (p_list == null)
{
p_list = new List<GDTextStyle>();
if (Parent != null)
Parent.Format = this;
}
}
}
}
|
TypeScript | UTF-8 | 1,999 | 3.0625 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | import * as Prompt from "prompt";
import * as commons from "@akashic/akashic-cli-commons";
/**
* game.jsonの初期値として与えるパラメータ。
*/
export interface BasicParameters {
/**
* ゲーム画面の幅。
*/
width: number;
/**
* ゲーム画面の高さ。
*/
height: number;
/**
* ゲームのFPS。
*/
fps: number;
}
/**
* ユーザ入力で `BasicParameters` を取得する。
*/
function promptGetBasicParameters(current: BasicParameters): Promise<BasicParameters> {
var schema = {
properties: {
width: {
type: "number",
message: "width must be a number",
default: current.width || 320
},
height: {
type: "number",
message: "height must be a number",
default: current.height || 320
},
fps: {
type: "number",
message: "fps must be a number",
default: current.fps || 30
}
}
};
return new Promise<BasicParameters>((resolve: (param: BasicParameters) => void, reject: (err: any) => void) => {
Prompt.message = "";
Prompt.delimiter = "";
Prompt.start();
Prompt.get(schema, (err: any, result: BasicParameters) => {
Prompt.stop();
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
/**
* game.json に BasicParameters の内容をセットする。
*/
function setBasicParameters(conf: commons.GameConfiguration, basicParams: BasicParameters): void {
conf.width = basicParams.width;
conf.height = basicParams.height;
conf.fps = basicParams.fps;
}
/**
* 指定した game.json の基本パラメータを更新する
*/
export function updateConfigurationFile(confPath: string, logger: commons.Logger): Promise<void> {
return commons.ConfigurationFile.read(confPath, logger)
.then(conf =>
promptGetBasicParameters({
width: conf.width,
height: conf.height,
fps: conf.fps
})
.then(basicParams => {
setBasicParameters(conf, basicParams);
return commons.ConfigurationFile.write(conf, confPath, logger);
})
);
}
|
C++ | UTF-8 | 2,036 | 2.765625 | 3 | [] | no_license | /*
ID: joaogui1
LANG: C++
TASK: snail
*/
#include <fstream>
#include <iostream>
#include <algorithm>
#define ff first
#define ss second
using namespace std;
typedef pair <int, int> pii;
int mark[1 << 7][1 << 7], ans = 0, n;
pii dz[4] = {pii(1, 0), pii(0, -1), pii(-1, 0), pii(0, 1)};
pii operator+(const pii& x, const pii& y) {
return pii(x.ff + y.ff, x.ss + y.ss);
}
//bool limit(pii p){
// return (p.ff > -1 && p.ss > -1 && p.ff < n && p.ss < n);
//}
void dfs(pii p, int d, int num){
//cout << "(" << p.ff << ", " << p.ss << ") " << d << " " << num << endl;
ans = max(ans, num);
//mark[p.ff][p.ss] = 1;
if(mark[p.ff + dz[d].ff][p.ss + dz[d].ss] == 2){
// if(p.ff == 5 && p.ss == 1){
// cout << limit(p+dz[d]) << endl;
// cout << p.ff + dz[d].ff << " " << p.ss + dz[d].ss << endl << endl;
//}
p = p + dz[(d + 1)%4];
if(mark[p.ff][p.ss] == 0){
mark[p.ff][p.ss] = 1;
dfs(p, (d + 1)%4, num + 1);
mark[p.ff][p.ss] = 0;
}
p = p + dz[(d + 3)%4]; // anula a soma anterior
p = p + dz[(d + 3)%4]; //outro giro
if(mark[p.ff][p.ss] == 0){
mark[p.ff][p.ss] = 1;
dfs(p, (d + 3)%4, num + 1);
mark[p.ff][p.ss] = 0;
}
return;
}
if(mark[p.ff + dz[d].ff][p.ss + dz[d].ss] == 0){
mark[p.ff + dz[d].ff][p.ss + dz[d].ss] = 1;
dfs(p + dz[d], d, num + 1);
mark[p.ff + dz[d].ff][p.ss + dz[d].ss] = 0;
}
return;
}
int main(){
//ios_base::sync_with_stdio(0);
ifstream fin ("snail.in");
ofstream fout ("snail.out");
int x, m;
char op;
fin >> n >> m;
for(int i = 0; i < 122; ++i)
for(int j = 0; j < 122; ++j)
mark[i][j] = 2;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
mark[i][j] = 0;
for(int i = 0; i < m; ++i){
fin >> op >> x;
mark[op -'A' + 1][x] = 2;
}
//for(int i = 0; i < n + 1; ++i)
//for(int j = 0; j < n + 1; ++j)
//cout << mark[j][i] << " \n"[j == n];
mark[1][1] = 1;
dfs(pii(1, 1), 0, 1);
dfs(pii(1, 1), 3, 1);
fout << ans << "\n";
return 0;
}
|
Markdown | UTF-8 | 4,794 | 2.5625 | 3 | [
"MIT"
] | permissive | # generator-upendodnn [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url]
> Scaffolds DNN extensions, including Modules (Webforms, SPA, and MVC), Persona Bar, Skin Object, Library, Scheduler, and Hotcakes Commerce projects (based on [generator-dnn](https://github.com/mtrutledge/generator-dnn) built by Matt Rutledge).
The 25 minute video below will walk you through everything you need to know. (right-click and open in a new tab)
[](http://www.youtube.com/watch?v=ZD1p5DDlY2E "DNN: Building Enterprise & Team Friendly Solutions & Extensions with UpendoDNN")
This solution is created and maintained by [Upendo Ventures](https://upendoventures.com) for the [DNN CMS Community](https://dnncommunity.org). Please consider [sponsoring us](https://github.com/sponsors/hismightiness) for this and the many other open-source efforts we do.
## Installation
First, install [Yeoman](http://yeoman.io) and generator-upendodnn using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)).
Warning: You may need to [add the user path to your Environmental Variables](https://superuser.com/questions/949560/how-do-i-set-system-environment-variables-in-windows-10). Here is an example from Windows 10 (you'd replace your username):
`C:\Users\yourUsername\AppData\Roaming\npm`
You also need to install the latest version of MSBuild if you don't already have it installed.
* [Build tools for Visual Studio 2017](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017)
* [Build tools for Visual Studio 2015](https://www.microsoft.com/en-us/download/details.aspx?id=48159)
* [Build tools for Visual Studio 2013](https://www.microsoft.com/en-us/download/details.aspx?id=40760)
> Note: Visual Studio 2019 should have installed MSBuild for you.
Now, simply run the following commands:
```bash
npm install -g yo
npm install -g yarn
npm install -g generator-upendodnn
```
Then generate your new project:
```bash
mkdir my-project-name
cd my-project-name
yo upendodnn
```
You're intended to first create the `Solution Structure` if you haven't yet done so in this directory.
[More verbose instructions on how to use this.](http://www.dnnsoftware.com/community-blog/cid/155574/create-a-dnn-module-in-less-than-2-minutes)
## Video Overview
* [DNN: Building Enterprise & Team Friendly Solutions & Extensions with UpendoDNN](https://www.youtube.com/watch?v=ZD1p5DDlY2E)
## First-Timers: How to Use
First, install the generator using the steps above.
1. Create and navigate to a folder where you wish to begin your new DNN-based solution. (command line example is above)
2. Run `yo upendodnn` in CMD or Powershell in that folder.
3. For the first time, you'll want to always first choose the `Solution Structure` scaffold and step through the wizard.
4. Once the solution scaffold is created, run `yo upendodnn` again to add your other desired DNN projects.
5. After you add the desired solution/project, open the original Solution scaffold in Visual Studio and add the new project to this main solution.
That's it! Now you can begin building your awesome DNN extension(s) as you see fit. Everything is now under one easy to open, run, code, build, and commit to source control solution.
Say hi to Will at [DNN Summit](https://www.dnnsummit.org/) and [DNN-Connect](https://www.dnn-connect.org/). :)
## Additional Features
By default, the namespace and extension names will be cased using Pascal-casing rules. If you'd like to override this behavior, you can add a `-f` parameter to the name.
For example, if your company name is abcCompany, the default behavior will change the name to AbcCompany. In most cases, this is the intended behavior. If you enter `abcCompany -f`, the namespace or extension name will honor the casing as-is.
## More Documentation
Want to learn more or how to build the generator code locally?
[Original Project Documentation](https://mtrutledge.github.io/generator-dnn/)
## License
MIT © 2018 [Matt Rutledge]()
MIT © 2019-2020 [Upendo Ventures, LLC](https://upendoventures.com)
[npm-image]: https://badge.fury.io/js/generator-upendodnn.svg
[npm-url]: https://npmjs.org/package/generator-upendodnn
[travis-image]: https://travis-ci.org/UpendoVentures/generator-upendodnn.svg?branch=master
[travis-url]: https://travis-ci.org/UpendoVentures/generator-upendodnn
[daviddm-image]: https://david-dm.org/UpendoVentures/generator-upendodnn.svg?theme=shields.io
[daviddm-url]: https://david-dm.org/UpendoVentures/generator-upendodnn
|
PHP | UTF-8 | 449 | 2.859375 | 3 | [] | no_license | <?php
namespace SecuredTodoList\tools;
/**
* Description of Functions
*
* @author scoupremanj
*/
class Functions {
static function formatPostInput($input){
if(!isset($_POST[$input])){
throw new FunctionsException('Oops ! Input format is not valid.');
}
return self::protectString($_POST[$input]);
}
static function protectString($string){
return strip_tags(trim($string));
}
}
|
C# | UTF-8 | 2,357 | 2.546875 | 3 | [] | no_license | using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
namespace Presentation
{
public class GameUiChanger : MonoBehaviour
{
public void SetPosition(RectTransform rectTransform, Vector2 x)
{
rectTransform.anchoredPosition = x;
}
public void SetPosition(GameObject go, Vector2 x)
{
go.GetComponent<RectTransform>().anchoredPosition = x;
}
public void SetText(Text text, string t)
{
text.text = t;
}
public void SetText(GameObject go, string t)
{
go.GetComponent<Text>().text = t;
}
public void SetColor(Image image, Color color)
{
image.color = color;
}
public void ChangePosition(RectTransform rectTransform, Vector2 x, float time)
{
rectTransform.DOAnchorPos(x, time);
}
public void ChangePosition(GameObject go, Vector2 x, float time)
{
go.GetComponent<RectTransform>().DOAnchorPos(x, time);
}
public void ChangePosition(Button button, Vector2 x, float time)
{
button.GetComponent<RectTransform>().DOAnchorPos(x, time);
}
public void ChangePosition(Text text, Vector2 x, float time)
{
text.GetComponent<RectTransform>().DOAnchorPos(x, time);
}
public void ShakePosition(GameObject go, float time)
{
go.transform.DOShakePosition(time, new Vector3(6f, 3f, 3f), 5, 20);
}
public IEnumerator CoChangeNumber(Text text, int oldNum, int newNum) {
if (newNum - oldNum < 10) {
for (var i = oldNum + 1; i <= newNum; ++i) {
text.text = i.ToString();
yield return new WaitForSeconds(0.07f);
}
}
else {
var xxx = (float) (newNum - oldNum) / 10;
float yyy = oldNum;
for (var i = 0; i < 10; ++i) {
yyy += xxx;
var zzz = (int) yyy;
text.text = zzz.ToString();
yield return new WaitForSeconds(0.07f);
}
text.text = newNum.ToString();
}
}
}
}
|
Markdown | UTF-8 | 4,401 | 3.078125 | 3 | [] | no_license | <div class="chapnav">
<span class="prev">Previous: [inference](./som-22.5.html)</span><span
class="next">Next: [causes and clauses](./som-22.7.html)</span><span
class="contents">[Contents](index.html)</span>
<div class="titlebar">
Society of Mind
===============
</div>
</div>
*22.6* expression
-----------------
Language lets us treat our thoughts as though they were much like
ordinary things. Suppose you meet someone who is trying to solve a
problem. You ask what's happening. *I'm thinking,* you are told. *I can
see that,* you say, *but what are you thinking about?* *Well, I was
looking for a way to solve this problem, and I think I've just found
one.* We speak as though ideas resemble building-blocks that one can
find and grasp!
Why do we *thing-ify* our thoughts? One reason is that this enables us
to reapply the wonderful machines our brains contain for understanding
worldly things. Another thing it does is help us organize our
expeditions in the mental world, much as we find our ways through space.
Consider how the strategies we use to *find* ideas resemble the
strategies we use for finding real things: Look in the places they used
to be or where they're usually found — but don't keep looking again and
again in the same place. Indeed, for many centuries our memory-training
arts have been dominated by two techniques. One is based on similarities
of sounds, exploiting the capacities of our language-agencies to make
connections between words. The other method is based on imagining the
items we want to remember as placed in some familiar space, such as a
road or room one knows particularly well. This way, we can apply our
thing-location skills to keeping track of our ideas.
Our ability to treat ideas as though they were objects goes together
with our abilities to reuse our brain-machinery over and over again.
Whenever an agency becomes overburdened by a large and complicated
structure, we may be able to treat that structure as a simple, single
unit by thing-ifying — or, as we usually say, *conceptualizing* — it.
Then, once we replace a larger structure by representing it with a
compact symbol-sign, that overloaded agency may be able to continue its
work. This way, we can build grand structures of ideas — much as we can
build great towers from smaller parts.
I suspect that, as they're represented in the mind, there's little
difference between a physical object and an idea. Worldly things are
useful to us because they are *substantial* — that is, because their
properties are relatively permanent. Now we don't usually think of ideas
as substantial, because they don't have the usual properties of worldly
things — such as color, shape, and weight. Yet *good ideas* must also
have substantiality, albeit of a different sort:
No conception or idea could have much use unless it could remain
unchanged — and stay in some kind of mental *place* — for long enough
for us to find it when we need it. Nor could we ever achieve a goal
unless it could persist for long enough. In short, no mind can work
without some stable states or memories.
This may sound as though I'm speaking metaphorically, since a mental
*place* is not exactly like a worldly place. But then, when you think of
a place you know, that thought itself is not a worldly place, but only a
linkage of memories and processes inside your mind. This wonderful
capacity — to think about thoughts as though they were things — is also
what enables us to contemplate the products of our thoughts. Without
that ability to reflect, we would have no general intelligence — however
large our repertoire of special-purpose skills might grow. Of course
this same capacity enables us to think such empty thoughts as *This
statement is about itself,* which is true but useless, or *This
statement is not about itself,* which is false and useless, or *This
statement is false,* which is downright paradoxical. Yet the benefit of
being able to conceptualize is surely worth the risk that we may
sometimes be nonsensical.
<div class="footer">
[](http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US)\
\
[{#book}
](http://www.amazon.com/gp/product/0671657135?ie=UTF8&camp=1789&creativeASIN=0671657135&linkCode=xm2&tag=marvinminsky)
</div>
|
PHP | UTF-8 | 273 | 3 | 3 | [] | no_license | <?php
header("Content-type:text/html; charset=utf-8");
require_once "Felidae.php";
class Cat extends Felidae{
private $race="猫";
function pet(){
echo "我是{$this->race}"."<hr/>";
}
}
$cat = new Cat();
$cat->pet();
$cat->tree();
$cat->predator(); |
Markdown | UTF-8 | 919 | 3.15625 | 3 | [
"MIT"
] | permissive | # _My Portfolio_
#### _This website showcases who I am and what I can do, June 30, 2017_
#### By _**Paul Guevarra**_
## Description
_This is a website I created to showcase my self and my abilities in computer programming. It gives a description of my background, hobbies, and a sample list of projects I have created.It is my hope that when this is further improved upon that it will become a useful tool in obtaining employment_
## Setup/Installation Requirements
* _Open web browser_
* _Enter website address "https://github.com/paulguevarra/my-portfolio"_
* _Browse through content_
## Known Bugs
_Navigation bar links are not working properly._
## Support and contact details
_For further issues or questions, please contact: Paul Guevarra email:p.a.guevarra@gmail.com_
## Technologies Used
_This program was built using HTML and CSS_
### License
_This Software is licensed under the MIT License_
Copyright (c) 2017 **Paul Guevarra**
|
Java | UTF-8 | 10,682 | 2.0625 | 2 | [] | no_license | package com.dinhduc_company.stockmarket;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import DataBase.DBStock;
/**
* A simple {@link Fragment} subclass.
* Use the {@link FragmentPortfolioManagement#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentPortfolioManagement extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
DBStock dbStock;
ArrayList<Portfolio> portfolios = new ArrayList<>();
PortfolioAdapter adapter;
ListView listPortfolio;
int position = 0;
String name;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentPortfolioManagement.
*/
// TODO: Rename and change types and number of parameters
public static FragmentPortfolioManagement newInstance(String param1, String param2) {
FragmentPortfolioManagement fragment = new FragmentPortfolioManagement();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentPortfolioManagement() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.fragment_portfolio_management, container, false);
dbStock = new DBStock(getActivity(), Login.username);
dbStock.open();
Cursor c = dbStock.getAllPortfolioManaging();
if (c.moveToFirst()) {
do {
Portfolio portfolio = new Portfolio();
portfolio.setId(c.getInt(c.getColumnIndex(DBStock.KEY_ROWID)));
portfolio.setPortfolioName(c.getString(c.getColumnIndex(DBStock.KEY_PORTFOLIO_NAME)));
portfolio.setInterest(c.getDouble(c.getColumnIndex(DBStock.KEY_INTEREST)));
portfolios.add(portfolio);
} while (c.moveToNext());
}
listPortfolio = (ListView) rootView.findViewById(R.id.listPortfolio);
adapter = new PortfolioAdapter(getActivity(), R.layout.portfolio, portfolios);
listPortfolio.setAdapter(adapter);
listPortfolio.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Portfolio portfolio = portfolios.get(i);
String portfolioName = portfolio.getPortfolioName();
Intent intent = new Intent(getActivity(), PortfolioActivity.class);
intent.putExtra("portfolio_name", portfolioName);
startActivity(intent);
}
});
registerForContextMenu(listPortfolio);
return rootView;
}
public void showAddDialog() {
final Dialog dialog = new Dialog(getActivity());
dialog.setTitle("Add Portfolio");
dialog.setContentView(R.layout.add_portfolio);
final EditText editText = (EditText) dialog.findViewById(R.id.addPortfolioET);
Button yesBtn = (Button) dialog.findViewById(R.id.yesBtn);
Button noBtn = (Button) dialog.findViewById(R.id.noBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String portfolioName = editText.getText().toString();
if (portfolioName.replace(" ","").equals("")){
Toast.makeText(getActivity(),"Portfolio Name must have letters", Toast.LENGTH_SHORT).show();
}else {
if (dbStock.getPortfolioManaging(portfolioName.trim()).moveToFirst()) {
Toast.makeText(getActivity(), "Can't add an exist Portfolio", Toast.LENGTH_SHORT).show();
} else {
dbStock.createPortfolioTable(portfolioName.trim());
dbStock.insertPortfolioManaging(portfolioName, 0, 0, 0);
Cursor c = dbStock.getAllPortfolioManaging();
c.moveToLast();
Portfolio portfolio = new Portfolio();
portfolio.setId(c.getInt(c.getColumnIndex(DBStock.KEY_ROWID)));
portfolio.setPortfolioName(portfolioName);
portfolio.setInterest(0);
portfolios.add(portfolio);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Add Portfolio Successfully", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.cancel();
}
});
dialog.show();
}
public void showEditDialog() {
final Dialog dialog = new Dialog(getActivity());
dialog.setTitle("Edit Portfolio");
dialog.setContentView(R.layout.add_portfolio);
final EditText editText = (EditText) dialog.findViewById(R.id.addPortfolioET);
final Portfolio portfolio = portfolios.get(position);
final String oldName = portfolio.getPortfolioName();
editText.setText(oldName);
Button yesBtn = (Button) dialog.findViewById(R.id.yesBtn);
Button noBtn = (Button) dialog.findViewById(R.id.noBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String portfolioName = editText.getText().toString();
if (dbStock.getPortfolioManaging(portfolioName.trim()).moveToFirst()) {
Toast.makeText(getActivity(), "Can't change to an exist Portfolio", Toast.LENGTH_SHORT).show();
} else {
dbStock.updatePortfolioManaging(portfolio.getId(), portfolioName);
portfolio.setPortfolioName(portfolioName);
adapter.notifyDataSetChanged();
dbStock.renameTable(oldName, portfolioName);
dbStock.updateHistory(portfolioName, oldName);
Toast.makeText(getActivity(), "Edit Portfolio Successfully", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.cancel();
}
});
dialog.show();
}
public void showDeleteDialog() {
final Portfolio portfolio = portfolios.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete");
builder.setMessage("Do you want to delete this portfolio");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String portfolioName = portfolio.getPortfolioName();
dbStock.deleteHistory(portfolioName);
dbStock.dropPortfolioTable(portfolioName);
dbStock.deletePortfolioManaging(portfolio.getId());
portfolios.remove(portfolio);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Delete Portfolio Successfully", Toast.LENGTH_SHORT).show();
dialogInterface.cancel();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.portfolio, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addPortfolio) {
showAddDialog();
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.portfolio_context_menu, menu);
if (v.getId() == R.id.listPortfolio) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
position = info.position;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.edit_portfolio) {
showEditDialog();
} else {
showDeleteDialog();
}
return super.onContextItemSelected(item);
}
@Override
public void onDestroyView() {
super.onDestroyView();
dbStock.close();
}
}
|
Markdown | UTF-8 | 5,631 | 3.8125 | 4 | [] | no_license | ---
ID: 748
post_title: '{Quickly} Fix Master Boot Record (MBR) on Windows 10!!'
author: Eva
post_excerpt: ""
layout: post
permalink: >
https://windowscrazy.com/748-quickly-fix-master-boot-record-mbr-on-windows-10/
published: true
post_date: 2020-05-29 08:54:22
---
<ul class="toc">
<li><a href="#1">How to fix MBR on Windows 10?</a></li>
<li><a href="#2">Verdict</a></li>
</ul>
<strong><strong><strong><span class="dcap">F</span><strong>ix Master Boot Record (MBR) on Windows 10</strong>:</strong></strong></strong> It enables your PC to find and identify the location of the operating system to allow Windows 10 to boot. MBR is also referred to as the <strong>master partition table or partition sector.</strong>
In this tutorial, we will describe the piece of information to<strong> fix Master Boot Record (MBR) on Windows 10</strong> using simple steps.
<h2 id="1">How to fix MBR on Windows 10?</h2>
Here, the below steps are used to<strong> fix MBR on Windows 10</strong>. Simply, follow the steps.
<ul>
<li>Firstly, you have to <a href="https://windowscrazy.com/317-can-windows-xp-be-upgraded-to-windows-10/"><strong>create a USB bootable media to install Windows 10.</strong></a></li>
<li>Then change your device<strong> BIOS settings</strong> to start from the bootable media.</li>
</ul>
<strong>Note:</strong> In this process, it usually requires to press one of the function keys F1, F2, F3, F10, or F12, ESC, or Delete key.
<ul>
<li>After that, start your PC with the bootable media and click the <strong>Next</strong> button in the Windows 10 Setup.</li>
<li>On the bottom left side, you have to press the <strong>Repair your computer </strong>tab.</li>
</ul>
[caption id="attachment_780" align="aligncenter" width="759"]<img class="wp-image-780 size-full" src="https://windowscrazy.com/wp-content/uploads/2020/05/Screenshot_5-7.png" alt="Repair your computer" width="759" height="555" /> Repair your computer[/caption]
<ul>
<li>Then click <strong>Troubleshoot </strong>and in that select the <strong>Advanced options.</strong></li>
<li>In the Advanced options select the <strong>Command Prompt.</strong></li>
</ul>
[caption id="attachment_782" align="aligncenter" width="1099"]<img class="wp-image-782 size-full" src="https://windowscrazy.com/wp-content/uploads/2020/05/Screenshot_6-6.png" alt="Advanced settings" width="1099" height="518" /> Advanced settings[/caption]
<ul>
<li>Type <strong>Bootrec.exe</strong> in the command prompt to launch this tool to repair the Master Boot Record on your Windows 10 PC.</li>
<li>Bootrec.exe tool supports a number of options depending on your situation.</li>
<li>To repair Master Boot Record corruption problems or need to clean the code from the MBR, you have to use the <strong>FixMbr</strong> option because this command will not overwrite the existing partition table in the hard drive.</li>
<li>Simply<strong>, copy and paste</strong> the below command in the command prompt.</li>
</ul>
<pre><code>Bootrec /fixMbr</code></pre>
<ul>
<li>When you installed an early version of the operating system alongside another more recent version or when the boot sector was replaced with another non-standard code, the boot sector is damaged you have to use the <strong>FixBoot</strong> option.</li>
<li><strong>Type</strong> the following command.</li>
</ul>
<pre><code>Bootrec /fixBoot</code></pre>
<ul>
<li>When the Boot Manager menu doesn’t list all the operating systems installed on your device, then you have to use the option of <strong>ScanOS. </strong>Copy and paste the below command.</li>
</ul>
<pre><code>Bootrec /ScanOS</code></pre>
<ul>
<li>The <strong>RebuildBcd</strong> option is used when you don’t have another option and you must rebuild the BCD (Boot Configuration Data) store.</li>
<li><strong>Copy and paste</strong> the below-mentioned command in your command prompt window.</li>
</ul>
<pre><code>Bootrec /RebuildBcd</code></pre>
[caption id="attachment_749" align="aligncenter" width="1242"]<img class="wp-image-749 size-full" src="https://windowscrazy.com/wp-content/uploads/2020/05/Screenshot_1-8.png" alt="Commands" width="1242" height="642" /> Commands[/caption]
<ul>
<li>If you are trying to troubleshoot a <strong>Bootmgr Is Missing</strong> error and rebuilding the BCD store doesn’t fix the problem.</li>
<li>Then, you can use the following commands to export and erase the BCD store and using the <strong>RebuildBcd</strong> command again to try getting Windows 10 to boot.</li>
<li><strong>Copy and paste</strong> the following commands in the command prompt and press <strong>Enter.</strong></li>
</ul>
<pre><code>BCDedit /export C:\BCD_Backup
C:
CD boot
Attrib BCD -s -h -r
Ren C:\boot\bcd bcd.old
Bootrec /RebuildBcd</code></pre>
<ul>
<li>To confirm adding Windows 10 to the list of the bootable operating systems on your computer <strong>press Y.</strong></li>
</ul>
[caption id="attachment_750" align="aligncenter" width="1235"]<img class="wp-image-750 size-full" src="https://windowscrazy.com/wp-content/uploads/2020/05/Screenshot_2-8.png" alt="Commands" width="1235" height="645" /> Commands[/caption]
<ul>
<li>Finally, close the<strong> command prompt</strong> window.</li>
<li>After completion of the above steps, you have to <strong>reboot your computer.</strong></li>
<li>Then, you should now be able to load <strong>Windows 10</strong> again.</li>
</ul>
<h2 id="2">Verdict:</h2>
In the above article, we have illustrated the easy steps <strong>to fix MBR on Windows 10. </strong>If you found this article helpful? Don’t forget to share your comments in the below section. |
Java | UTF-8 | 4,572 | 2.046875 | 2 | [] | no_license | package stationservice.controler;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import stationservice.UIcomponate.BonsDetailsCell;
import stationservice.UIcomponate.ProduitDetailsCell;
import stationservice.entity.Decbons;
import stationservice.entity.Declaration;
import stationservice.entity.DeclarationProduit;
import stationservice.report.ReportFacture;
import stationservice.ressource.Methode;
public class DeclarationDetialsController implements Initializable {
@FXML
private Text id;
@FXML
private JFXTextField date;
@FXML
private JFXTextField decl_total;
@FXML
private JFXTextField decl_bons;
@FXML
private JFXTextField pompiste_nom;
@FXML
private JFXTextField pompiste_prenom;
@FXML
private JFXListView<ProduitDetailsCell> liste_produit;
@FXML
private JFXListView<BonsDetailsCell> liste_Bons;
@FXML
private JFXButton print;
@FXML
private JFXButton close;
@FXML
private JFXTextField debut;
@FXML
private JFXTextField fin;
@FXML
private JFXTextField billets;
@FXML
private JFXTextField avance;
private Declaration declaration;
@FXML
private JFXTextField date1;
@FXML
private JFXTextField debut1;
@FXML
private JFXTextField fin1;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
public void init(Declaration declaration) {
this.declaration = declaration;
set_information();
}
private void set_information() {
id.setText(Integer.toString(this.declaration.getId()));
date.setText(Methode.dateFormat(this.declaration.getDate()));
debut.setText(this.declaration.getDebut_job());
fin.setText(this.declaration.getFin_job());
date1.setText(Methode.dateFormat(this.declaration.getDate2()));
debut1.setText(this.declaration.getDebut_job2());
fin1.setText(this.declaration.getFin_job2());
decl_total.setText(Double.toString(declaration.getTotal()));
decl_bons.setText(Double.toString(declaration.getBons()));
billets.setText(""+this.declaration.getBillets());
avance.setText(""+declaration.getAvance());
pompiste_nom.setText(declaration.getIdpompiste().getNom());
pompiste_prenom.setText(declaration.getIdpompiste().getPrenom());
bons_liste();
produit_liste();
}
private void produit_liste() {
List<ProduitDetailsCell> list = new ArrayList<>();
for (DeclarationProduit declarationProduit : this.declaration.getDeclarationProduits()) {
ProduitDetailsCell cell = new ProduitDetailsCell(declarationProduit);
list.add(cell);
}
ObservableList<ProduitDetailsCell> myObservableList = FXCollections.observableList(list);
this.liste_produit.setItems(myObservableList);
this.liste_produit.setExpanded(true);
}
private void bons_liste() {
List<BonsDetailsCell> list = new ArrayList<>();
for (Decbons decbons : this.declaration.getDecbonsCollection()) {
BonsDetailsCell cell = new BonsDetailsCell(decbons);
list.add(cell);
}
ObservableList<BonsDetailsCell> myObservableList = FXCollections.observableList(list);
this.liste_Bons.setItems(myObservableList);
this.liste_Bons.setExpanded(true);
}
@FXML
private void print_action(ActionEvent event) {
ReportFacture reportFacture = new ReportFacture(declaration);
reportFacture.create_report();
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("etatup.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
System.err.println(ex);
}
}
}
@FXML
private void close_action(ActionEvent event) {
Stage stage = Methode.getStage(event);
stage.close();
}
}
|
PHP | UTF-8 | 579 | 3.046875 | 3 | [] | no_license | <?php
function post_request ($url, $data) {
/* POSTデータをquery用に整形 */
$data = http_build_query($data, "", "&");
/* headerを設定 */
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($data)
);
/* ぜんぶHTTPリクエスト用に組み合わせる */
$context = array("http" => array(
"method" => "POST",
"header" => implode("\r\n", $header),
"content" => $data
));
/* リクエストを実行して結果を返す */
return file_get_contents($url, false, stream_context_create($context));
}
?> |
Markdown | UTF-8 | 6,631 | 2.96875 | 3 | [] | no_license | ---
layout: post
title: Getting people to sign up from Joshua Porter at Web 2.0 Expo
wordpress_id: 47
wordpress_url: http://www.varud.com/?p=52
date: 2008-09-17 12:04:46.000000000 -04:00
---
Joshua Porter (bokaro.com) gave a great presentation this morning at the Web 2.0 Expo in New York today.
Getting people to sign up on a site or app is difficult - there's a natural 'friction' that keeps people from signing up.
Real sign-up numbers from real companies:
<ul>
<li>8.0%</li>
<li>6.76%</li>
<li>4.7%</li>
<li>16.0%</li>
<li>0.003%</li>
</ul>
Usability is of course one of the main factors affecting the sign-up rate. Â Gmail for instance has correct tab order, they end with "@gmail.com" so it's clear to the user what they're creating with a login name. Â Checking availability is also possible without a full submit. Â The password box tells the restrictions (6 characters) and check immediately. Â Security questions can be a real burden for people who are new to sign ups. Â Other questions like location also deter. Â "Letters are case sensitive" means very little to the common user. Â In other words, Gmail does a great job but not a perfect job.
Boston.com forces one to fill out virtually all fields. Â They do tell you what to do right on the page but the number of unnecessary data points becomes a burden - people don't want to put in what their job is just to get the paper. Â Instead of saying to the user, "We are using this info to customize the paper/ads for you", they say nothing. Â Even after all that, they want the user to sign up for newsletters and then for information from advertisers.
Improving the use of forms involves
<ul>
<li>Â Reduce number of fields</li>
<li>Pre-submit username check</li>
<li>Password security right on the password input box</li>
<li>Following conventions like having 'sign-in' on top right of screen</li>
<li>Have a clear privacy policy</li>
</ul>
<div>But ... These issues are not 'sign-up'. Â Sign up is in the mind. Â Apathy is what drives people to not sign up. Â Are they motivated enough by what you're offering to care about filling out the form? Â "If ease of use were the only requirement, we would all be riding tricycles" (couldn't read the author).</div>
<div></div>
<div>"Eager Sellers, Stony Buyers" is a great article on buying. Â If you are a current user of software, you typically overvalue it by a factor of 3. Â If you are software maker trying to sell software by a factor of 3. Â They actually think it's 3 times better than it actually is. Â This is called the 9x effect whereby somebody who is already bought-in will experience a 9x overvaluation of the product when the seller is presenting it to them.</div>
<div></div>
<div>What we're asking of the user with sign-up isn't just to fill out a form, it's also asking somebody to change their behavior, give up accepted practices, jump into the unknown, trade known quantity for an unknown, and a "shift from potential to kinetic energy". Â </div>
<div></div>
<div>Motivation trumps the ease of use of the form. </div>
<div></div>
<div>We need to analyze what happens before the form.</div>
<div>
<ul>
<li>Product research</li>
<li>Considering the alternative</li>
<li>Learning about the product</li>
<li>Comparison with existing products</li>
<li>The user's current situation</li>
</ul>
<div>When you are the product creator or represent that company, you know much more about the product than the user who you're attempting to convince. Â We need to design for 3 visitor types.</div>
<div>
<ul>
<li>I know I want to sign up (get out of the way).</li>
<li>I want to make sure this is for me (Reiterate basic value proposition).</li>
<li>I'm skeptical (convince with more thorough information).</li>
</ul>
<div>Geni.com  has a great signup by having the user put the father's name and mother's name right into the signup form (they're a geneaology site).  Immediately, this explains the purpose of the information and gets buy-in.</div>
<div></div>
<div>Netvibes.com is another site. Â If you haven't been there before (no cookie), you'll get an intro right off the bat. Â If you've been cookied (but not a member), you'll get more of the end information without the intro information. Â Another concept is that once you've created a page, there is a sign that says, "Don't lose your page, become a member now." Â That is superior to just 'Sign Up'.</div>
<div></div>
<div>Instant engagement is the first and most important thing. Â Show them what they're getting, don't describe or tell them.</div>
<div></div>
<div>Netflix is another great example. Â The main page tells you everything right there. Â "Sign up today and try Netflix for FREE!" with a whole bunch of other follow-up content and the form is right there. Â In addtion, at the bottom, they give 4 tiles with the entire process of dealing with the company: Pick movies, get movies in mail, no late fees, drop movie in the mailbox. Â This simple explanation is critical. Â The copy uses words like "your" to show that this is how you deal with the system and "we" so it's clear who is responsible for what. Â If none of that works, in the lower right there's a phone number and chat link for people that want more information.</div>
<div></div>
<div>Tripit also has a 3 pane design showing how it works. Â They don't even ask for people to sign up off the bat. Â Just have people forward the emails from Orbitz and that's how they start the sign-in process. Â Movies and screencasts are also available - another great design element for this issue.</div>
<div></div>
</div>
</div>
<div>I won't go into the details about these sites that are poorly done: BillMyClients.com. Â In a redesign, it's even worse. Â The login is right on the home page but people who don't know how to get a login or what the site does don't know what to do. Â The login is best put in the top right. Â Also, the copy is really miserable - "Get a free email ..." Â The visual hierarchy is completely wrong. Â Blinksale.com, which does essentially the same thing has a much better sign up page (I think I'll have to check them out for invoicing). Â </div>
<div></div>
<div>Social Influence is the final piece of the sign up process. Â Basecamp does a great job with tons of testimonials from large brand publications and tastemakers and 'normal' people. Â Jaiku and Twitter make it real obvious that the whole world is on this, now, using it. Â Get press coverage on the web site. Â </div>
<div></div>
<div>In fine, motivation is everything.</div>
|
Java | UTF-8 | 1,747 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package net.n2oapp.framework.config.metadata.validation.standard.regions;
import net.n2oapp.framework.api.metadata.Source;
import net.n2oapp.framework.api.metadata.aware.SourceClassAware;
import net.n2oapp.framework.api.metadata.compile.SourceProcessor;
import net.n2oapp.framework.api.metadata.global.view.region.N2oScrollspyRegion;
import net.n2oapp.framework.api.metadata.validate.SourceValidator;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
public class ScrollspyValidator implements SourceValidator<N2oScrollspyRegion>, SourceClassAware {
@Override
public Class<? extends Source> getSourceClass() {
return N2oScrollspyRegion.class;
}
@Override
public void validate(N2oScrollspyRegion source, SourceProcessor p) {
N2oScrollspyRegion.AbstractMenuItem[] items = source.getMenu();
p.checkIdsUnique(collectItems(items), String.format("Меню '%s' встречается более одного раза в <scrollspy> '%s'", "%s", source.getId()));
}
private List<N2oScrollspyRegion.AbstractMenuItem> collectItems(N2oScrollspyRegion.AbstractMenuItem[] items) {
List<N2oScrollspyRegion.AbstractMenuItem> itemsList = new ArrayList<>();
Arrays.stream(items).forEach(item -> {
itemsList.add(item);
if (item instanceof N2oScrollspyRegion.GroupItem)
itemsList.addAll(collectItems(((N2oScrollspyRegion.GroupItem) item).getGroup()));
if (item instanceof N2oScrollspyRegion.SubMenuItem)
itemsList.addAll(collectItems(((N2oScrollspyRegion.SubMenuItem) item).getSubMenu()));
});
return itemsList;
}
}
|
C++ | UTF-8 | 765 | 2.71875 | 3 | [
"Zlib"
] | permissive | // Project: libv.math, File: src/libv/math/distance/intersect.hpp
#pragma once
// libv
#include <libv/math/vec.hpp>
namespace libv {
// -------------------------------------------------------------------------------------------------
[[nodiscard]] constexpr inline libv::vec3f intersect_ray_plane(libv::vec3f ray_point, libv::vec3f ray_dir, libv::vec3f plane_point, libv::vec3f plane_normal) noexcept {
const auto diff = ray_point - plane_point;
const auto prod1 = libv::vec::dot(diff, plane_normal);
const auto prod2 = libv::vec::dot(ray_dir, plane_normal);
const auto prod3 = prod1 / prod2;
return ray_point - ray_dir * prod3;
}
// -------------------------------------------------------------------------------------------------
} // namespace libv
|
C# | UTF-8 | 1,685 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | // This file is part of the CycloneDX Tool for .NET
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright (c) Steve Springett. All Rights Reserved.
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Xml;
namespace CycloneDX.Extensions
{
public static class HttpClientExtensions
{
/*
* Simple extension method to retrieve an XmlDocument from a URL.
*/
public static async Task<XmlDocument> GetXmlAsync(this HttpClient httpClient, string url)
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response;
response = await httpClient.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
var contentAsString = await response.Content.ReadAsStringAsync();
var doc = new XmlDocument();
doc.LoadXml(contentAsString);
return doc;
}
}
} |
Python | UTF-8 | 6,593 | 2.53125 | 3 | [] | no_license | '''
Simple tcp multi-threading server to play file to clients
Copyright: All Rights Reserved.
Created by Alex Petukhov. Jun, 2015
'''
import sys
import traceback
import socketserver, time, datetime
import struct
import logging
import authentification_pb2
import task1_heterogeneous_poisson_pb2
import pymongo
import dbutils
#These constants must be changed for our real database!!!!!!!!!!!!!!!!!!!!
BASE_NAME = 'dbtest'
TASK_NAME = 'task1' # Name of task MongoDB collection
TASK_FILES = 'task_files'
def now():
return time.ctime(time.time())
class ClientHandler(socketserver.BaseRequestHandler):
def send_msg(self, data):
#Send message to client. Message length placed in first two bytes
#send message length
self.request.send(struct.pack(">H", len(data)))
#send message
self.request.send(data)
def check_login(self, login_req):
self.login = login_req.login
self.password = login_req.enc_password
reply = dbutils.checkAuth(self.login, self.password, self.server.database)
return reply
def auth_reply(self, authReply):
#send to client information about connection status
reply = authentification_pb2.LoginReply()
reply.connection_status = authReply
data = reply.SerializeToString()
self.send_msg(data)
def play_file(self):
speed = dbutils.getSpeed(file_name, self.server.database, TASK_FILES)
if speed < 0: #something goes wrong in database, we cannot find correct speed for the file
return
event = task1_heterogeneous_poisson_pb2.Event()
alen = len(file_data)
#turn socket to non-blocking status
self.request.setblocking(False)
fin = False
reply_len = 0
delta = 0
self.signals = []
time_start = time.time()
time_start = datetime.datetime.utcfromtimestamp(time_start)
post = {'name':self.student_name, 'login':self.login, 'date_time':time_start}
self.server.database[TASK_NAME].insert(post)
time0 = time.time()
for i in range(alen):
t = time.time()
adj_data = file_data[i] / speed
while time0 + adj_data > t:
delta = time0 + adj_data - t
time.sleep(delta)
t = time.time()
event.server_timestamp_usec = int(time.time()*1000000)
print(event.server_timestamp_usec-1000000000000000)
if i < alen-1:
event.stream_end = False
else:
event.stream_end = True
data = event.SerializeToString()
self.send_msg(data)
reply_len = 0
try:
reply_len = struct.unpack(">H", self.request.recv(2))[0]
except Exception:
pass
if not reply_len: continue
else:
fin = True
self.process_reply(reply_len)
#turn socket to blocking status again
self.request.setblocking(True)
self.server.database[TASK_NAME].update(post, {'$set': {'time0':datetime.datetime.utcfromtimestamp(time0), 'end_time':datetime.datetime.utcfromtimestamp(time.time())}}, upsert=False)
if fin:
for signal in self.signals:
(tt, s) = signal
self.server.database[TASK_NAME].update(post, {"$push":{"signals":{'date_time':tt, 'signal':s}}})
pass
def process_reply(self, len):
#Process result from client
t = datetime.datetime.utcfromtimestamp(time.time())
reply_data = self.request.recv(len)
signal = task1_heterogeneous_poisson_pb2.Signal()
signal.ParseFromString(reply_data)
self.signals.append((t, signal.signal))
pass
#Further processing needed
def handle(self):
print(self.client_address, now())
try:
#read message length
alen = struct.unpack(">H", self.request.recv(2))[0]
if not alen: return
#read auth message
data = self.request.recv(alen)
if not data or len(data) < alen: return
#parse auth message
login_req = authentification_pb2.LoginRequest()
login_req.ParseFromString(data)
#check login, pass etc
authReply, self.student_name = self.check_login(login_req)
#reply to client for auth message
self.auth_reply(authReply)
if authReply != authentification_pb2.LoginReply.OK:
logger.info(u'Auth request from ' + self.student_name + ' FAILED')
return
logger.info(u'Auth request from ' + self.student_name + ' OK')
#start to play file
self.play_file()
logger.info(u'Data has been streamed successfully for ' + self.student_name)
self.request.close()
except ConnectionAbortedError:
logger.error(u'Connection was interrupted by ' + self.student_name + u' from ' + str(self.client_address[0]) + ':' + str(self.client_address[1]))
except Exception:
logger.exception('')
#traceback.print_exc()
self.request.close()
try:
log_file_name = './log/' + datetime.datetime.now().strftime(TASK_NAME + '_%H_%M_%d_%m_%Y.log')
logger = logging.getLogger('server')
hdlr = logging.FileHandler(log_file_name)
formatter = logging.Formatter('%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
#logging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG)
logger.info( u'Starting...' )
db = pymongo.MongoClient("localhost", 27017)
file_name = db[BASE_NAME][TASK_FILES].find_one({'task':TASK_NAME})['file']
file_data = []
file_data = [int(d)/1000000.0 for d in open(file_name)]
except Exception:
traceback.print_exc()
sys.exit(0)
try:
host = ''
port = 50007
addr = (host, port)
server = socketserver.ThreadingTCPServer(addr, ClientHandler)
server.database = db[BASE_NAME]
server.serve_forever()
except Exception:
traceback.print_exc()
sys.exit(0) |
C# | UTF-8 | 394 | 3.1875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.AnimalsTest
{
class Dog : Animal, ISound
{
public Dog(string name, int age, string sex)
: base(name, age, sex)
{
}
public void MakeSound()
{
Console.WriteLine("Bow");
}
}
}
|
C# | UTF-8 | 316 | 2.84375 | 3 | [] | no_license | using System;
namespace Composite
//Leaf
{
public class Manager : Employee
{
public Manager(string name) : base(name)
{
}
public override void ShowEmployeeDetails()
{
Console.Write("Manager = ");
base.ShowEmployeeDetails();
}
}
} |
C | UTF-8 | 1,687 | 3 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_reset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: trouger <trouger@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/15 11:02:19 by trouger #+# #+# */
/* Updated: 2021/09/20 14:42:03 by trouger ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/push_swap.h"
t_stack ft_reset_chunk_index(t_stack stack, t_list *chunk, char next_stack)
{
int index;
t_list *temp;
index = chunk->chunk_index;
temp = chunk;
chunk = ft_reset2(stack, chunk, next_stack, index);
chunk = temp;
if (next_stack == 'a')
stack.a = chunk;
else if (next_stack == 'b')
stack.b = chunk;
return (stack);
}
t_list *ft_reset2(t_stack stack, t_list *chunk, char next_stack, int index)
{
while (chunk != NULL && chunk->chunk_index == index)
{
if (next_stack == 'a')
{
if (stack.b)
chunk->chunk_index = stack.b->chunk_index;
else
chunk->chunk_index = 0;
}
if (next_stack == 'b')
{
if (stack.a)
chunk->chunk_index = stack.a->chunk_index;
else
chunk->chunk_index = 0;
}
chunk = chunk->next;
}
return (chunk);
}
|
TypeScript | UTF-8 | 6,808 | 3.15625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | class SubjectInfo {
constructor(public subject: ISubject,
public index: number,
public count: number,
public isAchievement: boolean,
public isAbility: boolean) {
if (subject) {
subject.count = count;
}
}
}
class SubjectPerformanceScore {
name: string;
lowCount: number;
lowPct: number;
avgCount: number;
avgPct: number;
highCount: number;
highPct: number;
constructor(public subject: SubjectType, public testNumber: number, public testDate: Date) {
const subjectHelper = new SubjectHelper();
this.name = subjectHelper.description(subject);
}
}
class SubjectHelper {
description(subjectType: SubjectType): string {
switch (subjectType) {
case SubjectType.Genab:
return "General Reasoning";
case SubjectType.Verbal:
return "Verbal Reasoning";
case SubjectType.NonVerbal:
return "Non Verbal Reasoning";
case SubjectType.Ravens:
return "Ravens SPM";
case SubjectType.MathReasoning:
return "Maths Reasoning";
case SubjectType.MathPerformance:
return "Maths Performance";
case SubjectType.Reading:
return "Reading Comprehension";
case SubjectType.Writing:
return "Writing Expression";
case SubjectType.Spelling:
return "Spelling";
case SubjectType.MathQr:
return "Math Reasoning";
default:
return "Unknown test subject";
}
}
}
class SubjectSummary {
subject: ISubject;
stanineAverage: number;
rawScoreAverage: number;
naplanAverage: number;
constructor(subject: ISubject) {
this.subject = subject;
}
set = (students: Array<Student>) => {
var scores = Enumerable.From(students).Select(s => this.subject.getScore(s)).ToArray();
this.stanineAverage = Enumerable.From(scores).Average(s => s.stanine);
this.rawScoreAverage = Enumerable.From(scores).Average(s => this.subject.getRawScore(s));
if (this.subject.hasNaplanScore) {
this.naplanAverage = Enumerable.From(scores).Average(s => s.naplan);
}
}
}
enum SubjectType {
Unknown = 0,
Genab = 1,
Verbal = 2,
NonVerbal = 3,
MathReasoning = 4,
MathPerformance = 5,
Reading = 6,
Writing = 7,
Spelling = 8,
Ravens = 9,
MathQr = 10
}
interface ISubject {
name: string;
count: number;
subject: SubjectType;
summary: SubjectSummary;
getScore(student: Student): Score;
getRawScore(score: Score): number;
isTested: boolean;
hasRangeScore: boolean;
hasNaplanScore: boolean;
hasCorrelationScore: boolean;
}
class GenabSubject implements ISubject{
getScore = (student: Student): Score => {
return student.genab;
}
getRawScore = (score: Score): number => {
return score.range.mid;
}
name = "General Reasoning";
count = 0;
subject = SubjectType.Genab;
hasRangeScore = true;
hasNaplanScore = false;
hasCorrelationScore = true;
isTested = false;
summary = new SubjectSummary(this);
}
class VerbalSubject implements ISubject {
getScore = (student: Student): Score => {
return student.verbal;
}
name = "Verbal Reasoning";
count = 0;
subject = SubjectType.Verbal;
getRawScore = (score: Score): number => {
return score.range.mid;
}
hasRangeScore = true;
hasNaplanScore = false;
hasCorrelationScore = true;
isTested = false;
summary = new SubjectSummary(this);
}
class NonVerbalSubject implements ISubject {
getScore = (student: Student): Score => {
return student.nonverbal;
}
name = "Non Verbal Reasoning";
count = 0;
getRawScore = (score: Score): number => {
return score.range.mid;
}
subject = SubjectType.NonVerbal;
hasRangeScore = true;
hasNaplanScore = false;
hasCorrelationScore = true;
isTested = false;
summary = new SubjectSummary(this);
}
class MathReasoningSubject implements ISubject {
getScore = (student: Student): Score => {
return student.mathReasoning;
}
getRawScore = (score: Score): number => {
return score.range.mid;
}
name = "Maths Reasoning";
count = 0;
subject = SubjectType.MathReasoning;
hasRangeScore = false;
hasNaplanScore = true;
hasCorrelationScore = true;
isTested = false;
summary = new SubjectSummary(this);
}
class MathPerformanceSubject implements ISubject {
getScore = (student: Student): Score => {
return student.mathPerformance;
}
name = "Maths Performance";
count = 0;
getRawScore = (score: Score): number => {
return score.raw;
}
subject = SubjectType.MathPerformance;
hasRangeScore = false;
hasNaplanScore = true;
hasCorrelationScore: boolean = false;
isTested = false;
summary = new SubjectSummary(this);
}
class ReadingSubject implements ISubject {
getScore = (student: Student): Score => {
return student.reading;
}
name = "Reading Comprehension";
count = 0;
getRawScore = (score: Score): number => {
return score.raw;
}
subject = SubjectType.Reading;
hasRangeScore = false;
hasNaplanScore = true;
hasCorrelationScore = false;
isTested = false;
summary = new SubjectSummary(this);
}
class SpellingSubject implements ISubject {
getScore = (student: Student): Score => {
return student.spelling;
}
name = "Spelling";
count = 0;
getRawScore = (score: Score): number => {
return score.raw;
}
subject = SubjectType.Spelling;
hasRangeScore = false;
hasNaplanScore = false;
hasCorrelationScore = false;
isTested = false;
summary = new SubjectSummary(this);
}
class WritingSubject implements ISubject {
getScore = (student: Student): Score => {
return student.writing;
}
name = "Writing Comprehension";
count = 0;
getRawScore = (score: Score): number => {
return score.raw;
}
subject = SubjectType.Writing;
hasRangeScore = false;
hasNaplanScore = true;
hasCorrelationScore = false;
isTested = false;
summary = new SubjectSummary(this);
}
class RavenSubject implements ISubject {
getScore = (student: Student): Score => {
return student.raven;
}
name = "Ravens SPM";
getRawScore = (score: Score): number => {
return score.raw;
}
count = 0;
subject = SubjectType.Ravens;
hasRangeScore = false;
hasNaplanScore = true;
hasCorrelationScore = false;
isTested = false;
summary = new SubjectSummary(this);
} |
JavaScript | UTF-8 | 1,551 | 2.546875 | 3 | [] | no_license | const colors = [
{'rgb': '250,250,160', 'srm': 1},
{'rgb': '250,250,105', 'srm': 2},
{'rgb': '245,246,50', 'srm': 3},
{'rgb': '235,228,47', 'srm': 4},
{'rgb': '225,208,50', 'srm': 5},
{'rgb': '215,188,52', 'srm': 6},
{'rgb': '205,168,55', 'srm': 7},
{'rgb': '198,148,56', 'srm': 8},
{'rgb': '193,136,56', 'srm': 9},
{'rgb': '192,129,56', 'srm': 10},
{'rgb': '192,121,56', 'srm': 11},
{'rgb': '192,114,56', 'srm': 12},
{'rgb': '190,106,56', 'srm': 13},
{'rgb': '180,99,56', 'srm': 14},
{'rgb': '167,91,54', 'srm': 15},
{'rgb': '152,84,51', 'srm': 16},
{'rgb': '138,75,48', 'srm': 17},
{'rgb': '124,68,41', 'srm': 18},
{'rgb': '109,60,34', 'srm': 19},
{'rgb': '95,53,23', 'srm': 20},
{'rgb': '81,45,11', 'srm': 21},
{'rgb': '67,38,12', 'srm': 22},
{'rgb': '52,30,17', 'srm': 23},
{'rgb': '38,23,22', 'srm': 24},
{'rgb': '33,19,18', 'srm': 25},
{'rgb': '28,16,15', 'srm': 26},
{'rgb': '23,13,12', 'srm': 27},
{'rgb': '18,9,8', 'srm': 28},
{'rgb': '13,6,5', 'srm': 29},
{'rgb': '8,3,2', 'srm': 30},
{'rgb': '6,2,1', 'srm': 31}
];
const isNumber = val => (val === '')
? false
: !isNaN(val);
const getHexForEbc = (ebc) => {
if (!isNumber(ebc)) {
return null;
}
var input = ebc / 2;
if (input < 1) {
input = 1;
} else if (input > 31) {
input = 31;
}
input = Math.round(input);
return colors.find(color => color.srm === input).rgb;
}
export default getHexForEbc; |
Java | UTF-8 | 3,927 | 2.171875 | 2 | [
"BSD-3-Clause"
] | permissive | package com.applozic.mobicomkit.uiwidgets.attachmentview;
import android.media.MediaRecorder;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.applozic.mobicomkit.uiwidgets.R;
import com.applozic.mobicomkit.uiwidgets.conversation.ConversationUIService;
import com.applozic.mobicommons.commons.core.utils.Utils;
import java.io.File;
/**
* Created by Rahul-PC on 17-07-2017.
*/
public class ApplozicAudioRecordManager implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {
FragmentActivity context;
String audioFileName, timeStamp;
ConversationUIService conversationUIService;
private MediaRecorder audioRecorder;
private String outputFile = null;
private boolean isRecordring;
public ApplozicAudioRecordManager(FragmentActivity context) {
this.conversationUIService = new ConversationUIService(context);
this.context = context;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public void setAudioFileName(String audioFileName) {
this.audioFileName = audioFileName;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public void recordAudio() {
try {
if (isRecordring) {
ApplozicAudioRecordManager.this.stopRecording();
} else {
if (audioRecorder == null) {
prepareMediaRecorder();
}
audioRecorder.prepare();
audioRecorder.start();
isRecordring = true;
}
} catch (Exception e){
e.printStackTrace();
}
}
public void cancelAudio() {
if (isRecordring) {
ApplozicAudioRecordManager.this.stopRecording();
}
if(outputFile != null){
File file = new File(outputFile);
if (file != null && file.exists()) {
Utils.printLog(context, "AudioFRG:", "File deleted...");
file.delete();
}
}
}
public void sendAudio() {
//IF recording is running stoped it ...
if (isRecordring) {
stopRecording();
}
//FILE CHECK ....
if(outputFile != null){
if (!(new File(outputFile).exists())) {
Toast.makeText(context, R.string.tap_on_mic_button_to_record_audio, Toast.LENGTH_SHORT).show();
return;
}
conversationUIService.sendAudioMessage(outputFile);
}
}
public void stopRecording() {
if (audioRecorder != null) {
try {
audioRecorder.stop();
} catch (RuntimeException stopException) {
Utils.printLog(context, "AudioMsgFrag:", "Runtime exception.This is thrown intentionally if stop is called just after start");
} finally {
audioRecorder.release();
audioRecorder = null;
isRecordring = false;
}
}
}
public MediaRecorder prepareMediaRecorder() {
audioRecorder = new MediaRecorder();
audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
audioRecorder.setAudioEncodingBitRate(256);
audioRecorder.setAudioChannels(1);
audioRecorder.setAudioSamplingRate(44100);
audioRecorder.setOutputFile(outputFile);
audioRecorder.setOnInfoListener(this);
audioRecorder.setOnErrorListener(this);
return audioRecorder;
}
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
}
@Override
public void onError(MediaRecorder mr, int what, int extra) {
}
} |
Java | UTF-8 | 7,893 | 1.742188 | 2 | [] | no_license | package com.judian.goule.store.adapter;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.ccy.ccyui.listener.NoDoubleClickListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.judian.goule.store.R;
import com.judian.goule.store.activity.LoginActivity;
import com.judian.goule.store.activity.youxuan.TetrisActivity;
import com.judian.goule.store.bean.GoodListBean;
import com.judian.goule.store.bean.SystemMsgData;
import com.judian.goule.store.bean.UserInfo;
import com.judian.goule.store.db.liteorm.UserInfoDBUtil;
import com.judian.goule.store.utils.FrescoUtils;
import com.judian.goule.store.utils.Token;
import java.util.List;
/**
* 新写的适配器
*/
public class MyAdapterUtil {
/**
* 我的收藏里面的适配器
*
* @param activity
* @return
*/
public static com.chad.library.adapter.base.BaseQuickAdapter<GoodListBean.ResultBean, BaseViewHolder> getCollectData(final Activity activity, final MyAdapterUtil.CollectLintener lintener) {
return new BaseQuickAdapter<GoodListBean.ResultBean, BaseViewHolder>(R.layout.item_collect) {
@Override
protected void convert(final BaseViewHolder viewHolder, final GoodListBean.ResultBean hotBean, int p) {
// Log.i("tiancao", hotBean.toString());
viewHolder.setTextView(R.id.pic, "¥ " + hotBean.getPrice());
UserInfo userInfo = UserInfoDBUtil.get(mContext);
if (userInfo.getResult().getLevel().equals("6")) {
viewHolder.getView(R.id.shengji_zhuan_pic).setVisibility(View.GONE);
viewHolder.setTextView(R.id.jifen, "分享赚" + hotBean.getFanli_money_fenxiang());
} else {
viewHolder.setTextView(R.id.shengji_zhuan_pic, "升级赚" + hotBean.getFanli_money_shengji());
viewHolder.setTextView(R.id.jifen, "分享赚" + hotBean.getFanli_money_fenxiang());
}
switch (hotBean.getUser_type()) {
case "0":
viewHolder.setTextView(R.id.taobao_and_tianmao, "淘宝价¥" + hotBean.getReserve_price());
break;
case "1":
viewHolder.setTextView(R.id.taobao_and_tianmao, "天猫价¥" + hotBean.getReserve_price());
break;
}
FrescoUtils.load(hotBean.getPict_url(), (SimpleDraweeView) viewHolder.getView(R.id.face), 2, 20, R.drawable.ioc_errer_image_z_y);
viewHolder.setText(R.id.title, hotBean.getTitle());
viewHolder.setText(R.id.quan, "领券减" + hotBean.getCoupon_money());
if (hotBean.isSel()) {
viewHolder.setImageResource(R.id.sel, R.mipmap.proxy_tag);
} else {
viewHolder.setImageResource(R.id.sel, R.mipmap.proxy_tag_de);
}
viewHolder.getView(R.id.my_collect_item_box_rl).setOnClickListener(new NoDoubleClickListener() {
@Override
protected void onNoDoubleClick(View v) {
if (hotBean.isSel()) {
lintener.remov(hotBean);
hotBean.setSel(false);
viewHolder.setImageResource(R.id.sel, R.mipmap.proxy_tag_de);
} else {
lintener.add(hotBean);
hotBean.setSel(true);
viewHolder.setImageResource(R.id.sel, R.mipmap.proxy_tag);
}
}
});
//点击进商品详情
viewHolder.getView(R.id.my_collect_image_view_rl).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TetrisActivity.openMain(activity, hotBean, 6);
}
});
viewHolder.getView(R.id.my_collect_info_view_ll).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TetrisActivity.openMain(activity, hotBean, 6);
}
});
}
};
}
public interface CollectLintener {
void add(GoodListBean.ResultBean hotBean);
void remov(GoodListBean.ResultBean hotBean);
void share(GoodListBean.ResultBean hotBean);
}
/**
* 系统消息
*
* @param activity
* @return
*/
public static BaseQuickAdapter<SystemMsgData.ResultBean, BaseViewHolder> getSystemMessages(final Activity activity, List<SystemMsgData.ResultBean> list) {
return new BaseQuickAdapter<SystemMsgData.ResultBean, BaseViewHolder>(R.layout.item_system_messages, list) {
@Override
protected void convert(BaseViewHolder viewHolder, final SystemMsgData.ResultBean hotBean, int position) {
viewHolder.setTextView(R.id.item_system_messages_title_tv, hotBean.getMsg_title());
viewHolder.setTextView(R.id.item_system_messages_con_tv, hotBean.getMsg_content());
viewHolder.setTextView(R.id.item_system_messages_time_tv, hotBean.getSend_time());
}
};
}
/**
* 免单商品列表页
*
* @param activity
* @return
*/
public static BaseQuickAdapter<GoodListBean.ResultBean, BaseViewHolder> getMIandanListData(final Activity activity, List<GoodListBean.ResultBean> list) {
return new BaseQuickAdapter<GoodListBean.ResultBean, BaseViewHolder>(R.layout.item_miandan, list) {
@Override
protected void convert(BaseViewHolder viewHolder, final GoodListBean.ResultBean hotBean, int position) {
viewHolder.setTextView(R.id.pic, hotBean.getCoupon_price());
FrescoUtils.load(hotBean.getPict_url(), (SimpleDraweeView) viewHolder.getView(R.id.face), 2, 20);
viewHolder.setTextView(R.id.title, " " + hotBean.getTitle());
switch (hotBean.getUser_type()) {
case "0":
viewHolder.setImageResource(R.id.type, R.mipmap.tb21);
break;
case "1":
viewHolder.setImageResource(R.id.type, R.mipmap.tm);
break;
}
if (hotBean.getCoupon_money().equals("")) {
viewHolder.setTextView(R.id.quan, "券 ¥ 0.0");
} else {
viewHolder.setTextView(R.id.quan, "券 ¥ " + hotBean.getCoupon_money());
}
// (ProgressBar) viewHolder.getView(R.id.item_miandan_pb);
viewHolder.setTextView(R.id.item_miandan_numm, "共" + hotBean.getGoods_num() + "件");
viewHolder.setTextView(R.id.item_miandan_shengyu, "剩余" + hotBean.getGoods_num_surplus() + "件");
viewHolder.getView(R.id.all).setOnClickListener(new NoDoubleClickListener() {
@Override
protected void onNoDoubleClick(View v) {
if (Token.isLogin()) {
TetrisActivity.openMain(activity, hotBean, 6);
} else {
activity.startActivity(new Intent(activity, LoginActivity.class));
}
}
});
}
};
}
}
|
SQL | UTF-8 | 599 | 3.25 | 3 | [] | no_license | CREATE TABLE departments (
dept_no VARCHAR,
dept_name VARCHAR(30)
);
CREATE TABLE dept_emp (
emp_no INT,
dept_no VARCHAR(10),
from_date DATE,
to_date DATE
);
CREATE TABLE dept_manager (
dept_no VARCHAR(10),
emp_no INT,
from_date DATE,
to_date DATE
);
CREATE TABLE employees (
emp_no INT,
birth_date DATE,
first_name VARCHAR(50),
last_name VARCHAR(50),
gender VARCHAR,
hire_date DATE
);
CREATE TABLE salaries (
emp_no INT,
salary INT,
from_date DATE,
to_date DATE
);
CREATE TABLE title (
emp_no INT,
title VARCHAR(50),
from_date DATE,
to_date DATE
); |
Java | UTF-8 | 493 | 3.25 | 3 | [] | no_license | package com.company;
public abstract class Animal {
public String name;
public int run;
public int swim;
private final int MaxRunLength = 0;
private final int MaxSwimLength = 0;
abstract void swim(int length);
abstract void run(int length);
public static void animalCount() {
int countCat = Cat.catCount+Dog.dogCount;
System.out.println("Созданное количество животных: "+countCat);
}
}
|
Java | UTF-8 | 862 | 3.46875 | 3 | [] | no_license | package OptionalTaskOne;
import java.util.Arrays;
import java.util.Scanner;
public class OptionalOneLength {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String numbers = scanner.nextLine();
String[] array = numbers.split(" ");
System.out.println(Arrays.toString(array));
shortNumber(array);
}
static void shortNumber(String[] array) {
int max = array[0].length();
int min = array[0].length();
for (int i = 0; i < array.length; i++) {
if (array[i].length() > max) {
max = array[i].length();
}
if (array[i].length() < min) {
min = array[i].length();
}
}
System.out.println("min = " + min);
System.out.println("max = " + max);
}
}
|
Python | UTF-8 | 1,095 | 2.5625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
# import scrapy
#
#
# class MyspiderItem(scrapy.Item):
# # define the fields for your item here like:
# # name = scr
#
# user_agent 设置ua
# coucurrent requests 设置并发请求的
# download-delay i下载延迟,默认无延迟
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/clicks.htm')
click_btn = driver.find_element_by_xpath('//input[@value="click me"]')
doubleclick_btn = driver.find_element_by_xpath('//input[@value="dbl click me"]')
rightclick_btn = driver.find_element_by_xpath('//input[@value="right click me"]')
ActionChains(driver).click(click_btn).double_click(doubleclick_btn).context_click(rightclick_btn).perform()
print (driver.find_element_by_name('t2').get_attribute('value'))
sleep(2)
driver.quit() |
Java | UTF-8 | 5,352 | 2.40625 | 2 | [] | no_license | package com.stw.kanban.client.view;
import java.util.ArrayList;
import junit.framework.Assert;
import org.junit.Test;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Widget;
import com.stw.kanban.client.AbstractKanbanBoardGwtTestCase;
import com.stw.kanban.client.entities.BoardColumn;
import com.stw.kanban.client.entities.StickyNoteIssue;
import com.stw.kanban.client.widget.StickyNoteWidgetOptions;
import com.stw.kanban.client.widget.view.BoardColumnWidget;
import com.stw.kanban.client.widget.view.StickyNoteWidget;
import com.stw.kanban.client.widget.view.StickyNoteWidget.StickyNoteWidgetUiBinder;
import com.stw.kanban.resources.KanbanBoardResources;
/*
* Some error issues when running a GWTTestCase:
*
* Issue 1. I get the exception: com.google.gwt.core.client.JavaScriptException: (null): null
* Solution. Make sure you are compiling for the right browser!
* Check the Kanbanboard.gwt.xml file's <set-property name="user.agent" value="<your browser>"/>
*
*
* */
public class BoardColumnWidgetGwtTest extends AbstractKanbanBoardGwtTestCase {
private KanbanBoardResources resources;
private StickyNoteIssue issue1;
private StickyNoteIssue issue2;
private StickyNoteWidgetOptions options;
private BoardColumnWidget boardColumnWidget;
private BoardColumn column;
private StickyNoteWidgetUiBinder uiBinder;
@Override
protected void gwtSetUp() {
resources = GWT.create(KanbanBoardResources.class);
uiBinder = GWT.create(StickyNoteWidgetUiBinder.class);
options = new StickyNoteWidgetOptions();
}
@Override
protected void gwtTearDown() {
}
@Test
public void testBoardColumnWidget_WithIssuesTest() {
Assert.assertNotNull(resources);
Assert.assertNotNull(uiBinder);
Assert.assertNotNull(options);
boardColumnWidget = new BoardColumnWidget("stickyNote", resources, uiBinder);
Assert.assertNotNull(boardColumnWidget);
issue1 = createJiraStickyNoteIssue();
issue2 = createJiraStickyNoteIssue();
issue2.setKey("Issue-2");
issue2.setSummary("This is the issue 2 summary.");
column = new BoardColumn();
column.setName("Development");
column.addIssue(issue1);
column.addIssue(issue2);
boardColumnWidget.setData(column);
Assert.assertEquals("Development", boardColumnWidget.getColumnName().getText());
ArrayList<Widget> stickyNoteList = boardColumnWidget.getStickyNotes();
Assert.assertEquals(2, stickyNoteList.size());
Widget widget1 = stickyNoteList.get(0);
Assert.assertEquals(StickyNoteWidget.class, widget1.getClass());
}
@Test
public void testBoardColumnWidget_WithoutIssuesTest() {
Assert.assertNotNull(resources);
Assert.assertNotNull(uiBinder);
Assert.assertNotNull(options);
boardColumnWidget = new BoardColumnWidget("stickyNote", resources, uiBinder);
Assert.assertNotNull(boardColumnWidget);
column = new BoardColumn();
column.setName("Development");
boardColumnWidget.setData(column);
Assert.assertEquals("Development", boardColumnWidget.getColumnName().getText());
ArrayList<Widget> stickyNoteList = boardColumnWidget.getStickyNotes();
Assert.assertEquals(0, stickyNoteList.size());
}
@Test
public void testBoardColumnWidget_WithNullIssueTest() {
Assert.assertNotNull(resources);
Assert.assertNotNull(uiBinder);
Assert.assertNotNull(options);
boardColumnWidget = new BoardColumnWidget("stickyNote", resources, uiBinder);
Assert.assertNotNull(boardColumnWidget);
StickyNoteIssue issue = null;
column = new BoardColumn();
column.addIssue(issue);
column.setName("Development");
Assert.assertNotNull(column);
try {
boardColumnWidget.setData(column);
}
catch (IllegalArgumentException expectedException) {
if (expectedException.getMessage().equals("The application tried to set a sticky note without any data!")) {
//expected exception and the correct message!
}
else {
fail("The correct exception but wrong message! Verify the message!");
}
}
catch (Exception notExpectedException) {
fail("An IllegalArgumentException was expected!");
}
ArrayList<Widget> stickyNoteList = boardColumnWidget.getStickyNotes();
Assert.assertEquals(0, stickyNoteList.size());
}
@Test
public void testBoardColumnWidget_WithNullColumnTest() {
Assert.assertNotNull(resources);
Assert.assertNotNull(uiBinder);
Assert.assertNotNull(options);
boardColumnWidget = new BoardColumnWidget("stickyNote", resources, uiBinder);
Assert.assertNotNull(boardColumnWidget);
column = null;
// We are expecting an exception in this test. The following code substitutes:
// org.junit.Rule and org.junit.rules.ExpectedException since they are not available
// for the GWTTestCase.
try {
boardColumnWidget.setData(column);
}
catch (IllegalArgumentException expectedException) {
if (expectedException.getMessage().equals("The application tried to set a column without any data!")) {
//expected exception and the correct message!
}
else {
fail("The correct exception but wrong message! Verify the message!");
}
}
catch (Exception notExpectedException) {
fail("An IllegalArgumentException was expected!");
}
}
}
|
Swift | UTF-8 | 1,996 | 2.875 | 3 | [] | no_license | //
// ViewController.swift
// PickerView
//
// Created by Macbook Pro A1990 on 12/6/18.
// Copyright © 2018 Macbook Pro A1990. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var uiPickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
uiPickerView.dataSource = self
uiPickerView.delegate = self
}
// MARK: - PickerView
let myOptions : [String] = ["one","two","three","four"]
func creaPickerView(){
/*
let myPickerView = UIPickerView()
myPickerView.frame = CGRect(x:0, y:100, width:self.view.bounds.width, height:280)
myPickerView.dataSource = self
myPickerView.delegate = self
self.view.addSubview(myPickerView)
*/
self.uiPickerView.dataSource = self
}
}
/////////////////////////////////////////////////////
// MARK: - Extensiones para PickerView
/////////////////////////////////////////////////////
extension ViewController : UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return arr.count
}
}
var arr = ["campana", "ramirez", "martinez", "joaquin", "villalba", "griselda"]
var arr2 = ["joaquin", "ramirez", "martinez", "trata", "villalba", "griselda"]
extension ViewController : UIPickerViewDelegate{
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return arr[row]
}
return arr2[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print ("row: \(row) de la columna \(component)")
}
}
|
Java | UTF-8 | 6,020 | 1.84375 | 2 | [] | no_license | package org.ootb.simulator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
/**
* Created by jiazhao on 10/3/17.
*/
public class LocalNoReceiptReturnTest extends BaseTest{
private String url_dev = "";
private String url_local = "";
private String data_dev = "";
private String data_local = "";
private String command = "";
// private String[] commands ;
// private String txnUUID = "";
private String baseUrl = "http://localhost:8080/orders/";
@Before
public void setup() throws Exception{
commands = new String[]{"curl","-H","Content-Type:application/json","-X","POST","-d","",""};
}
@After
public void tearDown() throws Exception{
}
@Test
public void testLocalNoReceiptReturn() throws IOException, InterruptedException {
blindReturn();
addProduct();
getTax();
issueMRC();
printRecepit();
submit();
}
private void blindReturn() throws IOException, InterruptedException {
url_local = baseUrl + "returns/blindreturn";
data_local = "{\"storeNumber\":\"05955\",\"registerNumber\":\"050\",\"brandName\":\"Athleta\",\"brandAbbreviation\":\"AT\",\"zipcode\":\"94403\"," +
"\"serialNumber\":\"testDevice-serial-no\",\"lasDeviceId\":\"3c651925-d54c-4798-9fb8-c8855ae30554\",\"localDate\":\"2017-10-04T11:08:00.030-0700\"," +
"\"appName\":\"error-500\",\"brandCode\":\"10\",\"city\":\"SAN MATEO\",\"phoneNumber\":\"(650) 638-0199\",\"localeCode\":\"en_US\",\"marketCode\":" +
"\"US\",\"storeName\":\"Some Name\",\"stateCode\":\"CA\",\"address\":\"49 WEST HILLSDALE BLVD.\",\"cashierId\":\"1580344\"}";
commands[6] = data_local;
commands[7] = url_local;
String result = exec();
fetchTxnUUID(result);
}
private void addProduct() throws IOException, InterruptedException {
url_local = baseUrl + "returns/blindreturn/" + txnUUID + "/product";
data_local = "{\"scanCode\":\"160738100002\",\"store\":{\"storeNumber\":\"05955\",\"registerNumber\":\"050\",\"brandName\":\"Athleta\",\"brandAbbreviation\":" +
"\"AT\",\"zipcode\":\"94403\",\"serialNumber\":\"testDevice-serial-no\",\"lasDeviceId\":\"3c651925-d54c-4798-9fb8-c8855ae30554\",\"localDate\":" +
"\"2017-08-30T11:08:00.030-0700\",\"appName\":\"error-500\",\"brandCode\":\"10\",\"city\":\"SAN MATEO\",\"phoneNumber\":\"(650) 638-0199\"," +
"\"localeCode\":\"en_US\",\"marketCode\":\"US\",\"storeName\":\"Some Name\",\"stateCode\":\"CA\",\"address\":\"49 WEST HILLSDALE BLVD.\"," +
"\"cashierId\":\"1580344\"}}";
commands[6] = data_local;
commands[7] = url_local;
exec();
}
private void getTax() throws IOException, InterruptedException {
url_local = baseUrl + txnUUID + "/tax";
data_local = "{\"maxProductSequence\":1,\"txnUUID\":\"1506578880030059550501449427177\",\"status\":\"NEW\",\"taxCalcMode\":\"AUTO\",\"totalUnits\":1," +
"\"totalDiscounts\":0,\"preTaxTotal\":35,\"taxTotal\":0,\"taxRate\":0,\"total\":35,\"header\":{\"transactionId\":null,\"datasourceId\":null," +
"\"salesDate\":\"2016-07-28\",\"transactionType\":\"SalesTransaction\"},\"orderLookupDetails\":[],\"returnPayments\":[]," +
"\"alternateTenderTypes\":[],\"hasTenderBasedDiscounts\":false,\"products\":[{\"sequence\":0,\"userDefinedId\":0,\"styleCode\":\"612346\"," +
"\"styleColorNumber\":\"612346002\",\"taxRate\":null,\"taxCharged\":null,\"sellingDivisionId\":\"WHS\",\"qualifyingPromos\":[]," +
"\"overriddenPrice\":null,\"type\":\"Merch\",\"posCode\":\"260833\",\"sku\":\"6123460020037\",\"sizeCode\":\"0036\",\"taxCode\":\"C2\"," +
"\"upc\":\"126083311047\",\"finalPrice\":35,\"merchandiseType\":\"Merch\",\"selected\":null,\"price\":\"35\",\"isPriceOverride\":null," +
"\"originalPrice\":35,\"departmentNumber\":\"304\",\"description\":\"Boys College Team Graphic Tees\",\"discounts\":[],\"quantity\":1," +
"\"promotionalPrice\":35,\"priceTypeId\":\"1\",\"colorCode\":\"081\",\"isTaxable\":null,\"lineTotalTax\":null,\"code\":null," +
"\"priceAdjustmentInfo\":{\"priceAdjustmentIndicator\":false,\"mappedDetails\":{}},\"onlineItem\":false}],\"discounts\":[{\"code\":" +
"\"FNF2015\",\"status\":\"Pending\",\"scannedCode\":\"FNF2015\",\"promotionCode\":null,\"promotionId\":null,\"appliedStatus\":null," +
"\"promotionType\":null,\"promotionDescription\":null,\"awardId\":null,\"qualifyingTenders\":null,\"membershipId\":null," +
"\"membershipToken\":null}],\"payments\":[],\"invalidDiscounts\":[],\"multipleProducts\":[],\"priceAdjustTransaction\":false}";
commands[6] = data_local;
commands[7] = url_local;
exec();
}
private void issueMRC() throws IOException, InterruptedException {
url_local = baseUrl + txnUUID + "/issueMRC";
data_local = "{\"giftCardNumber\":\"6003877903252141\",\"refundAmount\":\"25.00\",\"approvalCode\":\"\"}";
commands[6] = data_local;
commands[7] = url_local;
exec();
}
private void printRecepit() throws IOException, InterruptedException {
url_local = baseUrl + txnUUID + "/receipt/print";
data_local = "";
commands[4] = "GET";
commands[6] = data_local;
commands[7] = url_local;
exec();
}
private void submit() throws IOException, InterruptedException {
url_local = baseUrl + txnUUID + "/submit";
data_local = "";
commands[6] = data_local;
commands[7] = url_local;
exec();
}
}
|
C++ | UTF-8 | 1,386 | 2.65625 | 3 | [
"MIT"
] | permissive | /**
* @file image.h
* @brief JPEG decoding library.
*/
#pragma once
#include "types.h"
namespace nn
{
namespace image
{
// there's probably more
enum JpegStatus
{
OK = 0,
INVALID_FORMAT = -32,
UNSUPPORTED_FORMAT = -33,
OUT_OF_MEMORY = -64,
};
enum PixelFormat
{
RGBA32,
RGB24
};
enum ProcessStage
{
UNREGISTERED = 0,
REGISTERED = 1,
ANALYZED = 2
};
struct Dimension
{
f32 width;
f32 height;
};
class JpegDecoder
{
public:
JpegDecoder();
virtual ~JpegDecoder();
void SetImageData(void const *source, u64 size);
nn::image::JpegStatus Analyze();
nn::image::Dimension GetAnalyzedDimension() const;
s64 GetAnalyzedWorkBufferSize() const;
JpegStatus Decode(void *out, s64, s32 alignment, void *, s64);
nn::image::ProcessStage mProcessStage; // _8
void* mData; // _C
s64 mSize; // _14
s32 _18;
nn::image::PixelFormat mFormat; // _1C
Dimension mImgDimensions; // _20
s64 _28;
// rest is related to EXIF processing
};
};
}; |
Python | UTF-8 | 595 | 3.25 | 3 | [
"BSD-3-Clause"
] | permissive | # original Eratosthenes prime sieve from http://www.macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2
# with additions from https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python
import itertools
def eratosthenes():
d = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = d.pop(q, None)
if p is None:
d[q*q] = q
yield q
else:
x = 2*p + q
while x in d:
x += 2*p
d[x] = p
|
Python | UTF-8 | 2,165 | 2.609375 | 3 | [] | no_license | import pandas, cv2
import tensorflow as tf
import numpy as np
import math
def convert_reference(reference):
ref_str = str(reference)
if reference < 10:
index = '0000'
elif reference < 100:
index = '000'
else:
index = '00'
return index + ref_str
def read_images(index):
depth_filename = "/Users/georgestoica/Desktop/Research/Mini-Project/vkitti_1.3.1_depthgt/0001/clone/{}.png".format(index)
image_filename = "/Users/georgestoica/Desktop/Research/Mini-Project/vkitti_1.3.1_rgb/0001/clone/{}.png".format(index)
depth = np.reshape(cv2.imread(depth_filename, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH), (375, 1242, 1))
image = cv2.imread(image_filename, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
return image, depth
def downsize_image(image, max_height, max_width, num_channels):
downsized_image = tf.image.resize_image_with_crop_or_pad(image, max_height, max_width)
downsized_image.set_shape([max_height, max_width, num_channels])
downsized_image_encoded = tf.image.encode_png(downsized_image)
return downsized_image_encoded
def main(unusedargv):
NUM_IMAGES = 250
max_height, max_width = 188, 621
init_op = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init_op)
for reference in range(NUM_IMAGES):
image_index = convert_reference(reference)
image, depth = read_images(image_index)
# print("image shape: " + str(image.shape))
image_downsized = downsize_image(image, max_height, max_width, num_channels = 3)
depth_downsized = downsize_image(depth, max_height, max_width, num_channels = 1)
image_fpath = tf.constant("/Users/georgestoica/Desktop/Research/Mini-Project/ds_image/{}.png".format(image_index))
depth_fpath = tf.constant("/Users/georgestoica/Desktop/Research/Mini-Project/ds_depth/{}.png".format(image_index))
image_write = tf.write_file(image_fpath, image_downsized)
depth_write = tf.write_file(depth_fpath, depth_downsized)
dummy_ = sess.run(image_write)
dummy_ = sess.run(depth_write)
if __name__ == "__main__":
tf.app.run()
|
Java | UTF-8 | 91 | 1.679688 | 2 | [] | no_license | package com.dms.web.beans;
public enum Toast {
success, info, warning, error;
}
|
Java | UTF-8 | 4,986 | 1.890625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.cassandra;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import org.junit.jupiter.api.Test;
import org.rnorth.ducttape.TimeoutException;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.containers.ContainerLaunchException;
import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;
import org.testcontainers.images.builder.Transferable;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.testsupport.testcontainers.CassandraContainer;
import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link CassandraAutoConfiguration} that only uses password authentication.
*
* @author Stephane Nicoll
*/
@Testcontainers(disabledWithoutDocker = true)
class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests {
@Container
static final CassandraContainer cassandra = new PasswordAuthenticatorCassandraContainer().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(10))
.waitingFor(new CassandraWaitStrategy());
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class))
.withPropertyValues(
"spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(),
"spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s",
"spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s");
@Test
void authenticationWithValidUsernameAndPassword() {
this.contextRunner
.withPropertyValues("spring.cassandra.username=cassandra", "spring.cassandra.password=cassandra")
.run((context) -> {
SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local")
.setConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
assertThat(context.getBean(CqlSession.class).execute(select).one()).isNotNull();
});
}
@Test
void authenticationWithInvalidCredentials() {
this.contextRunner
.withPropertyValues("spring.cassandra.username=not-a-user", "spring.cassandra.password=invalid-password")
.run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class))
.hasMessageContaining("Authentication error"));
}
static final class PasswordAuthenticatorCassandraContainer extends CassandraContainer {
@Override
protected void containerIsCreated(String containerId) {
String config = copyFileFromContainer("/etc/cassandra/cassandra.yaml",
(stream) -> StreamUtils.copyToString(stream, StandardCharsets.UTF_8));
String updatedConfig = config.replace("authenticator: AllowAllAuthenticator",
"authenticator: PasswordAuthenticator");
copyFileToContainer(Transferable.of(updatedConfig.getBytes(StandardCharsets.UTF_8)),
"/etc/cassandra/cassandra.yaml");
}
}
static final class CassandraWaitStrategy extends AbstractWaitStrategy {
@Override
protected void waitUntilReady() {
try {
Unreliables.retryUntilSuccess((int) this.startupTimeout.getSeconds(), TimeUnit.SECONDS, () -> {
getRateLimiter().doWhenReady(() -> cqlSessionBuilder().build());
return true;
});
}
catch (TimeoutException ex) {
throw new ContainerLaunchException(
"Timed out waiting for Cassandra to be accessible for query execution");
}
}
private CqlSessionBuilder cqlSessionBuilder() {
return CqlSession.builder()
.addContactPoint(new InetSocketAddress(this.waitStrategyTarget.getHost(),
this.waitStrategyTarget.getFirstMappedPort()))
.withLocalDatacenter("datacenter1")
.withAuthCredentials("cassandra", "cassandra");
}
}
}
|
C# | UTF-8 | 1,146 | 2.53125 | 3 | [] | no_license | using System;
using Server;
using Server.Targeting;
namespace Server.Engines.Jail
{
/// <summary>
/// Generic target for use in the jailing system
/// </summary>
public class JailTarget : Target
{
/// <summary>
/// The function that should be called if the targeting action is succesful
/// </summary>
JailTargetCallback m_Callback;
/// <summary>
/// Creates a new jail target
/// </summary>
/// <param name="callback">The function that will be called if the target action is succesful</param>
public JailTarget( JailTargetCallback callback ) : base( -1, false, TargetFlags.None )
{
m_Callback = callback;
}
protected override void OnTarget(Mobile from, object targeted)
{
Server.Mobiles.PlayerMobile pm = targeted as Server.Mobiles.PlayerMobile;
if ( pm != null )
{
if ( pm.AccessLevel == AccessLevel.Player )
{
try
{
m_Callback.DynamicInvoke( new object[] { from, pm } );
}
catch {}
}
else
from.SendMessage( "The jail system isn't supposed to be used on staff" );
}
else
from.SendMessage( "The jail system only works on players" );
}
}
} |
C | UTF-8 | 3,683 | 3.75 | 4 | [] | no_license | // Question : Write a program to simulate online ticket reservations. Implement a write lock. Write a program to open a file, store a ticket number, and exit. Write a separate program, to open the file, implement write lock, read the ticket number, increment the number, and print the new ticket number then close the file
#include <sys/types.h> // Import for `open`, `lseek`
#include <sys/stat.h> // Import for `open`
#include <fcntl.h> // Import for `fcntl` & `open`
#include <unistd.h> // Import for `write`, `lseek` & `fcntl`
#include <stdio.h> // Import for `perror` & `printf`
void main()
{
char *ticketFile = "./sample-files/ticket-file.txt"; // Name of file used for storing the ticket number
int fileDescriptor, fcntlStatus;
ssize_t readBytes, writeBytes;
off_t lseekOffset;
int buffer;
struct flock ticketLock;
fileDescriptor = open(ticketFile, O_CREAT | O_RDWR, S_IRWXU);
if (fileDescriptor == -1)
perror("Error while opening the file!");
else
{
ticketLock.l_type = F_WRLCK;
ticketLock.l_pid = getpid();
// Lock the entire file
ticketLock.l_whence = SEEK_SET;
ticketLock.l_len = 0;
ticketLock.l_start = 0;
fcntlStatus = fcntl(fileDescriptor, F_GETLK, &ticketLock);
if (fcntlStatus == -1)
perror("Error while getting lock status!");
else
{
switch (ticketLock.l_type)
{
case F_WRLCK:
// File already has write lock
printf("The ticket File %s is already locked for writing!\n", ticketFile);
break;
case F_RDLCK:
// File already has a read lock
printf("The ticket File %s is already locked for reading!\n", ticketFile);
break;
default:
// No lock on the file
ticketLock.l_type = F_WRLCK;
fcntlStatus = fcntl(fileDescriptor, F_SETLKW, &ticketLock);
if (fcntlStatus == -1)
perror("Error while locking the ticket file!");
else
{
readBytes = read(fileDescriptor, &buffer, sizeof(int));
if (readBytes == -1)
perror("Error while reading ticket!");
else if (readBytes == 0)
{
buffer = 1;
writeBytes = write(fileDescriptor, &buffer, sizeof(int));
if (writeBytes == -1)
perror("Error while writing to ticket!");
else
printf("Your ticket number is %d\n", buffer);
}
else
{
lseekOffset = lseek(fileDescriptor, 0, SEEK_SET);
if (lseekOffset == -1)
perror("Error while seeking!");
else
{
buffer += 1;
writeBytes = write(fileDescriptor, &buffer, sizeof(int));
printf("Your ticket number is: %d\n", buffer);
}
}
ticketLock.l_type = F_UNLCK;
fcntlStatus = fcntl(fileDescriptor, F_SETLKW, &ticketLock);
if (fcntlStatus == -1)
perror("Error releasing lock!");
else
printf("Done!\n");
}
}
}
close(fileDescriptor);
}
} |
Go | UTF-8 | 6,298 | 2.609375 | 3 | [
"MIT"
] | permissive | package appencryption_test
import (
"fmt"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/godaddy/asherah/go/appencryption"
"github.com/godaddy/asherah/go/appencryption/internal"
"github.com/godaddy/asherah/go/appencryption/pkg/crypto/aead"
"github.com/godaddy/asherah/go/appencryption/pkg/kms"
"github.com/godaddy/asherah/go/appencryption/pkg/persistence"
)
const (
product = "enclibrary"
service = "asherah"
partitionID = "123456"
staticKey = "thisIsAStaticMasterKeyForTesting"
payloadSizeBytes = 100
)
var (
c = aead.NewAES256GCM()
config = &appencryption.Config{
Policy: appencryption.NewCryptoPolicy(),
Product: product,
Service: service,
}
metastore = persistence.NewMemoryMetastore()
caches = [...]string{
"mango",
"ristretto",
}
)
func BenchmarkSession_Encrypt(b *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(b, err)
factory := appencryption.NewSessionFactory(
config,
metastore,
km,
c,
)
randomBytes := make([][]byte, b.N)
for i := 0; i < b.N; i++ {
randomBytes[i] = internal.GetRandBytes(payloadSizeBytes)
}
sess, _ := factory.GetSession(partitionID)
b.ResetTimer()
for i := 0; i < b.N; i++ {
bytes := randomBytes[i]
if _, err := sess.Encrypt(bytes); err != nil {
b.Error(err)
}
}
}
func Benchmark_EncryptDecrypt_MultiFactorySamePartition(b *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(b, err)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
factory := appencryption.NewSessionFactory(
config,
metastore,
km,
c,
)
sess, _ := factory.GetSession(partitionID)
randomBytes := internal.GetRandBytes(payloadSizeBytes)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
b.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(b, randomBytes, data)
sess.Close()
factory.Close()
}
})
}
func Benchmark_EncryptDecrypt_MultiFactoryUniquePartition(b *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(b, err)
b.RunParallel(func(pb *testing.PB) {
zipf := newZipf(10, appencryption.DefaultSessionCacheMaxSize*16)
for i := 0; i < b.N && pb.Next(); i++ {
factory := appencryption.NewSessionFactory(
config,
metastore,
km,
c,
)
sess, _ := factory.GetSession(fmt.Sprintf(partitionID+"_%d", zipf()))
randomBytes := internal.GetRandBytes(payloadSizeBytes)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
b.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(b, randomBytes, data)
sess.Close()
factory.Close()
}
})
}
func Benchmark_EncryptDecrypt_SameFactoryUniquePartition(b *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(b, err)
factory := appencryption.NewSessionFactory(
config,
metastore,
km,
c,
)
defer factory.Close()
b.RunParallel(func(pb *testing.PB) {
zipf := newZipf(10, appencryption.DefaultSessionCacheMaxSize*16)
for pb.Next() {
partition := fmt.Sprintf(partitionID+"_%d", zipf())
randomBytes := internal.GetRandBytes(payloadSizeBytes)
sess, _ := factory.GetSession(partition)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
b.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(b, randomBytes, data)
sess.Close()
}
})
}
func newZipf(v float64, n uint64) func() uint64 {
zipfS := 1.7
z := rand.NewZipf(rand.New(rand.NewSource(time.Now().UnixNano())), zipfS, v, n)
return z.Uint64
}
func Benchmark_EncryptDecrypt_SameFactoryUniquePartition_WithSessionCache(b *testing.B) {
capacity := appencryption.DefaultSessionCacheMaxSize
for i := range caches {
engine := caches[i]
subtest := fmt.Sprintf("WithEngine %s", engine)
b.Run(subtest, func(bb *testing.B) {
conf := &appencryption.Config{
Policy: appencryption.NewCryptoPolicy(
appencryption.WithSessionCache(),
appencryption.WithSessionCacheEngine(engine),
),
Product: product,
Service: service,
}
km, err := kms.NewStatic(staticKey, c)
assert.NoError(bb, err)
factory := appencryption.NewSessionFactory(
conf,
metastore,
km,
c,
)
defer factory.Close()
bb.RunParallel(func(pb *testing.PB) {
zipf := newZipf(10, uint64(capacity)*16)
for pb.Next() {
partition := fmt.Sprintf(partitionID+"_%d", zipf())
randomBytes := internal.GetRandBytes(payloadSizeBytes)
sess, _ := factory.GetSession(partition)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
bb.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(bb, randomBytes, data)
sess.Close()
}
})
})
}
}
func Benchmark_EncryptDecrypt_SameFactorySamePartition(b *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(b, err)
factory := appencryption.NewSessionFactory(
config,
metastore,
km,
c,
)
defer factory.Close()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
randomBytes := internal.GetRandBytes(payloadSizeBytes)
sess, _ := factory.GetSession(partitionID)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
b.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(b, randomBytes, data)
sess.Close()
}
})
}
func Benchmark_EncryptDecrypt_SameFactorySamePartition_WithSessionCache(b *testing.B) {
for i := range caches {
engine := caches[i]
b.Run(fmt.Sprintf("WithEngine %s", engine), func(bb *testing.B) {
km, err := kms.NewStatic(staticKey, c)
assert.NoError(bb, err)
conf := &appencryption.Config{
Policy: appencryption.NewCryptoPolicy(
appencryption.WithSessionCache(),
appencryption.WithSessionCacheEngine(engine),
),
Product: product,
Service: service,
}
factory := appencryption.NewSessionFactory(
conf,
metastore,
km,
c,
)
defer factory.Close()
bb.RunParallel(func(pb *testing.PB) {
for pb.Next() {
randomBytes := internal.GetRandBytes(payloadSizeBytes)
sess, _ := factory.GetSession(partitionID)
drr, err := sess.Encrypt(randomBytes)
if err != nil {
bb.Error(err)
}
data, _ := sess.Decrypt(*drr)
assert.Equal(bb, randomBytes, data)
sess.Close()
}
})
})
}
}
|
C++ | UTF-8 | 237 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#define PI 3.14159
int main()
{
double radius,area;
printf("Enter radius (e.g. 10):");
scanf("%lf", & radius);
area = PI*radius*radius;
printf("\n Area = %lf\n", area );
return 0;
}
|
Java | UTF-8 | 7,745 | 2.03125 | 2 | [] | no_license | package com.app;
import com.app.model.*;
import com.app.model.dto.ProductDto;
import com.app.model.modelMappers.ModelMapper;
import com.app.payloads.requests.LoginPayload;
import com.app.repository.ProductRepository;
import com.app.repository.RoleRepository;
import com.app.repository.UserRepository;
import com.app.service.AmazonClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ProductRestControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@Autowired
private ProductRepository productRepository;
@Autowired
private ModelMapper modelMapper;
@Autowired
private RoleRepository roleRepository;
@Autowired
private UserRepository userRepository;
@MockBean
private AmazonClient amazonClient;
@Before
public void init() {
if (roleRepository.count() != RoleName.values().length) {
roleRepository.deleteAll();
Arrays
.stream(RoleName.values())
.forEach(role -> roleRepository.save(Role.builder().roleName(role).build()));
}
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
userRepository.save(User.builder().email("test@test.com").username("test").roles(Collections.singletonList(roleRepository.findByRoleName(RoleName.ROLE_USER).get())).password(bCryptPasswordEncoder.encode("123")).build());
productRepository.save(Product.builder().brand("Aaa").description("Adesc").quantity(10).price(10.0).productType("BEER").build());
productRepository.save(Product.builder().brand("Bbb").description("Bdesc").imgUrl("test.jpg").quantity(10).price(10.0).productType("BEER").build());
}
@Test
public void getProductsTest() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
List<ProductDto> productsDto = productRepository.findAll().stream().map(modelMapper::fromProductToProductDto).collect(Collectors.toList());
mvc.perform(get("/api/product")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Auth-Token", getAuthToken())
.header("Accept", "application/json"))
.andExpect(status().isOk())
.andExpect(content().json(gsonBuilder.toJson(productsDto)));
Assert.assertEquals(2, productRepository.findAll().size());
}
@Test
public void getProductTest() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
ProductDto productDto = productRepository.findById(1L).map(modelMapper::fromProductToProductDto).orElseThrow(NullPointerException::new);
mvc.perform(get("/api/product/1")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Auth-Token", getAuthToken())
.header("Accept", "application/json"))
.andExpect(status().isOk())
.andExpect(content().json(gsonBuilder.toJson(productDto)));
}
@Test
public void addProductTest() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
ClassLoader classLoader = getClass().getClassLoader();
FileInputStream fis = new FileInputStream(classLoader.getResource("images/pic3.png").getFile());
MockMultipartFile multipartFile = new MockMultipartFile("file", fis);
ProductDto productDto = ProductDto.builder().brand("Test").description("TestDesc").price(10.0).quantity(10).productType(ProductTypes.BEER).build();
when(amazonClient.uploadFile(multipartFile)).thenReturn(null);
mvc.perform(MockMvcRequestBuilders.multipart("/api/product")
.file("file", multipartFile.getBytes())
.param("productDto", gsonBuilder.toJson(productDto))
.header("X-Auth-Token", getAuthToken()))
.andExpect(status().isOk());
Assert.assertEquals(3, productRepository.findAll().size());
}
@Test
public void updateProductTest() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
ClassLoader classLoader = getClass().getClassLoader();
ProductDto productDto = productRepository.findById(1L).map(modelMapper::fromProductToProductDto).orElseThrow(NullPointerException::new);
FileInputStream fis = new FileInputStream(classLoader.getResource("images/pic3.png").getFile());
MockMultipartFile multipartFile = new MockMultipartFile("file", fis);
when(amazonClient.uploadFile(multipartFile)).thenReturn(null);
final String updateDesc = "UpdateDesc";
productDto.setDescription(updateDesc);
mvc.perform(MockMvcRequestBuilders.multipart("/api/product")
.file("file", multipartFile.getBytes())
.param("productDto", gsonBuilder.toJson(productDto))
.header("X-Auth-Token", getAuthToken()))
.andExpect(status().isOk());
Assert.assertEquals(2, productRepository.findAll().size());
Assert.assertEquals(updateDesc, productRepository.findById(1L).get().getDescription());
}
@Test
public void deleteProductTest() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
final int countBefore = productRepository.findAll().size();
ProductDto productDto = productRepository.findById(2L).map(modelMapper::fromProductToProductDto).orElseThrow(NullPointerException::new);
mvc.perform(delete("/api/product/2")
.contentType(MediaType.APPLICATION_JSON)
.header("X-Auth-Token", getAuthToken())
.header("Accept", "application/json"))
.andExpect(status().isOk())
.andExpect(content().json(gsonBuilder.toJson(productDto)));
Assert.assertEquals(countBefore - 1, productRepository.findAll().size());
}
private String getAuthToken() throws Exception {
Gson gsonBuilder = new GsonBuilder().create();
return mvc.perform(post("/api/auth/signin")
.contentType(MediaType.APPLICATION_JSON)
.content(gsonBuilder.toJson(LoginPayload.builder()
.email("test@test.com")
.password("123").build()))).andReturn()
.getResponse()
.getHeader("x-auth-token");
}
}
|
C | UTF-8 | 1,401 | 3.765625 | 4 | [] | no_license | /*
write a program which shows a menu card of a Burger house and give
the customer the choice of veg and non veg and each of them consist
of 4 different types of burger and print the order at least and ask
them again for more using do while loop and nested switch
Input:
Welcome to Burger King please select from the following
1.Veg
2.Non Veg
1
Veg Blasts
a.Veggie tikki Burger
b.Aloo Tikki Burger
c.Mushroom Veggie cheese Burger
d.Peanut Butter Sweet Potato Burger
*/
#include<stdio.h>
void main(){
int ch;
char choice;
do{
printf("1. Veg\n");
printf("2. Non Veg\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch){
case 1:
{
printf("*****************Veg Blasts****************\n");
printf("a. Veggie Tikki Burger\n");
printf("b. Aloo Tikki Burger\n");
printf("c. Mushroom Veggie Cheese Burger\n");
printf("d. Peanut Butter Sweet Potato Burger\n");
}
break;
case 2:
{
printf("*****************Non-Veg Blasts****************\n");
printf("a. chicken chilli cheese melt\n");
printf("b. chicken Whooper\n");
printf("c. crispy chicken supreme\n");
}
break;
default:
printf("Wrong data\n");
break;
}
printf("Do you want to continue?\n");
scanf(" %c",&choice);
}while(choice=='y' || choice=='Y');
}
|
C++ | UTF-8 | 1,200 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
#include<stdlib.h>
using namespace std;
int maxArea(vector<int>& height) {
int l = 0;
int r = height.size() -1 ;
int result = INT_MIN;
while(l<r){
int curArea = (r-l) * min(height[r], height[l]);
result = max(result, curArea);
// cout << "result: " << result << " curArea:" << curArea << " l:" << l << " r:"<< r<<endl;
if(height[r] > height[l]) {
l++;
} else {
r--;
}
}
return result;
}
int main() {
vector< vector<int> > inputs;
inputs.push_back( vector<int>(5, 1));
int case1[] = {1,8,6,2,5,4,8,3,7};
inputs.push_back( vector<int>(case1, case1+sizeof(case1)/sizeof(int)));
int case2[] = {1,1};
inputs.push_back( vector<int>(case2, case2+sizeof(case2)/sizeof(int)));
int case3[] = {4,3,2,1,4};
inputs.push_back( vector<int>(case3, case3+sizeof(case3)/sizeof(int)));
int case4[] = {1,2,1};
inputs.push_back( vector<int>(case4, case4+sizeof(case4)/sizeof(int)));
for(auto item: inputs){
int area = maxArea(item);
cout<< "area: " << area <<endl;
}
return 0;
} |
Java | UTF-8 | 532 | 3.296875 | 3 | [] | no_license | package JavaPracticeGitHub.C26_HashTable;
import java.util.*;
public class LengthLongestSubstring {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> myMap = new HashMap<>();
int max = 0;
for(int j = 0, i = 0; j < s.length() ; j++){
if(myMap.containsKey(s.charAt(j))) {
i = Math.max(myMap.get(s.charAt(j)), i);
}
max = Math.max(max, j - i + 1);
myMap.put(s.charAt(j), j + 1);
}
return max;
}
}
|
Markdown | UTF-8 | 10,812 | 2.859375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive |
<!-- PROJECT LOGO -->
<br />
<p align="center">
<h1 align="center">JavaScript PubSub</h1>
<p align="center">
Small and fast JavaScript PubSub library designed for writing maintainable and decoupled code in JavaScript.
<br />
</p>
</p>
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About the Project](#about-the-project)
* [Built With](#built-with)
* [Getting Started](#getting-started)
* [Usage](#usage)
* [API](#api)
* [Contributing](#contributing)
* [License](#license)
* [Contact](#contact)
<!-- ABOUT THE PROJECT -->
## About The Project
This is simple library designed for writing maintainable code in JavaScript using PubSub pattern. This library is designed to work with both Node.js and browser without issue. PubSub is a messaging pattern is a design pattern that provides a framework for exchanging messages that allows for loose coupling and scaling between the sender of messages (publishers) and receivers (subscribers) on topics they subscribe to.
In the pub/sub messaging pattern, publishers do not send messages directly to all subscribers; instead, messages are sent via brokers. Publishers do not know who the subscribers are or to which (if any) topics they subscribe. This means publisher and subscriber operations can operate independently of each other. This is known as loose coupling and removes service dependencies that would otherwise be there in traditional messaging patterns.
### Built With
This library is designed with technologies listed below -
* [JavaScript](https://www.javascript.com/)
<!-- GETTING STARTED -->
## Getting Started
Using this library is simple, you just have to add/import this library in your project. The simple technique is to add/import all modules which specify subscribers on your app entrypoint. Other modules do not need to add/import them, you simply has to publish events, subscribers callback will be called as event gets published. This technique keeps only your app entrypoint coupled with subscriber modules while keeping rest of your app decoupled.
<!-- USAGE EXAMPLES -->
## Usage
### Node.js example -
```js
const pubsub = require('./index');
pubsub.subscribe('locationChange', function(x){
console.log('locationChange: ', x);
if(typeof x !== 'number'){
generateErrorNow();
}
return x * 2;
});
pubsub.subscribe('locationUpdate', function(x){
console.log('locationUpdate: ', x);
return x * 3;
});
pubsub.publish('locationChange', function(error, x){
console.log("Error: ", error);
console.log("Data should be null: ", x);
}, "102");
pubsub.publish('locationUpdate', function(_error, x){
console.log("102*3 = ", x)
}, 102);
```
### Browser example -
```html
<html>
<head>
<script src="./pubsub.js" />
</head>
<body>
<script>
pubsub.subscribe('locationChange', function(x){
console.log('locationChange: ', x);
return x * 2;
});
pubsub.subscribe('locationUpdate', function(x){
console.log('locationUpdate: ', x);
return x * 3;
});
pubsub.publish('locationChange', function(_error, x){
console.log("100*2 = ", x)
}, 100);
pubsub.publish('locationUpdate', function(_error, x){
console.log("102*3 = ", x)
}, 102);
</script>
</body>
</html>
```
### Next.js example -
#### utilities/demo/index.js
```js
import pubsub from '../pubsub';
pubsub.subscribe('locationChange', function(x){
console.log('locationChange: ', x);
if(typeof x !== 'number'){
generateErrorNow();
}
return x * 2;
});
```
#### components/Card/index.js
```js
import React from 'react';
import pubsub from '../../pubsub';
const Card = ({title, children}) => (
<div style={{'backgroundColor': 'blue'}}>
<div style={{'backgroundColor': 'white', 'color': 'blue', 'padding': '20px', 'border': '5px solid red'}}>
<h3>{title}</h3>
</div>
{children}
</div>
);
pubsub.subscribe('components/card', function(){
return Card;
});
export default Card;
```
#### pages/_app.jsx
```js
import React from 'react';
import '../utilities/demo';
import '../components/Card';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp;
```
#### pages/index.jsx
```js
import React, {useEffect} from 'react';
import pubsub from '../pubsub';
import publishComponent from '../pubsub/react';
const Card = publishComponent('components/card');
const Homepage = () => {
useEffect(() => {
pubsub.publish('locationChange', function(error, x){
console.log("error: ", error);
console.log("Data should be null: ", x)
}, null);
pubsub.withDebugging('locationChange').publish('locationChange', function(_error, x){
console.log("300*2 = ", x)
}, 300);
}, []);
return (
<Card title="Amit">
<p>Hello world</p>
</Card>
)
};
export default Homepage;
```
<!-- API -->
## API
All API functions exists inside pubsub object such as - `pubsub.subscribe`.
### subscribe(eventName, callback, key)
Allows subscribing to the event and executing the callback when an event is published. Key is used to prevent same subscriber from registering twice. By default the key is `index` when subscriber with same key is passed, the previous subscriber is replaced with new one.
#### eventName
Type: `string`
Event to subscribe to.
#### callback
Type: `function`
Callback to be executed when the publish event is received. Data passed with `publish` and `publishAll` is passed to this function as parameter. The data returned by this function can be accessed using promise resolve callback, whereas error occurred can be accessed using promise reject callback. If you intentionally want to pass error from subscriber callback use code - `return Promise.reject("error data");`.
#### key
Type: `string`
Used to identify subscriber in a channel to prevent duplicate subscriber from registering twice. The value is optional and default key is `index`, if you want to register multiple subscriber, all must have unique key.
### unsubscribe(eventName)
Clear all subscribers or subscribers linked to a specific channel/event. If channel/event name is not provided, all subscribers are cleared.
### clearTaskQueue(eventName)
Clear all task in queues linked to a specific channel/event.
#### eventName
Type: `string`
Optional. When provided, it clear subscribers linked to specific channel/event. Otherwise, it clears all subscriber registered.
### publish(eventName, callback, data)
Returns a promise with boolean value, that specifies whether the task is executing or in queue waiting for subscriber. If returned value is `true`, task is being executed otherwise task is waiting for its subscriber. It can only be used with single subscriber, if multiple subscribers are added for same event, first one is used.
#### eventName
Type: `string`
Event published.
#### callback
Type: `function`
Callback function to get result after task execution. Callback function should have two parameters, where first one is `error` and second one is `response`.
#### data
Type: `any`
Data to be passed to subscriber callback.
### publishSync(eventName, data, defaultValue)
Run a task synchronously. Returns data provided by subscriber callback after task execution. When no subscriber is found, returns undefined. It can only be used with single subscriber, if multiple subscribers are added for same event, first one is used. It returns a JSON object -
```js
{ error: errorData, data: dataValue }
```
#### eventName
Type: `string`
Event published.
#### data
Type: `any`
Data to be passed to subscriber callback.
#### defaultValue
Type: `any`
Default data to be passed when no subscriber is found for channel/event.
### withDebugging(eventName)
Enable debugging for event/channel which displays all communications such as subscriber is executed or failed. It returns pubsub object.
#### eventName
Type: `string`
Event published.
### endDebugging(eventName)
Disable debugging for event/channel. It returns pubsub object.
#### eventName
Type: `string`
Event published.
### clearDebugger()
Clear all debugging. It returns pubsub object.
## React APIs
To help designing decoupled ReactJS application, the library provides `pubsub/react` module which allows you to safely render component with pubsub without any issue. The library includes default fallback component to prevent any issue if component subscriber is not registered. React APIs add two channels which allows access to error boundaries for React components.
* `components/withErrorBoundary` - Higher Order Component to render component with error boundaries.
* `components/errorBoundary` - React error boundary component to wrap around other components.
### publishComponent(channel, fallback)
Get instance of component from pubsub subscriber. It returns function/class of react component which means component is not rendered so that you can store it in variable and render when required.
#### channel
Type: `string`
Channel/event name where component subscriber is registered.
#### fallback
Type: `any`
Optional fallback component to display if component subscriber is not found. It is used to prevent app from crashing. If not provided, the default fallback component is used.
### publishComponentSafe
This function works same as `publishComponent` except that it wraps the target component with React error boundaries. It prevents app from crashing from any rendering error. It displays a fallback UI when error occurs.
#### channel
Type: `string`
Channel/event name where component subscriber is registered.
#### fallback
Type: `any`
Optional fallback component to display if component subscriber is not found. It is used to prevent app from crashing. If not provided, the default fallback component is used.
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<!-- LICENSE -->
## License
Distributed under the Apache License 2.0. See `LICENSE` for more information.
<!-- CONTACT -->
## Contact
Amit Kumar - amitcute3@gmail.com
Project Link: [https://github.com/amit08255/javascript-pubsub](https://github.com/amit08255/javascript-pubsub)
|
JavaScript | UTF-8 | 2,041 | 3.28125 | 3 | [] | no_license | let output = document.querySelector(".calculator__output")
var btns = document.querySelectorAll(".btn")
btns.forEach(btn => btn.addEventListener("click", operations))
let switchToggle = document.querySelector('.button-switch')
switchToggle.addEventListener('click', toggleTheme)
function operations (event){
event.preventDefault()
let key = event.target
let action = key.dataset.operation
let value = key.textContent //keyContent
let outputNum = output.textContent
let firstValue = 0
btns.forEach(item => item.classList.remove('--is-depressed'))
let previousKeyType = key.dataset.previousKeyType
if (!action) {
if(outputNum === '0' || previousKeyType === 'operator') {
output.textContent = value
} else {
output.textContent = outputNum + value
}
}
if (action === 'reset') {
output.textContent = 0
}
if(
action === 'add' ||
action === 'substract' ||
action === 'multiply' ||
action === 'divide' ||
action === 'module'
) {
key.classList.add('--is-depressed')
key.dataset.firstValue = outputNum
key.dataset.operator = value
console.log(key.dataset.operator);
key.dataset.previousKeyType = 'operator'
if(key.dataset.previousKeyType === 'operator') {
output.textContent = ''
}
}
if(action === 'decimal') {
if(!outputNum.includes('.')) {
output.textContent = outputNum + '.'
}
}
if(action === 'calculate') {
firstValue = Number(key.dataset.firstValue)
let operator = key.dataset.operator
let secondValue = outputNum
console.log(operator);
console.log(firstValue)
output.textContent = calculate(firstValue, secondValue)
}
if(action === 'int') { console.log('negativo')}
}
function calculate(value1, value2) {
let result = ''
result= parseFloat(value1) + parseFloat(value2)
return result
}
function toggleTheme () {
let main = document.querySelector('.calculator')
main.classList.toggle('--dark-theme')
}
|
Python | UTF-8 | 1,207 | 2.8125 | 3 | [] | no_license | from src.modules.kit.interface import AbstractKNN
from src.modules.utilities.model.impl.equal import ModelEqualKNN
from src.modules.utilities.learning.interface import AbstractLearningKNN
class LearningKNNEqual(AbstractLearningKNN):
def __init__(self, classifier: AbstractKNN, size: int, classes: int, max_k=20, ratio=.8):
"""
Launches the KNN Model.
:return: None
"""
self.__size: int = size
self.__ratio: float = ratio
self.__max_k: int = max_k
self.__classes: int = classes
self.__dataset: list or None = None
self.__classifier: AbstractKNN = classifier
def learn_model(self) -> int:
max_k = 0
max_precision = 0
for k in range(1, self.__max_k + 1):
pipeline: ModelEqualKNN = ModelEqualKNN(self.__classifier, k, self.__size, self.__classes)
x_train, x_test, y_train, y_test = pipeline.prepare_dataset()
precision = pipeline.estimate(x_train, y_train)
print("Precision on neighbours", k, "equals:", precision)
if precision > max_precision:
max_precision = precision
max_k = k
return max_k
|
JavaScript | UTF-8 | 245 | 2.90625 | 3 | [] | no_license | let firtsName = 'Amir';
lastname = 'Ahad'
fullName = firtsName + ' ' + lastname
let score = 100,
bonus= 30;
totalscore = score+bonus
// console.log(name);
console.log(totalscore);
console.log(fullName);
console.log(firtsName + ' ' + lastname);
|
Markdown | UTF-8 | 2,175 | 2.75 | 3 | [] | no_license | ---
title: Universal Package Manager
author: Amjad Masad
date: 2018-07-19T07:00:00.000Z
---
Open-source has revolutionized software development -- it wouldn't be an
overstatement to say that it's been the most significant productivity win for developers
in the last decade or so. At Repl.it, our goal is to make programming more
accessible and what better way to do that than make available to programmers the
entirety of open-source packages available at their fingertips.
Today we're excited to announce our Universal Package Manager -- the Repl.it
package manager that will grow to support every language on our platform. We're
now starting with JavaScript, Python, HTML/CSS/JS, and the web frameworks that
we support.
<div style='position:relative; padding-bottom:75.00%'><iframe src='https://gfycat.com/ifr/AmazingPessimisticAddax' frameborder='0' scrolling='no' width='100%' height='100%' style='position:absolute;top:0;left:0;' allowfullscreen></iframe></div>
We've had [basic support](python-import) for automatic package detection and installation for a
while now, but what changed is that we support search and spec files
(package.json, gemfile, requirements.txt, etc) across the board. Furthermore,
where we used to write custom code for every language that we support, now we
merely add fields to a config file.
This was mad possible by creating a common package manager runner abstractions.
Adding package manager support for a language is as easy as adding a
couple of fields in a JSON config:
```json
"dependencies": {
"env": {
"PYTHONPATH": "/run_dir/customize",
"MATPLOTLIBRC": "/run_dir/"
},
"installDir": ".site-packages",
"findCommand": [
"python",
"/run_dir/findreqs.py",
"--ignore",
"~/.site-packages"
],
"installCommand": [
"pip",
"install",
"--target=~/.site-packages"
],
"specFile": "requirements.txt",
```
In addition to this we have a more ambitious project in the works to build the same package
manager that works across all languages (with the same semantics). You should
[come work](/site/jobs) with us.
[Signup](/signup) and start [coding](/languages). |
Java | UTF-8 | 1,238 | 2.265625 | 2 | [] | no_license | package agh.edu.pl.project.controllers;
import agh.edu.pl.project.models.entities.User;
import agh.edu.pl.project.models.views.UserView;
import agh.edu.pl.project.repositories.UserRepository;
import agh.edu.pl.project.services.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequiredArgsConstructor
public class UsersController {
private final UserService userService;
private final UserRepository repository;
@GetMapping(value = "/users")
public ModelAndView list() {
ModelAndView model = new ModelAndView();
model.addObject("users", repository.findAll());
return model;
}
@GetMapping
@RequestMapping("{id}")
public UserView get(@PathVariable Long id) {
return userService.getOne(id);
}
@PostMapping
public User registerUser(User user) {
return repository.saveAndFlush(user);
}
}
|
SQL | UTF-8 | 19,315 | 3.375 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.6.1
-- http://www.phpmyadmin.net
--
-- Хост: localhost
-- Время создания: Июн 12 2016 г., 19:20
-- Версия сервера: 5.5.43-37.2
-- Версия PHP: 5.6.21
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `cu71173_electron`
--
-- --------------------------------------------------------
--
-- Структура таблицы `groups`
--
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`GrName` varchar(64) NOT NULL,
`Course` int(11) NOT NULL,
`SpecID` int(11) NOT NULL,
`CurID` int(11) NOT NULL,
`StewID` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `GrName` (`GrName`),
KEY `Course` (`Course`),
KEY `SpecID` (`SpecID`),
KEY `CurID` (`CurID`),
KEY `StewID` (`StewID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `groups`
--
INSERT INTO `groups` (`id`, `GrName`, `Course`, `SpecID`, `CurID`, `StewID`) VALUES
(1, '', 1, 1, 1, 1),
(2, 'КСК5', 3, 3, 2, 1),
(3, 'ПКС5', 1, 2, 2, 2),
(4, 'ОДЛ3', 3, 5, 1, 1),
(5, 'ПКС7', 1, 2, 4, 7);
-- --------------------------------------------------------
--
-- Структура таблицы `groups_subjects`
--
CREATE TABLE IF NOT EXISTS `groups_subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`GroupID` int(11) NOT NULL,
`SubjID` int(11) NOT NULL,
`TeachID` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `GroupsID` (`GroupID`),
KEY `SubjID` (`SubjID`),
KEY `TeachID` (`TeachID`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Дамп данных таблицы `groups_subjects`
--
INSERT INTO `groups_subjects` (`id`, `GroupID`, `SubjID`, `TeachID`) VALUES
(3, 3, 11, 2),
(6, 5, 3, 5),
(7, 3, 2, 4),
(8, 4, 3, 2),
(9, 3, 8, 6),
(10, 3, 10, 7),
(11, 3, 9, 2),
(12, 3, 12, 8),
(13, 2, 3, 5);
-- --------------------------------------------------------
--
-- Структура таблицы `lessons`
--
CREATE TABLE IF NOT EXISTS `lessons` (
`LessonID` int(11) NOT NULL AUTO_INCREMENT,
`Theme` varchar(64) NOT NULL,
`Homework` varchar(64) NOT NULL,
`Date` date NOT NULL,
`GroupID` int(11) NOT NULL,
`TeachID` int(11) NOT NULL,
`SubjID` int(11) NOT NULL,
PRIMARY KEY (`LessonID`),
KEY `GroupID` (`GroupID`),
KEY `TeachID` (`TeachID`),
KEY `SubjID` (`SubjID`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `lessons`
--
INSERT INTO `lessons` (`LessonID`, `Theme`, `Homework`, `Date`, `GroupID`, `TeachID`, `SubjID`) VALUES
(1, 'Ничего не делание', 'Ничего не делать', '2016-06-06', 3, 2, 11),
(2, 'Новая тема', 'Повторить новую тему', '2016-06-06', 5, 2, 8),
(3, 'Новая тема', 'Повторение новой темы', '2016-06-06', 5, 5, 3),
(4, 'Вторая тема', 'Повторение второй темы\r\n', '2016-06-06', 5, 5, 3),
(5, 'Ничего не делание', 'qqqq', '2016-06-04', 3, 2, 11),
(6, 'Название темы', 'Что-то сделать', '2016-06-07', 5, 5, 3),
(7, 'Тема ', 'Выучить стишки про сети', '2016-06-04', 3, 2, 11),
(8, 'Настривание роутера', 'Принести роутер', '2016-05-07', 3, 2, 11),
(9, 'Починка роутера', 'Сломать роутер', '2016-05-15', 3, 2, 11),
(10, 'Ничего не делание', 'Ничего не делать', '2016-05-10', 3, 2, 11),
(11, 'Тема', 'ДЗ', '2016-04-01', 3, 2, 11),
(12, 'Тема', 'ДЗ', '2016-04-02', 3, 2, 11),
(13, 'Тема', 'ДЗ', '2016-04-03', 3, 2, 11),
(14, 'Тема', 'ДЗ', '2016-04-04', 3, 2, 11),
(15, 'Подготовка к ЕГЭ', 'Решать сборники к ЕГЭ', '2016-06-12', 2, 5, 3),
(16, 'Контрольная работа', 'Вы', '2016-05-12', 3, 2, 11),
(17, 'Подготовка к ЕГЭ', 'sdssd', '2016-06-12', 3, 2, 11);
-- --------------------------------------------------------
--
-- Структура таблицы `marks`
--
CREATE TABLE IF NOT EXISTS `marks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`LessonID` int(11) NOT NULL,
`StudID` int(11) NOT NULL,
`Mark` int(11) NOT NULL,
`Absent` varchar(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `StudID` (`StudID`),
KEY `LessonID` (`LessonID`)
) ENGINE=InnoDB AUTO_INCREMENT=80 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `marks`
--
INSERT INTO `marks` (`id`, `LessonID`, `StudID`, `Mark`, `Absent`) VALUES
(3, 1, 4, 5, ''),
(6, 4, 6, 5, ''),
(7, 4, 7, 5, ''),
(9, 3, 6, 2, ''),
(10, 3, 6, 5, ''),
(11, 3, 7, 5, ''),
(12, 3, 7, 5, ''),
(13, 8, 5, 5, ''),
(14, 9, 9, 5, ''),
(15, 7, 5, 5, ''),
(16, 9, 2, 5, ''),
(17, 7, 2, 5, ''),
(18, 5, 2, 5, ''),
(19, 8, 2, 5, ''),
(20, 1, 2, 0, 'б'),
(21, 9, 3, 5, ''),
(22, 7, 3, 5, ''),
(24, 5, 10, 0, 'б'),
(25, 5, 5, 0, 'о'),
(26, 7, 9, 0, 'б'),
(28, 1, 10, 5, ''),
(30, 8, 3, 5, ''),
(31, 10, 8, 3, ''),
(32, 5, 8, 4, ''),
(33, 7, 8, 0, 'б'),
(34, 10, 4, 5, ''),
(35, 5, 4, 0, 'б'),
(36, 5, 5, 5, ''),
(37, 1, 5, 5, ''),
(38, 1, 8, 5, ''),
(39, 8, 9, 5, ''),
(40, 1, 9, 4, ''),
(41, 10, 17, 2, ''),
(42, 1, 17, 2, ''),
(43, 7, 21, 3, ''),
(44, 8, 18, 5, ''),
(45, 5, 18, 2, ''),
(46, 10, 26, 2, ''),
(47, 8, 10, 5, ''),
(48, 13, 20, 4, ''),
(49, 13, 20, 3, ''),
(50, 8, 20, 5, ''),
(51, 11, 26, 5, ''),
(52, 14, 8, 0, 'б'),
(53, 13, 26, 0, ''),
(54, 13, 26, 0, ''),
(55, 13, 26, 0, ''),
(56, 1, 15, 5, ''),
(57, 12, 8, 4, ''),
(58, 8, 30, 0, 'н'),
(59, 6, 6, 5, ''),
(60, 6, 7, 5, ''),
(61, 9, 18, 5, ''),
(62, 10, 27, 4, ''),
(63, 7, 20, 5, ''),
(64, 12, 23, 3, ''),
(65, 9, 16, 5, ''),
(66, 12, 16, 5, ''),
(67, 7, 27, 0, 'н'),
(68, 5, 27, 0, 'б'),
(69, 10, 2, 5, ''),
(70, 14, 3, 5, ''),
(71, 9, 28, 2, ''),
(72, 14, 18, 3, ''),
(73, 13, 18, 2, ''),
(74, 12, 19, 5, ''),
(75, 10, 19, 4, ''),
(76, 5, 19, 4, ''),
(78, 17, 10, 5, ''),
(79, 17, 2, 5, '');
-- --------------------------------------------------------
--
-- Структура таблицы `parents`
--
CREATE TABLE IF NOT EXISTS `parents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ParFIO` varchar(64) NOT NULL,
`UserID` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `UserID` (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `parents`
--
INSERT INTO `parents` (`id`, `ParFIO`, `UserID`) VALUES
(1, '', 1),
(2, 'Синявская Елена Петровна', 8),
(3, 'Сальникова Юлия Отествовна', 9),
(4, 'Мыключенко Александр Леонидович', 10),
(5, 'Лапий Лариса Отчествовна', 11),
(6, 'Иванов Иван Иванович', 12),
(7, 'Петров Пётр Петрович', 13),
(8, 'Сергеев Сергей Сергеевич', 14),
(9, 'Ананьев Иван Иванович', 15),
(11, 'Лукин Иван Иванович', 17),
(12, 'Кирпиченко Отец Отчествович', 46);
-- --------------------------------------------------------
--
-- Структура таблицы `settings`
--
CREATE TABLE IF NOT EXISTS `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Attribute` varchar(64) NOT NULL,
`Value` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `settings`
--
INSERT INTO `settings` (`id`, `Attribute`, `Value`) VALUES
(1, 'URL', 'http://localhost/'),
(2, 'CollegeName', 'Колледж КФУ'),
(3, 'SMTP_HOST', 'smtp.timeweb.ru'),
(4, 'SMTP_USER', 'mail@nataliamk.ru'),
(5, 'SMTP_PASSWORD', 'cortmx15'),
(6, 'MAIL_NAME', 'Электронный журнал ТК'),
(7, 'CollegeLogo', 'public/images/cfu.png');
-- --------------------------------------------------------
--
-- Структура таблицы `specialties`
--
CREATE TABLE IF NOT EXISTS `specialties` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`SpecName` varchar(128) NOT NULL,
`SpecCode` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `specialties`
--
INSERT INTO `specialties` (`id`, `SpecName`, `SpecCode`) VALUES
(1, '', ''),
(2, 'Программирование в компьютерных системах', '09.02.02'),
(3, 'Компьютерные системы и комплексы', '09.02.01'),
(4, 'Химия', '666'),
(5, 'Операционная деятельность в логистике', '38.02.03'),
(6, 'Финансы', '38.02.06'),
(7, 'Туризм', '43.02.10');
-- --------------------------------------------------------
--
-- Структура таблицы `students`
--
CREATE TABLE IF NOT EXISTS `students` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`StudFIO` varchar(128) NOT NULL,
`GrID` int(11) NOT NULL,
`ParentID` int(11) NOT NULL,
`UserID` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `GrID` (`GrID`),
KEY `ParentID` (`ParentID`),
KEY `UserID` (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `students`
--
INSERT INTO `students` (`id`, `StudFIO`, `GrID`, `ParentID`, `UserID`) VALUES
(1, '', 1, 1, 1),
(2, 'Синявский Иван Владимирович', 3, 2, 3),
(3, 'Мыключенко Наталья Александровна', 3, 4, 4),
(4, 'Сальников Владислав Андреевич', 3, 3, 5),
(5, 'Лапий Александр Николаевич', 3, 5, 6),
(6, 'Ананьев Владимир Отчествович', 5, 9, 19),
(7, 'Лукина Антонина Отчествовна', 5, 11, 20),
(8, 'Штогрин Богдан Отчествович', 3, 1, 22),
(9, 'Кирпиченко Анастасия Отчествовна', 3, 12, 23),
(10, 'Вишнёв Николай Николаевич', 3, 1, 24),
(11, 'Подоляк Денис Отчествович', 2, 1, 26),
(12, 'Терещенко Александр Отчествович', 2, 1, 27),
(13, 'Бекирова Лилия Отчествовна', 2, 1, 28),
(14, 'Исаев Егор Викторович', 4, 12, 29),
(15, 'Гемеджи Айдер Отчествович', 3, 1, 30),
(16, 'Дудко Александр Александрович', 3, 1, 31),
(17, 'Ободяк Любомир Любомирович', 3, 1, 32),
(18, 'Данилов Артём Отчествович', 3, 1, 33),
(19, 'Стансков Илья Владимирович', 3, 1, 34),
(20, 'Антонюк Родион Отчествович', 3, 1, 35),
(21, 'Перепёлка Борис Отчествович', 3, 1, 36),
(22, 'Назаров Никита Отчествович', 3, 1, 37),
(23, 'Карлаш Иван Отчествович', 3, 1, 38),
(24, 'Петрушин Александр Отчествович', 3, 1, 39),
(25, 'Лашко Анна Андреевна', 3, 1, 40),
(26, 'Гедзик Анастасия Отчествовна', 3, 1, 41),
(27, 'Климентовский Владислав Отчествович', 3, 1, 42),
(28, 'Тян Станислав Александрович', 3, 1, 43),
(29, 'Марьинских Светлана Отчествовна', 3, 1, 44),
(30, 'Субботина Валентина Отчествовна', 3, 1, 45),
(33, 'Тестовый', 3, 1, 58),
(35, 'Тестовый', 1, 1, 60),
(36, 'Тестовый', 1, 1, 61);
-- --------------------------------------------------------
--
-- Структура таблицы `subjects`
--
CREATE TABLE IF NOT EXISTS `subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`SubjName` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `subjects`
--
INSERT INTO `subjects` (`id`, `SubjName`) VALUES
(1, ''),
(2, 'Русский язык'),
(3, 'Информатика'),
(4, 'Математика'),
(5, 'Химия'),
(6, 'Биология'),
(7, 'Геометрия'),
(8, 'Высшая математика'),
(9, 'Технология разработки программного обеспечения'),
(10, 'Программирование'),
(11, 'ИКСС'),
(12, 'Технология разработки и защиты баз данных'),
(13, 'Философия');
-- --------------------------------------------------------
--
-- Структура таблицы `teachers`
--
CREATE TABLE IF NOT EXISTS `teachers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TeachFIO` varchar(128) NOT NULL,
`UserID` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `UserID` (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `teachers`
--
INSERT INTO `teachers` (`id`, `TeachFIO`, `UserID`) VALUES
(1, '', 1),
(2, 'Железняк Александр Владимирович', 7),
(3, 'Андрейчука Анна Михайловна', 16),
(4, 'Горащук Ольга Сергеевна', 18),
(5, 'Катунина Анна Юрьевна', 21),
(6, 'Смирнова Светлана Ивановна', 47),
(7, 'Михерский Ростислав Михайлович', 48),
(8, 'Бондарев Виктор Павлович', 49),
(9, 'Дихтярь Александр Иванович', 51),
(12, 'Беленькая Анна Сергеевна', 54);
-- --------------------------------------------------------
--
-- Структура таблицы `teachers_subjects`
--
CREATE TABLE IF NOT EXISTS `teachers_subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TeachID` int(11) NOT NULL,
`SubjID` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `TeachID` (`TeachID`),
KEY `SubjID` (`SubjID`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Дамп данных таблицы `teachers_subjects`
--
INSERT INTO `teachers_subjects` (`id`, `TeachID`, `SubjID`) VALUES
(1, 2, 3),
(2, 2, 8),
(3, 2, 9),
(4, 2, 10),
(5, 2, 11),
(6, 3, 3),
(7, 4, 2),
(8, 5, 3),
(9, 5, 4),
(10, 6, 8),
(11, 7, 10),
(12, 8, 12);
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`UserID` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`Email` varchar(48) NOT NULL,
`Admin` int(11) NOT NULL,
PRIMARY KEY (`UserID`)
) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`UserID`, `login`, `password`, `Email`, `Admin`) VALUES
(1, '', '', '', 0),
(2, 'admin', 'a454ada51211270133943e45af218a87', 'linki_98i@bk.ru', 1),
(3, 'linki_98i@bk.ru', 'Sinyavskij4815', 'linki_98i@bk.ru', 0),
(4, 'linki_98i@bk.ru', 'Myklyuchenko8563', 'linki_98i@bk.ru', 0),
(5, 'linki_98i@bk.ru', 'Salnikov4405', 'linki_98i@bk.ru', 0),
(6, '', 'Lapij8726', '', 0),
(7, 'linki_98i@bk.ru', 'ZHeleznyak4561', 'linki_98i@bk.ru', 0),
(8, '', 'Sinyavskaya1267', '', 0),
(9, '', 'Salnikova9562', '', 0),
(10, '', 'Myklyuchenko4123', '', 0),
(11, '', 'Lapij5885', '', 0),
(12, '', 'Roditel6158', '', 0),
(13, '', 'Roditel9164', '', 0),
(14, '', 'Roditel4494', '', 0),
(15, '', 'Roditel9617', '', 0),
(16, '', 'Andrejchuka1024', '', 0),
(17, 'linki_98i@bk.ru', '21232f297a57a5a743894a0e4a801fc3', 'linki_98i@bk.ru', 0),
(18, 'linki_98i@bk.ru', '86f8b60dee38866a7df676ad57366ce2', 'linki_98i@bk.ru', 0),
(19, 'linki_98i@bk.ru', 'd2d27025be9d8bafbf90127688de2399', 'linki_98i@bk.ru', 0),
(20, 'linki_98i@bk.ru', '0b4e696677754a361258b6c6555ca970', 'linki_98i@bk.ru', 0),
(21, 'linki_98i@bk.ru', 'f81fb366bf9f7c9b0b67bb090f02f5b4', 'linki_98i@bk.ru', 0),
(22, 'linki_98i@bk.ru', '3a94f048b53e32a13fe5fcfe8874450f', 'linki_98i@bk.ru', 0),
(23, 'linki_98i@bk.ru', '32ba95a16191bcb9a20496c6094c768b', 'linki_98i@bk.ru', 0),
(24, 'linki_98i@bk.ru', '3a27149dbda8813a936d44f644d6fae8', 'linki_98i@bk.ru', 0),
(25, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'linki_98i@bk.ru', 1),
(26, 'linki_98i@bk.ru', 'ade80e08dbc48a641871d68ec4eb7f75', 'linki_98i@bk.ru', 0),
(27, 'linki_98i@bk.ru', '56aa4898f5c46343eebe8f5ec33289bd', 'linki_98i@bk.ru', 0),
(28, 'linki_98i@bk.ru', '651eedd7e5cc228f5c19ca31d3d84c30', 'linki_98i@bk.ru', 0),
(29, '', 'b0741e41edd0fcb8d2497209419d0768', '', 0),
(30, '', 'f6d75ffad6d3ada42a2ad8926f27e7ad', '', 0),
(31, '', '6c4796d11862e2c93baea2d755eb27dc', '', 0),
(32, '', 'c55ed618129fe1fe81882517feb3f27b', '', 0),
(33, '', 'b1a2f6ddec003d4086c3b68696dbaa76', '', 0),
(34, '', '580b1a418abe2418e9ad1975743c775d', '', 0),
(35, '', '1deb202fea3aa1168e72b7b0b39e214f', '', 0),
(36, '', '55808894596243a84407f83a4fe9271a', '', 0),
(37, '', '9d44005f22f3d42d4c49a85fe2d0a855', '', 0),
(38, '', '201bdb1833513cce5815d4f4fce60459', '', 0),
(39, '', '2340f88935085927b56f266cb3a9b242', '', 0),
(40, '', '803ce7febef84dbd1afa8bf11de992a2', '', 0),
(41, 'linki_98i@bk.ru', '753bd9ffea7b5e84ea4587ff67c3ba88', 'linki_98i@bk.ru', 0),
(42, '', '343b11c1e57f44fcb17bf89123bf2c00', '', 0),
(43, '', '1f330960af0caf297f0842742ed7899a', '', 0),
(44, '', '200956cbbb936742d9aed9deb86b9f8b', '', 0),
(45, '', '26b6994d97f0e2239b43202a87889790', '', 0),
(46, 'linki_98i@bk.ru', '9a709b862f6ea6f463846e85558205d5', 'linki_98i@bk.ru', 0),
(47, 'linki_98i@bk.ru', '9aaf13336ddcf6d14c227bbc49c958d4', 'linki_98i@bk.ru', 0),
(48, 'linki_98i@bk.ru', '2561b17e49f2baed94577a92918571e2', 'linki_98i@bk.ru', 0),
(49, 'linki_98i@bk.ru', 'd60266e0aca6f0e72b0a47e724e662d7', 'linki_98i@bk.ru', 0),
(50, 'admin4', 'admin4', 'linki_98i@bk.ru', 1),
(51, '', '260713959b9cd4e7d285e995633424b7', '', 0),
(52, '', '285d20558ca17af3d2a711c2e5267297', '', 0),
(53, 'linki_98i@bk.ru', 'cd26fb3cea5e2c0b497c75d22c851275', 'linki_98i@bk.ru', 0),
(54, 'linki_98i@bk.ru', '588c1e5d75f646a05807f657b01a6307', 'linki_98i@bk.ru', 0),
(55, 'linki_98i@bk.ru', 'd03d0ed4ecb639e3fa12926b468e6340', 'linki_98i@bk.ru', 0),
(56, 'linki_98i@bk.ru', '27294f0d619c950a86a0fd2ada6c1889', 'linki_98i@bk.ru', 0),
(57, 'linki_98i@bk.ru', '256de5f68435fb85a1fbe9ba89c2c225', 'linki_98i@bk.ru', 0),
(58, 'linki_98i@bk.ru', 'f9a075b80bc4c7dfd6ff17e542b197bd', 'linki_98i@bk.ru', 0),
(59, 'linki_98i@bk.ru', '5c23b71fe4468583fc0837495fdf1a0d', 'linki_98i@bk.ru', 0),
(60, '', '87e22ae3b9b821806fe34c722fafafa6', '', 0),
(61, 'linki_98i@bk.ru', 'c616b769631669aad3ea85f884403d17', 'linki_98i@bk.ru', 0);
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `groups`
--
ALTER TABLE `groups`
ADD CONSTRAINT `groups_ibfk_1` FOREIGN KEY (`SpecID`) REFERENCES `specialties` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `groups_ibfk_2` FOREIGN KEY (`CurID`) REFERENCES `teachers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `groups_ibfk_3` FOREIGN KEY (`StewID`) REFERENCES `students` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `groups_subjects`
--
ALTER TABLE `groups_subjects`
ADD CONSTRAINT `groups_subjects_ibfk_1` FOREIGN KEY (`GroupID`) REFERENCES `groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `groups_subjects_ibfk_2` FOREIGN KEY (`SubjID`) REFERENCES `subjects` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `groups_subjects_ibfk_3` FOREIGN KEY (`TeachID`) REFERENCES `teachers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `lessons`
--
ALTER TABLE `lessons`
ADD CONSTRAINT `lessons_ibfk_1` FOREIGN KEY (`GroupID`) REFERENCES `groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `lessons_ibfk_2` FOREIGN KEY (`TeachID`) REFERENCES `teachers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `lessons_ibfk_3` FOREIGN KEY (`SubjID`) REFERENCES `subjects` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `marks`
--
ALTER TABLE `marks`
ADD CONSTRAINT `marks_ibfk_1` FOREIGN KEY (`LessonID`) REFERENCES `lessons` (`LessonID`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `marks_ibfk_2` FOREIGN KEY (`StudID`) REFERENCES `students` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `parents`
--
ALTER TABLE `parents`
ADD CONSTRAINT `parents_ibfk_1` FOREIGN KEY (`UserID`) REFERENCES `users` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `students`
--
ALTER TABLE `students`
ADD CONSTRAINT `students_ibfk_2` FOREIGN KEY (`ParentID`) REFERENCES `parents` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `students_ibfk_3` FOREIGN KEY (`UserID`) REFERENCES `users` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `teachers`
--
ALTER TABLE `teachers`
ADD CONSTRAINT `teachers_ibfk_1` FOREIGN KEY (`UserID`) REFERENCES `users` (`UserID`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `teachers_subjects`
--
ALTER TABLE `teachers_subjects`
ADD CONSTRAINT `teachers_subjects_ibfk_1` FOREIGN KEY (`TeachID`) REFERENCES `teachers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `teachers_subjects_ibfk_2` FOREIGN KEY (`SubjID`) REFERENCES `subjects` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | UTF-8 | 2,753 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | /* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.examples;
import java.util.*;
import java.io.*;
/** This class describes a single component of the authority service response.
*/
public class ResponseComponent
{
// Response types
public static final int RESPONSECOMPONENT_TOKEN = 0;
public static final int RESPONSECOMPONENT_AUTHORIZED = 1;
public static final int RESPONSECOMPONENT_UNREACHABLEAUTHORITY = 1;
public static final int RESPONSECOMPONENT_UNAUTHORIZED = 2;
public static final int RESPONSECOMPONENT_USERNOTFOUND = 3;
/** This the the component type */
protected int type;
/** This is the component value */
protected String value;
/** This is the type map, for quick lookups */
protected static Map<String,Integer> typeMap;
static
{
typeMap = new HashMap<String,Integer>();
typeMap.put("TOKEN",new Integer(RESPONSECOMPONENT_TOKEN));
typeMap.put("AUTHORIZED",new Integer(RESPONSECOMPONENT_AUTHORIZED));
typeMap.put("UNREACHABLEAUTHORITY",new Integer(RESPONSECOMPONENT_UNREACHABLEAUTHORITY));
typeMap.put("UNAUTHORIZED",new Integer(RESPONSECOMPONENT_UNAUTHORIZED));
typeMap.put("USERNOTFOUND",new Integer(RESPONSECOMPONENT_USERNOTFOUND));
}
/** Constructor.
*/
public ResponseComponent(String componentString)
throws IOException
{
int index = componentString.indexOf(":");
if (index == -1)
throw new IOException("Illegal component string: '"+componentString+"'");
String typeString = componentString.substring(0,index);
Integer typeInt = typeMap.get(typeString);
if (typeInt == null)
throw new IOException("Illegal component string: '"+componentString+"'");
type = typeInt;
value = componentString.substring(index+1);
}
/** Get the component type.
*@return the type.
*/
public int getType()
{
return type;
}
/** Get the component value.
*@return the value.
*/
public String getValue()
{
return value;
}
}
|
C# | UTF-8 | 2,071 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
namespace Whitelog.Core.LogScopeSyncImplementation
{
public static class LogScopeSyncFactory
{
private static Queue<Type> _types;
class A1 { }
class A2 { }
class A3 { }
class A4 { }
class A5 { }
class A6 { }
class A7 { }
class A8 { }
class A9 { }
class A10 { }
static LogScopeSyncFactory()
{
// We use generic types to create a diffrent ThreadStatic every time a new insatnce of this class is created
// This is a major hack and will be needed to be fixed some how....
_types = new Queue<Type>();
_types.Enqueue(typeof(A1));
_types.Enqueue(typeof(A2));
_types.Enqueue(typeof(A3));
_types.Enqueue(typeof(A4));
_types.Enqueue(typeof(A5));
_types.Enqueue(typeof(A6));
_types.Enqueue(typeof(A7));
_types.Enqueue(typeof(A8));
_types.Enqueue(typeof(A9));
_types.Enqueue(typeof(A10));
}
public static ILogScopeSyncImplementation Create()
{
lock (_types)
{
var currType = _types.Dequeue();
var logScopeSyncType = typeof (LogScopeSync<>).MakeGenericType(currType);
return (ILogScopeSyncImplementation) Activator.CreateInstance(logScopeSyncType);
}
}
public static void Free(ILogScopeSyncImplementation implementation)
{
lock (_types)
{
if (implementation.GetType().IsGenericType &&
implementation.GetType().GetGenericTypeDefinition() == typeof (LogScopeSync<>))
{
var type = implementation.GetType().GetGenericArguments()[0];
if (!_types.Contains(type))
{
_types.Enqueue(type);
}
}
}
}
}
} |
JavaScript | UTF-8 | 1,801 | 2.9375 | 3 | [] | no_license | window.addEventListener("DOMContentLoaded", function (e) {
var height = parseInt(document.getElementById('maze_container').getAttribute('height'));
var width = parseInt(document.getElementById('maze_container').getAttribute('width'));
let Maze = new MazeBuilder(width, height);
Maze.placeKey();
Maze.display("maze_container");
var maze = new Mazing("maze");
var tryAgain = document.getElementById('try-again');
tryAgain.addEventListener("click",tryAgainFunc);
function tryAgainFunc(){
maze.heroScore = maze.initScore;
maze.setMessage("first find the key");
maze.maze[maze.heroPos].classList.remove("hero");
maze.mazeContainer.classList.remove("face-right");
maze.heroPos = maze.initHeroPos;
maze.maze[maze.initHeroPos].classList.add("hero");
var keyPos = new Position(Maze.fr, Maze.fc);
if(!maze.maze[keyPos].classList.contains("key")){
maze.maze[keyPos].classList.add("key");
};
maze.mazeScore.classList.remove("has-key");
document.addEventListener("keydown", maze.keyPressHandler, false);
maze.mazeContainer.classList.remove("gameover");
};
var newGame = document.getElementById('new-game');
var maze_container = document.getElementById('maze_container');
newGame.addEventListener("click",newGameFunc);
function newGameFunc(){
while (maze_container.firstChild) {
maze_container.removeChild(maze_container.lastChild);
}
Maze = new MazeBuilder(16, 12);
Maze.placeKey();
Maze.display("maze_container");
maze = new Mazing("maze");
}
}, false);
|
Shell | UTF-8 | 3,907 | 3.96875 | 4 | [] | no_license | #!/bin/bash
cur_dir=$(pwd)
script_name=$(basename $0)
script_dir=$(dirname $0)
root_dir=${script_dir}/..
log_dir=${script_dir}/log
data_dir=${script_dir}/data
mkdir -p $log_dir $data_dir
result=${log_dir}/create_result
log=${log_dir}/create.log
tmp_log=${log_dir}/create_$$
server_ip_list=${data_dir}/server_ip_list
[ -e $result ] && rm -rf $result
[ -e $log ] && rm -rf $log
[ -e $tmp_log ] && rm -rf $tmp_log
[ -e $server_ip_list ] && rm -rf $server_ip_list
touch $log
touch $server_ip_list
declare -A IPS
DISTROS=""
function usage()
{
echo ""
echo "Usage: $script_name <paramters or options> "
echo ""
echo " -i INPUT_FILE "
echo " in format: <instance group> <index>"
echo " -o OUTPUT_HOSTS_FILE_NAME"
echo " in format: ansible hosts file under ../etc/ansible. The default is jenkins_slaves"
echo ""
exit
}
input_file=
slave_list=jenkins_slaves
while getopts "*hi:o:" arg
do
case $arg in
h) usage
;;
i) input_file=$OPTARG
;;
o) slave_list=$OPTARG
;;
?)
echo "Unknown option $arg"
usage
;;
esac
done
[ -z "$input_file" ] && usage
slave_list=${root_dir}/etc/ansible/$slave_list
[ -e $slave_list ] && rm -rf $slave_list
# Create new instances
#---------------------
error=0
while read group index options
do
[ -z "$group" ] && continue
echo $group | grep -q "^[[:space:]]*#"
[ $? -eq 0 ] && continue
#echo "$group,$index,$options"
#echo ""
echo "Launch $group $index" | tee -a $log
echo "-----------------------" | tee -a $log
${script_dir}/../client/create-instance.sh -g $group -i $index $options |& tee $tmp_log
if [ $? -eq 0 ]
then
# Collect new instance information
#---------------------------------
result_string=$(cat $tmp_log | tail -n 2 | grep -i "succeed")
if [ -z "result_string" ]
then
error=$(expr $error \+ 1)
cat $tmp_log >> $log
continue
fi
result_string=$(echo $result_string | cut -d' ' -f 2)
instance_ip=$(echo $result_string | cut -d',' -f 2 | cut -d'=' -f 2)
instance_name=$(cat $tmp_log | grep "^|[[:space:]][[:space:]]*name[[:space:]][[:space:]]*|" | \
sed 's/ //g' | cut -d'|' -f3)
echo "$instance_ip $instance_name" >> $server_ip_list
if [ ${IPS[$group]} ]
then
IPS[$group]="${IPS[$group]} $instance_ip"
else
IPS[$group]="$instance_ip"
fi
if echo $group | grep -q centos
then
if echo "$DISTROS" | grep -q -v $group
then
if [ -n "${DISTROS}" ]
then
DISTROS="${DISTROS} $group"
else
DISTROS="$group"
fi
fi
else
if echo "${DISTROS}" | grep -q -v $group
then
if [ -n "${DISTROS}" ]
then
DISTROS="${DISTROS} $group"
else
DISTROS="$group"
fi
fi
fi
else
error=$(expr $error \+ 1)
fi
cat $tmp_log >> $log
done < $input_file
if [ $error -eq 0 ]
then
echo "Succeed" | tee $result
else
echo "Failed. There are $error instance(s) failed to create." | tee $result
exit 1
fi
# Create host list file $slave_list
#----------------------------------
touch $slave_list
for group in ${DISTROS}
do
echo "[$group]" >> $slave_list
for ip in ${IPS[$group]}
do
echo "$ip" >> $slave_list
done
echo "" >> $slave_list
done
echo "" >> $slave_list
echo "[new:children]" >> $slave_list
for group in ${DISTROS}
do
echo "$group" >> $slave_list
done
echo "" >> $slave_list
echo ""
echo "Hosts file for Ansible" | tee -a $log
cat $slave_list | tee -a $log
|
Python | UTF-8 | 156 | 2.71875 | 3 | [] | no_license | # Jared Medeiros
# Comp340 HW5
#Test commit
import lexer
srcCode = "((12+3*5)+5/4)"
tokSeq = lexer.tokenize(srcCode)
for i in tokSeq:
print(i.type, i.value) |
C++ | UHC | 1,374 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void) {
int C;
cin >> C;
for (int c = 0; c < C; c++) {
int N;
cin >> N;
int before[100];
int cur[100];
int before_count[100];
int cur_count[100];
int max = 0;
int max_count;
before_count[0] = 1;
cur_count[0] = 1; //ʱȭ
for (int n = 1; n <= N; n++) {
//̽
for (int i = 0; i < n; i++) {
cin >> cur[i];
//ù ƴҶ ϸ
if (n != 1) {
if (i == 0) {
cur[i] += before[i];
cur_count[i] = before_count[i];
}
else if (i == n - 1) {
cur[i] += before[i-1];
cur_count[i] = before_count[i-1];
}
else {
if (before[i - 1] > before[i]) {
cur[i] += before[i - 1];
cur_count[i] = before_count[i - 1];
}
else if (before[i - 1] == before[i]) {
cur[i] += before[i];
cur_count[i] = before_count[i - 1] + before_count[i];
}
else {
cur[i] += before[i];
cur_count[i] = before_count[i];
}
}
}
}
for (int i = 0; i < n; i++) {
before[i] = cur[i];
before_count[i] = cur_count[i];
}
}
for (int i = 0; i < N; i++) {
if (cur[i] > max) {
max = cur[i];
max_count = cur_count[i];
}
else if (cur[i] == max)
max_count += cur_count[i];
}
cout << max_count << endl;
}
}
|
Markdown | UTF-8 | 627 | 4.03125 | 4 | [] | no_license | # $random
Returns random numbers.
## Usages
There are two usages of the `$random` function.
### Usage #1
```
$random
```
Returns a random number between 0 and 9.
### Usage #2
```
$random[minimum;maximum]
````
Returns a random number between 'minimum' and 'maximum'.
## Example
```
$nomention
🎲 You rolled `$random[1;7]`!
```
> `$random[]` never returns the 'maxium' value, as it's right side exclusive range. Basically, to get a random number between 1 and 10; you'd put 11 as the 'maxium' instead of 10.

|
Markdown | UTF-8 | 3,151 | 2.71875 | 3 | [
"MIT"
] | permissive | # Solution
Generate the YAML for a Deployment plus Pod for further editing.
```shell
$ kubectl create deployment deploy --image=nginx --dry-run=client -o yaml > deploy.yaml
```
Edit the labels. The selector should match the labels of the Pods. Change the replicas from 1 to 3.
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
tier: backend
name: deploy
spec:
replicas: 3
selector:
matchLabels:
app: v1
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: v1
spec:
containers:
- image: nginx
name: nginx
resources: {}
status: {}
```
Create the deployment by pointing it to the YAML file.
```shell
$ kubectl create -f deploy.yaml
deployment.apps/deploy created
$ kubectl get deployments
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
deploy 3 3 3 1 4s
```
Set the new image and check the revision history.
```shell
$ kubectl set image deployment/deploy nginx=nginx:latest
deployment.extensions/deploy image updated
$ kubectl rollout history deploy
deployment.extensions/deploy
REVISION CHANGE-CAUSE
1 <none>
2 <none>
$ kubectl rollout history deploy --revision=2
deployment.extensions/deploy with revision #2
Pod Template:
Labels: app=v1
pod-template-hash=1370799740
Containers:
nginx:
Image: nginx:latest
Port: <none>
Host Port: <none>
Environment: <none>
Mounts: <none>
Volumes: <none>
```
Now scale the Deployment to 5 replicas.
```shell
$ kubectl scale deployments deploy --replicas=5
deployment.extensions/deploy scaled
```
Roll back to revision 1. You will see the new revision. Inspecting the revision should show the image `nginx`.
```shell
$ kubectl rollout undo deployment/deploy --to-revision=1
deployment.extensions/deploy
$ kubectl rollout history deploy
deployment.extensions/deploy
REVISION CHANGE-CAUSE
2 <none>
3 <none>
$ kubectl rollout history deploy --revision=3
deployment.extensions/deploy with revision #3
Pod Template:
Labels: app=v1
pod-template-hash=454670702
Containers:
nginx:
Image: nginx
Port: <none>
Host Port: <none>
Environment: <none>
Mounts: <none>
Volumes: <none>
```
## Optional
> Can you foresee potential issues with a rolling deployment?
A rolling deployment ensures zero downtime which has the side effect of having two different versions of a container running at the same time. This can become an issue if you introduce backward-incompatible changes to your public API. A client might hit either the old or new service API.
> How do you configure a update process that first kills all existing containers with the current version before it starts containers with the new version?
You can configure the deployment use the `Recreate` strategy. This strategy first kills all existing containers for the deployment running the current version before starting containers running the new version. |
Markdown | UTF-8 | 1,055 | 2.765625 | 3 | [
"MIT"
] | permissive | ---
title: Richard Stobart shortlisted for UK Agile Awards 2014
date: "2014-10-24T11:55:00+01:00"
published: true
---
<p>Unboxed Consulting CEO, Richard Stobart, has been shortlisted for this year’s UK Agile Awards.<br/></p>
<p>The UK Agile Awards were created to recognise and award top Agile talent and recognise the challenge of adopting the discipline and serves to publicly recognise their efforts.<br/></p>
<p>For his role in the <a href="../product-stories/plymouth-university-gets-agile">Plymouth University gets Agile</a> project, Richard has been shortlisted in the ‘Best Agile Coach or Mentor – Process’ category.<br/></p>
<p>On the shortlist announcement, Richard said:<br/></p>
<p><i>“It’s wonderful to be shortlisted for my role in a project that was so meaningful to both Unboxed Consulting and Plymouth University. We instilled “The Unboxed Way” to deliver this Agile project, pioneering how Agile is supposed to be done.”</i><br/></p>
<p>The UK Agile Awards take place on 20th November 2014 at The Bloomsbury Ballroom, London.</p>
|
C | UTF-8 | 2,894 | 3.5 | 4 | [] | no_license | // a_pipe.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <wait.h>
int main (int argc,char *argv[]) {
int i;
char* arguments1 [] = { "ls", "-la", 0 };
char* arguments2 [] = { "grep", "ejemplo", 0 };
char* arguments3 [] = { "wc", "-l", 0 };
int fildes[2];
int fildes2[2]; //Variable per a la segona tuberia
pid_t pid;
//Variable fd per a obrir el fitxer i obrirlo
int fd;
fd = open("result.txt",O_RDWR | O_CREAT,S_IRWXU);
// Parent process creates a FIRST pipe
if ((pipe(fildes)==-1)) {
fprintf(stderr,"Pipe failure \n");
exit(-1);
}
// Parent process creates a SECOND pipe
if ((pipe(fildes2)==-1)) {
fprintf(stderr,"Pipe failure \n");
exit(-1);
}
for (i=0;i<3;i++) {
pid=fork(); // Creates a child process
if ((pid==0) && (i==0)) {
// Child process redirects its output to the pipe
dup2 (fildes[1],STDOUT_FILENO);
// Child process closes pipe descriptors
close(fildes[0]);
close(fildes[1]);
close(fildes2[0]);
close(fildes2[1]);
close(fd);
// Child process changes its memory image
if ( execvp("ls",arguments1)<0) {
fprintf(stderr,"ls not found \n");
exit(-1);
}
} else if ((pid==0) && (i==1)) {
// Child process redirects its input to the pipe
dup2 (fildes[0],STDIN_FILENO);
dup2 (fildes2[1],STDOUT_FILENO);
// Child process closses pipe descriptors
close(fildes[0]);
close(fildes[1]);
close(fildes2[0]);
close(fildes2[1]);
close(fd);
// Child process changes its memory image
if (execvp("grep",arguments2)<0) {
fprintf(stderr,"grep not found \n");
exit(-1);
}
} else if ((pid==0) && (i==2)) {
// Child process redirects its input to the pipe
dup2 (fildes2[0],STDIN_FILENO);
dup2 (fd,STDOUT_FILENO);
// Child process closses pipe descriptors
close(fildes[0]);
close(fildes[1]);
close(fildes2[0]);
close(fildes2[1]);
close(fd);
// Child process changes its memory image
if (execvp("wc",arguments3)<0) {
fprintf(stderr,"wc not found \n");
exit(-1);
}
}
}
//Tancar el fitxer
close(fd);
// Parent process closes pipe descriptors
close(fildes[0]);
close(fildes[1]);
close(fildes2[0]);
close(fildes2[1]);
for (i = 0; i < 3; i++) wait(NULL);
return(0);
}
|
C# | UTF-8 | 4,873 | 2.59375 | 3 | [
"Unlicense"
] | permissive | using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace RémiMod
{
public class TcpServer
{
private const int BUFFER_SIZE = 16000;
private TcpListener tcpListener;
private List<TcpClient> tcpClients = new List<TcpClient>();
private Queue<string> messages = new Queue<string>();
public TcpServer(int port)
{
//Use IPAddress.Any for IPv4 only
tcpListener = new TcpListener(new IPEndPoint(IPAddress.IPv6Any, port));
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(HandleConnect, null);
}
private void HandleConnect(IAsyncResult ar)
{
try
{
ClientObject co = new ClientObject();
co.client = tcpListener.EndAcceptTcpClient(ar);
co.buffer = new byte[BUFFER_SIZE];
co.writePos = 0;
co.client.GetStream().BeginRead(co.buffer, co.writePos, co.buffer.Length - co.writePos, HandleRead, co);
}
catch (Exception e)
{
Debug.Log("Error accepting client: " + e);
}
tcpListener.BeginAcceptTcpClient(HandleConnect, null);
}
private void HandleRead(IAsyncResult ar)
{
ClientObject co = ar.AsyncState as ClientObject;
try
{
int readBytes = co.client.GetStream().EndRead(ar);
int oldWritePos = co.writePos;
co.writePos += readBytes;
if (readBytes == 0)
{
Debug.Log("Client disconnected");
return;
}
int newLineCopy = -1;
for (int i = oldWritePos; i < (oldWritePos + readBytes); i++)
{
if (newLineCopy == -1)
{
int offset = 0;
if (i > 1 && co.buffer[i - 1] == 13)
{
offset = 1;
}
if (co.buffer[i] == 10)
{
string newMessage = Encoding.UTF8.GetString(co.buffer, 0, i - offset);
lock (messages)
{
messages.Enqueue(newMessage);
}
//Message found, reset it back
newLineCopy = 0;
co.writePos = 0;
}
}
else
{
//Copy left over data to start of the array
co.buffer[newLineCopy] = co.buffer[i];
co.writePos++;
}
}
}
catch (Exception e)
{
Debug.Log("Error reading client: " + e);
return;
}
co.client.GetStream().BeginRead(co.buffer, co.writePos, co.buffer.Length - co.writePos, HandleRead, co);
}
public void Pump(Dictionary<Guid, Queue<VesselUpdate>> vesselUpdates)
{
lock (messages)
{
while (messages.Count > 0)
{
string currentMessage = messages.Dequeue();
int firstSpace = currentMessage.IndexOf(' ');
string command = currentMessage.Substring(0, firstSpace);
string data = currentMessage.Substring(firstSpace + 1);
switch (command)
{
case "TIME":
double universeTime = double.Parse(data);
Planetarium.SetUniversalTime(universeTime);
break;
case "ORBIT":
string[] orbitDataString = data.Split(' ');
double[] orbitData = new double[6];
for (int i = 0; i < 6; i++)
{
orbitData[i] = double.Parse(orbitDataString[i]);
}
break;
case "POS":
string[] postDataString = data.Split(' ');
double[] posData = new double[6];
for (int i = 0; i < 6; i++)
{
posData[i] = double.Parse(postDataString[i]);
}
break;
}
}
}
}
}
}
|
Markdown | UTF-8 | 812 | 2.625 | 3 | [] | no_license | ### MongoDB
#### Download Docker for MongoDB
`docker pull mongo`
#### Run Docker for MongoDB (using port 27017, name mongo)
`docker run -d -p 27017:27017 --name mongo mongo`
#### Run MongoShell on Docker Instance
`docker exec -it mongo bash`
`mongo`
#### Execute MongoShell Commands
`show dbs`
`use local`
`db.startup_log.count();`
### Accessing Data with MongoDB and Spring
#### Tutorial for Spring and MongoDB
https://spring.io/guides/gs/accessing-data-mongodb/
#### Download Example
Export src/main/java/hello/* to src/main/java/customer/* and pom.xml
#### Build and Run Exmample
`mvn clean install`
`mvn spring-boot:run `
` -Dspring.data.mongodb.uri=mongodb://localhost:27017/customer`
#### Check Data in MongoDB
`docker exec -it mongo bash`
`mongo`
`use customer`
`db.customer.find()`
|
C++ | UTF-8 | 3,842 | 3.140625 | 3 | [] | no_license | #include "sceneHandler.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include "Background.h"
#include "ScreenRoot.h"
#include "Creature.h"
#include "Thing.h"
std::vector<std::string>& split(const std::string& str, char delim, std::vector<std::string>& elems )
{
std::stringstream ss(str+' ');
std::string item;
while(std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
///^^^copied shamelessly from stackoverflow, splits first argument according to second argument and puts the elements into third argument
///could be rewritten into void form
className strToClass(std::string x)
{
if(x == "Background") return Background_enum;
else if(x == "Creature") return Creature_enum;
else if(x == "Thing") return Thing_enum;
else if(x == "FixedGround") return FixedGround_enum;
else return Background_enum;///will never execute unless file is written incorrectly, could be reformatted into error handling
}
///^^^convert a string into the corresponding enum type
///used for a switch() in the file loader function
void loadSceneFromFile(std::string inputFileLocation)
{
ScreenRoot::access().wipeRoot();
//std::cout << inputFileLocation;
std::ifstream inputFile(inputFileLocation);
std::string inputString;
//getline(inputFile,inputString);
//std::cout << inputString;
//std::cout << "jenfjenf";
getline(inputFile,inputString);
while(inputString != "END")
{
std::vector<std::string> objectData;
split(inputString,';',objectData);
//std::cout << objectData[0];
switch(strToClass(objectData[0]))
{
case Background_enum:
{
std::string image = objectData[1];
int x = stoi(objectData[2]); ///conversion from string to integer, mingw needs patching in order to work
int y = stoi(objectData[3]);
int z = stoi(objectData[4]);
float ratio_x = stof(objectData[5]);
Background* background = new Background(image.c_str(),x,y,z,ratio_x);
(ScreenRoot::access()).addBackground(background);
}
break;
case Creature_enum:
{
std::string image = objectData[1];
int x = stoi(objectData[2]);
int y = stoi(objectData[3]);
int z = stoi(objectData[4]);
int height = stoi(objectData[5]);
int width = stoi(objectData[6]);
Creature* creature = new Creature(image.c_str(),x,y,z,height,width);
(ScreenRoot::access()).addStaticSo(creature);
}
break;
case Thing_enum:
{
std::string image = objectData[1];
int x = stoi(objectData[2]);
int y = stoi(objectData[3]);
int depth = stoi(objectData[4]);
Thing* thing = new Thing(image.c_str(),x,y,depth);
(ScreenRoot::access()).addStaticSo(thing);
}
break;
case FixedGround_enum:
{
std::string image = objectData[1];
int x = stoi(objectData[2]);
int y = stoi(objectData[3]);
int z = stoi(objectData[4]);
int width = stoi(objectData[5]);
int height = stoi(objectData[6]);
FixedGround* theGround = new FixedGround(image.c_str(),x,y,z,width,height);
(ScreenRoot::access()).addFixedGround(theGround); ///this is for the initialization of the protagonist
(ScreenRoot::access()).addStaticSo(theGround);
}
break;
}
getline(inputFile,inputString);
}
}
|
Python | UTF-8 | 798 | 4 | 4 | [] | no_license | import math
def split_check(total, num_of_people):
if num_of_people <= 1: # Make condition if there is not a single person to split the check
raise ValueError('More than 1 person is required to split the check')
cost_per_person = math.ceil(total / num_of_people)
return cost_per_person
try:
total_due = float(input('what is the total '))
num_of_people = int(input('How many people: '))
amount_due = split_check(total_due, num_of_people)
except ValueError as error: # create the new variable called error
print("that's not the correct value. Try again...")
# If there is not a single person to split a check
print('There is no such thing as 0 people')
else:
print("Each person owes {} rupees".format(amount_due))
|
C++ | UTF-8 | 987 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<math.h>
using namespace std;
int main(){
// Write your code here
vector<bool> prime(101,true);
prime[0]=false;
prime[1]=false;
for(int i=2;i<=sqrt(100);i++){
if(prime[i]){
for(int j=i*i;j<=100;j=j+i){
prime[j]=false;
}
}
}
vector<int> cubeFreeNumber(1000001,0);
for(int i=2;i<=100;i++){
if(prime[i]){
for(int j=i*i*i;j<=1000000;j=j+i*i*i){
cubeFreeNumber[j]=-1;
}
}
}
int ans=1;
for(int i=1;i<=1000000;i++){
if(cubeFreeNumber[i]!=-1){
cubeFreeNumber[i]=ans;
ans++;
}
}
int t;
cin>>t;
for(int i=1;i<=t;i++){
int n;
cin>>n;
if(cubeFreeNumber[n]==-1){
cout<<"Case "<<i<<": Not Cube Free"<<endl;
}else{
cout<<"Case "<<i<<": "<<cubeFreeNumber[n]<<endl;
}
}
return 0;
} |
Python | UTF-8 | 286 | 3.40625 | 3 | [] | no_license | #
# debug_2.py:
#
# L3-2: We'll run this in the PyCharm debugger to understand print()'s behavior...
#
result = ''
starting = input ("Enter a string: ")
for ch in starting:
print (ch,end='')
print() # needed to dump string accumulating in output print buffer before program ends
|
Java | UTF-8 | 482 | 3.25 | 3 | [] | no_license | package com.liar.basic;
import java.util.Arrays;
import java.util.Scanner;
/**
* 数组排序
*/
public class Sort {
public static void main(String[] args) {
Scanner sr = new Scanner(System.in);
int n=sr.nextInt();
int[] arr=new int[n];
for (int i=0;i<n;i++) {
arr[i]=sr.nextInt();
}
Arrays.sort(arr);
for (int i:arr) {
System.out.print(i);
System.out.print(" ");
}
}
}
|
JavaScript | UTF-8 | 916 | 3.375 | 3 | [] | no_license |
var NewCard = function(arg1, arg2){
var self = this;
self.name = "thisCard" + arg1;
console.log("new card object");
var maxSets = array.length;
var hasElement = false;
while (hasElement == false){
self.set = Math.round(Math.random() * maxSets);
self.value = array[self.set];
if (self.value == null){
// do nothing
} else {
var total = newArray1.push(self.value);
array[self.set] = null;
hasElement = true;
}
}
self.image = document.createElement("IMG");
self.image.src = "images/" + self.set + ".jpg";
document.getElementById('cardDiv').appendChild(self.image);
console.log(array);
console.log(newArray1);
// console.log(newArray2);
// console.log(removed);
}
var maxCards = 20;
// var maxSets = (maxCards/2)-1;
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newArray1 = [];
// var newArray2 = [];
for (var i = 0; i<maxCards; i++){
var card = new NewCard(i, maxCards);
}
|
Java | UTF-8 | 1,295 | 2.0625 | 2 | [] | no_license | package com.renrentui.renrenapi.dao.impl;
import org.springframework.stereotype.Repository;
import com.renrentui.renrenapi.common.DaoBase;
import com.renrentui.renrenapi.dao.inter.IOrderLogDao;
import com.renrentui.renrenentity.OrderLog;
@Repository
public class OrderLogDao extends DaoBase implements IOrderLogDao{
@Override
public int deleteByPrimaryKey(Long id) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insert(OrderLog record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insertSelective(OrderLog record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public OrderLog selectByPrimaryKey(Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public int updateByPrimaryKeySelective(OrderLog record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int updateByPrimaryKey(OrderLog record) {
// TODO Auto-generated method stub
return 0;
}
/**
* 记录订单表操作日志
* 操作类型:1抢单2提交审核3重复提交审核4取消订单5超时取消(系统)
*/
@Override
public int addOrderLog(OrderLog log) {
return getMasterSqlSessionUtil().insert("com.renrentui.renrenapi.dao.inter.IOrderLogDao.addOrderLog", log);
}
}
|
Java | WINDOWS-1250 | 2,002 | 2.28125 | 2 | [] | no_license | package br.com.planejamentoagro.controller;
import br.com.planejamentoagro.R;
import br.com.planejamentoagro.helper.DiretoriosHelper;
import br.com.planejamentoagro.helper.FormularioClienteHelper;
import br.com.planejamentoagro.model.Cliente;
import br.com.planejamentoagro.model.dao.ClienteDAO;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class EditaCliente extends Activity{
private FormularioClienteHelper helperCliente;
private int idCliente;
private String nomeCliente;
private ClienteDAO clienteDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulario_cliente);
helperCliente = new FormularioClienteHelper(this);
Cliente cliente = (Cliente) getIntent().getSerializableExtra("CLIENTE_SELECIONADO");
if (cliente != null)
{
helperCliente.setCliente(cliente);
idCliente = cliente.getId();
nomeCliente = cliente.getNome();
}
clienteDAO = new ClienteDAO(EditaCliente.this);
}
public void salvarCliente()
{
Cliente cliente = helperCliente.getCliente();
if(!cliente.getNome().equals(""))
{
cliente.setId(idCliente);
clienteDAO.editar(cliente);
clienteDAO.fecharConexao();
DiretoriosHelper.renameFile(InformacoesTecnicas.CAMINHO_IMAGENS+nomeCliente,InformacoesTecnicas.CAMINHO_IMAGENS+cliente.getNome());
finish();
}else Toast.makeText(getApplicationContext(), "Nome cliente obrigatrio.", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.cadastra_cliente, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_save) {
salvarCliente();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Python | UTF-8 | 239 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | import random
import string
def random_port():
return random.randint(1024, 65536)
def random_string(k=5):
return ''.join(random.choices(string.ascii_lowercase, k=k))
def random_int(a=0, b=10):
return random.randint(a, b)
|
Python | UTF-8 | 288 | 2.5625 | 3 | [] | no_license | x=[-4,1,2,3,4,50,0]
a = sum([v>0 for v in x if v!=0])
b = [i for i in range(len(x)) if x[i]!=0]
c = [v for v in x if (v in range(-3,50))]
d = max([v for v in x if v%3 == 0])
e = sum([v for v in x if v > 10])/len([v for v in x if v > 10])
f = [i for i in range(len(x)) if x[i] == min(x)]
|
Markdown | UTF-8 | 7,962 | 2.859375 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
keywords: powershell,cmdlet
ms.date: 10/04/2019
online version: https://learn.microsoft.com/previous-versions/powershell/module/microsoft.powershell.core/about/about_prompts?view=powershell-3.0&WT.mc_id=ps-gethelp
schema: 2.0.0
title: about_Prompts
---
# About Prompts
## Short description
Describes the `Prompt` function and demonstrates how to create a custom
`Prompt` function.
## Long description
The PowerShell command prompt indicates that PowerShell is ready to run a
command:
```
PS C:\>
```
The PowerShell prompt is determined by the built-in `Prompt` function. You can
customize the prompt by creating your own `Prompt` function and saving it in
your PowerShell profile.
## About the Prompt function
The `Prompt` function determines the appearance of the PowerShell prompt.
PowerShell comes with a built-in `Prompt` function, but you can override it by
defining your own `Prompt` function.
The `Prompt` function has the following syntax:
```powershell
function Prompt { <function-body> }
```
The `Prompt` function must return an object. As a best practice, return a
string or an object that is formatted as a string. The maximum recommended
length is 80 characters.
For example, the following `Prompt` function returns a "Hello, World" string
followed by a right angle bracket (`>`).
```powershell
PS C:\> function prompt {"Hello, World > "}
Hello, World >
```
### Getting the Prompt function
To get the `Prompt` function, use the `Get-Command` cmdlet or use the
`Get-Item` cmdlet in the Function drive.
For example:
```powershell
PS C:\> Get-Command Prompt
CommandType Name ModuleName
----------- ---- ----------
Function prompt
```
To get the script that sets the value of the prompt, use the dot method to get
the **ScriptBlock** property of the `Prompt` function.
For example:
```powershell
(Get-Command Prompt).ScriptBlock
```
```Output
"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
# .Link
# https://go.microsoft.com/fwlink/?LinkID=225750
# .ExternalHelp System.Management.Automation.dll-help.xml
```
Like all functions, the `Prompt` function is stored in the `Function:` drive.
To display the script that creates the current `Prompt` function, type:
```powershell
(Get-Item function:prompt).ScriptBlock
```
### The default prompt
The default prompt appears only when the `Prompt` function generates an error
or does not return an object.
The default PowerShell prompt is:
```
PS>
```
For example, the following command sets the `Prompt` function to `$null`, which
is invalid. As a result, the default prompt appears.
```powershell
PS C:\> function prompt {$null}
PS>
```
Because PowerShell comes with a built-in prompt, you usually do not see the
default prompt.
### Built-in prompt
PowerShell includes a built-in `Prompt` function.
```powershell
function prompt {
$(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
else { '' }) + 'PS ' + $(Get-Location) +
$(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}
```
The function uses the `Test-Path` cmdlet to determine whether the
`$PSDebugContext` automatic variable is populated. If `$PSDebugContext` is
populated, you are in debugging mode, and `[DBG]:` is added to the prompt, as
follows:
```Output
[DBG]: PS C:\ps-test>
```
If `$PSDebugContext` is not populated, the function adds `PS` to the prompt.
And, the function uses the `Get-Location` cmdlet to get the current file system
directory location. Then, it adds a right angle bracket (`>`).
For example:
```Output
PS C:\ps-test>
```
If you are in a nested prompt, the function adds two angle brackets (`>>`) to
the prompt. (You are in a nested prompt if the value of the
`$NestedPromptLevel` automatic variable is greater than 1.)
For example, when you are debugging in a nested prompt, the prompt resembles
the following prompt:
```Output
[DBG] PS C:\ps-test>>>
```
### Changes to the prompt
The `Enter-PSSession` cmdlet prepends the name of the remote computer to the
current `Prompt` function. When you use the `Enter-PSSession` cmdlet to start a
session with a remote computer, the command prompt changes to include the name
of the remote computer. For example:
```Output
PS Hello, World> Enter-PSSession Server01
[Server01]: PS Hello, World>
```
Other PowerShell host applications and alternate shells might have their own
custom command prompts.
For more information about the `$PSDebugContext` and `$NestedPromptLevel`
automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md).
### How to customize the prompt
To customize the prompt, write a new `Prompt` function. The function is not
protected, so you can overwrite it.
To write a `Prompt` function, type the following:
```powershell
function prompt { }
```
Then, between the braces, enter the commands or the string that creates your
prompt.
For example, the following prompt includes your computer name:
```powershell
function prompt {"PS [$env:COMPUTERNAME]> "}
```
On the Server01 computer, the prompt resembles the following prompt:
```Output
PS [Server01] >
```
The following `Prompt` function includes the current date and time:
```powershell
function prompt {"$(Get-Date)> "}
```
The prompt resembles the following prompt:
```Output
03/15/2012 17:49:47>
```
You can also change the default `Prompt` function:
For example, the following modified `Prompt` function adds `[ADMIN]:` to the
built-in PowerShell prompt when PowerShell is opened by using the
**Run as administrator** option:
```powershell
function prompt {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal] $identity
$(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
elseif($principal.IsInRole([Security.Principal.WindowsBuiltInRole]
"Administrator")) { "[ADMIN]: " }
else { '' }
) + 'PS ' + $(Get-Location) +
$(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}
```
When you start PowerShell by using the **Run as administrator** option, a
prompt that resembles the following prompt appears:
```Output
[ADMIN]: PS C:\ps-test>
```
The following `Prompt` function displays the history ID of the next command. To
view the command history, use the `Get-History` cmdlet.
```powershell
function prompt {
# The at sign creates an array in case only one history item exists.
$history = @(Get-History)
if($history.Count -gt 0)
{
$lastItem = $history[$history.Count - 1]
$lastId = $lastItem.Id
}
$nextCommand = $lastId + 1
$currentDirectory = Get-Location
"PS: $nextCommand $currentDirectory >"
}
```
The following prompt uses the `Write-Host` and `Get-Random` cmdlets to create a
prompt that changes color randomly. Because `Write-Host` writes to the current
host application but does not return an object, this function includes a
`Return` statement. Without it, PowerShell uses the default prompt, `PS>`.
```powershell
function prompt {
$color = Get-Random -Min 1 -Max 16
Write-Host ("PS " + $(Get-Location) +">") -NoNewLine `
-ForegroundColor $Color
return " "
}
```
### Saving the Prompt function
Like any function, the `Prompt` function exists only in the current session. To
save the `Prompt` function for future sessions, add it to your PowerShell
profiles. For more information about profiles, see [about_Profiles](about_Profiles.md).
## See also
[Get-Location](xref:Microsoft.PowerShell.Management.Get-Location)
[Enter-PSSession](xref:Microsoft.PowerShell.Core.Enter-PSSession)
[Get-History](xref:Microsoft.PowerShell.Core.Get-History)
[Get-Random](xref:Microsoft.PowerShell.Utility.Get-Random)
[Write-Host](xref:Microsoft.PowerShell.Utility.Write-Host)
[about_Profiles](about_Profiles.md)
[about_Functions](about_Functions.md)
[about_Scopes](about_Scopes.md)
[about_Debuggers](about_Debuggers.md)
[about_Automatic_Variables](about_Automatic_Variables.md)
|
Java | UTF-8 | 1,052 | 2.953125 | 3 | [] | no_license | //https://www.hackerrank.com/challenges/common-child/
public class CommonChild {
public static void main(String[] args) {
System.out.println(solve("ABCD", "ABDC"));
System.out.println(solve("HARRY", "SALLY"));
System.out.println(solve("SHINCHAN", "NOHARAAA"));
System.out.println(solve("FDAGCXGKCTKWNECHMRXZWMLRYUCOCZHJRRJBOAJOQJZZVUYXIC", "WEWOUCUIDGCGTRMEZEPXZFEJWISRSBBSYXAYDFEJJDLEBVHHKS"));
System.out.println(solve("APMCTKBUKYRGZPAUVZEBVUXRGDVITOYXWQWRVCSXESMEHQLHPDJQWETAWQVSBRRNRRFDLFTRXOTKQHFTYAZSGBORDNAMUAJTPVOKERLVOLEALDQQLUDCUIRXJHQEZBRWYPFJXNTPELEZHNJILIZVZLYQJDFYSYQNRFFAOYXHQBQVRLFDIIOGWKQIZGVELYOUKZBKMHVYGIKIPSEMWSCWYOJTHOQKMLBAIZYNAKYNCXKDTTESODDAEAHKCDHCJYAHERACMLYQHXIRDFUSRTZDNVHSYFKCSPPYSLHOGIBTNUJTZQWVTHKUNDNWZADMATSUXEISCACQNQXIHNTXGCZUGIGBDONYTUXAXFINAYGZJVDCTZCWPGFNQDPERUCNJUXIFDSQHULYPZRNUOKMLMMQAJMLKCHJMEFJVRYZIPFQOBSDPAITHGMNKROCWJEGESCGOIUOQHOYUEQNPJPBMCNRZUHOSQNSUNCSTVQVWFGMUFJZGMEUVUPH", "JUVSDRRSHFGSSLLLZEPJDVAWDPKQBKUHHOZFFXKQMGAACZUYOMNPHWGTYZWQGSMNYXWNFYNOIVVMPZXUNKJQYBYJINBOHXUWIVRTVLEKCOPDMTKTGDBWECDAVPMLHQLERZHDVZJZODPSAPGSRWJXNGFEBQBLTLNDIEGFHEGHJWFOIYXRUJMODSNXUFWBIJJMXTFMUKQEYPNBTZFEJNLDNWCGQLVUQUKGZHJOKZNPMUYEQLEYNNORKJQAMSTHTBCCPQTTCPRZATWNJQJXPODRXKIWDOFUBZVSDTAPFRMXJBJMUGVRZOCDUIPXVEGMRQNKXDKNWXMTNDJSETAKVSYMJISAREEJPLRABMXJSRQNASOJNEEVAMWCFJBCIOCKMHCMYCRCGYFNZKNALDUNPUSTSWGOYHOSWRHWSMFGZDWSBXWXGVKQPHGINRKMDXEVTNNZTBJPXYNAXLWZSBUMVMJXDIKORHBIBECJNKWJJJSRLYQIKKPXSNUT"));
}
private static int solve(String a, String b) {
char ac[] = a.toCharArray();
char bc[] = b.toCharArray();
int len = a.length();
int dp[][] = new int[len+1][len+1];
for(int i = 1; i <= len; i++) {
for(int j = 1; j <= len; j++) {
if(bc[i-1] == ac[j-1]){
dp[i][j] = dp[i-1][j-1] +1;
} else {
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
}
}
}
return dp[len][len];
}
}
|
PHP | UTF-8 | 486 | 3.453125 | 3 | [] | no_license | <?php
/*改行*/
$br = "<br />";
/*$x=3*/
$x = 3;
/*$y=4*/
$y = 4;
/*数値の大小を比較する*/
/*条件分岐1*/
if( $x>$y ){
echo "TRUE" . $br;
} else {
echo "FALSE" . $br;
}
/*条件分岐2*/
if( $x<$y ){
echo "TRUE" . $br;
} else {
echo "FALSE" . $br;
}
/*条件分岐3*/
if( $x>=$y ){
echo "TRUE" . $br;
} else {
echo "FALSE" . $br;
}
/*条件分岐4*/
if( $x<=$y ){
echo "TRUE" . $br;
} else {
echo "FALSE" . $br;
}
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.