language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 271
| 2.53125
| 3
|
[] |
no_license
|
'''
CS3150
PythonParser
@author: Sabrina Cown
'''
from Parser import *
class Id(object):
def __init__(self, ch):
self.ch = ch
def getValue(self, ch):
return Parser.fetch(self.ch)
def getChar(self, ch):
self.var = ch
return self.var
|
Java
|
UTF-8
| 2,168
| 2.3125
| 2
|
[] |
no_license
|
package kz.almaty.boombrains.viewmodel.records.record_view_model;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import org.jetbrains.annotations.NotNull;
import kz.almaty.boombrains.data.models.records_model.MyRecordsModel;
import kz.almaty.boombrains.data.services.APIService;
import kz.almaty.boombrains.data.services.RetrofitClass;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RecordViewModel extends ViewModel {
public void getAllRecords(Context context, RecordView view) {
final MutableLiveData<MyRecordsModel> data = new MutableLiveData<>();
APIService service = RetrofitClass.getApiService();
view.showLoading();
service.getListOfRecords(RetrofitClass.getUserToken(context)).enqueue(new Callback<MyRecordsModel>() {
@Override
public void onResponse(@NotNull Call<MyRecordsModel> call, @NotNull Response<MyRecordsModel> response) {
view.hideLoading();
if (response.isSuccessful()) {
if (response.body() != null) {
Log.d("EVERY::", "GOOD");
MyRecordsModel loginModel = response.body();
data.setValue(loginModel);
view.loadList(data.getValue());
} else {
showToast(context, "Result is empty!");
}
} else {
switch (response.code()) {
case 404: view.errorMessage(404); break;
case 401: view.errorMessage(401); break;
}
}
}
@Override
public void onFailure(@NotNull Call<MyRecordsModel> call, @NotNull Throwable t) {
view.hideLoading();
showToast(context, t.getMessage());
}
});
}
private void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
|
Python
|
UTF-8
| 750
| 3.359375
| 3
|
[] |
no_license
|
d=0
maxdel=2
for i in range(84052,84131):
k=0
for a in range(1,i+1):
if i%a==0:
k+=1
if k>maxdel:
maxdel=k
d=i
print(maxdel,d)
"""
Напишите программу, которая ищет среди целых чисел, принадлежащих числовому
отрезку [84052; 84130], число, имеющее максимальное количество различных
натуральных делителей, если таких чисел несколько — найдите минимальное из них. Выведите на экран количество делителей такого числа и само число.
"""
|
TypeScript
|
UTF-8
| 5,879
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import Controller, { Delete, Get, Post, Put, Route } from "@config/controller";
import Folder from "@models/folder/folder";
import FolderFolder from "@models/folder/folder_folder";
import { Request, Response } from "express";
import validate from "validate.js";
@Route("/api/folder")
export class FolderController extends Controller {
private readonly validateCreate: any;
private readonly validateUpdate: any;
constructor () {
super();
this.validateCreate = {
type_id: {
presence: {
allowEmpty: false,
message: "^Tipo não informado."
}
},
project_id: {
presence: {
allowEmpty: false,
message: "^Projeto não informado."
}
},
name: {
presence: {
allowEmpty: false,
message: "^Nome não informado."
},
length: {
maximum: 100,
tooLong: "^Nome deve ter no máximo %{count} caracteres."
}
},
description: {
presence: {
allowEmpty: false,
message: "^Descrição não informada."
},
length: {
maximum: 5000,
tooLong: "^Descrição deve ter no máximo %{count} caracteres."
}
}
};
this.validateUpdate = {
id: {
presence: {
allowEmpty: false,
message: "^ID não informado."
},
numericality: {
notValid: "^ID inválido."
}
},
...this.validateCreate
};
}
@Get()
async find (_req: Request, res: Response): Promise<Response> {
try {
const sql = `
SELECT f.id
, f.name
, f.description
, f.type_id
, ft.description type
, f.project_id
, p.description project
FROM folder f
INNER
JOIN folder_type ft
ON ft.deleted_at IS NULL
AND ft.id = f.type_id
INNER
JOIN project p
ON p.deleted_at IS NULL
AND p.id = f.project_id
WHERE f.deleted_at IS NULL`;
const folders: any = await this.select(sql);
return res.json(folders);
} catch (err) {
return res.status(500).json({
error: {
message: err.message,
type: err.name
}
});
}
}
@Get("/:id")
async read (req: Request, res: Response): Promise<Response> {
try {
const record = await Folder.findByPk(req.params.id, {
attributes: ["id", "name", "description", "type_id", "project_id"]
});
if (!record) this.error.notFoundForRead();
return res.json(record);
} catch (err) {
return res.status(500).json({
error: {
message: err.message,
type: err.name
}
});
}
}
@Post()
async create (req: Request, res: Response): Promise<Response> {
try {
const errors = validate(req.body, this.validateCreate);
if (errors) {
return res.status(500).json({ errors });
}
const { type_id, project_id, name, description, folder_id } = req.body;
let folder: any;
await this.faina().transaction(async (t) => {
folder = await Folder.create({
type_id: type_id,
project_id: project_id,
description: description,
name: name
}, {
transaction: t
});
// Inserir o Relacionamento da Pasta com a Pasta Mãe
if (!validate.isEmpty(folder_id)) {
await FolderFolder.create({
parent_id: folder.id,
folder_id: folder_id
}, {
transaction: t
});
}
});
return res.json({
folderId: folder.id,
message: this.message.successCreate()
});
} catch (err) {
return res.status(500).json({
error: {
message: err.message,
type: err.name
}
});
}
}
@Put()
async update (req: Request, res: Response): Promise<Response> {
try {
const errors = validate(req.body, this.validateUpdate);
if (errors) {
return res.status(500).json({ errors });
}
const { type_id, project_id, name, description, folder_id, folder_idNew } = req.body;
const folder = await Folder.findByPk(req.body.id);
if (!folder) {
this.error.notFoundForUpdate();
}
folder.type_id = type_id;
folder.project_id = project_id;
folder.description = description;
folder.name = name;
await this.faina().transaction(async (t) => {
await folder.save({ transaction: t });
if (!validate.isEmpty(folder_idNew)) {
const folderFolder = await FolderFolder.findOne({
where: {
parent_id: req.body.id,
folder_id: folder_id
}
});
if (folderFolder) {
folderFolder.folder_id = folder_idNew;
await folderFolder.save({ transaction: t });
}
}
});
return res.json({
id: folder.id,
message: this.message.successUpdate()
});
} catch (err) {
return res.status(500).json({
error: {
message: err.message,
type: err.name
}
});
}
}
@Delete("/:id")
async delete (req: Request, res: Response): Promise<Response> {
try {
const record = await Folder.findByPk(req.params.id);
if (!record) this.error.notFoundForDelete();
await record.destroy();
return res.json({
id: Number(req.params.id),
message: this.message.successDelete()
});
} catch (err) {
return res.status(500).json({
error: {
message: err.message,
type: err.name
}
});
}
}
}
export default FolderController;
|
Markdown
|
UTF-8
| 1,648
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<p align="center">
<a href="https://laravel.com" target="_blank"><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></a>
<!-- <a href="https://www.granatum.com.br/financeiro/api/" target="_blank"><span style="background-color:#00579B;"><img src="https://www.granatum.com.br/financeiro/img/logo-granatum-financeiro.png"></span></a>-->
</p>
# Granatum
Laravel Package to access Granatum API
## Requirements
curl extension
## Install
Via composer
``` bash
$ composer require emanuti/granatum
```
Open config/app.php
Add
``` php
Emanuti\Granatum\GranatumServiceProvider::class,
```
inside providers key of array
Add
``` php
'Granatum' => Emanuti\Granatum\Facade::class
```
inside aliases key of array
Run
``` bash
$ php artisan vendor:publish
```
will generate config/granatum.php
## Configuration
Open generated file granatum.php by vendor:publish comand and fill:
env will determine the enviroment that you are
token dev will be used to test and prod, you know :-)
## Usage
Available routes: https://www.granatum.com.br/financeiro/api/
To get a collection related with route
``` php
\Granatum::get('any_route_available');
```
To get an item of collection by id
``` php
\Granatum::get('any_route_available', id);
```
where id will be an integer
To add one item
``` php
\Granatum::post('any_route_available', fields);
```
where fields will be an array
To edit one item
``` php
\Granatum::put('any_route_available', id, fiedls);
```
where fields will be an array and id will be an integer
To delete one item
``` php
\Granatum::delete('any_route_available', id);
```
## License
The MIT License (MIT).
|
Java
|
UTF-8
| 224
| 2.15625
| 2
|
[] |
no_license
|
package uy.proitc.jaxws.server;
import javax.jws.WebService;
@WebService(targetNamespace = "http://jaxws.proitc.uy/wsdl")
public interface Calculator {
int sum(int num1, int num2);
int multiply(int num1, int num2);
}
|
Markdown
|
UTF-8
| 1,414
| 2.59375
| 3
|
[
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
---
title: Global Migrant Stock Chord Diagrams
date: '2020-06-20'
linkTitle: https://guyabel.com/post/global-migrant-stocks/
source: Posts on Guy Abel
description: ' <p>Over the last few months I have been playing around with different
ways of showing changing global bilateral migrant stocks, adapting the the code
from the plots for region to region flows in a recent estimation <a href="https://www.nature.com/articles/s41597-019-0089-3"
target="_blank">paper</a>.</p> <p>The first plot below shows the change over time
in the pattern of global migrant stocks. As with the <a href="http://guyabel.com/post/migrant-stock-chord-digrams"
target="_blank">regional plots</a> in my previous post, the chords in the diagrams
represent the connection between the places ...'
disable_comments: true
---
<p>Over the last few months I have been playing around with different ways of showing changing global bilateral migrant stocks, adapting the the code from the plots for region to region flows in a recent estimation <a href="https://www.nature.com/articles/s41597-019-0089-3" target="_blank">paper</a>.</p> <p>The first plot below shows the change over time in the pattern of global migrant stocks. As with the <a href="http://guyabel.com/post/migrant-stock-chord-digrams" target="_blank">regional plots</a> in my previous post, the chords in the diagrams represent the connection between the places ...
|
Java
|
GB18030
| 647
| 3.5
| 4
|
[] |
no_license
|
package day03;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
* ʹļַıļ
*/
public class FileCopy7 {
public static void main(String[] args) throws IOException {
/**
* ڶȡļַ
*/
FileReader reader=new FileReader("CopeFile5.java");//
/**
* дļַ
*/
FileWriter writer=new FileWriter("Copy_Copy_FileCopy.java");
int c=0;
while((c=reader.read())!=-1){
writer.write(c);
}
reader.close();
writer.close();
}
}
|
Python
|
UTF-8
| 672
| 3.171875
| 3
|
[] |
no_license
|
from collections import defaultdict
class Solution(object):
def findJudge(self, N, trust):
"""
:type N: int
:type trust: List[List[int]]
:rtype: int
"""
if not trust:
return 1 if N == 1 else -1
be_trusted = defaultdict(list)
trusting = set([])
for a, b in trust:
be_trusted[b].append(a)
trusting.add(a)
for judge, others in be_trusted.items():
if judge not in trusting and len(others) == N - 1:
return judge
return -1
sol = Solution()
# N = 2
# trust = [[1,2]]
N = 1
trust = []
print(sol.findJudge(N, trust))
|
Python
|
UTF-8
| 281
| 3.75
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 29:17:00 2020
@author: James
"""
print ("This program converts from miles to kilometers")
name = input("Please enter your name: ")
#print ("Hello " + name + ". Welcome to Python!")
print (f"Hello {name}. Welcome to Python!")
|
JavaScript
|
UTF-8
| 7,070
| 2.640625
| 3
|
[] |
no_license
|
//load iso data from local file
const data = Data;
//firebase config
const firebaseConfig = config;
firebase.initializeApp(firebaseConfig);
const messageAppReference = firebase.database();
//handlebars
let confirmed_source = $('#confirmed').html();
let confirmed_template = Handlebars.compile(confirmed_source);
let none_confirmed_source = $('#none-confirmed').html();
let none_confirmed_template = Handlebars.compile(none_confirmed_source);
let single_message = $('#single-message').html();
let single_message_template = Handlebars.compile(single_message);
const base_url = 'https://api.covid19api.com/summary'
const $country_list_container = $('#confirmed-list-container');
function getAndDisplayData(iso_codes){
$.ajax({
url: base_url,
type: "GET",
success: function(data){
let rawData = data['Countries'];
let confirmed_countries = [];
let no_case_countries = [];
for (let i = rawData.length - 1; i >= 0; i--) {
if (rawData[i]['TotalConfirmed']) {
let country_data = rawData[i]['Country'].replace(/\s+/g, '-');
confirmed_countries.push({
country: rawData[i]['Country'],
confirmed: rawData[i]['TotalConfirmed'],
deaths: rawData[i]['TotalDeaths'],
recovered: rawData[i]['TotalRecovered'],
country_data: country_data,
});
} else {
let country_data = rawData[i]['Country'].replace(/\s+/g, '-');
no_case_countries.push({country: rawData[i]['Country'], country_data: country_data});
}
}
//reverse order of arrays list alphabetically
confirmed_countries.reverse();
no_case_countries.reverse();
$country_list_container.append(confirmed_template({confirmed_countries}));
$country_list_container.append(none_confirmed_template({no_case_countries}));
},
error: function(error){
console.log('API did not send any data');
},
complete: function(){
let $individual_country = $('.individual-country');
let iso_codes = data['iso'];
$individual_country.each(function(index, element){
let $element = $(this);
let $elementName = $element.data('name');
for (let i = iso_codes.length - 1; i >= 0; i--) {
if ($elementName === iso_codes[i]['name']) {
$element.find('img').attr('src', 'https://www.countryflags.io/' + iso_codes[i]['code'] + '/flat/64.png');
}else if ($elementName === 'Cruise-Ship'|| $elementName === 'Diamond-Princess' || $elementName === 'MS-Zaandam' || $elementName === 'Others'){
$element.find('img').attr('src', '../ship.svg').addClass('other-flag');
}
}
});
addEventHandler();
searchCountries();
}
});
};
function searchCountries(){
//get input field set as variable
let userInput = $('#user-input');
userInput.keyup(data, function(){
let $userValue = $(this).val().toLowerCase();
let $allCountries = $('.individual-country');
$allCountries.filter(function(){
$(this).toggle($(this).text().toLowerCase().indexOf($userValue) > -1);
});
});
};
function addEventHandler(){
//get data from country on click and populate #country-status
$('.individual-country').on('click', function(e){
e.preventDefault();
let $this = $(this);
let $header = $('.individual-name');
$('.individual-name').html($this.data('name'));
$('.messages-for-country').html('Messages for ' + $this.data('name'));
$('.confirmed-number').html($this.data('confirmed'));
$('.deaths-number').html($this.data('deaths'));
$('.recovered-number').html($this.data('recovered'));
getCountryMessages($this.data('name').toLowerCase());
});
};
function saveMessage(){
let country = $('.individual-name').html().toLowerCase();
if ($('#message').val()) {
//variable for input data
let message = $('#message').val();
let id = messageAppReference.ref().child('messages/' + country).push().key;
let updates = {};
updates['messages/' + country + '/' + id] = {'message': message};
messageAppReference.ref().update(updates);
//clear out input field
$('#message').val('');
//save id to localStorage
let visitorLocalStorage = window.localStorage;
visitorLocalStorage.setItem('message:' + id, id);
} else {
alert('Must enter a value to send message.');
}
};
function getCountryMessages(country) {
// retrieve messages data when .on() initially executes and when its data updates
messageAppReference.ref('messages/' + country).on('value', function (results) {
const $messageList = $('#country-messages');
$messageList.empty();
const allMessages = results.val();
// iterate through results coming from database call; messages
for (const msg in allMessages) {
const message = allMessages[msg].message;
const id = msg;
//use handlebars template
$messageList.append(single_message_template({message, id, country}));
}
$('.fa-trash').on('click', function(){
let $this = $(this).closest('.individual-msg');
deleteCountryMessage($this);
});
$('.fa-pencil').on('click', function(){
let $this = $(this).closest('.individual-msg');
editCountryMessage($this);
});
})
};
function deleteCountryMessage(elem){
let id = elem.data('id');
let country = elem.data('msg-country');
//check localstorage for id
let post_author = window.localStorage.getItem('message:' + id);
if (post_author) {
// find message whose objectId is equal to the id we're searching with
messageAppReference.ref('messages/' + country + '/' + id).remove();
}else{
alert('You are not the author, you cannot delete.');
}
};
function editCountryMessage(elem){
let id = elem.data('id');
let country = elem.data('msg-country');
//check localstorage for id
let post_author = window.localStorage.getItem('message:' + id);
if (post_author) {
let currentMessage = elem.text().trim();
// find message whose objectId is equal to the id we're searching with
const messageReference = messageAppReference.ref('messages/' + country + '/' + id);
//set modal input to current message
$('#edit-message').val(currentMessage);
//show modal
$('#virusModal').modal('show');
$('#cancel-edit').on('click', function(e){
messageReference.update({'message': currentMessage});
});
$('#save-edit').on('click', function(e){
e.preventDefault();
//capture new message
let newMessage = $('#edit-message').val();
// update message in db
messageReference.update({'message': newMessage});
//close modal
$('#virusModal').modal('hide');
});
}else{
alert('You are not the author, you cannot edit.');
}
};
$(function(){
getAndDisplayData();
//save message when "send love" clicked
$('#send-love').on('click', function(e){
e.preventDefault();
saveMessage();
});
});
|
C#
|
UTF-8
| 2,534
| 4.125
| 4
|
[] |
no_license
|
using System;
namespace cSharpProjectEulerSolutions
{
public partial class ProjectEuler
{
/* *************************************10001st prime**************************************** */
/*By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?*/
/**************************************** Solution ***************************************** */
/*Solution 1 : loop through integer numbers to find prime numbers */
/*Solution 2 : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes */
public void p7()
{
Console.WriteLine("ProjectEuler Problem #7:");
/* solution 1 : easy solution */
int count=0;
int number=1;
while(count<10001){
number++;
if(isPrime(number)) // call isPrime(n) to find out whether n is prime or not?
{
count++;
}
}
Console.WriteLine("Solution One- Answer for the Problem #7 is : {0}",number);
/* solution 2 : Sieve of Eratosthenes */
int n = 10000000;
bool[] primeNumbers = new bool[n];
for (int i = 2; i < n; i++)
{
primeNumbers[i] = true;
}
for (int i = 2; i < n; i++)
{
if (primeNumbers[i])
{
for (int j = 2; (i * j) < n; j++)
{
primeNumbers[i * j] = false; // all i * j are not prime. just i is prime.
}
}
}
int index =1;
count=0;
while(count<10001)
{
index++;
if(primeNumbers[index]){count++;}
}
Console.WriteLine("Solution Two- Answer for the Problem #7 is : {0}",index);
}
/* Method isPrime to detrmine whether argument n is prime numebr or not by returning true or false */
public bool isPrime(int n)
{
bool isPrime = true; //the flag for checking prime factor
double len=Math.Sqrt(n);
for (int i = 2; i <= len; i++)
{
if (n % i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
}
}
|
Markdown
|
UTF-8
| 1,097
| 2.59375
| 3
|
[] |
no_license
|
---
link: http://pogue.blogs.nytimes.com/2011/04/14/the-tragic-death-of-the-flip/
date: 2011-04-15 13:27 UTC
# published: false
published: true
title: David Pogue on the Curious Death of The Flip
tags: []
---
Sorry to keep flooding the channel with Flip stuff, but it utterly bums me out since the Flip was a great example of accessible and culturally transformative technology. I remember when it was only sold at CVS as a "disposable" and I had cable access producers walk up to me and say "I just got this camera for $20, can you help me hack it?". At conferences it was like Bam! everyone who was carrying a GL2 the previous year was now jamming a Flip in your face---not to mention many more people who never carried a camera unless they were "on a shoot". People who are still carrying their Canon A40 still camera (the 8 year old one that takes 4 AA batteries), and would never buy a smartphone (because they couldn't/wouldn't do a contract) were dropping money on these things like crazy. <br><br>I sure hope Cisco is wicked smart about this decision, because otherwise they're only assholes.
|
PHP
|
UTF-8
| 1,699
| 2.75
| 3
|
[] |
no_license
|
<?php
namespace Core;
use Core\Application;
/**
* @package Core\Controller
*/
class Controller extends Application
{
/**
* @var string
*/
protected $controller;
/**
* @var string
*/
protected $action;
/**
* @var string
*/
public $view; // do may protected
/**
* @var object
*/
public $request;
/**
* Constructor
* @param string $controller
* @param string $action
* @return void
*/
public function __construct($controller, $action)
{
parent::__construct(); // Application constructor
$this->controller = $controller;
$this->action = $action;
$this->request = new Input();
$this->view = new View();
}
/**
* Load model
* @param string $model
* @return void
*/
protected function loadModel($model)
{
$modelPath = 'App\\Models\\' . $model;
if(class_exists($modelPath))
{
$this->{$model.'Model'} = new $modelPath();
}
}
/**
* Return json data
* @param array $response
* @return string
*/
public function jsonResponse($response)
{
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
http_response_code(200);
echo json_encode($response);
exit();
}
}
|
SQL
|
UTF-8
| 945
| 3.234375
| 3
|
[] |
no_license
|
CREATE database yelp;
CREATE TABLE YELP_ADDRESS
(Restaurant_id BIGINT(20) NOT NULL auto_increment,
comp_name VARCHAR(30),
street VARCHAR(30),
postalcode VARCHAR(10),
city VARCHAR(20),
PRIMARY KEY(Restaurant_id),
rating VARCHAR(20),
segment VARCHAR(20),
reviews varchar(60));
CREATE TABLE YELP_REVIEWS
(Review_id BIGINT(20) NOT NULL auto_increment,
Restaurant_id BIGINT(20),
review VARCHAR(8000),
rating VARCHAR(10),
PRIMARY KEY(Review_id),
FOREIGN KEY (Restaurant_id) REFERENCES YELP_ADDRESS(Restaurant_id));
CREATE TABLE YELP_PIC
(pic_id BIGINT(20) NOT NULL auto_increment,
Review_id BIGINT(20),
pic_url VARCHAR(150),
PRIMARY KEY(pic_id),
FOREIGN KEY (Review_id) REFERENCES YELP_REVIEWS(Review_id));
CREATE TABLE YELP_USER
(user_id BIGINT(20) NOT NULL auto_increment,
Review_id BIGINT(20),
name VARCHAR(30),
reviews VARCHAR(20),
PRIMARY KEY(user_id),
FOREIGN KEY (Review_id) REFERENCES YELP_REVIEWS(Review_id));
|
Markdown
|
UTF-8
| 6,163
| 3.265625
| 3
|
[] |
no_license
|
---
title: Rxjava学习:谈谈Rxjava的使用
date: 2016-08-25 17:27:24
categories: Rxjava学习
tags:
---

### 前言
在 [Rxjava学习:初识Rxjava](http://www.jianshu.com/p/264a1322669a) 一文中,我们对Rxjava的几个基本概念做了介绍,今天就来谈谈对Rxjava的使用。
<!-- more-->
### Rxjava的具体使用
下面还是从几个基本概念开始入手:
#### 创建Observer
作为Rxjava处理数据的最终出口,首先我们需要对其进行实现。
```
Observer<String> observer = new Observer<String>() {
@Override
public void onNext(String s) {
Log.d(tag, "Item: " + s);
}
@Override
public void onCompleted() {
Log.d(tag, "Completed!");
}
@Override
public void onError(Throwable e) {
Log.d(tag, "Error!");
}
};
```
除了 Observer 接口之外,RxJava 还提供了一个实现了 Observer 的抽象类:Subscriber。实际上在Observer接口的使用过程中,也是将其转换成Subscriber 来使用。
下面我们来看一下订阅方法的源码实现:
```
public final Subscription subscribe(final Observer<? super T> observer) {
if (observer instanceof Subscriber) {
return subscribe((Subscriber<? super T>)observer);
}
if (observer == null) {
throw new NullPointerException("observer is null");
}
return subscribe(new ObserverSubscriber<T>(observer));
}
```
可以看到 如果是 **Subscriber** 将直接被使用,如果是**observer**将被转换为 **ObserverSubscriber** 来使用。这里提到了** ObserverSubscriber **类 我们再来看一下 其源码,就会很清晰的理解这个过程了:
```
public final class ObserverSubscriber<T> extends Subscriber<T> {
final Observer<? super T> observer;
public ObserverSubscriber(Observer<? super T> observer) {
this.observer = observer;
}
@Override
public void onNext(T t) {
observer.onNext(t);
}
@Override
public void onError(Throwable e) {
observer.onError(e);
}
@Override
public void onCompleted() {
observer.onCompleted();
}
}
```
当然Subscriber 对 Observer 接口也进行了一些扩展。 下面提一下 Subscriber 与 Observer 使用上的不同:
- onStart(): Subscriber 对外提供了onStart 方法用于实现,onStart 在Subscriber中是一个空方法,用户可以选择性实现。**会在整个订阅过程开始之前被调用,与Subscribe()方法发生在同一线程,可以做一些 比如:数据的初始化 之类的操作,但不适合做对线程有具体要求的工作。例如:初始化UI界面,必须发生在主线程。**
- unsubscribe(): Subscriber 同时实现了另一个接口 Subscription ,Subscription 接口只提供了两个方法:
```
public interface Subscription {
void unsubscribe();
boolean isUnsubscribed();
}
```
Subscriber 对这两个方法分别做了实现,isUnsubscribed() 用于判断Subscriber 是否已经订阅 ,而 unsubscribe() 方法用于 取消订阅。在 subscribe() 之后, Observable 会持有 Subscriber 的引用,这个引用如果不能及时被释放,将有内存泄露的风险。所以最好保持一个原则:要在不再使用的时候尽快在合适的地方(例如 onPause() onStop() 等方法中)调用 unsubscribe() 来解除引用关系,以避免内存泄露的发生。
#### 创建 Observable
Observable 提供了大量的方法来进行 数据变换,下面我们借用 [Rxjava学习:初识Rxjava](http://www.jianshu.com/p/264a1322669a) 一文中的例子来对其各个API进行理解:
```
Observable.from(folders)
.flatMap(new Func1<File, Observable<File>>() {
@Override
public Observable<File> call(File file) {
return Observable.from(file.listFiles());
}
})
.filter(new Func1<File, Boolean>() {
@Override
public Boolean call(File file) {
return file.getName().endsWith(".png");
}
})
.map(new Func1<File, Bitmap>() {
@Override
public Bitmap call(File file) {
return getBitmapFromFile(file);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Bitmap>() {
@Override
public void call(Bitmap bitmap) {
imageCollectorView.addImage(bitmap);
}
});
```
- flatMap() : 通过传入的对象,根据需求 ,创建新的Observable 对象,并代替现有的Observable对象完成剩下的所要执行的方法。
- map() : 将传入的对象转换成另一个对象,是可以被直接发送到了Subscriber 的回调方法中使用的。如同上面示例中那样。
- filter() : 过滤筛选。 通过事件方法进行筛选,将符合要求的数据传递到下一个事件。例如示例中:符合**file.getName().endsWith(".png”)** 要求的数据才会传递。
#### 调用 subscribe() 进行订阅
创建了 Observable 和 Observer 之后,再用 subscribe() 方法将它们联结起来,整条链子就可以工作了。代码形式很简单:
```
observable.subscribe(observer);
```
同时subscribe()方法也提供了其他的重载以实现不完整定义的回调。
```
// 自动创建 Subscriber ,并使用 onNext 来定义 onNext()
subscribe(final Action1<? super T> onNext)
// 自动创建 Subscriber ,并使用 onNextAction 和 onErrorAction 来定义 onNext() 和 onError()
subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError)
// 自动创建 Subscriber ,并使用 onNextAction、 onErrorAction 和 onCompletedAction 来定义 onNext()、 onError() 和 onCompleted()
subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onCompleted)
```
### 总结:
讲到现在,对Rxjava的使用也有了清晰的了解,在这里并没有提到Scheduler的使用,我觉得Scheduler 对于Rxjava是十分重要的一部分,我打算在下一篇中做详细的介绍,并对Observable其他重要的API方法进行介绍。
|
Python
|
UTF-8
| 325
| 3.046875
| 3
|
[] |
no_license
|
import math
import time
import copy
start = time.clock()
number = 1
while 1:
for jump in range(1, 7):
if sorted(str(number)) != sorted(str(jump*number)):
number += 1
break
elif jump == 6:
print(number)
print(time.clock() - start)
quit()
|
Python
|
UTF-8
| 20,815
| 3.140625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# This Python file uses the following encoding: utf-8
from unittest import TestCase
from galactic.context.memory import *
class MemoryContextTest(TestCase):
def test___init__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
str(context),
"{'population': [], 'model': {'mybool': <class 'bool'>, 'myint': <class 'int'>}}",
"The context has not been correctly initialized"
)
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
str(context.population),
"['0', '1']",
"The context has not been correctly initialized"
)
self.assertEqual(
str(context.model),
"{'mybool': <class 'bool'>, 'myint': <class 'int'>}",
"The context has not been correctly initialized"
)
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals={'0': {'mybool': True}, '1': {'myint': 1}}
)
self.assertEqual(
str(context.population['0']),
"{'mybool': True, 'myint': 0}",
"The context has not been correctly initialized"
)
self.assertEqual(
str(context.population['1']),
"{'mybool': False, 'myint': 1}",
"The context has not been correctly initialized"
)
with self.assertRaises(TypeError):
_ = MemoryContext(definition='bad value')
with self.assertRaises(TypeError):
_ = MemoryContext(individuals=1000)
def test_population(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertTrue(
isinstance(context.population, Population),
"The property population is instance of Population"
)
def test_model(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertTrue(
isinstance(context.model, Model),
"The property model is instance of Model"
)
def test___contains__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertTrue(
context.population['0'] in context,
"The first individual of the context is in the context"
)
self.assertTrue(
context.model['mybool'] in context,
"The first attribute of the context is in the context"
)
other = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertFalse(
other.population['0'] in context,
"An unknown element is not in the context"
)
def test___bool__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertTrue(
context,
"The context is not empty"
)
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertFalse(
context,
"The context is empty"
)
context = MemoryContext(
individuals=['0', '1']
)
self.assertFalse(
context,
"The context is empty"
)
def test___str__(self):
context = MemoryContext(
definition={'mybool': bool},
individuals=['0']
)
self.assertEqual(
str(context),
"{'population': ['0'], 'model': {'mybool': <class 'bool'>}}",
"The string representation of this context is not correct"
)
class MemoryPopulationTest(TestCase):
def test_context(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
context.population.context,
context,
"The context of the population must be the original context"
)
def test_model(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
context.population.model,
context.model,
"The model of the population must be the original model"
)
def test___getitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
str(context.population['0']),
"{'mybool': False, 'myint': 0}",
"The textual representation of the first individual is not correct"
)
def test___setitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
context.population['0'] = {}
self.assertEqual(
str(context.population['0']),
"{'mybool': False, 'myint': 0}",
"The population is not correct"
)
context.population['0'] = {'mybool': True}
self.assertEqual(
str(context.population['0']),
"{'mybool': True, 'myint': 0}",
"The population is not correct"
)
with self.assertRaises(KeyError):
context.population['0'] = {'abc': 1}
def test___delitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
del context.population['0']
self.assertFalse(
bool(context.population),
"The population must be empty"
)
def test___len__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
len(context.population),
2,
"The length of the population is not correct"
)
def test___bool__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertFalse(
bool(context.population),
"The population must be empty"
)
context.population['0'] = {}
self.assertTrue(
bool(context.population),
"The population must be not empty"
)
def test___iter__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
for identifier, individual in context.population.items():
self.assertTrue(
isinstance(individual, Individual),
"Each individual must be an instance of the Individual class"
)
self.assertTrue(
isinstance(identifier, str),
"Each identifier must be a str"
)
def test___str__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
str(context.population),
"['0', '1']",
"The string representation of the population is not correct"
)
class MemoryModelTest(TestCase):
def test_context(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
context.model.context,
context,
"The context of the model must be the original context"
)
def test_population(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
context.model.population,
context.population,
"The population of the model must be the original population"
)
def test___getitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
str(context.model['mybool']),
"{'name': 'mybool', 'type': <class 'bool'>}",
"The attribute mybool is not correct"
)
def test___setitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals={'0': {'mybool': True}, '1': {'myint': 1}}
)
context.model['mybool'] = bool
self.assertEqual(
{identifier: str(individual) for identifier, individual in context.population.items()},
{'0': "{'mybool': True, 'myint': 0}", '1': "{'mybool': False, 'myint': 1}"},
"The individuals must remain unchanged"
)
context.model['mybool'] = int
self.assertEqual(
{identifier: str(individual) for identifier, individual in context.population.items()},
{'0': "{'mybool': 1, 'myint': 0}", '1': "{'mybool': 0, 'myint': 1}"},
"The individuals must change"
)
context.model['mybool'] = list
self.assertEqual(
{identifier: str(individual) for identifier, individual in context.population.items()},
{'0': "{'mybool': [], 'myint': 0}", '1': "{'mybool': [], 'myint': 1}"},
"The individuals must change"
)
del context.model['myint']
context.model['myint2'] = int
self.assertEqual(
{identifier: str(individual) for identifier, individual in context.population.items()},
{'0': "{'mybool': [], 'myint2': 0}", '1': "{'mybool': [], 'myint2': 0}"},
"The individuals must change"
)
def test___delitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
del context.model['mybool']
self.assertEqual(
str(context),
"{'population': ['0', '1'], 'model': {'myint': <class 'int'>}}",
"The context is not correct"
)
self.assertEqual(
str(context.population['0']),
"{'myint': 0}",
"The context is not correct"
)
def test___len__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
len(context.model),
2,
"The length of the model is not correct"
)
def test___bool__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertTrue(
bool(context.model),
"The bool representation of the model is not correct"
)
def test___iter__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
list(iter(context.model)),
['mybool', 'myint'],
"The iteration over the model is not correct"
)
def test___str__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int}
)
self.assertEqual(
str(context.model),
"{'mybool': <class 'bool'>, 'myint': <class 'int'>}",
"The string representation of the model must be correct"
)
class MemoryIndividualTest(TestCase):
def test_identifier(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0'].identifier,
'0',
"The identifier must be '0'"
)
def test_population(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0'].population,
context.population,
"The population of the individual named '0' must be the context population"
)
def test_context(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0'].context,
context,
"The context of the individual named '0' must be the context"
)
def test_model(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0'].model,
context.model,
"The model of the individual named '0' must be the context model"
)
def test_value(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0'].value(context.model['mybool']),
bool(),
"The value 'mybool' of the individual named '0' must be the False"
)
self.assertEqual(
context.population['0'].value(context.model['myint']),
int(),
"The value 'myint' of the individual named '0' must be the 0"
)
other = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
with self.assertRaises(ValueError):
_ = context.population['0'].value(other.model['myint'])
def test___setitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
context.population['0']['mybool'] = True
context.population['0']['myint'] = 1
self.assertEqual(
str(context.population['0']),
"{'mybool': True, 'myint': 1}",
"The textual representation of the first individual is not correct"
)
context.population['1']['mybool'] = True
context.population['1']['myint'] = 2
self.assertEqual(
str(context.population['1']),
"{'mybool': True, 'myint': 2}",
"The textual representation of the first individual is not correct"
)
with self.assertRaises(KeyError):
context.population['0']['unknown'] = 1
with self.assertRaises(ValueError):
context.population['0']['myint'] = 'abc'
def test___getitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.population['0']['mybool'],
bool(),
"The first value is not correct"
)
self.assertEqual(
context.population['0']['myint'],
int(),
"The second value is not correct"
)
with self.assertRaises(KeyError):
_ = context.population['0']['unknown']
def test___delitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
with self.assertRaises(ValueError):
del context.population['0']['myint']
def test___len__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
len(context.population['0']),
2,
"The length of the individual is not correct"
)
def test___eq__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertTrue(
context.population['0'] == context.population['0'],
"The individual is equal to itself"
)
self.assertFalse(
context.population['0'] == context.population['1'],
"Two different individuals are unequal"
)
other = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertFalse(
context.population['0'] == other.population['0'],
"Two individuals from two different contexts are unequal"
)
def test___iter__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
list(iter(context.population['0'])),
['mybool', 'myint'],
"The iteration over the individual is not correct"
)
def test___str__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
str(context.population['0']),
"{'mybool': False, 'myint': 0}",
"The string representation of the individual is not correct"
)
class MemoryAttributeTest(TestCase):
def test_name(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.model['mybool'].name,
'mybool',
"The name must be 'mybool'"
)
def test_type(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0']
)
self.assertEqual(
context.model['mybool'].type,
bool,
"The type must be bool"
)
def test_value(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
context.model['mybool'].value(context.population['0']),
context.population['0'].value(context.model['mybool']),
"The value must be correct"
)
def test___getitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
context.model['mybool']['0'],
context.population['0']['mybool'],
"The value must be correct"
)
def test___setitem__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
context.model['mybool']['0'] = True
context.model['myint']['0'] = 1
self.assertEqual(
str(context.population['0']),
"{'mybool': True, 'myint': 1}",
"The textual representation of the first individual is not correct"
)
context.model['mybool']['1'] = True
context.model['myint']['1'] = 2
self.assertEqual(
str(context.population['1']),
"{'mybool': True, 'myint': 2}",
"The textual representation of the first individual is not correct"
)
with self.assertRaises(KeyError):
context.model['mybool']['unknown'] = 1
with self.assertRaises(ValueError):
context.model['myint']['0'] = 'abc'
def test___len__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
len(context.model['mybool']),
2,
"The length must be correct"
)
def test___eq__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertTrue(
context.model['mybool'] == context.model['mybool'],
"The equality must be correct"
)
def test___iter__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
list(iter(context.model['mybool'])),
['0', '1'],
"The iter must be correct"
)
def test___str__(self):
context = MemoryContext(
definition={'mybool': bool, 'myint': int},
individuals=['0', '1']
)
self.assertEqual(
str(context.model['mybool']),
"{'name': 'mybool', 'type': <class 'bool'>}",
"The iter must be correct"
)
|
Java
|
UTF-8
| 1,815
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package cn.mapway.ui.client.mvc;
import com.google.gwt.user.client.ui.Widget;
/**
* 系统中模块的定义接口,根据设计原则,可以将代码划分为 系统/模块/子模块/操作 四个界别
* 这个接口定义了如果要满足 模块和子模块的功能必须要实现的接口
*
* @author zhangjianshe
*/
public interface IModule {
/**
* 初始化模块.
*
* @param parentModule the parent module
* @param parameters the parameters
* @return true 表示可以初始化本模块,false表示已经初始化子模块了,本模块可以不用初始化
*/
boolean initialize(IModule parentModule, ModuleParameter parameters);
/**
* 卸载模块.
*/
void unInitialize();
/**
* 返回模块的Widget.
*
* @return the root widget
*/
Widget getRootWidget();
/**
* 用于模块向父模块注册工具栏按钮
*
* @param tools the tools
* @return the boolean
*/
boolean updateTools(Widget... tools);
/**
* 用于模块向父模块注册工具栏按钮
*
* @param tools the tools
* @return the boolean
*/
boolean appendTools(Widget tools);
/**
* 用于模块向父模块注册工具栏按钮
*
* @param tools the tools
* @return the boolean
*/
boolean appendTools(Widget[] tools);
/**
* 获取模块信息
*
* @return module info
*/
ModuleInfo getModuleInfo();
/**
* 获取模块的父模块
*
* @return parent module
*/
IModule getParentModule();
/**
* 获取模块参数.
*
* @return parameters
*/
ModuleParameter getParameters();
}
|
JavaScript
|
UTF-8
| 449
| 4.28125
| 4
|
[] |
no_license
|
// Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it.
//For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24.
// Entry #004 05042019
'use strict'
var input = 4;
function FirstFactorial(input, output = 1) {
if (input == 0) {
return output;
} else {
output *= input--;
return FirstFactorial(input, output);
}
}
console.log(FirstFactorial(input));
|
PHP
|
UTF-8
| 778
| 2.609375
| 3
|
[] |
no_license
|
<?php
session_start ();
require_once 'class/User.class.php';
$user = new User();
$products = $user->viewProducts();
//$name,$description, $price , $supplier_id, $category_id, $image
?>
<?php include ("header.php");?>
<h3>Products</h3><a href="productAdd.php">Add Product</a>
<table class="table">
<tr>
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Image</th>
</tr>
<?php
foreach ($products as $product){
?>
<tr>
<td><?php echo $product[0];?></td>
<td><?php echo $product[1];?></td>
<td><?php echo $product[2];?></td>
<td><?php echo $product[3];?></td>
<td><img src="images/<?php echo $product[6] ?>" style="width: 100px;height: 100px;"></td>
</tr>
<?php
}
?>
</table>
<?php include ("footer.php");?>
|
Java
|
UTF-8
| 3,293
| 2.03125
| 2
|
[] |
no_license
|
package com.lavector.collector.crawler.project.weibo.weiboStar.page;
import com.jayway.jsonpath.JsonPath;
import com.lavector.collector.crawler.base.PageParse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Json;
import us.codecraft.webmagic.selector.Selectable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class WeiboSearchPage implements PageParse {
private Logger logger = LoggerFactory.getLogger(WeiboSearchPage.class);
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private String url = "https://weibo.com/aj/v6/comment/big?id=";
private String endUrl = "&page=1";
@Override
public boolean handleUrl(String url) {
return url.contains("https://s.taobao.com/search");
}
@Override
public Result parse(Page page) {
Result result = Result.get();
logger.info("获取到列表页面");
Person person = (Person) page.getRequest().getExtra("person");
Html html = page.getHtml();
List<String> scripts = html.xpath("script/html()").all();
List<Request> requests = new ArrayList<>();
Optional<String> optionalS = scripts.stream().filter(s -> s.contains("\"pl.content.homeFeed.index\",\"domid\":\"Pl_Official_MyProfileFeed")).findFirst();
optionalS.ifPresent(s -> {
String json = new Json(s).regex("FM.view\\((.*)\\)").get();
String htmlStr = JsonPath.read(json, "$.html");
if (htmlStr != null) {
Html newHtml = new Html(htmlStr);
List<Selectable> nodes = newHtml.xpath("//div[@action-type='feed_list_item']").nodes();
if (nodes != null && nodes.size() > 5) {
for (int i = 0; i < 5; i++) {
Request newRequest = new Request();
String mid = nodes.get(i).xpath("//div[@action-type='feed_list_item']/@mid").get();
person.setId(mid);
newRequest.setUrl(url + mid + endUrl)
.putExtra("person", person);
requests.add(newRequest);
}
}else {
for (int i = 0; i < nodes.size(); i++) {
Request newRequest = new Request();
String mid = nodes.get(i).xpath("//div[@action-type='feed_list_item']/@mid").get();
person.setId(mid);
newRequest.setUrl(url + mid + endUrl)
.putExtra("person", person);
requests.add(newRequest);
}
}
}
});
result.setRequests(requests);
page.setSkip(true);
return result;
}
@Override
public String pageName() {
return null;
}
@Override
public <T> T getRequestExtra(String key, Page page) {
return null;
}
@Override
public boolean handleRequest(Request request) {
return false;
}
}
|
Java
|
UTF-8
| 139
| 1.703125
| 2
|
[] |
no_license
|
package dao;
import java.util.List;
import domen.Predstave;
public interface DaoPredstave {
public List<Predstave>vratiPredstave ();
}
|
Java
|
UTF-8
| 4,244
| 2.390625
| 2
|
[] |
no_license
|
package com.xedu.auth;
import com.xedu.framework.client.XeduServiceList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
/**
* @Author: Xin Wang.
* @Date:Created in 2020/6/6 16:45.
* @Description: 测试登录申请令牌的流程
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestLogin {
/**
* 远程调用客户端
*/
@Autowired
RestTemplate restTemplate;
/**
* 本地负载均衡服务端,可以用来远程调用 eureka
*/
@Autowired
LoadBalancerClient loadBalancerClient;
/**
* 测试登录远程调用 spring security 并获取令牌的整个流程,这里需要进行远程调用
*/
@Test
public void testLogin(){
// 从 eureka 中获取认证服务的地址(因为Spring security在认证服务中)
// 从 eureka 中获取认证服务的一个实例对象
ServiceInstance serviceInstance = loadBalancerClient.choose(XeduServiceList.XEDU_SERVICE_UCENTER_AUTH);
// 获取远程服务的地址
URI uri = serviceInstance.getUri();
// 拼接远程调用申请令牌的地址:http://localhost:40400/auth/oauth/token
String auth_url = uri + "/auth/oauth/token";
// 定义header
LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();
// 向header中传入所需的数据
String httpBasic = getHttpBasic("XcWebApp", "XcWebApp");
header.add("Authorization",httpBasic);
// 定义body
LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
// 向body中传入所需的数据
body.add("grant_type","password");
body.add("username","itcast");
body.add("password","12322");
// 构建 http 请求对象
HttpEntity<MultiValueMap<String,String>> multiValueMapHttpEntity = new HttpEntity<>(body, header);
// 设置 resttemplate 远程调用的时候,对400和401不让报错,正常返回数据
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// 设置过滤400和401不让报错,正常返回数据
if(response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401){
super.handleError(response);
}
}
});
// 执行远程客户端网络调用获取响应对象
// String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,Class<T> responseType, Object... uriVariables
ResponseEntity<Map> exchange = restTemplate.exchange(auth_url, HttpMethod.POST, multiValueMapHttpEntity, Map.class);
// 获取申请的令牌信息
Map token_body = exchange.getBody();
System.out.println(token_body);
}
/**
* 将用户的账号和密码拼装进行base64加密
* @param clientId
* @param clientSecret
* @return
*/
private String getHttpBasic(String clientId, String clientSecret){
// 构建账号和密码的串
String result = clientId + ":" + clientSecret;
// 对串进行base64编码
byte[] encode = Base64Utils.encode(result.getBytes());
// 将结果拼装为指定的样式返回
return "Basic " + new String(encode);
}
}
|
C#
|
UTF-8
| 1,674
| 2.9375
| 3
|
[] |
no_license
|
namespace PrezzieWithDB.Migrations
{
using PrezzieWithDB.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<PrezzieWithDB.DAL.PrezzieContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(PrezzieWithDB.DAL.PrezzieContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
List<Rating> ratings = new List<Rating>();
ratings.Add(new Rating()
{
ratingValue = 1,
ratingValueDescription = "bad"
});
ratings.Add(new Rating()
{
ratingValue = 2,
ratingValueDescription = "poor"
});
ratings.Add(new Rating()
{
ratingValue = 3,
ratingValueDescription = "okay"
});
ratings.Add(new Rating()
{
ratingValue = 4,
ratingValueDescription = "good"
});
ratings.Add(new Rating()
{
ratingValue = 5,
ratingValueDescription = "super"
});
foreach (Rating rating in ratings)
context.ratings.Add(rating);
base.Seed(context);
}
}
}
|
C
|
UTF-8
| 1,298
| 3.0625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const unsigned int max_column = 78;
static const unsigned int tab_size = 8;
size_t fsize(FILE *fd) {
fseek(fd, 0, SEEK_END);
size_t size = (size_t)ftell(fd); // warning ftell return signed long
fseek(fd, 0, SEEK_SET);
return size;
}
int main(int argc, char **argv) {
unsigned char c = 0;
unsigned int column = 0;
unsigned int i = 0;
size_t count = 0;
size_t size = 0;
char aux_char;
FILE *fp;
char *name;
if (argc != 2) {
printf("Usage: bin2c file\n");
exit(1);
}
fp = fopen(argv[1], "rb");
if (!fp) {
printf("Cannot open %s", argv[1]);
exit(1);
}
size = fsize(fp);
name = basename(argv[1]);
i = sizeof(name);
while (i--) {
aux_char = name[i];
if (aux_char == '.') {
name[i] = '_';
}
}
printf("static const size_t %s_size = %lu;\n", name, size);
printf("static const unsigned char %s_data[] = {\n\t", name);
while (count < size) {
count++;
c = (unsigned char)getc(fp);
column += 6;
if (column >= max_column) {
printf("\n\t");
column = tab_size;
}
if (count == size) {
printf("0x%02X", c);
continue;
}
printf("0x%02X, ", c);
}
printf("\n};\n");
return 0;
}
|
Java
|
UTF-8
| 4,652
| 3.296875
| 3
|
[] |
no_license
|
package chess.pieces;
import chess.Board;
import chess.Move;
public class Pawn extends Piece {
private boolean has_moved;
private boolean isFirstMove;
public Pawn(int x, int y, boolean is_white, String file_path, Board board)
{
super(x,y,is_white,file_path, board, 'p', "\u2659", "\u265F");
has_moved = false;
isFirstMove = false;
}
public void setHasMoved(boolean has_moved)
{
this.has_moved = has_moved;
}
public boolean getHasMoved()
{
return has_moved;
}
public boolean getIsFirstMove() {
return isFirstMove;
}
public void setIsFirstMove(boolean firstMove) {
isFirstMove = firstMove;
}
@Override
public boolean canMove(int destination_x, int destination_y)
{
Piece possiblepiece = board.getPiece(destination_x,destination_y);
//Check if the move is backwards where it won't let it move.
if (board.getIsWhitePerspective()) {
if (this.isWhite() && this.getY() < destination_y) {
return false;
} else if (this.isBlack() && this.getY() > destination_y) {
return false;
}
}else{
if (this.isWhite() && this.getY() > destination_y) {
return false;
} else if (this.isBlack() && this.getY() < destination_y) {
return false;
}
}
//checks if there is a piece in front.
if(this.getX()==destination_x){
if(this.isWhite()){
Piece frontwhite = board.getIsWhitePerspective() ? board.getPiece(this.getX(), this.getY()-1) : board.getPiece(this.getX(), this.getY()+1);
if(frontwhite!=null){
return false;
}
} else if(this.isBlack()){
Piece frontblack = board.getIsWhitePerspective() ? board.getPiece(this.getX(), this.getY()+1) : board.getPiece(this.getX(), this.getY()-1);
if(frontblack!=null){
return false;
}
}
//Pawn movement where it only allows the two square movement at the start and also checks if there is a piece two squares infront.
if(Math.abs(destination_y-this.getY())>2){
return false;
} else if(Math.abs(destination_y-this.getY())==2){
if(this.has_moved){
return false;
}
if(this.isWhite()){
Piece frontwhite1 = board.getIsWhitePerspective() ? board.getPiece(this.getX(), this.getY()-2) : board.getPiece(this.getX(), this.getY()+2);
if(frontwhite1!=null){
return false;
}
} else if (this.isBlack()){
Piece frontblack1= board.getIsWhitePerspective() ? board.getPiece(this.getX(), this.getY()+2) : board.getPiece(this.getX(), this.getY()+2);
if(frontblack1!=null){
return false;
}
}
}
}else{
//Taking A piece.
if(Math.abs(destination_x - this.getX())!= 1 || Math.abs(destination_y-this.getY())!=1){
return false;
}
//en passant capture
if (!board.Moves.isEmpty()) {
if ((this.getY() == 3 || this.getY() == 4) && destination_y != 3 && destination_y != 4) {
Move lastMoved = board.Moves.get(board.Moves.size() - 1);
Piece movedPiece = lastMoved.getMovedPiece();
if (lastMoved.isEnPassant(board, lastMoved) && movedPiece.isWhite() != this.isWhite()) {
if (lastMoved.getFinalSpot().getY() - lastMoved.getInitialSpot().getY() > 0) {
return (destination_y == lastMoved.getFinalSpot().getY() - 1 && destination_x == movedPiece.getX());
} else {
return (destination_y == lastMoved.getFinalSpot().getY() + 1 && destination_x == movedPiece.getX());
}
}
}
}
if(this.isWhite()){
if((possiblepiece == null) || possiblepiece.isWhite()){
return false;
}
}
if(this.isBlack()){
if(possiblepiece == null || possiblepiece.isBlack()){
return false;
}
}
}
return canMoveChecked(destination_x, destination_y);
}
}
|
Python
|
UTF-8
| 4,808
| 2.796875
| 3
|
[] |
no_license
|
import pygame
import sys
import pygame.sprite as sprite
import time
import random
pygame.init()
pygame.display.set_caption("Uni Mario")
p_x = 100
p_y = 350
width = 40
height = 60
vel = 5
left=False
right=False
walk_count = 0
walkRight = []
walkLeft = []
myfont = pygame.font.SysFont("monospace", 25)
screen_over = pygame.font.SysFont("monospace", 100)
hit_count = 0
theClock = pygame.time.Clock()
background_image = pygame.image.load('Sprites/bg2.png')
background_size = background_image.get_size()
background_rect = background_image.get_rect()
sw = 840
sh = 464
win = pygame.display.set_mode((sw, sh))
w,h = background_size
g_x = sw
g_y = 360
g_v = 15
bg_x1 = 0
bg_y1 = 0
bg_x2 = w
bg_y2 = 0
t_x = 200
t_y = 250
t_v = random.randint(15,30)
d2 = 9999
d3 = 9999
count = 9999
def load_img(file_name): # loads the image, makes the pure white background transparent
img = pygame.image.load(file_name).convert()
img.set_colorkey((255,255,255))
return img
for i in range(1,7):
walkLeft.append( load_img("Sprites/L" + str(i) + ".png" ) ) #loads in lists of images
walkRight.append( load_img("Sprites/R" + str(i) + ".png") )
player_image = walkRight[0]
slide0 = pygame.image.load('Sprites/R1.png')
slide = pygame.transform.rotate(slide0, 90)
enemy_images = [pygame.image.load('Sprites/G1.png'), pygame.image.load('Sprites/G2.png')]
tube0 = pygame.image.load('Sprites/T1.png')
tube = pygame.transform.flip(tube0, False, True)
index = 0
pygame.mixer.music.load('Music/bensound-summer.mp3') #runs music on loop
pygame.mixer.music.play(-1)
isJump = False
jumpCount = 10
slideCount = 10
left_idx=0
right_idx=0
run = True #main loop
while run:
pygame.time.delay(50)
bg_x2 -= 8 #scrolling background
bg_x1 -= 8
if bg_x1 < sw - 2*w:
bg_x1 = sw
if bg_x2 < sw - 2*w:
bg_x2 = sw
g_x -= g_v #respawns Goomba every background frame
if g_x < 0:
g_x = sw
if g_v < 75:
g_v += 3
t_x -= 5
if t_x < 0:
t_x = sw
if t_v < 1000:
t_v += 2
if t_v >= 25 and t_v <= 30:
t_v = random.randint(15,30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if run == True:
if not isJump:
player_image = walkRight[right_idx]
right_idx += 1
if right_idx >= len(walkRight):
right_idx=0
if not(isJump): #jumping animation
if keys[pygame.K_UP]:
isJump = True
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
p_y -= (jumpCount ** 2)* 0.45 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
if not(isJump): #sliding animation
if keys[pygame.K_DOWN]:
player_image = slide
p_y = 350
slideCount -=1
#[index]
# index +=1
# if index >= len(slide):
#index = 0
if bg_x1 > -w:
win.blit(background_image,(bg_x1,bg_y1))
if bg_x2 > -w:
win.blit(background_image,(bg_x2,bg_y2))
win.blit(player_image, (p_x,p_y))
if run==True: #animation of Goomba
win.blit(enemy_images[index], (g_x, g_y))
pygame.time.delay(20)
index +=1
if index >= len(enemy_images):
index = 0
win.blit(tube, (t_x, t_y))
label = myfont.render("Hit Count = "+ str(hit_count), 1, (0, 0, 0))
win.blit(label, ((sw-250), 50))
pygame.display.update()
if count < 9999:
count += 1
d2 = (g_x - p_x)**2 + (g_y - p_y)**2 #calculates distance between Mario and Goomba
if d2 < 5000 and count > 10: #adds only one point per hit
hit_count +=1
count = 0
if hit_count > 100000000:
label2 = screen_over.render("Game Over", 1, (255, 0, 0))
win.blit(label2, (150, 200))
pygame.display.update()
time.sleep(3)
run= False
d3 = (t_x - p_x)**2 + (t_y - p_y)**2 #distance between tube and Mario
if count < 9999: count += 1
if d3 < 500:
label2 = screen_over.render("Game Over", 1, (255, 0, 0))
win.blit(label2, (165, 200))
pygame.display.update()
time.sleep(2)
run = False
theClock.tick(50)
pygame.quit()
|
C++
|
UTF-8
| 410
| 2.890625
| 3
|
[] |
no_license
|
#include<cstdio>
int main(){
int x,y;
bool xt,yt,t;
scanf("%d%d",&x,&y);
(x&1)?xt=true:xt=false; // false = even
(y&1)?yt=true:yt=false;
t=false;
if(x==y){
t=true;
if((!xt)&(!yt)){
printf("%d",x+y);
}else{
printf("%d",x+y-1);
}
}else if(x-2==y){
t=true;
if((!xt)&(!yt)){
printf("%d",x+y);
}else{
printf("%d",x+y-1);
}
}
(!t)?printf("No Number"):false;
return 0;
}
|
Java
|
UTF-8
| 1,156
| 2.421875
| 2
|
[] |
no_license
|
package com.li.cn;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* 异常处理
* 如何去掉spring boot默认的异常处理逻辑
*
* @SpringBootApplication( exclude = { ErrorMvcAutoConfiguration.class})
* <p>
* 使用ErrorPageRegistrar接口的registerErrorPages
* registry.addErrorPages
*
*
* 全局异常处理
* 1,写一个了,加上@ControllerAdvice注解
* 2,写一个异常处理方法 @ExceptionHandler(Exception.class)
*/
//@Component
public class CommonErrorPageRegistry implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error.html");
ErrorPage args = new ErrorPage(IllegalArgumentException.class, "/otherror.html");
registry.addErrorPages(e404, e500, args);
}
}
|
Java
|
UTF-8
| 431
| 1.890625
| 2
|
[] |
no_license
|
package com.functions;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class CreateBucket {
public static void main(String args[]) {
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.create(BucketInfo.of("bucket-new-bucket"));
}
}
|
Markdown
|
UTF-8
| 1,644
| 3.453125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#Component and props
컴포넌트를 사용하여 UI를 독립적이고 재사용 가능한 부분으로 분리하고 각 부분을 개별적으로 생각할 수 있다.
개념상 컴포넌트는 JavaScript 함수와 같다. 컴포넌트는 임의의 입력 ( "props"라고 함)을 받아들이고 무엇이 화면에 나타나야 하는지를 담고있는 React 요소를 반환한다.
##Component
컴포넌트를 정의하는 가장 쉬운 방법은 자바스크립트 함수를 정의하는 것이다.
```javascript
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
```
또는 ES6적으로 클래스를 사용하여 정의할 수 있다.
```java
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
```
위의 두 정의는 React개념상으로는 같은 의미이다.
##Component 구성하기
컴포넌트는 출력에서 다른 구성 요소를 참조 할 수 있고 이를 통해 모든 세부 수준에서 동일한 컴포넌트 추상화를 사용할 수 있다. React 앱에서는 버튼, 폼, 대화 상자, 화면 등 모든 것이 일반적으로 컴포넌트로 표현된다.
```javascript
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
여기서보면 props는 부모로부터 값을 넘겨받을 수 있는 매개체이다.
모든 React 컴포넌트는 props과 관련하여 pure 함수처럼 작동해야한다.
|
C++
|
UTF-8
| 1,697
| 2.546875
| 3
|
[] |
no_license
|
#pragma once
#include "Components/SkeletalMeshComponent.h"
#include "Puzzle/BarrierColor.h"
#include "LightningBarrierSkeletalMeshComp.generated.h"
/**
* @class ULightningBarrierSkeletalMeshComp
*
* @brief Class inherited from skeletal mesh component.
* Used to create a lightning barrier mesh and keeping track of the
* lightning state (on or off)
*/
UCLASS()
class TGCO_API ULightningBarrierSkeletalMeshComp : public USkeletalMeshComponent
{
GENERATED_BODY()
public:
/* @brief Constructor */
ULightningBarrierSkeletalMeshComp(const FObjectInitializer& ObjectInitializer);
/**
* @brief Changes the state of the lightning.
*
* @param ActivateLightning New state for the light
*/
UFUNCTION(BlueprintCallable, Category = "LightningBarrier")
void ChangeLightningState(bool ActivateLightning);
/**
* @brief Set the barrier material to give it an identifiable color.
* This color is also found on the diodes of the different @ref LightningSwitch that
* control this barrier
*
* @param BarColor Color to apply to the barrier
*/
UFUNCTION(BlueprintCallable, Category = "LightningBarrier")
void SetBarrierMaterial(EBarrierColor BarColor);
public:
/** Mesh of the barrier's first pylon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LightningBarrier")
UStaticMeshComponent * pFirstTerminalComponent;
/** Mesh of the barrier's lightning */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LightningBarrier")
UStaticMeshComponent * pSecondTerminalComponent;
/** Mesh of the barrier's second pylon */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LightningBarrier")
UStaticMeshComponent * pLightningComponent;
protected:
};
|
Ruby
|
UTF-8
| 1,146
| 3.0625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require_relative 'parser'
require_relative 'analyzer'
def display_results analyzer
# Get and display the conditional probabilities for each polarity
[:pos, :neg].each do |p|
probs = analyzer.cond_probs(p)
puts "P(Xi | #{p.to_s}) = [#{probs.join(" ")}]"
end
result = analyzer.accuracy(analyzer.classify)
puts "\nClassifier accuracy: " + result[:accuracy].to_s
puts "\nConfusion matrix:"
result[:confusion].each do |r|
puts r.join("\t")
end
puts "\nResult of cross-fold validation:"
result = analyzer.accuracy(analyzer.cross_fold_validation)
puts "\nClassifier accuracy: " + result[:accuracy].to_s
puts "\nConfusion matrix:"
result[:confusion].each do |r|
puts r.join("\t")
end
puts "\nRandom Reviews:"
reviews = analyzer.generate_reviews
puts "\nPositive:"
reviews[:pos].each { |r| puts r.empty? ? "<Blank Review Generated>" : r }
puts "\nNegative:"
reviews[:neg].each { |r| puts r.empty? ? "<Blank Review Generated>" : r }
end
if __FILE__ == $0
parser = Parser.new("./data/txt_sentoken")
analyzer = Analyzer.new(parser.features)
display_results(analyzer)
end
|
Java
|
UTF-8
| 616
| 2.0625
| 2
|
[] |
no_license
|
package com.zss.pattern.aop.controller;
import com.zss.pattern.aop.manager.MarketCalcManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@RestController
public class AopIndexController {
@Autowired
private MarketCalcManager marketCalcManager;
@RequestMapping("index")
public String index(){
marketCalcManager.runHk();
marketCalcManager.runUs();
return LocalDateTime.now().toString();
}
}
|
Python
|
UTF-8
| 1,533
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
from ability import Ability
from weapon import Weapon
from armor import Armor
from hero import Hero
from team import Team
class Arena:
def __init__(self, team_one, team_two):
self.team_one = team_one
self.team_two = team_two
def create_ability(self):
name = input("What is the ability name?")
max_damage = input("What is the max damage of the ability?")
return Ability(name, max_damage)
def create_weapon(self):
name = input("What is the weapon name?")
max_damage = input("What is the max damage of the weapon?")
return Ability(name, max_damage)
def create_armor(self):
name = input("What is the armor name?")
max_block = input("What is the max block?")
return Armor(name, max_block)
def create_hero(self):
hero_name = input("Hero's name: ")
hero = Hero(hero_name)
add_item = None
while add_item != "4":
add_item = input("[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: ")
if add_item == "1":
#TODO add an ability to the hero
#HINT: First create the ability, then add it to the hero
elif add_item == "2":
#TODO add a weapon to the hero
#HINT: First create the weapon, then add it to the hero
elif add_item == "3":
#TODO add an armor to the hero
#HINT: First create the armor, then add it to the hero
return hero
|
C++
|
UTF-8
| 600
| 2.53125
| 3
|
[] |
no_license
|
//
// StockMediator.hpp
// MediatorDesignpattern
//
// Created by Lihua Xu on 5/14/21.
//
#ifndef StockMediator_hpp
#define StockMediator_hpp
#include <stdio.h>
#include <string>
#include "Colleague.hpp"
class StockMediator:public Mediator{
public:
void addColleague(Colleague *colleague){
listColl.push_back(colleague);
colleagueNum++;
colleague->setCollCode(colleagueNum);
};
void saleOffer(std::string stock, int shares, int code);
void buyOffer(std::string stock, int shares, int code);
void getStockOffering();
};
#endif /* StockMediator_hpp */
|
Java
|
UTF-8
| 1,110
| 2.53125
| 3
|
[] |
no_license
|
package javaapplication1;
import java.io.File;
import javax.media.*;
import javax.media.format.AudioFormat;
public class Suono{
Time time;
Player player;
public Suono(String indirizzo){
time= new Time(0);
Format mp3 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{mp3},
new Format[]{output},
PlugInManager.CODEC
);
try{
player = Manager.createPlayer(new MediaLocator(new File(indirizzo).toURI().toURL()));
}
catch(Exception ex){
ex.printStackTrace();
}
player.realize();
}
public void Start() {
player.start();
}
public void setMediaTimer() {
player.setMediaTime(time);
}
public void Stop() {
player.stop();
}
public long getMediaTimer() {
return (long) player.getMediaTime().getSeconds();
}
public long getDuration() {
return (long) player.getDuration().getSeconds();
}
}
|
Markdown
|
UTF-8
| 2,333
| 3.65625
| 4
|
[] |
no_license
|
### [Beautiful Array](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/611/week-4-july-22nd-july-28th/3829/)
Given `n`, return an array which has no element that is the double of an element from the left of it + an element from
the right of it
### Thought process
#### Approach number 1:
My first thought was that there must be a pattern that lets me create the array in one go and involves something with
multiplying or dividing by 2 or the binary representation of numbers, but I could not see anything, so I decided to make
a backtracking solution and see how the results look like. As expected, the algorithm is slow for larger values, but
once I saw the results (up to n=64), some patterns started to emerge:
* all the solutions started with a 1
* all the results ended with a power of 2 and not just any power, the highest power less(or equal) than the number `n`
* there was a clear divide between even and odd numbers
* the number 2 was always in the middle
* the first odd number after 1 was a power of 2 + 1
* there seemed to be some sort of pattern if you looked at the binary values. For example, the result for n=33 starts
with 1,33,17,9,5 which, in binary, looks like: 1, 10 0001, 1 0001, 1001, 101
#### Approach number 2 (incomplete):
Since the number 2 always was in the middle, I thought i can divide and conquer the "left" side and the "right" side of
a number, and i would start with 2. Unfortunately I could not find a connection that is applicable on both sides. My
biggest issue was that on the number of evens and odds on both sides of 2 was about equal and that was not what I
observed with my previous approach . I tried a few ways of assigning values, but it was mostly me throwing stuff at the
problem and seeing what sticks so I decided to give up on this approach (at least for now)
#### Approach number 3 (accepted solution):
Looking for some inspiration for the approach number 2, I happened to see "reverse binary" and then it clicked. The
binary pattern I've been trying to figure out was the "0" front-padded reverse of a number. If we sort this
representations of the numbers, we get a valid solution.
I did not prove to myself yet why this solution works, but i've already spent too much time on this not so fun (and
despite it's name, ugly) math problem...
|
Markdown
|
UTF-8
| 5,477
| 3
| 3
|
[] |
no_license
|
# DSP-Assignment1
Run program instructions:
java -jar LocalApp.jar [input_file_path] [output_file_path] N [terminate?]
input file path – path to input file (including extension)
output file path – path to output file will be written (without extension)
N – number of messages to be processed per worker
Terminate – true or false whether shut-down manager and workers instances and delete all queues
- Important: must have aws credentials under ~/.aws/credentials to run
# Types of instance we used:
- Image-Id:
- ami-076515f20540e6e0b
Instance Type:
- T2_MICRO
Running examples:
2500 pdfs processed in 8 min where N was ~357 (i.e 7 workers)
Java – jar LocalApp.jar input-sample-1.txt output-sample-1 357 true
10,800 pdfs processed in 20 min where N was 1350 (i.e 8 workers)
Java – jar LocalApp.jar input-sample-2.txt output-sample-2 1350 true
2 local apps simultaneously – each with 100 pdfs - worked
Note: Input files can be found in the zip folder we submitted
• Security:
We used Amazon Ami-Role in order to give our soon to be launch instances the security credentials in a safe way.
Our bucket is private and cannot be accessed from outside
• Scalability:
We used thread pool in our manager implementation to make it scalable. Our program does not depend on some final number of clients, there is no reasonable reason for our code to crush on 1 million / 1 billion clients (it is a good idea to move to a cluster of several managers to be even more scaled)
• Persistence:
Each time we call aws service we are handling all possible outcomes, i.e. all relevant exceptions that might raise.
In a case of communication issue - for example worker reading from a queue which is not up yet, it will retry to recover indefinitely (with 1 sec sleep).
In a case worker instance shut-down unexpectedly, the message it took will be returned to the tasksQ.
In a case of delay of some worker, we have configured the Q visibility timeout to be longer.
• Threads:
Bad idea: when number of clients (local apps), exceeds some number (about several thousands) we should give more power to the manager in the form of Thread pool or even several managers
Good idea: We don’t make new local apps requests wait
We synchronized the activation of new EC2 instances to ensure no more than 10 instances will be running, regardless the number of concurrently running local apps (For student account compatibility).
# ---------------------
• Full run:
Local app:
For every local app we generate some unique id.
1. Local app gets an input file and upload it to a private s3 bucket to folder with the name which equal to the id of the local app (The file key will be “inputFile” + localAppId)
2. Local app checks if a manager is active and if not, starts it.
3. Local app sends a message to the manager in the “Local_Manager_Queue”
4. Local app waits for its result from its unique Q with the name “Manager_Local_Queue” + local app id.
Manager:
1. The manager reads messages from Local_Manager_Queue until it gets a “terminate” message.
2. (loops endlessly loops endlessly to receive messages from Local_Manager_Queue)
a. If it gets a task message
- i. Extracts the numOfPdfForWorker, local app id from the message
- ii. Asks the thread pool to spawn a new thread which process the local app message.
b. (terminate case detailed later)
Each managerRunner thread create the worker tasks, TasksQ and the tasksResultQ (with the name “TaskResultQ” + localAppid). Then launch number of workers as needed, delegate messages to them (in the TasksQueue), wait for all the tasks results to finish and make and upload a summary file to the Local app in the (Manager_Local_Q + id) Queue.
Worker: (loops endlessly to receive messages from TasksQ)
Each worker read messages from the TasksQueue until the manager shut them down.
• For each message, the worker download the pdf, performed the requested operation, upload the resulting output to s3 and sent a message in the (“TasksResultsQ + localAppId”). In a case of an error, the final message contains the error description.
• Termination Process:
When the manager gets its terminate message, it deletes all the queues and terminate all running workers and itself at last.
• System Limitation:
The manager has some limit on the number of threads it can run.
Our educate amazon account is limited in the number of allowed buckets and EC2 instances so we are have at most 10 EC2 instances (validated in our code).
• Workers Job:
All the workers sharing the same queue (Named “TasksQueue”), so there is no reasonable reason for some worker to work harder than others.
• Project structure:
We split the code into 4 modules: LocalApp, Manager, Worker and utils.
Each 1of the first 3 we mentioned contains a main class running only its relevant logic.
In addition, each module has its own specific dependencies defined in its own pom.xml file.
Any shared functionality like using S3, EC2 and SQS is taken place in the utils module so could can efficiently be reused cross modules.
We also added slf4j with simple logger implementation as our log provider.
• Distribution: the system is indeed distributed as we divide big amounts of work into multiple machines which work independently and asynchronously.
There are several threads that wait for another process to finish. E.g. local app actively waits for the summary file message and manger waits for all workers to complete their tasks.
|
Markdown
|
UTF-8
| 5,649
| 2.9375
| 3
|
[] |
no_license
|
---
layout: post
status: publish
published: true
title: We, in Europe, we eat many sardines
author:
display_name: luispedro
login: luispedro
email: luis@luispedro.org
url: ''
author_login: luispedro
author_email: luis@luispedro.org
wordpress_id: 764
wordpress_url: http://blog.luispedro.org/posts/we-in-europe-we-eat-many-sardines
date: '2006-12-01 21:29:47 -0800'
date_gmt: '2006-12-01 21:29:47 -0800'
categories:
- Europa
- Vida n'América
tags: []
comments:
- id: 12890
author: Luís Lavoura
author_email: balio@cftp.ist.utl.pt
author_url: ''
date: '2006-12-02 15:42:28 -0800'
date_gmt: '2006-12-02 15:42:28 -0800'
content: "Pois olhe, eu só me apercebi de que a Europa é
efetivamente um país quando vivi n'América. Pois que
a distância cultural entre a Europa e a América é
incomparavelmente maior do que entre os países europeus entre si.
Quando estava nos EUA, apercebi-me de facto de que era europeu.\r\n\r\nNão
me admira pois que os europeus nos EUA digam \"na Europa\". É que
a Europa existe mesmo, quando vista do lado de lá do Atlântico."
- id: 12904
author: luispedro
author_email: luis@luispedro.org
author_url: ''
date: '2006-12-02 17:01:58 -0800'
date_gmt: '2006-12-02 17:01:58 -0800'
content: "\"Pois que a distância cultural entre a Europa e a América
é incomparavelmente maior do que entre os países europeus
entre si. \"\r\n\r\nDisto discordo. A Europa do Norte está tão
longe culturalmente da Europa do Sul como os EUA estão da Europa
do Sul. Existem alguns blocos culturais na Europa (Norte, Sul, e Leste) e dentro
destes blocos há alguma homogeneadade, mas entre países
que bebem vinho e outros que bebem cerveja, a comunicação
é difícil.\r\n\r\nHonestamente, sinto-me provavelmente
menos estrangeiro numa festa de americanos do que numa festa de finlandeses.\r\n\r\nO
engraçado é que, por outro lado, me espanta a frequência
com que os americanos falam do \"seu\" estado e a existência e uso
corrente de palavras como \"Californian.\""
- id: 12905
author: luispedro
author_email: luis@luispedro.org
author_url: ''
date: '2006-12-02 17:06:27 -0800'
date_gmt: '2006-12-02 17:06:27 -0800'
content: 'Voltando ao tópico: este post era sobre os europeus que dizem
"na europa" e depois seguem-se coisas que são erros factuais (por
exemplo, "na europa, as notas são de 0 a 20" é erro
factual).'
- id: 12944
author: Bruno
author_email: bmcmartins@megamail.pt
author_url: http://ideiateca.blogspot.com
date: '2006-12-02 19:32:29 -0800'
date_gmt: '2006-12-02 19:32:29 -0800'
content: Não é preciso ir tão longe. Também
há portugueses que dizem "Em Portugal..." ou pessoas que dizem "A
nossa geração..." e segue-se afirmações
que dizem respeito apenas ao seu meio geográfico ou socio-económico.
- id: 13194
author: Eunice
author_email: eunice.costa@gmail.com
author_url: ''
date: '2006-12-07 00:56:05 -0800'
date_gmt: '2006-12-07 00:56:05 -0800'
content: Eu é que darei em breve um grande salto para esses lados,
como quem vai de Lisboa comer um Apfelstrudel a Viena (só para não
repetir a ópera), mesmo assim ainda ficarei longe de ti.
---
<p>Na série <i>Afinal até há europeus</i>:</p>
<p>Uma das coisas que me tem espantado a viver aqui nos EUA é ouvir os europeus dizerem <cite>in Europe</cite> com imensa frequência ao invés de dizerem <cite>in Portugal</cite> ou <cite>in France</cite>. Infelizmente, muitas vezes falam do seu país como <cite>a Europa</cite>.</p>
<p>Por exemplo, sendo isto o meio académico, a comparação de sistemas educativos e de ensino é corrente: Um português dirá <cite>In europe, grades are not in letters [aqui as notas são de A a F]. We assign a number between 0 and 20.</cite> Claro que em Inglaterra também se usam números, no ambiente germânico é de um a seis (um é o melhor), noutros é de um a seis, mas o seis é o melhor, e em certos países é de um a dez.</p>
<p>Dos americanos, esperava ouvir falar na Europa como um bloco único (como os europeus falam nos EUA como se fosse um país culturalmente único, com um sistema americano. Não nos apercebemos sequer da extensão geográfica: já me perguntaram porque é que eu ainda não fui visitar <cite>não-sem-quem</cite> na Califórnia. Inocentemente, sem perceber que é como perguntar a um americano em Lisboa porque é que ainda não foi à ópera de Viena).</p>
<p>Dos americanos, esperava isso: a europa como um grande bloco. Não esperava o mesmo dos europeus.</p>
|
JavaScript
|
UTF-8
| 4,522
| 3.140625
| 3
|
[] |
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.
*/
document.getElementById("car-table").innerHTML = fetchAllCars();
let switchbutton = true;
let getAllCarsBtn = document.getElementById("getAllCarsBtn");
getAllCarsBtn.addEventListener('click', () => {
fetchAllCars();
});
function fetchAllCars() {
let url = 'api/car/all';
let allCars = document.getElementById("car-div");
fetch(url)
.then(res => res.json())
.then(data => {
let newArray = data.map(x => `<tr><td>${x.manufacturer}</td><td>${x.year}</td><td>${x.model}</td><td>${x.price}</td><td>${x.quantity}</td></tr>`);
allCars.innerHTML =
`<table class="table" id="car-table">
<thead><th onclick="sortTable(0)">Manufacturer</th><th onclick="sortTableNumber(1)">Year</th><th onclick="sortTable(2)">Model</th><th onclick="sortTableNumber(3)">Price</th><th onclick="sortTableNumber(4)">Quantity</th></thead>
<tbody>${newArray.join("")}</tbody>
</table>`;
});
}
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("car-table");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
function sortTableNumber(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("car-table");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (Number(x.innerHTML) < Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
|
Java
|
UTF-8
| 1,158
| 1.96875
| 2
|
[] |
no_license
|
package com.pay.calculatorweb;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EnableJpaRepositories("com.pay.calculatorweb.repository")
public class CalculatorWebApplication {
public static void main(String[] args) {
SpringApplication.run(CalculatorWebApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// Do any additional configuration here
return builder.build();
}
@Bean
ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
return modelMapper;
}
}
|
Python
|
UTF-8
| 3,093
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/env python
#
# firewarebf.py attempts to bruteforce the password on a Watchguard firewall.
import poster
import urllib2
import ssl
import re
import argparse
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
def list_from_file(filename):
tmp = []
try:
f = open(filename, 'r')
except:
print "Could not open file: %s" % f.name()
for line in f:
tmp.append(line.rstrip('\r\n'))
return tmp
def check_user_pass(url, user, pwd, domain):
site = url + '/wgcgi.cgi?action=fw_logon&style=fw_logon.xsl&fw_logon_type=status'
values = {'submit' : 'Login',
'action' : 'fw_logon',
'style' : 'fw_logon_progress.xsl',
'fw_logon_type' : 'logon'}
values['fw_username'] = user
values['fw_password'] = pwd
values['fw_domain'] = domain
datagen, headers = poster.encode.multipart_encode(values)
req = urllib2.Request(site, datagen, headers)
resp = urllib2.urlopen(req).read()
if re.search('Authentication Failed:', resp):
print "Failed: %s, %s" % (u, p)
else:
print resp
print "Success: %s, %s" % (u, p)
#-----------------------------------------------------------------------------
# Main Program
#-----------------------------------------------------------------------------
# Setup poster module
poster.streaminghttp.register_openers()
#Parse command line arguments using argparse
desc = """firewarebf.py attempts to bruteforce the password on a Watchguard
firewall. You will need to provide the IP address of the firewall, the login
domain, and the login credentials to test.
"""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('server', action='store', default='192.168.0.1',
help="Ip address of server (Default: 192.168.0.1)")
passgroup = parser.add_mutually_exclusive_group(required=True)
passgroup.add_argument('-p', action='store', default=None, metavar='passfile',
help='List of passwords. Will use default usernames of admin and status.')
passgroup.add_argument('-f', action='store', default=None,
metavar='userpassfile',
help='List of user:pass combinations.')
parser.add_argument('-d', action='store', default='Firebox-DB',
metavar='domain', help='Login domain (Default: Firebox-DB')
parser.add_argument('--http', action='store_true', default=False,
help='Use an HTTP connection instead of HTTPS')
args = parser.parse_args()
# Set the URL based on --http flag
if args.http:
url = "http://" + args.server
else:
url = "https://" + args.server
# Test the passwords
if args.f:
for c in list_from_file(args.f):
u, p = c.split(":")
check_user_pass(url, u, p, args.d)
else:
users = ['admin', 'status']
pwds = list_from_file(args.p)
for u in users:
for p in pwds:
check_user_pass(url, u, p, args.d)
|
Java
|
UTF-8
| 290
| 1.835938
| 2
|
[] |
no_license
|
package com.gdf.diplomamunka.gaborbeke.nova.services;
import com.gdf.diplomamunka.gaborbeke.nova.email.Mail;
import javax.mail.MessagingException;
import java.io.IOException;
public interface EmailService {
public void sendEmail(Mail mail) throws MessagingException, IOException;
}
|
JavaScript
|
UTF-8
| 810
| 2.96875
| 3
|
[] |
no_license
|
(function() {
var form = document.getElementById('interests'); // get form
var elements = form.elements; // get all form elements
var options = elements.genre; // get all genres from array
var all = document.getElementById('all'); // get 'all' checkbox
function updateAll() {
// loop thru checkboxes and update checked property
for (var i = 0; i < options.length; i++) {
options[i].checked = all.checked;
}
}
// add event listener
addEvent(all, 'change', updateAll);
// get target, if not checked then uncheck 'all' checkbox
function clearAllOption(e) {
var target = e.target || e.srcElement;
if (!target.checked) {
all.checked = false;
}
}
for (var i = 0; i < options.length; i++) {
addEvent(options[i], 'change', clearAllOption);
}
}());
|
Markdown
|
UTF-8
| 1,419
| 2.8125
| 3
|
[] |
no_license
|
# Frontend Mentor - Loopstudios landing page

## The challenge
The challenge is to build out [this landing page](https://www.frontendmentor.io/challenges/loopstudios-landing-page-N88J5Onjw) and get it looking as close to the design as possible.
- Figma and Sketch files are provided
- Optimized assets are found in the `/images` folder.
- There is also a `style-guide.md` file, which contains the information such as color palette and fonts.
User Stories:
- View the optimal layout for the component depending on their device's screen size
- See hover states for all interactive elements on the page
## Tools I used
- Javascript
- SCSS
- BEM
- Grid and Flexbox
- Figma
- [Animate On Scroll library](https://michalsnik.github.io/aos/)
- [Perfect Pixel](https://www.welldonecode.com/perfectpixel)
## Learning outcomes
My focus for this project is to improve accessibility practices. I was able to implement:
1. Skip links
2. Screen-reader only text
3. ARIA labels
4. Styling focus outlines
5. Meaningful `alt` text
6. Subtle scroll animations and transitions
7. Use of `srcset` and `source` for `<picture>` tags
## My profile at Frontendmentor
[emestabillo](https://www.frontendmentor.io/profile/emestabillo)
## Solution preview
<p align="center">
<img src="images/loopstudios.gif">
</p>
<p align="center">
|
C++
|
UTF-8
| 1,476
| 2.546875
| 3
|
[
"PHP-3.01",
"Zend-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <glog/logging.h>
#include <folly/SocketAddress.h>
namespace proxygen {
struct AcceptorAddress {
enum class AcceptorType { TCP, UDP };
AcceptorAddress() = delete;
AcceptorAddress(folly::SocketAddress address, AcceptorType protocol)
: address(address), protocol(protocol) {
}
folly::SocketAddress address;
AcceptorType protocol;
};
inline bool operator<(const AcceptorAddress& lv, const AcceptorAddress& rv) {
if (lv.address < rv.address) {
return true;
}
if (rv.address < lv.address) {
return false;
}
return lv.protocol < rv.protocol;
}
inline std::ostream& operator<<(std::ostream& os,
const AcceptorAddress::AcceptorType& accType) {
switch (accType) {
case AcceptorAddress::AcceptorType::TCP:
os << "TCP";
break;
case AcceptorAddress::AcceptorType::UDP:
os << "UDP";
break;
default:
LOG(FATAL) << "Unknown Acceptor type.";
}
return os;
}
inline std::ostream& operator<<(std::ostream& os,
const AcceptorAddress& accAddr) {
os << accAddr.address << "<" << accAddr.protocol << ">";
return os;
}
using AcceptorType = AcceptorAddress::AcceptorType;
} // namespace proxygen
|
Markdown
|
UTF-8
| 5,196
| 2.953125
| 3
|
[] |
no_license
|
---
layout: post
title: Waterfall in Blazor Charts Component | Syncfusion
description: Checkout and learn here all about Waterfall Chart in Syncfusion Blazor Charts component and much more.
platform: Blazor
control: Chart
documentation: ug
---
# Waterfall in Blazor Charts Component
## Waterfall
`Waterfall Chart` helps to understand the cumulative effect of the sequentially introduced positive and negative values. To render a waterfall series, set the series [Type](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_Type) as **Waterfall**. [IntermediateSumIndexes](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_IntermediateSumIndexes) property of waterfall is used to represent the in-between sum values and [SumIndexes](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_SumIndexes) is used to represent the cumulative sum values.
```cshtml
@using Syncfusion.Blazor.Charts
<SfChart>
<ChartPrimaryXAxis ValueType="Syncfusion.Blazor.Charts.ValueType.Category">
</ChartPrimaryXAxis>
<ChartSeriesCollection>
<ChartSeries DataSource="@SalesReports" XName="XValue" YName="YValue" Type="ChartSeriesType.Waterfall" IntermediateSumIndexes="@index" SumIndexes="@sumIndex">
<ChartMarker Height="10" Width="10" Visible="true"></ChartMarker>
</ChartSeries>
</ChartSeriesCollection>
</SfChart>
@code{
double[] index = new double[] { 4 };
double[] sumIndex = new double[] { 8 };
public class ChartData
{
public string XValue { get; set; }
public double YValue { get; set; }
}
public List<ChartData> SalesReports = new List<ChartData>
{
new ChartData { XValue = "Income", YValue = 4711 },
new ChartData { XValue = "Sales", YValue = -1015 },
new ChartData { XValue = "Development", YValue = -688 },
new ChartData { XValue = "Revenue", YValue = 1030 },
new ChartData { XValue = "Balance" },
new ChartData { XValue = "Expense", YValue = -361 },
new ChartData { XValue = "Tax", YValue = -695 },
new ChartData { XValue = "Net Profit" },
};
}
```

> Explore our [Blazor Waterfall Chart Example](https://blazor.syncfusion.com/demos/chart/waterfall?theme=bootstrap4) to know how to render and configure the Waterfall type chart.
## Series Customization
The negative changes of waterfall charts is represented by using [NegativeFillColor](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_NegativeFillColor) and the summary changes are represented by using [SummaryFillColor](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_SummaryFillColor) properties respectively. By default, the [NegativeFillColor](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_NegativeFillColor) is **#E94649** and the [SummaryFillColor](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Charts.ChartSeries.html#Syncfusion_Blazor_Charts_ChartSeries_SummaryFillColor) is **#4E81BC**.
```cshtml
@using Syncfusion.Blazor.Charts
<SfChart>
<ChartPrimaryXAxis ValueType="Syncfusion.Blazor.Charts.ValueType.Category">
</ChartPrimaryXAxis>
<ChartSeriesCollection>
<ChartSeries DataSource="@ExpenseDetails" XName="XValue" SummaryFillColor="#e56590" NegativeFillColor="#f8b883"
YName="YValue" Type="ChartSeriesType.Waterfall" IntermediateSumIndexes="@intermediateSumIndexes" SumIndexes="@sumIndexes">
<ChartMarker Height="10" Width="10" Visible="true"></ChartMarker>
</ChartSeries>
</ChartSeriesCollection>
</SfChart>
@code{
double[] intermediateSumIndexes = new double[] { 4 };
double[] sumIndexes = new double[] { 7 };
public class ChartData
{
public string XValue;
public double YValue;
}
public List<ChartData> ExpenseDetails = new List<ChartData>
{
new ChartData { XValue = "Income", YValue = 4711 },
new ChartData { XValue = "Sales", YValue = -1015 },
new ChartData { XValue = "Development", YValue = -688 },
new ChartData { XValue = "Revenue", YValue = 1030 },
new ChartData { XValue = "Balance" },
new ChartData { XValue = "Expense", YValue = -361 },
new ChartData { XValue = "Tax", YValue = -695 },
new ChartData { XValue = "Net Profit" },
};
}
```

> Refer to our [Blazor Charts](https://www.syncfusion.com/blazor-components/blazor-charts) feature tour page for its groundbreaking feature representations and also explore our [Blazor Chart Example](https://blazor.syncfusion.com/demos/chart/line?theme=bootstrap4) to know various chart types and how to represent time-dependent data, showing trends at equal intervals.
## See Also
* [Data Label](../data-labels)
* [Tooltip](../tool-tip)
|
Markdown
|
UTF-8
| 1,059
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
# Create-Marker-Gene-Database
Scripts for creating "marker gene" reference files for use as database for sequence similarity searches
#### Overview
The `generate_annotation.sh` is taking a FASTA file with common header format as can be usually found in UniProt, NCBI, etc. and performs the following:
- Dereplicate sequences by 97 percent similarity with `cd-hit`
- Convert FASTA to one-line format and remove header description (after whitespace) with `awk`
- Convert headers to md5 with python script `convert_fasta_headers_md5.py`
- Merge files to create a complete annotation file with python script `merge_annotation_files.py`
#### Software requirements
```
cd-hit
Pandas (Python)
```
#### Requred files
- FASTA file (`.fa` extention)
- Tab-seperate annotation file (same name as FASTA with `.tab` exention)
Downloaded from UniProt, for example:
https://www.uniprot.org/uniprot/?query=terminase+family%3Aprotein+taxonomy%3A%22Viruses+%5B10239%5D%22&sort=score
#### Output files
1. derep.fa
2. derep.md5.fa
3. derep.fa.clstr
4. annotation.tsv
|
Markdown
|
UTF-8
| 3,343
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
# aws_ec2_local_gateway_route_table
[back](../aws.md)
### Index
- [Example Usage](#example-usage)
- [Variables](#variables)
- [Datasource](#datasource)
- [Outputs](#outputs)
### Terraform
```terraform
terraform {
required_providers {
aws = ">= 3.35.0"
}
}
```
[top](#index)
### Example Usage
```terraform
module "aws_ec2_local_gateway_route_table" {
source = "./modules/aws/d/aws_ec2_local_gateway_route_table"
# local_gateway_id - (optional) is a type of string
local_gateway_id = null
# local_gateway_route_table_id - (optional) is a type of string
local_gateway_route_table_id = null
# outpost_arn - (optional) is a type of string
outpost_arn = null
# state - (optional) is a type of string
state = null
# tags - (optional) is a type of map of string
tags = {}
filter = [{
name = null
values = []
}]
}
```
[top](#index)
### Variables
```terraform
variable "local_gateway_id" {
description = "(optional)"
type = string
default = null
}
variable "local_gateway_route_table_id" {
description = "(optional)"
type = string
default = null
}
variable "outpost_arn" {
description = "(optional)"
type = string
default = null
}
variable "state" {
description = "(optional)"
type = string
default = null
}
variable "tags" {
description = "(optional)"
type = map(string)
default = null
}
variable "filter" {
description = "nested block: NestingSet, min items: 0, max items: 0"
type = set(object(
{
name = string
values = set(string)
}
))
default = []
}
```
[top](#index)
### Datasource
```terraform
data "aws_ec2_local_gateway_route_table" "this" {
# local_gateway_id - (optional) is a type of string
local_gateway_id = var.local_gateway_id
# local_gateway_route_table_id - (optional) is a type of string
local_gateway_route_table_id = var.local_gateway_route_table_id
# outpost_arn - (optional) is a type of string
outpost_arn = var.outpost_arn
# state - (optional) is a type of string
state = var.state
# tags - (optional) is a type of map of string
tags = var.tags
dynamic "filter" {
for_each = var.filter
content {
# name - (required) is a type of string
name = filter.value["name"]
# values - (required) is a type of set of string
values = filter.value["values"]
}
}
}
```
[top](#index)
### Outputs
```terraform
output "id" {
description = "returns a string"
value = data.aws_ec2_local_gateway_route_table.this.id
}
output "local_gateway_id" {
description = "returns a string"
value = data.aws_ec2_local_gateway_route_table.this.local_gateway_id
}
output "local_gateway_route_table_id" {
description = "returns a string"
value = data.aws_ec2_local_gateway_route_table.this.local_gateway_route_table_id
}
output "outpost_arn" {
description = "returns a string"
value = data.aws_ec2_local_gateway_route_table.this.outpost_arn
}
output "state" {
description = "returns a string"
value = data.aws_ec2_local_gateway_route_table.this.state
}
output "tags" {
description = "returns a map of string"
value = data.aws_ec2_local_gateway_route_table.this.tags
}
output "this" {
value = aws_ec2_local_gateway_route_table.this
}
```
[top](#index)
|
Python
|
UTF-8
| 6,138
| 2.53125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
import argparse
import sys
from importlib import resources
from compass.setup import setup_cases
from compass.clean import clean_cases
def setup_suite(mpas_core, suite_name, config_file=None, machine=None,
work_dir=None, baseline_dir=None, mpas_model_path=None,
copy_executable=False):
"""
Set up a test suite
Parameters
----------
mpas_core : str
The MPAS core ('ocean', 'landice', etc.) of the test suite
suite_name : str
The name of the test suite. A file ``<suite_name>.txt`` must exist
within the core's ``suites`` package that lists the paths of the tests
in the suite
config_file : str, optional
Configuration file with custom options for setting up and running
test cases
machine : str, optional
The name of one of the machines with defined config options, which can
be listed with ``compass list --machines``
work_dir : str, optional
A directory that will serve as the base for creating test case
directories
baseline_dir : str, optional
Location of baselines that can be compared to
mpas_model_path : str, optional
The relative or absolute path to the root of a branch where the MPAS
model has been built
copy_executable : bool, optional
Whether to copy the MPAS executable to the work directory
"""
text = resources.read_text('compass.{}.suites'.format(mpas_core),
'{}.txt'.format(suite_name))
tests, cached = _parse_suite(text)
setup_cases(tests, config_file=config_file, machine=machine,
work_dir=work_dir, baseline_dir=baseline_dir,
mpas_model_path=mpas_model_path, suite_name=suite_name,
cached=cached, copy_executable=copy_executable)
def clean_suite(mpas_core, suite_name, work_dir=None):
"""
Clean up a test suite by removing its test cases and run script
Parameters
----------
mpas_core : str
The MPAS core ('ocean', 'landice', etc.) of the test suite
suite_name : str
The name of the test suite. A file ``<suite_name>.txt`` must exist
within the core's ``suites`` package that lists the paths of the tests
in the suite
work_dir : str, optional
A directory that will serve as the base for creating test case
directories
"""
text = resources.read_text('compass.{}.suites'.format(mpas_core),
'{}.txt'.format(suite_name))
tests, _ = _parse_suite(text)
clean_cases(tests=tests, work_dir=work_dir, suite_name=suite_name)
def main():
parser = argparse.ArgumentParser(
description='Set up a regression test suite', prog='compass suite')
parser.add_argument("-c", "--core", dest="core",
help="The MPAS core for the test suite",
metavar="CORE", required=True)
parser.add_argument("-t", "--test_suite", dest="test_suite",
help="Path to file containing a test suite to setup",
metavar="SUITE", required=True)
parser.add_argument("-f", "--config_file", dest="config_file",
help="Configuration file for test case setup",
metavar="FILE")
parser.add_argument("-s", "--setup", dest="setup",
help="Option to determine if regression suite should "
"be setup or not.", action="store_true")
parser.add_argument("--clean", dest="clean",
help="Option to determine if regression suite should "
"be cleaned or not.", action="store_true")
parser.add_argument("-m", "--machine", dest="machine",
help="The name of the machine for loading machine-"
"related config options", metavar="MACH")
parser.add_argument("-b", "--baseline_dir", dest="baseline_dir",
help="Location of baseslines that can be compared to",
metavar="PATH")
parser.add_argument("-w", "--work_dir", dest="work_dir",
help="If set, script will setup the test suite in "
"work_dir rather in this script's location.",
metavar="PATH")
parser.add_argument("-p", "--mpas_model", dest="mpas_model",
help="The path to the build of the MPAS model for the "
"core.",
metavar="PATH")
parser.add_argument("--copy_executable", dest="copy_executable",
action="store_true",
help="If the MPAS executable should be copied to the "
"work directory")
args = parser.parse_args(sys.argv[2:])
if not args.clean and not args.setup:
raise ValueError('At least one of -s/--setup or --clean must be '
'specified')
if args.clean:
clean_suite(mpas_core=args.core, suite_name=args.test_suite,
work_dir=args.work_dir)
if args.setup:
setup_suite(mpas_core=args.core, suite_name=args.test_suite,
config_file=args.config_file, machine=args.machine,
work_dir=args.work_dir, baseline_dir=args.baseline_dir,
mpas_model_path=args.mpas_model,
copy_executable=args.copy_executable)
def _parse_suite(text):
""" Parse the text of a file defining a test suite """
tests = list()
cached = list()
for test in text.split('\n'):
test = test.strip()
if len(test) == 0 or test.startswith('#'):
# a blank line or comment
continue
if test == 'cached':
cached[-1] = ['_all']
elif test.startswith('cached:'):
steps = test[len('cached:'):].strip().split(' ')
cached[-1].extend(steps)
else:
tests.append(test)
cached.append(list())
return tests, cached
|
Java
|
UTF-8
| 125
| 2.140625
| 2
|
[] |
no_license
|
package hello_world;
public class Print {
public String printing() {
return "Hello World to the standard out";
}
}
|
Python
|
UTF-8
| 1,032
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
# code for pulling down uniprot sequence for predictions
import urllib3
from predictKappa.kappa_exceptions import KappaError
def fetch_sequence(uniprot_id):
"""
Function that returns the amino acid sequence by polling UniProt.com
Note that right now the test for success is a bit hap-hazard (looks for the
string "Sorry", which appears if the UniProt call fails. We probably want
something a bit more robust in the future...
Parameters
--------------
uniprot_id : str
Uniprot accession number
Returns
-----------
str or None:
If the call is succesfull, this returns the amino acid string. If not, it returns
None.
"""
http = urllib3.PoolManager()
r = http.request('GET', 'https://www.uniprot.org/uniprot/%s.fasta' % (uniprot_id))
s = "".join(str(r.data).split('\\n')[1:]).replace("'", "")
if s.find('Sorry') > -1:
raise MetapredictError('Error: unable to fetch UniProt sequence with accession %s'%(uniprot_id))
return s
|
C++
|
UTF-8
| 461
| 4.125
| 4
|
[] |
no_license
|
//Write a function that takes a string and reverses the letters in-place.
#include <iostream>
using namespace std;
void reverse(string& str) {
if(str.empty()) return;
size_t leftIndex = 0;
size_t rightIndex = str.length() - 1;
while(leftIndex < rightIndex) {
swap(str[leftIndex], str[rightIndex]);
++ leftIndex;
-- rightIndex;
}
}
int main() {
string str = "love";
cout << str << endl;
reverse(str);
cout << str << endl;
}
|
C++
|
UTF-8
| 4,878
| 3.203125
| 3
|
[] |
no_license
|
// This code was written by Ethan Haarer and Aidan Mundy. It handles
// huffman encoding for assignment 7 of cs106b at stanford.
#include "encoding.h"
#include "priorityqueue.h"
#include "strlib.h"
#include "filelib.h"
Map<char, int> buildFrequencyTable(istream& input){
Map<char, int> freqTable;
char ch;
// Tallies the character frequencies
while (input.get(ch)){
freqTable[ch] = freqTable[ch] + 1;
}
return freqTable;
}
HuffmanNode* buildEncodingTree(Map<char, int>& freqTable){
double treePriority;
HuffmanNode* one;
HuffmanNode* zero;
PriorityQueue<HuffmanNode*> order;
// Enqueues all of the initial huffman nodes.
for (char ch : freqTable){
order.enqueue(new HuffmanNode(ch), freqTable[ch]);
}
// Orders the nodes into a huffman tree
while(order.size() > 1){
treePriority = order.peekPriority();
zero = order.dequeue();
treePriority += order.peekPriority();
one = order.dequeue();
order.enqueue(new HuffmanNode(zero, one), treePriority);
}
// Sends the final remaining node as the resultant tree.
return order.dequeue();
}
string flattenTreeToHeader(HuffmanNode* t){
string header = "";
// Recursively runs a string builder that builds the header.
return (t->isLeaf() ?
"." + charToString(t->ch) :
"(" + flattenTreeToHeader(t->zero) + flattenTreeToHeader(t->one) + ")");
}
HuffmanNode* recreateTreeFromHeader(string str){
// Base case, one single character left.
if (str[0] == '.' && str.length() == 2){
return new HuffmanNode(str[1]);
} else { //recursive case
str = str.substr(1, str.length()-2);
HuffmanNode* zero = nullptr;
HuffmanNode* one = nullptr;
// If the left side is a leaf, this runs
if(str[0] == '.'){
zero = new HuffmanNode(str[1]);
one = recreateTreeFromHeader(str.substr(2));
} else { // Otherise this runs
int parenthesesIndex = 0;
// Counts and matches up parentheses.
for(int i = 0; i < str.length(); i++){
if(str[i] == '(') {
parenthesesIndex++;
} else if(str[i] == ')'){
parenthesesIndex--;
if(parenthesesIndex <=0){ //Once parentheses are matched, assign appropriate children.
zero = recreateTreeFromHeader(str.substr(0, i+1));
one = recreateTreeFromHeader(str.substr(i+1));
break;
}
}
}
}
return new HuffmanNode(zero, one);
}
}
void searchTree(Map<char, string>& encoding, const HuffmanNode* treePtr, string sequence){
if (treePtr->isLeaf()){ // Base Case
encoding[treePtr->ch] = sequence;
} else { // Recursive Case
searchTree(encoding, treePtr->zero, sequence + '0');
searchTree(encoding, treePtr->one, sequence + '1');
}
}
Map<char, string> buildEncodingMap(HuffmanNode* encodingTree){
Map<char, string> encodingMap;
searchTree(encodingMap, encodingTree, "");
return encodingMap;
}
void freeTree(HuffmanNode* t){
if(t->isLeaf()){ // Base case
delete t;
} else { // Recursive case
freeTree(t->zero);
freeTree(t->one);
delete t;
}
}
void compress(istream& input, HuffmanOutputFile& output){
Map<char, int> freqTable = buildFrequencyTable(input);
HuffmanNode* huffmanTree = buildEncodingTree(freqTable);
Map<char, string> encMap = buildEncodingMap(huffmanTree);
output.writeHeader(flattenTreeToHeader(huffmanTree));
rewindStream(input); // Rewunds stream to beginning
char ch;
while (input.get(ch)){ // Writes each character's bits.
for(char bit : encMap[ch]){
output.writeBit(charToInteger(bit));
}
}
freeTree(huffmanTree);
}
void decompress(HuffmanInputFile& input, ostream& output){
HuffmanNode* huffmanTree = recreateTreeFromHeader(input.readHeader());
Map<char, string> encMap = buildEncodingMap(huffmanTree);
Map<string, char> revEncMap;
for(char oldKey : encMap.keys()){ // Reverse map of binary to characters.
revEncMap[encMap[oldKey]] = oldKey;
}
string tempString = "";
int bit = input.readBit();
while(bit != -1){ // Reads each characters bits
tempString += integerToString(bit);
if(revEncMap.containsKey(tempString)){ // If a character is found, search for next character and output this one.
output << revEncMap[tempString];
tempString = "";
}
bit = input.readBit();
}
freeTree(huffmanTree);
}
|
Markdown
|
UTF-8
| 2,427
| 2.875
| 3
|
[] |
no_license
|
# GitLab Single-Sign-On
___
Single-Sign-On can be configured with the following services.
## GitLab
Follow these steps to configure Mattermost to use GitLab as a single-sign-on (SSO) service for team creation, account creation and sign-in.
1. Login to your GitLab account and under **Profile Settings** go to **Applications**.
2. Add a new application called "Mattermost" with the following as Redirect URIs:
* `<your-mattermost-url>/login/gitlab/complete` (example: http://localhost:8065/login/gitlab/complete)
* `<your-mattermost-url>/signup/gitlab/complete`
Note: If your GitLab instance is set up to use SSL, your URIs must begin with `https://`. Otherwise, use `http://`.
3. Submit the application and copy the given _Id_ and _Secret_ into the appropriate _GitLabSettings_ fields in `config/config.json`
4. Also in `config/config.json`, set _Enable_ to `true` for the _gitlab_ section, leave _Scope_ blank and use the following for the endpoints:
* _AuthEndpoint_: `https://<your-gitlab-url>/oauth/authorize` (example https://example.com/oauth/authorize)
* _TokenEndpoint_: `https://<your-gitlab-url>/oauth/token`
* _UserApiEndpoint_: `https://<your-gitlab-url>/api/v3/user`
Note: Make sure your `HTTPS` or `HTTP` prefix for endpoint URLs matches your server configuration.
5. (Optional) If you would like to force all users to sign-up with GitLab only, in the _ServiceSettings_ section of `config/config.json` set _DisableEmailSignUp_ to `true`.
6. Restart your Mattermost server to see the changes take effect.
#### Notes:
- Only the default GitLab SSO is officially supported. "Double SSO", chaining GitLab SSO to other SSO solutions, is not supported.
- It may be possible to connect to use GitLab SSO in some cases with AD, LDAP, SAML, or MFA add-ons, but because of the special logic required they're not officially supported and are known not to work on some experiences.
- If having official AD, LDAP, SAML or MFA support is critical to your enterprise, please consider purchasing [Mattermost Enterprise Edition](https://about.mattermost.com/pricing/). Given all the features of Mattermost, it's quite affordable.
- See [GitLab section of Mattermost forum for troubleshooting help](https://forum.mattermost.org/c/general/gitlab).
- See [GitLab Omnibus documentation for installing GitLab Mattermost](http://doc.gitlab.com/omnibus/gitlab-mattermost/).
|
C#
|
UTF-8
| 739
| 2.609375
| 3
|
[
"AGPL-3.0-only"
] |
permissive
|
using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;
namespace WorldWebServer.Models {
public class WorldDbContext : DbContext {
public WorldDbContext(DbContextOptions<WorldDbContext> options)
: base(options) { }
public DbSet<Country> Country { get; set; }
public DbSet<City> City { get; set; }
}
public class WorldDbContextFactory {
public static WorldDbContext Create(string connectionStirng) {
var optionsBuilder = new DbContextOptionsBuilder<WorldDbContext>();
optionsBuilder.UseMySQL(connectionStirng);
var dbContext = new WorldDbContext(optionsBuilder.Options);
return dbContext;
}
}
}
|
Java
|
UTF-8
| 1,374
| 2.625
| 3
|
[] |
no_license
|
package tools;
import mons.Category;
import mons.Dex;
import mons.Move;
import mons.Type;
public class MovedexXmlParser extends AbstractXmlParser {
private Move fMove = null;
public MovedexXmlParser(String filePath) {
super(filePath);
parse();
}
@Override
protected void handleElement(String key, String value) {
if (key.equals("move")) {
fMove = new Move();
} else if (key.equals("name")) {
fMove.setName(value);
} else if (key.equals("type")) {
fMove.setType(Type.valueOf(value));
} else if (key.equals("category")) {
fMove.setCategory(value.contentEquals("") ? Category.Other : Category.valueOf(value));
} else if (key.equals("pp")) {
try {
fMove.setPp(Integer.parseInt(value));
} catch (NumberFormatException e) {
fMove.setPp(1000);
}
} else if (key.equals("maxpp")) {
fMove.setMaxpp(Integer.parseInt(value));
} else if (key.equals("power")) {
try {
fMove.setPower(Integer.parseInt(value));
} catch (NumberFormatException e) {
fMove.setPower(0);
}
} else if (key.equals("accuracy")) {
try {
fMove.setAccuracy(Integer.parseInt(value));
} catch (NumberFormatException e) {
fMove.setAccuracy(101);
}
} else if (key.equals("description")) {
fMove.setDescription(value);
Dex.MOVES.put(fMove.getName(), fMove);
}
}
}
|
C++
|
UTF-8
| 6,772
| 2.8125
| 3
|
[] |
no_license
|
#include "common/hiString.h"
#include <stdio.h>
#include <algorithm>
#include <functional>
#include <sstream>
#include <string>
using namespace std;
#define Hi_String_H_NOT_SUPPORT() \
stringstream oss;\
oss<<"function "<<__FUNCTION__<<" not support for linux";\
string text = oss.str();\
printf("function %s not support for linux\n", __FUNCTION__); \
throw text.c_str()
static bool u82uc(const char* str, wstring& content)
{
#ifdef WINDOWS_
int textlen ;
wchar_t * result;
textlen = MultiByteToWideChar( CP_UTF8, 0, str,-1, NULL,0 );
result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));
::memset(result,0,(textlen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0,str,-1,(LPWSTR)result,textlen);
content = result;
free(result);
#endif
#ifdef LINUX_
Hi_String_H_NOT_SUPPORT();
#endif
return true;
}
static bool uc2as(const wchar_t* str, string& content)
{
#ifdef WINDOWS_
char* result;
int textlen;
textlen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
result =(char *)malloc((textlen+1)*sizeof(char));
memset( result, 0, sizeof(char) * ( textlen + 1 ) );
WideCharToMultiByte( CP_ACP, 0, str, -1, result, textlen, NULL, NULL );
content = result;
free(result);
#endif
#ifdef LINUX_
Hi_String_H_NOT_SUPPORT();
#endif
return true;
}
static bool u82as(const char* str, string& content)
{
wstring temp;
u82uc(str, temp);
return uc2as(temp.c_str(), content);
}
static bool as2uc(const char* str, wstring& content)
{
#ifdef WINDOWS_
int textlen ;
wchar_t * result;
textlen = MultiByteToWideChar(CP_ACP, 0, str,-1, NULL,0 );
result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));
::memset(result,0,(textlen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0,str,-1,(LPWSTR)result,textlen);
content = result;
free(result);
#endif
#ifdef LINUX_
Hi_String_H_NOT_SUPPORT();
#endif
return true;
}
static bool uc2u8(const wchar_t* str, string& content)
{
#ifdef WINDOWS_
char* result;
int textlen;
textlen = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL );
result =(char *)malloc((textlen+1)*sizeof(char));
memset( result, 0, sizeof(char) * ( textlen + 1 ) );
WideCharToMultiByte( CP_UTF8, 0, str, -1, result, textlen, NULL, NULL );
content = result;
free(result);
#endif
#ifdef LINUX_
Hi_String_H_NOT_SUPPORT();
#endif
return true;
}
static bool as2u8(const char* str, string& content)
{
wstring temp;
as2uc(str, temp);
return uc2u8(temp.c_str(), content);
}
namespace Hi
{
HI_COMMON_LIB_API wstring u82uc(const char* str)
{
wstring temp;
if (::u82uc(str, temp))
{
return temp;
}
return L"";
}
HI_COMMON_LIB_API string uc2as(const wchar_t* str)
{
string temp;
if (::uc2as(str, temp))
{
return temp;
}
return "";
}
HI_COMMON_LIB_API string u82as(const char* str)
{
string temp;
if (::u82as(str, temp))
{
return temp;
}
return "";
}
HI_COMMON_LIB_API string as2u8(const char* str)
{
string temp;
if (::as2u8(str, temp))
{
return temp;
}
return "";
}
HI_COMMON_LIB_API wstring as2uc(const char* str)
{
wstring temp;
if (::as2uc(str, temp))
{
return temp;
}
return L"";
}
HI_COMMON_LIB_API string uc2u8(const wchar_t* str)
{
string temp;
if (::uc2u8(str, temp))
{
return temp;
}
return "";
}
struct IPv4
{
unsigned char ip3;
unsigned char ip2;
unsigned char ip1;
unsigned char ip0;
};
HI_COMMON_LIB_API unsigned int ip2uint(const char* ip)
{
IPv4 ipv4;
memset(&ipv4, 0, sizeof(IPv4));
string strIP = ip;
stringstream iss(ip);
int val = -1;
iss>>val;
if (val >= 0)
{
ipv4.ip0 = val;
}
string::size_type pos = strIP.find('.');
iss.seekg(pos + 1);
val = -1;
iss>>val;
if (val >= 0)
{
ipv4.ip1 = val;
}
pos = strIP.find('.', pos + 1);
iss.seekg(pos + 1);
val = -1;
iss>>val;
if (val >= 0)
{
ipv4.ip2 = val;
}
pos = strIP.find('.', pos + 1);
iss.seekg(pos + 1);
val = -1;
iss>>val;
if (val >= 0)
{
ipv4.ip3 = val;
}
unsigned int ret = 0;
memcpy(&ret, &ipv4, sizeof(IPv4));
return ret;
}
HI_COMMON_LIB_API string uint2ip(unsigned int ip)
{
IPv4 ipv4;
memcpy(&ipv4, &ip, sizeof(IPv4));
stringstream oss;
oss<<(int)ipv4.ip0<<"."<<(int)ipv4.ip1<<"."<<(int)ipv4.ip2<<"."<<(int)ipv4.ip3;
return oss.str();
}
static bool replace_if_pr_2(char itor, char old)
{
if (itor == old)
{
return true;
}
return false;
}
HI_COMMON_LIB_API bool replace(string& source, const char* old, const char* newStr)
{
if (::strlen(old) == 1 && ::strlen(newStr) == 1)
{
replace_if(source.begin(), source.end(),
bind2nd(ptr_fun(replace_if_pr_2), *old), *newStr);
return true;
}
string s1(old);
string s2(newStr);
if (s1 == s2)
{
return true;
}
string::size_type pos = source.find(s1);
while (pos != string::npos)
{
source.replace(pos, s1.size(), s2);
pos = source.find(old);
}
return true;
}
HI_COMMON_LIB_API void toLower(string& source)
{
transform(source.begin(), source.end(), source.begin(), ::tolower);
}
HI_COMMON_LIB_API void toUpper(string& source)
{
transform(source.begin(), source.end(), source.begin(), ::toupper);
}
HI_COMMON_LIB_API string toLower(const char* source)
{
string dst = source;
toUpper(dst);
return dst.c_str();
}
HI_COMMON_LIB_API string toUpper(const char* source)
{
string dst = source;
toUpper(dst);
return dst.c_str();
}
HI_COMMON_LIB_API void split(const char* ch, const char* token, vector<string>& dest)
{
int nend=0;
int nbegin=0;
string src = ch;
string temp;
while(nend != -1)
{
nend = src.find_first_of(token, nbegin);
if(nend == -1)
{
temp = src.substr(nbegin, src.length() - nbegin);
if (!temp.empty())
{
dest.push_back(temp.c_str());
}
}
else
{
temp = src.substr(nbegin, nend - nbegin);
dest.push_back(temp.c_str());
}
nbegin = nend + 1;
}
}
HI_COMMON_LIB_API std::string time2string(__time32_t t)
{
if (t == 0)
{
t = time(NULL);
}
struct tm* st = localtime(&t);
char arr[24];
memset(arr, 0, sizeof(arr));
strftime(arr, 24, "%2Y-%2m-%2d %2H:%2M:%2S", st);
return arr;
}
HI_COMMON_LIB_API __time32_t string2time(const char* t)
{
if (!t || ::strlen(t) > 19 || ::strlen(t) < 14)
{
return 0;
}
struct tm tm1;
__time32_t time1;
sscanf(t, "%d-%d-%d %d:%d:%d",
&tm1.tm_year,
&tm1.tm_mon,
&tm1.tm_mday,
&tm1.tm_hour,
&tm1.tm_min,
&tm1.tm_sec);
tm1.tm_year -= 1900;
tm1.tm_mon --;
tm1.tm_isdst=-1;
#ifdef WINDOWS_
time1 = _mktime32(&tm1);
#endif
#ifdef LINUX_
time1 = mktime(&tm1);
#endif
return time1;
}
}
|
Java
|
UTF-8
| 1,281
| 3.640625
| 4
|
[] |
no_license
|
package stacks_queues;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class StockSpan {
public static void display(int[] a) {
StringBuilder sb = new StringBuilder();
for (int val : a) {
sb.append(val + "\n");
}
System.out.println(sb);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(br.readLine());
}
int[] span = stockSpan(a);
display(span);
}
public static int[] stockSpan(int[] arr) {
int length = arr.length;
int[] res = new int[length];
res[0] = 1;
Stack<Integer> st = new Stack<>();
st.push(0);
for (int i = 1; i < length; i++) {
while (!st.isEmpty() && arr[st.peek()] <= arr[i]) {
st.pop();
}
if (st.isEmpty()) {
res[i] = i + 1;
} else {
res[i] = i - st.peek();
}
st.push(i);
}
return res;
}
}
|
Java
|
UTF-8
| 2,226
| 2.390625
| 2
|
[] |
no_license
|
package com.sxdubbo.learn.utils;
import com.sxdubbo.learn.domain.TestPaperPO;
import com.sxdubbo.learn.domain.CoursePO;
import com.sxdubbo.learn.domain.UserPO;
import com.sxdubboapi.learn.domain.TestPaper;
import com.sxdubboapi.learn.domain.Course;
import com.sxdubboapi.learn.domain.User;
import org.springframework.beans.BeanUtils;
import java.util.List;
/**
* created by luwei
* 2018-03-06 11:15.
**/
public class BeanTransferTestPaper {
public static List<TestPaper> transferTestPaperList(List<TestPaperPO> testPaperPOList,List<TestPaper> testPaperList){
for(int i = 0 ; i < testPaperPOList.size() ; i++) {
TestPaper testPaper = new TestPaper();
User user = new User();
Course course1 = new Course();
BeanUtils.copyProperties(testPaperPOList.get(i).getUserPO(),user);
BeanUtils.copyProperties(testPaperPOList.get(i).getCoursePO(),course1);
System.out.println("testpaper");
BeanUtils.copyProperties(testPaperPOList.get(i), testPaper);
testPaper.setUser(user);
testPaper.setCourse(course1);
testPaperList.add(testPaper);
}
return testPaperList;
}
public static TestPaperPO transferTestPaper(TestPaper testPaper,TestPaperPO testPaperPO){
UserPO userPO = new UserPO();
CoursePO coursePO = new CoursePO();
BeanUtils.copyProperties(testPaper.getUser(),userPO);
BeanUtils.copyProperties(testPaper.getCourse(),coursePO);
BeanUtils.copyProperties(testPaper, testPaperPO);
System.out.println("testpaper");
testPaperPO.setUserPO(userPO);
testPaperPO.setCoursePO(coursePO);
return testPaperPO;
}
public static TestPaper transferTestPaper(TestPaperPO testPaperPO,TestPaper testPaper){
User user = new User();
Course course = new Course();
BeanUtils.copyProperties(testPaperPO.getUserPO(),user);
BeanUtils.copyProperties(testPaperPO.getCoursePO(),course);
BeanUtils.copyProperties(testPaperPO, testPaper);
System.out.println("testpaper");
testPaper.setUser(user);
testPaper.setCourse(course);
return testPaper;
}
}
|
C++
|
UTF-8
| 1,182
| 2.71875
| 3
|
[] |
no_license
|
// ---------------------------------------------------------------------------
// Created by Gus Yudha on 27/05/2020
// ---------------------------------------------------------------------------
long unsigned int inputLOW;
long unsigned int jeda = 5000;
boolean tetapkanLOW = true;
boolean lamaLOW;
int pirPin = 8;
int ledPin = 4;
void setup(){ //-----------------SETUP
//Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, LOW);
delay(50);
}
void loop(){ //-----------------LOOP
if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, HIGH);
//Serial.println("Ada yang Bergerak");
if(tetapkanLOW){
tetapkanLOW = false;
delay(50);
}
lamaLOW = true;
}
if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW);
//Serial.println("Tidak Ada yang Bergerak");
if(lamaLOW){
inputLOW = millis();
lamaLOW = false;
}
if(!tetapkanLOW && millis() - inputLOW > jeda){
tetapkanLOW = true;
delay(50);
}
}
}
|
Java
|
UTF-8
| 1,230
| 2.8125
| 3
|
[] |
no_license
|
public enum KindSkiPass {
DAY1, DAYS2, DAYS5, HOISTS10, HOISTS20, HOISTS50, HOISTS100, SUBSCRIPTION;
int toInt() {
switch (this) {
case DAY1:
return 1;
case DAYS2:
return 2;
case DAYS5:
return 5;
case HOISTS10:
return 10;
case HOISTS20:
return 20;
case HOISTS50:
return 50;
case HOISTS100:
return 100;
case SUBSCRIPTION:
return 1000;
default:
return 0;
}
}
String skipass_type() {
switch (this) {
case DAY1:
return "day";
case DAYS2:
return "day";
case DAYS5:
return "day";
case HOISTS10:
return "hoist";
case HOISTS20:
return "hoist";
case HOISTS50:
return "hoist";
case HOISTS100:
return "hoist";
case SUBSCRIPTION:
return "subscription";
default:
return "hoist";
}
}
}
|
JavaScript
|
UTF-8
| 1,138
| 2.625
| 3
|
[] |
no_license
|
'use strict';
(() => {
const filter = document.querySelector('.filter');
const faqAccordion = document.querySelector('.faq');
if (faqAccordion) {
const faqAccordionItems = document.querySelectorAll('.faq__item dt');
const faqToggles = document.querySelectorAll('.faq__toggle');
faqAccordion.classList.remove('faq--nojs');
faqAccordionItems.forEach((item, index) => {
item.addEventListener('click', () => {
item.parentElement.classList.toggle('faq__item--opened');
faqToggles[index].classList.toggle('faq__toggle--opened');
});
});
}
if (filter) {
const filterAccordion = document.querySelectorAll('.filter__heading');
const filterButton = document.querySelectorAll('.filter__list-toggle');
const filterLists = document.querySelectorAll('.filter__list');
filter.classList.remove('filter--nojs');
filterAccordion.forEach((item, index) => {
item.addEventListener('click', () => {
filterLists[index].classList.toggle('filter__list--opened');
filterButton[index].classList.toggle('filter__list-toggle--opened');
})
})
}
})()
|
TypeScript
|
UTF-8
| 924
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import { Injectable } from '@angular/core';
@Injectable()
export class UtilService {
// constructor(){}
public getVideo(url: string, quality?: number) {
if (quality) {
return url + '?q=' + quality;
} else {
return url;
}
}
/**
* @param mimeType
* @returns {string}
*/
public getFileType(mimeType: string) {
return mimeType.replace(/\/(.*)/, '');
}
public getFullUrl(baseUrl: string, file: any, size?: string) {
let type: string;
if (this.getFileType(file.metaData.mimeType) === 'video') {
type = 'video';
} else {
type = 'files';
}
let sz = size ? `?s=${size}` : '';
return `${baseUrl}/${type}/${file.id}/${file.name}${sz}`;
}
public getMaxValue(arr: number[]) {
console.log(Math.max(...arr));
return Math.max(...arr);
}
}
|
PHP
|
UTF-8
| 1,859
| 2.75
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/3/14 0014
* Time: 21:01
*/
class NewsModel extends BaseModel{
const TYPE_ARR = [
'0'=>'公告',
'1'=>'活动',
'2'=>'攻略'
];
/**
* 查询列表
* @return array|bool
* @throws Exception
*/
public function getList($paramArr){
//分页
$page = 1;
$pageSize = 20;
if(isset($paramArr['page'])){
$page = $paramArr['page'];
}
if(isset($paramArr['pageSize'])){
$pageSize = $paramArr['pageSize'];
}
$sql = 'select id, title, type, publish_time from by_news where status=?';
$valArr = ['yifabu'];
if(isset($paramArr['type'])){
$sql .= ' and type=?';
array_push($valArr, $paramArr['type']);
}
//获取记录总数
$countSql = preg_replace('/select .* from/', 'select count(1) as cnt from', $sql);
$total = $this->DB()->query_fetch($countSql, $valArr);
$pageCount = ceil($total['cnt']/$pageSize);
//排序
$sql .= ' order by publish_time desc';
$sql .= ' limit ' . ($page-1) * $pageSize . ',' . $pageSize;
$result = $this->DB()->query($sql, $valArr);
//重构数据
foreach ($result as $key=>$item) {
$result[$key]['type'] = self::TYPE_ARR[$item['type']];
}
return ['pageCount'=>$pageCount, 'total'=>$total['cnt'], 'data'=>$result, 'result'=>0];
}
public function getDetail($newsId){
$sql = <<<SQL
select id, title, content, type, publish_time from by_news where id=?
SQL;
$result = $this->DB()->query_fetch($sql, [$newsId]);
//重构数据
$result['type'] = self::TYPE_ARR[$result['type']];
return $result;
}
}
|
Java
|
UTF-8
| 960
| 2.15625
| 2
|
[] |
no_license
|
package org.taxidriver.api.models.responses;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.taxidriver.api.models.simple.DriverDetail;
public class AuthorizationResponse {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("driver_id")
@Expose
private Integer driverId;
@SerializedName("driver_detail")
@Expose
private DriverDetail driverDetail;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getDriverId() {
return driverId;
}
public void setDriverId(Integer driverId) {
this.driverId = driverId;
}
public DriverDetail getDriverDetail() {
return driverDetail;
}
public void setDriverDetail(DriverDetail driverDetail) {
this.driverDetail = driverDetail;
}
}
|
JavaScript
|
UTF-8
| 1,457
| 2.625
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
export default class ProductFilter extends Component {
constructor(props) {
super(props);
this.state = {
userInput: ''
};
// Handlers
this.handleUserInput = this.handleUserInput.bind(this);
this.handleUserSearch = this.handleUserSearch.bind(this);
}
handleUserInput(value) {
this.setState({
userInput: value
});
}
handleUserSearch(e) {
// Evitamos que el formulario envie la data al servidor y refresque la pagina
e.preventDefault();
// Invocamos a la funcion del padre enviada como parametro en props
this.props.onProductFilter(this.state.userInput);
// Limpiamos valor para futuras busquedas
this.setState({
userInput: ''
});
}
render() {
return (
<div className="row justify-content-center">
<div className="col-xs-8 pt-3 mb-3">
<form className="form-inline" onSubmit={e => this.handleUserSearch(e)}>
<div className="form-group mx-sm-3 mb-2">
<input
type="text"
className="form-control"
onChange={e => this.handleUserInput(e.target.value)}
placeholder="Que estas buscando?"
value={this.state.userInput}
/>
</div>
<button type="submit" className="btn btn-primary mb-2">Buscar</button>
</form>
</div>
</div>
);
}
}
|
Markdown
|
UTF-8
| 2,678
| 2.921875
| 3
|
[] |
no_license
|
# Autonomous vehicle

## Dependencies
* Docker
* Ubuntu 18.04 or Ubuntu 20.04
## Goal
The goal of the project was to add the following functionalities to a simulated car in gazebo environment:
* Steering with keyboard/joystick
* First person visualisation
* Collecting visual data
* Autonomous drive
## How does it work?
The following diagram shows the idea behind the entire system:

* Prius - Vehicle's velocity, steering, front camera image and steering inputs
* Joy/Keyboard - Controls the vehicle, allows to turn data collection on/off and to choose between manual and autonomous steering
* Visualisation - Shows front's camera image, vehicles velocity and current steering
* Dataset - A dataset of collected images and its labels - steering and velocity
* Generate model - A Python script that uses collected data to create a CNN model
* CNN model - A generated model that uses front camera's image to predict vehicle's velocity and steering
* PID controller - An addition to predicted velocity, allows to modify vehicle's performance after the model is trained.
## Convolutional Neural Network
Three convolutional networks models were considered during the implementation
* ResNet
* EfficientNet
* [Network by github.com/maxritter](https://github.com/maxritter/SDC-End-to-end-driving?fbclid=IwAR3Md7GCu1JMYJ-xzSEOihjX94t30AZDxypfHpQWLQ1J06Dri437TFBLtrY)
The third, customised architecture seemed to give the best results. With a modification of a few layers, the network was ready for training. The initial data collected from the front camera had the dimensions of 800x800. Because most of the image contained the sky and vehicle's hood, only 220x800 part of the image was taken into account and then resized to 200x200 RGB image.
Architecture of the created model:

The `train/CNN.py` script includes the preprocessing and training of the CNN model.
## Scripts
The scripts are contained in `av_07/scripts`. Every Python script creates an individual rosnode and subscribes/publishes following data:
* controller_node - Subscribes the input from joystick/keyboard, allows to control the vehicle, turn on the data collection and autonomous steering
* states_node - Subscribes car's global x,y,z velocities and publishes them as one vector
* visualiser_node - Subscribes car's front camera image, and its current parameters and displays them in a new window
* collector_node - Subscribes car's front camera image, its current velocity and steer and saves them in data folder
* control_prediction_node - Subscribes car's front camera image and predicts its velocity and steer using the CNN model
|
Markdown
|
UTF-8
| 710
| 2.578125
| 3
|
[] |
no_license
|
# General instructions
Programs can be written in any language, In addition to the program,
you should have a writeup that contains the plots requested in the
homework questions, answers to any analytical or explanation
questions, and a short description of your code and how to run
it. This can be done in, e.g., LaTeX, markdown, etc. Code and
writeup should be submitted using git via github in the repo
that was created from github classroom link
# Instructions for turning in via github classroom:
To access the Homework2 repository, navigate to the following link: [https://classroom.github.com/a/29DKsW-W](https://classroom.github.com/a/29DKsW-W). The deadline is **Sept. 30, 2021 at 23:00**.
|
Java
|
UTF-8
| 1,231
| 3.359375
| 3
|
[] |
no_license
|
public class merge {
public void sort(int arr[], int left, int right) {
if(left < right)
{
int mid = (left+right)/2;
sort(arr, 0, mid);
sort(arr, mid+1, right);
merger(arr, left, right, mid);
}
}
public void merger(int arr[], int left, int right, int mid)
{
int n1 = mid-left+1;
int n2 = right-mid;
int[] lArray = new int[n1];
int[] rArray = new int[n2];
for(int i = 0; i< n1; ++i)
{
lArray[i] = arr[left+i];
}
for(int j = 0; j<n2; ++j)
{
rArray[j] = arr[mid + 1 + j];
}
int i = 0, j= 0;
int k = left;
while(i<n1 && j<n2)
{
if(lArray[i] > rArray[j])
{
arr[k] = rArray[j];
j++;
}else
{
arr[k] = lArray[i];
i++;
}
}
while (i < n1)
{
arr[k] = lArray[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = rArray[j];
j++;
k++;
}
display(arr);
}
public void display(int[] arr) {
for(int i = 0; i<arr.length; i++)
System.out.println(arr[i]);
}
}
|
Java
|
UTF-8
| 2,414
| 2.234375
| 2
|
[] |
no_license
|
package com.softsystem.backend.model;
import javax.persistence.*;
@Entity
@Table(name = "Bet")
public class Bet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_bet")
private Long id;
@Column(name = "amount")
private float amount;
@Column(name = "betResult")
private Boolean betResult;
@Column(name = "prize")
private float prize;
@Column(name = "result")
private String result;
@Column(name = "is_general")
private Boolean isGeneral;
@JoinColumn(name = "id_member")
@ManyToOne
private Member member;
@JoinColumn(name = "id_event")
@ManyToOne
private Event event;
@JoinColumn(name = "id_user")
@ManyToOne
private User user;
public Bet(float amount, Boolean betResult, float prize, String result, Boolean isGeneral, Member member, Event event, User user) {
this.amount = amount;
this.betResult = betResult;
this.prize = prize;
this.result = result;
this.isGeneral = isGeneral;
this.member = member;
this.event = event;
this.user = user;
}
public Bet() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public Boolean getBetResult() {
return betResult;
}
public void setBetResult(Boolean betResult) {
this.betResult = betResult;
}
public float getPrize() {
return prize;
}
public void setPrize(float prize) {
this.prize = prize;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Boolean getGeneral() {
return isGeneral;
}
public void setGeneral(Boolean general) {
isGeneral = general;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
|
Java
|
UTF-8
| 550
| 1.96875
| 2
|
[] |
no_license
|
package ulas.hrmsDemo.business.abstracts;
import org.springframework.web.multipart.MultipartFile;
import ulas.hrmsDemo.core.utilities.results.DataResult;
import ulas.hrmsDemo.core.utilities.results.Result;
import ulas.hrmsDemo.entities.concretes.CurriculumViate;
import java.util.List;
public interface CurriculumViateService {
DataResult<List<CurriculumViate>> getAll();
Result add(CurriculumViate curriculumViate);
Result saveImage(MultipartFile file, int cvId);
DataResult<List<CurriculumViate>> getByCandidateId(int id);
}
|
Java
|
UTF-8
| 2,437
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* SPDX-FileCopyrightText: 2020 DB Station&Service AG <bahnhoflive-opensource@deutschebahn.com>
*
* SPDX-License-Identifier: Apache-2.0
*/
package de.deutschebahn.bahnhoflive.ui;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewAnimator;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import de.deutschebahn.bahnhoflive.R;
public class LoadingContentDecorationViewHolder extends RecyclerView.ViewHolder {
private static final int CHILD_CONTENT = 0;
private static final int CHILD_PROGRESS = 1;
private static final int CHILD_ERROR = 2;
private static final int CHILD_EMPTY = 3;
private final ViewAnimator container;
private final TextView errorTextView;
private final TextView emptyTextView;
public LoadingContentDecorationViewHolder(View itemView, int container, int errorText, int emptyText) {
super(itemView);
this.container = itemView.findViewById(container);
this.errorTextView = itemView.findViewById(errorText);
this.emptyTextView = itemView.findViewById(emptyText);
showProgress();
}
public LoadingContentDecorationViewHolder(View itemView) {
this(itemView, R.id.view_flipper, R.id.error_message, R.id.empty_message);
}
public void showContent() {
showChild(CHILD_CONTENT);
}
public void showProgress() {
showChild(CHILD_PROGRESS);
}
public void showError(@Nullable CharSequence message) {
final TextView errorTextView = this.errorTextView;
if (errorTextView != null) {
if (message != null) {
errorTextView.setText(message);
} else {
errorTextView.setText(R.string.error_data_unavailable);
}
}
showError();
}
public void showChild(int child) {
if (container.getChildCount() > child) {
container.setDisplayedChild(child);
}
}
public void showError() {
showChild(CHILD_ERROR);
}
public void showEmpty(CharSequence message) {
if (emptyTextView != null) {
emptyTextView.setText(message);
}
showEmpty();
}
public void showEmpty() {
showChild(CHILD_EMPTY);
}
public void showEmpty(int message) {
if (emptyTextView != null) {
emptyTextView.setText(message);
}
showEmpty();
}
}
|
Shell
|
UTF-8
| 168
| 3.3125
| 3
|
[] |
no_license
|
read -p "Enter number : " n
i=1
sum=0
echo "Digits : "
while [ $i -le $n ]
do
echo "$i"
sum=$(( $sum + $i ))
i=$(( $i + 1 ))
done
echo "Sum = $sum"
|
Shell
|
UTF-8
| 492
| 3.703125
| 4
|
[] |
no_license
|
#!/bin/sh
if [ x"$2" = x ]; then
echo "Usage: $0 <cidr> <owner> [<ns[/nsip]>...]" >&2; exit 255
fi
cidr="$1"
hex=$($(dirname "$0")/cidr2hex "$cidr") || exit 1
dir=db/ip/"$hex"
if [ -e "$dir" ]; then
echo "Refusing to clobber existing record" >&2; exit 1
fi
mkdir -p "$dir" || exit 1
echo "$cidr" > "$dir"/cidr
echo "$2" > "$dir"/owner
mkdir "$dir"/ns || exit 1
shift; shift;
while [ x"$1" != x ]; do
echo "$1" | tr / ' ' | (
read ns nsip
echo "$nsip" > "$dir/ns/$ns"
)
shift;
done
|
Python
|
UTF-8
| 1,015
| 2.703125
| 3
|
[] |
no_license
|
import requests
from lxml import etree
def get_text(url_start):
headers = {
'USER-AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
response =requests.get(url = url_start,headers = headers)
if response:
html = response.text
return html
else:
return None
def get_real_url(html):
list = []
html = etree.HTML(html)
result = html.xpath('//*[@id="content"]/div/div[1]/div[1]/div/attribute::data-cid')
for item in result:
url = 'https://movie.douban.com/j/review/'+str(item)+'/full'
list.append(url)
return list
def get_authods(list):
for url in list:
response = requests.get(url)
result = response.json()
#print(result['html'].replace('<p>','').replace('</p>',''))
html = get_text(url_start = 'https://movie.douban.com/review/best/')
list = get_real_url(html)
a = get_authods(list)
print(a)
#authods = html.xpath('')
#print(authods)
|
Java
|
UTF-8
| 399
| 2.203125
| 2
|
[] |
no_license
|
package com.cc.cart.controller.bean;
public class CartItem {
private int itemId;
private int cartId;
public int getItemId() {
return itemId;
}
public void setItemId(final int itemId) {
this.itemId = itemId;
}
public int getCartId() {
return cartId;
}
public void setCartId(final int cartId) {
this.cartId = cartId;
}
}
|
Python
|
UTF-8
| 538
| 3.296875
| 3
|
[] |
no_license
|
"""
@author Lucas
@date 2019/4/3 14:07
"""
def reverseArray():
NandM = str(input())
n = int(NandM.split(" ")[0])
m = int(NandM.split(" ")[1])
# array = []
# for i in range(1, n+1):
# array.append(i)
#
# for i in range(len(array)):
# if i % (2*m) == 0:
# for j in range(m):
# array[i+j] = -array[i+j]
# print(array)
#
# sum = 0
# for i in array:
# sum += i
# print(sum)
print(m*n/2)
if __name__ == '__main__':
reverseArray()
|
PHP
|
UTF-8
| 723
| 2.53125
| 3
|
[] |
no_license
|
<?php
namespace App\Http\Controllers;
use App\Models\Admin\Tipo;
use Illuminate\Http\Request;
class TipoController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/*
* Obtener todos los registros de la tabla TIPOS
*
* @return \Illuminate\Http\Response
*/
public function tipos(){
$tipos = Tipo::select('id as value', 'nombre as text')
->orderBy('id','asc')
->get()
->toArray();
array_unshift($tipos,['value' =>'', 'text' => '']);
return $tipos;
// return response()->json([
// 'tipos' => Tipo::orderBy('id','asc')->get()
// ]);
}
}
|
Shell
|
UTF-8
| 607
| 3.03125
| 3
|
[] |
no_license
|
#!/bin/sh
printf "#################################\n### Installing MySQL\n#################################\n"
# Install MySQL Server in a Non-Interactive mode
echo "mysql-server mysql-server/root_password password $DB_PASSWORD" | debconf-set-selections
echo "mysql-server mysql-server/root_password_again password $DB_PASSWORD" | debconf-set-selections
apt-get -y install mysql-server
service mysql restart
mysql -uroot -p${DB_PASSWORD} -e 'USE mysql; UPDATE `user` SET `Host`="%" WHERE `User`="root" AND `Host`="localhost"; DELETE FROM `user` WHERE `Host` != "%" AND `User`="root"; FLUSH PRIVILEGES;'
|
PHP
|
UTF-8
| 6,411
| 3.234375
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: Alfie
* Date: 2016/04/14
* Time: 8:04 PM
*/
class page
{
// page title
private $title = '';
// template tags
private $tags = array();
// tags which should be processed after the page has been parsed
// reason: what if there are template tags within the database
//content, we must parse the page, then parse it again for post parse tags
private $postParseTags = array();
//template bits
private $bits = array();
// the page content
private $content = "";
private $apd = array();
/**
* Create our page object
*/
function __construct(Registry $registry)
{
$this->registry = $registry;
}
/**
* Get the page title from the page
* @return String
*/
public function getTitle()
{
return $this->title;
}
/**
* Set the page title
* @param String $title the page title
* @return void
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Set the page content
* @param String $content the page content
* @return void
*/
public function setContent($content)
{
$this->content = $content;
}
/**
* Add a template tag, and its replacement value/data to the page
* @param String $key the key to store within the tags array
* @param String $data the replacement data (may also be an array)
* @return void
*/
public function addTag($key, $data)
{
$this->tags[$key] = $data;
}
/**
* Remove move tags
* @param $key
*/
public function removeTag($key)
{
unset($this->tags[$key]);
}
/**
* Get tags associated with the page
* @return void
*/
public function getTags()
{
return $this->tags;
}
/**
* Add post parse tags: as per adding tags
* @param String $key the key to store within the array
* @param String $data the replacement data
* @return void
*/
public function addPPTag($key, $data)
{
$this->postParseTags[$key] = $data;
}
/**
* Get tags to be parsed after the first batch have been parsed
* @return array
*/
public function getPPTags()
{
return $this->postParseTags;
}
/**
* Add a template bit to the page, doesnt actually add the content
* just yet
* @param String the tag where the template is added
* @param String the template file name
* @return void
*/
public function addTemplateBit($tag, $bit)
{
$this->bits[$tag] = $bit;
}
/**
* Adds additional parsing data
* A.P.D is used in parsing loops. We may want to have an extra bit
* of data depending on on iterations value
* for example on a form list, we may want a specific item to be
* "selected"
* @param String block the condition applies to
* @param String tag within the block the condition applies to
* @param String condition : what the tag must equal
* @param String extratag : if the tag value = condition then we have
* an extra tag called extratag
* @param String data : if the tag value = condition then extra tag
*is replaced with this value
*/
public function addAdditionalParsingData($block, $tag, $condition,
$extratag, $data)
{
$this->apd[$block] = array($tag => array('condition' => $condition,
'tag' => $extratag, 'data' => $data));
}
/**
* Get the template bits to be entered into the page
* @return array the array of template tags and template file names
*/
public function getBits()
{
return $this->bits;
}
public function getAdditionalParsingData()
{
return $this->apd;
}
/**
* Gets a chunk of page content
* @param String the tag wrapping the block ( <!-- START tag -->
* block <!-- END tag --> )
* @return String the block of content
*/
//TODO: find it hard t actually understand this function......
public function getBlock($tag)
{
//echo $tag;
//TODO : write the code..
}
public function getContent()
{
return $this->content;
}
public function getContentToPrint()
{
$this->content = preg_replace ('#{form_(.+?)}#si', '',
$this->content);
$this->content = preg_replace ('#{nbd_(.+?)}#si', '',
$this->content);
$this->content = str_replace('</body>', '<!-- Generated by our
Fantastic Social Netowk -->
</body>', $this->content );
return $this->content;
}
/**
* Set the URL path
* @param String the url path
*/
public function setURLPath($path)
{
$this->urlPath = $path;
}
/**
* Gets data from the current URL
* @return void
*/
public function getURLData()
{
$urldata = ( isset( $_GET['page'] ) ) ? $_GET['page'] : '' ;
$this->urlPath = $urldata;
if( $urldata == '' )
{
$this->urlBits[] = '';
$this->urlPath = '';
}
else
{
$data = explode( '/', $urldata );
while ( !empty( $data ) && strlen( reset( $data ) ) === 0 )
{
array_shift( $data );
}
while ( !empty( $data ) && strlen( end( $data ) ) === 0)
{
array_pop($data);
}
$this->urlBits = $this->array_trim( $data );
}
}
public function getURLBits()
{
return $this->urlBits;
}
public function getURLBit( $whichBit )
{
return ( isset( $this->urlBits[ $whichBit ] ) ) ?
$this->urlBits[ $whichBit ] : 0 ;
}
public function getURLPath()
{
return $this->urlPath;
}
public function buildURL( $bits, $qs, $admin )
{
$admin = ( $admin == 1 ) ? $this->registry->getSetting('admin_
folder') . '/' : '';
$the_rest = '';
foreach( $bits as $bit )
{
$the_rest .= $bit . '/';
}
$the_rest = ( $qs != '' ) ? $the_rest . '?&' .$qs : $the_rest;
return $this->registry->getSetting('siteurl') . $admin . $the_rest;
}
}
|
C++
|
UTF-8
| 2,292
| 3.65625
| 4
|
[] |
no_license
|
//
// List.cpp
// 52_FirstCommonNodesInLists
//
// Created by LiLe on 2020/2/28.
// Copyright © 2020 lile. All rights reserved.
//
#include "List.hpp"
#include <iostream>
using namespace std;
ListNode *CreateListNode(int value)
{
ListNode *pNode = new ListNode();
pNode->value = value;
pNode->next = nullptr;
return pNode;
}
void ConnectListNodes(ListNode *pCurrent, ListNode *pNext)
{
if (pCurrent == nullptr) {
cout << "Error to connect two nodes." << endl;
exit(1);
}
pCurrent->next = pNext;
}
void PrintListNode(ListNode *pNode)
{
if (pNode == nullptr) {
cout << "The node is nullptr." << endl;
} else {
cout << "The value in node is " + pNode->value << endl;
}
}
void PrintList(ListNode *pHead)
{
cout << "------- PrintList start -------" << endl;
ListNode *node = pHead;
while (node != nullptr) {
cout << node->value << " ";
node = node->next;
}
cout << "------- PrintList end -------" << endl;
}
void DestroyList(ListNode *pHead)
{
ListNode *node = pHead;
while (pHead != nullptr) {
pHead = pHead->next;
delete node;
node = pHead;
}
}
void AddToTail(ListNode **pHead, int value)
{
ListNode *newNode = new ListNode();
newNode->value = value;
newNode->next = nullptr;
if (*pHead == nullptr) {
*pHead = newNode;
} else {
ListNode *node = *pHead;
while (node->next != nullptr) {
node = node->next;
}
node->next = newNode;
}
}
void RemoveNode(ListNode **pHead, int value)
{
if (pHead == nullptr || *pHead == nullptr) {
return;
}
ListNode *willDeleteNode = nullptr;
if ((*pHead)->value == value) {
willDeleteNode = *pHead;
*pHead = (*pHead)->next;
} else {
ListNode *node = *pHead;
while (node->next != nullptr && node->next->value != value) {
node = node->next;
}
if (node->next != nullptr && node->next->value == value) {
willDeleteNode = node->next;
node->next = node->next->next;
}
}
if (willDeleteNode != nullptr) {
delete willDeleteNode;
willDeleteNode = nullptr;
}
}
|
Java
|
UTF-8
| 2,570
| 2.3125
| 2
|
[] |
no_license
|
package aas.project.tera.com.autoattendancesystem;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.rey.material.widget.Button;
import java.util.ArrayList;
import aas.tera.com.autoattendancesystem.R;
/**
* Created by Administrator on 2015-06-02.
*/
public class AttendanceBookAdapter extends BaseAdapter{
private ArrayList<TakeCourseBean> items = new ArrayList<>();
private AQuery aQuery;
public AttendanceBookAdapter(AQuery aQuery){
this.aQuery = aQuery;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Context c = aQuery.id(R.id.item_container).getContext();
LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.attendance_book_item, null);
TextView grade = (TextView)v.findViewById(R.id.grade_title);
TextView classNumber = (TextView)v.findViewById(R.id.class_number_title);
TextView name = (TextView)v.findViewById(R.id.name_title);
Button attendance = (Button)v.findViewById(R.id.attendance);
attendance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setTag(1);
}
});
Button lateness = (Button)v.findViewById(R.id.lateness);
lateness.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setTag(2);
}
});
Button absence = (Button)v.findViewById(R.id.absence);
absence.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setTag(3);
}
});
grade.setText(String.valueOf(items.get(position).getYear()));
classNumber.setText(String.valueOf(items.get(position).getSno()));
name.setText(items.get(position).getSname());
return v;
}
public void addItem(TakeCourseBean takeCourseBean) {
items.add(takeCourseBean);
}
}
|
PHP
|
UTF-8
| 7,108
| 2.90625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
<?php
/**
* Fwk
*
* Copyright (c) 2011-2012, Julien Ballestracci <julien@nitronet.org>.
* All rights reserved.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* PHP Version 5.3
*
* @category Core
* @package Fwk\Core
* @author Julien Ballestracci <julien@nitronet.org>
* @copyright 2011-2012 Julien Ballestracci <julien@nitronet.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://www.phpfwk.com
*/
namespace Fwk\Core;
use Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpFoundation\Response;
/**
* Action Context
*
* This class represents the whole running context of a client's request.
* <pre>
* Client --> Request
* : |
* | Context |
* | :
* Response <-- Action
* </pre>
*
* @category Core
* @package Fwk\Core
* @author Julien Ballestracci <julien@nitronet.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://www.phpfwk.com
*/
class Context
{
const STATE_ERROR = -1;
const STATE_INIT = 0;
const STATE_READY = 1;
const STATE_EXECUTED = 2;
const STATE_DONE = 3;
/**
* Client request
*
* @var Request
*/
protected $request;
/**
* Reponse to be sent to client
*
* @var Response
*/
protected $response;
/**
* Current state
*
* @var integer
*/
protected $state = self::STATE_INIT;
/**
* Description of current error
*
* @var string
*/
protected $error;
/**
* Action's result returned by executed method
* (recommended: string)
*
* @var mixed
*/
protected $result;
/**
* The parent context (if any)
*
* @var Context
*/
protected $parent;
/**
* The action name
*
* @var string
*/
protected $actionName;
/**
* Constructor
*
* @param Request $request Client's request
* @param Response $response Pre-defined return response
*
* @return void
*/
public function __construct(Request $request, Response $response = null)
{
$this->request = $request;
$this->response = $response;
}
/**
* Returns client's request
*
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* Returns Response if defined or null otherwise
*
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/**
* Returns parent context (if any)
*
* @return Context
*/
public function getParent()
{
return $this->parent;
}
/**
* Defines a parent Context
*
* This usually happends when running multiples actions within a same
* request (modules, widgets ...)
*
* @param Context $context The parent context
*
* @return void
*/
public function setParent(Context $context)
{
$this->parent = $context;
}
/**
* Tells if a parent context is defined
*
* @return boolean
*/
public function hasParent()
{
return ($this->parent instanceof Context);
}
/**
* Returns a new parent Context
*
* @return Context
*/
public function newParent()
{
$ctx = new self($this->request);
$ctx->setParent($this);
return $ctx;
}
/**
* Tells if this context is ready (Action name is defined)
*
* @return boolean
*/
public function isReady()
{
return ($this->state >= self::STATE_READY);
}
/**
* Tells if this context encountered an error
*
* @return boolean
*/
public function isError()
{
return ($this->state === self::STATE_ERROR);
}
/**
* Tells if the context has been executed
*
* @return boolean
*/
public function isExecuted()
{
return ($this->state >= self::STATE_EXECUTED);
}
/**
* Tells if the context has ended execution and client's response
* has been defined
*
* @return boolean
*/
public function isDone()
{
return ($this->state >= self::STATE_DONE);
}
/**
* Sets a description of the error and toggle error state
*
* @param string $description Error description
*
* @see ContextEvents::ERROR
* @return void
*/
public function setError($description)
{
$this->error = $description;
$this->state = self::STATE_ERROR;
}
/**
* Returns the error description (if any)
*
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* Sets state to executed and store result
*
* @param mixed $result Action's result (recommended: string)
*
* @see ContextEvents::EXECUTED
* @return void
*/
public function setResult($result)
{
$this->state = self::STATE_EXECUTED;
$this->result = $result;
}
/**
* Defines response and sets state to Done.
*
* @param Response $response Client response
*
* @see ContextEvents::RESPONSE
* @return void
*/
public function setResponse(Response $response)
{
$this->state = self::STATE_DONE;
$this->response = $response;
}
/**
*
* @return integer
*/
public function getState()
{
return $this->state;
}
/**
*
* @return mixed
*/
public function getResult()
{
return $this->result;
}
public function getActionName()
{
return $this->actionName;
}
public function setActionName($actionName)
{
if ($actionName !== false) {
$this->actionName = $actionName;
if (!empty($actionName)) {
$this->state = self::STATE_READY;
}
} else {
$this->setError('No action found');
}
}
}
|
Python
|
UTF-8
| 774
| 2.9375
| 3
|
[] |
no_license
|
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
n, m = len(num1), len(num2)
res = [0] * (n + m)
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
tmp = res[i+j+1] + int(num1[i]) * int(num2[j])
res[i+j+1] = tmp % 10
res[i+j] += tmp / 10
# can be bigger than 10 here
# will be smoothed by next round
# Q: no need to worry about the most significant bit
# because it is guaranteed no overflow
res = "".join(map(str, res)).lstrip('0')
if not res:
return "0"
return res
|
JavaScript
|
UTF-8
| 2,840
| 2.625
| 3
|
[] |
no_license
|
const hre = require('hardhat')
const { CHAIN_ID } = require('../const')
const { PFX, NUMBER_OF_LEVELS } = require('../presaleConstants')
const PFX_CONTRACT = require('@polarfox/governance/artifacts/contracts/pfx/PFX.sol/PFX.json')
async function main() {
const [admin] = await hre.ethers.getSigners()
const chainId = await admin.getChainId()
const apa = chainId == CHAIN_ID.AVALANCHE ? require('./json/production-addresses.json') : require('./json/test-addresses.json')
// Run safety checks first
if (!safetyChecks(apa.data)) return
// #1: Deploy the VestedAirdrop contract
const VestedAirdrop = await hre.ethers.getContractFactory('VestedAirdrop')
const vestedAirdrop = await VestedAirdrop.deploy(PFX) // PFX address
console.log('VestedAirdrop deployed to:', vestedAirdrop.address)
// #2: Exclude the VestedAirdrop contract from PFX fees
const pfx = await hre.ethers.getContractAt(PFX_CONTRACT.abi, PFX, admin)
await pfx.excludeSrc(vestedAirdrop.address)
await pfx.excludeDst(vestedAirdrop.address)
console.log('VestedAirdrop excluded from PFX fees')
// #3: Set addresses on the VestedAirdrop contract
const array = Array.from(apa.data)
for (var i = 0; i < array.length; i++) {
await vestedAirdrop.setAddressesForLevel(
array[i].amountsPerAddresses.map((element) => element.address), // address[] memory addresses
array[i].amountsPerAddresses.map((element) => element.amount), // uint256[] memory amounts
array[i].level // uint8 level
)
console.log('Set addresses for level', array[i].level)
}
console.log('All done!')
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error)
process.exit(1)
})
const safetyChecks = (data) => {
// Safety check #1: levels should only appear once, start at 0 and end at 119
// Isolate the levels
const levels = data.map((element) => element.level).sort((a, b) => a - b)
for (var i = 0; i < NUMBER_OF_LEVELS; i++) {
if (levels[i] != i) {
console.error('Levels are configurated incorrectly')
return false
}
}
// Safety check #2: an address should not appear twice in one level
// For each level
var error = false
data.forEach((element) => {
// See if there is a duplicate in the addresses
const addresses = element.amountsPerAddresses.map((element_) => element_.address)
const uniqueAddresses = Array.from(new Set(addresses))
if (addresses.length != uniqueAddresses.length) {
console.error(`Some addresses in level ${element.level} appear multiple times`)
error = true
}
})
if (error == true) return false
console.log('Safety checks OK')
return true
}
|
Java
|
UTF-8
| 1,437
| 1.734375
| 2
|
[] |
no_license
|
package com.wisrc.sys.webapp.service;
import com.wisrc.sys.webapp.vo.employee.AddEmployeeVO;
import com.wisrc.sys.webapp.vo.employee.SetEmployeeVO;
import com.wisrc.sys.webapp.entity.GatherEntity;
import com.wisrc.sys.webapp.entity.SysEmployeeInfoEntity;
import com.wisrc.sys.webapp.entity.VUserCategoryEntity;
import com.wisrc.sys.webapp.utils.Result;
import org.springframework.validation.BindingResult;
import java.util.List;
public interface EmployeeInfoService {
Result find(Integer pageNum, Integer pageSize, GatherEntity gatherEntity);
Result update(SetEmployeeVO addEmployee, BindingResult bindingResult);
Result add(AddEmployeeVO addEmployee, BindingResult bindingResult);
Result getEmployeeDetail(String employeeId);
Result getNewEmployeeId();
void changeStatus(String employeeId, Integer statusCd);
Result getDeptAncestor(String deptCd);
Result getUnAccount();
SysEmployeeInfoEntity getById(String employeeId);
Result statusSelector();
List<SysEmployeeInfoEntity> search(String[] ids);
Result findAllOperationEmployee(Integer statusCd, String deptCd, String positionCd, String[] employeeIdList);
List<VUserCategoryEntity> searchCategory(String userId, String[] employeeIdList,
String positionCd, String upEmployeeId,
String executiveDirectorId, String upPositionCd);
}
|
JavaScript
|
UTF-8
| 1,484
| 2.90625
| 3
|
[] |
no_license
|
//This assignment is to create transaction
//by Muhammad Irfan PIAIC1337739
//first of all install following for creating a transaction
//npm install ethereumjs-tx
//environmental variables
require('dotenv').config()
//export your private keys to safe env
const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1, 'hex')
//import transaction library
var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3')
const rpcURL = process.env.myRpcURL
const web3 = new Web3(rpcURL)
const account1 = process.env.myAccount1;
const account2 = process.env.myAccount2;
//Steps to use
//1. Build a transaction object
//2. Sign the transaction
//3. Broadcast the transaction to the network
//1. Build a transaction object
web3.eth.getTransactionCount(account1, (err, txCount)=>{
console.log("Transaction nonce is :", txCount);
const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.1','ether')),
gasLimit: web3.utils.toHex(300000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
}
//2. Sign the Transaction
const tx = new Tx(txObject, {chain: 'ropsten', hardfork: 'petersburg'})
tx.sign(privateKey1)
const serializTx = tx.serialize()
const raw = '0x' + serializTx.toString('hex')
//3. Broadcast the transaction to the network
web3.eth.sendSignedTransaction(raw, (err, txHash)=>{
console.log('txHash :', txHash)
})
})
|
Java
|
UTF-8
| 534
| 2.140625
| 2
|
[] |
no_license
|
package com.marisoft.ziba.shared.model.screens;
import java.util.Map;
import com.marisoft.ziba.shared.ModelDataEx;
public class ShippingDocsItem extends ModelDataEx{
/*
private ShippingDoc doc ;
//*/
public ShippingDocsItem(Map<String, Object> data) {
super(data);
}
public ShippingDocsItem() {
}
public ShippingDocsItem(ShippingDoc doc) {
setDoc(doc);
}
public void setDoc(ShippingDoc doc) {
set("doc", doc);
}
public ShippingDoc getDoc() {
return get("doc");
}
}
|
Python
|
UTF-8
| 134
| 4.15625
| 4
|
[] |
no_license
|
num = 1
while num > 0:
num = int(input("Input a whole number less than 100: "))
if num > 99:
continue
print("Num = ", num)
|
Markdown
|
UTF-8
| 3,204
| 2.515625
| 3
|
[] |
no_license
|
# Article R*1142-1
Le ministre de la défense prépare et met en œuvre la politique de défense conformément aux directives générales du Premier
ministre. Il traduit ces directives en ordres et instructions pour les autorités subordonnées.
I.-Il est responsable de la préparation et, sous réserve des dispositions particulières relatives à la dissuasion, de
l'emploi des forces. Il est également responsable de la sécurité des moyens militaires de défense.
Il fixe l'organisation des armées ainsi que des directions et services du ministère.
Il établit la programmation des effectifs, des équipements et des infrastructures ; il en contrôle la mise en œuvre.
Il définit la politique des ressources humaines et veille au respect des droits et obligations des militaires.
Il organise le soutien des personnels et du matériel et fixe les orientations de la gestion du patrimoine immobilier.
Il détermine les conditions de la contribution du service de santé des armées à la politique de santé et définit les besoins
spécifiques de la défense dans le domaine de la santé. Il participe à la définition des modalités de la contribution des
autres acteurs du système de santé au soutien sanitaire des forces armées.
Il propose et met en œuvre les politiques de coopération et d'exportation relatives aux équipements de défense.
Il définit les missions relevant de sa compétence confiées aux formations spécialisées de la gendarmerie.
Il définit également la mission militaire des prévôts à l'exception des missions de police judiciaire militaire prévues à
l'article L. 411-2 du code de la justice militaire.
Il exerce son autorité sur les personnels militaires de la gendarmerie engagés dans des missions militaires à l'intérieur
comme à l'extérieur du territoire national.
Il propose la nomination et l'affectation des officiers généraux.
II.-Il est chargé du renseignement extérieur et du renseignement d'intérêt militaire.
III.-Au titre de la politique internationale de défense :
1° Il conduit les négociations internationales intéressant la défense ;
2° Il propose la nomination des attachés de défense.
IV.-Il est responsable de la prospective de défense.
V.-Au titre de la politique industrielle et de recherche dans les domaines intéressant la défense :
1° Il définit la stratégie et détermine les actions à mener ;
2° Il fixe les orientations de l'action des organismes intervenant dans le domaine de la défense dont il assure la tutelle ;
3° Il assure, notamment par l'intermédiaire de commissaires du Gouvernement, le contrôle des industries participant à
l'exécution de marchés relatifs à des matériels de guerre.
**Liens relatifs à cet article**
_Cité par_:
- Décret n°2004-374 du 29 avril 2004 - art. 23-1 (V)
- Décret n°2004-374 du 29 avril 2004 - art. 37 (V)
- Décret n°2004-374 du 29 avril 2004 - art. 42 (V)
_Anciens textes_:
- Décret n°2005-506 du 19 mai 2005 - art. 1, v. init.
- Décret n°2005-506 du 19 mai 2005 - art. 1 (Ab)
_Modifié par_:
- Décret n°2018-894 du 17 octobre 2018 - art. 1
_Cite_:
- Code de justice militaire. - art. L411-2
|
Java
|
UTF-8
| 698
| 3.015625
| 3
|
[] |
no_license
|
import java.util.Scanner;
class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int p = 1;
int sum = 0;
while (number != -1) { int k = number;
while (k != 0) {
sum = sum + (k % 10);
k = k/10;
}
if ((sum % 2) != 0) {
p=p*number;
}
number = scanner.nextInt();
sum = 0;
}
System.out.println(p);
}
}
|
Swift
|
UTF-8
| 4,059
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// UserDetailsTableViewCell.swift
// JSON_Parser
//
// Created by Kedar Sukerkar on 28/04/20.
// Copyright © 2020 Kedar-27. All rights reserved.
//
import UIKit
import Kingfisher
class UserDetailsTableViewCell: UITableViewCell {
// MARK: - Outlets
lazy var userImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
return imageView
}()
lazy var nameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.textColor = .black
label.textAlignment = .left
label.font = .boldSystemFont(ofSize: 16)
label.numberOfLines = 1
return label
}()
lazy var ageLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.textColor = .black
label.textAlignment = .left
label.font = .boldSystemFont(ofSize: 12)
label.numberOfLines = 1
return label
}()
lazy var locationLabel: UILabel = {
let label = UILabel()
label.text = ""
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .black
label.textAlignment = .center
label.font = .boldSystemFont(ofSize: 12)
label.numberOfLines = 1
return label
}()
// MARK: - Properties
// MARK: - UIView
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupView()
self.setupConstraints()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.setupView()
self.setupConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
self.userImageView.image = nil
}
override func layoutSubviews() {
super.layoutSubviews()
self.userImageView.layer.cornerRadius = self.userImageView.frame.height / 2
self.userImageView.layer.masksToBounds = true
}
private func setupView(){
self.selectionStyle = .none
self.addSubview(self.userImageView)
self.addSubview(self.nameLabel)
self.addSubview(self.locationLabel)
self.addSubview(self.ageLabel)
}
private func setupConstraints(){
[
self.userImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
self.userImageView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.8),
self.userImageView.widthAnchor.constraint(equalTo: self.self.userImageView.heightAnchor),
self.userImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor,constant: 20),
self.nameLabel.topAnchor.constraint(equalTo: self.userImageView.topAnchor),
self.nameLabel.leadingAnchor.constraint(equalTo: self.userImageView.trailingAnchor, constant: 10),
self.ageLabel.topAnchor.constraint(equalTo: self.nameLabel.bottomAnchor, constant: 5),
self.ageLabel.leadingAnchor.constraint(equalTo: self.nameLabel.leadingAnchor),
self.locationLabel.centerYAnchor.constraint(equalTo: self.ageLabel.centerYAnchor),
self.locationLabel.leadingAnchor.constraint(equalTo: self.ageLabel.trailingAnchor,constant: 8)
].forEach({$0.isActive = true})
}
func configureCell(name: String, age: String, location:String, imageURL: String){
self.nameLabel.text = name
self.ageLabel.text = age
self.locationLabel.text = location
self.userImageView.kf.setImage(with: URL(string: imageURL),placeholder: UIImage(named: "profile"))
}
}
|
C
|
UTF-8
| 2,047
| 2.515625
| 3
|
[] |
no_license
|
#include "krigfunctions.h"
#include "random.h"
#include "clusterfunctions.h"
#include "datafunctions.h"
/*
* Kriging clustering example for random data.
*/
void print_data(Objects* data){
DWORD i;
for(i=0;i<data->size;i++){
printf("x=%lf,y=%lf,attribute=%lf,time=%lf\n",data->objects[i]->spatial_coordinates[0],data->objects[i]->spatial_coordinates[1],data->objects[i]->attribute,data->objects[i]->time);
}
}
int main(void){
/*
struct timeval start;
gettimeofday(&start,NULL);
init_genrand(start.tv_usec);
DWORD cluster_size=10,max_size=500,min_points=10;
DTYPE max_distance=0.02,max_distance2=2.0,x_min=0,x_max=1,y_min=0,y_max=1,t_min=30,t_max=50,alpha=1.3;
Stack* stack=random_data(cluster_size,max_size,min_points,max_distance,max_distance2,x_min,x_max,y_min,y_max,t_max,t_min,alpha);
Object** objects=Calloc(max_size,Object*);
DWORD i=0;
while(!is_empty(stack)){
objects[i]=pop(stack);
objects[i]->classification=UNCLASSIFIED;
i++;
}
DTYPE* C=Calloc(2,DTYPE);
C[0]=.2;
C[1]=.5;
DTYPE* distances=Calloc(2,DTYPE);
distances[0]=max_distance2;
distances[1]=DIS_UNCHECKED;
Objects* data=Calloc(1,Objects);
data->size=max_size;
data->objects=objects;
write_spatial_temporal_data(data,"random.csv",TRUE);
*/
Objects* data=read_csv("random.csv",SPATIAL_TEMPORAL_DATA,TRUE);
print_data(data);
Object** objects=data->objects;
DWORD cluster_size=10,max_size=500,min_points=10;
DTYPE max_distance=0.02,max_distance2=.3,x_min=0,x_max=1,y_min=0,y_max=1,t_min=30,t_max=50,alpha=1.3;
DTYPE* C=Calloc(2,DTYPE);
C[0]=0.4;
C[1]=.4;
DTYPE* distances=Calloc(2,DTYPE);
distances[0]=max_distance2;
distances[1]=DIS_UNCHECKED;
Clusters* clusters=krig_clustering(objects,max_size,3,C,distances,EXPONENTIAL_VARIOGRAM);
printf("# of clusters=%lld\n",clusters->size);
print_clusters(clusters);
DTYPE test_statistics=chi_square_coefficient(clusters,C,distances,EXPONENTIAL_VARIOGRAM);
printf("chi square test statistics=%lf\n",test_statistics);
Free(C);
Free(distances);
Free(data->objects);
Free(data);
return 0;
}
|
Python
|
UTF-8
| 3,729
| 2.671875
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
from gensim.models import KeyedVectors
#import spacy
import re
import math
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics.pairwise import cosine_similarity
import itertools
import logging
N_CLUSTERS = 256
OUTPUT_DIR = "/space/Work/adrian/output/"#"/home/adrian/workspace/Hierarchical-Clustering-Active-Learning-Text/outputs/"
VECTORS_FILE = "/space/tmp/pubmed2018_w2v_200D.bin" #"/home/adrian/PhD/Data/Word2Vec/BioASQvectors2018/pubmed2018_w2v_200D/pubmed2018_w2v_200D.bin"
DATA_DIR = "/space/Work/adrian/baseline_diabetes_unique_maxNperClass5000.parquet" #"/home/adrian/PhD/Data/Pubmed/baseline_diabetes_unique.parquet"
LOGFILE = "logfile.txt"
logging.basicConfig(filename=OUTPUT_DIR+LOGFILE,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
#define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
#formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
formatter = logging.Formatter('%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger().addHandler(console)
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
def avg_feature_vector(sentence, model, index2word_set, num_features=200):
try:
words = bioclean(sentence)
except:
print("bioclean did not work for: {}".format(sentence))
print(type(sentence))
print(math.isnan(sentence))
feature_vec = np.zeros((num_features, ), dtype='float32')
n_words = 0
for word in words:
if word in index2word_set:
n_words += 1
feature_vec = np.add(feature_vec, model[word])
#else:
# if hasNumbers(word):
# print("word not in vocabulary: {}".format(word))
if (n_words > 0):
feature_vec = np.divide(feature_vec, n_words)
return feature_vec
logging.info("Load model..")
model = KeyedVectors.load_word2vec_format(VECTORS_FILE, binary=True)
logging.info("Load data..")
df = pd.read_parquet(DATA_DIR)
index2word_set = set(model.wv.index2word)
# clean for BioASQ
bioclean = lambda t: re.sub('[.,?;*!%^&_+():-\[\]{}]', '', t.replace('"', '').replace('/', '').replace('\\', '').replace("'",'').strip().lower()).split()
df_vec = np.stack(
(df.title + " " + df.abstract).map(lambda abstract: avg_feature_vector(abstract, model, index2word_set)).values
, axis = 0)
logging.info("Vector shape: {}".format(df_vec.shape))
#df_vec = cosine_similarity(df_vec)
#print("Similarity matrix shape: {}".format(df_vec.shape))
HC = AgglomerativeClustering(n_clusters=N_CLUSTERS, affinity="cosine", linkage="average")
logging.info("Fit..")
HC.fit(df_vec)
logging.info("Number of leaves: {}".format(HC.n_leaves_))
logging.info("Number of clusters: {}".format(HC.n_clusters_))
# https://stackoverflow.com/questions/27386641/how-to-traverse-a-tree-from-sklearn-agglomerativeclustering
ii = itertools.count(df_vec.shape[0])
tree = [{'node_id': next(ii), 'left': x[0], 'right':x[1]} for x in HC.children_]
df["class_predict"] = HC.labels_
tree_df = pd.DataFrame(tree, columns=["node_id", "left", "right"])
logging.info("Save results to file..")
df.to_parquet(OUTPUT_DIR+"/diabetes_abstracts_HC_output.parquet")
tree_df.to_parquet(OUTPUT_DIR+"/diabetes_abstracts_tree_output.parquet")
logging.info("All good :)")
|
C#
|
UTF-8
| 827
| 2.71875
| 3
|
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace B17.ODEV
{
public static class SanalDatabase
{
private static ArrayList db = new ArrayList();
public static void UrunEkle(BaseClass model)
{
if(model != null && !String.IsNullOrEmpty(model.barkod))
{
db.Add(model);
}
}
public static bool BarkodControl(string barkod)
{
bool result = false;
foreach (BaseClass item in db)
{
if (item.barkod == barkod)
{
result = true;
break;
}
}
return result;
}
}
}
|
Shell
|
UTF-8
| 182
| 2.96875
| 3
|
[] |
no_license
|
#!/bin/sh
SEARCH_PREFIX=($(retrieve "prefix"))
if [[ ${#SEARCH_PREFIX[@]} -eq 0 ]]
then
exit
fi
s="($(prefix_list ${SEARCH_PREFIX[@]} ))\s*=?\s*(\\\{|\\\[)?\s*('|\\\")?"
echo $s
|
Java
|
UTF-8
| 12,320
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sohu.tv.cachecloud.client.jedis.stat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sohu.tv.cachecloud.client.basic.util.DateUtils;
import com.sohu.tv.cachecloud.client.basic.util.NamedThreadFactory;
import com.sohu.tv.cachecloud.client.basic.util.NetUtils;
import com.sohu.tv.jedis.stat.constant.ClientReportConstant;
import com.sohu.tv.jedis.stat.data.UsefulDataCollector;
import com.sohu.tv.jedis.stat.enums.ClientCollectDataTypeEnum;
import com.sohu.tv.jedis.stat.enums.ClientExceptionType;
import com.sohu.tv.jedis.stat.model.ClientReportBean;
import com.sohu.tv.jedis.stat.model.CostTimeDetailStatKey;
import com.sohu.tv.jedis.stat.model.CostTimeDetailStatModel;
import com.sohu.tv.jedis.stat.model.ExceptionModel;
import com.sohu.tv.jedis.stat.model.ValueLengthModel;
import com.sohu.tv.jedis.stat.utils.AtomicLongMap;
import com.sohu.tv.jedis.stat.utils.NumberUtil;
/**
* jedis数据收集上报任务执行器
*
* @author leifu
* @Date 2015年1月14日
* @Time 上午11:45:09
*/
public class ClientDataCollectReportExecutor {
private final Logger logger = LoggerFactory.getLogger(ClientDataCollectReportExecutor.class);
/**
* 客户端ip(实际使用了web中统计的ip作为真正的客户端ip, 这个作为备用)
*/
private static String clientIp = NetUtils.getLocalHost();
/**
* 数据收集上报
*/
private final ScheduledExecutorService jedisDataCollectReportScheduledExecutor = Executors.newScheduledThreadPool(3,
new NamedThreadFactory("jedisDataCollectReportScheduledExecutor", true));
private ScheduledFuture<?> jedisDataCollectReportScheduleFuture;
private final int delay = 5;
private final int fixCycle = 60;
private volatile static ClientDataCollectReportExecutor jedisDataCollectAndReportExecutor;
private ClientDataCollectReportExecutor() {
init();
}
public static ClientDataCollectReportExecutor getInstance() {
if (jedisDataCollectAndReportExecutor == null) {
synchronized (ClientDataCollectReportExecutor.class) {
if (jedisDataCollectAndReportExecutor == null) {
jedisDataCollectAndReportExecutor = new ClientDataCollectReportExecutor();
}
}
}
return jedisDataCollectAndReportExecutor;
}
/**
* 初始化
*/
public void init() {
Thread clientDataCollectReportThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String currentMinuteStamp = ClientReportConstant.getCollectTimeSDf().format(new Date());
collectReportAllData(currentMinuteStamp);
} catch (Exception e) {
UsefulDataCollector.collectException(e, "", System.currentTimeMillis(), ClientExceptionType.CLIENT_EXCEPTION_TYPE);
logger.error("ClientDataCollectReport thread message is" + e.getMessage(), e);
}
}
});
clientDataCollectReportThread.setDaemon(true);
// 启动定时任务
jedisDataCollectReportScheduleFuture = jedisDataCollectReportScheduledExecutor.scheduleWithFixedDelay(
clientDataCollectReportThread, delay, fixCycle, TimeUnit.SECONDS);
}
/**
* 收集上报数据
* @param currentMinuteStamp
*/
private void collectReportAllData(String currentMinuteStamp) {
//1. 获取上一分钟的所有数据
String lastMinute = getLastMinute(currentMinuteStamp);
if (lastMinute == null || "".equals(lastMinute.trim())) {
return;
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.addAll(collectReportCostTimeData(lastMinute));
list.addAll(collectReportValueDistriData(lastMinute));
list.addAll(collectReportExceptionData(lastMinute));
//上报统计数据,观察是否存在内存泄露的情况
Map<String, Object> otherInfo = new HashMap<String, Object>(4, 1);
otherInfo.put(ClientReportConstant.COST_MAP_SIZE, UsefulDataCollector.getDataCostTimeMapAll().size());
otherInfo.put(ClientReportConstant.VALUE_MAP_SIZE, UsefulDataCollector.getDataValueLengthDistributeMapAll().size());
otherInfo.put(ClientReportConstant.EXCEPTION_MAP_SIZE, UsefulDataCollector.getDataExceptionMapAll().size());
otherInfo.put(ClientReportConstant.COLLECTION_MAP_SIZE, UsefulDataCollector.getCollectionCostTimeMapAll().size());
//2. 上报数据
if (!list.isEmpty()) {
ClientReportBean ccReportBean = new ClientReportBean(clientIp, NumberUtil.toLong(lastMinute), System.currentTimeMillis(), list, otherInfo);
ClientReportDataCenter.reportData(ccReportBean);
}
}
/**
* 收集耗时
*
* @param lastMinute
*/
private List<Map<String, Object>> collectReportCostTimeData(String lastMinute) {
try {
//1. 收集数据
Map<CostTimeDetailStatKey, AtomicLongMap<Integer>> map = UsefulDataCollector.getCostTimeLastMinute(lastMinute);
if (map == null || map.isEmpty()) {
return Collections.emptyList();
}
// 2. 组装数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Entry<CostTimeDetailStatKey, AtomicLongMap<Integer>> entry : map.entrySet()) {
CostTimeDetailStatKey costTimeDetailStatKey = entry.getKey();
AtomicLongMap<Integer> statMap = entry.getValue();
CostTimeDetailStatModel model = UsefulDataCollector.generateCostTimeDetailStatKey(statMap);
Map<String, Object> tempMap = new HashMap<String, Object>();
tempMap.put(ClientReportConstant.COST_COUNT, model.getTotalCount());
tempMap.put(ClientReportConstant.COST_COMMAND, costTimeDetailStatKey.getCommand());
tempMap.put(ClientReportConstant.COST_HOST_PORT, costTimeDetailStatKey.getHostPort());
tempMap.put(ClientReportConstant.COST_TIME_90_MAX, model.getNinetyPercentMax());
tempMap.put(ClientReportConstant.COST_TIME_99_MAX, model.getNinetyNinePercentMax());
tempMap.put(ClientReportConstant.COST_TIME_100_MAX, model.getHundredMax());
tempMap.put(ClientReportConstant.COST_TIME_MEAN, model.getMean());
tempMap.put(ClientReportConstant.COST_TIME_MEDIAN, model.getMedian());
tempMap.put(ClientReportConstant.CLIENT_DATA_TYPE, ClientCollectDataTypeEnum.COST_TIME_DISTRI_TYPE.getValue());
list.add(tempMap);
}
return list;
} catch (Exception e) {
UsefulDataCollector.collectException(e, "", System.currentTimeMillis(), ClientExceptionType.CLIENT_EXCEPTION_TYPE);
logger.error("collectReportCostTimeData:" + e.getMessage(), e);
return Collections.emptyList();
}
}
/**
* 收集异常
* @param lastMinute
*/
private List<Map<String, Object>> collectReportExceptionData(String lastMinute) {
try {
// 1. 只取当前时间前一分钟的的数据
Map<ExceptionModel, Long> map = UsefulDataCollector.getExceptionLastMinute(lastMinute);
if (map == null || map.isEmpty()) {
return Collections.emptyList();
}
// 2. 组装数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> tempMap = null;
for (Entry<ExceptionModel, Long> entry : map.entrySet()){
ExceptionModel exceptionModel = entry.getKey();
Long exceptionCount = entry.getValue();
tempMap = new HashMap<String, Object>();
tempMap.put(ClientReportConstant.EXCEPTION_CLASS, exceptionModel.getExceptionClass());
tempMap.put(ClientReportConstant.EXCEPTION_MSG, "");
tempMap.put(ClientReportConstant.EXCEPTION_HAPPEN_TIME, System.currentTimeMillis());
tempMap.put(ClientReportConstant.EXCEPTION_HOST_PORT, exceptionModel.getHostPort());
tempMap.put(ClientReportConstant.EXCEPTION_COUNT, exceptionCount);
tempMap.put(ClientReportConstant.EXCEPTION_TYPE, exceptionModel.getClientExceptionType().getType());
tempMap.put(ClientReportConstant.CLIENT_DATA_TYPE, ClientCollectDataTypeEnum.EXCEPTION_TYPE.getValue());
list.add(tempMap);
}
return list;
} catch (Exception e) {
UsefulDataCollector.collectException(e, "", System.currentTimeMillis(), ClientExceptionType.CLIENT_EXCEPTION_TYPE);
logger.error("collectReportExceptionData:" + e.getMessage(), e);
return Collections.emptyList();
}
}
/**
* 收集值分布
*
* @param lastMinute
*/
private List<Map<String, Object>> collectReportValueDistriData(String lastMinute) {
try {
// 1. 只取当前时间前一分钟的的数据
Map<ValueLengthModel, Long> jedisValueLengthMap = UsefulDataCollector.getValueLengthLastMinute(lastMinute);
if (jedisValueLengthMap == null || jedisValueLengthMap.isEmpty()) {
return Collections.emptyList();
}
// 2.解析拼接数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Entry<ValueLengthModel, Long> entry : jedisValueLengthMap.entrySet()) {
ValueLengthModel model = entry.getKey();
Long count = entry.getValue();
Map<String, Object> tempMap = new HashMap<String, Object>();
tempMap.put(ClientReportConstant.VALUE_DISTRI, model.getRedisValueSizeEnum().getValue());
tempMap.put(ClientReportConstant.VALUE_COUNT, count);
tempMap.put(ClientReportConstant.VALUE_COMMAND, model.getCommand());
tempMap.put(ClientReportConstant.VALUE_HOST_PORT, model.getHostPort());
tempMap.put(ClientReportConstant.CLIENT_DATA_TYPE, ClientCollectDataTypeEnum.VALUE_LENGTH_DISTRI_TYPE.getValue());
list.add(tempMap);
}
return list;
} catch (Exception e) {
UsefulDataCollector.collectException(e, "", System.currentTimeMillis(), ClientExceptionType.CLIENT_EXCEPTION_TYPE);
logger.error("collectReportValueDistriData:" + e.getMessage(), e);
return Collections.emptyList();
}
}
/**
* 获取上一分钟的字符串
*
* @param currentMinuteStamp
* @return
*/
private String getLastMinute(String currentMinuteStamp) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date currentDate = sdf.parse(currentMinuteStamp);
Date lastMinute = DateUtils.addMinutes(currentDate, -1);
return sdf.format(lastMinute);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
return null;
}
}
/**
* 关闭
*/
public void close() {
//TODO可以加个JVM钩子
try {
jedisDataCollectReportScheduleFuture.cancel(true);
} catch (Throwable t) {
logger.error(t.getMessage(), t);
}
}
public static String getClientIp() {
return clientIp;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.