language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 4,687 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
package praktomatTask1;
import java.util.*;
public class TOHSolution {
private static int numOfDiscs = 0, numOfMoves = 0, numOfDiscs_Post1 = 0, numOfDiscs_Post2 = 0, numOfDiscs_Post3 = 0;
private static Stack<Integer> post_1 = new Stack<Integer>();
private static Stack<Integer> post_2 = new Stack<Integer>();
private static Stack<Integer> post_3 = new Stack<Integer>();
public static void main (String[] args) {
try {
numOfDiscs = Integer.parseInt(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
if (numOfDiscs <= 1 || numOfDiscs >= 10) {
System.out.println ("Minimum number of discs to play is 2. Maximum number of discs to play is 9. To play, please enter a number between 2 and 9.");
return;
}
int i = numOfDiscs;
while (i >= 1) {
post_1.push(i--);
}
numOfDiscs_Post1 = post_1.size();
numOfDiscs_Post2 = post_2.size();
numOfDiscs_Post3 = post_3.size();
output();
play (numOfDiscs, post_1, post_2, post_3);
System.out.println ( "Number of moves made is " + numOfMoves );
while (post_3.size() > 0) {
post_3.pop();
}
}
private static int play (int numOfDiscs, Stack<Integer> from, Stack<Integer> intermediate, Stack<Integer> to) {
if (numOfDiscs <= 4) {
if ((numOfDiscs % 2) == 0) {
simplePlay (from, intermediate, to);
numOfDiscs = numOfDiscs - 1;
if (numOfDiscs == 1) {
return 1;
}
intermediate.push (from.pop());
numOfMoves++;
output();
simplePlay (to, from, intermediate);
to.push (from.pop());
numOfMoves++;
output();
play (numOfDiscs, intermediate, from, to);
} else {
if (numOfDiscs == 1) {
return -1;
}
simplePlay (from, to, intermediate);
numOfDiscs = numOfDiscs - 1;
to.push ( from.pop() );
numOfMoves++;
output();
simplePlay (intermediate, from, to);
}
return 1;
} else if (numOfDiscs >= 5) {
play(numOfDiscs - 2, from, intermediate, to);
intermediate.push (from.pop());
numOfMoves++;
output();
play(numOfDiscs - 2, to, from, intermediate);
to.push (from.pop());
numOfMoves++;
output();
play(numOfDiscs - 1, intermediate, from, to);
}
return 1;
}
private static void simplePlay (Stack<Integer> from, Stack<Integer> intermediate, Stack<Integer> to) {
intermediate.push(from.pop());
numOfMoves++;
output();
to.push(from.pop());
numOfMoves++;
output();
to.push(intermediate.pop());
numOfMoves++;
output();
}
private static void output() {
if (numOfDiscs_Post1 != post_1.size() || numOfDiscs_Post2 != post_2.size() || numOfDiscs_Post3 != post_3.size()) {
int delta_1 = post_1.size() - numOfDiscs_Post1;
int delta_2 = post_2.size() - numOfDiscs_Post2;
if (delta_1 == 1) {
if (delta_2 == -1) {
System.out.print ("Move Disc " + post_1.peek() + " from Post 2 to Post 1");
} else {
System.out.print ("Move Disc " + post_1.peek() + " from Post 3 to Post 1");
}
} else if ( delta_2 == 1 ) {
if ( delta_1 == -1 ) {
System.out.print ("Move Disc " + post_2.peek() + " from Post 1 to Post 2");
} else {
System.out.print ("Move Disc " + post_2.peek() + " from Post 3 to Post 2");
}
} else {
if ( delta_1 == -1 ) {
System.out.print ("Move Disc " + post_3.peek() + " from Post 1 to Post 3");
} else {
System.out.print ("Move Disc " + post_3.peek() + " from Post 2 to Post 3");
}
}
numOfDiscs_Post1 = post_1.size();
numOfDiscs_Post2 = post_2.size();
numOfDiscs_Post3 = post_3.size();
System.out.println();
}
System.out.print(post_1.toString() + " : ");
System.out.print(post_2.toString() + " : ");
System.out.print(post_3.toString() + " -> ");
}
}
|
C
|
UTF-8
| 5,519 | 2.90625 | 3 |
[] |
no_license
|
/*
Example for Secure_2 Click
Date : Jul 2017.
Author : Djordje Rosic
Test configuration KINETIS :
MCU : MK64
Dev. Board : HEXIWEAR
ARM Compiler ver : v5.1.0.0
Description :
Following example demonstrates sending commands to Secure 2 click using
ATAES132 Library.
It shows correct initialization of the device, as well as three sample
functions that can be used to test the device without locking it.
All advanced operation requires the configuration zone of the device to be
locked. This is irreversible, so it is not included in the basic example.
Function "additionalTests", that is commented out, shows how to lock the
config zone, and contains additional test function that outputs a random
number.
All output is via USB UART, turn on the required switches on the board.
*/
#include <stdint.h>
#include "aes132_comm_marshaling.h"
#include "__SECURE2_Driver.h"
#define LOG(x) UART0_Write_Text(x)
static void outputHex (uint8_t * pOutput, uint8_t length);
static void additionalTests ();
uint8_t txBuffer[84];
uint8_t rxBuffer[36];
uint8_t inputBuffer [16];
/*
System Initialization
Initializes UART output and I2C connection.
*/
void systemInit()
{
UART0_Init(9600);
I2C0_Init_Advanced( 100000, &_GPIO_Module_I2C0_PD8_9 );
LOG ("\r\nInitialized");
delay_ms (100);
}
/*
Secure 2 Initialization
Initializes driver and sets buffer to 0.
*/
void Secure_2_Init()
{
SECURE2_I2CdriverInit( I2C0_Start, 0, 0, I2C0_Write, I2C0_Read);
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
//This function resets the address pointer, in case there was an error
aes132c_reset_io_address ();
}
void main()
{
systemInit();
Secure_2_Init();
LOG( "\r\nStarting device testing...\r\n" );
//First test - Reading serial number
if (aes132m_execute(AES132_BLOCK_READ, 0x00, 0xF000, 0x0008,
0, 0, 0, 0, 0, 0, 0, 0, txBuffer, rxBuffer)
== AES132_FUNCTION_RETCODE_SUCCESS)
{
LOG( "\r\n Serial number: " );
outputHex (&rxBuffer[2], 8);
}
else LOG( "\r\n Reading serial number failed..." );
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
//Second test - Reading device info
delay_ms (1500);
if (aes132m_execute(AES132_INFO, 0x00, 0x0006, 0x0000,
0, 0, 0, 0, 0, 0, 0, 0, txBuffer, rxBuffer)
== AES132_FUNCTION_RETCODE_SUCCESS)
{
LOG( "\r\n\r\n Device num register: " );
outputHex (&rxBuffer[2], 2);
}
else LOG( "\r\n\r\n Reading device information..." );
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
//Third test - Crunch function for a given input
delay_ms (1500);
memset (inputBuffer, 42, 16);
if (aes132m_execute(AES132_CRUNCH, 0x00, 0x0001, 0x0000,
16, inputBuffer, 0, 0, 0, 0, 0, 0, txBuffer, rxBuffer)
== AES132_FUNCTION_RETCODE_SUCCESS)
{
LOG( "\r\n\r\n Crunch operation output: " );
outputHex (&rxBuffer[2], 16);
LOG( "\r\n Expected Crunch output: 7A 78 A9 7D 27 47 90 7D ");
LOG("7A A6 20 5B 14 AB 58 73");
}
else LOG( "\r\n\r\n Crunch operation failed.." );
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
/*
IMPORTANT: Uncommenting these lines permanently locks the config zone of the
device.
This is irreversible, so make sure configuration is set according to your
needs. All the following tests won't work unless config zone is locked.
additionalTests ();
*/
LOG( "\r\n\r\n--------------------------------------------" );
LOG( "\r\nEND" );
}
/*
IMPORTANT: Following functions permanently lock the config zone of the
device. Do not use them if you are not sure what you're doing.
This function WILL LOCK THE CONFIG ZONE. After that it will generate a
random number, and output it.
*/
static void additionalTests ()
{
//Configuration zone locking
if (aes132m_execute(AES132_LOCK, 0x02, 0x0000, 0x0000,
0, 0, 0, 0, 0, 0, 0, 0, txBuffer, rxBuffer)
== AES132_FUNCTION_RETCODE_SUCCESS)
{
LOG( "\r\n\r\n Configuration zone locked! " );
}
else
{
LOG( "\r\n\r\n Configuration zone locking failed" );
LOG( " or it is already locked." );
}
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
/*
Fourth test - Random number generator
Will only return 0xA5 unless config zone is locked first.
*/
if (aes132m_execute(AES132_RANDOM, 0x00, 0x0000, 0x0000,
0, 0, 0, 0, 0, 0, 0, 0, txBuffer, rxBuffer)
== AES132_FUNCTION_RETCODE_SUCCESS)
{
LOG( "\r\n\r\n Generated random number: " );
outputHex (&rxBuffer[2], 16);
}
else LOG( "\r\n\r\n Random number generation failed..." );
memset (txBuffer, 0, 84);
memset (rxBuffer, 0, 36);
}
//Help function for outputing data in hex format
static void outputHex (uint8_t * pOutput, uint8_t length)
{
uint8_t i;
char text [10];
for( i = 0; i < length; i++ )
{
ByteToHex( pOutput[ i ], text );
LOG( Ltrim(text) );
LOG( " " );
}
}
|
Python
|
UTF-8
| 693 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
"""
Client Class
"""
import socket
import json
# localhost, free port (> 1023)
HOST, PORT = '127.0.0.1', 1234
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(str.encode('Hello, World'))
data1 = s.recv(1024)
orig_list = [1, 2, 3]
l_string = json.dumps(orig_list)
s.sendall(str.encode(l_string))
data2 = s.recv(1024)
l_list = json.loads(data2)
print('Received:', repr(data1))
print('Received:', repr(data2))
print('orig_list:', orig_list)
print('orig_list type:', type(orig_list))
print('l_string:', l_string)
print('l_string type:', type(l_string))
print('l_list:', l_list)
print('l_list type:', type(l_list))
|
Shell
|
UTF-8
| 291 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
set -e
docker build -f "$DOCKERFILE_PATH" -t $DOCKER_REPO:${DOCKER_TAG//,/ -t $DOCKER_REPO:} . \
--build-arg "build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")" \
--build-arg "vcs_ref=$SOURCE_COMMIT" \
--build-arg "image_version=$SOURCE_BRANCH"
|
Python
|
UTF-8
| 1,747 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
"""
Sample code to test timely3
"""
import time
from pprint import pprint
from timely3 import timely3
import timely3 as timely3_module
import logging
log = logging.getLogger('timely3/simple')
logging.basicConfig(
format='[%(name)s:%(lineno)s][%(levelname)s] %(message)s',
level=logging.DEBUG,
)
log.setLevel(logging.DEBUG)
# Import after logger setup
from example_module.example_submodule import ( # noqa: E402
func_from_pkg_01,
func_from_pkg_02,
)
def func01():
"""
Func with timed block
"""
with timely3('deepest_block'):
time.sleep(0.1)
@timely3()
def func02():
"""
decorated function
"""
time.sleep(0.2)
@timely3('super_duper')
def func03():
"""
decorated function with custom scope name
"""
time.sleep(0.3)
if __name__ == "__main__":
assert timely3.sw.count == 0
assert timely3.sw.duration_total == 0
with timely3():
func01()
func02()
func03()
for _ in range(3):
func01()
func_from_pkg_01()
func_from_pkg_02()
assert timely3.sw.count == 0
assert timely3.sw.duration_total == 0
with timely3('second_top_level') as t1:
assert t1.stack.len() == 1
with timely3('sub_level') as t2:
assert t1.stack.len() == 2
assert t2.stack.len() == 2
for _ in range(4):
func02()
assert timely3.sw.count == 0
assert timely3.sw.duration_total == 0
assert len(t2.journal) == 0
# report
# as module-level function
pprint(timely3_module.report())
# as method
pprint(timely3().report()) # bad idea since add new scope
# as staticmethod
pprint(timely3.report())
|
Markdown
|
UTF-8
| 7,174 | 2.90625 | 3 |
[] |
no_license
|
---
title: "GPIO Character Device"
layout: post
comments: true
date: 2021-03-11 14:24
image:
headerImage:
tag:
- Linux
- GPIO
star: false
category: Linux
author: jihun
---
<!-- more -->
# Overview
The GPIO character device has been implemented since kernel 4.8. It will be replaces *sysfs*(`CONFIG_GPIO_SYSFS`) gpio interface.
> The user interface using the ABI based on the sysfs will be deprecated.
In additional, Discovery mechanism(It doesn't use magic numbers) is applied, and gpio pin control is possible through `ioctl()` (`/dev/gpiochip#`).
# Usage in User Application
## Getting Information
### `gpiochip` information
*name*, *label*, and *line number* of gpiochip are retrieved and shown.
```cpp
int chip_info(int fd)
{
struct gpiochip_info cinfo;
int ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &cinfo);
if (ret < 0) {
printf("GPIO_GET_CHIPINFO_IOCTL failed.\n");
return -1;
}
printf("GPIO chip: %s, \"%s\", %u GPIO lines\n",
cinfo.name, cinfo.label, cinfo.lines);
return 0;
}
```
### GPIO line information
Retrieves the line name specified by the requested gpio number.
```cpp
int line_info(int fd, int gpio)
{
int ret;
struct gpioline_info linfo;
memset(&linfo, 0, sizeof(linfo));
linfo.line_offset = gpio;
ret = ioctl(fd, GPIO_GET_LINEINFO_IOCTL, &linfo);
if (ret < 0) {
printf("GPIO_GET_LINEINFO_IOCTL failed.\n");
return -errno;
}
printf("line %2d: %s\n", linfo.line_offset, linfo.name);
return fd;
}
```
## Access
### Request to use GPIO line
Set the line corresponding to the requested gpiochip number to the mode corresponding to the flag value. You can also specify a label name.
Flags
- GPIOHANDLE_REQUEST_INPUT
- GPIOHANDLE_REQUEST_OUTPUT
```cpp
int request_gpio(int fd, int gpio, int flags, const char *label, int *req_fd)
{
struct gpiohandle_request req;
int ret;
req.flags = flags;
req.lines = 1;
req.lineoffsets[0] = gpio;
req.default_values[0] = 0;
strcpy(req.consumer_label, label);
ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
if (ret < 0) {
printf("GPIO_GET_LINEHANDLE_IOCTL failed.\n");
return -1;
}
*req_fd = req.fd;
return 0;
}
```
### Read GPIO line
The value is read and printed from the line corresponding to the requested gpio number.
```cpp
int get_value(int req_fd, int gpio, int *value)
{
struct gpiohandle_data data;
int ret;
memset(&data, 0, sizeof(data));
ret = ioctl(req_fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
if (ret < 0) {
printf("GPIO_GET_LINE_VALUES_IOCTL failed.\n");
return -1;
}
printf("line %d is %s\n", gpio, data.values[0] ? "high" : "low");
*value = data.values[0];
return 0;
}
```
### Write GPIO line
Prints the value of the line corresponding to the requested gpio number.
```cpp
int set_value(int req_fd, int gpio, int value)
{
struct gpiohandle_data data;
int ret;
memset(&data, 0, sizeof(data));
data.values[0] = value;
ret = ioctl(req_fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
if (ret < 0) {
printf("GPIO_SET_LINE_VALUES_IOCTL failed.\n");
return -errno;
}
printf("line %d is %s\n", gpio, data.values[0] ? "high" : "low");
return 0;
}
```
## Event
### Request GPIO Event
Set the line corresponding to the requested gpio number to the input mode and prepare to receive events. In the this example, the pin is set to the open-drain and respond evenly to both of edges(rising and falling) events.
```cpp
int request_event(int fd, int gpio, const char *label, int *req_fd)
{
struct gpioevent_request req;
int ret;
req.lineoffset = gpio;
strcpy(req.consumer_label, label);
req.handleflags = GPIOHANDLE_REQUEST_OPEN_DRAIN;
req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE |
GPIOEVENT_REQUEST_FALLING_EDGE;
ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
if (ret < 0) {
printf("GPIO_GET_LINEEVENT_IOCTL failed.\n");
return -1;
}
*req_fd = req.fd;
return 0;
}
```
### Wait for GPIO Event
It wait for an event on the line corresponding to the requested gpio number.
```cpp
#define USE_POLL
int recv_event(int req_fd, int gpio)
{
struct gpioevent_data event;
struct pollfd pfd;
ssize_t rd;
int ret;
#ifdef USE_POLL
pfd.fd = req_fd;
pfd.events = POLLIN | POLLPRI;
rd = poll(&pfd, 1, 1000);
if (rd < 0) {
printf("poll failed.\n");
return -1;
}
#endif
ret = read(req_fd, &event, sizeof(event));
if (ret < 0) {
printf("read failed.\n");
return -1;
}
printf( "GPIO EVENT @%" PRIu64 ": ", event.timestamp);
if (event.id == GPIOEVENT_EVENT_RISING_EDGE)
printf("RISING EDGE");
else
printf("FALLING EDGE");
printf ("\n");
return 0;
}
```
# GPIO Tools
For more approaches, see the `tools/gpio` in the kernel directory
## lsgpio
it shows the gpio line name and usage status after opening the gpio controller device with the name `gpiochip#`.
```bash
GPIO chip: gpiochip0, "pinctrl-bcm2835", 54 GPIO lines
line 0: "[SDA0]" unused
line 1: "[SCL0]" unused
(...)
line 16: "STATUS_LED_N" unused
line 17: "GPIO_GEN0" unused
line 18: "GPIO_GEN1" unused
line 19: "NC" unused
line 20: "NC" unused
line 21: "CAM_GPIO" unused
line 22: "GPIO_GEN3" unused
line 23: "GPIO_GEN4" unused
line 24: "GPIO_GEN5" unused
line 25: "GPIO_GEN6" unused
line 26: "NC" unused
line 27: "GPIO_GEN2" unused
```
## gpio-hammer
```bash
$ gpio-hammer --help
gpio-hammer: invalid option -- '-'
Usage: gpio-hammer [options]...
Hammer GPIO lines, 0->1->0->1...
-n <name> Hammer GPIOs on a named device (must be stated)
-o <n> Offset[s] to hammer, at least one, several can be stated
[-c <n>] Do <n> loops (optional, infinite loop if not stated)
-? This helptext
Example:
gpio-hammer -n gpiochip0 -o 4
$ gpio-hammer -n gpiochip0 -o 5 -c 2
Hammer lines [5] on gpiochip0, initial states: [1]
[\] [5: 1]
```
## gpio-event-mon
```bash
$ gpio-event-mon --help
gpio-event-mon: invalid option -- '-'
Usage: gpio-event-mon [options]...
Listen to events on GPIO lines, 0->1 1->0
-n <name> Listen on GPIOs on a named device (must be stated)
-o <n> Offset to monitor
-d Set line as open drain
-s Set line as open source
-r Listen for rising edges
-f Listen for falling edges
[-c <n>] Do <n> loops (optional, infinite loop if not stated)
-? This helptext
Example:
gpio-event-mon -n gpiochip0 -o 4 -r -f
$ gpio-event-mon -n gpiochip0 -o 6 -r -c 2
Monitoring line 6 on gpiochip0
Initial line value: 1
GPIO EVENT 1527053280817909942: rising edge
GPIO EVENT 1527053282195388044: rising edge
```
# Reference
- [GPIO Subsystem -4- (new Interface)](http://jake.dothome.co.kr/gpio-4/)
|
Java
|
UTF-8
| 880 | 1.898438 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.event.discovery.agent.base.config;
import com.event.discovery.agent.framework.utils.IDGenerator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class DiscoveryConfig {
@Bean
@ConditionalOnMissingBean
public IDGenerator idGenerator() {
return new IDGenerator();
}
@Bean(name = "eventDiscoveryAgentTaskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("EDA-");
executor.setCorePoolSize(20);
return executor;
}
}
|
Markdown
|
UTF-8
| 15,746 | 3.59375 | 4 |
[] |
no_license
|
# ES6 In Depth: Modules
### By [Jason Orendorff](https://blog.mozilla.org/jorendorff/)
Posted on August 14, 2015 in [ES6 In Depth](https://hacks.mozilla.org/category/es6-in-depth/), [Featured Article](https://hacks.mozilla.org/category/featured/), and [JavaScript](https://hacks.mozilla.org/category/javascript/)
*[ES6 In Depth](https://hacks.mozilla.org/category/es6-in-depth/) is a series on new features being added to the JavaScript programming language in the 6th Edition of the ECMAScript standard, ES6 for short.*
When I started on Mozilla’s JavaScript team back in 2007, the joke was that the length of a typical JavaScript program was one line.
This was two years after Google Maps launched. Not long before that, the predominant use of JavaScript had been form validation, and sure enough, your average `<input onchange=>` handler would be… one line of code.
Things have changed. JavaScript projects have grown to jaw-dropping sizes, and the community has developed tools for working at scale. One of the most basic things you need is a module system, a way to spread your work across multiple files and directories—but still make sure all your bits of code can access one another as needed—but also be able to load all that code efficiently. So naturally, JavaScript has a module system. Several, actually. There are also several package managers, tools for installing all that software and coping with high-level dependencies. You might think ES6, with its new module syntax, is a little late to the party.
Well, today we’ll see whether ES6 adds anything to these existing systems, and whether or not future standards and tools will be able to build on it. But first, let’s just dive in and see what ES6 modules look like.
### Module basics
An ES6 module is a file containing JS code. There’s no special `module` keyword; a module mostly reads just like a script. There are two differences.
- ES6 modules are automatically strict-mode code, even if you don’t write `"use strict";` in them.
- You can use `import` and `export` in modules.
Let’s talk about `export` first. Everything declared inside a module is local to the module, by default. If you want something declared in a module to be public, so that other modules can use it, you must *export* that feature. There are a few ways to do this. The simplest way is to add the `export` keyword.
```js
// kittydar.js - Find the locations of all the cats in an image.
// (Heather Arthur wrote this library for real)
// (but she didn't use modules, because it was 2013)
export function detectCats(canvas, options) {
var kittydar = new Kittydar(options);
return kittydar.detectCats(canvas);
}
export class Kittydar {
... several methods doing image processing ...
}
// This helper function isn't exported.
function resizeCanvas() {
...
}
...
```
You can `export` any top-level `function`, `class`, `var`, `let`, or `const`.
And that’s really all you need to know to write a module! You don’t have to put everything in an [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) or a callback. Just go ahead and declare everything you need. Since the code is a module, not a script, all the declarations will be scoped to that module, *not* globally visible across all scripts and modules. Export the declarations that make up the module’s public API, and you’re done.
Apart from exports, the code in a module is pretty much just normal code. It can use globals like `Object` and `Array`. If your module runs in a web browser, it can use `document` and `XMLHttpRequest`.
In a separate file, we can import and use the `detectCats()` function:
```js
// demo.js - Kittydar demo program
import {detectCats} from "kittydar.js";
function go() {
var canvas = document.getElementById("catpix");
var cats = detectCats(canvas);
drawRectangles(canvas, cats);
}
```
To import multiple names from a module, you would write:
```js
import {detectCats, Kittydar} from "kittydar.js";
```
When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
And those are the basics of modules. It’s really quite simple. ;-)
### Export lists
Rather than tagging each exported feature, you can write out a single list of all the names you want to export, wrapped in curly braces:
```js
export {detectCats, Kittydar};
// no `export` keyword required here
function detectCats(canvas, options) { ... }
class Kittydar { ... }
```
An `export` list doesn’t have to be the first thing in the file; it can appear anywhere in a module file’s top-level scope. You can have multiple `export` lists, or mix `export` lists with other `export` declarations, as long as no name is exported more than once.
### Renaming imports and exports
Once in a while, an imported name happens to collide with some other name that you also need to use. So ES6 lets you rename things when you import them:
```js
// suburbia.js
// Both these modules export something named `flip`.
// To import them both, we must rename at least one.
import {flip as flipOmelet} from "eggs.js";
import {flip as flipHouse} from "real-estate.js"; ...
```
Similarly, you can rename things when you export them. This is handy if you want to export the same value under two different names, which occasionally happens:
```js
// unlicensed_nuclear_accelerator.js - media streaming without drm
// (not a real library, but maybe it should be)
function v1() { ... }
function v2() { ... }
export {
v1 as streamV1,
v2 as streamV2,
v2 as streamLatestVersion
};
```
### Default exports
The new standard is designed to interoperate with existing CommonJS and AMD modules. So suppose you have a Node project and you’ve done `npm install lodash`. Your ES6 code can import individual functions from Lodash:
```js
import {each, map} from "lodash";
each([3, 2, 1], x => console.log(x));
```
But perhaps you’ve gotten used to seeing `_.each` rather than `each` and you still want to write things that way. Or maybe you want to use `_` as a function, since [that’s a useful thing to do in Lodash](https://lodash.com/docs#_).
For that, you can use a slightly different syntax: import the module without curly braces.
``
```js
import _ from "lodash";
```
``
This shorthand is equivalent to `import {default as _} from "lodash";`. All CommonJS and AMD modules are presented to ES6 as having a `default` export, which is the same thing that you would get if you asked `require()` for that module—that is, the `exports` object.
ES6 modules were designed to let you export multiple things, but for existing CommonJS modules, the default export is all you get. For example, as of this writing, the famous [colors](https://github.com/Marak/colors.js) package doesn’t have any special ES6 support as far as I can tell. It’s a collection of CommonJS modules, like most packages on npm. But you can import it right into your ES6 code.
```js
// ES6 equivalent of `var colors = require("colors/safe");`
import colors from "colors/safe";
```
``
If you’d like your own ES6 module to have a default export, that’s easy to do. There’s nothing magic about a default export; it’s just like any other export, except it’s named `"default"`. You can use the renaming syntax we already talked about:
``
```js
let myObject = {
field1: value1,
field2: value2
};
export {myObject as default};
```
``
Or better yet, use this shorthand:
``
```js
export default {
field1: value1,
field2: value2
};
```
``
The keywords `export default` can be followed by any value: a function, a class, an object literal, you name it.
### Module objects
Sorry this is so long. But JavaScript is not alone: for some reason, module systems in all languages tend to have a ton of individually small, boring convenience features. Fortunately, there’s just one thing left. Well, two things.
``
```
import * as cows from "cows";
```
``
When you `import *`, what’s imported is a module namespace object. Its properties are the module’s exports. So if the “cows” module exports a function named `moo()`, then after importing “cows” this way, you can write: `cows.moo()`.
### Aggregating modules
Sometimes the main module of a package is little more than importing all the package’s other modules and exporting them in a unified way. To simplify this kind of code, there’s an all-in-one import-and-export shorthand:
``
```
// world-foods.js - good stuff from all over
// import "sri-lanka" and re-export some of its exports
export {Tea, Cinnamon} from "sri-lanka";
// import "equatorial-guinea" and re-export some of its exports
export {Coffee, Cocoa} from "equatorial-guinea";
// import "singapore" and export ALL of its exports
export * from "singapore";
```
Each one of these `export-from` statements is similar to an `import-from` statement followed by an `export`. Unlike a real import, this doesn’t add the re-exported bindings to your scope. So don’t use this shorthand if you plan to write some code in `world-foods.js` that makes use of `Tea`. You’ll find that it’s not there.
If any name exported by “singapore” happened to collide with the other exports, that would be an error, so use `export *` with care.
Whew! We’re done with syntax! On to the interesting parts.
### What does `import` actually do?
Would you believe… *nothing?*
Oh, you’re not that gullible. Well, would you believe the standard *mostly doesn’t say* what `import` does? And that this is a good thing?
ES6 leaves the details of module loading entirely [up to the implementation](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-hostresolveimportedmodule). The rest of module execution is [specified in detail](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-toplevelmoduleevaluationjob).
Roughly speaking, when you tell the JS engine to run a module, it has to behave as though these four steps are happening:
1. Parsing: The implementation reads the source code of the module and checks for syntax errors.
2. Loading: The implementation loads all imported modules (recursively). This is the part that isn’t standardized yet.
3. Linking: For each newly loaded module, the implementation creates a module scope and fills it with all the bindings declared in that module, including things imported from other modules.
This is the part where if you try to `import {cake} from "paleo"`, but the “paleo” module doesn’t actually export anything named `cake`, you’ll get an error. And that’s too bad, because you were *so close* to actually running some JS code. And having cake!
4. Run time: Finally, the implementation runs the statements in the body of each newly-loaded module. By this time, `import` processing is already finished, so when execution reaches a line of code where there’s an `import` declaration… nothing happens!
See? I told you the answer was “nothing”. I don’t lie about programming languages.
But now we get to the fun part of this system. There’s a cool trick. Because the system doesn’t specify how loading works, and because you can figure out all the dependencies ahead of time by looking at the `import` declarations in the source code, an implementation of ES6 is free to do all the work at compile time and bundle all your modules into a single file to ship them over the network! And tools like [webpack](http://www.2ality.com/2015/04/webpack-es6.html) actually do this.
This is a big deal, because loading scripts over the network takes time, and every time you fetch one, you may find that it contains `import` declarations that require you to load dozens more. A naive loader would require a lot of network round trips. But with webpack, not only can you use ES6 with modules today, you get all the software engineering benefits with no run-time performance hit.
A detailed specification of module loading in ES6 was originally planned—and built. One reason it isn’t in the final standard is that there wasn’t consensus on how to achieve this bundling feature. I hope someone figures it out, because as we’ll see, module loading really should be standardized. And bundling is too good to give up.
### Static vs. dynamic, or: rules and how to break them
For a dynamic language, JavaScript has gotten itself a surprisingly static module system.
- All flavors of `import` and `export` are allowed only at toplevel in a module. There are no conditional imports or exports, and you can’t use `import` in function scope.
- All exported identifiers must be explicitly exported by name in the source code. You can’t programmatically loop through an array and export a bunch of names in a data-driven way.
- Module objects are frozen. There is no way to hack a new feature into a module object, polyfill style.
- *All* of a module’s dependencies must be loaded, parsed, and linked eagerly, before any module code runs. There’s no syntax for an `import` that can be loaded lazily, on demand.
- There is no error recovery for `import` errors. An app may have hundreds of modules in it, and if anything fails to load or link, nothing runs. You can’t `import` in a `try/catch` block. (The upside here is that because the system is so static, webpack can detect those errors for you at compile time.)
- There is no hook allowing a module to run some code before its dependencies load. This means that modules have no control over how their dependencies are loaded.
The system is quite nice as long as your needs are static. But you can imagine needing a little hack sometimes, right?
That’s why whatever module-loading system you use will have a programmatic API to go alongside ES6’s static `import/export` syntax. For example, [webpack includes an API](http://webpack.github.io/docs/code-splitting.html) that you can use for “code splitting”, loading some bundles of modules lazily on demand. The same API can help you break most of the other rules listed above.
The ES6 module *syntax* is very static, and that’s good—it’s paying off in the form of powerful compile-time tools. But the static syntax was designed to work alongside a rich dynamic, programmatic loader API.
### When can I use ES6 modules?
To use modules today, you’ll need a compiler such as [Traceur](https://github.com/google/traceur-compiler#what-is-traceur) or [Babel](http://babeljs.io/). Earlier in this series, [Gastón I. Silva showed how to use Babel and Broccoli](https://hacks.mozilla.org/2015/06/es6-in-depth-babel-and-broccoli/) to compile ES6 code for the web; building on that article, Gastón has [a working example with support for ES6 modules](https://github.com/givanse/broccoli-babel-examples/tree/master/es6-modules). This [post by Axel Rauschmayer](http://www.2ality.com/2015/04/webpack-es6.html) contains an example using Babel and webpack.
The ES6 module system was designed mainly by Dave Herman and Sam Tobin-Hochstadt, who defended the static parts of the system against all comers (including me) through years of controversy. Jon Coppeard is implementing modules in Firefox. Additional work on a [JavaScript Loader Standard](https://github.com/whatwg/loader) is underway. Work to add something like `` to HTML is expected to follow.
And that’s ES6.
This has been so much fun that I don’t want it to end. Maybe we should do just one more episode. We could talk about odds and ends in the ES6 spec that weren’t big enough to merit their own article. And maybe a little bit about what the future holds. Please join me next week for the stunning conclusion of ES6 In Depth.
|
Python
|
UTF-8
| 642 | 3.265625 | 3 |
[] |
no_license
|
import numpy as np
from numpy import linalg as la
#相似度计算,若inA,inB都是行向量
#欧式距离
def euclidsimilar(inA,inB):
return 1.0/(1.0+la.norm(inA-inB))
#皮尔逊相关系数
def pearsonsimilar(inA,inB):
if len(inA)<3:
return 1.0
return 0.5+0.5*np.corrcoef(inA,inB,rowvar=0)[0][1]
#余弦相似度
def cossimilar(inA,inB):
inA = np.mat(inA)
inB = np.mat(inB)
num = float(inA*inB.T)
denom = la.norm(inA)*la.norm(inB)
return 0.5+0.5*(num/denom)
inA=np.array([1,2,3])
inB=np.array([2,4,6])
print(euclidsimilar(inA,inB))
print(pearsonsimilar(inA,inB))
print(cossimilar(inA,inB))
|
JavaScript
|
UTF-8
| 618 | 2.5625 | 3 |
[] |
no_license
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var location = req.param('location');
if( location === 'milano') {
res.send('{"condizione":"soleggiato", "temperatura":"32°C"}');
}
if( location === 'padova') {
res.send('{"condizione":"variabile", "temperatura":"32°C"}');
}
if( location === 'genova') {
res.send('{"condizione":"nuvoloso", "temperatura":"22°C"}');
}
if( location === 'roma') {
res.send('{"condizione":"pioggie sparse", "temperatura":"18°C"}');
}
});
module.exports = router;
|
C++
|
GB18030
| 1,459 | 3.4375 | 3 |
[] |
no_license
|
#include <iostream>
#include <climits>
//3,1ѧϰ͵ĴС
//ʱ䣺2020112222:06:52
//int main()
//{
// using namespace std;
// int n_int = INT_MAX;
// short n_short = SHRT_MAX;
// long n_long = LONG_MAX;
// long long n_llong = LLONG_MAX;
//
// cout << "short is " << sizeof(short) << " bytes." << endl;
// cout << "int is " << sizeof(int) << " bytes." << endl;
// cout << "long is " << sizeof(long) << " bytes." << endl;
// cout << "long long is " << sizeof(long long) << " bytes." << endl << endl;
//
// cout << "Maximum values:" << endl;
// cout << "short:" << n_short << endl;
// cout << "int: " << n_int << endl;
// cout << "long:" << n_long << endl;
// cout << "long long is:" << n_llong << endl << endl;
//
// cout << "Minimum int value = " << INT_MIN << endl;
// cout << "Bits per byte = " << CHAR_BIT << endl; //CHAR_BITΪֽڵλ
//
// system("pause");
// return 0;
//}
/*
//32λģʽеõĽ£
short is 2 bytes.
int is 4 bytes.
long is 4 bytes.
long long is 8 bytes.
Maximum values:
short:32767
int: 2147483647
long:2147483647
long long is:9223372036854775807
Minimum int value = -2147483648
Bits per byte = 8
//64λģʽеõĽ£
short is 2 bytes.
int is 4 bytes.
long is 4 bytes.
long long is 8 bytes.
Maximum values:
short:32767
int: 2147483647
long:2147483647
long long is:9223372036854775807
Minimum int value = -2147483648
Bits per byte = 8
*/
|
Python
|
UTF-8
| 343 | 2.9375 | 3 |
[] |
no_license
|
from PIL import Image
im = Image.open('F:\相册\塞尔达\四英杰.png')
# src_image.show()
# print(src_image)
rgb_pixels = list(im.getdata())
r_pixels = list(im.getdata(band=0))
g_pixels = list(im.getdata(band=1))
b_pixels = list(im.getdata(band=2))
print(rgb_pixels[:10])
print(r_pixels[:10])
print(g_pixels[:10])
print(b_pixels[:10])
|
TypeScript
|
UTF-8
| 266 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import { AsyncSpecification } from '../index';
export class NumberIsPrime extends AsyncSpecification<number> {
async isSatisfiedBy(n: number) {
for (var i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return n > 1;
}
}
|
Python
|
UTF-8
| 491 | 2.5625 | 3 |
[] |
no_license
|
import paramiko
def login_ssh (ip, username, password, port = 22, cmd = 'ip address print'):
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port = port , username = username, password = password, timeout=5, compress=True)
stdin, stdout, stderr = ssh.exec_command(cmd)
return stdout.read().decode()
if __name__ == '__main__':
print(login_ssh('172.30.13.1', 'admin', 'asiafort@ro'))
|
JavaScript
|
UTF-8
| 2,098 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
define(function () {
'use strict';
var Characters = {
SPACE: ' ',
TAB: '\t'
};
function TabConvertion(units) {
this.units = units;
}
TabConvertion.prototype.getIndentation = function (wsCount, tabCount) {
if (!wsCount) {
return;
}
var newTabs = Math.floor(wsCount / this.units);
var totalTabs = tabCount + newTabs;
var totalSpaces = wsCount - (newTabs * this.units);
var indentation = totalTabs ? new Array(totalTabs + 1).join(Characters.TAB) : '';
indentation += totalSpaces ? new Array(totalSpaces + 1).join(Characters.SPACE) : '';
return indentation;
};
function SpaceConvertion(units) {
this.units = units;
}
SpaceConvertion.prototype.getIndentation = function (wsCount, tabCount) {
if (!tabCount) {
return;
}
var newSpaces = wsCount + (tabCount * this.units);
var indentation = new Array(newSpaces + 1).join(Characters.SPACE);
return indentation;
};
function ReplacePattern(useTab, units) {
this.pattern = useTab ? (new TabConvertion(units)) : (new SpaceConvertion(units));
}
ReplacePattern.prototype.exec = function (line) {
var pattern = this.pattern;
var wsCount = 0, tabCount = 0;
var character, i, length;
for (i = 0, length = line.length; i < length; i++) {
character = line[i];
if (character === ' ') {
wsCount++;
}
else if (character === '\t') {
tabCount++;
}
else {
break;
}
}
var start = 0;
var end = wsCount + tabCount;
var replaceWith = pattern.getIndentation(wsCount, tabCount);
if (end && replaceWith && line.substring(0, end) === replaceWith) {
replaceWith = false;
}
return {
replaceWith: replaceWith,
start: start,
end: end
};
};
ReplacePattern.create = function (settings) {
return new ReplacePattern(settings.useTab, settings.units);
};
ReplacePattern.create.TabConvertion = TabConvertion;
ReplacePattern.create.SpaceConvertion = SpaceConvertion;
return ReplacePattern.create;
});
|
Java
|
UTF-8
| 2,227 | 2.59375 | 3 |
[] |
no_license
|
package ui.controls;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.math.MathUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import org.libsdl.app.SDLActivity;
public class Joystick extends View {
// Stick positions, [-1; 1]
private float posX, posY;
// left or right stick
private int stickId = 0;
private Paint paint = new Paint();
public Joystick(Context context) {
super(context);
}
public Joystick(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Joystick(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setStick(int id) {
stickId = id;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
canvas.drawRect(0, 0, getWidth() - 1, getHeight() - 1, paint);
paint.setColor(Color.GREEN);
float cx = (posX + 1.0f) * getWidth() / 2;
float cy = (posY + 1.0f) * getHeight() / 2;
float r = getWidth() / 5;
canvas.drawCircle(cx, cy, r, paint);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
{
posX = MathUtils.clamp(2 * event.getX() / getWidth() - 1.0f, -1, 1);
posY = MathUtils.clamp(2 * event.getY() / getHeight() - 1.0f, -1, 1);
break;
}
case MotionEvent.ACTION_UP: {
posX = posY = 0;
break;
}
}
GamepadEmulator.updateStick(stickId, posX, posY);
invalidate();
return true;
}
}
|
Markdown
|
UTF-8
| 1,542 | 2.609375 | 3 |
[] |
no_license
|
---
layout: post
title: Tomcat URL 长度限制
date: 2015-08-06 16:54:54
categories: Tomcat
---
* content
{:toc}
## 原因
某次用户请求的url总长度为12364字符,tomcat直接报400错误
---
## 分析
我之前一直知道一个"真理":
get请求是限制长度的,而post请求是不限制长度的
在查询解决方案的过程中发现,上面的"真理"有问题:
在http协议中,其实并没有对url长度作出限制
url的最大长度和用户浏览器和Web服务器有关
一语惊醒梦中人啊
知道了原因问题就好解决了,由于我们是服务器间请求,不涉及浏览器等
所以只需要修改tomcat配置,使其支持更长的url就可以了
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" maxHttpHeaderSize="65536"/>
最后的maxHttpHeaderSize属性就是url最大长度啦
问题解决
---
## 附录
Microsoft Internet Explorer (Browser)
IE浏览器对URL的最大限制为2083个字符,如果超过这个数字,提交按钮没有任何反应
Firefox (Browser)
对于Firefox浏览器URL的长度限制为65,536个字符
Safari (Browser)
URL最大长度限制为 80,000个字符
Opera (Browser)
URL最大长度限制为190,000个字符
Google (chrome)
URL最大长度限制为8182个字符
Apache (Server)
能接受最大url长度为8,192个字符
Microsoft Internet Information Server(IIS)
能接受最大url的长度为16,384个字符
ubuntu14.04 + tomcat 7.0.54
url最大长度7509
|
PHP
|
UTF-8
| 7,645 | 2.625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
class model_user extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library(array('session', 'form_validation', 'email'));
}
//send verification email to user's email id
function sendEmail($name, $subject, $from_email, $message)
{
$to_email = 'info@besha-analitika.co.id';
/*$subject = 'Verify Your Email Address'; */
$messages = 'Dear Admin Besha Analitika, You get message from :'.$name.' '.$from_email.'<br>'.$message;
//configure email settings
$config['protocol'] = 'smtp';
$config['mailtype'] = 'html';
$config['priority'] = '1';
$config['charset'] = 'iso-8859-1';
$config['newline'] = "\r\n"; //use double quotes*/
$config['wordwrap'] = TRUE;
$config['smtp_host'] = 'ssl://besha-analitika.co.id';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'info@besha-analitika.co.id';
$config['smtp_pass'] = 'be=$.P!TQ6X*';
$this->email->initialize($config);
//send mail
$this->email->to($to_email);
$this->email->from($from_email , $name);
$this->email->subject($subject);
$this->email->message($messages);
return $this->email->send();
}
//activate user account
function verifyEmailID($key)
{
$data = array('act_status' => 1);
$this->db->where('md5(email)', $key);
return $this->db->update('user_tbl', $data);
}
//send verification to email admin id
function sendEmailAdmin($to_email,$username)
{
$from_email = 'info@besha-analitika.co.id';
$subject = 'Verify Your Email Address';
$message = 'Dear Admin Besha Analitika,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://www.besha-analitika.co.id/login/verify/admin/'.$username.'<br /><br /><br />Thanks<br />';
//configure email settings
$config['protocol'] = 'smtp';
$config['mailtype'] = 'html';
$config['priority'] = '1';
$config['charset'] = 'iso-8859-1';
$config['newline'] = "\r\n"; //use double quotes*/
$config['wordwrap'] = TRUE;
$config['smtp_host'] = 'ssl://besha-analitika.co.id';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'info@besha-analitika.co.id';
$config['smtp_pass'] = 'be=$.P!TQ6X*';
$this->email->initialize($config);
//send mail
$this->email->from($from_email, 'Besha Analitika');
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
return $this->email->send();
}
function verifyEmailAdmin($key)
{
$data = array('status' => 1);
$this->db->where('md5(email)', $key);
return $this->db->update('admin_tbl', $data);
}
function list_users(){
$stock = $this->db->get('admin_tbl');
return $stock->result();
}
function list_user_member()
{
$str = "SELECT * FROM user_tbl ";
$q = $this->db->query($str);
$f = $q->result_array();
return $f;
}
function get_user_detail($user_id)
{
$str = "SELECT * FROM user_tbl WHERE user_id = '$user_id' ";
$q = $this->db->query($str);
$f = $q->row_array();
return $f;
}
function get_user_detail_email($email)
{
$str = "SELECT * FROM user_tbl WHERE email = '$email' ";
$q = $this->db->query($str);
$f = $q->row_array();
return $f;
}
function address_book_list($user_id)
{
$str = "SELECT * FROM user_address_tbl WHERE user_id = '$user_id' ";
$q = $this->db->query($str);
$f = $q->result_array();
return $f;
}
function check_account($email,$password)
{
$password = md5($password);
$str = "SELECT * FROM user_tbl WHERE email = '$email' AND password = '$password' ";
$q = $this->db->query($str);
$f = $q->row_array();
return $f;
}
function change_password($password)
{
$user_id = $this->session->userdata("user_id");
$dt = array(
"password" => md5($password)
);
$this->db->where('user_id', $user_id);
$this->db->update('user_tbl', $dt);
}
function change_email($email)
{
$user_id = $this->session->userdata("user_id");
$dt = array(
"email" => $email
);
$this->db->where('user_id', $user_id);
$this->db->update('user_tbl', $dt);
}
function edit_profile_process()
{
$id_user = $this->session->userdata("user_id");
$contact_person = $this->input->post("contact_person",TRUE);
$no_telp = $this->input->post("no_telp",TRUE);
$no_hp = $this->input->post("no_hp",TRUE);
$no_fax = $this->input->post("no_fax",TRUE);
//$billing_address = $this->input->post("billing_address",TRUE);
//$shipping_address = $this->input->post("shipping_address",TRUE);
$data = array(
'contact_person' => $contact_person,
'no_tlp' => $no_telp,
'no_hp' => $no_hp,
"no_fax" => $no_fax,
//"billing_address" => $billing_address,
//"shipping_address" => $shipping_address
);
$this->db->where('user_id', $id_user);
$this->db->update('user_tbl', $data);
}
function add_address_book()
{
$user_id = $this->session->userdata("user_id");
$datetime = date("Y-m-d H:i:i");
$contact_person = $this->input->post("contact_person",TRUE);
if(empty($contact_person))
{
$contact_person = $this->session->userdata("contact_person");
}
$no_hp = $this->input->post("no_hp",TRUE);
$id_province = $this->input->post("id_province",TRUE);
$id_city = $this->input->post("id_city",TRUE);
$kecamatan = $this->input->post("kecamatan",TRUE);
$kode_pos = $this->input->post("kode_pos",TRUE);
$shipping_address = $this->input->post("shipping_address",TRUE);
//$billing_address = $this->input->post("billing_address",TRUE);
$dt = array(
"user_id" => $user_id,
"contact_person" => $contact_person,
"no_hp" => ($no_hp != NULL) ? $no_hp : "",
"provinsi" => $id_province,
"kota" => $id_city,
"kecamatan" => $kecamatan,
"kode_pos" => $kode_pos,
"shipping_address" => $shipping_address,
//"billing_address" => $billing_address ,
"create_date" => $datetime
);
//$this->db->set("");
$this->db->insert("user_address_tbl",$dt);
}
function delete_address_book()
{
}
function register_process()
{
$contact_person = $this->input->post("contact_person",TRUE);
$email = $this->input->post("email",TRUE);
$password = $this->input->post("password",TRUE);
$no_telp = $this->input->post("no_telp",TRUE);
$no_hp = $this->input->post("no_hp",TRUE);
$no_fax = $this->input->post("no_fax",TRUE);
$id_province = $this->input->post("id_province",TRUE);
$id_city = $this->input->post("id_city",TRUE);
$kecamatan = $this->input->post("kecamatan",TRUE);
$kode_pos = $this->input->post("kode_pos",TRUE);
//$billing_address = $this->input->post("billing_address",TRUE);
$shipping_address = $this->input->post("shipping_address",TRUE);
$datetime = date("Y-m-d H:i:s");
$dt_user = array(
"contact_person"=>$contact_person,
"no_tlp"=>$no_telp,
"no_fax"=>$no_fax,
"no_hp"=>$no_hp,
"email"=>$email,
"password"=>md5($password),
"act_status"=>0,
"joindate"=>$datetime,
"discount_price"=>0
);
$this->db->insert("user_tbl",$dt_user);
$user_detail = $this->get_user_detail_email($email);
$dt_user_add = array(
"user_id"=>$user_detail["user_id"],
"contact_person"=>$contact_person,
//"billing_address"=>$billing_address,
"shipping_address"=>$shipping_address,
"provinsi"=>$id_province,
"kota"=>$id_city,
"kecamatan"=>$kecamatan,
"kode_pos"=>$kode_pos,
"no_hp"=>$no_hp,
"create_date"=>$datetime
);
$this->db->insert("user_address_tbl",$dt_user_add);
}
}
|
Java
|
UTF-8
| 2,693 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
package se.iths.httpHandler;
import se.iths.model.HttpRequest;
import se.iths.model.HttpResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
public class ResponseHandler {
/**
* Constructs our httpResponse and send it out to the client via class methods.
*
* @param content received from our plugins (file or database query)
*/
public void handleResponse(byte[] content, Socket socket, HttpRequest httpRequest) throws Exception {
var output = new PrintStream(socket.getOutputStream());
HttpResponse httpResponse = createHttpResponse(content, httpRequest);
sendHttpResponse(httpResponse, output);
}
/**
* Populates our httpResponse object.
*
* @param content from our IoHandlers. If it is 0 bytes we return a 404 httpResponse object.
* @param httpRequest with requested information.
* @return populated httpResponse.
*/
private HttpResponse createHttpResponse(byte[] content, HttpRequest httpRequest) throws IOException {
if (content.length > 0) {
return new HttpResponse(httpRequest.getRequestMethod(), "200 OK", findContentType(httpRequest.getRequestPath()), content);
} else {
return new HttpResponse(httpRequest.getRequestMethod(), "404", "text/html", Files.readAllBytes(Path.of("core/src/main/resources/404.html")));
}
}
/**
* Sends the response to client.
*
* @param httpResponse populated with all data needed for response.
* @param output (Printstream) used for sending the requested data to client; closes after sending data.
*/
private void sendHttpResponse(HttpResponse httpResponse, PrintStream output) throws IOException {
output.println(httpResponse.getStatus());
output.println("Content-Length: " + httpResponse.getContentLength());
output.println(httpResponse.getContentType());
output.println("");
if (!httpResponse.getMethod().equals("HEAD")) {
output.write(httpResponse.getContent());
}
output.flush();
output.close();
}
/**
* If the url points to a database action , the content type is set to Json.
* Otherwise we check mimetype of the file.
*
* @param requestPath to the file or database path
* @return mimetype/content-type of the file / path
*/
private String findContentType(String requestPath) throws IOException {
if (requestPath.contains("/contacts") || requestPath.contains("/postcontact") || requestPath.contains("/insertcontactviaget")) {
return "application/json";
} else {
if ("/".equals(requestPath)) {
requestPath = "index.html";
}
Path path = Path.of(requestPath);
return Files.probeContentType(path);
}
}
}
|
Python
|
UTF-8
| 1,837 | 2.65625 | 3 |
[] |
no_license
|
import urllib.request
import xml.etree.ElementTree as ET
import pickle
import difflib
from pprint import pprint as pp
def main():
# mid = '1f4p3zPa1uU_gRnbQzMAqCZTPzD4' # National Parks
# mid = '1Zn_fIUf06TLnOshLtZCqdbbHLCo' # CA Parks
# mid = '1_QU4xcCYTGTszmV4IXMgKeN4uPE' # DG Courses Small
# mid = '1irCF0iGu0KeGYiGPfqE1RLvvqd4' # DG Courses Large
mid = '1aJKR8O-8BWOb9uR7p_2UmapNTL6n154B' # Other
url = 'http://www.google.com/maps/d/kml?forcekml=1&mid={}'.format(mid)
listOfPlacemarks = []
with urllib.request.urlopen(url) as response:
html = response.read()
root = ET.fromstring(html)
for i in root[0][-1].findall('{http://www.opengis.net/kml/2.2}Placemark'):
myText = i[0].text.replace('\xa0', '')
myText = myText.replace('\n', '')
listOfPlacemarks.append(myText)
# pp(listOfPlacemarks)
# Cache the list of Placemarks
# with open('listOfPlacemarks.pkl', 'wb') as f:
# pickle.dump(listOfPlacemarks, f)
with open('listOfPlacemarks.pkl', 'rb') as f:
cachedListOfPlacemarks = pickle.load(f)
# Quick Tests:
# cachedListOfPlacemarks.append('test')
# listOfPlacemarks.append('another')
delta = set(listOfPlacemarks)^set(cachedListOfPlacemarks)
print('Number of Placemarks:', len(listOfPlacemarks), '\n')
if delta:
print('There ARE differences between cached and live placemark list.')
# pp(delta)
diff = difflib.Differ().compare(cachedListOfPlacemarks, listOfPlacemarks)
for i in diff:
if i[0] != ' ':
print(i)
# print('\n'.join(diff))
else:
print('There are NO differences between cached and live placemark list.')
if __name__ == '__main__':
main()
|
C
|
UTF-8
| 3,098 | 3.046875 | 3 |
[] |
no_license
|
#include <stdio.h>
typedef struct
{
double prob;
int prev_idx;
}viterbi_node;
#define RIGHT 0
#define LEFT 1
#define STOP 2
#define FORWARD 3
const char *states[] = {"RIGHT", "LEFT", "STOP", "FORWARD"}; // labels for states 0...3
#define NONE 0
#define H1 1
#define H2 2
#define H3 3
#define H4 4
const char *observations[] = {"NONE", "H1", "H2", "H3", "H4"};
double tl_prob[4][4] = {
{0.45, 0.09, 0.10, 0.36}, // RIGHT
{0.08, 0.55, 0.10, 0.27}, // LEFT
{0.08, 0.12, 0.60, 0.20}, // STOP
{0.09, 0.09, 0.15, 0.67} // FORWARD
};
double obs_prob[4][5] = {
{-1.0, 0.60, 0.05, 0.15, 0.20},
{-1.0, 0.12, 0.62, 0.10, 0.16},
{-1.0, 0.15, 0.20, 0.63, 0.02},
{-1.0, 0.01, 0.04, 0.25, 0.70}
};
int main()
{
unsigned int obs[] = {NONE, H1, H3, H3, H4, H2, H1, H3, H1, H1, H2};
int t = sizeof(obs)/sizeof(obs[0]) - 1;
int n = sizeof(states)/sizeof(states[0]);
int i;
for(i = 0; i < n; ++i)
printf("state %d: %s\n", i, states[i]);
puts("");
for(i = 1; i <= t; ++i)
printf("observation %2d: %s\n", i, observations[obs[i]]);
puts("\n\nprobabilities:\n");
for(i = 0; i < n; ++i)
{
int j;
for(j = 0; j < n; ++j)
{
printf("%s->%s = %.02f\n", states[i], states[j], tl_prob[i][j]);
}
puts("");
}
for(i = 0; i < n; ++i)
{
int j;
for(j = 1; j <= 4; ++j)
{
printf("%s::%s = %.02f\n", states[i], observations[j], obs_prob[i][j]);
}
puts("");
}
// let's go!
viterbi_node chain[t+1][n];
for(i = 0; i < n; ++i)
{
chain[0][i].prob = 0;
}
chain[0][RIGHT].prob = 1.0; // FIRST STATE = RIGHT;
for(i = 1; i <= t; ++i)
{
int j;
for(j = 0; j < n; ++j)
{
int k;
int max_idx;
double max_prob = -1.0;
for(k = 0; k < n; ++k)
{
double val = chain[i-1][k].prob * tl_prob[k][j] * obs_prob[j][obs[i]];
if(val > max_prob)
{
max_idx = k;
max_prob = val;
}
}
chain[i][j].prob = max_prob;
chain[i][j].prev_idx = max_idx;
}
}
int cur_idx;
double goal_prob = -1.0;
for(i = 0; i < n; ++i)
{
if(chain[t][i].prob > goal_prob)
{
cur_idx = i;
goal_prob = chain[t][i].prob;
}
}
puts("sequence in reverse order, cause reversing is not part of the task... and I'm lazy. :) Just read it in opposite order..");
puts("----");
for(i = t; i > 0; --i)
{
printf("chain[%d][%d].prob = %e :: ", i, cur_idx, chain[i][cur_idx].prob);
printf("%d: %s\n", cur_idx, states[cur_idx]);
cur_idx = chain[i][cur_idx].prev_idx;
}
puts("probabilities: ");
for(i = 0; i < n; ++i)
{
int j;
for(j = 0; j <=t; ++j)
{
printf("%e ", chain[j][i].prob);
}
puts("");
}
double prob_last[n];
for(i = 0; i < n; ++i)
{
double sum = 0;
int j;
for(j = 0; j < n; ++j)
{
sum += chain[t][j].prob * tl_prob[j][i];
}
prob_last[i] = sum;
}
int max_obs;
double max_prob = -1;
for(i = 1; i <= 4; ++i)
{
int j;
double sum = 0;
for(j = 0; j < n; ++j)
{
double val = prob_last[j] * obs_prob[j][i];
sum += val;
}
if(sum > max_prob)
{
max_prob = sum;
max_obs = i;
}
}
printf("%s\n", observations[max_obs]);
// printf("Viterbi's motherfucker.\n");
return 0;
}
|
C++
|
UTF-8
| 1,239 | 3.109375 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: binaryinsertsort.h
> Author:
> Mail:
> Created Time: Thu 06 Dec 2018 03:20:37 AM PST
************************************************************************/
#ifndef _BINARYINSERTSORT_H
#define _BINARYINSERTSORT_H
//gist:using binary method to find the insert index quickly
#include<iostream>
using namespace std;
int* binaryinsertsort(int* data, int size)
{
int array[size]={0};
for (int i=0; i<size; ++i)
array[i]=data[i];
int *time = new int[2]{0};
for (int i=0; i<size; ++i)
{
int low=0, high=i-1;//start to search the sorted queue;
int m;
while(low<high)
{
time[0]++;
m = (low+high)/2;
if (array[m]<array[i])
low = m+1;
else high = m-1;
}
cout<<"high="<<high<<" low="<<low<<endl;
if (low!=i)
{
int k;
int tmp = array[i];
for (k=i-1; k>=low; k--)
{
time[1]++;
array[k+1] = array[k];
}
time[1]++;
array[k+1]=tmp;
}
}
return time;
}
#endif
|
Java
|
UTF-8
| 7,189 | 2.421875 | 2 |
[] |
no_license
|
package com.visionbizsolutions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.FileCopyUtils;
import com.visionbizsolutions.mvc.models.FileMeta;
import com.visionbizsolutions.orm.jpa.bean.User;
import com.visionbizsolutions.orm.jpa.service.UserService;
public class HttpServletRequestFileUploadProcessor implements
FileUploadProcessor {
private static final Logger logger = LoggerFactory
.getLogger(HttpServletRequestFileUploadProcessor.class);
@SuppressWarnings("unchecked")
@Override
public LinkedList<FileMeta> processUploadedFile(HttpServletRequest request,
Long fileSizeAllowed, String dirPath, UserService userService) throws Exception {
LinkedList<FileMeta> files = new LinkedList<FileMeta>();
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> fileItems = fileUpload.parseRequest(request);
// 1. build an iterator
Iterator<FileItem> mitr = fileItems.iterator();
// 2. get each file
while (mitr.hasNext()) {
boolean isValidFileSize = true;
boolean isValidFileType = true;
boolean isFileSavedToDir = true;
boolean isUserAuthenticated = true;
boolean isFileInfoSavedToDB = true;
String _fileUploadStatusMessage = null;
FileMeta fileMeta = new FileMeta();
// FileItem item = itr.next();
FileItem item = mitr.next();
logger.debug("Uploading file: " + item.getName());
/* , Integer fileSizeAllowed, String dirPath */
if (Utils.isValidFileType(item.getContentType())) {
if (item.getSize() <= fileSizeAllowed) {
// 2.2 Populate FileMeta object
fileMeta.setFileName(item.getName());
fileMeta.setFileSize(item.getSize() / 1024 + " Kb");
fileMeta.setFileType(item.getContentType());
File file = new File(dirPath + fileMeta.getFileName());
try {
// 2.3 save file in directory
FileCopyUtils.copy(item.getInputStream(),
new FileOutputStream(file));
} catch (IOException e) {
e.printStackTrace();
isFileSavedToDir = false;
_fileUploadStatusMessage = e.getLocalizedMessage();
logger.debug(_fileUploadStatusMessage);
}
if (isFileSavedToDir) {
// File saving has some problems
logger.debug(file + " uploaded! ");
// 2.4 save file info in database
Authentication auth = SecurityContextHolder
.getContext().getAuthentication();
logger.debug("Getting User from Context !!");
User user = null;
if (auth instanceof UsernamePasswordAuthenticationToken) {
UserDetails userDetail = (UserDetails) auth
.getPrincipal();
String username = userDetail.getUsername();
logger.info("Got username for saving file info. which is "
+ username);
user = userService.getUserByUsername(username);
}
if (user != null) {
logger.debug("Got user with username: "
+ user.getUsername());
try {
// TODO: check before adding info to DB that the
// same file name was uploaded then
// Step1: delete the file from directory
// Step2: Get current time in long
// Step3: Save file again with
// filename+current-time_stamp
// Step4: Then save file info in Database
userService.saveFile(user, fileMeta
.getFileName(), item.getSize(), Utils
.getShortFileType(fileMeta
.getFileType())); // converting
// long
// file_type
// to short
// one
_fileUploadStatusMessage = fileMeta
.getFileName()
+ " is uploaded successfully. Relavent person will look into this,"
+ " and you will be notified, if more information is needed.";
logger.debug("File information saved into database.");
logger.debug("Congratulations! File Saved completely.");
} catch (Exception e) {
isFileInfoSavedToDB = false;
_fileUploadStatusMessage = "Sorry! "
+ fileMeta.getFileName()
+ " is not uploaded. There was an error in saving file info. in Database."
+ " Please try again later.";
logger.error("File information is not saved into database "
+ System.getProperty("line.separator")
+ Utils.getStackTrace(e.fillInStackTrace()));
// Deleting file because its information is not
// saved in database.
file.delete();
}
}// user is found and authenticated to upload files
else {
isUserAuthenticated = false;
_fileUploadStatusMessage = "Sorry! "
+ fileMeta.getFileName()
+ " is not uploaded. Either you are not logged-in OR"
+ "your session is expried. Please re-login to upload your file.";
logger.error("User is authenticated!");
// Deleting file because user is not logged-in or
// his
// session is expired.
file.delete();
}
}// isFileUploaded if()
else {
_fileUploadStatusMessage = "Sorry! "
+ fileMeta.getFileName()
+ " is not uploaded. There was an error in uploading, which is as: "
+ _fileUploadStatusMessage;
logger.error("File is not saved into the specified directory "
+ dirPath);
}
}// isValidFileSize
else {
isValidFileSize = false;
_fileUploadStatusMessage = "Sorry! "
+ item.getName()
+ " is not uploaded. This file size allowed is only "
+ (fileSizeAllowed / 1000000)
+ " MB. Please try again with smaller size file.";
logger.debug("File size " + item.getSize()
+ " is greater then the limit "
+ (fileSizeAllowed / 1000000) + " MB.");
}
}// isValidFileType if()
else {
isValidFileType = false;
_fileUploadStatusMessage = item.getName()
+ " is not uploaded. This file type is not allowed. Please upload"
+ " the files from mentioned file types only. Please try again with other file.";
logger.debug("File is not of a valid type "
+ item.getContentType());
}
// 2.5 add to files
if (isValidFileSize && isValidFileType && isFileSavedToDir
&& isUserAuthenticated && isFileInfoSavedToDB) {
fileMeta.setFileName(_fileUploadStatusMessage);
} else {
fileMeta.setFileName("");
fileMeta.setFileType(_fileUploadStatusMessage);
}
logger.debug("Adding file objects for providing status.....");
files.add(fileMeta);
}// while loop
return files;
}
}
|
Java
|
UTF-8
| 5,250 | 2.109375 | 2 |
[] |
no_license
|
package ch.hsr.mge.gadgeothek.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import ch.hsr.mge.gadgeothek.R;
import ch.hsr.mge.gadgeothek.service.Callback;
import ch.hsr.mge.gadgeothek.service.LibraryService;
public class AbstractAuthenticationActivity extends AppCompatActivity {
public static final String PREFERENCES = "PREFERENCES";
public static final String EMAIL = "EMAIL";
public static final String PASSWORD = "PASSWORD";
public static final String LAST_AUTOLOGIN_FAILED = "LAST_AUTOLOGIN_FAILED";
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gadgeothek, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showProgress(final View loginFormView, final View progressView, final boolean show) {
int shortAnimTime = getShortAnimationTime();
loginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
loginFormView
.animate()
.setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
loginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
progressView.setVisibility(show ? View.VISIBLE : View.GONE);
progressView
.animate()
.setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
progressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
}
protected int getShortAnimationTime() {
return getResources().getInteger(android.R.integer.config_shortAnimTime);
}
protected void showInDismissableSnackbar(View parent, String message) {
final Snackbar snackbar = Snackbar.make(parent, "Login failed: " + message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.dismiss_snackbar, new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
}).show();
}
protected void hideSoftKeyboard(View view) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
protected void login(final String email, final String password, final boolean isAutoLogin) {
SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
String url = preferences.getString(
getString(R.string.settings_server_address),
getString(R.string.settings_default_server));
LibraryService.setServerAddress(url);
LibraryService.login(email, password, new Callback<Boolean>() {
@Override
public void onCompletion(Boolean success) {
SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(EMAIL, email);
editor.putString(PASSWORD, password);
editor.putBoolean(LAST_AUTOLOGIN_FAILED, false);
editor.commit();
loginSucceeded(isAutoLogin);
}
@Override
public void onError(String message) {
SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(LAST_AUTOLOGIN_FAILED, true);
editor.commit();
loginFailed(message);
}
});
}
protected void loginFailed(String message) {
}
protected void loginSucceeded(boolean isAutoLogin) {
}
protected void startMainActivity(boolean isAutoLogin) {
Intent intent = new Intent(AbstractAuthenticationActivity.this, GadgeothekActivity.class);
startActivity(intent);
if (!isAutoLogin) {
// No animation when logging in automatically to make it faster
overridePendingTransition(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
}
finish();
}
}
|
Swift
|
UTF-8
| 3,138 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
//
// Animation.swift
// VPFramework
//
// Created by Vandan Patel on 11/4/17.
// Copyright © 2017 Vandan Patel. All rights reserved.
//
import UIKit
import UIKit
let appIdeasAnimation = AppIdeasAnimation.sharedInstance
class AppIdeasAnimation {
static let sharedInstance = AppIdeasAnimation()
func slideInAnimation(_ view: UIView, delay: Double, duration: Double) {
view.transform = CGAffineTransform(translationX: -(view.superview?.frame.width)!, y: 0)
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
view.transform = .identity
}) { (success) in }
}
func fadeInAnimation(_ view: UIView, delay: Double, duration: Double) {
view.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: .allowUserInteraction, animations: {
view.alpha = 1.0
}, completion: nil)
}
func scaleInAnimation(_ view: UIView, delay: Double, duration: Double) {
view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05)
UIView.animate(withDuration: duration, delay: delay, options: .allowUserInteraction, animations: {
view.transform = .identity
}, completion: nil)
}
func shakeAnimation(_ view: UIView) {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 3
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: view.center.x - 10, y: view.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: view.center.x + 10, y: view.center.y))
view.layer.add(animation, forKey: "position")
}
func hideView(_ view: UIView, withAnimation: Bool) {
if withAnimation {
UIView.animate(withDuration: 1.0, animations: {
view.alpha = 0.0
})
} else {
view.alpha = 0.0
}
}
func showView(_ view: UIView, withAnimation: Bool) {
if withAnimation {
UIView.animate(withDuration: 1.5, delay: 0.0, options: .allowUserInteraction, animations: {
view.alpha = 1.0
}, completion: nil)
} else {
view.alpha = 1.0
}
}
//animation for signUpVC
func hideView(_ view: UIView, withAnimation: Bool, completion: @escaping () -> ()) {
if withAnimation {
UIView.animate(withDuration: 1.0, animations: {
view.alpha = 0.0
}, completion: { (_) in
completion()
})
} else {
view.alpha = 0.0
completion()
}
}
//animation for signInVC
func buttonClickAnimation(for button: UIButton, completion: @escaping (Bool)->()) {
button.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
UIView.animate(withDuration: 0.2, animations: {
button.transform = .identity
}) { (success) in
completion(success)
}
}
}
|
PHP
|
UTF-8
| 1,111 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace App\Database\Repositories;
use App\Database\Eloquent\Repository;
use App\Database\Models\User;
use App\Helpers\RouteHelper;
class RoomRepository extends Repository
{
/**
* Return the model class name.
*
* @return string
*/
public function modelName()
{
return 'Room';
}
/**
* Create a new room
*
* @var User $user the user creating the room
* @return $this
*/
public static function store(User $user)
{
return self::create([
'user_id' => $user->id
]);
}
/**
* Check if the specified user has joined the room.
*
* @param User $user
* @return bool
*/
public function containsUser($user)
{
return $this->model->users->contains($user);
}
/**
* Add the specified user to the room.
*
* @param User $user
* @return bool
*/
public function addUser($user)
{
return $this->model->users()->save($user);
}
public function getKey()
{
return $this->model->key;
}
}
|
C
|
UTF-8
| 3,672 | 3.953125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
}TreeNode;
TreeNode *minVal(TreeNode *root) {
while(root != NULL && root->left != NULL && root->right != NULL) {
root = root->left;
}
return root;
}
TreeNode *maxVal(TreeNode *root) {
while(root != NULL && root->left != NULL && root->right != NULL) {
root = root->right;
}
return root;
}
int maxValue(TreeNode *root) {
while(root != NULL && root->left != NULL && root->right != NULL) {
root = root->right;
}
return root->data;
}
int minValue(TreeNode *root) {
while(root != NULL && root->left != NULL && root->right != NULL) {
root = root->left;
}
return root->data;
}
int treeHeight(TreeNode *root) {
int leftHeight, rightHeight;
if(root != NULL) {
leftHeight = treeHeight(root->left);
rightHeight = treeHeight(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
}
int treeSize(TreeNode *root) {
if(root != NULL) return 1 + treeSize(root->left) + treeSize(root->right);
}
void inorderTraversal(TreeNode *root) {
TreeNode *ptr = root;
if(ptr != NULL) {
inorderTraversal(ptr->left);
printf("Data: %d\n", ptr->data);
inorderTraversal(ptr->right);
}
}
void preorderTraversal(TreeNode *root) {
TreeNode *ptr = root;
if(ptr != NULL) {
printf("Data: %d\n", ptr->data);
preorderTraversal(ptr->left);
preorderTraversal(ptr->right);
}
}
void postorderTraversal(TreeNode *root) {
TreeNode *ptr = root;
if(ptr != NULL) {
postorderTraversal(ptr->left);
postorderTraversal(ptr->right);
printf("Data: %d\n", ptr->data);
}
}
TreeNode *addTree(TreeNode *root, int data) {
TreeNode *temp = (TreeNode *)malloc(sizeof(TreeNode));
TreeNode *ptr = root;
temp->data = data;
temp->left = temp->right = NULL;
temp->parent = NULL;
if(root == NULL) {
root = temp;
} else {
if(ptr->data > data) {
if(ptr->left == NULL) {
ptr->left = temp;
temp->parent = ptr;
}
else {
addTree(ptr->left, data);
}
} else {
if(ptr->right == NULL) {
ptr->right = temp;
temp->parent = ptr;
}
else {
addTree(ptr->right, data);
}
}
}
return root;
}
TreeNode *deleteTree2(TreeNode *root, int data) {
TreeNode *ptr = root, *temp = NULL;
while(ptr != NULL && ptr->data != data) {
if(data > ptr->data) ptr = ptr->right;
else if(data < ptr->data) ptr = ptr->left;
}
if(ptr == NULL) {
printf("The number to be deleted was not founded: %d\n", data);
return root;
}
if(ptr->left == NULL && ptr->right == NULL) {
if(ptr->data > ptr->parent->data) ptr->parent->right = NULL;
else if(ptr->data < ptr->parent->data) ptr->parent->left = NULL;
free(ptr);
} else if(ptr->left == NULL) {
if(ptr->parent->left->data == ptr->data) ptr->parent->left = ptr->right;
else if(ptr->parent->right->data == ptr->data) ptr->parent->right = ptr->right;
ptr->right->parent = ptr->parent;
free(ptr);
} else if(ptr->right == NULL) {
if(ptr->parent->left->data == ptr->data) ptr->parent->left = ptr->left;
else if(ptr->parent->right->data == ptr->data) ptr->parent->right = ptr->left;
ptr->left->parent = ptr->parent;
free(ptr);
} else if(ptr->left != NULL && ptr->right != NULL) {
temp = minVal(ptr->right);
ptr->data = temp->data;
if(temp->data > temp->parent->data) temp->parent->right = NULL;
else if(temp->data < temp->parent->data) temp->parent->left = NULL;
free(temp);
}
return root;
}
int main(void) {
TreeNode *root = NULL;
root = addTree(root, 10);
root = addTree(root, 5);
root = addTree(root, 3);
inorderTraversal(root);
root = deleteTree2(root, 8);
return 0;
}
|
Swift
|
UTF-8
| 3,972 | 2.515625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// UITextFieldProcessor.swift
// XibProcessor
//
// Created by 张楠[产品技术中心] on 2018/6/6.
//
import Foundation
import SWXMLHash
class UITextFieldProcessor: UIControlProcessor {
override func process(attrName: String, attrText: String) {
if attrName == "text" {
output[attrName] = attrText.quoteAsCodeString
} else if attrName == "borderStyle" {
output[attrName] = attrText.borderStyleString
} else if attrName == "placeholder" {
output[attrName] = attrText.quoteAsCodeString
} else if attrName == "textAlignment" {
output[attrName] = attrText.textAlignmentString
} else if attrName == "clearsOnBeginEditing" {
output[attrName] = attrText
} else if attrName == "adjustsFontForContentSizeCategory" {
output[attrName] = attrText
} else if attrName == "adjustsFontSizeToFit" {
output["adjustsFontSizeToFitWidth"] = attrText
} else if attrName == "minimumFontSize" {
output[attrName] = attrText
} else if attrName == "background" {
output[attrName] = "[UIImage imageNamed:\(attrText.quoteAsCodeString)]"
} else if attrName == "disabledBackground" {
output[attrName] = "[UIImage imageNamed:\(attrText.quoteAsCodeString)]"
} else if attrName == "clearButtonMode" {
output[attrName] = attrText.clearButtonModeString
}
}
override func process(childElem: SWXMLHash.XMLElement) {
let name = childElem.name
if name == "color" {
let attrName = childElem.attribute(by: "key")!.text
output[attrName] = childElem.colorString
} else if name == "fontDescription" {
output["font"] = childElem.fontString
} else if name == "textInputTraits" {
if let attrText = childElem.attribute(by: "autocapitalizationType")?.text {
output["autocapitalizationType"] = attrText.autocapitalizationTypeString
}
if let attrText = childElem.attribute(by: "autocorrectionType")?.text {
output["autocorrectionType"] = attrText.autocorrectionTypeString
}
if let attrText = childElem.attribute(by: "spellCheckingType")?.text {
output["spellCheckingType"] = attrText.spellCheckingTypeString
}
if let attrText = childElem.attribute(by: "keyboardType")?.text {
output["keyboardType"] = attrText.keyboardTypeString
}
if let attrText = childElem.attribute(by: "keyboardAppearance")?.text {
output["keyboardAppearance"] = attrText.keyboardAppearanceString
}
if let attrText = childElem.attribute(by: "returnKeyType")?.text {
output["returnKeyType"] = attrText.returnKeyTypeString
}
if let attrText = childElem.attribute(by: "enablesReturnKeyAutomatically")?.text {
output["enablesReturnKeyAutomatically"] = attrText
}
if let attrText = childElem.attribute(by: "secureTextEntry")?.text {
output["secureTextEntry"] = attrText
}
if let attrText = childElem.attribute(by: "smartDashesType")?.text {
output["smartDashesType"] = attrText.smartDashesTypeString
}
if let attrText = childElem.attribute(by: "smartInsertDeleteType")?.text {
output["smartInsertDeleteType"] = attrText.smartInsertDeleteTypeString
}
if let attrText = childElem.attribute(by: "smartQuotesType")?.text {
output["smartQuotesType"] = attrText.smartQuotesTypeString
}
} else {
super.process(childElem: childElem)
}
}
}
|
Ruby
|
UTF-8
| 2,349 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'forwardable'
require 'json'
require 'stringio'
require 'haml_lint/logger'
require 'cc/engine/issue'
module CC
module Engine
# Converts the +HamlLint+ report format to CodeClimate issues
class ReportAdapter
extend Forwardable
include Enumerable
# Instantiates a new report adapter
#
# @example
# CC::Engine::ReportAdapter.new(
# report: HamlLint::Report.new([], %w(a.haml)),
# root: "/tmp"
# )
#
# @api public
# @param [HamlLint::Report] report the report to adapt to CodeClimate
# @param [String] root the root path for the report
def initialize(report:, root:)
@report = report
@root = root
end
# @!method each
# Enumerates through the issues in a report
#
# @example
# adapter = CC::Engine::ReportAdapter.new(
# report: HamlLint::Report.new([], %w(a.haml)),
# root: "/tmp"
# )
#
# adapter.each { |issue| puts issue }
#
# @api public
# @see Array#each
# @return [Enumerator] an enumerator of the issues in the report
def_delegators :issues, :each
private
# The report to convert
#
# @api private
# @return [HamlLint::Report]
attr_reader :report
# The root for the analysis
#
# @api private
# @return [String]
attr_reader :root
# Creates all of the issues for a particular report analysis
#
# @api private
# @param [Hash] analysis the Hash of report analysis results
# @return [Array<CC::Engine::Issue>]
def create_issues_from(analysis)
analysis[:offenses].map do |offense|
Issue.new(offense.merge(path: analysis[:path], root: root))
end
end
# Converts the HamlLint JSON output to a list of issues
#
# @api private
# @return [Array<CC::Engine::Issue>]
def issues
@issues ||=
output
.fetch(:files, [])
.flat_map { |file| create_issues_from(file) }
end
# Captures the output from the HamlLint reporter
#
# @api private
# @return [String]
def output
@output ||= report.display
end
end
end
end
|
Java
|
UTF-8
| 1,847 | 3.734375 | 4 |
[] |
no_license
|
//给定一个字符串,逐个翻转字符串中的每个单词。
//
//
//
// 示例 1:
//
// 输入: "the sky is blue"
//输出: "blue is sky the"
//
//
// 示例 2:
//
// 输入: " hello world! "
//输出: "world! hello"
//解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
//
//
// 示例 3:
//
// 输入: "a good example"
//输出: "example good a"
//解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
//
//
//
//
// 说明:
//
//
// 无空格字符构成一个单词。
// 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
// 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
//
//
//
//
// 进阶:
//
// 请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。
// Related Topics 字符串
// 👍 224 👎 0
package leetcode.editor.cn.mainThread;
import org.junit.Test;
//Java:翻转字符串里的单词
//2020-09-22 15:27:17
public class P151ReverseWordsInAString {
@Test
public void testResult() {
//TO TEST
Solution solution = new P151ReverseWordsInAString().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String reverseWords(String s) {
String[] split = s.trim().split(" +");
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < split.length; i++) {
stringBuilder.append(split[split.length - 1 - i]).append(" ");
}
return stringBuilder.toString().trim();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
|
Java
|
UTF-8
| 708 | 2.015625 | 2 |
[] |
no_license
|
package com.example.android_shopping.interfaces.googs;
import com.example.android_shopping.interfaces.Callback;
import com.example.android_shopping.interfaces.IBaseModel;
import com.example.android_shopping.interfaces.IBasePresenter;
import com.example.android_shopping.interfaces.IBaseView;
import com.example.android_shopping.module.data.GoodsBean;
public interface IGoogs {
/**
* 契约类
*/
interface View extends IBaseView {
void getGoogsReturn(GoodsBean goodsBean);
}
interface Presenter extends IBasePresenter<IGoogs.View> {
void getGoogs(int id);
}
interface Model extends IBaseModel {
void getGoods(int id,Callback callback);
}
}
|
PHP
|
UTF-8
| 2,921 | 3.046875 | 3 |
[] |
no_license
|
<?php
// including the database connection file
$servername = "lab.chrhjq7ibkz8.us-east-1.rds.amazonaws.com";
$username = "master";
$password = "lab-password";
$dbname = "lab";
$mysqli = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['submit']))
{
$id = $_POST['id'];
$fname=$_POST['Firstname'];
$lname=$_POST['Lastname'];
$email=$_POST['Email'];
$ad=$_POST['Address'];
$tel=$_POST['Tel'];
// checking empty fields
if(empty($fname) || empty($lname) || empty($email)) {
if(empty($fname)) {
echo "<font color='red'>First Name field is empty.</font><br/>";
}
if(empty($lname)) {
echo "<font color='red'>Last Name field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE phonebook SET FirstName='$fname',LastName='$lname',Email='$email',Tel='$tel',Address='$ad' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM phonebook WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$fname = $res['FirstName'];
$lname = $res['LastName'];
$email = $res['Email'];
$tel = $res['Tel'];
$ad = $res['Address'];
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://s3.amazonaws.com/webapp-phone/style.css"/>
</head>
<body>
<img src="https://s3.amazonaws.com/webapp-phone/banner_address_book.gif" width = "1920">
<br>
<div class="form">
<p><a href="index.php">View Phonebook</a></p>
<div>
<p style="color:#FF0000;"></p>
<form action="" method="post">
<div class = "input-group">
<label>First Name:</label>
<input type ="text" name="Firstname" value="<?php echo $fname;?>">
</div>
<div class = "input-group">
<label>Last Name:</label>
<input type ="text" name="Lastname" value="<?php echo $lname;?>">
</div>
<div class = "input-group">
<label>Telephone:</label>
<input type ="text" name="Tel" value="<?php echo $tel;?>">
</div>
<div class = "input-group">
<label>Address:</label>
<input type ="text" name="Address" value="<?php echo $ad;?>">
</div>
<div class = "input-group">
<label>Email:</label>
<input type ="text" name="Email" value="<?php echo $email;?>">
</div>
<div class = "input-group">
<input type="hidden" name="id" value=<?php echo $_GET['id'];?>>
<button class="btn" type="submit" name="submit">EDIT</button>
</div>
</form>
</body>
</html>
|
Java
|
UTF-8
| 235 | 2.640625 | 3 |
[] |
no_license
|
package optional;
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String nullString = null;
String optionalS = Optional.ofNullable(nullString).orElse("");
}
}
|
Java
|
UTF-8
| 2,090 | 3.21875 | 3 |
[] |
no_license
|
package study.patter.prototype.testclone;
import study.patter.prototype.original.Desciption;
import study.patter.prototype.original.Original;
/*
* date 20180712
* author suxin
* desciptioni 深度克隆复制的不是一份引用,即新产生的对象和原始对象中的非基本数据类型的属性指向的不是同一个对象
* */
public class DeepClone {
public static void main(String[] args) {
Original original = new Original();
original.setId(1);
original.setName("Original");
Desciption desciption = new Desciption();
desciption.setDesciption("this is child class");
original.setDesciption(desciption);
Original target = new Original();
Desciption targetDesciption = new Desciption();
targetDesciption.setDesciption(desciption.getDesciption());
target.setId(original.getId());
target.setDesciption(targetDesciption);
target.setName(original.getName());
if(target.getName() == original.getName()){
System.out.println("name:"+true);
}else{
System.out.println("name:"+false);
}
if(target.getDesciption() == original.getDesciption()){
System.out.println("desciption:"+true);
}else{
System.out.println("desciption:"+false);
}
System.out.println("original desciption is:"+original.getDesciption()+":"+original.getDesciption().getDesciption());
System.out.println("target desciption is:"+target.getDesciption()+":"+target.getDesciption().getDesciption());
desciption.setDesciption("This is change");
original.setDesciption(desciption);
original.setId(2);
System.out.println("original desciption is:"+original.getDesciption()+":"+original.getDesciption().getDesciption());
System.out.println("target desciption is:"+target.getDesciption()+":"+target.getDesciption().getDesciption());
System.out.println("original id is:"+original.getId());
System.out.println("target id is:"+target.getId());
}
}
|
Swift
|
UTF-8
| 988 | 3.125 | 3 |
[] |
no_license
|
//
// FaceExpression.swift
// standford_view
//
// Created by Myeongjin kyeong on 2017. 6. 14..
// Copyright © 2017년 Myeongjin kyeong. All rights reserved.
//
import Foundation
struct FacialExpression {
let eyes: Eyes
let mouth : Mouth
enum Eyes : Int{
case open
case closed
case squinting
}
enum Mouth : Int{
case frown
case smirk
case netrual
case grin
case smile
var sadder : Mouth{
return Mouth(rawValue : rawValue - 1) ?? .frown
}
var happier : Mouth{
return Mouth(rawValue : rawValue + 1) ?? .smile
}
}
var sadder: FacialExpression{
return FacialExpression(eyes: self.eyes, mouth: self.mouth.sadder)
}
var happier: FacialExpression{
return FacialExpression(eyes: self.eyes, mouth: self.mouth.happier)
}
}
|
Python
|
UTF-8
| 523 | 3.734375 | 4 |
[] |
no_license
|
# Judge Route Circle
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
# Time Comp O( len(moves))
# Space Comp is O(1)
x,y = 0,0
for m in moves:
if m == "U":
y += 1
elif m == "D":
y -= 1
elif m == "R":
x += 1
else:
x -= 1
if x == 0 and y == 0 :
return True
return False
|
Java
|
ISO-8859-13
| 650 | 3.140625 | 3 |
[] |
no_license
|
package recurso;
public class Pessoa {
char sexo;
float altura;
float massa;
String nome;
public Pessoa(String n,char sexo)
{
nome=n;
this.sexo=sexo;
}
public void andar(int passos) {System.out.println("Andei "+ passos+ " passos"); }
public void falar(String oque){ System.out.println("Frase: " + oque);}
public void ouvir(){}
public boolean sorrir(){return true;}
public void comer(String oque) {}
public static void main(String[] args) {
// TODO Auto-generated method stub
Pessoa J=new Pessoa("Joo",'M');
J.falar("Meu nome Joo e nasci agora");
J.andar(3);
}
}
|
Markdown
|
UTF-8
| 2,673 | 2.59375 | 3 |
[] |
no_license
|
> [Livre des monstres](tome_of_beasts_old.md)
---
# Mi-Go
- Source: (LDM p300)(TOB p287)
- TOB: Mi-Go
- Plante de taille Moyenne (M), neutre mauvaise
- **Classe d'armure** 17 (armure naturelle)
- **Points de vie** 76 (8d8+40)
- **Vitesse** 9 m, vol 18 m
|FOR|DEX|CON|INT|SAG|CHA|
|---|---|---|---|---|---|
|16 (+3)|19 (+4)|21 (+5)|25 (+7)|15 (+2)|13 (+1)|
- **Jets de sauvegarde** For +6, Con +8, Cha +4
- **Compétences** Arcanes +10, Supercherie +7, Médecine +5, Perception +5, Discrétion +7
- **Résistance aux dégâts** radiants, de froid
- **Sens** vision aveugle 9 m, vision dans le noir 72 m, Perception passive 15
- **Langues** commun, mi-go, langue du Vide
- **Dangerosité** 5 (1 800PX)
**_Voyageur astral._** Un mi-go n'a pas besoin d'air ni de chaleur pour survivre, uniquement de la lumière solaire (et très peu). Il peut prendre une forme de spore capable de survivre aux voyages dans le vide et de reprendre conscience une fois les conditions redevenues favorables.
**_Attaque sournoise (1/tour)._** Le mi-go inflige 7 (2d6) dégâts supplémentaires à sa cible s'il la touche avec une attaque de
griffes et qu'il est avantagé lors de son jet d'attaque, ou si elle se trouve dans un rayon de 1,50 mètre autour d'un allié non neutralisé du mi-go et que ce dernier n'est pas désavantagé lors de son jet d'attaque.
**_Technologie inquiétante._** Les mi-gos forment une race très évoluée et beaucoup ont des objets de haute technologie. On peut représenter ces objets technologiques en utilisant les mêmes règles que pour les objets magiques, mais leur fonction est plus difficile à identifier : identification ne sert à rien, il faut passer 1heure à étudier l'objet mi-go et réussir un test d'Arcanes DD 19 pour comprendre son utilité et son fonctionnement.
## ACTIONS
**_Attaques multiples._** Le mi-go fait deux attaques de griffes.
**_Griffes._** _Attaque d'arme au corps à corps :_ +7 pour toucher, allonge 1,50 m, une cible. Touché: 14 (3d6+4) dégâts tranchants et la cible est empoignée (évasion DD13). Si les deux attaques de griffes touchent la même cible lors d'un même tour, cette cible subit 13 (2d12) dégâts psychiques supplémentaires.
## RÉACTIONS
**_Libération de spores._** Quand un mi-go meurt, il libère les spores qu'il lui restait. Toute créature vivante dans un rayon de 3 mètres subit 14 (2d8+5) dégâts de poison et se trouve empoisonnée. Si elle réussit un jet de sauvegarde de Constitution DD 16, les dégâts sont réduits de moitié et elle n'est pas empoisonnée. Une créature empoisonnée refait le jet à la fin de son tour et met un terme à l'effet sur un succès.
|
C#
|
UTF-8
| 1,763 | 2.515625 | 3 |
[] |
no_license
|
using ActivityMessaging;
using MassTransit.Util;
using Models;
using System.Collections.Generic;
namespace ServiceLayer
{
//service layer
public class DMBus
{
//ovo treba da postane interfejs
private static RabbitMqBus _bus;
public DMBus(RabbitMqBus rabbit)
{
_bus = rabbit;
}
public void Start(Activity activity)
{
ConfigureInput(activity.InputDocuments);
ConfigureOutput(activity.OutputDocuments);
_bus.StartBus();
}
public DocumentsResponse SendRequest(Document input)
{
return _bus.Request(input);
}
public void SendDocument(Document document)
{
_bus.Publish(document);
}
private void ConfigureInput(IEnumerable<Document> inputs)
{
if(inputs != null)
foreach (var input in inputs)
{
switch (input.InputOperation)
{
case InputOperations.Read:
_bus.AddConsumer(input);
break;
case InputOperations.Request:
break;
}
}
}
private void ConfigureOutput(IEnumerable<Document> outputs)
{
if (outputs != null)
foreach (var output in outputs)
{
switch (output.OutputOperation)
{
case OutputOperations.Send:
break;
case OutputOperations.Create:
_bus.AddRequestConsumer(output);
break;
}
}
}
}
}
|
PHP
|
UTF-8
| 2,468 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Crm\PaymentsModule\Hermes;
use Crm\PaymentsModule\Repository\RetentionAnalysisJobsRepository;
use Crm\PaymentsModule\Retention\RetentionAnalysis;
use Nette\Localization\Translator;
use Psr\Log\LoggerAwareTrait;
use Tomaj\Hermes\Handler\HandlerInterface;
use Tomaj\Hermes\MessageInterface;
class RetentionAnalysisJobHandler implements HandlerInterface
{
use LoggerAwareTrait;
private static $currentJobId = null;
private int $executionTimeLimit = 30; // in minutes
public function __construct(
private RetentionAnalysisJobsRepository $retentionAnalysisJobsRepository,
private RetentionAnalysis $retentionAnalysis,
private Translator $translator
) {
}
/**
* Set maximum execution time of retention analysis (default is 30 minutes)
*
* @param int $minutes maximum execution time
*/
public function setExecutionTimeLimit(int $minutes): void
{
$this->executionTimeLimit = $minutes;
}
public function handle(MessageInterface $message): bool
{
set_time_limit(60 * $this->executionTimeLimit);
$payload = $message->getPayload();
$job = $this->retentionAnalysisJobsRepository->find($payload['id']);
if (!$job) {
throw new \InvalidArgumentException("No retention analysis job with id #{$payload['id']} found.");
}
// Only first handler being run (in Hermes worker) should register a shutdown function.
// This prevents multiple shutdown functions registration since worker may run without shutting down between jobs processing
if (!self::$currentJobId) {
// If execution takes too long, record it failed
register_shutdown_function(function () {
$longExecutionErrorMessage = $this->translator->translate('payments.admin.retention_analysis.errors.long_execution_time', ['minutes' => $this->executionTimeLimit]);
$this->retentionAnalysisJobsRepository->setFailed(self::$currentJobId, $longExecutionErrorMessage);
});
}
self::$currentJobId = $job->id;
try {
$this->retentionAnalysis->runJob($job);
} catch (\Throwable $exception) {
$this->retentionAnalysisJobsRepository->setFailed($job->id, $this->translator->translate('payments.admin.retention_analysis.errors.unexpected_error'));
throw $exception;
}
return true;
}
}
|
Java
|
UTF-8
| 1,342 | 2.171875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.imadcn.framework.lock.spring.schema;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import com.imadcn.framework.lock.redis.RedisLockManager;
public class LockBeanDefinitionParser extends BaseBeanDefinitionParser {
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(RedisLockManager.class);
String group = element.getAttribute("group");
String redisTemplate = element.getAttribute("redisTemplate");
String messageContainer = element.getAttribute("messageContainer");
if (!StringUtils.hasText(group)) {
throw new IllegalArgumentException("redis lock group name should not be null");
}
builder.addPropertyValue("groupName", group);
if (StringUtils.hasText(redisTemplate)) {
builder.addPropertyReference("redisTemplate", redisTemplate);
}
if (StringUtils.hasText(messageContainer)) {
builder.addPropertyReference("container", messageContainer);
}
builder.setInitMethodName("init");
return builder.getBeanDefinition();
}
}
|
Java
|
UTF-8
| 823 | 2.390625 | 2 |
[] |
no_license
|
package com.abee.ftp;
import com.abee.ftp.client.AdvancedOperationSet;
import com.abee.ftp.client.BasicOperationSet;
import com.abee.ftp.client.MyFtpClient;
import com.abee.ftp.client.secure.Authenticator;
import org.apache.commons.codec.DecoderException;
import java.io.*;
/**
* @author xincong yao
*/
public class FtpClient {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Authenticator authenticator = new Authenticator();
authenticator.connect("localhost", 2222);
authenticator.authenticate();
MyFtpClient client = new MyFtpClient();
client.connect("localhost", 2221);
client.upload("D:/OTHER/client/root", "D:/OTHER/server/root", false);
//client.download("D:/OTHER/server/root", "D:/OTHER/client/root", true);
}
}
|
Python
|
UTF-8
| 3,318 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
from dskc.visualization.graphs import bars, bars_target_proportion
from dskc._util.string import get_display_text
from dskc.visualization.terminal.jupyter import markdown_h2
from dskc._util.dates import get_weekdays
from . import util
def time_graphs(df, column, ylabel="", year=True, month=True, day=True, weekday=True):
'''
Display graphs by year, month, day and weekday
:param df: pandas dataframe
:param column: column name
:param ylabel:
:param year:
:param month:
:param day:
:param weekday:
:return:
'''
ylabel = ylabel.capitalize()
if year:
series = df[column + "_YEAR"]
title = "over the Years"
if ylabel:
title = ylabel + " " + title
title = title.capitalize()
bars(series,
sort_labels=True,
title=title,
xlabel="Year",
ylabel=ylabel)
if month:
series = df[column + "_MONTH"]
title = "over the Months"
if ylabel:
title = ylabel + " " + title
title = title.capitalize()
bars(series,
sort_labels=True,
title=title,
xlabel="Month",
ylabel=ylabel)
if day:
title = "over the Days"
if ylabel:
title = ylabel + " " + title
title = title.capitalize()
bars(df[column + "_DAY"],
title=title,
sort_labels=True,
xlabel="Day",
ylabel=ylabel)
if weekday:
series = df[column + "_WEEKDAY"]
title = "over the Weeks"
if ylabel:
title = ylabel + " " + title
title = title.capitalize()
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
bars(series,
sort_labels=True,
title=title,
xlabel="Day of the Week",
xticks=days,
ylabel=ylabel)
def _bars(series, xticks, section_number, sub_section, display_name):
sub_section = util.header(section_number, sub_section, "{} Bars Graph".format(display_name))
bars(series,
sort_labels=True,
xticks=xticks)
return sub_section
def _bars_proportion(df, name, xticks, target, target_true, section_number, sub_section, display_name):
sub_section = util.header(section_number, sub_section, "{} Mean Success Bars Graph".format(display_name))
bars_target_proportion(df, name, target,
sort_labels=True,
target_true=target_true,
xticks=xticks)
return sub_section
def date_col(df, name, target, target_true=False, section_number=1):
# set names
display_name = get_display_text(name)
sub_section = 1
# set series
series = df[name]
# graphs
if str(series.dtype).find("date") >= 0:
return
markdown_h2("Line graph")
# todo line
if name.lower().endswith("_weekday"):
xticks = get_weekdays()
else:
xticks = False
# bars
sub_section = _bars(series, xticks, section_number, sub_section, display_name)
# bars proportion
if target:
_bars_proportion(df, name, xticks, target, target_true, section_number, sub_section, display_name)
|
Python
|
UTF-8
| 4,581 | 2.734375 | 3 |
[] |
no_license
|
from app import app
from flask import render_template
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html', title='Home')
#########################################
##### My Stuff Below #####
#########################################
@app.route('/test')
def test():
return render_template('test.html', title = 'Test')
@app.route('/processerror')
def processeserror():
return render_template('processerror.html', title='Error')
@app.route('/speciesunknown')
def speciesunknown():
return render_template('speciesunknown.html', title='Mysterious')
#@app.route('/newpage')
#def newpage():
# return render_template('newpage.html', title='Playground')
@app.route('/results')
def results():
backend_value = 'complete' # incomplete until function 2 finishes.
species = 'test' # unknown vs. species vs. null to be filled by lookup from csv
if backend_value == 'incomplete':
return render_template('loading.html', title='loading') ##HOW TO SET REFRESH TIIMER
elif backend_value == 'complete':
if species =='unknown':
return render_template('speciesunknown.html', title='Mysterious')
else:
return render_template('results.html', title='Mysterious')
else:
return render_template('processerror.html', title='Error')
############################
@app.route('/newresults')
def new_results():
import pandas
from google.cloud import storage
storage_client = storage.Client()
def download_blob(bucket_name1, source_blob_name1, destination_file_name1):
bucket = storage_client.get_bucket(bucket_name1)
blob1 = bucket.blob(source_blob_name1)
blob1.download_to_filename(destination_file_name1)
print('Blob {} downloaded to {}.'.format(source_blob_name1, destination_file_name1))
download_blob('tempml_bucket4', 'query_results.txt', '/tmp/query_results.csv')
df = pandas.read_csv('/tmp/query_results.csv')
return render_template('new_results.html', title='New Results', UniqueName = df['UniqueName'][0], GenusName = df['GenusName'][0], SpeciesName = df['SpeciesName'][0], Family = df['Family'][0], Order = df['Order'][0], CommonName = df['CommonName'][0], Leaf_Type = df['Leaf_Type'][0], GrowthRate = df['GrowthRate'][0], MatureHeight_ft = df['MatureHeight_ft'][0], URLLink = df['URLLink'][0], ImageLink = df['ImageLink'][0])
############################
# if species == 'unknown':
# return render_template('test.html', title='Mysterious')
# else:
# return render_template('index.html', title='wtf?')
# else:
# return render_template('processerror.html', title='Error')
#@app.route('/results')
#def results():
# backend_state = 1 ### We'll make a function that tests backend to see if ready, broken, etc.
# species = 'spot'
# if backend_state == 1 and species == 'unknown':
# return render_template('speciesunknown.html', title='Mysterious')
# elif backend_state == 1:
# return render_template('results.html', title='Classification Results')
# elif backend_state == 0:
# return render_template('processerror.html', title='Error')
# else:
# return render_template('processerror.html', title='Error')
## For above, we'll need function that keeps checking to see output form backend.
#@app.route('/prediction')
#def prediction():
# if output file is a species name
# render everything in the output file
# elif output file is unknown_species
# render "STUMPED" template (function ran but species not known)
# elif error in returning file:
# if counter < threshold
# render loading page#
# add to counter
# refresh in 10 seconds
# if counter >= threshold:
# render error page (something went wrong, function did not produce output).
#
#try:
# f = open(fname, 'rb')
#except OSError:
# print "Could not open/read file:", fname
# sys.exit()
#
#with f:
# reader = csv.reader(f)
# for row in reader:
# pass #do stuff here
#
########## OLD INDEX BELOW:
#def index():
# user = {'username': 'Albus'}
# posts = [
# {
# 'author': {'username': 'Minerva'},
# 'body': 'Disloyalty!?'
# },
# {
# 'author': {'username': 'Severus'},
# 'body': 'I miss Lilly'
# }
# ]
# return render_template('index.html', title='Home', user=user['username'], posts=posts)
|
Markdown
|
UTF-8
| 1,010 | 3 | 3 |
[] |
no_license
|
---
title: "great mens circle tonight"
tags: [ "mkp", "circle" ]
author: Rob Nugen
date: 2018-08-14T22:50:52+09:00
---
##### 22:50 Tuesday 14 August 2018 JST
Four men in the circle tonight, including two relatively newcomers. I
experienced beautiful facilitation to help me get the courage to
implement my new idea.
I have just sent this message to my friend H.
I am thinking about doing a 6 month set of weekly circles on
Friday nights. Could I do them at your place? Would you be able
to attend, assuming you'd be interested in the content?
My idea is to do something very close to the men's circle, but
with a focus of finding one's mission/purpose in life. Once the
circle is formed relatively well, we would do an exercise for each
person to find their life mission, and then focus on implementing
that life mission for the remaining 3 months or so. The timing I
have in mind is just a rough guess, but wondering if you would be
interested in participating?
|
Python
|
UTF-8
| 2,881 | 2.921875 | 3 |
[] |
no_license
|
"""
Project:
File: main.py
Created by: louise
On: 10/13/17
At: 3:09 PM
"""
from __future__ import print_function
import time
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import torch.optim as optim
import torchvision.transforms as transforms
from scipy.misc import face
from primal_dual_model import PrimalDualNetwork
from energies import PrimalEnergyROF, DualEnergyROF
from differential_operators import ForwardGradient, BackwardDivergence
if __name__ == '__main__':
# cuda
use_cuda = torch.cuda.is_available()
print("Cuda = ", use_cuda)
dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
pil2tensor = transforms.ToTensor()
tensor2pil = transforms.ToPILImage()
t0 = time.time()
# Create image to noise and denoise
img_ = face(True)
h, w = img_.shape
img_.resize((h, w, 1))
img_tensor = pil2tensor(img_.transpose(1, 0, 2)).cuda()
img_ref = Variable(img_tensor)
img_obs = img_ref + Variable(torch.randn(img_ref.size()).cuda() * 0.1)
# Parameters
norm_l = 7.0
max_it = 200
theta = 1.0
tau = 0.01
sigma = 1.0 / (norm_l * tau)
#lambda_TVL1 = 1.0
lambda_rof = 7.0
x = Variable(img_obs.data.clone()).cuda()
x_tilde = Variable(img_obs.data.clone()).cuda()
img_size = img_ref.size()
y = Variable(torch.zeros((img_size[0]+1, img_size[1], img_size[2]))).cuda()
perof = PrimalEnergyROF()
p_nrg = perof.forward(x, img_obs, lambda_rof)
print("Primal Energy = ", p_nrg.data)
derof = DualEnergyROF()
d_nrg = derof.forward(y, img_obs)
print("Dual Energy = ", d_nrg)
# Solve ROF
primal = np.zeros((max_it,))
dual = np.zeros((max_it,))
gap = np.zeros((max_it,))
primal[0] = p_nrg.data[0]
dual[0] = d_nrg.data[0]
fwdgd = ForwardGradient()
y = fwdgd.forward(x, dtype=torch.cuda.FloatTensor)
# Plot reference, observed and denoised image
# f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
# ax1.imshow(tensor2pil(img_ref.data.cpu()))
# ax1.set_title("Reference image")
# ax2.imshow(tensor2pil(img_obs.data.cpu()))
# ax2.set_title("Observed image")
# ax3.imshow(tensor2pil(x_tilde.data.cpu()))
# ax3.set_title("Denoised image")
# Net approach
t0 = time.time()
net = PrimalDualNetwork()
dn_image = net.forward(x)
print("Elapsed time = ", time.time() - t0, "s")
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
# Display results
ax1.imshow(tensor2pil(img_ref.data.cpu()))
ax1.set_title("Reference image")
ax2.imshow(tensor2pil(img_obs.data.cpu()))
ax2.set_title("Observed image")
ax3.imshow(tensor2pil(dn_image.data.cpu()))
ax3.set_title("Denoised image")
plt.show()
|
Java
|
UTF-8
| 14,400 | 2.4375 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Thread;
import com.monitorjbl.xlsx.StreamingReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author MinhPC
*/
public class ProcessingExcelFile implements ProcessExcel {
private String filePath;
private File file;
private int instanceNumber;
private JSONArray listColumn;
private int transactionNumber;
private JSONArray listTransaction;
Workbook workbook = null;
HSSFWorkbook wb_xls = null;
public ProcessingExcelFile() {
}
;
public ProcessingExcelFile(String filePath) {
this.filePath = filePath;
try {
file = new File(filePath);
if (file.getName().contains(".xlsx")) {
/*Xử lý nếu file là dạng xlsx*/
InputStream is = null;
try {
is = new FileInputStream(file);
workbook = StreamingReader.builder()
.rowCacheSize(100) // number of rows to keep in memory (defaults to 10)
.bufferSize(4096) // buffer size to use when reading InputStream to file (defaults to 1024)
.open(is); // InputStream or File for XLSX file (required)
Sheet mysheet = workbook.getSheetAt(0);
instanceNumber = mysheet.getLastRowNum() - 1;
JSONArray listColumn = new JSONArray();
int index = 0;
for (Row r : mysheet) {
String str = "";
for (Cell c : r) {
JSONObject json = new JSONObject();
json.put("index", index++);
json.put("value", c.getStringCellValue());
listColumn.put(json);
}
break;
}
this.listColumn = listColumn;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
} else if (file.getName().contains(".xls")) {
/*Xử lý file khi là dạng xls*/
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
wb_xls = new HSSFWorkbook(fs);
HSSFSheet sheet = wb_xls.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for (int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if (row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if (tmp > cols) {
cols = tmp;
}
}
}
JSONArray listColumn = new JSONArray();
int index = 0;
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c < cols; c++) {
cell = row.getCell((short) c);
if (cell != null) {
JSONObject json = new JSONObject();
json.put("index", index++);
json.put("value", cell.toString());
listColumn.put(json);
}
}
}
break;
}
this.listColumn = listColumn;
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
} catch (Exception e) {
}
}
@Override
public JSONArray listColumn() {
return listColumn;
}
@Override
public int getTransactionNumber() {
return transactionNumber;
}
@Override
public int getInstanceNumber() {
return instanceNumber;
}
@Override
public JSONArray listTransaction(JSONObject ids, JSONObject items) {
//ids là để xác định ids transaction
int indexOfIds = ids.getInt("index");
int indexOfItems = items.getInt("index");
JSONArray list = new JSONArray();
if (file.getName().contains(".xlsx")) {
Sheet mysheet = workbook.getSheetAt(0);
for (Row r : mysheet) {
JSONObject json = new JSONObject();
for (Cell c : r) {
if (c.getColumnIndex() == indexOfIds) {
json.put("idItem", c.getStringCellValue());
}
if (c.getColumnIndex() == indexOfItems) {
if(c.getStringCellValue()!=null && !c.getStringCellValue().equals(""))
json.put("valueItem", c.getStringCellValue().replaceAll(" ", "_"));
else json.put("valueItem", "null");
}
}
list.put(json);
}
} else if (file.getName().contains(".xls")) {
HSSFSheet sheet_xls = wb_xls.getSheetAt(0);
int rows; // No of rows
rows = sheet_xls.getPhysicalNumberOfRows();
HSSFRow row;
HSSFCell cell;
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for (int i = 0; i < 10 || i < rows; i++) {
row = sheet_xls.getRow(i);
if (row != null) {
tmp = sheet_xls.getRow(i).getPhysicalNumberOfCells();
if (tmp > cols) {
cols = tmp;
}
}
}
for (int r = 0; r < rows; r++) {
JSONObject json = new JSONObject();
row = sheet_xls.getRow(r);
if (row != null) {
for (int c = 0; c < cols; c++) {
cell = row.getCell((short) c);
if (cell != null) {
if (cell.getColumnIndex() == indexOfIds) {
json.put("idItem", cell.toString());
}
if (cell.getColumnIndex() == indexOfItems) {
json.put("valueItem", cell.toString().replaceAll(" ", "_"));
}
}
}
}
list.put(json);
}
}
System.out.println("============>" + list.length());
JSONArray result = new JSONArray();
int transactionNumber = 0;
int current = 0;
while (current < (list.length() - 2)) {
JSONObject _new = new JSONObject();
JSONArray itemList = new JSONArray();
JSONObject json = list.getJSONObject(current);
System.out.println(json.toString());
_new.put("id", json.getString("idItem"));
if(json.getString("valueItem")!=null&&json.getString("valueItem")!="")
itemList.put(json.getString("valueItem"));
else itemList.put(" ");
int temp = current + 1;
try {
while (list.getJSONObject(temp).getString("idItem").equals(json.getString("idItem"))) {
itemList.put(list.getJSONObject(temp).getString("valueItem"));
temp++;
}
} catch (Exception e) {
return result;
}
_new.put("list", itemList);
// System.out.println(_new);
result.put(_new);
current = temp;
transactionNumber++;
}
this.transactionNumber = transactionNumber;
//items là id của item
return result;
}
public void convertToTxt(int collumId, int collumItem) {
JSONArray listT = this.listTransaction(this.listColumn.getJSONObject(collumId), this.listColumn.getJSONObject(collumItem));
this.transactionNumber = listT.length();
try {
//Bước 1: Tạo đối tượng luồng và liên kết nguồn dữ liệu
File f = new File(System.getProperty("user.dir") + "/data.txt");
FileWriter fw = new FileWriter(f);
//Bước 2: Ghi dữ liệu
for (int i = 0; i < listT.length(); i++) {
JSONObject obj = listT.getJSONObject(i);
JSONArray itemSet = obj.getJSONArray("list");
for (int j = 0; j < itemSet.length(); j++) {
// System.out.println(itemSet.get(j));
fw.write(itemSet.get(j).toString());
if (j < itemSet.length() - 1) {
fw.write(" ");
}
}
fw.write("\r\n");
// fw.write(obj[0]);
}
//Bước 3: Đóng luồng
fw.close();
} catch (IOException ex) {
System.out.println("Loi ghi file: " + ex);
}
}
public void convertToTxtFColumn(DefaultTableModel model) {
ArrayList<Integer> array = new ArrayList<Integer>();
int j = 0;
for (int i = 0; i < model.getRowCount(); i++) {
boolean val = (boolean) model.getValueAt(i, 1);
if (val == true) {
System.out.println(i);
array.add(i);
j++;
}
}
System.out.println(array.toString());
try {
//Bước 1: Tạo đối tượng luồng và liên kết nguồn dữ liệu
File f = new File(System.getProperty("user.dir") + "/data.txt");
FileWriter fw = new FileWriter(f);
//Bước 2: Ghi dữ liệu
if (file.getName().contains(".xlsx")) {
Sheet mysheet = workbook.getSheetAt(0);
System.out.println("array length : " + array.size());
for (Row r : mysheet) {
for (int i = 0; i < array.size(); i++) {
Cell cell = r.getCell(array.get(i));
String value = cell.getStringCellValue();
fw.write(value.replaceAll(" ", "_"));
fw.write(" ");
}
fw.write("\r\n");
}
} else if (file.getName().contains(".xls")) {
HSSFSheet sheet_xls = wb_xls.getSheetAt(0);
int rows; // No of rows
rows = sheet_xls.getPhysicalNumberOfRows();
HSSFRow row;
HSSFCell cell;
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for (int i = 0; i < 10 || i < rows; i++) {
row = sheet_xls.getRow(i);
if (row != null) {
tmp = sheet_xls.getRow(i).getPhysicalNumberOfCells();
if (tmp > cols) {
cols = tmp;
}
}
}
for (int r = 1; r < rows; r++) {
row = sheet_xls.getRow(r);
if (row != null) {
for (int i = 0; i < array.size(); i++) {
HSSFCell cel = row.getCell(array.get(i));
String value = cel.toString().replaceAll(" ", "_");
fw.write(value);
fw.write(" ");
}
}
fw.write("\r\n");
}
}
//Bước 3: Đóng luồng
fw.close();
} catch (IOException ex) {
System.out.println("Loi ghi file: " + ex);
}
}
public static void main(String[] args) {
// String filePath = "data/OnlineRetail2.xlsx";
// ProcessingExcelFile demo = new ProcessingExcelFile(filePath);
// demo.convertToTxt(0, 1);
// System.out.println("Number instance : " + demo.getInstanceNumber());
// System.out.println("Table of columns");
// JSONArray list = demo.listColumn();
// for (int i = 0; i < list.length(); i++) {
// JSONObject obj = list.getJSONObject(i);
//// System.out.println(obj);
// }
// JSONArray listT = demo.listTransaction(list.getJSONObject(7), list.getJSONObject(1));
// for (int i = 0; i < listT.length(); i++) {
// JSONObject obj = listT.getJSONObject(i);
// System.out.println(obj);
// }
}
}
|
Java
|
UTF-8
| 1,073 | 2.125 | 2 |
[] |
no_license
|
package com.kafka.producer.server;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class ProducerConfiguration {
@Bean
public Producer<String, String> initProducer() {
Properties props = new Properties();
props.put("bootstrap.servers", "box1:9092,box2:9092,box3:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
System.out.println("Initializing KafkaProducer");
return new KafkaProducer
<String, String>(props);
}
}
|
Markdown
|
UTF-8
| 629 | 4.03125 | 4 |
[
"MIT"
] |
permissive
|
# Caesar Cipher
A simple [caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) in Python.
This script takes text input and rotates each character according to a predefined numeric offset.
Disclaimer: This code is for learning purposes only and should never be used for practical purposes as it is easily reversable.
## Usage
Run caesar_cipher.py passing in quoted plaintext and an integer offset as program arguments.
eg. Running <code>python3 caesar_cipher.py "Encrypt Me" 3</code> will produce the following result:
<pre>
Caesar Cipher
Plaintext: Encrypt Me <br>
Offset: 3<br>
Ciphertext: Hqfu|sw#Ph<br>
</pre>
|
Swift
|
UTF-8
| 3,554 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
import NIO
import NIOHTTP1
import NetService
import Socket
import class Foundation.RunLoop
class MyServiceDelegate: NetServiceDelegate {
func netServiceWillPublish(_ sender: NetService) {
print("Will publish: \(sender)")
}
func netServiceDidPublish(_ sender: NetService) {
print("Did publish: \(sender)")
}
func netService(_ sender: NetService, didNotPublish error: Error) {
print("Did not publish: \(sender), because: \(error)")
}
func netServiceDidStop(_ sender: NetService) {
print("Did stop: \(sender)")
}
func netService(_ sender: NetService, didAcceptConnectionWith socket: Socket) {
print("Did accept connection: \(sender), from: \(socket.remoteHostname)")
print(try! socket.readString() ?? "")
try! socket.write(from: "HTTP/1.1 200 OK\r\nContent-Length: 14\r\n\r\nHello, Karbon!")
socket.close()
}
}
public class KarbonService {
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let threadPool = BlockingIOThreadPool(numberOfThreads: 6)
let host: String
let port: Int
var netService: NetService?
public init(host: String, port: Int) {
self.host = host
self.port = port
}
public func start() throws {
threadPool.start()
let bootstrap = ServerBootstrap(group: group)
// Specify backlog and enable SO_REUSEADDR for the server itself
.serverChannelOption(ChannelOptions.backlog, value: 256)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
// Set the handlers that are applied to the accepted Channels
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).then {_ in
channel.pipeline.add(handler: RequestHandler())
}
}
// Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
.childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1)
var sa = sockaddr_in()
sa.sin_family = sa_family_t(AF_INET)
sa.sin_addr.s_addr = UInt32(bigEndian: INADDR_ANY)
sa.sin_port = UInt16(port).bigEndian
let address = SocketAddress(sa, host: "")
let channel = try { () -> Channel in
return try bootstrap.bind(to: address).wait()
}()
guard let localAddress = channel.localAddress else {
fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.")
}
print("Server started and listening on \(localAddress)")
netService = NetService(domain: "local.", type: "_http._tcp.", name: "karbon", port: Int32(localAddress.port!))
let serviceDelegate = MyServiceDelegate()
_ = netService?.setTXTRecord(["id":"6789"])
netService?.delegate = serviceDelegate
netService?.publish()
try channel.closeFuture.wait()
}
public func stop() {
netService?.stop()
try! threadPool.syncShutdownGracefully()
try! group.syncShutdownGracefully()
print("Server closed")
}
}
|
JavaScript
|
UTF-8
| 354 | 2.6875 | 3 |
[] |
no_license
|
import * as types from './action.type'
const inniState = {
number: 0
}
export const reducer = (state = inniState, action) => {
switch (action.type) {
case types.PLUS:
return { number: state.number + 1 }
case types.MINUS:
return { number: state.number - 1 }
default:
return state
}
}
|
SQL
|
UTF-8
| 829 | 3.46875 | 3 |
[] |
no_license
|
drop table t_base_user_info_s_tbuserinfo_t_step3 ;
create table t_base_user_info_s_tbuserinfo_t_step3 as
select t3.*,prov as tel_prov,city as tel_city from
(
SELECT
uid as tb_id ,
regexp_replace(alipay, 'None', '-') as alipay,
buycnt,
verify,
regtime,
nick as tb_nick,
location as tb_location ,
t1.tgender as qq_gender,
t1.tage as qq_age,
t1.tname as qq_name,
t1.tloc as qq_loc
from t_base_user_info_s t1 RIGHT OUTER join
(select * from t_base_ec_tb_userinfo where ds=20160608) t2
on t1.ds=20160418 and t1.tb_id=t2.uid
)t3 LEFT join t_base_ec_loc t4 on t3.tb_id=t4.user_id ;
-- SELECT
-- COUNT(1)
-- from t_base_user_info_s t1 RIGHT OUTER join
-- (select * from t_base_ec_tb_userinfo where ds=20160608) t2
-- on t1.ds=20160418 and t1.tb_id=t2.uid
--
-- select COUNT(1) from t_base_ec_tb_userinfo where ds=20160608
|
Java
|
UTF-8
| 429 | 1.890625 | 2 |
[] |
no_license
|
package net.absolutioncraft.api.bukkit.rank;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import net.absolutioncraft.api.bukkit.rank.expirer.RankExpirer;
/**
* @author MelonDev
* @since 1.0.0
*/
public class RankExpirationModule extends AbstractModule {
@Override
protected void configure() {
bind(RankExpirer.class).to(RankExpirationChecker.class).in(Scopes.SINGLETON);
}
}
|
Markdown
|
UTF-8
| 1,300 | 2.828125 | 3 |
[] |
no_license
|
# jsonformat
Simple chrome extension to format JSON responses. Load the extension and click the "J" icon to format a response.
## Installation
This plugin hasn't been uploaded to the Chrome Web Store yet. Instead you can add this extension to Chrome by:
1. Downloading [the code](https://github.com/ColdHeat/jsonformat/archive/refs/heads/master.zip) and unzipping
2. Browse to [chrome://extensions](chrome://extensions) in Chrome
3. Click on the "Load Unpacked" button in the top left
4. Browse to the jsonformat folder that you just unzipped and select it
5. The extension should be installed! I recommend pinning it and allowing it in incognito
## Background
For whatever reason Chrome does not provide a prettified JSON viewer like Firefox does. This has led to there being a variety of JSON beautifier plugins in the Chrome Web Store.
These extensions often have the ability to read and modify all the pages I visit. Some extensions have gone further and added [forms of monitoring](https://github.com/teocci/JSONViewer-for-Chrome/issues/8) to their extension. I don't really want to trust these extensions with my browsing data.
Instead of being capable of running on every page this plugin takes a much less invasive approach by just formating JSON when you click on the extension icon.
|
Markdown
|
UTF-8
| 3,448 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[](https://github.com/BiltuDas1/the-private-torrent/releases/latest)
[](https://github.com/BiltuDas1/the-private-torrent/releases/tag/1.0.3)
[](https://github.com/BiltuDas1/the-private-torrent/issues/new/choose)
# The Private Torrent
**The Private torrent** is used for bypassing download limit on torrent files which was given by websites(Eg: TeamOS). The program stops sending download information to the announce URL so that users can download unlimited files from those websites.
* ### How Torrent works?
If you download any file using any torrent client, then the file transfers from the Bittorrent network which uses Peer-to-Peer (P2P) connection. P2P network means the file is transferred by many computers using this Bittorrent network.
* While downloading torrent, your torrent client connects to the uploader and nearby computers (called seeder), then it starts downloading. It downloads files like IDM by parting the file. If the torrent file is downloaded many times and too many people are seeding the torrent, then your download will be very faster than a normal torrent file.
* After your torrent client gets all parts, it then merges them and verifies the data. The end result is the files present on your storage and this is how torrent works.
* ### What are seeders, peers and leechers?
Seeders are the people who have the complete file, means they have downloaded the complete file.
* Peers are those persons who haven't downloaded the complete file, they have pieces of the torrent data.
* Leechers are those persons who downloaded complete file, but they don't share his data to the seeders or peers.
## How the Program Works?
Usually, all operations are done by our Bittorrent client. If our client got a seeding request, then it seeds.
But the modified torrent client (For Windows) doesn't follow the rule. It stops sending announce url about download information, so that the announce url doesn't detect how much size of data are downloaded.
**Note:** The torrent should be downloaded before the tracker update time ends.
**Edit:** Now The Windows Application only can bypass announce update time, just you need to use Pause button before the update time ends.
## Download and Installation
NOTE : MAKE SURE TO CHECK MD5 BEFORE USING, SOME ANTIVIRUS MAY DETECT THE PROGRAM AS VIRUS, IT'S FALSE POSITIVE.
**Windows:**
* Just Download the latest version of the Program, and Double-click on it, confirm Admin password, then it will install automatically (It's a silent installer).
**Linux:**
* qBittorrent: Install and Launch qBitttorrent (Don't add any torrent and keep all settings by default). Now close the qBittorrent, Make sure you closed qBittorrent from the tray. Now extract the archive file. Open Terminal into the extracted folder directory with user permission (Don't run it as Adminisrator) and type
```
bash install
```
**macOS:**
* Coming Soon...
# Contact
If you are interested then you can join into our telegram group [@techsouls0](https://t.me/techsouls0) or channel [@tecsouls](https://t.me/tecsouls)
|
C#
|
UTF-8
| 782 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace Workflow.Controls
{
public class GradientButton:Button
{
public BindableProperty StartColor { get; set; }
public BindableProperty EndColor { get; set; }
public Color Start { get; set; }
public Color End { get; set; }
public GradientButton() : base()
{
StartColor = BindableProperty.Create("StartColor", typeof(Color), typeof(Color), Color.FromHex("#2fa362"));
EndColor = BindableProperty.Create("EndColor", typeof(Color), typeof(Color), Color.FromHex("#237547"));
Start = (Color)GetValue(StartColor);
End = (Color)GetValue(EndColor);
}
}
}
|
Markdown
|
UTF-8
| 1,589 | 2.609375 | 3 |
[] |
no_license
|
[Back to the Ling/Light_DatabaseInfo api](https://github.com/lingtalfi/Light_DatabaseInfo/blob/master/doc/api/Ling/Light_DatabaseInfo.md)<br>
[Back to the Ling\Light_DatabaseInfo\Helper\TypeHelper class](https://github.com/lingtalfi/Light_DatabaseInfo/blob/master/doc/api/Ling/Light_DatabaseInfo/Helper/TypeHelper.md)
TypeHelper::getSimpleTypes
================
TypeHelper::getSimpleTypes — Returns an array of column name => simple type from the given sql types.
Description
================
public static [TypeHelper::getSimpleTypes](https://github.com/lingtalfi/Light_DatabaseInfo/blob/master/doc/api/Ling/Light_DatabaseInfo/Helper/TypeHelper/getSimpleTypes.md)(array $types) : array
Returns an array of column name => simple type from the given sql types.
The simple types are either:
- str: a string type, such as varchar, char, text, ...
- int: an int type, such as int, tinyint, float, decimal, but also bit, bool, ...
- date: a type containing a date, such as date, time, datetime...
The given types are sql types, which might be followed by the precision (inside parenthesis),
such as tinyint(4) for instance.
Parameters
================
- types
Return values
================
Returns array.
Source Code
===========
See the source code for method [TypeHelper::getSimpleTypes](https://github.com/lingtalfi/Light_DatabaseInfo/blob/master/Helper/TypeHelper.php#L30-L63)
See Also
================
The [TypeHelper](https://github.com/lingtalfi/Light_DatabaseInfo/blob/master/doc/api/Ling/Light_DatabaseInfo/Helper/TypeHelper.md) class.
|
PHP
|
UTF-8
| 268 | 2.640625 | 3 |
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
<?php declare(strict_types=1);
namespace JonVaughan\WebapiClient\Api\Data;
interface ApiObjectInterface
{
/**
* @return array|null
*/
public function getData();
/**
* @param array $data
*/
public function setData(array $data);
}
|
Java
|
UTF-8
| 1,166 | 3.140625 | 3 |
[] |
no_license
|
public class LastViewedSeries {
private String seriesName;
private int lastViewedEpisode;
private int[] viewedEpisodes = new int[]{0,0,0};
private boolean isSeriesFinishedToBeViewed;
public LastViewedSeries(String seriesName) {
this.seriesName = seriesName;
}
public String getSeriesName() {
return seriesName;
}
public void setSeriesName(String seriesName) {
this.seriesName = seriesName;
}
public int getLastViewedEpisode() {
return lastViewedEpisode;
}
public void setLastViewedEpisode(int lastViewedEpisode) {
this.lastViewedEpisode = lastViewedEpisode;
}
public boolean isSeriesFinishedToBeViewed() {
return isSeriesFinishedToBeViewed;
}
public void setSeriesFinishedToBeViewed(boolean seriesFinishedToBeViewed) {
isSeriesFinishedToBeViewed = seriesFinishedToBeViewed;
}
public void checkEpisode(int episodeNumber) throws Exception {
if (episodeNumber - 1 < 0 || episodeNumber - 1 > 2) {
throw new Exception("Invalid episode number");
}
viewedEpisodes[episodeNumber - 1] = 1;
}
}
|
PHP
|
UTF-8
| 1,747 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace FormulaTG\Commands;
use Exception;
use FormulaTG\Utils\HelpInfo;
use FormulaTG\Validators\Command\CountParams;
class HelpCommand extends Command
{
protected function validate(): void
{
if (count($this->params) === 0) {
return;
}
$validateParamsQuantity = new CountParams('help', ['command']);
$validateParamsQuantity->validate($this->params);
}
public function execute(): string
{
try {
$this->validate();
} catch (Exception $e) {
return $e->getMessage();
}
if (count($this->params) === 0) {
return HelpInfo::GENERAL_HELP;
}
$helpInfo = '';
switch ($this->params[0]) {
case 'create':
$helpInfo = HelpInfo::CREATE_HELP;
break;
case 'list':
$helpInfo = HelpInfo::LIST_HELP;
break;
case 'positions':
$helpInfo = HelpInfo::POSITION_HELP;
break;
case 'start':
$helpInfo = HelpInfo::START_HELP;
break;
case 'overview':
$helpInfo = HelpInfo::OVERVIEW_HELP;
break;
case 'overtake':
$helpInfo = HelpInfo::OVERTAKE_HELP;
break;
case 'finish':
$helpInfo = HelpInfo::FINISH_HELP;
break;
case 'history':
$helpInfo = HelpInfo::HISTORY_HELP;
break;
default:
$helpInfo = 'Help command invalid';
break;
}
return $helpInfo;
}
}
|
Java
|
UTF-8
| 538 | 2.1875 | 2 |
[] |
no_license
|
package tw.com.useful.data.model;
import com.mongodb.BasicDBObject;
public class Field extends BasicDBObject {
/**
*
*/
private static final long serialVersionUID = 1L;
public Field(String code, String name){
put("code", code);
put("name", name);
}
public Field(){
}
public String getName() {
return getString("name");
}
public void setName(String name) {
put("name", name);
}
public String getCode() {
return getString("code");
}
public void setCode(String code) {
put("code", code);
}
}
|
Markdown
|
UTF-8
| 2,494 | 3.1875 | 3 |
[] |
no_license
|
# Simple Informational Only Scenario
## Table of Contents
* [Scenario Motivation](#motivation)
* [Scenario Technical Introduction](#introduction)
* [Detailed Message Exchange](#message-exchange)
* [Scenario Conclusion](#conclusion)
## Motivation
This scenario is to avoid inteference with the neighouring nodes' transmission when the transmission on this node starts.
The node alerts all its neighbours
* before it starts to send on a particular channel
* or/and before reroutes its path to the destination
This makes sure that the neighbouring nodes donot select the same channel as that of the node for its transmission. Or if they want to use that channel, the routes should be selected accordingly
## Introduction
This scenario involves a toy example of two Collaborative Intelligent Radio Networks, N1 and N2.
They each have 5 radio nodes. communication within the N1's radio nodes are positioned such that it comes in the radio range of N2's radio nodes.
If nodes in the routing path for this communication send a beacon signal to its neighbouring nodes, the N2 network can reuse the same channel avoiding the nodes that comes in the radio range of N1's nodes. This way effective reuse of bands takes place.
See the diagram.
**Beacon.png**
Without having the ability to collaborate, it would be very difficult for N2 to decide the route reusing the same bands.
N2 is therefore might not be able to effectively collabrate with N1.
This scenario will show how the simplest interaction available in the Collaboration Protocol can
solve this problem.
## Message Exchange
1. N1 sends N2 **Beacon message**: The array contains the node id of the nodes present in the routing path and/or the rerouted path.
2. N2 receives **Beacon message**: N2 alerts the nodes neighbouring the node ids present in the beacon message against using the same channel as the one used by N1 nodes.
3. N2 can use the same channel to send data over a path that does not involve the neighbouring nodes. This way, channel is reused and hence better collabration.
## Conclusion
This scenario showed how two radio networks were able to acheive reuse of channel without interference using beacon messages in the Collaboration Protocol.
This also helps in avoiding the inteference which occurs in the neighbouring nodes when a node is down and the network reroutes the messages.
These factors are also to be considered when the route and the band is selected for transmitting.
|
C
|
UTF-8
| 1,718 | 3.234375 | 3 |
[] |
no_license
|
/** \file logger.h
* Functions to handle the logging of the gopher file transfers.
* @file logger.c
*/
#ifndef LOGGER_H
#define LOGGER_H
#include "datatypes.h"
#include "globals.h"
#define LOGGER_SUCCESS 0
#define LOGGER_FAILURE -1
/**
* A struct representing an instance of a transfer log
*/
typedef struct {
/** Pipe to use for read/write */
pipe_t logPipe;
/** Pointer to the mutex guarding the log pipe */
mutex_t* pLogMutex;
/** [Linux only] Pointer to the condition variable to notify the logger for incoming data */
cond_t* pLogCond;
/** [Windows only] Event to notify the logger for incoming data */
event_t logEvent;
/** The pid of the log process */
proc_id_t pid;
} logger_t;
/**
* Starts a logging process and writes its information in a logger_t struct.
* @param pLogger The struct that will contain information about the logger.
* @return LOGGER_SUCCESS if the process was started correctly,
* LOGGER_FAILURE if pLogger is NULL or a system error occurs.
* @see logger_t
*/
int startTransferLog(logger_t* pLogger);
/**
* Stops a logging process.
* NOTE: Be sure to initialize the logger_t struct by calling startTransferLog().
* @param pLogger A pointer to the struct representing the logger process to stop.
* @return LOGGER_SUCCESS or LOGGER_FAILURE.
* @see logger_t
*/
int stopTransferLog(logger_t* pLogger);
/**
* Passes a message to a logging process.
* @param pLogger The struct representing the logging process.
* @param log The message to log.
* @return LOGGER_SUCCESS or LOGGER_FAILURE.
* @see logger_t
*/
int logTransfer(const logger_t* pLogger, cstring_t log);
#endif
|
TypeScript
|
UTF-8
| 1,667 | 2.859375 | 3 |
[] |
no_license
|
import DecryptService from "@app/services/decrypt-service";
import EncryptService, { IEncrypt } from "@app/services/encrypt-service";
import EncrypterParams from '@app/services/encrypter-params';
import { PASS_LENGTH, SALT_LENGTH } from "@app/config/env";
import { KeyHelper } from '@app/helpers/key.util';
export class Encrypter {
private static encrypter: Encrypter;
private _key: string;
private readonly _encrypt: typeof EncryptService;
private readonly _decrypt: typeof DecryptService;
private readonly _keyHelper: KeyHelper;
private constructor(){
this._decrypt = DecryptService;
this._encrypt = EncryptService;
this._keyHelper = new KeyHelper();
this._key = this._keyHelper.generateKey();
}
async encrypt<T>(params: EncrypterParams<T>): Promise<IEncrypt> {
const salt = this._keyHelper.extractSaltFromKey(this._key);
const password = this._keyHelper.extractPassFromKey(this._key);
return this._encrypt<T>({ ...params, password, salt});
}
async decrypt<T>(params: EncrypterParams<string>): Promise<T> {
const salt = this._keyHelper.extractSaltFromKey(this._key);
const password = this._keyHelper.extractPassFromKey(this._key);
return this._decrypt<T>({ ...params, password, salt});
}
setKey(key: string): void {
const minLength = PASS_LENGTH + SALT_LENGTH;
if(!key || key.length < minLength){
throw new Error(`Invalid key. It must has min ${minLength} chars`)
}
this._key = key;
}
get key(): string {
return this._key;
}
public static init():Encrypter {
const hasInitialized = Encrypter.encrypter;
if(!hasInitialized){
Encrypter.encrypter = new Encrypter();
}
return Encrypter.encrypter;
}
}
|
Java
|
UTF-8
| 3,039 | 2.1875 | 2 |
[] |
no_license
|
package my.spring.siw.tud.controllers;
import java.lang.reflect.InvocationTargetException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import my.spring.siw.tud.controllers.session.Session;
import my.spring.siw.tud.model.Credentials;
import my.spring.siw.tud.model.Project;
import my.spring.siw.tud.model.Utente;
import my.spring.siw.tud.modelServices.CredentialsService;
import my.spring.siw.tud.modelServices.UserService;
import my.spring.siw.tud.security.validation.CredentialsValidator;
@SuppressWarnings("unused")
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private Session sessionData;
@Autowired
private CredentialsService credService; // its in userController instead of CredentialController (used once)
@Autowired
private CredentialsValidator credentialsValidator;
@RequestMapping(value="/userDetails", method = RequestMethod.GET)
public String showUserDetails(Model model) {
Credentials current = sessionData.getLoggedCredentials();
model.addAttribute("currentCredentials",current);
model.addAttribute("currentUser",current.getUser());
return "details";
}
//BUG: Users can only update both username and password (due to CredentialValidator logic)
@RequestMapping(value="/editDetails", method = RequestMethod.POST)
public String editDetails(Model model, RedirectAttributes redirectAttributes,
@RequestParam("username") String username, @RequestParam("password") String password) {
Credentials currentCredentials = sessionData.getLoggedCredentials();
Credentials newCredentials = new Credentials();
newCredentials.setPassword(password);
newCredentials.setUsername(username);
DataBinder dataBinder = new DataBinder(newCredentials);
BindingResult credentialsBindingResult = dataBinder.getBindingResult();
this.credentialsValidator.validate(newCredentials, credentialsBindingResult);
if(!credentialsBindingResult.hasErrors()) { // has error if the user only update pwd, username already exists
currentCredentials.setPassword(password);
currentCredentials.setUsername(username);
this.credService.saveCredentials(currentCredentials);
redirectAttributes.addFlashAttribute("changed", "Details changed");
}
else
redirectAttributes.addFlashAttribute("notValid", "Enter valid credentials");
return "redirect:/userDetails";
}
}
|
Java
|
UTF-8
| 965 | 3.234375 | 3 |
[] |
no_license
|
static void removeDups(LinkedListNode root){
LinkedListNode curr = root, prev = null;
HashSet<Integer> set = new HashSet<>();
while(curr != null){
if(set.contains(curr.val))
prev.next = curr.next;
else{
set.add(curr.val);
prev = curr;
}
curr = curr.next;
}
return;
}
// Without extra space;
static void removeDups(LinkedListNode root){
LinkedListNode slow = root;
LinkedListNode fast, fastPrev;
while(slow != null){
fast = slow.next;
fastPrev = slow;
while(fast != null){
if(fast.val == slow.val)
fastPrev.next = fast.next;
else
fastPrev = fast;
fast = fast.next;
}
slow = slow.next;
}
return;
}
|
C
|
UTF-8
| 152 | 2.984375 | 3 |
[] |
no_license
|
#include<stdio.h>
main()
{
float a,b;
int c;
printf("Enter two floatting numbers : ");
scanf("%f %f",&a,&b);
c=a+b;
printf("%f\n %f\n %i",a,b,c);
}
|
Ruby
|
UTF-8
| 404 | 3.375 | 3 |
[] |
no_license
|
class Sieve
def initialize(max_number)
@potential_primes = (2..max_number).to_a
end
def primes(remaining_nums = @potential_primes, found_primes = [])
if remaining_nums.length.zero?
found_primes
else
found_primes.push(remaining_nums.shift)
remaining_nums.select!{|num| !(num % found_primes.last).zero?}
primes(remaining_nums, found_primes)
end
end
end
|
C++
|
UTF-8
| 690 | 2.546875 | 3 |
[] |
no_license
|
#include "guide_lan.h"
#include "guide_lanmgr.h"
namespace maxnet{
LanMgr::LanMgr(){
}
LanMgr::~LanMgr(){
#if 1
Lan * if_lan = NULL;
for(unsigned int i=0; i < node_list.size(); i++){
if_lan = (Lan *)node_list.at(i);
if(!if_lan->isGroup())
delete if_lan;
}
node_list.clear();
#endif
return;
}
void LanMgr::add(std::string ifname, std::string mac, std::string ipaddr, std::string netmask){
Lan * if_lan = new Lan();
if_lan->setIfName(ifname);
if_lan->setIP(ipaddr);
if_lan->setMask(netmask);
if_lan->setMAC(mac);
if(if_lan->isVaild())
{
addNode(if_lan);
}
else{
delete if_lan;
}
return;
}
}
|
Markdown
|
UTF-8
| 1,038 | 2.78125 | 3 |
[] |
no_license
|
# Machine-Learning-Artificial-Intelligence-MSIS549
This repository stores my assignments and labs from the graduate curriculum - Machine Learning and Artificial Intelligence For Business Applications (MSIS 549).
Assignment 1: Multi-class classification problem on Reuters Newswires Dataset. How to encode labels and solve a multi-class classification problem? How to avoid overfitting with epoch selection? How to adjust Dense Layer and Hidden Layer to improve model performance? Why is it important to have having sufficiently large intermediate layers
Assignment 2: Convolution Neural Network (CNN) problem on Rock/Paper/Scissors Gesture Image Dataset. How to build a fully connect model and a CNN model to achieve best prediction on test data?
Assignment 3: Recurrent Neural Network (RNN) problem on Reuters Newswires Dataset. How to build a fully connect model and a RNN model to achieve best prediction on test data? Why are RNN layers (LSTM, GRU) more powerful? Can pre-trained word embedding help improve the model prediction?
|
Java
|
UTF-8
| 644 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
package com.hit.basinfo.base_data_structure;
import com.hit.common.ListNode;
/**
* author:Charies Gavin
* date:2019/1/21,11:30
* https:github.com/guobinhit
* description: Simple Stack
*/
public class SimpleStack {
ListNode top;
void push(Object item) {
ListNode t = new ListNode(Integer.valueOf((String) item));
if (top != null) {
t.next = top;
top = t;
}
}
Object pop() {
if (top != null) {
Object item = top.val;
top = top.next;
return item;
}
return null;
}
Object peek() {
return top.val;
}
}
|
Markdown
|
UTF-8
| 532 | 3.28125 | 3 |
[] |
no_license
|
## Branches
- Creating and naming a branch -> `git checkout -b <name of branch>`
- Can also change with `git checkout <name of branch e.g. main>` back to another branch
- Once in the branch, can add files to that branch with `git add .` `git commit -m "message"` and `git push origin <branch name>`

- **Merging** - Once code has been pushed into your branch, you can do a pull request on github to merge into the main branch
- To make sure that your branch is up to date `git pull origin main` on your branch
|
Markdown
|
UTF-8
| 15,464 | 2.65625 | 3 |
[] |
no_license
|
# SunSystems automated backups script
This repository hosts the powershell backup & setup scripts. This repository provides:
- documentation & installation information,
- issue tracking and
- full change/version control.
Kindly contact trghelp@trginternational.com for any additional clarifications required.
## Table Of Contents
<!-- MarkdownTOC depth=3 autolink=true bracket=round -->
- [Getting Started:](#getting-started)
- [Install 7z](#install-7z)
- [Add PowerShell-ISE to server (Optional)](#add-powershell-ise-to-server-optional)
- [Ensure `ExecutionPolicy` allows unsigned local scripts](#ensure-executionpolicy-allows-unsigned-local-scripts)
- [Create a Windows account as a backup operator for the Auto backup script.](#create-a-windows-account-as-a-backup-operator-for-the-auto-backup-script)
- [Create a SunSystems account for backup operator](#create-a-sunsystems-account-for-backup-operator)
- [Record a SunSystems macro called `FB`](#record-a-sunsystems-macro-called-fb)
- [Edit the SunSystems Macro (add username & password)](#edit-the-sunsystems-macro-add-username--password)
- [Get the latest backup-script files](#get-the-latest-backup-script-files)
- [Edit the `config.xml`](#edit-the-configxml)
- [Test the `SunBackup.ps1` script](#test-the-sunbackupps1-script)
- [Schedule the `SunBackup.ps1` script](#schedule-the-sunbackupps1-script)
- [Script Feature Overview:](#script-feature-overview)
- [Contributing](#contributing)
- [ChangeLog](#changelog)
- [PowerShell basics](#powershell-basics)
<!-- /MarkdownTOC -->
## Getting Started:
### Install 7z
Ensure 7zip is installed on the server, without 7z the script will fail.

```powershell
$wc = New-Object System.Net.WebClient
#download & run 7zip installer
Write-Host -ForegroundColor Green "Downloading 7zip installer script... "
$wc.DownloadFile("http://www.7-zip.org/a/7z920-x64.msi","$env:TEMP\7z.msi")
Write-Host -ForegroundColor Green "Running 7zip installer script in background... "
& "$env:TEMP\7z.msi" "/passive"
```
http://www.7-zip.org/download.html
### Add PowerShell-ISE to server (Optional)
this is not mandatory, but is very useful when you are required to review or edit the script.
Through Windows Server Feature Manager

or using PowerShell to enable ISE directly
```powershell
Import-Module ServerManager
Add-WindowsFeature Powershell-ISE
ise
```

### Ensure `ExecutionPolicy` allows unsigned local scripts

**Note**: `RemoteSigned` will allow local scripts to be unsigned, but require remote scripts to be signed. Before changing the execution policy - ensure it was not set to `Unrestricted` by someone else. Below screenshot shows the `ExecutionPolicy` was set to `Unrestricted` in which case we should **not** modify the setting.

To set the `ExectionPolicy` run the `Set-ExecutionPolicy` cmdlet with `RemoteSigned` as the new value:
```powershell
Set-ExecutionPolicy RemoteSigned
```
### Create a Windows account as a backup operator for the Auto backup script.
Only provide the minimum permissions required for the script:

1. This account should be able to run SunSystems (should be member of SUClients local group)
2. This account should be able to run scripts on schedule (should be a member of Backup Operators local group)
3. This account password should **not expire** and **be strong**
### Create a SunSystems account for backup operator
Enable windows authentication and give ISM permissions to the backup operator account:
1. General, added to ISM group

2. SunSystems 4 settings

3. Windows Authentication

### Record a SunSystems macro called `FB`
Ensure the macro covers all the databases requiring daily backups. This macro will be stored in the `STANDARD.MDF` file in SunSystems root folder.
**Note**: `SunBackup.ps1` expects the macro name to be `FB` and it should be located in the `STANDARD.MDF` file.

### Edit the SunSystems Macro (add username & password)
Once the macro has been recorded, it is required to **edit** the macro, adding the Backup user SUN Operator ID and Password, below the macro name but before any SunSystems commands. This is required to run scripts from command line even with Windows Authentication enabled on the account.
**Note**: Due to the Hilton Policy, after 90 days the password will be expired and will need to be updated. The script will notify relevant parties when the backups are no longer working.

### Get the latest backup-script files
You can get the latest version of the script via https://github.com/trgint/trg.hhc.autobackup
**Note** it is recommended to use `D:\BACKUP` as the path, the `TaskConfig.xml` expects powershell script to exist under this path!
or with this one liner **powershell 3+** (Windows Server 2012):
```powershell
@("config.xml","SunBackup.ps1","ScheduleBackup.ps1") | % { iwr ("https://github.com/trgint/trg.hhc.autobackup/raw/master/$_") -OutFile $_ }
```
or with this one liner for **powershell 2** (Windows Server 2008):
```powershell
@("SunBackup.ps1","config.xml","ScheduleBackup.ps1") | % { (New-Object System.Net.WebClient).DownloadFile("https://github.com/trgint/trg.hhc.autobackup/raw/master/{0}" -f $_, $_) }
```
### Edit the `config.xml`

Ensure the following 2 points:
1. The config should point to the correct FileSystems paths, **communicate these paths to ISM** to ensure tape backups or network mirrored folders exist.
2. Update the e-mail contacts to be notified in case SunSystems backup files are out of date.
**Note** `<` and `>` are invalid characters in XML and need to be written as `<` and `>` to ensure email contacts show up with a caption `TRGHelp <trghelp@trginternational.com>` becomes `TRGHelp <TRGHelp@trginternational.com>`
**Note** some ISM create an `<INNCODE>_IT@Hilton.com` or `<INNCODE>_ISM@Hilton.com` alias for their property to ensure future emails will always reach the correct person (in case ISM moved to another property or left the company), **please verify with ISM if such alias exists**
### Test the `SunBackup.ps1` script
Test the script by running it with PowerShell. For example using the standard windows command shell:

### Schedule the `SunBackup.ps1` script
A Scheduled task should be created to run the `SunBackup.ps1` script daily outside of working hours.
Either schedule the task manually, following the screenshots below, or download & run the `ScheduleBackup.ps1` script to have the task created automatically with common settings.
```powershell
.\ScheduleBackup.ps1
```
**Note** This script expects backup folder to be `D:\BACKUP`
This will download a Task configuration template and prompt for the Windows account `.\svcSunBaK` created [earlier](#create-a-sunsystems-account-for-backup-operator).

If creating the task **manually**, ensure the following 4 points:
1. Run the task using the Windows account `.\svcSunBaK` created [earlier](#create-a-sunsystems-account-for-backup-operator). Configure the task to **run wether user is logged on or not**

2. Schedule the task to run daily at a time sun operators would not be logged in making sure operation is not affected by the strain of the File Backup function.

3. Create the action to run the PowerShell script under the Actions tab:

4. \[Optional\] create more actions, although scheduling this task to send an email daily will result in these emails being ignored and nobody will notice the task is not running anymore and that would defeat the purpose of the email...

Finally, test the task by triggering the task manually:

Review the History to ensure the Task ran successfully

## Script Feature Overview:
This PowerShell script has the following features:
- Only requires `PowerShell`, `7zip` and a Sun `FB` macro in the **Standard** Macro Definition file. This script does not rely on any other programs or batch files and stands by itself.
`PowerShell` comes by default on recent versions of Microsoft Operating Systems (Windows 7+ & Windows Server 2008+)
- Ability to **detect the age of SunSystems backup files**, ensuring the files being archived are up to date.
- Ability to **send a high priority email with detailed instructions** in case the SunSystems backup files are outdated. (**and only IF the files are outdated**, saving the e-mail inbox of everybody involved)
- Ability to effectively name the archives being created with a full ISO date not relying on registry keys to parse file system dates (as the old MSDOS batch had to do)
- Ability to prevent a full disk by removing any backups older than 4 weeks
## Contributing
- master is stable
- create feature branch if you work on this repository
- fork & submit pull request after rebase to master
## ChangeLog
Here is full changelog.
Date | By | Changes
------------- | ---------------- | ---------------------------------------------------------------
May 2015 | Vincent De Smet | added task scheduler, migrated to github https://github.com/trgint/trg.hhc.autobackup
April 2015 | Vincent De Smet | added script to source control https://bitbucket.org/trginternational/trg.hhc.autobackup/
| | converted documentation from word to markdown
| | added ability to kill sun32.exe based on time-out - ensuring email is sent
| | added ability to lookup airport information based on INNCODE
November 2014 | Vincent De Smet | Fixed bug causing script not to remove older backups correctly
August 2014 | Vincent De Smet | This is the 2nd version of the PowerShell script adding the ability to identify backup file age, emails and removing the reliance on additional files
August 2013 | Vincent De Smet | This is the 1st version of the PowerShell script using the PowerShell advanced DateTime formatting and filtering capabilities to easily name archive files and delete archives older than a 7 days. Created by Vincent De Smet
## PowerShell basics
This PowerShell script relies on the following PowerShell basics:
- The array operator [`@( .. )`](http://technet.microsoft.com/en-us/library/hh847882.aspx) to create arrays
- The hashtable operator [` @{ <name> = <value>; [<name> = <value> ] ...}`](https://technet.microsoft.com/en-us/library/hh847780.aspx)
- [`Join-Path`](http://technet.microsoft.com/en-us/library/hh849799.aspx) cmdlet is used to compose system independent paths
- The [`Get-Date`](http://technet.microsoft.com/en-us/library/hh849887.aspx) cmdlet to get a DateTime object
- The [`DateTime`](http://msdn.microsoft.com/en-us/library/system.datetime_members.aspx) object member functions such as .AddDays()
- The Here-String [`@” .. “@`](http://technet.microsoft.com/en-us/library/ee692792.aspx) to conveniently compose the e-mail body with placeholders
- The [`format (-f)`](http://social.technet.microsoft.com/wiki/contents/articles/7855.using-the-f-format-operator-in-powershell.aspx) operator to set the “from” field of the email to the server name and fill out the placeholders in the e-mail body.
- The [`New-Item`](http://technet.microsoft.com/en-us/library/ee176914.aspx) cmdlet to ensure the target backup path exists (with the -Force argument switch)
- The [`Measure-Object`](http://technet.microsoft.com/en-us/library/hh849965.aspx) cmdlet and [`Measure-Latest`](http://dmitrysotnikov.wordpress.com/2008/07/16/measure-latest-finding-the-latest-date-time/) function to get the latest LastWriteTime of the backup files
- The [`Start-Process`](http://technet.microsoft.com/en-us/library/hh849848.aspx) cmdlet to start a process with a certain working directory and argumentlist
- The [`Get-ChildItem`](http://technet.microsoft.com/en-us/library/ee176841.aspx) cmdlet to recursively fetch files and subdirectories filtering on extension
- The [`Call (&)`](http://technet.microsoft.com/en-us/library/hh847732.aspx) operator to call 7zip with all required arguments
- The [`Send-Mailmessage`](http://technet.microsoft.com/en-us/library/hh849925.aspx) cmdlet to intuitively send an email from the script
Additional Tips to better understand the inner workings of this script:
- Read about [Scripting in PowerShell](http://technet.microsoft.com/en-us/library/bb978526.aspx)
- Use the [`Get-Member`](http://technet.microsoft.com/en-us/library/ee176854.aspx) & [`Get-Help`](http://technet.microsoft.com/en-us/library/ee176848.aspx) cmdlets to get information on the member functions available in PowerShell objects
- Read about the [Automatic variables](http://technet.microsoft.com/en-us/library/dd347675.aspx) maintained by the PowerShell runtime
- Read about the [fundamental concept of drives](http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/07/use-powershell-to-work-easily-with-drives-and-paths.aspx) in Powershell
- Read about the [environment provider](http://technet.microsoft.com/en-us/library/hh847860.aspx)
- This PowerShell script does not use aliases for the cmdlets to ensure maximum readability except for:
- `?` as an alias for the [`Where-Object`](http://technet.microsoft.com/en-us/library/hh849715.aspx) cmdlet
- `%` as an alias for the `ForEach-object` cmdlet
- [This technet blog](http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/04/use-powershell-to-translate-airport-code-to-city-name.aspx) walks you through using a webservice.
|
C#
|
UTF-8
| 2,387 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace FileExplorer.WPF.BaseControls
{
/// <summary>
/// Display ContentOn or ContentOff depends on whether IsSwitchOn is true.
/// </summary>
public class Switch : HeaderedContentControl
{
#region Constructor
static Switch()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Switch),
new FrameworkPropertyMetadata(typeof(Switch)));
}
#endregion
#region Methods
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
//this.AddHandler(HeaderedContentControl.MouseDownEvent, (RoutedEventHandler)((o, e) =>
// {
// this.SetValue(IsSwitchOnProperty, !IsSwitchOn);
// }));
}
public static void OnIsSwitchOnChanged(object sender, DependencyPropertyChangedEventArgs args)
{
}
#endregion
#region Data
#endregion
#region Public Properties
public bool IsSwitchOn
{
get { return (bool)GetValue(IsSwitchOnProperty); }
set { SetValue(IsSwitchOnProperty, value); }
}
public static readonly DependencyProperty IsSwitchOnProperty =
DependencyProperty.Register("IsSwitchOn", typeof(bool),
typeof(Switch), new UIPropertyMetadata(true, new PropertyChangedCallback(OnIsSwitchOnChanged)));
public object ContentOn
{
get { return (object)GetValue(ContentOnProperty); }
set { SetValue(ContentOnProperty, value); }
}
public static readonly DependencyProperty ContentOnProperty =
DependencyProperty.Register("ContentOn", typeof(object),
typeof(Switch), new UIPropertyMetadata(null));
public object ContentOff
{
get { return (object)GetValue(ContentOffProperty); }
set { SetValue(ContentOffProperty, value); }
}
public static readonly DependencyProperty ContentOffProperty =
DependencyProperty.Register("ContentOff", typeof(object),
typeof(Switch), new UIPropertyMetadata(null));
#endregion
}
}
|
C#
|
UTF-8
| 1,068 | 2.890625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// this is an abstract class for all distributions that need to be rendered on screen
/// </summary>
public abstract class Distribution : MonoBehaviour
{
/// <summary>
/// returns the probability P(x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public abstract float Value(float x);
/// <summary>
/// the highest probable event
/// </summary>
public abstract float Maximum
{
get;
}
/// <summary>
/// where the values start to become existent or interesting
/// </summary>
public abstract float LowerBound
{
get;
}
/// <summary>
/// where the values stop being existent or interesting
/// </summary>
public abstract float UpperBound
{
get;
}
/// <summary>
/// this is called when there is a change in the distribution
/// </summary>
public abstract event UnityAction ValueChanged;
}
|
Java
|
UTF-8
| 7,485 | 3.109375 | 3 |
[] |
no_license
|
/**
* AsteroidGame.java
* @date Mar 31, 2012
* @author ricky barrette
*
* Copyright 2012 Richard Barrette
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.RickBarrette.asteroids;
import java.util.ArrayList;
import java.util.Random;
/**
* This class maintain's the game logic. It is the main driver
* @author ricky barrette
*/
public class AsteroidGameThread extends Thread {
private static final int DELAY_IN_MSEC = 50;
private final ArrayList<Object> mWorld;
private final GameApplet mGameApplet;
public boolean isStarted = false;
private long mLastTime;
/**
* Creates an new Asteroids game
* @author ricky barrette
*/
public AsteroidGameThread(GameApplet gameFrame) {
mGameApplet = gameFrame;
mWorld = new ArrayList<Object>();
//TODO simulate game play unitll game ist started
this.start();
}
/**
* Adds an object to the world
* @param add
* @author ricky barrette
*/
public synchronized void addElement(final Object o) {
mWorld.add(o);
}
/**
* When this methods is called, the player's ship is down.
* @author ricky barrette
*/
private void downShip() {
System.out.println("Ship collision dected");
/*
* move the players ship's
*/
Object o = null;
Ship s = null;
for (int i = 0; i < mWorld.size(); i++){
o = mWorld.get(i);
if(o instanceof Ship)
s = (Ship) o;
}
if(s != null){
s.allStop();
s.hyperJump();
}
mGameApplet.getStatusBar().decrementShipCount();
if(mGameApplet.getStatusBar().getShipCount() > 0){
pauseGame();
mGameApplet.setDisplayText("You died, You can hyper jump to a safe place now... Press start when ready.");
} else {
mGameApplet.setDisplayText("Game Over");
if(s != null)
mWorld.remove(s);
}
mGameApplet.repaint();
}
/**
* @return the game's frame
* @author ricky barrette
*/
public GameApplet getGameFrame() {
return this.mGameApplet;
}
/**
* @return the world
* @author ricky barrette
*/
public ArrayList<Object> getWorld() {
return mWorld;
}
/**
* populates the world for a new game
* @author ricky barrette
*/
public void initLevel() {
Random gen = new Random();
/*
* added a asteroid per level
*/
for(int i = 0; i < mGameApplet.getStatusBar().getLevel(); i ++)
addElement(new Asteroid(gen.nextInt(mGameApplet.getDisplayWidth()), gen.nextInt(mGameApplet.getDispalyHeight()), 1, 10, 50, 3, 3, this));
notification("Level "+ mGameApplet.getStatusBar().getLevel());
}
/**
* @return true if the world is empty
* @author ricky barrette
*/
public boolean isEmpty() {
return mWorld.isEmpty();
}
/**
* Clears the world, and Creates a new game
* @author ricky barrette
*/
public void newGame() {
Random gen = new Random();
mWorld.clear();
mGameApplet.setDisplayText(null);
mGameApplet.getStatusBar().setShipCount(3);
mGameApplet.getStatusBar().setScore(0);
mGameApplet.getStatusBar().setAsteroidCount(1);
mGameApplet.getStatusBar().setTime(0);
mGameApplet.getStatusBar().setShotCount(0);
mGameApplet.getStatusBar().setLevel(1);
mWorld.add(new Ship(gen.nextInt(mGameApplet.getDisplayWidth()), gen.nextInt(mGameApplet.getDispalyHeight()), 0, .35, .98, .2, 1, this));
initLevel();
startGame();
notification("Level "+ mGameApplet.getStatusBar().getLevel());
mGameApplet.repaintDispaly();
}
/**
* Displays a nofication to the user for 2 seconds
* @param string
* @author ricky barrette
*/
private void notification(final String string) {
mGameApplet.setDisplayText(string);
new Thread(new Runnable(){
@Override
public void run(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(isStarted)
mGameApplet.setDisplayText(null);
}
}).start();
}
/**
* Pauses the game
* @author ricky barrette
*/
public synchronized void pauseGame(){
isStarted = false;
mGameApplet.setDisplayText("Paused");
setMovingSpaceObjectsEnabled(false);
}
/**
* Removes an object from this world.
* @param o object to be removed
* @author ricky barrette
*/
public synchronized void removeElement(final Object o) {
if(o instanceof Asteroid) {
mGameApplet.getStatusBar().incrementScore(2);
}
mWorld.remove(o);
}
/**
* Main game driver method.
*
* @author ricky barrette
*/
@Override
public void run() {
boolean hasOneUped = false;
int asteroidCount = 0, shotCount = 0;
Object o;
Collider c;
Object[] world;
while (true){
if(isStarted) {
/*
* brute force focus,
* this seems to be the only fix I can find, for now
*/
mGameApplet.requestFocus();
/*
* increment time
*/
mGameApplet.getStatusBar().incrementTime(System.currentTimeMillis() - mLastTime);
mLastTime = System.currentTimeMillis();
/*
* update the display and stats
*/
mGameApplet.repaintDispaly();
mGameApplet.getStatusBar().updateStatus();
/*
* check for collsions
*/
world = mWorld.toArray();
for (int i = 0; i < world.length; i++){
o = world[i];
if(o instanceof Collider){
asteroidCount++;
c = (Collider) o;
for(int index = 0; index < world.length; index++)
if(c.checkForCollision(world[index]))
//check to see if the ship blew up
if(world[index] instanceof Ship)
downShip();
}
//coutn the shots
if(o instanceof Shot)
shotCount++;
}
/*
* if there are no more asteroids, then increment the level
*/
if(asteroidCount == 0){
mGameApplet.getStatusBar().incrementLevel();
initLevel();
}
/*
* 1up every 200 points
*/
if(mGameApplet.getStatusBar().getScore() > 0 && mGameApplet.getStatusBar().getScore() % 200 == 0){
if(!hasOneUped){
mGameApplet.getStatusBar().incrementShipCount();
hasOneUped = true;
notification("1up!");
}
} else
hasOneUped = false;
/*
* update the status bar with the new counts
*/
mGameApplet.getStatusBar().setShotCount(shotCount);
mGameApplet.getStatusBar().setAsteroidCount(asteroidCount);
/*
* reset counters
*/
asteroidCount = 0;
shotCount = 0;
}
/*
* sleep till next time
*/
try {
sleep(DELAY_IN_MSEC);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Sets the enabled state of Moving Space Objects
* @param b
* @author ricky barrette
*/
public void setMovingSpaceObjectsEnabled(final boolean b) {
for(Object item : mWorld)
if(item instanceof MovingSpaceObject)
((MovingSpaceObject) item).setActive(b);
}
/**
* @return the number of objects in the world
* @author ricky barrette
*/
public int size() {
return mWorld.size();
}
/**
* Starts the game
* @author ricky barrette
*/
public synchronized void startGame(){
mLastTime = System.currentTimeMillis();
mGameApplet.setDisplayText(null);
setMovingSpaceObjectsEnabled(true);
isStarted = true;
}
}
|
C++
|
UTF-8
| 5,495 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/hud_display/data_source.h"
#include <algorithm>
#include "ash/hud_display/memory_status.h"
#include "base/functional/bind.h"
#include "base/threading/thread_restrictions.h"
namespace ash {
namespace hud_display {
namespace {
// Returns number of bytes rounded up to next Gigabyte.
int64_t EstimatePhysicalRAMSize(int64_t total_ram) {
// Round up to nearest Gigabyte.
constexpr int64_t one_gig = 1024 * 1024 * 1024;
if (total_ram % one_gig) {
return ((total_ram / one_gig) + 1) * one_gig;
}
return total_ram;
}
// Calculates counter difference with respect to overflow.
CpuStats Delta(const CpuStats& newer, const CpuStats& older) {
static_assert(sizeof(CpuStats) == sizeof(uint64_t) * 10,
"This method should be updated when CpuStats is changed.");
// Calculates (left - right) assuming |left| and |right| are increasing
// unsigned counters with respect to possible counter overflow.
auto minus = [](const uint64_t& left, const uint64_t right) {
return left > right
? (left - right)
: (left + (std::numeric_limits<uint64_t>::max() - right));
};
CpuStats result;
result.user = minus(newer.user, older.user);
result.nice = minus(newer.nice, older.nice);
result.system = minus(newer.system, older.system);
result.idle = minus(newer.idle, older.idle);
result.iowait = minus(newer.iowait, older.iowait);
result.irq = minus(newer.irq, older.irq);
result.softirq = minus(newer.softirq, older.softirq);
result.steal = minus(newer.steal, older.steal);
result.guest = minus(newer.guest, older.guest);
result.guest_nice = minus(newer.guest_nice, older.guest_nice);
return result;
}
// Returns sum of all entries. This is useful for deltas to calculate
// percentage.
uint64_t Sum(const CpuStats& stats) {
static_assert(sizeof(CpuStats) == sizeof(uint64_t) * 10,
"This method should be updated when CpuStats is changed.");
return stats.user + stats.nice + stats.system + stats.idle + stats.iowait +
stats.irq + stats.softirq + stats.steal + stats.guest +
stats.guest_nice;
}
} // anonymous namespace
// --------------------------------
////////////////////////////////////////////////////////////////////////////////
// DataSource, public:
DataSource::Snapshot::Snapshot() = default;
DataSource::Snapshot::Snapshot(const Snapshot&) = default;
DataSource::Snapshot& DataSource::Snapshot::operator=(const Snapshot&) =
default;
DataSource::DataSource() {
cpu_stats_base_ = {0};
cpu_stats_latest_ = {0};
}
DataSource::~DataSource() = default;
DataSource::Snapshot DataSource::GetSnapshotAndReset() {
// Refresh data synchronously.
Refresh();
Snapshot snapshot = GetSnapshot();
if (cpu_stats_base_.user > 0) {
// Calculate CPU graph values for the last interval.
CpuStats cpu_stats_delta = Delta(cpu_stats_latest_, cpu_stats_base_);
const double cpu_ticks_total = Sum(cpu_stats_delta);
// Makes sure that the given value is between 0 and 1 and converts to
// float.
auto to_0_1 = [](const double& value) -> float {
return std::clamp(static_cast<float>(value), 0.0f, 1.0f);
};
snapshot.cpu_idle_part = cpu_stats_delta.idle / cpu_ticks_total;
snapshot.cpu_user_part =
(cpu_stats_delta.user + cpu_stats_delta.nice) / cpu_ticks_total;
snapshot.cpu_system_part = cpu_stats_delta.system / cpu_ticks_total;
// The remaining part is "other".
snapshot.cpu_other_part =
to_0_1(1 - snapshot.cpu_idle_part - snapshot.cpu_user_part -
snapshot.cpu_system_part);
}
ResetCounters();
return snapshot;
}
DataSource::Snapshot DataSource::GetSnapshot() const {
return snapshot_;
}
void DataSource::ResetCounters() {
snapshot_ = Snapshot();
cpu_stats_base_ = cpu_stats_latest_;
cpu_stats_latest_ = {0};
}
////////////////////////////////////////////////////////////////////////////////
// DataSource, private:
void DataSource::Refresh() {
const MemoryStatus memory_status;
snapshot_.physical_ram =
std::max(snapshot_.physical_ram,
EstimatePhysicalRAMSize(memory_status.total_ram_size()));
snapshot_.total_ram =
std::max(snapshot_.total_ram, memory_status.total_ram_size());
snapshot_.free_ram = std::min(snapshot_.free_ram, memory_status.total_free());
snapshot_.arc_rss = std::max(snapshot_.arc_rss, memory_status.arc_rss());
snapshot_.arc_rss_shared =
std::max(snapshot_.arc_rss_shared, memory_status.arc_rss_shared());
snapshot_.browser_rss =
std::max(snapshot_.browser_rss, memory_status.browser_rss());
snapshot_.browser_rss_shared = std::max(snapshot_.browser_rss_shared,
memory_status.browser_rss_shared());
snapshot_.renderers_rss =
std::max(snapshot_.renderers_rss, memory_status.renderers_rss());
snapshot_.renderers_rss_shared = std::max(
snapshot_.renderers_rss_shared, memory_status.renderers_rss_shared());
snapshot_.gpu_rss_shared =
std::max(snapshot_.gpu_rss_shared, memory_status.gpu_rss_shared());
snapshot_.gpu_rss = std::max(snapshot_.gpu_rss, memory_status.gpu_rss());
snapshot_.gpu_kernel =
std::max(snapshot_.gpu_kernel, memory_status.gpu_kernel());
cpu_stats_latest_ = GetProcStatCPU();
}
} // namespace hud_display
} // namespace ash
|
C#
|
UTF-8
| 1,001 | 3.53125 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace August2017
{
class Program
{
static void Main(string[] args)
{
Queue<long> numbers = new Queue<long>();
List<long> list = new List<long>();
long n = long.Parse(Console.ReadLine());
numbers.Enqueue(n);
list.Add(n);
while (list.Count <= 50)
{
long current = numbers.Dequeue();
long s1 = current + 1;
numbers.Enqueue(s1);
list.Add(s1);
long s2 = (2 * current) + 1;
numbers.Enqueue(s2);
list.Add(s2);
long s3 = current + 2;
numbers.Enqueue(s3);
list.Add(s3);
}
for (int i = 0; i < 50; i++)
{
Console.Write(list[i] + " ");
}
}
}
}
|
Java
|
UTF-8
| 13,697 | 2.0625 | 2 |
[] |
no_license
|
package com.example.btapp;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import static com.example.btapp.Drawer_Activity.LONG_TOAST;
import static com.example.btapp.Drawer_Activity.SHORT_TOAST;
import static com.example.btapp.Drawer_Activity.chatHandler;
//***** TEMPLATE *****/
/*******************************************************************************************************
NAME: FunctionName
INPUTS: variable1: Type1 (Keyword)
AUX VARIABLES: aux1: Type1
OUTPUTS: output1: Type1, output2: Type2
DESCRIPTION: short Function description
********************************************************************************************************/
/*******************************************************************************************************
// Class: //
NAME: My_dialog
INHERITS FROM: AppCompatDialogFragment
IMPLEMENTS: AdapterView.OnItemClickListener
MEMBER VARIABLES: my_scanned_devices: ArrayList<BluetoothDevice> (none)
bt_paired_devices: Set<BluetoothDevice> (none)
btAdapter: BluetoothAdapter (none)
bluetoothDevice: BluetoothDevice (none)
dev_list: ArrayList<String> (none)
arrayAdapter: ArrayAdapter<String> (none)
view: View (none)
pairedList: ListView (none)
newDevList: ListView (none)
receiver: BroadcastReceiver (none)
MY_UUID: UUID (static final)
PURPOSE: defines the fragment used for connection setup
*********************************************************************************************************/
public class My_dialog extends AppCompatDialogFragment implements AdapterView.OnItemClickListener {
private ArrayList<BluetoothDevice> my_scanned_devices = new ArrayList<>();
private Set<BluetoothDevice> bt_paired_devices;
private BluetoothAdapter btAdapter;
private BluetoothDevice bluetoothDevice;
ArrayList<String> dev_list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
View view;
ListView pairedList;
ListView newDevList;
BroadcastReceiver receiver;
private static final UUID MY_UUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
/*******************************************************************************************************
NAME: onCreateDialog
INPUTS: savedInstanceState: Bundle
AUX VARIABLES: builder: AlertDialog.Builder
inflater: LayoutInflater
intentFilter: IntentFilter
btn_dev: Button
btn_scan: Button
OUTPUTS: builder.create(): Dialog
DESCRIPTION: generic onCreate method for a fragment
********************************************************************************************************/
@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = Objects.requireNonNull(getActivity()).getLayoutInflater();
view = inflater.inflate(R.layout.activity_connect_room, null);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedList = view.findViewById(R.id.paired_devices_list_view);
newDevList = view.findViewById(R.id.new_devices_list_view);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
dev_list.add(dev.getName() + " " + dev.getAddress());
my_scanned_devices.add(dev);
arrayAdapter.notifyDataSetChanged();
}
}
};
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(receiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, dev_list);
newDevList.setAdapter(arrayAdapter);
Button btn_dev = view.findViewById(R.id.btn_scan_dev);
btn_dev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showToast("Scanning Request Sent",3, LONG_TOAST);
dev_list.clear();
arrayAdapter.notifyDataSetChanged();
btAdapter.startDiscovery();
}
});
Button btn_scan = view.findViewById(R.id.btn_list_dev);
btn_scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bt_paired_devices = btAdapter.getBondedDevices();
String[] devices_names = new String[bt_paired_devices.size()];
int i = 0;
if (bt_paired_devices.size() > 0) {
for (BluetoothDevice bluetoothDevice : bt_paired_devices) {
devices_names[i] = bluetoothDevice.getName() + " " + bluetoothDevice.getAddress();
i++;
}
ArrayAdapter<String> adapterArr = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, devices_names);
pairedList.setAdapter(adapterArr);
}
}
});
/*******************************************************************************************************
* OnClickListener for ian item in the paired devices list
*******************************************************************************************************/
pairedList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
String name = info.replaceAll(address," ");
ArrayList<BluetoothDevice> bt_dev_arr = new ArrayList<>();
for(BluetoothDevice dev : bt_paired_devices){
bt_dev_arr.add(dev);
}
bluetoothDevice = bt_dev_arr.get(position);
connectToDevice(bluetoothDevice.getAddress());
showToast("Connect request sent to " + name,3, SHORT_TOAST);
}
});
/*******************************************************************************************************
* OnClickListener for ian item in the new devices list
*******************************************************************************************************/
newDevList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
btAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
String name = info.replaceAll(address," ");
if(my_scanned_devices.get(position).getBondState() == BluetoothDevice.BOND_BONDED){
showToast("Already Paired Device",4, SHORT_TOAST);
return;
}
boolean result = my_scanned_devices.get(position).createBond();
if(result)
showToast("Pairing Request Sent",3, LONG_TOAST);
else
showToast("Pairing Request Error",4, SHORT_TOAST);
}
});
builder.setView(view)
/*******************************************************************************************************
* Fragment OK button
*******************************************************************************************************/
.setNegativeButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
/*******************************************************************************************************
NAME: onDestroyView
INPUTS: -
AUX VARIABLES: -
OUTPUTS: -
DESCRIPTION: generic fragment onDestroy method that is called when the fragment is destroyed
********************************************************************************************************/
@Override
public void onDestroyView() {
super.onDestroyView();
Objects.requireNonNull(getActivity()).unregisterReceiver(receiver);
Log.d("Tag", "Fragment.onDestroyView() has been called.");
}
/*******************************************************************************************************
NAME: showToast
INPUTS: text: String, type: int, duration: int
AUX VARIABLES: inflater: LayoutInflater, layout: View, toastText: TextView
OUTPUTS: -
DESCRIPTION: generates and shows a custom toast
********************************************************************************************************/
public void showToast(String text, int type, int duration) {
LayoutInflater inflater = getLayoutInflater();
View layout;
switch (type){
case 1:
layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
case 2:
layout = inflater.inflate(R.layout.bt_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
case 3:
layout = inflater.inflate(R.layout.ok_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
case 4:
layout = inflater.inflate(R.layout.error_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
case 5:
layout = inflater.inflate(R.layout.warning_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
case 6:
layout = inflater.inflate(R.layout.stream_toast, (ViewGroup) view.findViewById(R.id.toast_root));
break;
default:
return;
}
TextView toastText = layout.findViewById(R.id.toast_text);
toastText.setText(text);
Toast toast = new Toast(Objects.requireNonNull(getActivity()).getApplicationContext());
if (type == 2){
toast.setGravity(Gravity.BOTTOM, 0, 50);
}
else if (type == 3 || type == 4 || type == 5){
toast.setGravity(Gravity.BOTTOM, 0, 50);
}
else
toast.setGravity(Gravity.CENTER, 0, 50);
if(duration == LONG_TOAST)
toast.setDuration(Toast.LENGTH_LONG);
if(duration == SHORT_TOAST)
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
/*******************************************************************************************************
NAME: connectToDevice
INPUTS: deviceAddress: String
AUX VARIABLES: device: BluetoothDevice
OUTPUTS: -
DESCRIPTION: connection method between devices
********************************************************************************************************/
private void connectToDevice(String deviceAddress) {
btAdapter.cancelDiscovery();
BluetoothDevice device = btAdapter.getRemoteDevice(deviceAddress);
chatHandler.initializeClient(device, MY_UUID);
}
}
|
Markdown
|
UTF-8
| 1,250 | 2.640625 | 3 |
[
"Apache-2.0",
"CC-BY-3.0"
] |
permissive
|
---
name: Propose new content
about: Use this ticket when you are submitting new content to the site.
title: 'content: <Add your title>'
labels: content proposal
assignees: ''
---
**A one to two sentence description of your post**
What are you planning to teach folks in this post?
**Target publish date:** `<yyyy-mm-dd>`
- [ ] Check this box if this is a hard deadline.
**Process**
Take a moment to look over the [web.dev handbook](https://web.dev/handbook) and
familiarize yourself with the process.
When you're ready, make a copy of [this template](https://docs.google.com/document/d/1ydauCufwwavStaKxhIDHuNivVxgQBOdDno4uLjGIjmE/edit)
and fill in the proposal and outline sections. When you're finished, drop a link
to the doc in the 1st step below and check the box. A member of the web.dev team
will assign this ticket to themselves and work as your reviewer to help you
complete the remaining steps.
- [ ] 1. I've done my proposal `<add a link to your proposal doc>`
- [ ] 2. Proposal approved — _reviewer checks this_
- [ ] 3. I've added a draft to my proposal doc
- [ ] 4. Draft approved — _reviewer checks this_
- [ ] 5. I've submitted a pull request `#<add PR number>`
- [ ] 6. Pull request approved — _reviewer checks this_
|
C
|
UTF-8
| 1,610 | 2.8125 | 3 |
[] |
no_license
|
#include "rt.h"
t_vec cam_vect_mult(t_vec cross_x, t_vec cross_y, t_vec dir, t_vec init_dir)
{
t_vec out;
out.x = cross_x.x * init_dir.x + cross_y.x * init_dir.y +
dir.x * init_dir.z;
out.y = cross_x.y * init_dir.x + cross_y.y * init_dir.y +
dir.y * init_dir.z;
out.z = cross_x.z * init_dir.x + cross_y.z * init_dir.y +
dir.z * init_dir.z;
return (out);
}
t_vec optional_cam_dir(t_rt *rt, t_vec dir, int x, int y)
{
t_vec out;
t_vec init_vert;
t_vec init_dir;
t_vec cross_y;
t_vec cross_x;
init_vert.x = 1;
init_vert.y = 0;
init_vert.z = 0;
init_dir.x = (((double)x + 0.5) / (double)rt->w) - 0.5;
init_dir.y = (((double)y + 0.5) / (double)rt->h) - 0.5;
init_dir.z = 1;
v_normalize(&init_dir);
cross_y = v_cross(&init_vert, &dir);
v_normalize(&cross_y);
cross_x = v_cross(&cross_y, &dir);
v_normalize(&cross_x);
out = cam_vect_mult(cross_x, cross_y, dir, init_dir);
out.x = -out.x;
v_normalize(&out);
return (out);
}
t_vec camera_dir(t_rt *rt, t_vec dir, int x, int y)
{
t_vec out;
t_vec init_vert;
t_vec init_dir;
t_vec cross_y;
t_vec cross_x;
if (dir.y == 1 || dir.y == -1)
{
out = optional_cam_dir(rt, dir, x, y);
return (out);
}
init_vert.x = 0;
init_vert.y = 1;
init_vert.z = 0;
init_dir.x = (((double)x + 0.5) / (double)rt->w) - 0.5;
init_dir.y = (((double)y + 0.5) / (double)rt->h) - 0.5;
init_dir.z = 1;
v_normalize(&init_dir);
cross_x = v_cross(&init_vert, &dir);
v_normalize(&cross_x);
cross_y = v_cross(&cross_x, &dir);
v_normalize(&cross_y);
out = cam_vect_mult(cross_x, cross_y, dir, init_dir);
v_normalize(&out);
return (out);
}
|
TypeScript
|
UTF-8
| 599 | 2.515625 | 3 |
[] |
no_license
|
import {
IsArray,
IsNotEmpty,
IsNumber,
ArrayNotEmpty,
ValidateNested,
Min,
} from 'class-validator';
import { ApiProperty, getSchemaPath } from '@nestjs/swagger';
import { Type } from 'class-transformer';
export class ProductCartDto {
@IsNumber()
@Min(1)
@ApiProperty()
id: number;
@IsNumber()
@Min(1)
@ApiProperty()
quantity: number;
}
export class CreateCartDtoRequest {
@IsArray()
@IsNotEmpty()
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => ProductCartDto)
@ApiProperty({
type: [ProductCartDto],
})
products: ProductCartDto[];
}
|
Java
|
UTF-8
| 816 | 3.34375 | 3 |
[] |
no_license
|
package myapp;
import lombok.extern.log4j.Log4j;
@Log4j
public class StringEqualExample {
public static void main(String[] args) {
String strVar1 = "신민철"; // 문자열 리터럴 저장
String strVar2 = "신민철"; // 문자열 리터럴 저장
//새로운 문자열 객체 생성
String strVar3 = new String("신민철");
// [ new 연산자 ]
//지정된 타입의 클래스로부터 객체를 힙메모리 영역에 생성
//new 뒤에 나오는 String() 생성자이다. 즉 생성자를 호출
//초기화까지 끝낸 객체의 주소를 반환한다.
log.info(strVar1 == strVar2);
log.info(strVar1 == strVar3);
log.info("");
log.info(strVar1.equals(strVar2));
log.info(strVar1.equals(strVar3));
} //main
} //end class
|
C++
|
UTF-8
| 3,310 | 3.09375 | 3 |
[] |
no_license
|
/*Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent edges; that is, no two edges share a common vertex.
A maximum matching is a matching that contains the largest possible number of edges. There may be many maximum matchings.
The matching number of a graph is the size of a maximum matching. The problem is to find maximum matching of for given graph.
One of possible solutions for this problem is Blossom shrinking algorithm. An efficient implementation is described by Gabow.
Since original Gabow's algorithm is complicated I found a way how to construct more simplified version.
I tested it on some random graphs and found that is is only twice slower. So I think it is ok.
*/
#include <cstdlib>
#include <cstdio>
int G[101][101];
int VLabel[101];
int Queue[101];
int Mate[101];
int Save[101];
int Used[101];
int Up, Down;
int V, E;
void Input()
{
scanf("%d %d\n", &V, &E);
for (int i = 1; i <= E; i++)
{
int x, y;
scanf("%d %d\n", &x, &y);
G[x][++G[x][0]] = y;
G[y][++G[y][0]] = x;
}
}
void ReMatch(int x, int y)
{
int m = Mate[x]; Mate[x] = y;
if (Mate[m] == x)
{
if (VLabel[x] <= V)
{
Mate[m] = VLabel[x];
ReMatch(VLabel[x], m);
}
else
{
int a = 1 + (VLabel[x] - V - 1) / V;
int b = 1 + (VLabel[x] - V - 1) % V;
ReMatch(a, b); ReMatch(b, a);
}
}
}
void Traverse(int x)
{
for (int i = 1; i <= V; i++) Save[i] = Mate[i];
ReMatch(x, x);
for (int i = 1; i <= V; i++)
{
if (Mate[i] != Save[i]) Used[i]++;
Mate[i] = Save[i];
}
}
void ReLabel(int x, int y)
{
for (int i = 1; i <= V; i++) Used[i] = 0;
Traverse(x); Traverse(y);
for (int i = 1; i <= V; i++)
{
if (Used[i] == 1 && VLabel[i] < 0)
{
VLabel[i] = V + x + (y - 1) * V;
Queue[Up++] = i;
}
}
}
void Solve()
{
for (int i = 1; i <= V; i++)
if (Mate[i] == 0)
{
for (int j = 1; j <= V; j++) VLabel[j] = -1;
VLabel[i] = 0; Down = 1; Up = 1; Queue[Up++] = i;
while (Down != Up)
{
int x = Queue[Down++];
for (int p = 1; p <= G[x][0]; p++)
{
int y = G[x][p];
if (Mate[y] == 0 && i != y)
{
Mate[y] = x; ReMatch(x, y);
Down = Up; break;
}
if (VLabel[y] >= 0)
{
ReLabel(x, y);
continue;
}
if (VLabel[Mate[y]] < 0)
{
VLabel[Mate[y]] = x;
Queue[Up++] = Mate[y];
}
}
}
}
}
void Output()
{
int Count = 0;
for (int i = 1; i <= V; i++)
if (Mate[i] > i) Count++;
printf("Maximum matching = %d\n", Count);
}
int main(int argc, char * argv[])
{
Input(); Solve(); Output();
return 0;
}
|
Python
|
UTF-8
| 1,176 | 3.296875 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 13:20:25 2021
@author: eshasharma
"""#
# import csv and random libraries
import csv
import random
# for random example
from datetime import datetime
# Introductin to csv library and dict reader
with open('BanditsData.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
print(row['Sample A'])
with open('homes.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
# Introduction to random library and seed
from random import seed
from random import random
from random import sample
# seed random number generator - this will be used to generate the random
# numbers
seed(1)
# generate some random numbers
print(random(), random(), random())
# reset the seed
seed(2)
# generate some random numbers
print(random(), random(), random())
# generate some random numbers based on current date
seed(datetime.now())
# Generate 10 random numbers
print(random(), random(), random())
s = sample(range(1000), k=10)
print(s)
|
PHP
|
UTF-8
| 913 | 3.078125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php
class SiteMessageValidator extends RequiredFields {
/**
* Custom validation for the SiteMessage CMS form
* @param Mixed $data
* @return Boolean Returns TRUE/FALSE based on errors found in the validator
*/
function php($data) {
$valid = TRUE;
// If there is button text but no page to link to
if($data['ButtonText'] && !$data['PageID']) {
$this->validationError(
"PageID",
_t("SiteMessage.PAGEIDERROR", "Please choose a page to link to or remove the button text."),
"error"
);
// Return false
$valid = FALSE;
}
// If there is no button text but a page to link to
if(!$data['ButtonText'] && $data['PageID']) {
$this->validationError(
"ButtonText",
_t("SiteMessage.BUTTONTEXTERROR", "Please enter button text or remove the page to link to."),
"error"
);
// Return false
$valid = FALSE;
}
return $valid;
}
}
|
Markdown
|
UTF-8
| 9,152 | 2.875 | 3 |
[] |
no_license
|
# Algorithmus
Als Grundlage für die automatisch generierten Einkaufslisten wird das `last`-Array,
das die letzten 10 abgeschlossenen Einkaufslisten enthält, verwendet. Die Einkaufslisten
sind nach dem Abschlussdatum sortiert. Zu Beginn wird überprüft, ob die vom Benutzer eingestellte
Zeitspanne seit der letzten Erstellung bereits vergangen ist. Dafür sind die Felder
`settings.ai_interval` sowie `last_automatically_generated` der User-Collection verantwortlich.
Sollte dies nicht der Fall sein, wird das Erstellen der Einkaufsliste abgebrochen.
Der Erstellungsprozess läuft folgendermaßen ab. Zuerst wird die Zeitspanne in Tagen zwischen
dem neuesten und dem ältesten Einkauf ausgerechnet. Danach wird für jedes Produkt, welches
zumindest einmal auf einer Einkaufsliste vorkommt, ausgerechnet, wie oft es gekauft wurde.
Damit wird mithilfe der oben erwähnten Zeitspanne ausgerechnet, in welchem Zeitabstand
eine Einheit des entsprechenden Produktes gekauft wurde. Dies wurde wie folgt umgesetzt:
\begin{lstlisting}[language=JavaScript]
function calculateFrequency(lastLists: object[], days: number) {
const itemFrequency: object = {};
for (const list of lastLists) {
for (const item of list["items"]) {
itemFrequency[item["name"]] = itemFrequency[item["name"]]
? itemFrequency[item["name"]] + item["count"]
: item["count"];
}
}
for (const key in itemFrequency) {
itemFrequency[key] = Math.round(days / itemFrequency[key]);
}
return itemFrequency;
}
\end{lstlisting}
\needspace{9\baselineskip}
Nachdem die Zeitspanne der Produkte berechnet wurde, wird für jedes eingekaufte Produkt
das Datum des letzten Einkaufs gesucht. Danach wird überprüft, ob das Produkt
demnächst gekauft werden muss bzw. ob es unmittelbar vor heute gekauft werden hätte sollen.
Um die Anzahl der Produkte miteinzubeziehen wird der Zeitabstand zwischen dem nächsten Einkauf
des Produktes und dem heutigen Datum durch die Häufigkeit des Produktes gerechnet. Beispielsweise,
wenn das Produkt das nächste Mal in 5 Tagen gekauft werden soll, es in die Kriterien für den
Vorschlag fällt, aber das Produkt alle 2 Tage gekauft wurde, wird das Produkt mit einer Stückzahl
von 2 vorgeschlagen.
\begin{lstlisting}[language=JavaScript]
const timeSpan = Math.ceil(Math.abs(lastDay - firstDay) / (1000 * 60 * 60 * 24));
const itemFrequency: object = calculateFrequency(lists, timeSpan);
Object.keys(itemFrequency).forEach(i => {
const next: Date = getLastDateWithItem(lists, i);
next.setDate(next.getDate() + itemFrequency[i]);
const timeDiffToToday = Math.ceil(Math.floor(today - next) / (1000 * 60 * 60 * 24));
// (itemFrequency[i] <= timeSpan/2) damit zu selten gekaufte
// Produkte nicht vorgeschlagen werden
// timeDiffToToday + 5 <= 2 damit ein kleiner Puffer
// für die Tage davor gegeben ist
if ((timeDiffToToday >= 0 || timeDiffToToday + 5 <= 2)
&& (itemFrequency[i] <= timeSpan/2)) {
recommendation.push(
{
count: timeDiffToToday === 0
? 1
: Math.round(timeDiffToToday / itemFrequency[i]),
name: i,
bought: false,
price: 0,
category: "Generated"
}
);
}
});
function getLastDateWithItem(lastLists: object[], name: string) {
const lastPossibilities: Date[] = [];
lastLists.forEach((el, index) => {
if (el["items"].map(i => i["name"]).includes(name)) {
lastPossibilities.push(
lastLists[index]["completed"].toDate()
);
}
});
return new Date(Math.max(...lastPossibilities));
}
\end{lstlisting}
\needspace{6\baselineskip}
Nachdem ein Array von vorgeschlagenen Produkten erstellt wurde, wird dieses in eine neue Einkaufsliste
eingefügt. Die Einkaufsliste bekommt den Namen "Autogeneriert List DD.MM.YY". Zusätzlich wird bei dem Benutzer
bzw. bei der Gruppe, für den/die die Einkaufsliste generiert wird, das Feld `last_automatically_generated` auf
den jetzigen Zeitpunkt gesetzt. Damit der folgende Code besser lesbar ist, wird die Funktion nur für Benutzer dargestellt.
\begin{lstlisting}[language=JavaScript]
const newList = {
created: Timestamp.now(),
name: `Autogenerierte Liste $\$${("00" + today.getDate()).substr(-2)}.$\$${("00" + (today.getMonth() + 1)).substr(-2)}.$\$${today.getFullYear()}`,
type: "pending",
items: recommendedItems
};
if(recommendedItems.length === 0){
return { status: "Failed" };
}
return Promise.all([
db.collection("users").doc(uid).collection("lists").add(newList),
db.collection("users").doc(uid).set(
{
last_automatically_generated: Timestamp.now()
}, { merge: true })
]).catch(() => {
return { status: "Failed" };
}).then(() => {
return { status: "Successful" };
});
\end{lstlisting}
Bei den vorgeschlagenen Produkten werden keine Preise oder Kategorien gespeichert. Der Grund dafür ist, dass
es keine einheitlichen Preise gibt. Die Preise werden vom Benutzer selbst bzw. vom Rechnungsscanner eingetragen.
Daher ist es möglich, Produkte zu unterschiedlichen Preisen einzukaufen. Es könnte beispielsweise der Preis, zu dem
das Produkt das erste Mal gekauft wurde, oder ein Durschnittspreis hinterlegt werden. Darauf wurde jedoch aus
Zeitgründen verzichtet. Dieses Problem gibt es in schwächerer Form auch bei den Kategorien. Prinzipiell hat ein
Produkt nur eine Kategorie, jedoch kann das Produkt auch als "Selbst erstellt", oder als "Gescannt", eingefügt
werden. Es wäre möglich, diese Kategorien zu ignorieren und die übrig gebliebene zu verwenden. Das würde allerdings
nicht funktionieren, wenn das Produkt nie mit der richtigen Kategorie gekauft wurde.
\needspace{15cm}
# Implementierung in die App
Die Überprüfung, ob bereits die vom Benutzer eingestellte Dauer vergangen ist, erfolgt nicht nur in der
Cloud-Function, sondern auch auf der Clientseite, in der App selbst. Dazu wird der folgende Code in der
Einkaufslisten-View verwendet:
\begin{lstlisting}[language=Dart]
User user = Provider.of<User>(context);
if(user.settings != null) {
if (user.settings["ai_enabled"]) {
if (user.settings["ai_interval"] != null) {
if (user.lastAutomaticallyGenerated == null) {
_createAutomaticList();
} else {
DateTime nextList = user.lastAutomaticallyGenerated
.toDate().add(
Duration(
days: user.settings["ai_interval"]
)
);
if (DateTime.now().isAfter(nextList)) {
_createAutomaticList();
}
}
}
}
}
_createAutomaticList() async {
final HttpsCallable autoList = cloudFunctionInstance.getHttpsCallable(
functionName: "createAutomaticList"
);
try {
dynamic resp = await autoList.call({
"groupid": null
});
if (resp.data["status"] != "Successful") {
//Fehler in der Cloud-Function
// z.B.: Nicht genug Einkäufe abgeschlossen
} else {
InfoOverlay.showInfoSnackBar(
"Automatische Einkaufsliste wurde erstellt"
);
}
}catch(e) {
//Fehler beim Aufrufen der Cloud-Function
}
}
\end{lstlisting}
Der gleiche Code wird auch für Gruppen verwendet, mit dem Unterschied, dass anstelle der Benutzereinstellungen
die Gruppeneinstellungen geladen werden und die Cloud-Function mit der GruppenID aufgerufen wird.
\needspace{12cm}
# Vorschläge mit künstlicher Intelligenz (AI)
Beim Überlegen, wie die AI aussehen sollte, gab es einige Schwierigkeiten mit der AI. Mit einem Convolutional Neural Network
(CNN) ist diese Art von AI nicht möglich. Im Unterricht wurden CNN Grundlagen beigebracht, jedoch nur im Zusammenhang
mit Bildklassifizierung und nicht als eine Art "Vorschlags-AI". Später im Unterricht wurde das sogenannte Recurrent
Neural Network (RNN) diskutiert. Diese Art von neuronalen Netzwerken wird vor allem bei Aktienkursvorhersagen verwendet.
Anstelle der für CNNs benutzen Dense- und Conv2D-Layern, verwendet ein RNN sogenannte Long short-term memory (LSTM)-Layer.
Da ein RNN Aktienpreise vorhersagen kann, wäre es auch möglich, dieses für Produktvorhersagen zu trainieren.
# Unterschied zwischen Algorithmus und AI
Der Vorteil einer AI ist, dass sie sich auch an den Benutzer anpassen kann und dazulernt. Der Algorithmus funktioniert bei
jedem Benutzer gleich und ist daher nicht so individuell wie eine AI. Eine AI benötigt für eine gute Funktionsweise jedoch
extrem viele Trainingsdaten. Aus diesen Gründen wurde entschieden, für die automatischen Einkaufslisten-Vorschläge einen
Algorithmus zu verwenden. Der Algorithmus ist für diese Aufgabe besser geeignet, da man keine Trainingsdaten benötigt und
er zudem schneller funktioniert. Zudem verbraucht der Algorithmus auch nicht so viele Ressourcen wie eine AI.
|
Markdown
|
UTF-8
| 2,491 | 3.40625 | 3 |
[] |
no_license
|
# Amazon_Vine_Analysis
## Overview of The Analysis
PySpark was used to perform the ETL process and analyze Amazon review data on groceries written by members of the paid Amazon Vine program.The Amazon Vine program is a service that allows manufacturers and publishers to receive reviews for their products. Companies pay Amazon to provide their products to the program and then have them publish reviews by the members. The analysis involved extracting the dataset, transforming the data, connecting to an AWS RDS instance, and then loading the transformed data into pgAdmin. Additionally, PySpark was used to evaluate if there is any bias toward favorable reviews from Vine members in the groceries dataset.
## Results
There were 61 Vine (paid) reviews and 28287 non-Vine (unpaid) reviews in the groceries database.

There were 20 Vine reviews that were 5 star reviews while there were 15689 non-Vine reviews that were 5 star reviews.

Therefore 32.79% of Vine reviews were 5 star reviews and 55.46% of non-Vine reviews were 5 star reviews.

## Summary
Based on the results of this particular database, there is no bias shown when it comes to the best rated reviews and reviewers who are Vine members and therefore getting paid for their efforts. Clearly only approximately 33 percent of Vine member reviews were 5 star reviews while there was a higher percentage of approximately 55 percent of non-Vine member 5 star reviews. It is important to note that while there was a lower percentage for Vine members (supporting the fact that the data is not biased in the way explained), the sample size for Vine members is significantly lower than non-Vine members in this dataset. On one hand it is good to think that most of the Amazon reviews for these grocery products are not done by people who were paid to review them, but this also makes me wonder if the sample size for each type of reviewer was approximately equal then would the bias shown towards 5 star reviews be different. Therefore additional analysis could be done on these products with a more equal sample size for each type of reviewer. Another way this dataset could be used to evaluate biases is by looking at the star_rating column and comparing the average ratings for Vine reviews versus non-Vine reviews to see if on average paid reviews are reviewed slightly more positively than unpaid reviews as opposed to just focusing on five star ratings.
|
Python
|
UTF-8
| 289 | 3.34375 | 3 |
[] |
no_license
|
#!/usr/bin/python3
"""
Module contains inherits_from function
"""
def inherits_from(obj, a_class):
""" checks if object is a direct or indirect instance of a_class """
if issubclass(type(obj), a_class) and a_class != type(obj):
return True
else:
return False
|
Java
|
UTF-8
| 1,178 | 2.71875 | 3 |
[] |
no_license
|
package ru.gurkin.spring.journal.actuator.health;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.OptionalInt;
import java.util.stream.IntStream;
@Component
public class DayTimeHealthIndicator implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // выполняем определенную проверку работоспособности
if (errorCode != 0) {
return Health.down().withDetail("Time to sleep", errorCode).build();
}
return Health.up().build();
}
private int check(){
Instant currentTime = Instant.now();
LocalDateTime ldt = LocalDateTime.ofInstant(currentTime, ZoneId.systemDefault());
int hour = ldt.getHour();
OptionalInt result = IntStream.range(9, 21).filter(i -> i == hour).findAny();
if (result.isPresent()){
return 0;
}else {
return hour;
}
}
}
|
Java
|
UTF-8
| 4,110 | 2.359375 | 2 |
[] |
no_license
|
package com.chhaichivon.backend.springbootangular2.controllers;
import com.chhaichivon.backend.springbootangular2.models.Product;
import com.chhaichivon.backend.springbootangular2.services.ProductService;
import com.chhaichivon.backend.springbootangular2.utils.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* AUTHOR : CHHAI CHIVON
* EMAIL : chhaichivon1995@gmail.com
* DATE : 8/7/2017
* TIME : 3:47 PM
*/
@RestController
@RequestMapping(value = "/api")
public class ProductController extends BaseController<Product> {
@Autowired
private ProductService productService;
public Map<String, Object> map;
@RequestMapping(value = "/products", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Map<String, Object>> findAll(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "limit", required = false, defaultValue = "15") int limit
){
Page<Product> products= null;
try {
products = productService.findAll(new PageRequest(page,limit));
} catch (Exception e) {
e.printStackTrace();
System.out.print("Error" + e.getMessage());
}
return responseJson(products, HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Map<String, Object>> findById(@PathVariable("id") Long id) {
map = new HashMap<>();
Product product = null;
try {
product = productService.findById(id);
} catch (Exception e) {
e.printStackTrace();
}
return responseJson(product,HttpStatus.OK);
}
@RequestMapping(value = "/products", method = RequestMethod.POST, headers = "Accept=Application/json")
public ResponseEntity<Map<String, Object>> save(@RequestBody Product product) {
map = new HashMap<>();
try {
productService.save(product);
} catch (Exception e) {
e.printStackTrace();
}
return responseJson(product,HttpStatus.CREATED);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT, headers = "Accept=Application/json")
public ResponseEntity<Map<String, Object>> update(@PathVariable("id") Long id, @RequestBody Product newProduct){
map = new HashMap<>();
Product oldProduct = null;
try {
oldProduct = productService.findById(id);
if(oldProduct != null){
oldProduct.setProductName(newProduct.getProductName());
oldProduct.setPrice(newProduct.getPrice());
oldProduct.setImageUrl(newProduct.getImageUrl());
oldProduct.setDescription(newProduct.getDescription());
productService.update(oldProduct);
}
}catch (Exception e){
e.printStackTrace();
System.out.print(e.getMessage());
}
return responseJson(oldProduct,HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Map<String, Object>> delete(@PathVariable("id") long id) {
map = new HashMap<>();
Product product = productService.findById(id);
try {
if (product != null) {
productService.delete(product);
}
} catch (Exception e) {
e.printStackTrace();
}
return responseJson(product, HttpStatus.OK);
}
}
|
Java
|
UTF-8
| 2,688 | 4.125 | 4 |
[] |
no_license
|
package edu.northeastern.ccs.cs5500.homework5;
import java.util.*;
/**
* Populates a deck of cards and handles various standard functionalities
* on the deck of cards
* @author adim
*
*/
public class CardDecks {
private Random getRand = new Random();
private ArrayList<Card> deckOfCards = new ArrayList<Card>();
private int ind;
/**
* populates an empty deck with cards
* @param c an empty set of cards, which will be populated
*/
public void populateDeck(Card[] c) {
for(int i = 0; i < c.length; i++) {
deckOfCards.add(c[i]);
}
}
/**
* Indicates whether the given card is present in the deck
* @param card the card to be searched in the deck
* @return true if the card is present else false
*/
public boolean hasCard(Card card) {
if(deckOfCards.contains(Objects.requireNonNull(card)))
return true;
else
return false;
}
/**
* Deals cards from the deck
* @return the card dealt from deck
*/
private Card deal() {
if(ind != deckOfCards.size()) {
Card c = (Card) deckOfCards.get(ind);
ind++;
return c;
}
return null;
}
/**
* Since this is a game of blackjack, one of the card that belongs to the
* dealer should be hidden. The below method deals the card in hidden form.
* @return hidden card that is dealt from the deck
*/
public Card hiddenDeal() {
Card c = deal();
if(c != null) {
c.setPos(false);
}
return c;
}
/**
* Resets and shuffles a deck of cards
*/
public void shuffle() {
reset();
shuffleDeck();
shuffleDeck();
shuffleDeck();
shuffleDeck();
}
private void shuffleDeck() {
int count = deckOfCards.size();
for(int i = 0; i < count; i++) {
int ind = getRand.nextInt(count);
Card firstCard = (Card) deckOfCards.get(i);
Card nextCard = (Card) deckOfCards.get(ind);
deckOfCards.set(i, nextCard);
deckOfCards.set(ind, firstCard);
}
}
/**
* Once the card is dealt the cards are exposed, so the cards has to be
* hidden again for a new game. The below method handles this factor.
*/
public void reset() {
ind = 0;
Iterator<Card> itr = deckOfCards.iterator();
while(itr.hasNext()) {
Card c = (Card) itr.next();
c.setPos(false);
}
}
/**
* States the size of the deck
* @return count of cards present in the deck
*/
public int deckSize() {
return deckOfCards.size();
}
/**
* Since this is a game of blackjack, except for one card that belongs to the
* dealer rest of the cards should be dealt normally, the below method
* deals the card in normal form.
* @return normally dealt card
*/
public Card normalDeal() {
Card c = deal();
if(c != null) {
c.setPos(true);
}
return c;
}
}
|
JavaScript
|
UTF-8
| 9,788 | 3.21875 | 3 |
[] |
no_license
|
/**
* varFn Date Picker
* @author Fu Xiaochun
*/
(function() {
// 根据时间戳获取时间信息。
function getDates(timeStamp) {
var D = typeof timeStamp === 'undefined' ? new Date() : new Date(timeStamp);
return {
year: D.getFullYear(),
month: D.getMonth() + 1,
date: D.getDate(),
day: D.getDay(),
hour: D.getHours(),
min: D.getMinutes(),
sec: D.getSeconds()
};
}
// 获取指定月的总天数
function getDaysEveryMonth(y, m, d) {
return new Date(y, m, d).getDate();
}
// 获取星期的html模板
function getWeekTpl() {
var week = '日一二三四五六';
var cls = '';
var html = '';
for (var i = 0; i < 7; i++) {
cls = (i === 0) || (i === 6) ? 'class="red"' : '';
html += '<span ' + cls + '>' + week.charAt(i) + '</span>';
}
return html;
}
// 获取指定日期是星期几
function getTheDay(y, m, d) {
return new Date(y, m, d).getDay();
}
// 处理生成日历天数的数组。
function makeDaysArr(len, position, monthDays) {
var arr = [];
var i = 0;
if (position === 'desc') {
for (; i < len; i++) {
arr.unshift(monthDays - i);
}
} else {
for (; i < len; i++) {
arr.push(i + 1);
}
}
return arr;
}
// 以周为单位生成日历数据,返回二维数组。
function makeDateListByWeek(arr) {
var len = arr.length;
var weeks = len / 7;
var start = 0;
var end = 0;
var tempArr = [];
for (var i = 0; i < weeks; i++) {
tempArr[i] = arr.splice(0, 7);
}
return tempArr;
}
// 根据时间戳获取指定月的日历的HTML模板
function getDateTpl(timeStamp) {
var D = getDates(timeStamp);
var year = D.year;
var month = D.month;
var day = D.date;
var TODAY = getDates();
var todayStr = TODAY.year + '/' + TODAY.month + '/' + TODAY.date;
// 本月和上下月的每月总天数
var curMonthDays = getDaysEveryMonth(year, month, 0);
var lastMonthDays = getDaysEveryMonth(year, month - 1, 0);
var nextMonthDays = getDaysEveryMonth(year, month + 1, 0);
// 当月前面空的天数
var startDays = getTheDay(year, month - 1, 1);
var endDays = 6 - getTheDay(year, month - 1, curMonthDays);
var beforeDaysArr = makeDaysArr(startDays, 'desc', lastMonthDays);
var afterDaysArr = makeDaysArr(endDays, 'asc');
var curDaysArr = makeDaysArr(curMonthDays, 'asc');
// 日期列表数据:一维数组,以月为组
var dateListArr = beforeDaysArr.concat(curDaysArr).concat(afterDaysArr);
// 日期列表数据:二维数组,以周为组
var dateListArrByWeek = makeDateListByWeek(dateListArr);
// 拼接字符串
var html = '';
var len = dateListArrByWeek.length;
var curYM = year + '/' + month;
var curYMD = '';
var todayClassStr = '';
var isFirstWeek,
isLastWeek,
loopDate;
for (var i = 0; i < len; i++) {
html += '<li>';
for (var j = 0; j < 7; j++) {
loopDate = dateListArrByWeek[i][j];
curYMD = curYM + '/' + loopDate;
isFirstWeek = i === 0 && loopDate > 20;
isLastWeek = i === len - 1 && loopDate < 10;
todayClassStr = curYMD === todayStr ? 'class="cur"' : '';
if (isFirstWeek || isLastWeek) {
html += '<del>' + loopDate + '</del>';
} else {
html += '<span ' + todayClassStr + ' data-time="' + curYMD + '">' + loopDate + '</span>';
}
}
html += '</li>';
}
return html;
}
// 初始化渲染日历
function initHTML(timeStamp) {
var timeStr = typeof timeStamp === 'undefined' ? +new Date() : timeStamp;
var curYear = getDates(timeStr).year;
var curMonth = getDates(timeStr).month;
var weekTpl = getWeekTpl();
var datesTpl = getDateTpl(timeStr);
var $datePicker = $('<div class="dp-wrap" id="varfn-dp"><div class="dp-menu"><div class="dp-nav" data-nav="lastY" title="上一年"><<</div><div class="dp-nav" data-nav="lastM" title="上一月"><</div><div class="ym"><dl class="y"><dt data-type="year" id="varfn-curYear">' + curYear + '</dt></dl><p>年</p><dl class="m"><dt data-type="month" id="varfn-curMonth">' + curMonth + '</dt></dl><p>月</p></div><div class="dp-nav" data-nav="nextM" title="下一月">></div><div class="dp-nav" data-nav="nextY" title="下一年">>></div></div><div class="day" id="varfn-dp-day">' + weekTpl + '</div><ul class="date" id="varfn-dp-date">' + datesTpl + '</ul></div>');
$('body').append($datePicker);
}
////////////////////////////////////////////////////////////////////////////
// 日历下拉选项数据
var selectionData = {
year: (function() {
var arr = [];
var start = new Date().getFullYear() - 50;
for (var i = 0; i < 100; i++) {
arr.push(start++);
}
return arr;
})(),
month: (function() {
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
})()
};
// 初始化日历年月下拉选项
function initSelection() {
var $html = null;
$('#varfn-curYear, #varfn-curMonth').on('click', function(e) {
var $this = $(this);
var $parent = $this.parent();
var type = $this.data('type');
var html = '';
var data = selectionData[type];
if ($parent.hasClass('active')) {
return false;
}
$parent.addClass('active').siblings('dl').removeClass('active');
$('.date-selector').remove();
html += '<dd class="date-selector"><ul>';
for (var i = 0; i < data.length; i++) {
html += '<li>' + data[i] + '</li>';
}
html += '</ul></dd>';
$html = $(html);
$parent.append($html);
$html.show();
bindSelection();
return false;
});
$('#varfn-dp').on('click', function() {
$('.date-selector').hide();
$('.ym dl').removeClass('active');
});
}
// 获取下拉选择后的日期
function getSelectedDate() {
var y = $('#varfn-curYear').text();
var m = $('#varfn-curMonth').text();
return y + '/' + m + '/1';
}
// 绑定下拉选项相关事件。
function bindSelection() {
var $selector = $('.date-selector');
$selector.on('click', 'li', function() {
var $this = $(this);
var $p = $this.parents('dd');
var val = $this.text();
$p.siblings('dt').text(val);
$p.hide();
$('.ym dl').removeClass('active');
changeDate(getSelectedDate());
});
// 滚轮事件
var $selectorContent = $selector.children('ul');
var selectorHeight = $selector.height();
var whellContentTop = 0;
var pMinTop = selectorHeight - $selectorContent.height();
var movedifs = 100;
function scroll(n) {
if (n > 0) { // up
whellContentTop += movedifs;
whellContentTop = whellContentTop > 0 ? 0 : whellContentTop;
} else { // down
whellContentTop -= movedifs;
whellContentTop = whellContentTop < pMinTop ? pMinTop : whellContentTop;
}
$selectorContent.stop().animate({
'top': whellContentTop
}, 200);
}
$selector[0].onmousewheel = function(evt) {
var e = evt || window.event;
scroll(e.wheelDelta);
return false;
};
$selector.on('DOMMouseScroll', function(e) {
scroll(-e.detail);
return false;
});
}
// 点击选择年月
function initPageNav() {
$('.dp-menu').on('click', '.dp-nav', function() {
var $this = $(this);
var type = $this.data('nav');
var $curYear = $('#varfn-curYear');
var $curMonth = $('#varfn-curMonth');
var year = $curYear.text() / 1;
var month = $curMonth.text() / 1;
switch (type) {
case 'lastY':
year -= 1;
break;
case 'lastM':
month -= 1;
if (month < 1) {
month = 12;
year = year - 1;
}
break;
case 'nextM':
month += 1;
if (month > 12) {
month = 1;
year = year + 1;
}
break;
case 'nextY':
year += 1;
// no default
}
$curYear.text(year);
$curMonth.text(month);
changeDate(getSelectedDate());
});
}
// 日期格式化
function dateFormat(time, template) {
time = parseInt(time);
var date = new Date(time);
var Y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var i = date.getMinutes();
var s = date.getSeconds();
function leftPad(n) {
if (n < 10) {
return '0' + n;
}
return n + '';
}
var data = {
Y: Y,
y: Y.toString().substr(-2),
M: leftPad(m),
m: m,
D: leftPad(d),
d: d,
H: leftPad(h),
h: h,
I: leftPad(i),
i: i,
S: leftPad(s),
s: s
};
var reg = /([YMDHISymdhis])/g;
return template.replace(reg, function(match, u1) {
return data[u1];
});
}
// 选择日期输入
function initInput(obj) {
$('#varfn-dp-date').on('click', 'span', function() {
var date = $(this).data('time');
var formate = obj.data('dateformat');
date = +new Date(date);
obj.val(dateFormat(date, formate));
});
$(document).on('click', '#varfn-dp-date span', function() {
$('#varfn-dp').remove();
});
}
// 根据拿到的日历数据重新渲染日历
function changeDate(date) {
var datesTpl = getDateTpl(date);
$('#varfn-dp-date').html(datesTpl);
}
// 初始化日历
function init() {
var inputForm = null;
var isFocus = false;
$(document).on('click', '[data-node=datePicker]', function(e) {
var $this = $(this);
var thisHeight, $offset, left, top;
e.stopPropagation();
if (inputForm === $this) {
return false;
}
isFocus = true;
thisHeight = $this.outerHeight();
$offset = $this.offset();
left = $offset.left;
top = $offset.top + thisHeight;
inputForm !== null && $('#varfn-dp').remove();
initDatePicker($this);
inputForm = $this;
$('.dp-wrap').css({
left: left,
top: top
}).show();
});
$(document).on('click', '#varfn-dp', function(e) {
e.stopPropagation();
});
$(document).on('click', function() {
$('#varfn-dp').remove();
});
function initDatePicker(obj) {
initHTML();
initSelection();
initPageNav();
initInput(obj);
}
}
$(function() {
init();
});
})();
|
Java
|
UTF-8
| 155 | 1.507813 | 2 |
[] |
no_license
|
package testPackage;
public class test {
public static void main(String[] args) {
System.out.println("This is for GIT testing");
}
}
|
C#
|
UTF-8
| 1,864 | 2.5625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
namespace BitCI.Models.BuildSteps
{
public class PostBuildEmailStep : IBuildStep
{
public int Id { get; set; }
public int BuildId { get; set; }
public Build Build { get; set; }
public StepStatus Status { get; set; }
public string Value { get; set; }
public void Execute()
{
//update log
object locker = new Object();
lock (locker)
{
using (FileStream file = new FileStream(Build.Log, FileMode.Append, FileAccess.Write, FileShare.Read))
using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
{
writer.WriteLine();
writer.WriteLine("Step 5:");
writer.WriteLine("Send email to - " + Value);
}
}
try
{
SmtpClient mailServer = new SmtpClient("smtp.mail.ru", 2525);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("bitcimail@mail.ru", "Test1234");
string from = "bitcimail@mail.ru";
string to = Value;
MailMessage msg = new MailMessage(from, to)
{
Subject = "BitCI test report",
Body = "BitCI notifys You for a triggered build."
};
msg.Attachments.Add(new Attachment(Build.Log));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email to " + Value + ". Error : " + ex.Message);
}
}
}
}
|
JavaScript
|
UTF-8
| 1,070 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
document.addEventListener("DOMContentLoaded", function(event) {
var productsCount = document.getElementById("products-count");
console.log(productsCount);
var addToCartButtons = document.querySelectorAll(".add-to-cart")
console.log(addToCartButtons);
for( var i = 0; i < addToCartButtons.length; i++){
addToCartButtons[i].addEventListener("click",function (e) {
e.preventDefault();
var prevProductsCount =+ productsCount.textContent;
productsCount.textContent = prevProductsCount + 1;
})
}
var buttonLike = document.querySelectorAll(".device_like")
console.log(buttonLike)
var length = buttonLike.length;
for( let i = 0; i < length; i++) {
buttonLike[i].addEventListener("click", function(e){
e.preventDefault();
console.log('is like', buttonLike[i].classList.contains("like") );
if ( this.classList.contains("like") ) {
this.classList.remove("like")
} else {
this.classList.add("like")
}
}
)}
$('.slider').slick({
dots: true,
speed: 3000,
autoplay: true,
autoplayspeed: true
});
});
|
Java
|
UTF-8
| 1,918 | 3.15625 | 3 |
[] |
no_license
|
/**
* wxh Inc.
* Copyright (c) 2006-2017 All Rights Reserved.
*/
package com.wxh.rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/**
* 服务器
* 创建RMI注册表,启动RMI服务,并将远程对象注册到RMI注册表中
* @author wxh
* @version $Id: HelloServer.java, v 0.1 2017年6月13日 上午10:19:50 wxh Exp $
*/
public class HelloServer {
public static void main(String[] args) {
try {
// 创建一个远程对象
IHello rHello = new HelloImpl();
/*
* 本地主机上的远程对象注册表Registry的实例,并指定端口为8888,
* 这一步必不可少(Java默认端口是1099),必不可缺的一步,
* 缺少注册表创建,则无法绑定对象到远程注册表上
*/
LocateRegistry.createRegistry(8888);
/*
* 把远程对象注册到RMI注册服务器上,并命名为RHello
* 绑定的URL标准格式为:rmi://host:port/name(其中协议名可以省略
*/
// Naming.bind("//localhost:8888/RHello",rhello);
Naming.bind("rmi://localhost:8888/RHello", rHello);
System.out.println(">>>>>> INFO:远程IHello对象绑定成功! >>>>>> ");
} catch (RemoteException e) {
System.out.println("创建远程对象发生异常!");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("发生URL畸形异常!");
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println("发生重复绑定对象异常!");
e.printStackTrace();
}
}
}
|
Python
|
UTF-8
| 2,342 | 2.8125 | 3 |
[] |
no_license
|
import sys
import os
import pprint
root_dir = '/Users/mattfaus/dev/dev-git'
def parse_logs(file_paths):
# print 'Parsing ', file_paths
# These files are generated with a command line like the following:
# analytics@ip-10-0-0-108:~/kalogs/2013/04/10$ zgrep -e "UserData.*put" *.gz >> 2013.04.10-UserDataPut.txt
pp = pprint.PrettyPrinter(indent=4)
for path in file_paths:
full_path = os.path.join(root_dir, path)
print 'Parsing', full_path
the_dict = parse_log(open(full_path, 'r'))
print_dict(the_dict)
def parse_log(the_file):
# Example log entries:
# 00:00:00Z.log.gz:16: api/v1_notifications.py:122 -- UserData.<put>
# 00:00:00Z.log.gz:92: api/v1_notifications.py:88 -- UserData.<put>
# 00:00:00Z.log.gz:7: api/v1_user.py:2224 -- UserData.<put>
# 00:00:00Z.log.gz:27: api/v1_user.py:533 -- UserData.<put>
# Build a dict that looks like this:
# {
# 'discussion/voting.py':
# {
# # Line number : Count
# 172: 15000,
# 185: 25000,
# },
# ...
# }
line_count_dict = {}
for line in the_file:
parts = line.split(' ')
if len(parts) < 2 or ':' not in parts[1]:
print 'Could not understand', line
continue
# 00:00:00Z.log.gz:27: api/v1_user.py:533 -- UserData.<put>
count = int(parts[0].split(':')[3])
path_parts = parts[1].split(':')
path = path_parts[0]
src_line_num = path_parts[1]
if not line_count_dict.get(path):
line_count_dict[path] = {}
if not line_count_dict[path].get(src_line_num):
line_count_dict[path][src_line_num] = count
line_count_dict[path][src_line_num] += count
return line_count_dict
def print_dict(the_dict):
"""Print stuff in CSV format for easy input to Excel."""
for k in the_dict:
for l in the_dict[k]:
print "{0},{1},{2}".format(k, l, the_dict[k][l])
if __name__ == "__main__":
# Find files that look like 2013.03.10-UserDataPut.txt
#files = [f for f in os.listdir(root_dir) if 'UserData' in f]
if len(sys.argv) < 2:
print 'Usage: parse_userdata_put_logs.py <file_to_parse> [second_file] [third_file] [...] [nth file]'
else:
parse_logs(sys.argv[1:])
|
C
|
UTF-8
| 1,436 | 2.625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
static sig_atomic_t sig_status = 0;
void usr1_hand()
{
sig_status = 1;
}
int main(int argc, char **argv)
{
pid_t p, s;
int i;
struct sigaction usr1_act;
p = fork();
if (p == -1) {
perror("fork()");
exit(errno);
}
if (p != 0) {
// printf("%ld\n", (long int)p);
_exit(0);
}
else {
s = setsid();
if (s < 0) {
perror("setsid()");
exit(errno);
}
printf("%ld\n", (long int)s);
//setsid() = %ld;\n", (long int)getpid(), (long int)s);
for (i = 0; i < 3; i++)
close(i);
sigemptyset(&usr1_act.sa_mask);
usr1_act.sa_flags = 0;
usr1_act.sa_handler = (void *)&usr1_hand;
for(;;) {
if (sigaction(SIGURG, &usr1_act, NULL) < 0) {
perror("sigaction(SIGUSR1)");
return 1;
}
if (sig_status == 1)
break;
}
_exit(0);
}
return 0;
}
|
C
|
UTF-8
| 29,659 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <signal.h>
#include "socket.h"
#ifndef PORT
#define PORT 50055
#endif
#define LISTEN_SIZE 5
#define WELCOME_MSG "Welcome to CSC209 Twitter! Enter your username: "
#define SEND_MSG "send"
#define SHOW_MSG "show"
#define FOLLOW_MSG "follow"
#define UNFOLLOW_MSG "unfollow"
#define BUF_SIZE 256
#define MSG_LIMIT 8
#define FOLLOW_LIMIT 5
struct client {
int fd;
struct in_addr ipaddr;
char username[BUF_SIZE];
char message[MSG_LIMIT][BUF_SIZE];
struct client *following[FOLLOW_LIMIT]; // Clients this user is following
struct client *followers[FOLLOW_LIMIT]; // Clients who follow this user
char inbuf[BUF_SIZE]; // Used to hold input from the client
char *in_ptr; // A pointer into inbuf to help with partial reads
struct client *next;
};
// Provided functions.
void add_client(struct client **clients, int fd, struct in_addr addr);
void remove_client(struct client **clients, int fd);
// These are some of the function prototypes that we used in our solution
// You are not required to write functions that match these prototypes, but
// you may find them helpful when thinking about operations in your program.
// Send the message in s to all clients in active_clients.
void announce(struct client **active_clients, char *s);
// Move client c from new_clients list to active_clients list.
void activate_client(struct client *c,
struct client **active_clients_ptr, struct client **new_clients_ptr);
//Handle the input and output for the client who has not yet entered a name.
int handle_new_client(struct client *p, struct client **active_clients, struct client **new_clients);
//Handle the commands form the current active user.
void handle_commands(struct client *p, struct client **active_clients_ptr);
// Find the network newline in the input from users.
int find_network_newline(const char *buf, int n);
//Read the input form a client.
int read_from_any_client(struct client *p);
//Partial_remove is a helper function that removes a client p from both lists.
void partial_remove(struct client *p, struct client *current_following, struct client *current_follower);
//Client1 unfollows client2.
int unfollow(struct client *client1, struct client *client2, struct client **active_clients_ptr);
//Client1 follows client2.
int follow(struct client *client1, struct client *client2, struct client **active_clients_ptr);
// Broadcast the message to all the followers.
int send_message(struct client *client, char *msg, struct client **active_clients);
//Displays the previously sent messages of those users this user is following.
void show_messages(struct client *p, struct client **active_clients_ptr);
// Indicate to the user that the command entered is invalid.
void invalid_command(struct client *p, struct client **active_clients_ptr);
// Announce to all clients except the client with username as he is the one exiting.
void exit_announce(struct client **active_clients_ptr, char *username);
// The set of socket descriptors for select to monitor.
// This is a global variable because we need to remove socket descriptors
// from allset when a write to a socket fails.
fd_set allset;
/*
* Create a new client, initialize it, and add it to the head of the linked
* list.
*/
void add_client(struct client **clients, int fd, struct in_addr addr) {
// Create all the fields of the new_client and add it to the head of clients list.
struct client *p = calloc(1 ,sizeof(struct client));
if (!p) {
perror("calloc");
exit(1);
}
printf("Adding client %s\n", inet_ntoa(addr));
p->fd = fd;
p->ipaddr = addr;
memset(p->username, '\0', sizeof(p->username));
p->in_ptr = p->inbuf;
p->inbuf[0] = '\0';
p->next = *clients;
// initialize messages to empty strings
for (int i = 0; i < MSG_LIMIT; i++) {
p->message[i][0] = '\0';
}
*clients = p;
}
/*
* Remove client from the linked list and close its socket.
* Also, remove socket descriptor from allset.
*/
void remove_client(struct client **clients, int fd) {
struct client **p;
for (p = clients; *p && (*p)->fd != fd; p = &(*p)->next);
// Now, p points to (1) top, or (2) a pointer to another client
// This avoids a special case for removing the head of the list
if (*p) {
// TODO: Remove the client from other clients' following/followers
// lists
for (int i = 0; i < FOLLOW_LIMIT; i++){
// These are the temporary pointers to both lists in p.
struct client *following = (*p)->following[i];
struct client *follower = (*p)->followers[i];
partial_remove(*p, following, follower);
(*p)->following[i] = NULL;
(*p)->followers[i] = NULL;
}
// Remove the client
struct client *t = (*p)->next;
printf("Removed client. %d %s\n", fd, inet_ntoa((*p)->ipaddr));
FD_CLR((*p)->fd, &allset);
close((*p)->fd);
free(*p);
*p = t;
} else {
fprintf(stderr, "Trying to remove fd %d, but I don't know about it\n", fd);
}
}
int main (int argc, char **argv) {
int clientfd, maxfd, nready;
struct client *p;
struct sockaddr_in q;
fd_set rset;
// If the server writes to a socket that has been closed, the SIGPIPE
// signal is sent and the process is terminated. To prevent the server
// from terminating, ignore the SIGPIPE signal.
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGPIPE, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
// A list of active clients (who have already entered their names).
struct client *active_clients = NULL;
// A list of clients who have not yet entered their names. This list is
// kept separate from the list of active clients, because until a client
// has entered their name, they should not issue commands or
// or receive announcements.
struct client *new_clients = NULL;
struct sockaddr_in *server = init_server_addr(PORT);
int listenfd = set_up_server_socket(server, LISTEN_SIZE);
// Initialize allset and add listenfd to the set of file descriptors
// passed into select
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
// maxfd identifies how far into the set to search
maxfd = listenfd;
while (1) {
// make a copy of the set before we pass it into select
rset = allset;
nready = select(maxfd + 1, &rset, NULL, NULL, NULL);
if (nready == -1) {
perror("select");
exit(1);
} else if (nready == 0) {
continue;
}
// check if a new client is connecting
if (FD_ISSET(listenfd, &rset)) {
printf("A new client is connecting\n");
clientfd = accept_connection(listenfd, &q);
FD_SET(clientfd, &allset);
if (clientfd > maxfd) {
maxfd = clientfd;
}
printf("Connection from %s\n", inet_ntoa(q.sin_addr));
add_client(&new_clients, clientfd, q.sin_addr);
char *greeting = WELCOME_MSG;
if (write(clientfd, greeting, strlen(greeting)) == -1) {
fprintf(stderr,
"Write to client %s failed\n", inet_ntoa(q.sin_addr));
remove_client(&new_clients, clientfd);
}
}
// Check which other socket descriptors have something ready to read.
// The reason we iterate over the rset descriptors at the top level and
// search through the two lists of clients each time is that it is
// possible that a client will be removed in the middle of one of the
// operations. This is also why we call break after handling the input.
// If a client has been removed, the loop variables may no longer be
// valid.
int cur_fd, handled;
for (cur_fd = 0; cur_fd <= maxfd; cur_fd++) {
if (FD_ISSET(cur_fd, &rset)) {
handled = 0;
// Check if any new clients are entering their names
for (p = new_clients; p != NULL; p = p->next) {
if (cur_fd == p->fd) {
// Handle input from a new client who has not yet
// entered an acceptable name.
if (read_from_any_client(p) == 1) {
// Invalid read from client p.
fprintf(stderr, "Read from the client failed\n");
remove_client(&new_clients, p->fd);
} else {
// Handle the new user who is yet to enter username.
handled = handle_new_client(p, &active_clients, &new_clients) + 1;
// If handeled is 1 then correct usename has been entered.
// Thus activate client.
if (handled == 1) {
activate_client(p, &active_clients, &new_clients);
} else {
fprintf(stderr, "Invalid username entered by user:%d\n", p->fd);
}
break;
}
}
}
// This is for previously added users (i.e. active users).
// User that was just activated doesn't satisfy this if condition.
if (handled == 0) {
// Check if this socket descriptor is an active client
for (p = active_clients; p != NULL; p = p->next) {
if (cur_fd == p->fd) {
// Handle input from an active client.
if(read_from_any_client(p) == 1) {
fprintf(stderr, "Read from the client failed\n");
exit_announce(&active_clients, p->username);
remove_client(&active_clients, p->fd);
} else {
// Handle any command issues by this of the active users.
handle_commands(p, &active_clients);
break;
}
}
}
}
}
}
}
return 0;
}
int handle_new_client(struct client *p, struct client **active_clients, struct client **new_clients) {
// p->inbuf refers to the username of the client as its a new client.
// Checking whether username is valid or not.
int flag = 0;
if (p->inbuf[0] != '\0'){
struct client *temp_client = (*active_clients);
while (temp_client != NULL){
if (strcmp(temp_client->username, p->inbuf) == 0) flag = -1;
temp_client = temp_client->next;
}
}
// Username entered is not valid.
if (p->inbuf[0] == '\0' || flag == -1) {
char *msg = "INVALID USERNAME PLEASE ENTER AGAIN: ";
if (write(p->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. A\n");
exit_announce(active_clients, p->username);
remove_client(new_clients, p->fd);
}
return 1;
} else {
return 0;
}
}
void handle_commands(struct client *p, struct client **active_clients){
// p->inbuf refers to the current message/command of the client p.
printf("%s: %s\n", p->username, p->inbuf);
char *space = strchr(p->inbuf, ' ');
// Check if command has a space in it.
if (space == NULL) {
// For the command to be valid it has to be show or a quit command.
if (strcmp(p->inbuf, "show") == 0){
show_messages(p, active_clients);
} else if (strcmp(p->inbuf, "quit") == 0){
exit_announce(active_clients, p->username);
remove_client(active_clients, p->fd);
} else {
// Otherwise, the user entered an invalid command.
invalid_command(p, active_clients);
return;
}
} else {
// Parse the command that conatins a space.
// Split it into two parts the command and
// the rest_command that remains after the space.
int size = strlen(p->inbuf) - strlen(space) + 1;
char command[size];
char rest_command[strlen(space)];
strncpy(command, p->inbuf, size - 1);
strncpy(rest_command, space + 1, strlen(space) - 1);
command[size - 1] = '\0';
rest_command[strlen(space) - 1] = '\0';
// If its a follow command.
if (strcmp(command, "follow") == 0){
int flag = 1;
// Compare usernames that are in the active clients list.
// If username matches the rest_command then follow that user.
struct client *temp = *active_clients;
while (temp != NULL) {
if (strcmp(temp->username, rest_command) == 0){
// Found the client to follow.
int ret = follow(p, temp, active_clients);
if (ret == 1){
invalid_command(p, active_clients);
return;
}
flag = 0;
}
temp = temp->next;
}
// if user to follow not found then username to follow was invalid.
// Notify user p.
if (flag == 1){
invalid_command(p, active_clients);
return;
}
// If its a un-follow command.
} else if (strcmp(command, "unfollow") == 0){
int flag = 1;
// Compare usernames that are in the active clients list.
// If username matches the rest_command then un-follow that user.
struct client *temp = *active_clients;
while (temp != NULL) {
if (strcmp(temp->username, rest_command) == 0){
// Found the client to un-follow.
int ret = unfollow(p, temp, active_clients);
// If can't follow.
if (ret == 1){
invalid_command(p, active_clients);
return;
}
flag = 0;
}
temp = temp->next;
}
// If user to un-follow not found then username to un-follow was invalid.
// Notify user p.
if (flag){
invalid_command(p, active_clients);
return;
}
// If the command is send send the message.
} else if (strcmp(command, "send") == 0){
send_message(p, rest_command, active_clients);
} else {
invalid_command(p, active_clients);
}
}
}
// Helper method to write "Invalid Command to the user p.
void invalid_command(struct client *p, struct client **active_clients){
char *msg = "Invalid command.\n";
if (write(p->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed.\n");
exit_announce(active_clients, p->username);
remove_client(active_clients, p->fd);
}
}
void show_messages(struct client *p, struct client **active_clients){
// Iterate over the following list of p.
for (int i = 0; i < FOLLOW_LIMIT; i++){
struct client *temp = p->following[i];
// If p is following another user.
if (temp != NULL){
// Send all the previously sent messages of that user to p.
for (int j = 0; j < MSG_LIMIT && temp->message[j][0] != '\0'; j++){
// Initialising the message.
int size = strlen(temp->username) + strlen(" wrote: ") + strlen(temp->message[j]) + 2;
char buf[size];
buf[0] = '\0';
strncat(buf, temp->username, strlen(temp->username));
strncat(buf, " wrote: ", strlen(" wrote: "));
strncat(buf, temp->message[j], strlen(temp->message[j]));
buf[size - 2] = '\n';
buf[size - 1] = '\0';
// Writing the message to p.
if (write(p->fd, buf, strlen(buf)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients, p->username);
remove_client(active_clients, p->fd);
}
}
}
}
}
// Helper method that is responsible for partial reads from the user and store the data read in p-inbuf.
int read_from_any_client(struct client *p) {
int num_buf = 0; // How many bytes currently in buffer?
int room = sizeof(p->inbuf); // How many bytes remaining in buffer?
int nbytes;
//memset(p->inbuf, '\0', strlen(p->inbuf));
p->in_ptr = p->inbuf;
while ((nbytes = read(p->fd, p->in_ptr, room)) > 0){
// Step 1: update inbuf (how many bytes were just added?)
num_buf += nbytes;
p->in_ptr = &(p->inbuf[num_buf]);
int where;
// The loop condition below calls find_network_newline
// to determine if a full line has been read from the client.
while ((where = find_network_newline(p->inbuf, num_buf)) > 0 ){
// We have a full line.
// Output the full line, not including the "\r\n",
// using print statement below.
p->inbuf[where - 2] = '\0';
printf("[%d] Read %d bytes\n", p->fd, num_buf);
printf("[%d] Found Newline: %s\n", p->fd, p->inbuf);
return 0;
}
// Update p->in_ptr and room, in preparation for the next read.
p->in_ptr = &p->inbuf[num_buf];
room = BUF_SIZE - num_buf;
}
// Error as we cant read from p.
return 1;
}
void activate_client(struct client *c, struct client **active_clients_ptr, struct client **new_clients_ptr) {
add_client(active_clients_ptr, c->fd, c->ipaddr);
strncat((*active_clients_ptr)->username, c->inbuf, strlen(c->inbuf));
//Removing the client from the new_clients list.
struct client **p;
for (p = new_clients_ptr; *p && (*p)->fd != c->fd; p = &(*p)->next);
// Now, p points to the client to be removed.
if (*p) {
// Remove the client
struct client *t = (*p)->next;
free(*p);
*p = t;
}
// Creating a message for new user joining Twitter.
int size = strlen(" has just joined.\n") + 1 + strlen((*active_clients_ptr)->username);
char msg[size];
msg[0] = '\0';
strncat(msg, (*active_clients_ptr)->username, strlen((*active_clients_ptr)->username));
strncat(msg, " has just joined.\n", strlen(" has just joined.\n"));
printf("%s", msg);
// Send the message to all the active clients.
announce(active_clients_ptr, msg);
}
// Helper method for remove_client. Partial_remove removes p from both the followers and following
// lists of current_following and current_follower clients respepctively.
void partial_remove(struct client *p, struct client *current_following, struct client *current_follower) {
// Removing p from the current_follower client's following list.
if (current_follower != NULL) {
struct client *temp = (current_follower->following)[0];
if (temp != NULL) {
for (int i = 0; i < FOLLOW_LIMIT; i++) {
if (strcmp(temp->username, p->username) == 0){
current_follower->following[i] = NULL;
break;
}
temp += i;
}
}
}
// Removing p from the current_following client's followers list.
if (current_following != NULL) {
struct client *temp_new = (current_following->followers)[0];
if (temp_new != NULL){
for (int i = 0; i < FOLLOW_LIMIT; i++){
if ((strcmp(temp_new->username, p->username)) == 0){
current_following->followers[i] = NULL;
break;
}
temp_new += i;
}
}
}
}
// Client 1 unfollows client 2.
int unfollow(struct client *client1, struct client *client2, struct client **active_clients_ptr){
if (client1 != NULL && client2 != NULL){
// Removing client1 from the followers list of client2.
for (int i = 0; i < FOLLOW_LIMIT; i++){
if (client2->followers[i] != NULL) {
if ((strcmp(client1->username, (client2->followers[i])->username)) == 0) {
client2->followers[i] = NULL;
}
}
}
// Removing client2 from the following list of client1.
for (int i = 0; i < FOLLOW_LIMIT; i++){
if (client1->following[i] != NULL) {
if (strcmp(client2->username, (client1->following[i])->username) == 0) {
client1->following[i] = NULL;
}
}
}
// Success message to client 1 that he has successfully unfollowed client 2.
int size = strlen("Unfollowed successfully.") + strlen(client2->username) + 2;
char msg[size];
msg[0] = '\0';
strncat(msg, "Unfollowed ", 11);
strncat(msg, client2->username, strlen(client2->username));
strncat(msg, " successfully.", 14);
msg[size - 2] = '\n';
msg[size - 1] = '\0';
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed.\n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 0;
}
return 1;
}
// Client 1 follows client 2.
int follow(struct client *client1, struct client *client2, struct client **active_clients_ptr){
if (client1 != NULL && client2 != NULL) {
// Checking if client1 already follows client2.
for (int i = 0; i < FOLLOW_LIMIT; i++) {
// Check if client1 is already present in client2 followers list.
if (client2->followers[i] != NULL) {
// Check if client1 == client2 or if client 1 is already following client2.
if (strcmp((client2->followers[i])->username, client1->username) == 0) {
char *msg = "Already following client.\n";
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 1;
}
}
if (strcmp(client2->username, client1->username) == 0){
char *msg = "Cant follow yourself.\n";
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 1;
}
}
//Add the client2 to the followings list of client1.
int flag1 = 1;
for (int i = 0; i < FOLLOW_LIMIT; i++) {
if (client1->following[i] == NULL) {
//There is empty space in the following list so add client 2 here.
client1->following[i] = client2;
flag1 = 0;
break;
}
}
// If no sufficient space in the followings list notify user.
if (flag1 == 1) {
char *msg = "Maximum following capacity reached couldn't follow.\n";
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 1;
}
//Add the client1 to the followers list of client2.
int flag2 = 1;
for (int i = 0; i < FOLLOW_LIMIT; i++) {
if (client2->followers[i] == NULL) {
client2->followers[i] = client1;
flag2 = 0;
break;
}
}
// If no sufficient space in the followers list notify user.
if (flag2 == 1) {
char *msg = "Maximum followers capacity reached couldn't allow %s to follow.\n";
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed.\n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 1;
}
// Success message to client 1 that he has successfully followed client 2.
int size = strlen("Following successfully.") + strlen(client2->username) + 2;
char msg[size];
msg[0] = '\0';
strncat(msg, "Following ", 10);
strncat(msg, client2->username, strlen(client2->username));
strncat(msg, " successfully.", 14);
msg[size - 2] = '\n';
msg[size - 1] = '\0';
if (write(client1->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed.\n");
exit_announce(active_clients_ptr, client1->username);
remove_client(active_clients_ptr, client1->fd);
}
return 0;
}
return 1;
}
int send_message(struct client *client, char* msg, struct client **active_clients) {
// Checking whether this client has issued MSG_LIMIT messages.
int flag = 1;
for (int i = 0; i < MSG_LIMIT; i++){
if (client->message[i][0] == '\0'){
flag = 0;
strncpy(client->message[i], msg, strlen(msg));
// The client has space to issue messages.
// Broadcast the message to all of its followers.
int size = strlen(client->username) + 4 + strlen(msg);
char arr[size];
arr[0] = '\0';
strncat(arr, client->username, strlen(client->username));
strncat(arr, ": ", 2);
strncat(arr, msg, strlen(msg));
arr[size - 2] = '\n';
arr[size - 1] = '\0';
for (int i = 0; i < FOLLOW_LIMIT; i++){
if (client->followers[i] != NULL) {
if (write((client->followers[i])->fd, arr, strlen(arr)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients, client->username);
remove_client(active_clients, client->fd);
}
}
}
return 0;
}
}
// User has reached limit number of messages can't send anymore.
if (flag) {
char *msg = "Reached maximum limit of messages to send. Cant send more messages.\n";
if (write(client->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. \n");
exit_announce(active_clients, client->username);
remove_client(active_clients, client->fd);
}
return 1;
}
return 0;
}
// Send message s to all of the active clients.
void announce(struct client **active_clients, char *s){
struct client *temp = *active_clients;
while (temp != NULL) {
if (write(temp->fd, s, strlen(s)) == -1) {
fprintf(stderr, "Write to client failed. \n");
remove_client(active_clients, temp->fd);
return;
}
temp = temp->next;
}
}
// Announce to all clients except the client with username as he is the one exiting.
void exit_announce(struct client **active_clients_ptr, char* username){
// Announcing that this user has exited Twitter.
int size = strlen(username) + strlen(" has exited Twitter.") + 2;
char msg[size];
msg[0] = '\0';
strncat(msg, username, strlen(username));
strncat(msg, " has exited Twitter.", strlen(" has exited Twitter."));
msg[size - 2] = '\n';
msg[size - 1] = '\0';
struct client *temp = *active_clients_ptr;
while(temp != NULL){
if (strcmp(temp->username, username) != 0){
if (write(temp->fd, msg, strlen(msg)) == -1) {
fprintf(stderr, "Write to client failed. \n");
remove_client(active_clients_ptr, temp->fd);
return;
}
}
temp = temp->next;
}
}
/*
* Search the first n characters of buf for a network newline (\r\n).
* Return one plus the index of the '\n' of the first network newline,
* or -1 if no network newline is found.
*/
int find_network_newline(const char *buf, int n) {
for (int i = 0; i < n - 1; i++){
if (buf[i] == '\r' && buf[i + 1] == '\n'){
return i + 2;
}
}
return -1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.