language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
2,842
3.109375
3
[]
no_license
import java.io.IOException; import java.text.ParseException; public class Parser { private Lexeme current; private Lexer lexer; Parser(Lexer lexer) throws ParseException, IOException { this.lexer = lexer; current = lexer.getLexeme(); } int calculate() throws ParseException, IOException { int res; res = this.parseExpr(); if (this.getCurrent().getType() != LexemeType.EOF) throw new ParseException("Incorrect file end", 30); return res; } private int parseExpr() throws ParseException, IOException { int temp = parseTerm(); while (current.getType() == LexemeType.PLUS || current.getType() == LexemeType.MINUS) { if (current.getType() == LexemeType.PLUS) { current = lexer.getLexeme(); temp += parseTerm(); } if (current.getType() == LexemeType.MINUS) { current = lexer.getLexeme(); temp -= parseTerm(); } } return temp; } private int parseTerm() throws ParseException, IOException { int temp = parseFactor(); while (current.getType() == LexemeType.MULT || current.getType() == LexemeType.DIV) { if (current.getType() == LexemeType.MULT) { current = lexer.getLexeme(); temp *= parseFactor(); } if (current.getType() == LexemeType.DIV) { current = lexer.getLexeme(); temp /= parseFactor(); } } return temp; } private int parseFactor() throws ParseException, IOException { int temp = parsePower(); if (current.getType() == LexemeType.POW) { current = lexer.getLexeme(); temp = (int) Math.pow(temp, parsePower()); } return temp; } private int parsePower() throws ParseException, IOException { if (current.getType() == LexemeType.MINUS) { current = lexer.getLexeme(); return -parseAtom(); } return parseAtom(); } private int parseAtom() throws ParseException, IOException { if (current.getType() == LexemeType.NUM) { int temp = Integer.parseInt(current.getText()); current = lexer.getLexeme(); return temp; } if (current.getType() == LexemeType.OPEN) { current = lexer.getLexeme(); int temp = parseExpr(); if (current.getType() != LexemeType.CLOSE) throw new ParseException("Closing bracket not found", 30); current = lexer.getLexeme(); return temp; } throw new ParseException("Incorrect lexeme", 30); } private Lexeme getCurrent() { return current; } }
Java
UTF-8
1,109
2.578125
3
[]
no_license
package model; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDate; @Entity @Table(name = "news", schema = "polyclinic") public class News implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "news_id") private Integer id; @Column(name = "news_text") private String text; @Column(name = "publish_date") private LocalDate publishDate; @Column(name = "header") private String header; public News() {} public News(String text, String header) { this.text = text; this.header = header; this.publishDate = LocalDate.now(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public LocalDate getPublishDate() { return publishDate; } public void setPublishDate(LocalDate publishDate) { this.publishDate = publishDate; } }
Python
UTF-8
1,019
3.65625
4
[]
no_license
import pytest class TestDictRestrictions: def test_dict_get_not_existing(self): dictionary = {'alice': 10} with pytest.raises(KeyError): print(dictionary['bob']) def test_dict_only_hashable_keys(self): dictionary = {} with pytest.raises(TypeError): dictionary[[1, 2, 3]] = 'something' def test_dict_overwriting(self, random_int): dictionary = {} for i in range(random_int): dictionary['key'] = i assert dictionary == {'key': random_int-1} def test_dict_comprehension(): assert {i: i ** 2 for i in range(5)} == {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} @pytest.mark.parametrize('dict1,dict2', [({'a': 10, 'b': 20}, {'c': 30, 'd': 40}), ({'a': 10, 'b': 20, 'c': 30}, {'d': 40}), ({'a': 10, 'b': 20, 'c': 30, 'd': 40}, {})]) def test_dict_get_summarize(dict1, dict2): assert {**dict1, **dict2} == {'a': 10, 'b': 20, 'c': 30, 'd': 40}
Java
UTF-8
516
1.796875
2
[]
no_license
package com.smile.backend.service; import com.smile.backend.model.PaysEntity; import com.smile.backend.repository.PaysRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PaysService { @Autowired PaysRepository paysRepository; public List<PaysEntity> findByZoneGeographique(long idZoneGeographique){ return paysRepository.findByZoneGeographique_Id(idZoneGeographique); } }
C++
UTF-8
713
2.9375
3
[ "MIT" ]
permissive
// Created by Eko Hardiyanto (ehardi19) #include <bits/stdc++.h> using namespace std; #define MAX 1000001 bool prime[MAX + 1]; void SieveOfEratosthenes() { memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { if (prime[p] == true) { for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } } int solve(int n) { int count = 0, num = 1; long long int sum = 0; while (count < n) { if (prime[num]) { sum += num; count++; } num++; } return sum; } int main() { SieveOfEratosthenes(); int t, n; cin >> t; for (int i = 0; i < t; i++) { cin >> n; cout << solve(n) << endl; } return 0; }
Java
UTF-8
803
2.015625
2
[]
no_license
package com.hanyu.project.controller; import com.hanyu.project.response.ReturnResult; import com.hanyu.project.service.PromoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class PromoController { @Autowired private PromoService promoService; @RequestMapping("/generateToken") @ResponseBody public ReturnResult generateToken(Integer userId,Integer itemId, Integer promoId) { String token = promoService.generateToken(userId, itemId, promoId); ReturnResult result = new ReturnResult(); result.setData(token); return result; } }
Python
UTF-8
1,207
3.78125
4
[ "Apache-2.0" ]
permissive
# Задача 5. Вариант 34 # Напишите программу, которая бы при запуске случайным образом отображала имя # одного из шести генеральных секретарей ЦК КПСС. # Korsakov A.A. # 13.04.2016 print ('Программа случайным образом отображает имя одного из шести генеральных секретарей ЦК КПСС') import random Perviy = 'Иосиф Сталин' Vtoroy = 'Никита Хрущёв' Tretiy = 'Леонид Брежнев' Chetverty = 'Юрий Андропов' Pyaty = 'Константин Черненко' Shestoy = 'Михаил Горбачёв' n = random.randint(1,6) if n == 1: print('генеральных секретарей ЦК КПСС:', Perviy) elif n == 2: print('генеральных секретарей ЦК КПСС:', Vtoroy) elif n == 3: print('генеральных секретарей ЦК КПСС:', Tretiy) elif n == 4: print('генеральных секретарей ЦК КПСС:', Chetverty) elif n == 5: print('генеральных секретарей ЦК КПСС:', Pyaty) else: print('генеральных секретарей ЦК КПСС:', Shestoy) input ('\n\n Нажмите Enter для выхода')
PHP
UTF-8
5,105
2.796875
3
[]
no_license
<?php namespace app\models; use app\core\DBModel; class TicketingModel extends DBModel { public $ticket_id; public $title; public $content; public $user_id; public $created_at; public $updated_at; public $status_id; public $priority_id; public $solution; public $category_id; public function rules(): array { return [ 'title' => [self::RULE_REQUIRED], 'content' => [self::RULE_REQUIRED] ]; } /** * @return array * Read all data from table ticket */ public function readAll() { $db = $this->dbConnection->conn(); $dbData = $db->query("SELECT * FROM tickets;") or die($db->error); $resultArray = []; while ($result = $dbData->fetch_assoc()) { array_push($resultArray, $result); } return $resultArray; } public function readOne(TicketingModel $model): TicketingModel { $db = $this->dbConnection->conn(); $dbData = $db->query("SELECT * FROM tickets WHERE ticket_id = '$model->ticket_id'") or die($db->error); $result = $dbData->fetch_assoc(); $model->loadData($result); return $model; } public function ticketLoadMore($numberOfPage, $numberOfRows, $search) { $db = $this->dbConnection->conn(); if ($search !== null and $search !== "") { $sqlString = " select ticket.ticket_id, ticket.title, ticket.content, ticket.user_id, ticket.created_at, ticket.updated_at, ticket.status_id, ticket.priority_id, ticket.solution, ticket.category_id from tickets ticket where (ticket.title like '%$search%' or ticket.user_id like '%$search%' or ticket.ticket_id like '%$search%') and ticket.status_id = 1 order by priority_id desc LIMIT $numberOfRows"; } else { $startOn = $numberOfPage * $numberOfRows; $sqlString = " select ticket.ticket_id, ticket.title, ticket.content, ticket.user_id, ticket.created_at, ticket.updated_at, ticket.status_id, ticket.priority_id, ticket.solution, ticket.category_id from tickets ticket where (ticket.title like '%$search%' or ticket.user_id like '%$search%' or ticket.ticket_id like '%$search%') and ticket.status_id = 1 order by priority_id desc LIMIT $startOn, $numberOfRows"; print $sqlString; exit; } $dbData = $db->query($sqlString) or die($db->error); $resultArray = []; while ($result = $dbData->fetch_assoc()) { array_push($resultArray, $result); } return $resultArray; } public function editTicket(TicketingModel $model) { $db = $this->dbConnection->conn(); $sqlString = "UPDATE tickets SET `updated_at` = '$model->updated_at', `status_id` = '$model->status_id', `priority_id` = '$model->priority_id', `solution` = '$model->solution', `category_id` = '$model->category_id' WHERE `ticket_id` = '$model->ticket_id';"; $db->query($sqlString) or die(); return true; } public function tableName() { return 'tickets'; } public function attributes(): array { return [ 'ticket_id', 'title', 'content', 'user_id', 'created_at', 'updated_at', 'status_id', 'priority_id', 'solution', 'category_id' ]; } public function labels(): array { return [ "title" => "Title", "content" => "Content", "created_at" => "Date created", "updated_at" => "Date updated", "status_id" => "Status", "priority_id" => "Priority", "solution" => "Solution", "category_id" => "Category" ]; } public function ticketByCategory() { $db = $this->dbConnection->conn(); $sqlString = "select categories.`name`, tickets.`category_id`, count(ticket_id) as 'numberOfTickets' FROM `tickets` inner join categories on tickets.category_id = categories.category_id group by `category_id`"; $dataResult = $db->query($sqlString) or die(); $resultArray = []; while ($result = $dataResult->fetch_assoc()) { array_push($resultArray, $result); } return $resultArray; } }
Markdown
UTF-8
1,696
2.53125
3
[ "MIT" ]
permissive
# SelectLayersByString English / [Japanese](README_jp.md) Lightwave Modeler Python Script ## Overview ![SelectLayersByString](SelectLayersByString.png) Search the layer name as a character string and select the layer that matches the condition. The search condition you entered remains as history. You can select a layer using history. Layers that do not contain a mesh are not selected. If there is no layer that can be selected as the foreground layer, an error will result. An error also occurs if there is no mesh in the object. ## Download [SelectLayersByString.zip](SelectLayersByString.zip) Download the zip file by "Save as..", unzip zip file and add plugin. Plugin is added as "SK_SelectLayersByString". ## How To Use ### - String : Specify a character string to search for the layer name. ### - Select FG Layer : Specify whether to select the layer containing the string as the foreground layer or the layer not included. ### - Select others as BG Layer : Select the layer that was not selected as the foreground layer as the background layer. ### - Move the last condition up if they match : Switching, if there is a matching history, whether to move to the top or not. Please turn it off to stop sorting history. ### - History list Click history to recall the search condition. ### - Remove Button Deletes the selected history. ## Change log 2018.12.11 (ver.1.03) - Fix : Issue where default search condition is fixed at the top of history list. 2018.12.11 (ver.1.02) - Whether or not to make the selectable, matching history move to the top 2018.12.10 (ver.1.01) - Set the previous search condition as default condition 2018.12.9 (ver.1.0) - Release
Java
UTF-8
2,065
1.960938
2
[]
no_license
package com.politechnika.lukasz.dagger; import com.politechnika.lukasz.services.WeatherService; import com.politechnika.lukasz.views.activities.AstroInfoActivity; import com.politechnika.lukasz.views.activities.EditFavLocationsActivity; import com.politechnika.lukasz.views.activities.MainActivity; import com.politechnika.lukasz.views.activities.SettingsActivity; import com.politechnika.lukasz.views.fragments.MainInfoFragment; import com.politechnika.lukasz.views.fragments.MoonFragment; import com.politechnika.lukasz.views.fragments.SunFragment; import com.politechnika.lukasz.providers.AstroCalculatorProvider; import com.politechnika.lukasz.views.fragments.WeatherBasicFragment; import com.politechnika.lukasz.views.fragments.WeatherDetailsFragment; import com.politechnika.lukasz.views.fragments.WeatherForecastFragment; import com.politechnika.lukasz.views.fragments.WeatherFragment; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {MainModule.class}) public interface DaggerGraphComponent { void inject(MainActivity mainActivity); void inject(SettingsActivity settingsActivity); void inject(SunFragment sunFragment); void inject(AstroCalculatorProvider astroCalculatorProvider); void inject(MoonFragment moonFragment); void inject(AstroInfoActivity astroInfoActivity); void inject(MainInfoFragment mainInfoFragment); void inject(WeatherService weatherService); void inject(EditFavLocationsActivity editFavLocationsActivity); void inject(WeatherFragment weatherFragment); void inject(WeatherDetailsFragment weatherDetailsFragment); void inject(WeatherBasicFragment weatherBasicFragment); void inject(WeatherForecastFragment weatherForecastFragment); static final class Initializer { private Initializer() { } public static DaggerGraphComponent init(DaggerApplication app) { return DaggerDaggerGraphComponent.builder() .mainModule(new MainModule(app)) .build(); } } }
Python
UTF-8
1,507
2.984375
3
[]
no_license
import re import json import urllib2 import simplejson class Request(object): def __init__(self, textS): self.text = textS self.create_list() self.create_request() self.get_results() def create_list(self): re.sub(' +', ' ', self.text) if self.text[0] == ' ': self.text = self.text[1 : len(self.text)] if self.text[-1] == ' ': self.text = self.text[0 : len(self.text) - 1] self.list_args = self.text.split() def create_request(self): question = "" for i in range(len(self.list_args) - 1): question = question + str(self.list_args[i]) + '%20' question = question + str(self.list_args[len(self.list_args) - 1]) self.url = ('https://ajax.googleapis.com/ajax/services/search/web' '?v=1.0&q=' + question + '&userip=USERS-IP-ADDRESS') def get_results(self): request = urllib2.Request(self.url) response = urllib2.urlopen(request) self.links = [] self.content = [] results = simplejson.load(response) for value in results["responseData"]["results"]: self.links.append(value["url"]) self.content.append(value["content"]) def get_links(self): return self.links def get_content(self): return self.content a = Request("Paris Hilton") request = urllib2.Request(a.url) response = urllib2.urlopen(request) print type( response ) print response.read()
Markdown
UTF-8
2,099
2.78125
3
[]
no_license
# GoMN Meetup - httpexpect ## Folders Description * `1_gotesting`: Golang tests (no server involved) of an Add function using table driven data and subtests * `2_go_web_servers`: Different approaches of serving HTTP requests using the Golang builtin `net/http` package * server1: Define a HTTP Handler and use ServeHTTP * server2: Convert a function to HTTP handler using `http.HandlerFunc` * server3: Convert a function implicitly to `http.HandlerFunc` * server4: Use `http.HandleFunc` to register functions as HTTP handlers * `3_httptest`: Examples using `net/http/httptest` * `4_httpexpect`: Examples using `httpexpect` * `add_server`: testing of the Add function served via HTTP * `fastapi`: testing of a FastAPI server using Golang and `httpexpect` * `self_contained`: server and test in the same file * `separate_processes`: test a server started as a separate process * `slides`: Presentation slides in PDF format ## FastAPI Example FastAPI is a Python high performance web framework compatible with Python 3.6+ To execute the FastAPI server in directory `4_httpexpect/fastapi/web` you first need to prepare a Python virtual environment. The instructions below assume that you have Python 3 installed: ``` $ python3 -m venv .venv $ . .venv/bin/activate $ pip install fastapi[all] # only once $ uvicorn main:app ``` The installation of fastapi is done only once. Subsequently, the folloing should be sufficient to activate the environment and start the web server: ``` $ . .venv/bin/activate $ uvicorn main:app ``` The `Makefile` included in the same folder shows other options to start the server. After starting the server, you can point your browser to http://localhost:8000/docs to display the Swagger UI. To test using `httpexpect`, in the directory `4_httpexpect/fastapi/test`, execute the following command: ``` $ go test -v ``` The test folder is a Go mod project. If you experience any error related to the `httpexpect`, fetch the package manually with the followng command, and execute the test again: ``` $ go get github.com/gavv/httpexpect/v2 ```
JavaScript
UTF-8
1,287
2.875
3
[ "MIT" ]
permissive
function ScheduledSession (parsedObject) { this.room = isNaN(parsedObject.room) ? "" : parseInt(parsedObject.room); this.day = parsedObject.day; this.hour = parsedObject.hour; this.minutes = parsedObject.minutes || "00"; this.roomspan = parsedObject.roomspan || 1; this.timespan = parsedObject.timespan || howManyHalfHourSlots(parsedObject.session.session_type); this.session = new Session(parsedObject.session); function howManyHalfHourSlots (sessionType) { if (sessionType == "Relatos de Experiência") { return 1; } else if(sessionType == "Mão na Massa") { return 3; } return 2; } this.positionYourself = function() { var table = $("[data-day='" + this.day + "']"); var line = table.find("[data-time='" + this.hour + ":" + this.minutes + "']"); var cell = line.find("[data-room='" + this.room + "']"); cell.attr("rowspan", this.timespan).attr("colspan", this.roomspan); this.session.informationFor(cell); for (var room = 1; room < this.roomspan; room++) { line.find("[data-room='" + (this.room + room) + "']").remove(); } for (var time = 1; time < this.timespan; time++) { line = line.next(); for (var room = 0; room < this.roomspan; room++) { line.find("[data-room='" + (this.room + room) + "']").remove(); } } }; }
Python
UTF-8
290
3.03125
3
[]
no_license
from decoder import get_id with open("data.txt", "r") as f: codes = [code.replace('\n', '') for code in f.readlines()] seats = sorted([get_id(code) for code in codes]) my_id = [ seats[i] + 1 for i in range(len(seats) - 1) if seats[i + 1] - seats[i] == 2 ] print(my_id)
Markdown
UTF-8
2,414
3.796875
4
[]
no_license
# Writing generators The first thing the generator does should be calling `gen_init()`, storing the returned value (generator handle). Return type of the function should be declared as `gen_t *`. To actually return, do `gen_return(handle, val); return handle;`. Never exit the generator without calling `gen_return()`, even if there's no important value to pass. To yield, call `gen_yield(handle, val)`. The call returns the value sent via `gen_send()`, so make sure to save it if it's important. # Calling generators Call the generator as a usual function. It won't do anything immediately, but return the handle you will use to control it. Interact with the generator by calling `gen_send(handle, val)`. The value you send will be returned inside the generator from `gen_yield()`, whereas the value that the generator yields next time will be returned from the `gen_send()` call. Note: the first call of `gen_send()` has no corresponding `gen_yield()` call to return value from, so the value you pass will be silently discarded. When the generator returns, the return value is passed as the result of `gen_send()` in the same way that yielded values are. Use `gen_is_done()` to distinguish between yielded and return values. After the generator returns, call `free()` on the handle. # Notes It should work fine to pass handles around and call `gen_*()` on them from somewhat unexpected places (ex. yield the value from a generator from inside some other generator that was called by the first one). However, generator invocations are not reentrant, that is, you should not call `gen_yield()` on a handle twice without a `gen_send()` call on the same handle in between, and vice versa. All `gen_*()` functions are thread-safe. As `gen_return()` function never returns, putting `return handle;` after it is merely a convention, doubled as a way to silence the compiler warning about not returning a `gen_t *` value. As you could see by reading the source code, `gen_send()` and `gen_yield()` are actually the same function. What it does is it dumps the state, switches to the other stack, loads the state saved there and returns the value it got passed in the first place. We tried hard to make generators debug-friendly. In particular, we display the original generator call in the call stack, rather than the place `gen_send()` was called (especially useful in coroutines running on an event loop).
JavaScript
UTF-8
788
2.515625
3
[ "MIT" ]
permissive
const express = require('express'); const cors = require('cors') const {fetchArticle,fetchArticleWithQuery} = require('./scrape'); const app = express(); app.use(express.static('public')); app.use(express.urlencoded({extended:true})); app.use(express.json()); app.use(cors()); app.post('/articles',(req,res)=>{ const queryText = req.body.query; console.log(queryText); fetchArticleWithQuery(queryText).then(value =>{ res.status(200).send(value); }) }); app.get('/test', (req,res)=>{ fetchArticle().then(value =>{ res.send(value); }) // console.log(result); // res.send(result); }) app.set('port', process.env.PORT || 8080); const server = app.listen(app.get('port'),()=>{ console.log("Server listening on ",app.get('port')); });
JavaScript
UTF-8
1,465
3.078125
3
[]
no_license
var Space, SpaceImg, Asteroid, AsteroidImg, Spaceship, SpaceshipImg var gameState = "PLAY"; function preload(){ SpaceImg = loadImage("Space.png") AsteroidImg = loadImage("Asteroid.png") SpaceshipImg = loadImage("SpaceShip.png") } function setup(){ createCanvas(1000,650); edges = createEdgeSprites() //Background Space = createSprite(300,300,0,0) Space.scale = 8; Space.addImage(SpaceImg); //Space Ship Spaceship = createSprite(100,500,0,0) Spaceship.scale = 0.5; Spaceship.addImage(SpaceshipImg); AsteroidGroup = new Group(); } function draw(){ background("white"); if(gameState === "PLAY"){ //Arrow Functions if(keyDown(UP_ARROW)){ Spaceship.y = Spaceship.y - 6; } if(keyDown(DOWN_ARROW)){ Spaceship.y = Spaceship.y + 6; } Spaceship.collide(edges) if(AsteroidGroup.isTouching(Spaceship)){ gameState = "END"; } camera.position.x = Spaceship.x; camera.position.y = Spaceship.y; asteroid(); drawSprites(); } if(gameState === "END"){ textSize(50); stroke("yellow"); fill("black"); text("Game Over", 200,200); } } function asteroid(){ if(frameCount % 70 === 0){ Math.round(random(20,600)); Asteroid = createSprite(950,0,0,0); Asteroid.y = Math.round(random(20,600)); Asteroid.velocityX = -3 Asteroid.scale = 0.3; AsteroidGroup.lifetime = 50; Asteroid.addImage(AsteroidImg); AsteroidGroup.add(Asteroid); } }
Markdown
UTF-8
66,830
3.171875
3
[]
no_license
# Module 6: Implementing Server-Side Operations - [Module 6: Implementing Server-Side Operations](#module-6-implementing-server-side-operations) - [Lab: Querying and analyzing big data with Cosmos DB](#lab-querying-and-analyzing-big-data-with-cosmos-db) - [Lab Scenario](#lab-scenario) - [Objectives](#objectives) - [Lab Setup](#lab-setup) - [Exercise 1: Extending product search capabilities](#exercise-1-extending-product-search-capabilities) - [Exercise 1 Scenario](#exercise-1-scenario) - [Prepare the Environment](#prepare-the-environment) - [Task 1: Create an Azure Search Service for the Cosmos DB database](#task-1-create-an-azure-search-service-for-the-cosmos-db-database) - [Task 2: Index the Data in the Cosmos DB Database](#task-2-index-the-data-in-the-cosmos-db-database) - [Task 3: Update the Adventure-Works app to use Azure Search](#task-3-update-the-adventure-works-app-to-use-azure-search) - [Task 4: Use the Suggester in the Search Field](#task-4-use-the-suggester-in-the-search-field) - [Exercise 2: Generating Month-end Order Summaries](#exercise-2-generating-month-end-order-summaries) - [Exercise 2 Scenario](#exercise-2-scenario) - [Task 1: Create an HDInsight Cluster for Running Spark](#task-1-create-an-hdinsight-cluster-for-running-spark) - [Task 2: Upload Sample Orders to the Cosmos DB Database](#task-2-upload-sample-orders-to-the-cosmos-db-database) - [Task 3: Install and Configure PuTTY](#task-3-install-and-configure-putty) - [Task 4: Perform Interactive Queries Against Cosmos DB Using Spark](#task-4-perform-interactive-queries-against-cosmos-db-using-spark) - [Task 5: Perform Batch Operations by Using a Jupyter Notebook](#task-5-perform-batch-operations-by-using-a-jupyter-notebook) - [Exercise 3: Visualizing Sales Data](#exercise-3-visualizing-sales-data) - [Exercise 3 Scenario](#exercise-3-scenario) - [Task 1: Create an Azure Databricks Service and Cluster](#task-1-create-an-azure-databricks-service-and-cluster) - [Task 2: Create a Library and PyDocumentDB Notebook](#task-2-create-a-library-and-pydocumentdb-notebook) - [Task 3: Write Python Code to Retrieve and Display the Data](#task-3-write-python-code-to-retrieve-and-display-the-data) - [Task 4: Create a Dashboard](#task-4-create-a-dashboard) - [Task 5: Cleanup the lab environment](#task-5-cleanup-the-lab-environment) ## Lab: Querying and analyzing big data with Cosmos DB ### Lab Scenario Your company, Adventure Works, has a functioning online store. However, the customer support team has raised an issue that customers are complaining that they are unable to find the products with the current search. The head of IT has proposed making use of Azure Search to provide smart searching and auto suggestions to customers. They would also like to receive a new month end report to see if the search changes have improve sales. ### Objectives At the end of this lab, you should be able to: 1. Add a search capability to an existing web app. 2. Use HDInsight and Spark to produce a monthly report. ### Lab Setup Estimated time: **60 minutes** Virtual machine: **20777A-LON-DEV** User name: **LON-DEV\\Administrator** Password: **Pa55w.rd** ## Exercise 1: Extending product search capabilities ### Exercise 1 Scenario Customers can currently search for products by category, subcategory, name, model, or product id. You have been tasked with extending the search capabilities to include fields such as the product description. Additionally, you want to optimize the way in which the data in the Cosmos DB database is indexed, to reduce the data maintenance overhead in the database. You decide to use Azure Search to index the data and provide lookup services. The main tasks for this exercise are as follows: 1. Prepare the environment. 2. Create an Azure Search service. 3. Index data in a Cosmos DB database. 4. Add a new search feature to the Adventure Works web applicaiton. ### Prepare the Environment 1. Ensure that the **MT17B-WS2016-NAT** and **20777A-LON-DEV** virtual machines are running, and then log on to **20777A-LON-DEV** as **LON-DEV\\Administrator** with the password **Pa55w.rd**. 2. Using File Explorer, navgiate to **E:\\Labfiles\\Lab06\\Starter**, right-click **full-cosmos-setup.ps1.txt**, and then click **Edit**. 3. In Notepad, on line 2, edit **20777a-mod6-sql-&lt;your initials and day&gt;** and change the **&lt;your initials and day&gt;** to your initials and a number between 1 and 31, for example **20777a-mod6-sql-pjs14**. 4. On line 3, edit **20777a-mod6-&lt;your initials and day&gt;** and change the **&lt;your initials and day&gt;** to your initials and a number between 1 and 31, for example **20777a-mod6-pjs14**. 5. On line 4, edit **20777blobmod6&lt;your initials and day&gt;** and change the **&lt;your initials and day&gt;** to your initials and a number between 1 and 31, for example, **20777blobmod6pjs14**. 6. On line 22, set the **ResourceGroupLocation** variable to the name of your nearest location. 7. Save the file, and close Notepad. 8. Using File Explorer, navigate to **E:\\Labfiles\\Lab06\\Starter**, run **Setup.cmd** as **Administrator**. 9. When prompted enter your Azure credentials. 10. On the toolbar, click **Internet Explorer**. 11. In Internet Explorer, go to **http://portal.azure.com**, and sign in using the Microsoft account that is associated with your Azure Learning Pass subscription. 12. On the left, click **All resources**, and then click **20777a-mod6-sql-\<your initials and day\>**. 13. On the **20777a-mod6-sql-\<your initials and day\>** blade, click **Keys**. 14. Make a note of the **URI**, and **PRIMARY KEY** values. 15. On the left, click **All resources**, and then click **20777blobmod6\<your initials and day\>**. 16. Under **Settings**, click **Access keys**. 17. Make a note of the **Connect string** under **key1**. 18. On the Start menu, click **Visual Studio 2017**. 19. On the File menu, point to **Open**, and then click **Project/Solution**. 20. In the **Open Project** dialog box, go to **E:\\Labfiles\\Lab06\\Starter\\MigrateProductData**, click **MigrateProductData.sln**, and then click **Open**. 21. In Solution Explorer, double-click **App.config**. 22. In the **Value** attribute of the **BlobStorageConnectionString** key, paste the value you noted in step 10, replacing the text **enter Blob storage connection string**. 23. Press F5 to build and run the application. 24. In the console window, once completed, press Enter. 25. On the **File** menu, click **Exit**. ### Task 1: Create an Azure Search Service for the Cosmos DB database 1. In the Azure portal, in the left panel click **+ Create a Resource**. 2. On the **New** blade, in the **Search** box, type **azure search** then press Enter. Click **Azure Search**, then click **Create**. 3. On the **Azure Search** blade, in the **URL** box, type **20777a-search-&lt;your name&gt;-&lt;the day&gt;** for example, **20777a-search-john-31**. 4. Under **Resource Group**, select **Use existing**, and then select **20777Mod06**. 5. In the **Location** box, select the same location as your Cosmos DB account, or the closest physical location if the location you selected for your Cosmos DB account is not available. 6. Click **Pricing tier**. 7. On the **Choose your pricing tier** blade, click **Free**, and then click **Select**. 8. Click **Create**, and wait for the search account to be created before proceeding. 9. Make a note of the **Manage query keys**, and **&lt;empty&gt;** values in the **Keys** settings of the Search Service. ### Task 2: Index the Data in the Cosmos DB Database 1. In the Azure portal, go to your Cosmos DB account. 2. Click **Data Explorer**, select the **Adventure-Works** database, select the **Data** collection, and then click **Scale & Settings**. 3. Modify the **Indexing Policy** to include the excluded paths shown below, and then click **Save**. This policy prevents the **description**, **documentation**, and **images** fields from being indexed. The **description** field is free text and can be quite large; you will configure Azure Search to index this field more efficiently. The **documentation** and **images** fields are references to items in blob storage, and indexing these fields is not worthwhile. ```JSON { "indexingMode": "consistent", "automatic": true, "includedPaths": [ { "path": "/*", "indexes": [ { "kind": "Range", "dataType": "Number", "precision": -1 }, { "kind": "Range", "dataType": "String", "precision": -1 }, { "kind": "Spatial", "dataType": "Point" } ] } ], "excludedPaths": [ { "path": "/description/*" }, { "path": "/documentation/*" }, { "path": "/images/*" } ] } ``` 4. Return to your Search Service account in the Azure portal. 5. Click **Import Data**. 6. In the **Import data** blade, click **Connect to your data**, and then click **Cosmos DB**. 7. In the **New data source** blade, in the **Name** box, type **productdata**. 8. Under **Cosmos DB acount**, click **Select an account**, and select your Cosms DB account. 9. In the **Database** field, select **Adventure-Works**, in the **Collection** field, select **Data**, and then click **OK**. 10. In the **Import Data** blade, under **Index**, click **Customize target index**. 11. Delete the **ttl** field from the index. 12. Mark all remaining fields as **Retrievable**. 13. Mark the following fields as **Filterable**: - **id** - **partitionkey** - **productcategory** - **productname** - **productnumber** - **model** - **description** - **doctype** 14. Mark the following fields as **Searchable**: - **productcategory** - **productname** - **productnumber** - **model** - **description** 15. Select **Suggester**, set the **suggester name** to **suggest**, and set the **Search mode** to **analyzingInfixMatching**. 16. Mark the following fields to use the suggester, and then click **OK**: - **productname** - **model** - **description** 17. In the **Create an Indexer** blade, set the **Name** to **productsindexer**, change the **Schedule** to **Hourly**, and then click **OK**. 18. On the **Import data** blade, click **OK**. 19. On the search service blade, under **Usage**, click the **Indexers** box. 20. On the **Indexers** blade, click the **productsindexer** index. 21. On the **productsindexer** blade, click **Run**, and then click **Yes**. 22. Wait for a minute, close the **productsindexer** blade, and then in the **Indexers** blade, click the **productsindexer** index again. 23. On the **productsindexer** blade, verify that indesing was completed successfully. 24. Close the **productsindexer** blade. 25. Close the **Indexers** blade. 26. On the search service blade, click **Search explorer**. 27. On the **Search explorer** blade, click **Search**. Verify that the search returns a list of documents. 28. In the **Query string** box, type **search=bike**, and then click **Search**. Verify that a list of documents appear that include the text **bike** in one of the searchable fields. 29. In the **Query string** box, type **search=natural**, and then click **Search**. This time only two documents should be retrieved. Both documents include the word **natural** in the **description** field. ### Task 3: Update the Adventure-Works app to use Azure Search 1. Using Visual Studio 2017, open the **Adventure-Works** solution in the **E:\Labfiles\Lab06\Starter\Exercise 1\Adventure-Works** folder. 2. In Solution Explorer, open the **Repository.cs** file. The **Repository** implements the functionality required by the app to retrieve and maintain data in the Cosmos DB database. You will extend this class to incorporate Azure Search capabilities. 3. Find the comment **TODO: Add namespaces containing Search functionality**, and add the following using directives: ```CSharp using Microsoft.Azure.Search; using Microsoft.Azure.Search.Models; ``` 4. In the **Repository** class, after the comment **TODO: Define fields to support connecting to the Azure Search Service**, add the following statements. This code defines the variables that the repository will use to connect to the search service. The **SearchIndexClient** type provides the methods that an app can use to send search requests and retrieve the results. ```CSharp private static string searchService; private static string queryKey; private static string searchIndex; private static string suggesterName; private static SearchIndexClient searchClient; ``` 5. In the **Initialize** method, add the following statements after the comment **TODO: Initialize the connection to the Azure Search Service**. These statements read the parameters required to connect to the Azure Search Service from the web.config file. You will provide values for these parameters when you configure the application later: ```CSharp searchService = ConfigurationManager.AppSettings["SearchService"]; queryKey = ConfigurationManager.AppSettings["SearchServiceQueryKey"]; searchIndex = ConfigurationManager.AppSettings["SearchIndex"]; suggesterName = ConfigurationManager.AppSettings["Suggester"]; searchClient = new SearchIndexClient(searchService, searchIndex, new SearchCredentials(queryKey)); ``` 6. Find the **SearchForItemsAsync** method shown below. You will complete this method to use the Azure Search Service to find all documents in the Cosmos DB database that match a specified search term passed in as the **SearchString** parameter. The **advanced** parameter indicates whether the string in the **SearchString** parameter should be treated as a literal value, or it contains an Azure Search expression: ```CSharp // TODO: Use Azure Search to find items that match the specified search string public static async Task<IEnumerable<T>> SearchForItemsAsync(string searchString, bool advanced) { // TODO: If this is not an advanced query, enclose the search string in quotes to ensure that Azure Search treats it as a literal rather than a query expression // TODO: Specify that the search should only return the id and partitionkey fields of the document from the index // TODO: Find the ids of all documents that match the search string // TODO: Iterate through the results, and construct a list of matching documents from the Cosmos DB database List<T> docs = new List<T>(); foreach (var result in searchResults.Results) { // TODO: Construct the document URI for the document // TODO: Extract the partition key from the index // TODO: Fetch the document and add it to the list } // TODO: Return the list of documents identified by the search } ``` 7. After the comment **TODO: If this is not an advanced query, enclose the search string in quotes to ensure that Azure Search treats it as a literal rather than a query expression**, add the following block of code. If the **advanced** parameter is false, these statements add quotes to search string to ensure that it is handled as a literal value by the Azure Search Service: ```CSharp if (!advanced) { searchString = $"\"{searchString}\""; } ``` 8. After the comment **TODO: Specify that the search should only return the id and partitionkey fields of the document from the index**, add the following statements. The purpose of the Azure Search Service index is to quickly locate the id of matching documents in the Cosmos DB database. When you retrieve these documents from the database you will also require the partition key: ```CSharp var searchParams = new SearchParameters { Select = new [] { "id", "partitionkey" } }; ``` 9. After the comment **TODO: Find the ids of all documents that match the search string**, add the following code that sends the search request to the Azure Search Service. ```CSharp var searchResults = await searchClient.Documents.SearchAsync<dynamic>(searchString, searchParams); ``` 10. In the **foreach** loop that iterates through the results of the search request, after the comment **TODO: Construct the document URI for the document**, add the following statements. This code uses the id returned by the Azure Search Service to build the URI of the corresponding document in the Cosmos DB database. ```CSharp string docID = result.Document.id; Uri docUri = UriFactory.CreateDocumentUri(database, collection, docID); ``` 11. After the comment **TODO: Extract the partition key from the index**, add the following statements. The **RequestOptions** object will be passed to a Cosmos DB request that fetches the document: ```CSharp string partitionkey = result.Document.partitionkey; var options = new RequestOptions { PartitionKey = new PartitionKey(partitionkey) }; ``` 12. After the comment **TODO: Fetch the document and add it to the list**, add the following statements. Racall that the **ReadDocumentAsync** method provides the fastest way to access data in a Cosmos DB database: ```CSharp var response = await client.ReadDocumentAsync<T>(docUri, options); docs.Add(response.Document); ``` 13. After the comment **TODO: Return the list of documents identified by the search**, replace that code that throws the **NotImplementedException** with the following statement: ```CSharp return docs; ``` 14. In Solution Explorer, expand the **Models** folder, and then double-click **ViewModel.cs**. 15. In the **ProductViewModel** class, after the comment **TODO: Add the "AdvancedSearch" field to the view model, to record whther the user has selected a simple text or expression-based search**, add the following property: ```CSharp public bool AdvancedSearch { get; set; } ``` 16. In Solution Explorer, expand the **Controllers** folder, and then double-click the **ProductsController.cs** file. 17. Find the **SearchProductsAsync** method. You will complete this method to search for products using the repository. 18. After the comment **TODO: Use the repository to find products that match the specified search string in the Product View Model**, add the following statement: ```CSharp IEnumerable<Product> products = await Repository<Product>.SearchForItemsAsync(productViewModel.SearchString, productViewModel.AdvancedSearch); ``` 19. After the comment **TODO: Construct a new view model containing the results and display it**, replace the statement that throws the **NotImplementException** with the following code. This statement constructs a new view model containing the results of the search, and sends the view model back to the view for display: ```CSharp return View("FindProducts", new ProductViewModel { Products = products, SelectableCategories = Session["selectableCategories"] as ProductCategoryViewModel ?? await InitializeCategoriesAsync(), SelectableSubcategories = Session["selectableSubcategories"] as ProductSubcategoryViewModel ?? await InitializeSubCategoriesAsync() }); ``` 20. In Solution Explorer, expand the **Views** folder, exapnd the **Products** folder, and then double-click the **FindProducts.cshtml** file. 21. Find the comment **&lt;!-- TODO: Adjust the form to enable the user to specify a simple or advanced search --&gt;**. Note that this form calls the **SearchProducts** action (which runs the **SearchProductsAsync** method) in the **ProductsController**. 22. Replace the **&Html.TextBoxFor** statement after this comment with the following markup. This code adds the search string entered by the user on the form, together with a boolean indicating whether the user selected the **Advanced** check box, to the view model which is passed to the **SearchProductsAsync** method: ```HTML <table class="table"> <tr> <td> @Html.TextBoxFor(t => t.SearchString, new { @class = "form-control" }) </td> <td> @Html.Label("AdvancedSearch", "Advanced?", new { @class = "form-control" }) </td> <td> @Html.CheckBoxFor(t => t.AdvancedSearch, new { @class = "form-control" }) </td> </tr> </table> ``` 23. Edit the Web.config file and specify values for the following settings: - **EndpointUrl**. The URL of your Cosmos DB account - **PrimaryKey**. The primary key for your Cosmos DB account - **SearchService**. The name of your Azure Search Service. - **SearchServiceQueryKey**. The query key for your Azure Search Service. 24. Build and run the app. 25. In the **Search for Products** section of the form, enter **natural**, and then click **Search**. Verify that the search returns two products (Mountain Bike Socks, M and L). On either row, click **Details**. The **Description** contains the following text: ```Text Combination of natural and synthetic fibers stays dry and provides just the right cushioning. ``` 26. Go back to the **Adventure-Works Product Catalog** page and search for **Bib-Shorts**. The results should list three products (Men's Bib-Shorts, S, M and L). 27. Select the **Advanced?** option and then click **Search** again. This time the search returns more products. The search string has been interpreeted as a query expression, and now finds all products that contain the text **Bib** and/or **Shorts** 28. Experiment with other searches. When you have finished, close the app and return to Visual Studio. ### Task 4: Use the Suggester in the Search Field 1. In Visual Studio, return to the **Repository.cs** file and find the **GetSuggestions** method. THis method takes a string parameter, and will use the Azure Search Service Suggester that you created earlier to suggest matching terms from the search index. 2. After the comment **TODO: Specify the Suggestion parameters: enable fuzzy searching, fetch the top 10 results, and add highlighting**, add the following code: ```CSharp var parameters = new SuggestParameters { UseFuzzyMatching = true, Top = 10, HighlightPreTag = "<b>", HighlightPostTag = "</b>" }; ``` 3. After the comment **TODO: Retrieve suggestions from the Azure Search service**, add the following statement: ```CSharp DocumentSuggestResult result = await searchClient.Documents.SuggestAsync(term, suggesterName, parameters); ``` 4. After the comment **TODO: Return the suggestions as a list of strings**, replace the code that throws the **NotImplementedException** with the following statement. This statement extracts the **Text** field from each of the results and converts these items into a list: ```CSharp return result.Results.Select(x => x.Text).ToList(); ``` 5. Edit the **ProductControler.cs** file and find the **SuggestAsync** method shown below. This method responds to the **Suggest** HTTP GET request. The parameter is a string on which to base suggestions: ```CSharp // TODO: Method called by the autocomplete feature of the form to use the Suggester in Azure Search to "suggest" search strings [ActionName("Suggest")] [HttpGet] public async Task<ActionResult> SuggestAsync(string term) { // TODO: Call the GetSuggestions method in repository to find suggestions that match the term provided // TODO: Return the list of suggestions throw new NotImplementedException(); } ``` 6. After the comment **TODO: Call the GetSuggestions method in repository to find suggestions that match the term provided**, add the following statement: ```CSharp var suggestions = await Repository<Product>.GetSuggestions(term); ``` 7. After the comment **TODO: Return the list of suggestions**, replace the code that throws the **NotImplementedException** with the following statement: ```CSharp return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = suggestions }; ``` 8. Return to the **FindProducts.cshtml** view and find the comment **&lt;!-- TODO: Add jquery-ui stylesheet and function to add autocomplete to the SearchString text field--&gt;** near the top of the file. You will use the **autocomplete** feature of the jquery-ui package to send the **Suggest** request to the controller as te user enters data into the **Search** field. 9. Add the following markup to the view. This code adds a reference to the style-sheet that is used by the jquery-ui package: ```HTML <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> ``` 10. Inside the **&lt;script&gt;** tag, after the comment **TODO: Replace anything that looks like HTML markup from the SearchString field after performing autocomplete**, add the following JavaScript function: ```JavaScript var updateTextbox = function (event, ui) { var result = ui.item.value.replace(/<\/?[^>]+(>|$)/g, ""); $("#SearchString").val(result); return false; }; ``` 11. After the comment **TODO: Trigger autocomplete on the SearchString field to invoke the Suggest method on the form. The data typed so far is provided as an input parameter to the method**, add the following code. The call to the jquery-ui **autocomplete** function invokes the **Suggest** action once the user has entered three or more characters. The JSON data returned by the **Suggest** is displayed as a drop-down listbox by the **autocomplete** function. When the user selects an item from the list, any HTML tags (such as those generated by Azure Suggester highlighting) are stripped out using the **updateTextbox** function as the item is written to the **SearchString** field: ```JsvaScript $("#SearchString").autocomplete({ html: true, source: "/Products/Suggest", minLength: 3, select: updateTextbox, focus: updateTextbox }).data("ui-autocomplete")._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.label + "</a>") .appendTo(ul); }; ``` 12. Build and run the app. 13. In the **Search** box, type **nat**. A list of suggestions should appear, with the matching text highlighted in bold. Note that similar items are included that are not necessarily an exact match for the text; this is because the repository uses fuzzy matching with the suggester. 14. Change the text to **natu**, and the list should be refined to two entries. 15. Click one of the entries and then click **Search**. The result should be two products. 16. Click **Details**, and you should see that both products have identical descriptions containing the word **natural**. 17. Clear the **Search** box, and then enter **bib**. Select **Men's Bib-Shorts, M** and then click **Search**. This time only a single product should be displayed. > **Note:** If you select **Advanced** and click **Search** again, you will get more results. This is because the text in the search box is now interpreted as a query expression, and some of the characters have special meanings. 18. Experiment with other suggestions and searches. Close the app when you have finished. ## Exercise 2: Generating Month-end Order Summaries ### Exercise 2 Scenario As part of the month-end processing, you need to generate summaries that indicate how many orders were placed, the total value of those orders, and which were the most popular products for that month. ### Task 1: Create an HDInsight Cluster for Running Spark 1. In the Azure Portal, in the left pane, click **+ Create a resource**. 2. Click **Analytics**, and then click **HDInsight**. 3. On the **HDInsight** blade, click **Custom (size, settings, apps)**. 4. On the **Basics** blade, type the following details, and then click **Cluster type**: - Cluster name: **hdi-&lt;your name&gt;&lt;date&gt;** - Subscription: **your subscription** 5. On the **Cluster configuration** blade, enter the following details, and then click **Select**: - Cluster type: **Spark** - Version: **Spark 2.3.0 (HDI 3.6)** 6. On the **Basics** blade, enter the following details: - Cluster login username: **sparkadmin** - Cluster login password: **Pa55w.rdPa55w.rd** - Secure Shell (SSH) username: **sadmin** - Use same password as cluster login: **selected** - Resource group (use existing): **20777Mod06** - Location: Select your region 7. On the **Basics** blade, click **Next**. 8. On the **Storage** blade, under **Select a Storage account**, click **Create new**. 9. In the **Create a new Storage account** box, type **&lt;your name&gt;&lt;date&gt;sa**. 10. In the **Default container** box, replace the suggested name with the name of your cluster. 11. Leave the other settings at their defaults, and then click **Next** 12. On the **Applications (optional)** blade, click **Next**. 13. On the **Cluster size** blade, in the **Number of Worker nodes** box, type 2. 14. Click **Worker node size**. 15. On the **Choose your node size blade**, click **D12 v2 Optimized**, and then click **Select**. 16. Click **Head node size**. 17. On the **Choose your node size** blade, click **View all**, click **D12 v2 Optimized**, and then click **Select**. 18. On the **Cluster size** blade, click **Next**. 19. On the **Advanced settings** blade, click **Next**. 20. On the **Cluster summar**y blade, click **Create**. 21. Wait for the cluster to be provisioned and the status to show as **Running**. This is likely to take at least 10 minutes. You can continue with the next task while cluster is being built. ### Task 2: Upload Sample Orders to the Cosmos DB Database 1. Using Visual Studio, open **GenerateOrderData** solution in the **E:\\Labfiles\\Lab06\\Data\\GenerateOrderData** folder. 2. In Solution Explorer, open the **app.config** file. 3. Specify the following configuration settings in the **appSettings** section: - **EnpointUrl**: The URL of your Cosmos DB account. - **PrimaryKey**: The primary access key for the Cosmos DB account. - **Database**: Adventure-Works - **Collection**: Data - **NumOrders**: 5000. This is the number of orders that will be created. 4. Build and run the application. The orders will be generated quckly, but might take a minute or two to be uploaded to the database. 5. In the Azure portal, go to your Cosmos DB account. 6. Select **Data Explorer**, select the **Adventure-Works** database, and then select the **Data** collection. 7. Click **New SQL Query**, and enter the following query: ```SQL SELECT * FROM c WHERE c.doctype = "ShoppingCartOrder" ``` 8. Click **Execute Query**, and examine the first few orders that have been created. 9. Change the query as follows: ```SQL SELECT VALUE COUNT(1) FROM c WHERE c.doctype = "ShoppingCartOrder" ``` 10. Click **Execute Query**, and verify that the database contains 5000 orders. ### Task 3: Install and Configure PuTTY 1. Using Internet Explorer, browse to **https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html**. 2. Download the 64-bit version of putty.exe and save it as **E:\putty\putty.exe**. 3. Download 64-bit version of pscp.exe, and save it as **E:\putty\pscp.exe**. 4. Return to the Azure Portal and verify that the HDInsight cluster has been created. If not, wait for prvisioning to complete. 5. Click **All Resources**. 6. On the **All Resources** blade, click the HDInsight cluster. 7. On the cluster blade, click **SSH + Cluster Login**. 8. On the **SSH + Cluster login** blade, in the **Hostname** box, select the name of your cluster (it should be the only entry), then click the **Click to copy** button (two document icons on a blue background). 9. In File Explorer, navigate to **E:\putty**, and then double-click **putty.exe**. 10. In the **PuTTY Configuration** window, right-click the **Host Name (or IP Address)** box, and paste the hostname stored on the clipboard. Edit the pasted value to remove **ssh sadmin@** at the beginning of the host name. 11. In the **Saved Sessions** box, type **HDInsight**, click **Save**, and then click **Open**. 12. In the **PuTTY Security Alert** window, click **Yes**. 13. In the PuTTY window, at the **login as** prompt, login as **sadmin** with password **Pa55w.rdPa55w.rd**. If login is successful, you will be presented with a prompt that starts **sadmin@hn0-**. ### Task 4: Perform Interactive Queries Against Cosmos DB Using Spark 1. At the prompt in PuTTY, type the following command and wait for the Spark shell to start running: ```Bash spark-shell --master yarn --packages com.microsoft.azure:azure-cosmosdb-spark_2.3.0_2.11:1.2.0 ``` 2. When the **scala>** appears, enter the following commands: ```Scala import com.microsoft.azure.cosmosdb.spark.schema._ import com.microsoft.azure.cosmosdb.spark._ import com.microsoft.azure.cosmosdb.spark.config._ ``` 3. Enter the following command that creats a configuration object that you will use to retrieve the orders held in the Cosmos DB database. Replace **\~URL\~** with the URL of yor Cosmos DB account, and replace **\~KEY\~** with the primary access key for the account: ```Scala val databaseConfig = Config(Map( "Endpoint" -> "~URL~", "Masterkey" -> "~KEY~", "Database" -> "Adventure-Works", "Collection" -> "Data", "query_custom" -> "SELECT * FROM c WHERE c.doctype = 'ShoppingCartOrder'" )) ``` 4. Run the following command. This command executes the query and creats a temporary Hive view called **orders** that references the results (the data in the view is not persisted): >**Note:** You will receive a warning specifying that JNI has not been loaded. You can ignore this warning. ```Scala val collection = spark.sqlContext.read.cosmosDB(databaseConfig) collection.createOrReplaceTempView("orders") ``` 5. Run the following query, and verify that it fins 5000 rows. Note that the query runs as a Spark job: ```Scala val data = spark.sql("SELECT * FROM orders") data.count() ``` 6. Run the following command. This command shows the schema generated for the orders view, based on the data returned by the query in the configuration object. ```Scala data.printSchema ``` 7. Notice that the **orderitems** field is structured as an array in the view: ```Text root |-- _attachments: string (nullable = true) |-- _etag: string (nullable = true) |-- _rid: string (nullable = true) |-- _self: string (nullable = true) |-- _ts: integer (nullable = true) |-- customerdiscountrate: integer (nullable = true) |-- dateplaced: long (nullable = true) |-- doctype: string (nullable = true) |-- id: string (nullable = true) |-- isshoppingcartororder: string (nullable = true) |-- itemscost: double (nullable = true) |-- lastupdated: long (nullable = true) |-- numberofitems: integer (nullable = true) |-- orderitems: array (nullable = true) | |-- element: struct (containsNull = false) | | |-- backorderreference: string (nullable = true) | | |-- lineitemtotalcost: double (nullable = true) | | |-- numberincartorordered: integer (nullable = true) | | |-- numberonbackorder: integer (nullable = true) | | |-- productid: string (nullable = true) | | |-- productname: string (nullable = true) | | |-- productnumber: string (nullable = true) | | |-- subcategory: string (nullable = true) | | |-- unitcost: double (nullable = true) |-- orderstatus: string (nullable = true) |-- partitionkey: string (nullable = true) |-- totalcost: double (nullable = true) |-- ttl: integer (nullable = true) ``` 8. Perform the following query. This query returns the name of the first product in each order together with the number ordered (the output is truncated to display only the first 20 orders): ```Scala spark.sql("SELECT orderitems[0].productname, orderitems[0].numberincartorordered FROM orders").show() ``` 9. Run the following query. This query reports the total value of orders that are in progress, that have been delivered, and that have been cancelled: ```Scala spark.sql("SELECT SUM(totalcost), orderstatus FROM orders GROUP BY orderstatus").show() ``` 10. Experiment by running other queries against the **orders** view. 11. When you have finished, type **:quit**, press Enter, and then press CTRL+C to close the spark shell. ### Task 5: Perform Batch Operations by Using a Jupyter Notebook 1. Open a command prompt window and go to the **E:\Labfiles\Lab06\starter\Exercise 2** folder. 2. Run the following command. This command uses the pscp utility to upload the jar file containing the Cosmos DB connector for Spark to the first head node of your HDInsight cluster. Replace **&lt;cluster-name&gt;** with **hdi-&lt;your name&gt;&lt;date&gt;**. Enter **Pa55w.rdPa55w.rd** when prompted for a password: ```Script e:\putty\pscp azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar sadmin@<cluster-name>-ssh.azurehdinsight.net:azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar ``` 3. Open the HDInsight PuTTY session, and connect using **sadmin** and **Pa55w.rdPa55w.rd**. 4. In the PuTTY window, run the following command. Verify that the file **azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar** is listed: ```Bash ls ``` 5. Run the following command to copy the Cosmos DB connector to the folder required by Spark applications: ```Bash sudo cp *.jar /usr/hdp/current/spark2-client/jars/ ``` 6. Run the following commands to copy the Cosmos DB connector to the same folder on the remaining head node and worker node of the HDInsight cluster. At each prompt **Are you sure you want to continue connecting**, type **yes**, and enter the pasword **Pa55w.rdPa55w.rd**: ```Bash hn=`hostname` && hn1="${hn/hn0-/hn1-}" rcp azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar $hn1:azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar hn=`hostname` && wn0="${hn/hn0-/wn0-}" rcp azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar $wn0:azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar hn=`hostname` && wn1="${hn/hn0-/wn1-}" rcp azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar $wn1:azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar ssh $hn1 sudo cp *.jar /usr/hdp/current/spark2-client/jars/ exit ssh $wn0 sudo cp *.jar /usr/hdp/current/spark2-client/jars/ exit ssh $wn1 sudo cp *.jar /usr/hdp/current/spark2-client/jars/ exit ``` >**Note:** If the **wn1** node shows an error, replace **wn1** with **wn2** and re-run the command. 7. Return to the Azure portal and go to your HDInsight cluster. 8. On the **HDInsight cluster** blade, in the **Quick Links** section, click **Cluster dashboard**, and then click **Ambari Home**. 9. Log in as **sparkadmin** with password **Pa55w.rdPa55w.rd** when prompted. 10. Restart the **Spark2** services. 11. On the **Cluster dashboards** blade, click **Jupyter Notebook**. Internet Explorer opens a new page connected to the Jupyter UI. 12. On the **Jupyter** page, click **New** and then click **Spark**. This action creates a Scala notebook that can perform Spark queries. 13. In the page heading, click **Untitled** and change the name of the notebook to **Monthly Analysis**. >**Note:** The complete code for the notebook is available in the file **E:\\Labfiles\\Lab06\\Solution\\Exercise 2\\Monthly+Analysis.txt**. 14. In the first cell of the notebook, add the following Scala code. This code creates a useful utility class that can convert between datetime values and ticks (as used by the documents in the CosmosDB database): ```Scala // Helper class for converting between dates and ticks import java.util.Calendar import java.util.Date object DateHelper { private final val TICKS_AT_EPOCH = 621355968000000000L private final val TICKS_PER_MILLISECOND = 10000 def getUTCTicks(date: Date): Long = { val calendar = Calendar.getInstance calendar.setTime(date) return (calendar.getTimeInMillis() * TICKS_PER_MILLISECOND) + TICKS_AT_EPOCH } def getDate(ticks: Long): Date = { return new Date((ticks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND) } } ``` 15. On the **Insert** menu, click **Insert Cell Below**. 16. In the new cell, add the following code ```Scala // Get the time in ticks one month ago val calendar = Calendar.getInstance calendar.add(Calendar.MONTH, -1) val then = calendar.getTime val thenInTicks = DateHelper.getUTCTicks(then) ``` 17. On the **Insert** menu, click **Insert Cell Below**. 18. In the new cell, add the following code. This code imports the libraries required by the Cosmos DB connector: ```Scala import com.microsoft.azure.cosmosdb.spark.schema._ import com.microsoft.azure.cosmosdb.spark._ import com.microsoft.azure.cosmosdb.spark.config._ ``` 19. On the **Insert** menu, click **Insert Cell Below**. 20. In the new cell, add the following code. This uses an %%sql magic to drop the orders table in the Hive database if it currently exists. This step is nessary as you will create a virtual table, named orders, that references the orders in the Data collection in the CosmosDB database: ```SQL %%sql -- Drop the orders table if it currently exists DROP TABLE IF EXISTS orders ``` 21. On the **Insert** menu, click **Insert Cell Below**. 22. Add the following SQL magic to the new cell. Replace **\~URI\~** with the URI of your Cosmos DB acount, and replace **\~KEY\~** with the primary access key for the account. This code creates a virtual table that references the orders data in the Cosmos DB database directly rather than by creating a Hive view (the data is not copied, rather the query is performed everytime the table is accessed): ```SQL %%sql -- Rebuild the orders table as a reference to the Data collection in the Cosmos DB database -- Don't include the orderitems subdocuments - these are arrays and are better handled as a seperate external table CREATE TABLE orders using com.microsoft.azure.cosmosdb.spark options ( endpoint "~URI~", masterkey "~KEY~", database "Adventure-Works", collection "Data", query_custom "SELECT c.id, c.numberofitems, c.itemscost, c.customerdiscountrate, c.totalcost, c.dateplaced, c.orderstatus, c.lastupdated FROM c WHERE c.doctype = 'ShoppingCartOrder'") ``` 23. On the **Insert** menu, click **Insert Cell Below**. 24. In the new cell, add the following code. This drops the orderitems table in the Hive database. You will create another table that contains the order items from all of the orders: ```SQL %%sql -- Drop the orderitems table if it currently exists DROP TABLE IF EXISTS orderitems ``` 25. On the **Insert** menu, click **Insert Cell Below**. 26. Add the following SQL magic to the new cell. As before, replace **\~URI\~** with the URI of your Cosmos DB acount, and replace **\~KEY\~** with the primary access key for the account. This code creates another virtual table that references the order items for each order in the Cosmos DB database. This data is held as subdocuments, and each subdocument contains an array of order items. The query that fetches the data for this table uses a CosmosDB JOIN clause to flatten this data out into a simple table which makes the data easier to handle using Spark SQL.: ```SQL %%sql -- Get the orderitems for orders placed in the last month. The JOIN clause flattens the arrays in the subdocuments into a tabular format CREATE TABLE orderitems using com.microsoft.azure.cosmosdb.spark options ( endpoint "~URI~", masterkey "~KEY~", database "Adventure-Works", collection "Data", query_custom "SELECT o.id, o.dateplaced, o.orderstatus, i.productnumber, i.productname, i.numberincartorordered, i.lineitemtotalcost FROM o JOIN i IN o.orderitems WHERE o.doctype = 'ShoppingCartOrder'") ``` 27. On the **Insert** menu, click **Insert Cell Below**. 28. Add the following Scala code to the new cell. This code creates a Spark dataframe that retrieves all documents from the CosmosDB collection (via the orders virtual table) for orders that have been placed in the last month: ```Scala // Find the status and cost of all orders placed in the last month // Note: Only retrieve the necessary columns (not "*"), to keep the dataframe lean val orders = spark.sqlContext.sql(s"SELECT orderstatus, totalcost FROM orders WHERE dateplaced > $thenInTicks") ``` 29. On the **Insert** menu, click **Insert Cell Below**. 30. Add the following Scala code to the new cell. This code creates a new dataframe that summarizes the data just fetched, to generate a count of the number of orders in the last month, grouped by order status: ```Scala // Find the total number of orders, grouped by order status ("In progress", "Delivered", "Cancelled") val numbersByStatus = orders.groupBy("orderstatus").count() numbersByStatus.show ``` 31. On the **Insert** menu, click **Insert Cell Below**. 32. Add the following Scala code to the new cell. This code generates a dataframe that shows the total revenue grouped by order status. Using this dataframe you can quickly see how much revenue has been generated by delivered orders and orders currently in progress, as well as determine how much money was refunded due to cancelled orders: ```Scala // Find the sum value of the revenue for all orders, grouped by order status val revenuesByStatus = orders.groupBy("orderstatus").sum("totalcost") revenuesByStatus.show ``` 33. On the **Insert** menu, click **Insert Cell Below**. 34. Add the following Scala code to the new cell. This code generates a dataframe that summarizes information about the items ordered in the last month, retrieved using the orderitems virtual table. You can use this dataframe to establish which were the most popular products, and which products generated the most revenue: ```Scala // Find the items ordered in the last month val orderitems = spark.sqlContext.sql(s"SELECT productnumber, productname, SUM(numberincartorordered) AS numordered, SUM(lineitemtotalcost) AS revenue FROM orderitems WHERE dateplaced > $thenInTicks AND orderstatus <> 'Cancelled' GROUP BY productnumber, productname") orderitems.show(5) ``` 35. On the **Insert** menu, click **Insert Cell Below**. 36. Add the following Scala code to the new cell. This code sorts the order item summary records by number ordered. The result shows the products in decreasing order or popularity: ```Scala // Sort the data in descending order of volume (numordered) val orderedByVolume = orderitems.sort($"numordered".desc) orderedByVolume.show(5) ``` 37. On the **Insert** menu, click **Insert Cell Below**. 38. Add the following Scala code to the new cell. This code sorts the order item summary records by revenue: ```Scala // Sort the data in descending order of revenue per product val orderedByRevenue = orderitems.sort($"revenue".desc) orderedByRevenue.show(5) ``` 39. On the **Insert** menu, click **Insert Cell Below**. 40. Add the following Scala code to the new cell. This code configures a connection that you will use to write the summary data just generated back to the Cosmos DB database. Replace **\~URI\~** and **\~KEY\~** with the values for your Cosmos DB account: ```Scala // Write the summaries back to Cosmos DB with doctype "MonthlySummary" import org.apache.spark.sql._ val writeConfigMap = Map( "Endpoint" -> "~URI~", "Masterkey" -> "~KEY~", "Database" -> "Adventure-Works", "Collection" -> "Data" ) val writeConfig = Config(writeConfigMap) ``` 41. On the **Insert** menu, click **Insert Cell Below**. 42. Add the following Scala code to the new cell. This code creates a text value containing the month and year. You will add this value to the summary data: ```Scala val month = calendar.get(Calendar.MONTH) + 1 val year = calendar.get(Calendar.YEAR) val monthYear = s"$month/$year" ``` 43. On the **Insert** menu, click **Insert Cell Below**. 44. Add the following Scala code to the new cell. This code augments the "orders by status" dataframe with three columns; doctype ("MonthlySummary"), month (the text value just created), and partitionKey ("summary"). It then uses the connection to the Cosmos DB database to write this data as a document back to the Cosmos DB database: ```Scala val numbers = numbersByStatus.withColumn("doctype", functions.lit("MonthlySummary")).withColumn("month", functions.lit(monthYear)).withColumn("partitionKey", functions.lit("summary")) numbers.write.mode(SaveMode.Append).cosmosDB(writeConfig) numbers.show(5) ``` 45. On the **Insert** menu, click **Insert Cell Below**. 46. Add the following Scala code to the new cell. This code is similar to the previous cell except that it saves the data in the "revenues by status" dataframe: ```Scala val revenues = revenuesByStatus.withColumn("doctype", functions.lit("MonthlySummary")).withColumn("month", functions.lit(monthYear)).withColumn("partitionKey", functions.lit("summary")) revenues.write.mode(SaveMode.Append).cosmosDB(writeConfig) revenues.show(5) ``` 47. On the **Insert** menu, click **Insert Cell Below**. 48. Add the following Scala code to the new cell. This code saves the dataframe that shows the popularity of products: ```Scala val itemsVolume = orderedByVolume.withColumn("doctype", functions.lit("MonthlySummary")).withColumn("month", functions.lit(monthYear)).withColumn("partitionKey", functions.lit("summary")) itemsVolume.write.mode(SaveMode.Append).cosmosDB(writeConfig) itemsVolume.show(5) ``` 49. On the **Insert** menu, click **Insert Cell Below**. 50. Add the following Scala code to the new cell. This code displays a dataframe that shows the revenue generated by product. You do not need to save this data,a s it is the same as that generated by te previous dataframe, just in a different order: ```Scala val itemsRevenue = orderedByRevenue.withColumn("doctype", functions.lit("MonthlySummary")).withColumn("month", functions.lit(monthYear)).withColumn("partitionKey", functions.lit("summary")) itemsRevenue.show(5) ``` 51. In the toolbar, click the **Save and checkpoint** icon. 52. On the **Cell** menu, click **Run All**. You should see the results output by each cell as it is executed. > **Note:** With the small-scale Spark configuation used by this lab (to save costs), the final few cells that write the data back to Cosmos DB can take some time to run. You should continue with the next exercise while the notebook executes, and come back to verify the results later. 53. When the notebook has completed, using the Azure portal go to your Cosmos DB account, select **Document Explorer**, select the **Adventure-Works** database, select the **Data** collection, and then click **New SQL Query**. Enter the following query, and then click **Execure Query**: ```SQL SELECT * FROM c WHERE c.doctype = "MonthlySummary" ``` 54. Verify that a set of summary documents appear. The example below shows the typical documents showing the number of orders by order status: ```JSON [ { "doctype": "MonthlySummary", "orderstatus": "Delivered", "month": "7/2018", "partitionKey": "summary", "count": 236, "id": "84c0b06a-4191-4859-b5d6-9cd434bd5a71", "_rid": "CyxpAK2n81T2HQAAAAAAAA==", "_self": "dbs/CyxpAA==/colls/CyxpAK2n81Q=/docs/CyxpAK2n81T2HQAAAAAAAA==/", "_etag": "\"0000ef1f-0000-0000-0000-5b6af6f00000\"", "_attachments": "attachments/", "_ts": 1533736688 }, { "doctype": "MonthlySummary", "orderstatus": "In progress", "month": "7/2018", "partitionKey": "summary", "count": 309, "id": "02727670-622b-420d-9790-36354c0b77a7", "_rid": "CyxpAK2n81T3HQAAAAAAAA==", "_self": "dbs/CyxpAA==/colls/CyxpAK2n81Q=/docs/CyxpAK2n81T3HQAAAAAAAA==/", "_etag": "\"0000f01f-0000-0000-0000-5b6af6f10000\"", "_attachments": "attachments/", "_ts": 1533736689 }, { "doctype": "MonthlySummary", "orderstatus": "Cancelled", "month": "7/2018", "partitionKey": "summary", "count": 46, "id": "e1f8ce67-749b-4cbd-abef-ec165b8fff3c", "_rid": "CyxpAK2n81T4HQAAAAAAAA==", "_self": "dbs/CyxpAA==/colls/CyxpAK2n81Q=/docs/CyxpAK2n81T4HQAAAAAAAA==/", "_etag": "\"0000f11f-0000-0000-0000-5b6af6f50000\"", "_attachments": "attachments/", "_ts": 1533736693 }, ... ] ``` ## Exercise 3: Visualizing Sales Data ### Exercise 3 Scenario You have been asked to create a dashboard that shows the sales volumes and revenues generated by product. You decide to implement this dashboard by using Azure Databricks, with Cosmos DB as the data source. To ensure that the system is scalable and responsive, you will use Spark to connect to Cosmos DB. ### Task 1: Create an Azure Databricks Service and Cluster 1. In the Azure Portal, click **Create a Resource**, type **Azure Databricks**, and then press Enter. 2. On the **Azure Databricks** blade, click **Create**. 3. On the **Azure Databricks Service** blade, in the **Workspace name** box, type **20777a-databricks-&lt;your name&gt;-&lt;the day&gt;**, for example, 20777a-databricks-john-31. 4. Select your Azure subscription. 5. In the **Resource group** box, click **Use existing**, and then click **20777Mod06**. > **Note:** The Azure Databricks service creates a significant number of resources. It places them in a seperate resource group with a name based on the name that you select here. 6. Set the **Location to West US 2**. > **Note:** Currently, not all regions support the range of VMs used by Azure Databricks to host Spark clusters. West US 2 does. 7. For the **Pricing Tier**, select **Trial**, and then click **Create**. 8. When the service has been deployed, click **All Resources**. 9. In the **All Resources** blade, click your **Azure Databricks** service (20777a-databricks-&lt;your name&gt;-&lt;the day&gt;). 10. On the **20777a-databricks-&lt;your name&gt;-&lt;the day&gt;** blade, click **Launch Workspace**. 11. On the **Azure Databricks** blade, under **Common Tasks**, click **New Cluster**. 12. On the **New Cluster** blade, for the **Cluster Name**, type **&lt;your name&gt;-cluster**. 13. Set **Max Workers** to 4, leave all other settings at their default values, and then click **Create Cluster**. 14. Wait while the cluster is created and started. Verify that its **State** is set to **Running** before continuing. ### Task 2: Create a Library and PyDocumentDB Notebook 1. In the toolbar to the left of the **Clusters** blade, click **Azure Databricks**. 2. On the **Azure Databricks** blade, under **Common Tasks** click **Import Library**. 3. On the **New Library** blade, in the **Source** drop-down list box, select **Upload Python Egg or PyPI**, in the **PyPi Name** box type **pydocumentdb**, and then click **Install Library** 4. On the **pydocumentdb** blade, select the check box for your cluster, and wait while the library is attached to the cluster; the **Status** should change to **Attached**. 5. On the **Azure Databricks** blade, create a new library called **Cosmos DB Connector**, and upload the **E:\\Labfiles\\Lab06\\Starter\\Exercise 2\\azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar** library file. 6. On the **azure-cosmosdb-spark_2.3.0_2.11-1.2.0-uber.jar** blade, select the check box for your cluster, and wait while the library is attached to the cluster; the **Status** should change to **Attached**. 7. In the toolbar to the left of the **pydocumentdb** blade, click **Azure Databricks**. 8. On the **Azure Databricks** blade, under **Common Tasks** click **New Notebook**. 9. In the **Create Notebook** dialog box, in the **Name** box, type **Analyze Orders**, set the **Language** to **Python**, and then click **Create** > **Note:** This exercise Python and PyDocumentDB, which is suitable for processing moderate amounts of data. If you have a large and growing volume of data, you should consider creating a Scala notebook with the Cosmos DB Connector, which can provide a more scalable solution. ### Task 3: Write Python Code to Retrieve and Display the Data 1. In the first cell of the notebook, enter the following code that specifies the modules that will be used by the notebook: ```Python # Import modules import pydocumentdb from pydocumentdb import document_client from pydocumentdb import documents import datetime from datetime import datetime ``` 2. In the toolbar at the top right-hand side of the cell, click the **play** icon, and then click **Run Cell**. Verify that the code in the cell runs without any errors. 3. In the same toolbar, click the down-arrow icon, and then click **Add Cell Below**. ```Python # Work out what this time last month was, in ticks thisTimelastMonthInTicks = (datetime.utcnow() - datetime(1,1,1)).total_seconds() * 1000000 ``` 4. Run the cell. 5. Add another cell and enter the following code. This code defines the query that the notebook will use to retrieve the data from Cosmos DB. ```Python # Define the query to retrieve the orders data from Cosmos DB query = 'SELECT o.id, o.dateplaced, o.orderstatus, i.productnumber, i.productname, i.numberincartorordered, i.lineitemtotalcost FROM o JOIN i IN o.orderitems WHERE o.doctype = \\\'ShoppingCartOrder\\\' AND o.dateplaced > ' + str(thisTimelastMonthInTicks) ``` 6. Run the cell. 7. Add another cell and enter the following code. Replace **--URI--** and **--KEY--** with the values for your Cosmos DB account. This code specifies the command that Spark will use to create a virtual table that it can use to fetch the data from Cosmos DB. ```Python # Specify the Spark SQL command to create a virtual table that references the data defined by the query in the Cosmos DB collection command = "create table orderdata using com.microsoft.azure.cosmosdb.spark options (endpoint '--URI--', masterkey '--KEY--', database 'Adventure-Works', collection 'Data', query_custom '" + str(query) + "')" ``` 8. Run the cell. 9. Add another cell and enter the following code. This statement removes the **orderdata** table from the database if it already exists. ```Python # Remove any existing version of the orderdata table spark.sql('drop table if exists orderdata') ``` 10. Run the cell. 11. Add another cell and enter the following code. This statement runs the **create table** command to recreate the **orderdata** table, using the latest value for **thisTimeLastMonthInTicks** (any previous version of the table would have been created using an older value for this variable, so would reference data more than a month old). ```Python # Recreate the orderdata table using the new query spark.sql(command) ``` 12. Run the cell. 13. Add another cell and enter the following code. These statements create a Spark dataframe from the rows in the **orderdata** table, and display the first 20 rows. ```Python # Create a Spark dataframe using the records in the orderdata virtual table ordersdf = spark.sql("select * from orderdata") ordersdf.show() ``` 14. Run the cell. > **Note:** You can view the progress of the Spark job that creates this dataset by expanding the **Spark Jobs** node under the cell as it runs. Click the (i) icon to see a detailed viewYou can also view the schema of the dataframe that is being created. 15. Add another cell and enter the following code. This code creates another Spark dataframe that summarizes the volume of sales and revenue generated for each product. ```Python # Create a dataframe that summarizes the data to show the total number of each product ordered, and the revenue generated by each product orderitemssummary = spark.sql("SELECT productnumber, productname, SUM(numberincartorordered) AS numordered, SUM(lineitemtotalcost) AS revenue FROM orderdata WHERE orderstatus <> 'Cancelled' GROUP BY productnumber, productname") orderitemssummary.show() ``` 16. Run the cell. 17. Add another cell and enter the following code. These statements create a further dataframe that sorts the data by volume ordered and displays the results. ```Python # Sort the data by volume ordered for each product, and show the results in a bar chart productsByVolume = orderitemssummary.orderBy("numordered", ascending = False) display(productsByVolume) ``` 18. Run the cell. The results should appear in a tabular format, with the most popular product at the top. 19. Click the graph icon below the table and select **Bar**, and then click **Plot Options**. 20. In the **Customize Plot** window, remove the fields from the **Keys** and **Values** boxes, drag the **productname** field to the **Series groupings** box, drag the **numberordered** field to the **Values** box, set **Aggregation** to **SUM**, and then click **Apply**. The bar chart should be displayed in the notebook. 21. Add another cell and enter the following code. These statements create a final dataframe that sorts the data by vrevenue and displays the results. ```Python # Sort the data by revenue for each product, and show the results in another bar chart productsByRevenue = orderitemssummary.orderBy("revenue", ascending = False) display(productsByRevenue) ``` 22. Run the cell. 23. Click the graph icon below the table and select **Bar**, and then click **Plot Options**. 24. In the **Customize Plot** window, remove the fields from the **Keys** box (leave the **Values** box set to **Revenue**), drag the **productname** field to the **Series groupings** box, set **Aggregation** to **SUM**, and then click **Apply**. ### Task 4: Create a Dashboard 1. Return to the cell showing the bar chart that sorts orders by product volume. 2. In the toolbar at the top right-hand side of the final cell in the notebook, click the **Show in Dashboard Menu** icon (this icon has the image of a graph). Click **Add to New Dshboard**. 3. In the **Analyze Orders** blade showing the dashboard, change the title to **Monthly Orders Analysis**. 4. Resize the graph so that it occupies the entire presentation pane. 5. Click the **Analyze Orders** link adjacent to **View of notebook** under the dashboard title to return to the notebook. 6. Go to the final cell in the notebook, click **Show in Dashboard**, and then select the check box for **Monthly Orders Analysis**, and then click the **Go to Dashboard Monthly Orders Analysis** icon. You should see the revenue graph below the numberordered graph on te dashboard. 7. Resize the revenue graph to make it the same size as the numberordered graph. 8. Click **Run All** to test the notebook and dashboard. The data from the graphs will disappear while the notebook runs, and then reappear once the dataframes have been regenerated. ### Task 5: Cleanup the lab environment - In the Azure portal, delete the **20777_Mod06** resource group. --- © 2018 Microsoft Corporation. All rights reserved. The text in this document is available under the [Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/legalcode), additional terms may apply. All other content contained in this document (including, without limitation, trademarks, logos, images, etc.) are **not** included within the Creative Commons license grant. This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. This document is provided "as-is." Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it. Some examples are for illustration only and are fictitious. No real association is intended or inferred. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Java
UTF-8
298
2.015625
2
[ "Beerware" ]
permissive
package io.mateu.mdd.tester.app.simpleCase; import io.mateu.mdd.core.annotations.Action; public class SubMenu { @Action public String option1() { return "Returned from option 1"; } @Action public String option2() { return "Returned from option 2"; } }
Java
UTF-8
12,188
2.078125
2
[ "Apache-2.0" ]
permissive
package de.wackernagel.android.sidekick.annotations.processor.generators; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import de.wackernagel.android.sidekick.annotations.Check; import de.wackernagel.android.sidekick.annotations.ConflictClause; import de.wackernagel.android.sidekick.annotations.ForeignKey; import de.wackernagel.android.sidekick.annotations.NotNull; import de.wackernagel.android.sidekick.annotations.Unique; import de.wackernagel.android.sidekick.annotations.processor.definitions.BaseDefinition; import de.wackernagel.android.sidekick.annotations.processor.definitions.ColumnDefinition; import de.wackernagel.android.sidekick.annotations.processor.definitions.TableDefinition; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; class ContractGenerator { static void generate( final TypeSpec.Builder classBuilder, final TableDefinition tableDefinition, final Set<ColumnDefinition> fields) { final Set<ColumnDefinition> contractFields = filter( fields ); final ClassName contractName = ClassName.get(tableDefinition.getPackageName(), "Contract"); final TypeSpec.Builder contractBuilder = TypeSpec.classBuilder( contractName ) .addModifiers(PUBLIC, STATIC); extend(contractBuilder, tableDefinition, contractFields); tableConstant(contractBuilder, tableDefinition.getTableName() ); columnConstants(contractBuilder, contractFields); projection(contractBuilder, contractFields); contentUri(contractBuilder, tableDefinition.getTableAuthority()); classBuilder.addType( contractBuilder.build() ); } private static Set<ColumnDefinition> filter( final Set<ColumnDefinition> columnDefinitions ) { final Set<ColumnDefinition> contractFields = new LinkedHashSet<>( columnDefinitions ); for( final Iterator<ColumnDefinition> iterator = contractFields.iterator(); iterator.hasNext() ; ) { if( iterator.next().isCollectionType() ) { iterator.remove(); } } return contractFields; } private static void extend( final TypeSpec.Builder classBuilder, final TableDefinition tableDefinition, final Set<ColumnDefinition> fields) { classBuilder.superclass(ClassName.get("de.wackernagel.android.sidekick.frameworks.contentproviderprocessor.contract", "TableContract")); classBuilder.addMethod( MethodSpec.methodBuilder("getTable") .addModifiers(PUBLIC) .addAnnotation(Override.class) .returns(String.class) .addStatement("return $L", "TABLE") .build()); final ClassName db = ClassName.get("android.database.sqlite", "SQLiteDatabase"); classBuilder.addMethod( MethodSpec.methodBuilder("onCreate") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(db, "db", FINAL) .addCode(createTableStatement( tableDefinition, fields)) .returns(TypeName.VOID) .build() ); classBuilder.addMethod( MethodSpec.methodBuilder("onUpgrade") .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(db, "db", FINAL) .addParameter(int.class, "oldVersion", FINAL) .addParameter(int.class, "newVersion", FINAL) .returns(TypeName.VOID) .build() ); } private static CodeBlock createTableStatement(final TableDefinition table, final Set<ColumnDefinition> fields) { final CodeBlock.Builder sql = CodeBlock.builder(); sql.add("db.execSQL( \"CREATE TABLE IF NOT EXISTS " + escape( table.getTableName() ) + " (\"\n"); final Map<Integer, Set<ColumnDefinition>> uniqueness = new HashMap<>(); Iterator<ColumnDefinition> iterator = fields.iterator(); while( iterator.hasNext() ) { final ColumnDefinition column = iterator.next(); if( column.skipSQLite() ) { continue; } sql.add( "\t + \"" + escape( column.getColumnName() ) + " " + column.getSQLiteType() ); if( column.isPrimaryKey() ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_pk' PRIMARY KEY AUTOINCREMENT"); } final NotNull notNull = column.notNull(); if( notNull != null ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_not_null' NOT NULL"); if( notNull.onConflict() != ConflictClause.NONE ) { sql.add( " ON CONFLICT ").add(notNull.onConflict().toString() ); } } final Unique unique = column.unique(); if( unique != null ) { if( unique.group() < 0 ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_unique' UNIQUE"); if( unique.onConflict() != ConflictClause.NONE ) { sql.add( " ON CONFLICT ").add(unique.onConflict().toString() ); } } else { final Integer groupNumber = column.unique().group(); Set<ColumnDefinition> groupNames; if( uniqueness.containsKey( groupNumber ) ) { groupNames = uniqueness.get( groupNumber ); } else { groupNames = new LinkedHashSet<>( 1 ); } groupNames.add( column ); uniqueness.put(groupNumber, groupNames); } } final String defaultValue = column.defaultValue(); if( defaultValue != null && defaultValue.length() > 0 ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_default' DEFAULT ").add(defaultValue); } final Check checkConstraint = column.check(); if( checkConstraint != null && checkConstraint.value().length() > 0 ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_check' CHECK(" + checkConstraint.value() + ")"); } if (column.isBoolean() ) { sql.add(" CONSTRAINT '" + column.getColumnName() + "_check_boolean' CHECK(" + escape( column.getColumnName() ) + " IN ( 0, 1 ) )"); } if( column.isForeignKey() ) { String parentTable = BaseDefinition.formatNameForSQL( column.getObjectType() ); sql.add(" CONSTRAINT '" + column.getColumnName() + "_fk' REFERENCES " + escape( parentTable ) + "('_id')" ); final ForeignKey foreignKey = column.foreignKey(); if( foreignKey != null && foreignKey.onDelete() != ForeignKey.Action.NONE ) { sql.add(" ON DELETE ").add(foreignKey.onDelete().toString() ); } if( foreignKey != null && foreignKey.onUpdate() != ForeignKey.Action.NONE ) { sql.add(" ON UPDATE ").add(foreignKey.onUpdate().toString() ); } } if( iterator.hasNext() || !uniqueness.isEmpty() ) { sql.add( ", " ); } sql.add( "\"\n" ); } int last = uniqueness.size() - 1; int index = 0; for( Set<ColumnDefinition> groupElements : uniqueness.values() ) { sql.add("\t + \"CONSTRAINT '"); int j = 0; for( ColumnDefinition column : groupElements ) { if( j > 0 ) { sql.add( "_" ); } sql.add( column.getColumnName() ); j++; } sql.add( "_unique' UNIQUE(" ); int k = 0; for( ColumnDefinition column : groupElements ) { if( k > 0 ) { sql.add( "," ); } sql.add( escape( column.getColumnName() ) ); k++; } sql.add(")"); int e = 0; for( ColumnDefinition column : groupElements ) { if( column.unique().onConflict() != ConflictClause.NONE ) { sql.add( " ON CONFLICT " ).add( column.unique().onConflict().toString() ); e++; } if( e > 1 ) { throw new IllegalStateException( "A unique constraint with more then one column has more then one conflict-clauses defined! See member field '" + column.getFieldName() + "' in class '" + table.getObjectType( false, false ) + "'." ); } } if( index != last ) { sql.add( ", " ); } sql.add( "\"\n" ); index++; } sql.add( "\t + $S );\n", ");" ); return sql.build(); } private static void tableConstant( final TypeSpec.Builder classBuilder, final String name) { classBuilder.addField( constant(String.class, "TABLE", name).build() ); } private static void columnConstants( final TypeSpec.Builder classBuilder, final Set<ColumnDefinition> columnDefinitions) { for( ColumnDefinition columnDefinition : columnDefinitions) { if( columnDefinition.isPrimaryKey() ) { continue; } classBuilder.addField( constant(String.class, columnDefinition.getConstantFieldName(), columnDefinition.getColumnName()) .build() ); } } private static void projection( final TypeSpec.Builder classBuilder, final Set<ColumnDefinition> columns ) { if( columns.size() > 0 ) { final CodeBlock.Builder value = CodeBlock.builder(); int index = 0; for( ColumnDefinition column : columns ) { value.add( (index == 0 ? "{\n" : "") + "\t$L" + (index+1 == columns.size() ? "\n" : ",\n"), column.getConstantFieldName()); index++; } value.add( "}" ); classBuilder.addField( FieldSpec.builder(String[].class, "PROJECTION") .addModifiers(PUBLIC, STATIC, FINAL) .initializer(value.build()) .build()); } } private static void contentUri(final TypeSpec.Builder classBuilder, final String authority) { if (authority != null && authority.length() > 0) { ClassName uri = ClassName.get( "android.net", "Uri"); classBuilder.addField( FieldSpec.builder(uri, "CONTENT_URI") .addModifiers(PUBLIC, STATIC, FINAL) .initializer("Uri.parse( \"content://" + authority + "/\" + $L )", "TABLE") .build()); } } private static FieldSpec.Builder constant(final Class<?> type, final String name, final String value) { return constant(type, name, "$S", value); } private static FieldSpec.Builder constant(final Class<?> type, final String name, final String pattern, final String value) { return FieldSpec.builder(type, name) .addModifiers(PUBLIC, STATIC, FINAL) .initializer(pattern, value); } private static String escape( final String value ) { final String quotation = "'"; return quotation.concat( value ).concat( quotation ); } }
PHP
UTF-8
2,866
2.84375
3
[ "MIT" ]
permissive
<?php // +---------------------------------------------------------------------- // | // +---------------------------------------------------------------------- // | Copyright (c) 2015 bookfuns.com All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: u0mo5 // +---------------------------------------------------------------------- class Action{ //模板文件 public $template_dir = 'App/Cache/templates'; //编译文件 public $compile_dir = 'App/Cache/templates_c'; //缓存文件 public $cache_dir = 'App/cache'; //模板变量 public $_tpl_var = array(); //是否开启缓存 public $caching = false; public function __construct() { $this->checkDir(); } public function Action($action_class,$action_function){ } //检查目录是否建好 private function checkDir() { if (!is_dir($this->template_dir)) { exit('模板文件目录templates不存在!请手动创建'); } if (!is_dir($this->compile_dir)) { exit('编译文件目录templates_c不存在!请手工创建!'); } if (!is_dir($this->cache_dir)) { exit('缓存文件目录'.$this->cache_dir.'不存在!请手工创建!'); } } //模板变量注入方法 public function assign($tpl_var, $var = null) { if (isset($tpl_var) && !empty($tpl_var)) { $this->_tpl_var[$tpl_var] = $var; } else { exit('模板变量名没有设置好'); } } //文件编译 public function display($file="index") { //模板文件 $tpl_file = './App/View/Index/'.$file.'.html'; if (!file_exists($tpl_file)) { exit('ERROR:模板文件不存在!'); } //编译文件'' $parse_file = $this->compile_dir.'/'.md5($file).$file.'.php'; //只有当编译文件不存在或者是模板文件被修改过了 //才重新编译文件 if (!file_exists($parse_file) || filemtime($parse_file) < filemtime($tpl_file)) { include 'Compile.class.php'; $compile = new Compile($tpl_file); $compile->parse($parse_file); } //开启了缓存才加载缓存文件,否则直接加载编译文件 if ($this->caching) { //缓存文件 $cache_file = $this->cache_dir.'/'.md5($file).$file.'.html'; //只有当缓存文件不存在,或者编译文件已被修改过 //重新生成缓存文件 if (!file_exists($cache_file) || filemtime($cache_file) < filemtime($parse_file)) { //引入缓存文件 include $parse_file; //缓存内容 $content = ob_get_clean(); //生成缓存文件 if (!file_put_contents($cache_file, $content)) { exit('缓存文件生成出错!'); } } //载入缓存文件 include $cache_file; } else { //载入编译文件 include $parse_file; } } } ?>
JavaScript
UTF-8
2,986
2.9375
3
[]
no_license
var express = require('express'); var router = express.Router(); router.get('/hello', function(req, res){ res.send('GET route on things.'); }); router.post('/', function(req, res){ res.send('POST route on things.'); }); router.all('/test', function(req, res){ res.send("HTTP method doesn't have any effect on this route!"); }); router.get('/random.text', function (req, res) { res.send('random.text') }) //This route path will match acd and abcd. router.get('/ab?cd', function (req, res) { res.send('ab?cd') }) //his route path will match abcd, abbcd, abbbcd, and so on. router.get('/ab+cd', function (req, res) { res.send('ab+cd') }) //This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on. router.get('/ab*cd', function (req, res) { res.send('ab*cd') }) //This route path will match /abe and /abcde. router.get('/ab(cd)?e', function (req, res) { res.send('ab(cd)?e') }) //This route path will match anything with an “a” in it. router.get(/a/, function (req, res) { res.send('/a/') }) router.get(/.*fly$/, function (req, res) { res.send('/.*fly$/') }) router.get('/flights/:from-:to', function (req, res) { res.send(req.params) }) router.get('/plantae/:genus.:species', function (req, res) { res.send(req.params) }) router.get('/things/:name/:id', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.params.name); }); router.get('/things/:id([0-9]{5})', function(req, res){ res.send('id: ' + req.params.id); }); //More than one callback function can handle a route (make sure you specify the next object) router.get('/example/b', function (req, res, next) { console.log('the response will be sent by the next function ...') next() }, function (req, res) { res.send('Hello from B!') }) //An array of callback functions can handle a route. For example: var cb0 = function (req, res, next) { console.log('CB0') next() } var cb1 = function (req, res, next) { console.log('CB1') next() } var cb2 = function (req, res) { res.send('Hello from C!') } router.get('/example/c', [cb0, cb1, cb2]) var cb0 = function (req, res, next) { console.log('CB0') next() } var cb1 = function (req, res, next) { console.log('CB1') next() } router.get('/example/d', [cb0, cb1], function (req, res, next) { console.log('the response will be sent by the next function ...') next() }, function (req, res) { res.send('Hello from D!') }) router.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') }) router.get('*', function(req, res){ res.send('Sorry, this is an invalid URL.'); }); //export this router to use in our index.js module.exports = router;
Java
UTF-8
816
1.796875
2
[]
no_license
package com.gmsj.model.bo; import lombok.Data; import java.io.Serializable; import java.util.List; /** * @author baojieren * @date 2020/4/24 14:52 */ @Data public class PolicyProfileBo implements Serializable { public Integer id; /** * 文章标题 */ public String title; /** * 文章内容 */ public String content; /** * 主题图片 */ public String themeImage; /** * 图片地址,多个用逗号隔开 */ public List<String> images; /** * 浏览数 */ public Integer browseSum; /** * 评论数 */ public Integer commentSum; /** * 点赞数 */ public Integer praiseSum; /** * 分类名称 */ public String menuName; public String createTime; }
Java
UTF-8
2,480
2.46875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avalon.fortress.impl.factory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * InvocationHandler that just passes on all methods to target object. * * @author <a href="mailto:dev@avalon.apache.org">Avalon Development Team</a> */ final class PassThroughInvocationHandler implements InvocationHandler { /** * The target object delegated to. */ private final Object m_object; /** * Create an Invocation handler for specified object. * * @param object the object to delegate to */ public PassThroughInvocationHandler( final Object object ) { if ( null == object ) { throw new NullPointerException( "object" ); } m_object = object; } /** * Invoke the appropriate method on underlying object. * * @param proxy the proxy object * @param meth the method * @param args the arguments * @return the return value of object * @exception Throwable method throws an exception */ public Object invoke( final Object proxy, final Method meth, final Object[] args ) throws Throwable { try { return meth.invoke( m_object, args ); } catch ( final InvocationTargetException ite ) { throw ite.getTargetException(); } } /** * Retrieve the underlying object delegated to. * * @return the object delegated to */ Object getObject() { return m_object; } }
Java
UTF-8
7,570
2.765625
3
[]
no_license
package ryanguru; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; import javax.swing.JFrame; public class ColorDisplay { private static JFrame window; private static Pixel[][] screen; private static RowLabel[] rowLabels; private static ColLabel[] colLabels; private static int STD_PIXEL_SIZE = 50; private static int PIXEL_SIZE; private static int H_MAX_PIX = 20; private static int V_MAX_PIX = 10; private static int STD_ROW_LABEL_WIDTH = 70, STD_COL_LABEL_HEIGHT = 70; private static int ROW_LABEL_WIDTH, COL_LABEL_HEIGHT; private static String[] color = { "GREEN", "PINK", "ORANGE", "BLUE", "YELLOW", "RED" }; public static void openDisplay(String title) { int pixelPerInch = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); int scalingFactor = 1; // pixelPerInch / 150; PIXEL_SIZE = STD_PIXEL_SIZE * scalingFactor; ROW_LABEL_WIDTH = STD_ROW_LABEL_WIDTH * scalingFactor; COL_LABEL_HEIGHT = STD_COL_LABEL_HEIGHT * scalingFactor; window = new JFrame(); window.setLayout(null); window.setSize(ROW_LABEL_WIDTH + 15 * scalingFactor + H_MAX_PIX * PIXEL_SIZE, COL_LABEL_HEIGHT + 35 * scalingFactor + V_MAX_PIX * PIXEL_SIZE); window.setTitle(title); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().setBackground(Color.black); screen = new Pixel[V_MAX_PIX][H_MAX_PIX]; for (int c = 0; c < H_MAX_PIX; c++) for (int r = 0; r < V_MAX_PIX; r++) { screen[r][c] = new Pixel(r, c, ROW_LABEL_WIDTH + c * PIXEL_SIZE, (V_MAX_PIX - 1) * PIXEL_SIZE - r * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE, scalingFactor); window.add(screen[r][c]); } rowLabels = new RowLabel[V_MAX_PIX]; for (int r = 0; r < V_MAX_PIX; r++) { rowLabels[r] = new RowLabel(r, 0, (V_MAX_PIX - 1) * PIXEL_SIZE - r * PIXEL_SIZE, ROW_LABEL_WIDTH, PIXEL_SIZE, scalingFactor); window.add(rowLabels[r]); } colLabels = new ColLabel[H_MAX_PIX]; for (int c = 0; c < H_MAX_PIX; c++) { colLabels[c] = new ColLabel(c, ROW_LABEL_WIDTH + c * PIXEL_SIZE, V_MAX_PIX * PIXEL_SIZE, PIXEL_SIZE, COL_LABEL_HEIGHT, scalingFactor); window.add(colLabels[c]); } window.setVisible(true); window.setAlwaysOnTop(true); window.setAlwaysOnTop(false); } public static void closeDisplay() { window.dispose(); } public static void setPixelON(int r, int c) { setPixelColor(r, c, "ORANGE"); } public static void setPixelOFF(int r, int c) { setPixelColor(r, c, "GRAY"); } public static void setPixelColor(int r, int c, String color) { screen[r][c].setColor(pickColor(color)); window.repaint(); } private static Color pickColor(String color) { Color result; if (color.equals("RED")) result = Color.red; else if (color.equals("GREEN")) result = Color.green; else if (color.equals("BLUE")) result = Color.blue; else if (color.equals("CYAN")) result = Color.cyan; else if (color.equals("ORANGE")) result = Color.orange; else if (color.equals("GRAY")) result = Color.gray; else if (color.equals("WHITE")) // addon result = Color.white; else if (color.equals("PINK")) // addon result = Color.pink; else if (color.equals("YELLOW")) // addon result = Color.yellow; else if (color.equals("DARK_GRAY"))// addon result = Color.darkGray; else if (color.equals("LIGHTGRAY"))// addon result = Color.lightGray; else result = Color.black; return result; } public static void setScreenOFF() { for (int c = 0; c < H_MAX_PIX; c++) for (int r = 0; r < V_MAX_PIX; r++) { setPixelOFF(r, c); } window.repaint(); } public static void pause(int x) { try { Thread.sleep(x); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String randomColor() { int colorIdx = (int) (Math.round((Math.random() * (color.length - 1)))); return color[colorIdx]; } public static int randomRow() { return (int) (Math.random() * (V_MAX_PIX - 1)); } public static int randomCol() { return (int) (Math.random() * (H_MAX_PIX - 1)); } } class Pixel extends JComponent { private Color c; private int x, y, w, h; private int PIXEL_SIZE; private int row, col; private int scalingFactor; public Pixel(int r, int c, int x, int y, int w, int h, int size, int scalingFactor) { super(); this.row = r; this.col = c; this.x = x; this.y = y; this.w = w; this.h = h; this.setBounds(x, y, w, h); PIXEL_SIZE = size; this.c = Color.gray; this.scalingFactor = scalingFactor; } public void setColor(Color w) { c = w; } public void paint(Graphics g) { g.setColor(c); g.fillRect(0, 0, w, h); g.setColor(Color.white); g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, g.getFont().getSize() * scalingFactor)); FontMetrics context = g.getFontMetrics(); String text = row + "," + col; int textwidth = context.stringWidth(text); int textheight = context.getHeight(); g.drawString(text, w / 2 - textwidth / 2, h / 2 + textheight / 2); // g.drawString(row+","+col, 2, PIXEL_SIZE-5); g.setColor(Color.black); g.drawRect(0, 0, w, h); } } class RowLabel extends JComponent { private Color c; private int x, y, w, h; private int row; private int scalingFactor; public RowLabel(int r, int x, int y, int w, int h, int scalingFactor) { super(); this.row = r; this.x = x; this.y = y; this.w = w; this.h = h; this.setBounds(x, y, w, h); this.c = new Color(0, 0, 180); // RGB this.scalingFactor = scalingFactor; } public void setColor(Color w) { c = w; } public void paint(Graphics g) { g.setColor(c); g.fillRect(0, 0, w, h); g.setColor(Color.white); g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, g.getFont().getSize() * scalingFactor)); FontMetrics context = g.getFontMetrics(); String text = "R:" + row; int textwidth = context.stringWidth(text); int textheight = context.getHeight(); g.drawString(text, w / 2 - textwidth / 2, h / 2 + textheight / 2); g.setColor(Color.black); ((Graphics2D) g).setStroke(new BasicStroke(3)); g.drawRect(0, 0, w, h); } } class ColLabel extends JComponent { private Color c; private int x, y, w, h; private int col; private int scalingFactor; public ColLabel(int c, int x, int y, int w, int h, int scalingFactor) { super(); this.col = c; this.x = x; this.y = y; this.w = w; this.h = h; this.setBounds(x, y, w, h); this.c = new Color(128, 0, 128); // RGB this.scalingFactor = scalingFactor; } public void setColor(Color w) { c = w; } public void drawRotate(Graphics2D g2d, double x, double y, int angle, String text) { g2d.translate((float) x, (float) y); g2d.rotate(Math.toRadians(angle)); g2d.drawString(text, 0, 0); g2d.rotate(-Math.toRadians(angle)); g2d.translate(-(float) x, -(float) y); } public void paint(Graphics g) { g.setColor(c); g.fillRect(0, 0, w, h); g.setColor(Color.white); g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, g.getFont().getSize() * scalingFactor)); FontMetrics context = g.getFontMetrics(); String text = "C:" + col; int textwidth = context.stringWidth(text); int textheight = context.getHeight(); g.drawString(text, w / 2 - textwidth / 2, h / 2 + textheight / 2); g.setColor(Color.black); ((Graphics2D) g).setStroke(new BasicStroke(3)); g.drawRect(0, 0, w, h); } }
Markdown
UTF-8
2,024
3.1875
3
[]
no_license
# Assignment 3: Adding tabs Continue building on what you have made in Assignment 2 ## Reading materials - User interface and & navigation - Layouts --> create a list with recyclerview (usage of adapters) - Look and feel - In depth: styles and themes, floating action button buttons - Quickly checkout: checkboxes, radio buttons, toggle,spinners. - Notifications - Create a notification - *other topics not needed* - Slide between fragments with the viewpager - Background tasks - Background operations overview - Specifiying the code to run on a thread - *other topics not needed* - Connectivity - Transmitting Network data using volley - Sending a simple Request - Additional: https://www.itsalif.info/content/android-volley-tutorial-http-get-post-put - *other topics not needed* ## New app components - Tab infrastructure. - One tab points to what was MainAcitivy and is called 'Contact Wolfpack' (convert to Fragment and make new MainActivity) [viewpager] - Second tab is called 'Shout!'. This Fragment shows a List of possible shoutouts that can be posted to our Slack channel. [recyclerview] ## New app requirements - When clicking on one of the Shout List items, a background task ensures the shout is send through the API of Slack and posted in our random channel [background tasks] - Inform the user using toasts of succes/fail of this task - Sending the message to the slack API is a simple POST call implementation [connectivity] - Choose your own shouts like 'I want coffee NOW' - When email is succesfully sent (check the callback by the email intent) A notification (in the notificationbar) has to be posted saying 'Sent an picture to Rene!' [notifications] - Change the colorscheme of the app to your choice BUT using the correct styling and themeing options. - Use the debugger to place breakpoints when testing the app. play around with it! - Don't forget the appropriate permiissions **Done when I receive an email and post displays in Slack**
Java
UTF-8
2,343
2.234375
2
[]
no_license
package cl.awake.psegurito.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="visita") public class Visita { //Variables// @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQUENCE1") @SequenceGenerator(name="SEQUENCE1", sequenceName="ID_VISITA_SEQ", allocationSize=1) private int id_visita; @Temporal(value=TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") private Date fechavisita; private int numerovisita; @JoinColumn(name="profesional_id_profesional") @ManyToOne private Profesional profesional; @JoinColumn(name="cliente_id_cliente") @ManyToOne private Cliente cliente; public Visita() { } public Visita(int id_visita, Date fechavisita, int numerovisita, Profesional profesional, Cliente cliente) { super(); this.id_visita = id_visita; this.fechavisita = fechavisita; this.numerovisita = numerovisita; this.profesional = profesional; this.cliente = cliente; } public int getNumerovisita() { return numerovisita; } public void setNumerovisita(int numerovisita) { this.numerovisita = numerovisita; } public int getId_visita() { return id_visita; } public void setId_visita(int id_visita) { this.id_visita = id_visita; } public Date getFechavisita() { return fechavisita; } public void setFechavisita(Date fechavisita) { this.fechavisita = fechavisita; } public Profesional getProfesional() { return profesional; } public void setProfesional(Profesional profesional) { this.profesional = profesional; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } }
C++
UHC
7,198
2.796875
3
[]
no_license
#include"CollisionManager.h" #include"Obj.h" #include"Input.h" DEFINITION_SINGLE(CCollisionManager) CCollisionManager::CCollisionManager() { } CCollisionManager::~CCollisionManager() { Safe_Delete_Map(m_mapGroup); } bool CCollisionManager::CreateCollisionGroup(const string& strGroup) { PCOLLISIONGROUP pGroup = FindCollisionGroup(strGroup); if (pGroup) return false; pGroup = new COLLISIONGROUP; m_mapGroup.insert(make_pair(strGroup, pGroup)); return true; } CCollisionManager::PCOLLISIONGROUP CCollisionManager::FindCollisionGroup(const string& strGroup) { unordered_map<string, PCOLLISIONGROUP>::iterator iter = m_mapGroup.find(strGroup); if (iter == m_mapGroup.end()) return nullptr; return iter->second; } void CCollisionManager::AddCollider(CObj* pObj) { const list<CCollider*>* pColliderList = pObj->GetColliderList(); if (pColliderList->empty()) return; list<CCollider*>::const_iterator iter; list<CCollider*>::const_iterator iterEnd = pColliderList->end(); for (iter = pColliderList->begin(); iter != iterEnd; ++iter) { if (!(*iter)->IsEnable()) { (*iter)->DeletePrevCollider(); continue; } PCOLLISIONGROUP pGroup = FindCollisionGroup((*iter)->GetCollisionGroup()); if (!pGroup) continue; if (pGroup->iSize == pGroup->iCapacity) { pGroup->iCapacity *= 2; CCollider** pList = new CCollider * [pGroup->iCapacity]; memcpy(pList, pGroup->pList, sizeof(CCollider*) * pGroup->iSize); SAFE_DELETE_ARRAY(pGroup->pList); pGroup->pList = pList; } pGroup->pList[pGroup->iSize] = *iter; ++pGroup->iSize; } } bool CCollisionManager::Init() { CreateCollisionGroup("Default"); CreateCollisionGroup("UI"); return true; } void CCollisionManager::Collision(float fTime) { //콺 UI 浹ؼ UI 浹ɰ 콺 Ʈ //浹ó Ѵ. bool bCollision = false; //콺 浹ü ´. CObj* pMouseObj = (CObj*)GET_SINGLE(CInput)->GetMouseObj(); CCollider* pMouse = pMouseObj->GetCollider("MouseUI"); CCollider* pMouseWorld = pMouseObj->GetCollider("Mouse"); PCOLLISIONGROUP pCollGroup = FindCollisionGroup("UI"); if (pCollGroup) { for (int i = 0; i < pCollGroup->iSize; ++i) { if (bCollision) break; CCollider* pDest = pCollGroup->pList[i]; //浹 if (pMouse->Collision(pDest)) { bCollision = true; pDest->SetIntersectPos(pMouse->GetIntersectPosition()); // 浹ߴ Ͽ Dest ٸ ó 浹Ѵٴ if (!pMouse->CheckPrevCollider(pDest)) { // 콺 浹ƴ ٸ Ʈ LeaveóѴ. pMouseWorld->DeletePrevCollider(); pMouse->AddPrevCollider(pDest); pDest->AddPrevCollider(pMouse); pMouse->OnCollisionEnter(pDest, fTime); pDest->OnCollisionEnter(pMouse, fTime); } else { pMouse->OnCollision(pDest, fTime); pDest->OnCollision(pMouse, fTime); } } //浹 ȵ else { //浹 ȵɶ 浹Ͽ 밡 Ѵٸ //浹ϴٰ ٴ ̴. if (pMouse->CheckPrevCollider(pDest)) { pMouse->DeletePrevCollider(pDest); pDest->DeletePrevCollider(pMouse); pMouse->OnCollisionLeave(pDest, fTime); pDest->OnCollisionLeave(pMouse, fTime); } } } } SAFE_RELEASE(pMouse); //콺 Ϲ Ʈ 浹ó. ⼭ UI 浹 ȵ óѴ. if (!bCollision) { unordered_map<string, PCOLLISIONGROUP>::iterator iter; unordered_map<string, PCOLLISIONGROUP>::iterator iterEnd = m_mapGroup.end(); for (iter = m_mapGroup.begin(); iter != iterEnd; ++iter) { if (iter->first == "UI") continue; pCollGroup = iter->second; for (int i = 0; i < pCollGroup->iSize; ++i) { if (bCollision) break; CCollider* pDest = pCollGroup->pList[i]; //浹 if (pMouseWorld->Collision(pDest)) { bCollision = true; pDest->SetIntersectPos(pMouseWorld->GetIntersectPosition()); // 浹ƴ Ͽ Dest ٸ ó 浹Ѵ. if (!pMouseWorld->CheckPrevCollider(pDest)) { pMouseWorld->AddPrevCollider(pDest); pDest->AddPrevCollider(pMouseWorld); pMouseWorld->OnCollisionEnter(pDest, fTime); pDest->OnCollisionEnter(pMouseWorld, fTime); } else { pMouseWorld->OnCollision(pDest, fTime); pDest->OnCollision(pMouseWorld, fTime); } } //浹 ȵ else { //浹 ȵɶ 浹Ͽ 밡 Ѵٸ //浹 ϴٰ ٴ if (pMouseWorld->CheckPrevCollider(pDest)) { pMouseWorld->DeletePrevCollider(pDest); pDest->DeletePrevCollider(pMouseWorld); pMouseWorld->OnCollisionLeave(pDest, fTime); pDest->OnCollisionLeave(pMouseWorld, fTime); } } } } } SAFE_RELEASE(pMouseWorld); SAFE_RELEASE(pMouse); unordered_map<string,PCOLLISIONGROUP>::iterator iter; unordered_map<string, PCOLLISIONGROUP>::iterator iterEnd = m_mapGroup.end(); for (iter = m_mapGroup.begin(); iter != iterEnd; ++iter) { //浹ü ŭ ݺ. ,浹ü 1 浹ó ص PCOLLISIONGROUP pGroup = iter->second; if (pGroup->iSize < 2) { pGroup->iSize = 0; continue; } for (int i = 0; i < pGroup->iSize - 1; ++i) { CCollider* pSrc = pGroup->pList[i]; CObj* pSrcObj = pSrc->GetObj(); for (int j = i + 1; j < pGroup->iSize; ++j) { //浹ó Ѵ. , Ʈ ִ 浹ü óʴ´. CCollider* pDest = pGroup->pList[j]; if (pSrc->GetCollisionType() == pDest->GetCollisionType()) continue; //浹ü ִ Ʈ ´. CObj* pDestObj = pDest->GetObj(); if (pSrcObj == pDestObj) { SAFE_RELEASE(pDestObj); continue; } SAFE_RELEASE(pDestObj); //浹 if (pSrc->Collision(pDest)) { pDest->SetIntersectPos(pSrc->GetIntersectPosition()); // 浹ߴ Ͽ Dest ٸ ó 浹Ѵٴ . if (!pSrc->CheckPrevCollider(pDest)) { pSrc->AddPrevCollider(pDest); pDest->AddPrevCollider(pSrc); pSrc->OnCollisionEnter(pDest, fTime); pDest->OnCollisionEnter(pSrc, fTime); } else { pSrc->OnCollision(pDest, fTime); pDest->OnCollision(pSrc, fTime); } } //浹 ȵ else { //浹 ȵɶ 浹Ͽ 밡 Ѵٸ //浹ϴٰ ٴ ̴. if (pSrc->CheckPrevCollider(pDest)) { pSrc->DeletePrevCollider(pDest); pDest->DeletePrevCollider(pSrc); pSrc->OnCollisionLeave(pDest, fTime); pDest->OnCollisionLeave(pSrc, fTime); } } } SAFE_RELEASE(pSrcObj); } pGroup->iSize = 0; } }
C++
UTF-8
3,289
2.71875
3
[]
no_license
#include "algorithms.h" Algorithms::Algorithms() { shortPrimes = new unsigned long[PRIMELIMITS]; Eratosthen(); } void Algorithms::Eratosthen() { unsigned long i, j, k; bool *prime = new bool[PRIMELIMITS]; for(i = 0; i < PRIMELIMITS; i++) prime[i] = true; prime[0] = prime[1] = false; for(i = 2, k = 0; i < PRIMELIMITS; i++) if(prime[i]) { for(j = i + i; j < PRIMELIMITS; j += i) prime[j] = false; shortPrimes[k++] = i; } shortPrimes[k] = 0; maxPrimeIndex = k - 1; } void Algorithms::GeneratePrime(mpz_t number, unsigned int numBits, unsigned int randomaiser) { unsigned int i; bool isComposite; char *prime_str = new char[numBits + 1]; mpz_t buf; mpz_init(buf); srand(randomaiser); prime_str[0] = '1'; while(true) { for(i = 1; i < numBits - 1; i++) prime_str[i] = (int)(2.0 * rand() / (RAND_MAX + 1.0)) + '0'; prime_str[numBits - 1] = '1'; prime_str[numBits] = '\0'; mpz_set_str(number,prime_str,2); for(isComposite = false, i = 0; i <= maxPrimeIndex; i++) { if(mpz_cmp_ui(number,shortPrimes[i]) <= 0) break; mpz_mod_ui(buf, number, shortPrimes[i]); if(mpz_cmp_ui(buf,(unsigned long int)0) == 0) { isComposite = true; break; } } if(isComposite) continue; if(MillerRabin(number, numBits, 10)) break; } mpz_clear(buf); free(prime_str); } bool Algorithms::MillerRabin(mpz_t number, unsigned int numBits, unsigned int numTest) { unsigned int i, j, k; char *a_str; mpz_t buf, t, gcd, a, c; mpz_init(buf); mpz_init(t); mpz_init(gcd); mpz_init(a); mpz_init(c); if(mpz_cmp_ui(number,(unsigned long)2) == 0) return true; mpz_mod_ui(buf, number, (unsigned long)2); if(mpz_cmp_ui(buf,(unsigned long)0) == 0) return false; unsigned long s = 0; mpz_sub_ui(t,number,(unsigned long)1); mpz_mod_ui(buf, t, (unsigned long)2); while(mpz_cmp_ui(buf,(unsigned long)0) == 0) { mpz_tdiv_qr_ui(t, buf, t, (unsigned long)2); mpz_mod_ui(buf, t, (unsigned long)2); s++; } a_str = new char[numBits]; for(i = 0; i < numTest; i++) { for(k = 0; k < numBits - 1; k++) a_str[k] = (int)(2.0 * rand() / (RAND_MAX + 1.0)) + '0'; a_str[k] = '\0'; mpz_set_str(a,a_str,2); mpz_gcd(gcd,a,number); if(mpz_cmp_ui(gcd,(unsigned long)1) != 0) return false; mpz_powm(c, a, t, number); if(mpz_cmp_ui(c,(unsigned long)1) == 0) continue; mpz_sub_ui(buf,number,(unsigned long)1); if(mpz_cmp(c,buf) == 0) continue; bool f = true; for(j = 0; j < s - 1; j++) { mpz_powm_ui(c, c,(unsigned long)2, number); if(mpz_cmp(c,buf) == 0) f = false; } if(f) return false; } mpz_clear(buf); mpz_clear(t); mpz_clear(gcd); mpz_clear(a); mpz_clear(c); free(a_str); return true; }
PHP
UTF-8
909
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
<?php namespace Telegram\Bot\Methods; use Telegram\Bot\Objects\ChatMember; /** * Class GetChatAdministrators * * Get a list of administrators in a chat. * * <code> * $params = [ * 'chat_id' => '', * ]; * </code> * * @link https://core.telegram.org/bots/api#getchatadministrators * * @method GetChatAdministrators chatId($chatId) int|string Unique identifier for the target chat or username of the target supergroup * or channel (in the format @channelusername); * * @method ChatMember[] getResult($dumpAndDie = false) */ class GetChatAdministrators extends Method { /** {@inheritdoc} */ protected $getRequest = true; /** {@inheritdoc} */ protected function returns() { return collect($this->factory->response()->getResult()) ->map(function ($admin) { return new ChatMember($admin); }) ->all(); } }
TypeScript
UTF-8
464
2.609375
3
[ "MIT", "CC-BY-3.0", "CC-BY-4.0" ]
permissive
import { vec4 } from "gl-matrix" export class Vec4 { static set(x: number, y: number, z: number, w: number, out = new Float32Array(4)) { return <Float32Array>vec4.set(out, x, y, z, w) } static transformMat4(a: Float32Array, m: Float32Array, out = new Float32Array(4)) { return <Float32Array>vec4.transformMat4(out, a, m) } static fromValues(x: number, y: number, z: number, w: number) { return <Float32Array>vec4.fromValues(x, y, z, w) } }
TypeScript
UTF-8
2,396
2.578125
3
[]
no_license
import { Injectable } from '@angular/core'; import { HttpRequest, HttpEventType ,HttpEvent,HttpHandler,HttpInterceptor,HttpErrorResponse } from '@angular/common/http'; import { Observable,ReplaySubject } from 'rxjs'; import 'rxjs/add/operator/do'; import { Subject } from 'rxjs/Subject'; import {} from 'rxjs/add/operator/do'; import {InternetConnection} from '../ewepserver.service' @Injectable() export class ProgressInterceptor implements HttpInterceptor { public progress$: Observable<number | null>; private progressSubject: Subject<number | null>; public ErrorMessage$: Observable<InternetConnection | null>; private ErrorMessageSubject: Subject<InternetConnection | null>; constructor() { this.progressSubject = new ReplaySubject<number | null>(1); this.progress$ = this.progressSubject.asObservable(); this.ErrorMessageSubject = new ReplaySubject<InternetConnection | null>(1); this.ErrorMessage$ = this.ErrorMessageSubject.asObservable(); } intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> { const reportingRequest = req.clone({ reportProgress: true }); const handle = next.handle(reportingRequest); return handle.do((event: HttpEvent<T>) => { switch (event.type) { case HttpEventType.Sent: this.progressSubject.next(null); break; case HttpEventType.DownloadProgress: case HttpEventType.UploadProgress: if (event.total) { this.progressSubject.next(Math.round((event.loaded / event.total) * 100)); } break; case HttpEventType.Response: this.progressSubject.next(100); break; } },(error: any) => { let newError:InternetConnection = {UsingInternet:false,progress:0,StopInternet:false,ErrorMessage:"",DebugErrorMessage:"",HTTPStatus:""}; if(error instanceof ErrorEvent){ newError.ErrorMessage = 'An error occurred:', error.error.message; this.ErrorMessageSubject.next(newError); } if(error instanceof HttpErrorResponse){ newError.ErrorMessage =`Backend returned code ${error.status}, ` + `body was: ${error.error.error}`; this.ErrorMessageSubject.next(newError); } console.log("HTTP Error ",error.error); }); } }
C#
UTF-8
1,216
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace zVirtualClient { public class Credential { public bool Default { get; set; } public string Name { get; set; } public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public string Domain { get; set; } public System.Uri Uri { get { if(!Host.ToLower().StartsWith("http")) { Host = "http://" + Host; } System.Uri u; if (Uri.TryCreate(string.Format("{0}:{1}", Host, Port), UriKind.RelativeOrAbsolute, out u)) { return u; } else { throw new ArgumentOutOfRangeException("Host and/or Port not valid for URI Creation:" + string.Format("{0}:{1}", Host, Port)); } } } public override string ToString() { return Name; } } }
Java
UTF-8
358
3.328125
3
[]
no_license
class Layout { static int s = 343; int x; { x = 7; int x2 = 5; } Layout() { x += 8; int x3 = 6; } void doStuff() { int y = 0; for (int z = 0; z < 4; z++) { y += z + x; System.out.println(y); } } public static void main(String[] args) { Layout l = new Layout(); System.out.println(s + " " + l.x); l.doStuff(); } }
Markdown
UTF-8
2,485
2.953125
3
[ "MIT" ]
permissive
# ![logo](https://raw.githubusercontent.com/Lughus/e-pigeon/master/ressources/logo.png) e-pigeon Implementation of an handmade application protocol for messaging Be careful this is an alpha version of the software and many bugs can be found in it. If you use it and found some, please create an issue, it can be helpful. ## What does it do ? That's a simple messaging server / client using node-ipc in the hood\ It garantee the order of sended messages and that the message has been received.\ You can send a message to a group of clients.\ Server cannot receive message, but you can start a client in the same app of the server and will use localhost to communicate. ## Getting started Works on node 8+\ Install it with `npm i @lug/e-pigeon` You can check [example](https://github.com/Lughus/e-pigeon/tree/master/example) for an simple use of this module. ### Server ```js const { EPigeonServer } = require('@lug/e-pigeon') const server = new EPigeonServer() server.serve(9999) ``` ### Client ```js const { EPigeonClient } = require('@lug/e-pigeon') const client = new EPigeonClient() client.connect('host', 9999) ``` ## Documentation For debugging, you can set the env debug variable to `epigeon:*` like described in the [debug](https://github.com/visionmedia/debug) module ### Server #### Methods | name | params | description | | ----- | -------- | ------------------ | | serve | port:Int | serve on this port | | stop | - | stop the server | ### Client #### Methods | name| params| description| |-|-|-| | connect| host:string / port:Int| connect to server| | disconnect|-| disconnect from server| | updateSession | {key:value,...}| set values to your client session| | sendMessage | to: uuid or {key:value} / content:any | send a message to a uuid or to all client that match the key:value on their session | #### Events You can add en event handler with `client.on(<event>, <callback>)` | event | callback params | description| |-|-|-| | connected| - | when the client is connected to the server| | disconnected | - | when the client is disconnected| | authenticated | - | when the client is authenticated| | session.update | {uuid, session} | when a client update his session| | message | message | when a message is recieved, contains many things but the content is stored in `message.payload` | client.connect | uuid | when a client connect to the server| | client.disconnect | uuid | when a client disconnect from the server|
C++
UTF-8
237
2.890625
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int n, s=0, sum=0; cin>>n; for(int i=1; i<=n; i++){ s = s*10 + i; sum += s; cout<<s<<" "; } cout<<endl<<"Sum is => "<<sum; return 0; }
Java
UTF-8
528
3.453125
3
[]
no_license
package recursion; public class RodCuttingRecursion { static int max = Integer.MIN_VALUE; public static void main(String[] args) { int a[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; System.out.println(rodCutting(a, a.length)); } private static int rodCutting(int[] a, int n) { if (n <= 0) return 0; max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { max = Math.max(max, rodCutting(a, n - i - 1) + a[i]); } return max; } }
Java
UTF-8
917
2.5625
3
[]
no_license
/** * */ package org.finki.auction.common.datastructures; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * @author chemicalangel * */ public class ServiceRegistery { private Map<String, String> services = new HashMap<>(); public static class ServiceEntry { private String serviceName; private String methodName; public ServiceEntry(String serviceName) { this.serviceName = serviceName; } @Override public int hashCode() { return Objects.hash(methodName); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ServiceEntry other = (ServiceEntry) obj; return Objects.equals(this.methodName, other.methodName); } } public String getServiceName(String methodName) { return services.get(methodName); } }
Markdown
UTF-8
2,122
2.859375
3
[]
no_license
--- title: "How to Setup a Cronjob for a Tool Installed via pipx" date: 2021-08-02T10:54:16+02:00 tags: - pipx - cronjob --- The company I work for finally says good-bye to [Subversion](https://subversion.apache.org/), and while migrating to git, we also decided to move to GitHub and no longer host the repositories inhouse. While I think GitHub should be pretty reliable, data loss still could happen, so I decided we need some backup. I use [all-repos](https://github.com/asottile/all-repos) to manage open source repositories on a daily basis. Its `all-repos-clone` command looks like a great fit to backup the repositories to a local virtual machine. I setup everything, double checked that it works manually, setup a cronjob, and ... was surprised that it did not work. The cronjob looked like... ```cron 0 2 * * * cd ~/all && all-repos-clone ``` The syslog reveals... not much. ```log Aug 2 02:00:01 hades CRON[3640]: (kopia) CMD (cd ~/all && all-repos-clone) Aug 2 02:00:01 hades CRON[3639]: (CRON) info (No MTA installed, discarding output) ``` So, I setup the cronjob to log its output and let it run every five minutes to get quick feedback. ```cron 0 2 * * * (cd ~/all && all-repos-clone) 2>&1 | logger -t all-repos ``` This time there is a hint for me... ```log Aug 2 08:30:01 hades CRON[7482]: (kopia) CMD ((cd /home/kopia/all && all-repos-clone) 2>&1 | logger -t all-repos) Aug 2 08:30:01 hades all-repos: /bin/sh: 1: all-repos-clone: not found ``` So, the user is correct, the command is correct... what is missing? Well, turns out, the `cronjob` does not source the user's `.profile`, and so `all-repos` is not available on the path. This also means, there are two solutions... - hardcode the path to `all-repos` or - amend the PATH env-var I went with hardcoding the path. While this seemed hacky at first, actually this the cleanest solution. When I come back later, or even a colleague who never saw this setup, it is pretty obvious what should happen here. ## Thanks Thank you [Bernát Gábor](https://twitter.com/gjbernat) and [senpos](https://twitter.com/_senpos) for the feedback!
Markdown
UTF-8
2,936
3.53125
4
[]
no_license
# Object Oriented Programming in JavaScript This is a discussion on: - object oriented programming - reasons to use it - applications that would benefit from OOP ## Table of contents - [Overview](#overview) - [What is OOP?](#what-is-oop) - [Why would you use it?](#why-would-you-use-it) - [When would you use OOP patterns?](#when-would-you-use-oop-patterns) - [Example OOP project](#example-oop-project) - [Images](#images) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Useful resources](#useful-resources) - [Author](#author) ## Overview ### What is OOP? The basic idea of **object oriented programming** is that we can use **objects** to model real world things. These **objects** can have data and other code to represent important information about the thing you are trying to model. ### Why would you use it? **Objects** have their own properties and functions (known as **methods**) which can be stored neatly inside an object package, making it easy to structure and access. **Objects** are also commonly used as data stores that can be easily sent across a network. ### When would you use OOP patterns? When you need to solve complex programming challenges and want to add code tools to your skill set, OOP is a great choice, because it allows you to break down your project into bite-sized problems that you can then solve - one object at a time. ### Example OOP project A movie database is one type of application you can build that would benefit greatly from an OOP structure. Users of such a database can use the application to: - Browse available movies - Search for movies - See a particular movie's details - View movies in a favorites list - Add movies to a favorites list - Remove movies from a favorites list ### Images ![](./img/oop_chart.svg) An example image depicting an **OOP** structure for a movie database. What's in view: - **Objects** that would be in such an application - **Properties** that such **Objects** would have - **Methods** that would be found in such **objects** - How the **objects** can be instantiated using the **new** keyword ## My process ### Built with - [Inkscape](https://inkscape.org) ### What I learned - With the power of **encapsulation** locating and fixing problems is much easier when using an **OOP** approach. - **inheritance** makes it is easy to reuse code. ### Continued development - I want to understand **OOP** better by using it more in projects. That would, in turn, help me improve my problem solving skills. ### Useful resources - [Inkscape](https://inkscape.org) - Inkscape SVG Editor. I use it all the time when I'm working on any web project. ## Author - Github - [Allan Kirui](https://www.github.com/AllanKirui) - Instagram - [@nallawilljr](https://www.instagram.com/nallawilljr)
Java
UTF-8
1,442
3.390625
3
[]
no_license
package com.xue.oj; public class Atoi { public static void main(String[] args) { Atoi main = new Atoi(); /* System.out.println(main.myAtoi("1")); System.out.println(main.myAtoi("2147483648")); System.out.println(main.myAtoi("-")); System.out.println(main.myAtoi("+-2")); System.out.println(main.myAtoi(" -0012a42"));*/ System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MAX_VALUE + 1); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MIN_VALUE - 1); } public int myAtoi(String str) { if (str == null) return 0; str = str.trim(); char[] arr = str.toCharArray(); boolean min = false; int signCount = 0; double sum = 0; for (char c : arr) { if (c == '+') { signCount++; continue; } if (c == '-') { min = true; signCount++; continue; } if (c >= '0' && c <= '9') { sum *= 10; sum += c - '0'; } else { break; } } if (signCount > 1) return 0; if (min) sum *= -1; if (sum < Integer.MIN_VALUE) return Integer.MIN_VALUE; if (sum > Integer.MAX_VALUE) return Integer.MAX_VALUE; return (int) sum; } }
Java
UTF-8
3,646
2.84375
3
[]
no_license
/** * */ package org.yelong.core.cache; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.yelong.core.annotation.Nullable; /** * 缓存管理器 * * @since 1.3 */ public interface CacheManager { /** * 添加一个缓存,如果缓存管理器中已经存在该缓存的键值,将替换原来的值 * * @param <T> cache entity type * @param key key * @param cacheEntity 缓存对象 * @return 缓存的对象 */ <T> CacheEntity<T> putCache(String key, CacheEntity<T> cacheEntity); /** * 添加一个缓存,如果缓存管理器中已经存在该缓存的键值,将替换原来的值 * * @param <T> cache entity type * @param key key * @param entity 缓存的实体对象 * @return 缓存的对象 */ <T> CacheEntity<T> putCache(String key, T entity); /** * 获取缓存的实体,如果不存在该键值的缓存则工具工厂获取值,在将值放入缓存中 * * @param <T> cache entity type * @param key 键值 * @param cacheValueFactory 缓存的值工厂 * @return 缓存的实体 * @since 2.1 */ default <T> CacheEntity<T> putCacheIfAbsent(String key, Function<String, T> cacheValueFactory) { synchronized (this) { boolean containsKey = containsKey(key); if (containsKey) { return getCache(key); } T entity = cacheValueFactory.apply(key); CacheEntity<T> cacheEntity = CacheEntitys.defaultCacheEntity(entity); putCache(key, cacheEntity); return cacheEntity; } } /** * 获取缓存的值,如果不存在该键值的缓存则工具工厂获取值,在将值放入缓存中 * * @param <T> cache entity type * @param key 键值 * @param cacheValueFactory 缓存的值工厂 * @return 缓存的值 * @since 2.1 */ default <T> T putCacheObjIfAbsent(String key, Function<String, T> cacheValueFactory) { return putCacheIfAbsent(key, cacheValueFactory).get(); } /** * 获取缓存信息 * * @param <T> cache entity type * @param key key * @return 获取缓存中的缓存信息。如果缓存中不存在这个缓存则返回 {@link CacheEntitys#emptyCacheEntity()} */ <T> CacheEntity<T> getCache(String key); /** * 获取缓存的实体 * * @param <T> cache entity type * @param key key * @return 缓存的对象。如果缓存中不存在这个缓存则返回 <code>null</code> */ @SuppressWarnings("unchecked") default <T> T getCacheObj(String key) { return (T) getCache(key).get(); } /** * @return 所有已经缓存的对象 */ Map<String, CacheEntity<?>> getCacheAll(); /** * 缓存中是否存在该键值的缓存 * * @param key key * @return <code>true</code> 缓存中存在该缓存 */ boolean containsKey(String key); /** * 移除一个缓存对象 * * @param <T> cache entity type * @param key key * @return 如果缓存中存在这个这个对象,则返回原来缓存的这个对象,否则返回 * {@link CacheEntitys#emptyCacheEntity()} */ <T> CacheEntity<T> remove(String key); /** * 直接移除缓存中该键值的对象 * * @param key key */ void removeQuietly(String key); /** * @return 该缓存管理器中所有已经缓存的键值集合 */ Set<String> getKeys(); /** * 清空该缓存管理器中的所有缓存对象 */ void clear(); /** * @return 缓存管理器的名称 */ @Nullable String getName(); }
Java
UTF-8
3,317
2.046875
2
[ "Apache-2.0", "GPL-1.0-or-later", "MIT", "GPL-2.0-only", "BSD-3-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.core.clientImpl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.accumulo.core.client.admin.CompactionStrategyConfig; public class CompactionStrategyConfigUtil { public static final CompactionStrategyConfig DEFAULT_STRATEGY = new CompactionStrategyConfig( "org.apache.accumulo.tserver.compaction.EverythingCompactionStrategy") { @Override public CompactionStrategyConfig setOptions(Map<String,String> opts) { throw new UnsupportedOperationException(); } }; private static final int MAGIC = 0xcc5e6024; public static void encode(DataOutput dout, CompactionStrategyConfig csc) throws IOException { dout.writeInt(MAGIC); dout.writeByte(1); dout.writeUTF(csc.getClassName()); dout.writeInt(csc.getOptions().size()); for (Entry<String,String> entry : csc.getOptions().entrySet()) { dout.writeUTF(entry.getKey()); dout.writeUTF(entry.getValue()); } } public static byte[] encode(CompactionStrategyConfig csc) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); try { encode(dos, csc); dos.close(); return baos.toByteArray(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } public static CompactionStrategyConfig decode(DataInput din) throws IOException { if (din.readInt() != MAGIC) { throw new IllegalArgumentException("Unexpected MAGIC "); } if (din.readByte() != 1) { throw new IllegalArgumentException("Unexpected version"); } String classname = din.readUTF(); int numEntries = din.readInt(); HashMap<String,String> opts = new HashMap<>(); for (int i = 0; i < numEntries; i++) { String k = din.readUTF(); String v = din.readUTF(); opts.put(k, v); } return new CompactionStrategyConfig(classname).setOptions(opts); } public static CompactionStrategyConfig decode(byte[] encodedCsc) { ByteArrayInputStream bais = new ByteArrayInputStream(encodedCsc); DataInputStream dis = new DataInputStream(bais); try { return decode(dis); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
SQL
UTF-8
2,111
2.578125
3
[]
no_license
INSERT INTO `Bonuses` (`CreateDate`, `ExpirationDate`, `UserID`, `ServiceID`, `SchemeID`, `DaysReserved`, `DaysRemainded`, `Discont`, `Comment`) SELECT `CreateDate`, (UNIX_TIMESTAMP() + 365*24*3600), `UserID`,'10000',`SchemeID`,`DaysReserved`,`DaysRemainded`,`Discont`,`Comment` FROM `HostingBonuses`; -- SEPARATOR INSERT INTO `Bonuses` (`CreateDate`, `ExpirationDate`, `UserID`, `ServiceID`, `SchemeID`, `DaysReserved`, `DaysRemainded`, `Discont`, `Comment`) SELECT `CreateDate`, (UNIX_TIMESTAMP() + 365*24*3600), `UserID`,'30000',`SchemeID`,`DaysReserved`,`DaysRemainded`,`Discont`,`Comment` FROM `VPSBonuses`; -- SEPARATOR INSERT INTO `Bonuses` (`CreateDate`, `ExpirationDate`, `UserID`, `ServiceID`, `SchemeID`, `DaysReserved`, `DaysRemainded`, `Discont`, `Comment`) SELECT `CreateDate`, (UNIX_TIMESTAMP() + 365*24*3600), `UserID`,'40000',`SchemeID`,`DaysReserved`,`DaysRemainded`,`Discont`,`Comment` FROM `DSBonuses`; -- SEPARATOR INSERT INTO `Bonuses` (`CreateDate`, `ExpirationDate`, `UserID`, `ServiceID`, `SchemeID`, `DaysReserved`, `DaysRemainded`, `Discont`, `Comment`) SELECT `CreateDate`, (UNIX_TIMESTAMP() + 365*24*3600), `UserID`,'50000',`SchemeID`,`DaysReserved`,`DaysRemainded`,`Discont`,`Comment` FROM `ExtraIPBonuses`; -- SEPARATOR INSERT INTO `Bonuses` (`CreateDate`, `ExpirationDate`, `UserID`, `ServiceID`, `SchemeID`, `DaysReserved`, `DaysRemainded`, `Discont`, `Comment`) SELECT `CreateDate`, (UNIX_TIMESTAMP() + 365*24*3600), `UserID`,'51000',`SchemeID`,`DaysReserved`,`DaysRemainded`,`Discont`,`Comment` FROM `ISPswBonuses`; -- SEPARATOR DROP VIEW IF EXISTS `HostingBonusesOwners`; -- SEPARATOR DROP TABLE IF EXISTS `HostingBonuses`; -- SEPARATOR DROP VIEW IF EXISTS `VPSBonusesOwners`; -- SEPARATOR DROP TABLE IF EXISTS `VPSBonuses`; -- SEPARATOR DROP VIEW IF EXISTS `DSBonusesOwners`; -- SEPARATOR DROP TABLE IF EXISTS `DSBonuses`; -- SEPARATOR DROP VIEW IF EXISTS `ExtraIPBonusesOwners`; -- SEPARATOR DROP TABLE IF EXISTS `ExtraIPBonuses`; -- SEPARATOR DROP VIEW IF EXISTS `ISPswBonusesOwners`; -- SEPARATOR DROP TABLE IF EXISTS `ISPswBonuses`;
Python
UTF-8
1,700
2.96875
3
[]
no_license
# #listdir stat # import os # print(os.listdir('d:')) # files = os.listdir('d:') # for file in files: # print(file) # print(os.stat("D:/345.jpg")) #返回文件的相关系统信息 # print(os.stat('d:/345.jpg').st_atime) #查看最后访问文件的时间 # print(os.stat('d:/345.jpg').st_mtime) #查看文件的最后修改时间 # print(os.stat('d:/345.jpg').st_ctime) #文件创建时间 # print(os.stat('d:/345.jpg').st_size) #文件字节大小 # import time # print(dir(time)) # print(time.localtime()) # print(time.asctime(time.localtime(time.time()))) #格式化时间 # #查看当前工作目录 # print(os.getcwd()) # name = "jao" # age = 16 # sex = 'man' # print(name,age,sex,end = " ",sep = "**") #sep分隔符 # f = open("日记本.txt",'w') # print('2019年7月13日阅读完一本书',file = f) from pillowfrom PIL import Image, ImageDraw, ImageFont def add_num(img): draw = ImageDraw.Draw(img) myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=40) fillcolor = "#ff0000" width, height = img.size draw.text((width-40, 0), '99', font=myfont, fill=fillcolor) img.save('result.jpg','jpeg') return 0 if __name__ == '__main__': image = Image.open('image.jpg') add_num(image) import Image, ImageDraw, ImageFont def add_num(img): draw = ImageDraw.Draw(img) myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf', size=40) fillcolor = "#ff0000" width, height = img.size draw.text((width-40, 0), '99', font=myfont, fill=fillcolor) img.save('result.jpg','jpeg') return 0 if __name__ == '__main__': image = Image.open('image.jpg') add_num(image)
PHP
UTF-8
2,059
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "intclient". * * @property integer $id * @property string $intclient_desc * @property string $intclient_remarks * @property integer $dep_id * @property integer $intclient_xinterger1 * @property boolean $intclient_xboolean1 * @property string $intclient_xdate1 * @property string $intclient_xvarchar1 * * @property Dep $dep * @property Mi[] $mis */ class Intclient extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'intclient'; } /** * @inheritdoc */ public function rules() { return [ [['intclient_desc', 'dep_id'], 'required'], [['dep_id', 'intclient_xinterger1'], 'integer'], [['intclient_xboolean1'], 'boolean'], [['intclient_xdate1'], 'safe'], [['intclient_desc'], 'string', 'max' => 20], [['intclient_remarks'], 'string', 'max' => 50], [['intclient_xvarchar1'], 'string', 'max' => 30], [['dep_id'], 'exist', 'skipOnError' => true, 'targetClass' => Dep::className(), 'targetAttribute' => ['dep_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'intclient_desc' => 'Intclient', 'intclient_remarks' => 'Remarks', 'dep_id' => 'Dep', 'intclient_xinterger1' => 'Intclient Xinterger1', 'intclient_xboolean1' => 'Intclient Xboolean1', 'intclient_xdate1' => 'Intclient Xdate1', 'intclient_xvarchar1' => 'Intclient Xvarchar1', ]; } /** * @return \yii\db\ActiveQuery */ public function getDep() { return $this->hasOne(Dep::className(), ['id' => 'dep_id']); } /** * @return \yii\db\ActiveQuery */ public function getMis() { return $this->hasMany(Mi::className(), ['intclient_id' => 'id']); } }
Java
UTF-8
350
2
2
[]
no_license
package com.dto; import javax.validation.constraints.Min; import org.springframework.stereotype.Component; import lombok.Data; @Component @Data public class SongSystemDTO { @Min(value = 0, message = "{songsystem.positive}") private int positionInPlaylist; @Min(value = 0, message = "{songsystem.positive}") private Integer secondsPlayed; }
Java
UTF-8
892
2.09375
2
[]
no_license
package com.example.bazadedateexplo; public class ParinteClass { int idParinte; String nume; String prenume; String gen; String nrDeTelefon; public int getIdParinte() { return idParinte; } public void setIdParinte(int idParinte) { this.idParinte = idParinte; } public String getNume() { return nume; } public void setNume(String nume) { this.nume = nume; } public String getPrenume() { return prenume; } public void setPrenume(String prenume) { this.prenume = prenume; } public String getGen() { return gen; } public void setGen(String gen) { this.gen = gen; } public String getNrDeTelefon() { return nrDeTelefon; } public void setNrDeTelefon(String nrDeTelefon) { this.nrDeTelefon = nrDeTelefon; } }
Python
UTF-8
8,162
3.921875
4
[]
no_license
# # MNIST via Multilayer Convolution Network # This script is baed on the [MNIST for Deep Learning Experts using TensorFlow](https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/examples/tutorials/mnist/mnist_deep.py) # # Setup # - Ensure TensorFlow is installed via PyPi # - Note this is a demo script as opposed to a Python script file; # i.e. execute via python shell # # 1. Start Python # - type "python" within bash terminal # # ## Convolution, pooling, weights and biases # The first method helps to create a 2-D convolutional layer for a specified input ```x``` and specified kernel size ```W```. The ```strides``` parameter specifies the *movement* of the kernel on the original image: in this case each convolution will *skip* one pixel at a time. The ```padding``` parameter keeps the output size of the features ```SAME``` as the input. # The pooling layers will be created using the ```max_pool(...)``` method. Each of our pooling layers has a 2x2 kernel and will skip---the ```strides``` parameter---2 rows and 2 columns at a time. The ```padding``` parameter here will apply padding if any downsampling results in a fractional number of pixels. # Every neuron (apart from those in the input layer) is connected to its predecessors via a number of links, each with a specific weight attached to it. The code below initializes the weights to a random number drawn from a ```truncated_normal``` distribution with standard deviation of 0.1. The ```shape``` parameter is used by the method's logic to determine how many weights to create. # Just like the weights, each neuron has some *tuneable* bias. The ```bias_variable(...)``` method initializes the biases for the neurons to a ```constant``` equal to 0.1; these biases change as we train the network. # # 2. Setup functions # def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): """max_pool_2x2 downsamples a feature map by 2X.""" return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Weight Initialization def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # ## Create the model # The ```deepnn(...)``` method builds the artificial neural network we will use to classify the digits. # Here's the overview of the structure of the network we will use: # ![](http://tomdrabas.com/data/PyData/ConvStructure_NoTanh.png) # 1. The input layer is a grey scale image of 28x28 pixels. This is accomplished with the ```tf.reshape(...)``` method. The first parameter to the function is the *tensor* we want to reshape, and the other one specifies the desired shape of the output. # 2. Convolution layer 1 maps one grayscale image to 32 feature maps using 5x5 kernels using ReLU (rectifier) activation function # 3. Pooling layer 1 down samples image by 2x so you have a 14x14 matrix # 4. Convolution layer 2 maps 32 feature maps to 64 using ReLU (rectifier) activation function # 5. Pooling layer 2 down samples by 2x with 64 images of 7x7 (vs. 14x14) # 6. The fully connected feed-forward part maps the 64 features of 7x7 pixels to an array of 1024 neurons that then get passed throught the ```argmax(...)``` method to come up with an actual output with one activated neuron. The ```matmul(...)``` method is nothing more than a matrix multiplication applied to an input matrix and corresponding matrix of weights. def deepnn(x): """deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values equal to the logits of classifying the digit into one of 10 classes (the digits 0-9). keep_prob is a scalar placeholder for the probability of dropout. """ # Reshape to use within a convolutional neural net. # Last dimension is for "features" - there is only one here, since images are # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. x_image = tf.reshape(x, [-1, 28, 28, 1]) # # First convolutional layer - maps one grayscale image to 32 feature maps. W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # # Pooling layer - downsamples by 2X. h_pool1 = max_pool_2x2(h_conv1) # # Second convolutional layer -- maps 32 feature maps to 64. W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # # Second pooling layer. h_pool2 = max_pool_2x2(h_conv2) # # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image # is down to 7x7x64 feature maps -- maps this to 1024 features. W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # # Dropout - controls the complexity of the model, prevents co-adaptation of # features. keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # # Map the 1024 features to 10 classes, one for each digit W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 return y_conv, keep_prob # ## Training the model # This is the main script of the tutorial where we use all that we have defined so far. # First, we read in the ```MNIST_data``` and specify that the output is to be ```one_hot``` encoded. Next, we create the placeholders for our input and output. Using the previously defined ```deepnn(...)``` method we create our DNN to be trained. # The goal of training our network is to minimze the ```cross_entropy```; the ```cross_entropy``` is defined as an average of the outputs from the ```softmax``` layer. We are using the ```AdamOptimizer``` with a specified learning rate of 0.0001. # To determine if the network has produced a correct prediction we use the ```argmax(...)``` method that returns an index associated with the maximum value in our output layer; this is then compared with the *desired* signal using the ```equal(...)``` method. # The overall accuracy is calculated as a mean of the correct and incorrect responses. # To train our network we use batches of 50 images; the weights are adjusted only after each batch iteration. # Import TensorFlow import tensorflow as tf # Import MNIST digit images data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Create the model x = tf.placeholder(tf.float32, [None, 784]) # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, 10]) # Build the graph for the deep net y_conv, keep_prob = deepnn(x) cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Launch the model sess = tf.InteractiveSession() # Initialize the variables tf.global_variables_initializer().run() # By default, should have the range go to 20,000 for i in range(1500): batch = mnist.train.next_batch(50) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) print('step %d, training accuracy %g' % (i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) ## Finally, we test the accuracy of our trained network. print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images[:500, :784], y_: mnist.test.labels[:500,:10], keep_prob: 1.0}))
Java
UTF-8
701
2.671875
3
[]
no_license
package validator; import entity.Choices; import exceptions.ChoicesException; public class ChoicesValidator { public boolean validChoices(Choices choices) throws ChoicesException { boolean res = validAnswer(choices.getAnswers()); res &= validA(choices.getOptionA()); res &= validB(choices.getOptionB()); res &= validC(choices.getOptionC()); if(!res) throw new ChoicesException(); return res; } private boolean validAnswer(String a){ return !a.isEmpty();} private boolean validA(String a){ return !a.isEmpty();} private boolean validB(String a){ return !a.isEmpty();} private boolean validC(String a){ return !a.isEmpty();} }
Python
UTF-8
3,004
2.875
3
[]
no_license
import sqlite3 import os FILE = input("Enter File Name") File_Loc = os.path.join(os.path.dirname(__file__), (FILE + ".db")) def table_print(): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"Select name from sqlite_master where type='table'") table_name = [i[0] for i in cur.fetchall()] con.close() return table_name def table_exists(table_name): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"Select count(*) from sqlite_master where type='table' and name='{table_name}' ") if (cur.fetchone()[0] == 0): con.close() return False else: con.close() return True def column_print(table_name): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"Pragma table_info({table_name})") columns = [i[1] for i in cur.fetchall()] con.close() return columns def column_exists(table_name, col_name): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"Pragma table_info({table_name})") columns = [i[1].lower() for i in cur.fetchall()] con.close() if (col_name.lower() in columns): return True else: return False def create_table(table_name, columns): con = sqlite3.connect(File_Loc) columns_string = ",".join([" ".join(column) for column in columns]) cur = con.cursor() cur.execute( f"create table {table_name} ({columns_string})") con.commit() con.close() def drop_table(table_name): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"drop table {table_name}") con.commit() con.close() def insert_in(table_name, data, columns=[]): con = sqlite3.connect(File_Loc) cur = con.cursor() columns_string = "" if (columns != []): columns_string = "(" + ",".join(columns) + ")" data_string = "(" + ",".join(data) + ")" cur.execute( f"insert into {table_name} {columns_string} values {data_string}") con.commit() con.close() def update_table(table_name, upd, cond=""): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"update {table_name} set {upd}" + ((" where " + cond) if cond else "")) con.commit() con.close() def delete_table(table_name, cond=""): con = sqlite3.connect(File_Loc) cur = con.cursor() cur.execute( f"delete from {table_name}" + ((" where " + cond) if cond else "")) con.commit() con.close() def print_table(table_name, columns=["*"], cond=""): con = sqlite3.connect(File_Loc) cur = con.cursor() column_stg = ",".join(columns) cur.execute( (f"select {column_stg} from {table_name} " + (("where " + cond) if cond else ""))) tup = list(cur.fetchall()) stg = "" for i in tup: for j in i: stg += (str(j) + "\t") stg += "\n" con.close() return stg print(print_table("User_Files"))
PHP
UTF-8
647
2.59375
3
[]
no_license
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\User; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // \App\Models\User::factory(10)->create(); $faker = Faker\Factory::create(); for($i = 0; $i < 25; $i++) { User::create([ 'name' => $faker->name, 'email' => $faker->email, 'password' => 'sss', 'created_at' => $faker->date, 'updated_at' => $faker->date, ]); } } }
JavaScript
UTF-8
276
3.171875
3
[]
no_license
function getMin() { if (arguments.length === 0) { console.log("empty arguments"); return; } var min = arguments[0]; for (let i = 1; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i]; } } return console.log(min); } getMin(1, 5,4,-1,-5);
C#
UTF-8
837
2.6875
3
[]
no_license
using System; namespace Ivony.Http.Pipeline { /// <summary> /// a jointer to join two pipeline /// </summary> internal sealed class HttpPipelineJointer : IHttpPipeline { private readonly IHttpPipeline _upstream; private readonly IHttpPipeline _downstream; public HttpPipelineJointer( IHttpPipeline upstream, IHttpPipeline downstream ) { if ( downstream is IDummyHttpPipeline ) throw new InvalidOperationException( "can not join a dummy pipeline as downstream!" ); _upstream = upstream; _downstream = downstream; } IHttpPipelineHandler IHttpPipeline.Join( IHttpPipelineHandler handler ) { return _upstream.Join( _downstream.Join( handler ) ); } public override string ToString() { return $"{_upstream}\n-> {_downstream}"; } } }
PHP
UTF-8
1,837
2.53125
3
[ "MIT" ]
permissive
<?php /* * This file is part of the API Platform project. * * (c) Kévin Dunglas <dunglas@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace ApiPlatform\JsonLd\Serializer; use ApiPlatform\JsonLd\AnonymousContextBuilderInterface; use ApiPlatform\JsonLd\ContextBuilderInterface; /** * Creates and manipulates the Serializer context. * * @author Kévin Dunglas <dunglas@gmail.com> * * @internal */ trait JsonLdContextTrait { /** * Updates the given JSON-LD document to add its @context key. */ private function addJsonLdContext(ContextBuilderInterface $contextBuilder, string $resourceClass, array &$context, array $data = []): array { if (isset($context['jsonld_has_context'])) { return $data; } $context['jsonld_has_context'] = true; if (isset($context['jsonld_embed_context'])) { $data['@context'] = $contextBuilder->getResourceContext($resourceClass); return $data; } $data['@context'] = $contextBuilder->getResourceContextUri($resourceClass); return $data; } private function createJsonLdContext(AnonymousContextBuilderInterface $contextBuilder, $object, array &$context): array { // We're in a collection, don't add the @context part if (isset($context['jsonld_has_context'])) { return $contextBuilder->getAnonymousResourceContext($object, ($context['output'] ?? []) + ['api_resource' => $context['api_resource'] ?? null, 'has_context' => true]); } $context['jsonld_has_context'] = true; return $contextBuilder->getAnonymousResourceContext($object, ($context['output'] ?? []) + ['api_resource' => $context['api_resource'] ?? null]); } }
Python
UTF-8
2,436
4.4375
4
[]
no_license
# 写法一: class Rectangle: "正方形" def __init__(self, width, height): # ① self.width = width self.height = height def __setattr__(self, key, value): if key == "square": self.width = value self.height = value else: # ② print("setattr: ", key, value) self.key = value def _getArea(self): "获取面积" return self.width * self.height ## # 此处代码造成的结果是 死循环。 # Cause By,init 方法执行给属性设置值(代码片段①),进入 setattr 方法, # 然后执行到 ② 位置再次进行 设置值,又再次回到了 setattr 方法,这样就形成了一个无限递归。直到当前系统分配的递归层次执行完成。 # ## # print("-------方式1------") # a = Rectangle(4, 5) # 以上代码调整写法 写法二 class Rectangle1: "正方形" def __init__(self, width, height): # ① self.width = width self.height = height def __setattr__(self, key, value): if key == "square": self.width = value self.height = value else: # ② print("setattr: ", key, value) # self.key = value super().__setattr__(key, value) # 修改此处代码为调用父类的 setattr 方法 def getArea(self): "获取面积" return self.width * self.height print("-------方式2------") a = Rectangle1(4, 5) print(a.getArea()) # 执行结果 # setattr: width 4 # setattr: height 5 # 20 print("-------------") a.square = 10 print(a.getArea()) # 执行结果 # setattr: width 10 # setattr: height 10 # 100 print("-------方式3------") # dict 获取对象中的所有属性参数 # print(a.__dict__) # 输出 {'width': 10, 'height': 10} # 改法三 class Rectangle2: "正方形" def __init__(self, width, height): # ① self.width = width self.height = height def __setattr__(self, key, value): if key == "square": self.width = value self.height = value else: # ② print("setattr: ", key, value) # self.key = value self.__dict__[key] = value def getArea(self): "获取面积" return self.width * self.height a = Rectangle2(4, 5) print(a.getArea())
C#
UTF-8
1,450
3.15625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using XmlValidation.FileTypes; namespace XmlValidation { public class XsdCache { /// <summary> /// Cache that Holds all the loaded XSDs /// </summary> private Dictionary<string, XsdFile> xsds = new Dictionary<string, XsdFile>(); /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public XsdFile Load(string path) { // load the new xsd if (File.Exists(path) == false) { //TODO : create a specific extesion throw new Exception("XSD File doest not exist"); } XsdFile xsdFileInfo = new XsdFile() { Name = Path.GetFileName(path), Path = path }; this.xsds.Add(path, xsdFileInfo); return xsdFileInfo; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public XsdFile Get(string path) { //check if the file is loaded if (xsds.ContainsKey(path)) { //return from cache return xsds[path]; } return this.Load(path); } } }
TypeScript
UTF-8
3,297
2.875
3
[]
no_license
import axios from 'axios'; import { injectable } from 'tsyringe'; import { HttpInterceptor, HttpRequestInterceptor } from '../../../models/httpClient'; @injectable() export class ArianeeHttpClient { private httpRequestInterceptor:HttpRequestInterceptor; private httpFetch=(url, config) => axios(url, config).then(result => result.data); public setRequestInterceptor=(interceptor:HttpRequestInterceptor):ArianeeHttpClient => { this.httpRequestInterceptor = interceptor; return this; } public setHttpFetch=(httpFetch:(url, config)=>Promise<any>):ArianeeHttpClient => { this.httpFetch = httpFetch; return this; } /** * Calculate hash key from url and headers of a request * @param url * @param config * @return {string} */ private static createKeyFromURL = (url, config) => { const hash = function (s) { let a = 1; let c = 0; let h; let o; if (s) { a = 0; for (h = s.length - 1; h >= 0; h--) { o = s.charCodeAt(h); a = ((a << 6) & 268435455) + o + (o << 14); c = a & 266338304; a = c !== 0 ? a ^ (c >> 21) : a; } } return String(a); }; return hash(JSON.stringify(url) + JSON.stringify(config)); } private RPCConfigurationFactory = (endpoint, method, params) => { return { method: 'POST', data: { jsonrpc: '2.0', method: method, params: params, id: ArianeeHttpClient.createKeyFromURL(endpoint, params) }, headers: { 'Content-Type': 'application/json' } }; } public RPCCall = async <resultType=any>(endpoint: string, method: string, params: any): Promise<{ jsonrpc: number, id: string, result?: resultType }> => { const config = this.RPCConfigurationFactory(endpoint, method, params); const RPCRes = await this.fetch(endpoint, config); if (RPCRes.error) { throw new Error(JSON.stringify(RPCRes.error)); } if (RPCRes.result) { RPCRes.result = (typeof (RPCRes.result) === 'string') ? JSON.parse(RPCRes.result) : RPCRes.result; } return RPCRes; } /** * Default headers for fetch */ public static get defaultConfig () { return { method: 'GET', headers: { 'Content-Type': 'application/json' } }; } /** * HTTP call * Default configuration of headers is method GET and content-type: application/json * @param url * @param config * @return Promise{any} */ public async fetch ( url: string, config: any = { ...ArianeeHttpClient.defaultConfig } ) { if (config.body) { config.data = config.body; } if (this.httpRequestInterceptor) { const result = await this.httpRequestInterceptor(url, config); url = result.url; config = result.config; } try { return this.httpFetch(url, config); } catch (e) { console.warn('Error on fetch', url, config); Promise.reject(e); } } /** * The exact same method as static fetch method */ }
Swift
UTF-8
1,628
2.765625
3
[ "MIT" ]
permissive
// // ViewController.swift // 191203_Segue // // Created by Demian on 2019/12/03. // Copyright © 2019 Demian. All rights reserved. // import UIKit class FirstViewController: UIViewController { var count = 0 override func viewDidLoad() { super.viewDidLoad() } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { super.shouldPerformSegue(withIdentifier: identifier, sender: sender) let plus = identifier == "plus1" ? 1 : 10 count += plus return count <= 40 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) // segue.destination // 목적지 // segue.source // 출발지 // segue.identifier // segue의 이 guard let label_b = segue.destination as? SecondViewController else { return } if segue.identifier == "plus1" { // label_b.text = "Card" label_b.text = String(count) } else { // label_b.text = "Fullscreen" label_b.text = String(count) } } @IBAction func unwindToVC_a(_ unwindSegue: UIStoryboardSegue) { let sourceViewController = unwindSegue.source guard let textfield_a = unwindSegue.source as? SecondViewController else { return } print(textfield_a.minus) self.count -= textfield_a.minus } }
Python
UTF-8
4,178
3.21875
3
[ "MIT" ]
permissive
##I'm still working on a new tests import spaghetti_sort import unittest class O: def __init__(self, x): self.x = x def __repr__(self): return str(self.x) class Autotests(unittest.TestCase): def test_simple_list(self): self.assertEqual(spaghetti_sort.spaghetti([-3, 3, 1, 2, -1, 4, 0]), [-3, -1, 0, 1, 2, 3, 4]) #test nr 0 self.assertEqual(spaghetti_sort.spaghetti([1096, 2006, 1004, 1008]), [1004, 1008, 1096, 2006]) #test nr 1 self.assertEqual(spaghetti_sort.spaghetti([-800, -600, 1100, 900]), [-800, -600, 900, 1100]) #test nr 2 self.assertEqual(spaghetti_sort.spaghetti([157, 69, 67, 420]), [67, 69, 157, 420]) #test nr 3 def test_list_with_repeated_elements(self): self.assertEqual(spaghetti_sort.spaghetti([54607, -67893, 23674, -30540, -94432, -67893]), [-94432, -67893, -67893, -30540, 23674, 54607]) #test nr 4 self.assertEqual(spaghetti_sort.spaghetti([67, -63, 64, 67, 64, -63, 65, 65, 64]), [-63, -63, 64, 64, 64, 65, 65, 67, 67]) #test nr 5 self.assertEqual(spaghetti_sort.spaghetti([0, 0, 0, 0, 0, 0, 0]), [0, 0, 0, 0, 0, 0, 0]) #test nr 6 self.assertEqual(spaghetti_sort.spaghetti([81, 81, 78, 78, 78]), [78, 78, 78, 81, 81]) #test nr 7 def test_list_already_sorted(self): self.assertEqual(spaghetti_sort.spaghetti([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #test nr 8 self.assertEqual(spaghetti_sort.spaghetti([8, 67, 545, -9063, 34607, -567]), [-9063, -567, 8, 67, 545, 34607]) #test nr 9 self.assertEqual(spaghetti_sort.spaghetti([14, 14, 14, 14, 14, 14]), [14, 14, 14, 14, 14, 14]) #test nr 10 self.assertEqual(spaghetti_sort.spaghetti([-78, -78, -81]), [-81, -78, -78]) #test nr 11 def test_list_sorted_reversed(self): self.assertEqual(spaghetti_sort.spaghetti([769003, 12999, 9001, 238, 98, 2, 1, 0]), [0, 1, 2, 98, 238, 9001, 12999, 769003]) #test nr 12 self.assertEqual(spaghetti_sort.spaghetti([-23098, 23067, -23054, 23045, 23008]), [-23098, -23054, 23008, 23045, 23067]) #test nr 13 self.assertEqual(spaghetti_sort.spaghetti([697, 586, 475, 364, 253, 142, 31, 2, -1, -901]), [-901, -1, 2, 31, 142, 253, 364, 475, 586, 697]) #test nr 14 self.assertEqual(spaghetti_sort.spaghetti([8, 6, 4, 2, 0, -2, -4, -6, -8]), [-8, -6, -4, -2, 0, 2, 4, 6, 8]) #test nr 15 def test_stable(self): e1, e2, e3, e4, e5 = O(5), O(8), O(8), O(15), O(8) self.assertEqual(spaghetti_sort.spaghetti([e4, e2, e3, e1], key = lambda elem: elem.x), [e1, e2, e3, e4]) #test nr 16 self.assertEqual(spaghetti_sort.spaghetti([e5, e1, e2, e4, e3], key = lambda elem: elem.x), [e1, e5, e2, e3, e4]) #test nr 17 self.assertEqual(spaghetti_sort.spaghetti([e5, e2, e3], key = lambda elem: elem.x), [e5, e2, e3]) #test nr 18 self.assertEqual(spaghetti_sort.spaghetti([e4, e2, e1, e5, e1], key = lambda elem: elem.x, descending = True), [e4, e2, e5, e1, e1]) #test nr 19 def test_descending_order(self): self.assertEqual(spaghetti_sort.spaghetti([16208, 16203, -5067, 16205, 16204, -34], descending = True), [16208, 16205, 16204, 16203, -34, -5067]) #test nr 20 self.assertEqual(spaghetti_sort.spaghetti([91, 23, 145, 130, 145, -6, 13], descending = True), [145, 145, 130, 91, 23, 13, -6]) #test nr 21 self.assertEqual(spaghetti_sort.spaghetti([-10, -5, -4, -3, -2, -1], descending = True), [-1, -2, -3, -4, -5, -10]) #test nr 22 self.assertEqual(spaghetti_sort.spaghetti([-3, 3, -3, 4, -4, 4, -4, 4], descending = True), [4, 4, 4, 3, -3, -3, -4, -4]) #test nr 23 def test_other(self): self.assertEqual(spaghetti_sort.spaghetti([]), []) #test nr 24 self.assertEqual(spaghetti_sort.spaghetti([], descending = True), []) #test nr 25 self.assertEqual(spaghetti_sort.spaghetti([[9, 'x']], key = lambda elem: elem[0]), [[9, 'x']]) #test nr 26 self.assertEqual(spaghetti_sort.spaghetti([[9, 'x']], descending = True, key = lambda elem: elem[0]), [[9, 'x']]) #test nr 27 if __name__ == '__main__': unittest.main()
C++
UTF-8
457
2.671875
3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
#ifndef NUMPY_H #define NUMPY_H namespace TSnap { /// Converts TIntV to Numpy array. void TIntVToNumpy(TIntV& IntV, int* IntNumpyVecOut, int n); /// Converts TFltV to Numpy array. void TFltVToNumpy(TFltV& FltV, float* FltNumpyVecOut, int n); /// Converts NumpyArray to TIntV void NumpyToTIntV(TIntV& IntV, int* IntNumpyVecIn, int n); /// Converts NumpyArray to TFltV void NumpyToTFltV(TFltV& FltV, float* FltNumpyVecIn, int n); } #endif //NUMPY_H
Markdown
UTF-8
8,529
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
## Hotspot A human-friendly HTML landing page for users resolving URLs within their browser that point to resources on a FHIR server. This is a pure client-side app that is configured to point to a FHIR endpoint. #### Configuration The Docker image can be configured using the following environment variables: * `HOTSPOT_FHIR_SERVER`: The FHIR endpoint used for retrieving requested FHIR resources. The path component of the URL is appended to this value upon each request, e.g. if your `HOTSPOT_FHIR_SERVER` was http://ontoserver.csiro.au/stu3-latest, then a request with the path `/CodeSystem/some-code-system` would retrieve the resource from http://ontoserver.csiro.au/stu3-latest/CodeSystem/some-code-system. Defaults to `https://ontoserver.csiro.au/stu3-latest`. * `HOTSPOT_PROXY_TARGET`: The FHIR endpoint used for proxying requests from the Docker container to the FHIR server. This may be different to `HOTSPOT_FHIR_SERVER` if the FHIR server is referred to by a different hostname when viewed from your Hotspot Docker container. * `HOTSPOT_FHIR_VERSION`: The version of FHIR (x.y.z) assumed to be in use by the FHIR server. Defaults to `3.0.1`. * `HOTSPOT_PATH_PREFIX`: A prefix to append to all routes within the Hotspot application (eg. `/someprefix/fhir/CodeSystem`). Defaults to `''`. Note that this does not affect requests from Hotspot to the FHIR server, these requests are controlled solely by the `HOTSPOT_FHIR_SERVER` variable. * `HOTSPOT_NARRATIVE_STYLES`: A URL to a custom stylesheet to override styles within narrative content. * `HOTSPOT_PATH_ROUTES`: Provides a means of specifying custom path routing rules (see [Path Routing](#path-routing)). ##### Example Docker Compose file ```yaml version: "3" services: polecat: image: hotspot ports: - "80:80" environment: HOTSPOT_FHIR_SERVER: https://ontoserver.csiro.au/stu3-latest HOTSPOT_FHIR_VERSION: 3.0.1 HOTSPOT_NARRATIVE_STYLES: /agency-narrative.css HOTSPOT_PATH_ROUTES: "[{ 'matchPattern': '.*', 'removeParams': [ '_format' ] }]" ``` ##### Example Docker Compose file, incorporating FHIR server (Ontoserver) This expands upon the [official Ontoserver Docker Compose example](http://ontoserver.csiro.au/docs). ```yaml version: '2' volumes: onto: driver: local pgdata: driver: local services: db: image: postgres volumes: - pgdata:/var/lib/postgresql/data ontoserver: image: aehrc/ontoserver:ctsa-5.1 container_name: ontoserver depends_on: - db expose: - "8080" environment: - authentication.oauth.endpoint.client_id.0=NCTS_ACCESS_CODE - authentication.oauth.endpoint.client_secret.0=NCTS_CLIENT_SECRET - JAVA_OPTS=-Xmx4G # Minimum # - JAVA_OPTS=-Xmx8G # Preferred volumes: - onto:/var/onto hotspot: image: hotspot ports: - '80:80' depends_on: - ontoserver environment: - HOTSPOT_FHIR_SERVER=http://somedomain.com/fhir - HOTSPOT_PROXY_TARGET=http://ontoserver:8080/fhir - HOTSPOT_PATH_PREFIX=/fhir - HOTSPOT_NARRATIVE_STYLES=/agency-narrative.css ``` ##### Path Routing Path routing rules can be used to disallow requests that would otherwise render Hotspot to be non-performant. For example, when receiving a request at `<FHIR_ENDPOINT>/CodeSystem` you may want to redirect the client to a URL that limits the amount of data that would otherwise be returned (--> `<FHIR_ENDPOINT>/CodeSystem?_elements=id,name,status`). Another common example would be to strip the `_format` parameter (eg. `<FHIR_ENDPOINT>/metadata?_format=xml` --> `<FHIR_ENDPOINT>/metadata`). When provided with a location, with a pathname that matches a rule in the pathRoute config, the corresponding rule is applied to the redirect URL. **NOTE:** `matchPattern` supports regular expressions. **Actions that can be applied to a match include:** * **addSuffix**: Append a suffix to the provided pathname (NOTE: it will add a slash between the existing path and suffix). * **removeParams**: If the provided query string contains a parameter listed in 'removeParams', it will be removed from the redirect query string. * **addParams**: If the provided query string does not contain the params defined in "addParams", they will be added to the redirect query string. A message can also be associated with each rule, which will be displayed on the page when the rule has been applied. An example of this is a message which informs the user that some of the information has been trimmed from the response. **To log re-route message:** * **id**: An key to uniquely identify each routing rule. * **message**: An informational message to be reported, after the client is re-routed. ##### Default configuration ``` { "fhirServer": "https://api.healthterminologies.gov.au/integration/v2/fhir", "fhirVersion": "3.0.1", "narrativeStyles": "/hotspot/agency-narrative.css", "pathPrefix": "/integration/v2/fhir", "pathRoutes": [ { "id": "00", "message": "The '_format' parameter has been removed from the provided URL. It is not supported via the browser representation of this terminology server.", "matchPattern": ".*", "removeParams": ["_format"] }, { "id": "01", "matchPattern": "/integration/v2/fhir[/]*$", "addSuffix": "metadata" }, { "id": "02", "message": "Please be aware that you are viewing a subset of this bundle. The 'concept' attribute has been deliberately excluded from this view. The full content of each resource can be viewed, via the 'Full Resource' button.", "matchPattern": "/CodeSystem[/]*$", "addParams": { "_elements": [ "resourceType", "id", "meta", "implicitRules", "language", "text", "contained", "extension", "modifierExtension", "url", "identifier", "version", "name", "title", "status", "experimental", "date", "publisher", "contact", "description", "useContext", "jurisdiction", "purpose", "copyright", "caseSensitive", "valueSet", "hierarchyMeaning", "compositional", "versionNeeded", "content", "count", "filter", "property" ], "_count": 100 } }, { "id": "03", "message": "Please be aware that you are viewing a subset of this bundle. The 'compose' attribute has been deliberately excluded from this view. The full content of each resource can be viewed, via the 'Full Resource' button.", "matchPattern": "/ValueSet[/]*$", "addParams": { "_elements": [ "resourceType", "id", "meta", "implicitRules", "language", "text", "contained", "extension", "modifierExtension", "url", "identifier", "version", "name", "title", "status", "experimental", "date", "publisher", "contact", "description", "useContext", "jurisdiction", "immutable", "purpose", "copyright", "extensible", "expansion" ], "_count": 100 } }, { "id": "04", "message": "Please be aware that you are viewing a subset of this bundle. The 'group' attribute has been deliberately excluded from this view. The full content of each resource can be viewed, via the 'Full Resource' button.", "matchPattern": "/ConceptMap[/]*$", "addParams": { "_elements": [ "resourceType", "id", "meta", "implicitRules", "language", "text", "contained", "extension", "modifierExtension", "url", "identifier", "version", "name", "title", "status", "experimental", "date", "publisher", "contact", "description", "useContext", "jurisdiction", "purpose", "copyright", "source", "target" ], "_count": 100 } } ] } ```
Python
UTF-8
3,224
2.953125
3
[]
no_license
from board import main def test_pawn_takes_pawn(): b = main.Board() b.add_piece('p', 'd4', is_white=True) b.add_piece('p', 'e5', is_white=False) moves = b.get_naive_moves(from_white=True) takes = [m for m in moves if m.is_take] assert len(moves) == 2 assert len(takes) == 1 moves_san = [m.to_string() for m in moves] assert 'd5' in moves_san assert 'dxe5' in moves_san def test_pawn_takes_pawns(): b = main.Board() b.add_piece('p', 'd4', is_white=True) b.add_piece('p', 'e5', is_white=False) b.add_piece('p', 'c5', is_white=False) moves = b.get_naive_moves(from_white=True) moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(takes) == 2 assert len(moves) == 3 assert 'd5' in moves_san assert 'dxe5' in moves_san assert 'dxc5' in moves_san def test_knight_takes_pawns(): b = main.Board() b.add_piece('n', 'd4', is_white=True) b.add_piece('p', 'e6', is_white=False) b.add_piece('p', 'c2', is_white=False) moves = b.get_naive_moves(from_white=True) moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(moves) == 8 assert len(takes) == 2 assert 'Nf5' in moves_san assert 'Nxe6' in moves_san assert 'Nxc2' in moves_san def test_rook_takes_pawn(): b = main.Board() b.add_piece('r', 'a1', is_white=True) b.add_piece('p', 'a8', is_white=False) moves = b.get_naive_moves(from_white=True) moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(moves) == 14 assert len(takes) == 1 assert 'Ra4' in moves_san assert 'Rxa8' in moves_san def test_bishop_takes_pawn(): b = main.Board() b.add_piece('b', 'a1', is_white=True) b.add_piece('p', 'b2', is_white=False) moves = b.get_naive_moves(from_white=True) moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(moves) == 1 assert len(takes) == 1 assert 'Bxb2' in moves_san def test_king_takes_pawns(): b = main.Board() b.add_piece('k', 'a1', is_white=True) b.add_piece('p', 'a2', is_white=False) b.add_piece('p', 'b1', is_white=False) b.add_piece('p', 'b2', is_white=False) moves = b.get_naive_moves(from_white=True) moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(moves) == 3 assert len(takes) == 3 assert 'Kxa2' in moves_san assert 'Kxb1' in moves_san assert 'Kxb2' in moves_san def test_queen_takes_pawns(): b = main.Board() b.add_piece('q', 'd4', is_white=True) b.add_piece('p', 'd5', is_white=False) b.add_piece('p', 'd3', is_white=False) b.add_piece('p', 'e3', is_white=False) b.add_piece('p', 'e4', is_white=False) b.add_piece('p', 'e5', is_white=False) b.add_piece('p', 'c3', is_white=False) b.add_piece('p', 'c4', is_white=False) b.add_piece('p', 'c5', is_white=False) moves = b.get_naive_moves(from_white=True) # moves_san = [m.to_string() for m in moves] takes = [m for m in moves if m.is_take] assert len(moves) == 8 assert len(takes) == 8
Java
UTF-8
6,565
1.515625
2
[]
no_license
package com.example.smlightwai; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.example.smlightwai.R; import com.example.smlightwai.shebei_page1.sblxThread; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import jiekou.Utils; import jiekou.appapi; public class shebeichaxunneirong extends Activity { TextView shebeileixing; TextView shebeilouceng; TextView gourushijian; TextView shenchanchangjia; TextView chengbaodanwei; TextView fuzerenyuan; TextView fuzerendianhua; TextView edingdianliu; TextView edingdianya; TextView edinggonglv; TextView zixitongmingcheng; TextView suozailouceng; TextView suozaiquyu; TextView gongchenbianma; String itemid; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch(msg.what) { case 0: try { String str = (String) msg.obj; JSONObject jsonObject = new JSONObject(str); //���������UI�������������ʾ�������� shebeileixing.setText(new JSONObject(jsonObject.getString("deviceType")).getString("name")); shebeilouceng.setText(new JSONObject(jsonObject.getString("ibsItemDTO")).getString("name")); gourushijian.setText(jsonObject.getString("buy_date")); shenchanchangjia.setText(jsonObject.getString("factory")); chengbaodanwei.setText(jsonObject.getString("contractorUnit")); fuzerenyuan.setText(jsonObject.getString("director")); fuzerendianhua.setText(jsonObject.getString("phone")); edingdianliu.setText(jsonObject.getString("rated_current")); edingdianya.setText(jsonObject.getString("rated_voltage")); edinggonglv.setText(jsonObject.getString("rated_power")); zixitongmingcheng.setText(new JSONObject(jsonObject.getString("ibsResourceDTO")).getString("name")); suozailouceng.setText(new JSONObject(jsonObject.getString("floorInfo")).getString("name")); suozaiquyu.setText(jsonObject.getString("area")); gongchenbianma.setText(jsonObject.getString("project_code")); itemid = jsonObject.getString("id"); } catch(JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.shebeichaxunneirong); shebeileixing = (TextView) this.findViewById(R.id.shebeileixingneirong); shebeilouceng = (TextView) this.findViewById(R.id.shebeiloucengneirong); gourushijian = (TextView) this.findViewById(R.id.gourushijianneirong); shenchanchangjia = (TextView) this.findViewById(R.id.shenchanchangjia); chengbaodanwei = (TextView) this.findViewById(R.id.chengbaodanwei); fuzerenyuan = (TextView) this.findViewById(R.id.fuzerenyuanneirong); fuzerendianhua = (TextView) this.findViewById(R.id.fuzerendianhua); edinggonglv = (TextView) this.findViewById(R.id.edinggonglv); edingdianliu = (TextView) this.findViewById(R.id.edingdianliu); edingdianya = (TextView) this.findViewById(R.id.edingdianya); zixitongmingcheng = (TextView) this.findViewById(R.id.zixitongmingcheng); suozailouceng = (TextView) this.findViewById(R.id.suozailouceng); suozaiquyu = (TextView) this.findViewById(R.id.suozaiquyu); gongchenbianma = (TextView) this.findViewById(R.id.gongchenbianma); Button weibojihua = (Button) this.findViewById(R.id.weibojihua); ImageButton btn_fanhui = (ImageButton) this.findViewById(R.id.fanhuishebeichaun); btn_fanhui.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utils.isFastClick()) { //Intent��һ������ʱ�󶨣�run-time binding�����ƣ������ڳ������й���������������ͬ������� Intent intent = new Intent(shebeichaxunneirong.this, shebeilist.class); ////���� startActivity(intent); } } }); weibojihua.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utils.isFastClick()) { //Intent��һ������ʱ�󶨣�run-time binding�����ƣ������ڳ������й���������������ͬ������� new Thread(new shebeichaweibaolistThread()).start(); } } }); //�豸��ϸ��Ϣ Bundle bundle = this.getIntent().getExtras(); //����nameֵ String cxnr = bundle.getString("chaxunxiangxixinxi"); Message message = new Message(); message.what = 0; message.obj = cxnr.toString(); handler.sendMessage(message); } class shebeichaweibaolistThread extends Thread { public void run() { try { //post���� URL url = new URL("http://222.178.109.129:9082/ibs/api/maintainPlan/getMaintainPlanByItemId/" + "68792"); Map<String, Object> params = new LinkedHashMap<String, Object>(); String resStr = appapi.getWebServiceRes(params, url); Log.d("MainActivity", ">>>>>>>>>>>>>��" + resStr); Log.d("itemid", itemid); Intent intent = new Intent(shebeichaxunneirong.this, shebeichaweibaolist.class); Bundle bundle = new Bundle(); //����name����Ϊtinyphp bundle.putString("shebeichaweibaolist", resStr); intent.putExtras(bundle); startActivity(intent); } catch(MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Java
UTF-8
379
2.140625
2
[]
no_license
package Ticket; import ticketingsystem.Date; public class SolvedTicket { protected Date TimeTakenToBeSolved; public Date getTimeTakenToBeSolved() { return TimeTakenToBeSolved; } public void setTimeTakenToBeSolved(Date TimeTakenToBeSolved) { this.TimeTakenToBeSolved = TimeTakenToBeSolved; } public void SolvedTickets(){ } }
Markdown
UTF-8
1,188
2.734375
3
[]
no_license
## Table of content * [General info](#general-info) * [Technologies](#technologies) * [Setup](#setup) * [To-Do](#to-do) * [Images](#images) ## General info Simple script which gathers a few informations (Windows version, host name, IP and MAC adress) and saves into the .xlsx file (Excel format). ## Technologies ``` Everything in "requirements.txt": DOWNLOAD -> RUN "pip install -r requirements.txt" -> PROFIT ``` - Python (of course), - pandas, - openpyxl, - xlrd, - re, - subprocess, - getmac. ## Setup Everything you need to do is download the newest version of the <a href="https://github.com/bartosz-sporek/audit-script/releases">audit.rar</a>, extract it and open audit.exe file! The result will be saved in audit.xlsx file. ## To-Do - [x] Add MAC gathering with adapters menu choose - [x] Shrink setup - python and dependencies to .exe file - [x] Before gather info generate Excel file with headers (Windows Version, Host Name, IP Adress, MAC Adress) - [ ] Add Windows key gathering - [ ] Add auto-adjusting cell width - [ ] Fix error causing getting always first IP from ipconfig ## Images ![cmd](https://i.imgur.com/emkb52p.jpeg) ![Excel](https://i.imgur.com/zpRBZSc.jpeg)
C++
GB18030
14,294
2.828125
3
[]
no_license
#ifndef __LIDARBASETOOLS__ #define __LIDARBASETOOLS__ #include <iostream> #include <deque> #include <vector> #include <string> #include <fstream> #include <iomanip> namespace LiDARBaseTools{ const float NODATA = -999.99; const float eps = 0.001; struct LasPoint{ float x; float y; float z; short classification; short intensity; }; struct GrideIndex// { std::vector<int> ptIndex; }; bool readTXTPointData(const char* filename,std::vector<LasPoint>& inputCloud) /* todo: read txt point data to a LasPoint vector date: 2015.3.8 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin reading..."<<std::endl; std::fstream infile; infile.open(filename); if (infile.fail()) { std::cout<<"bad file name"<<std::endl; return false; } int nCount(0); char temp[256]; LasPoint tempLasPoint; float x(0),y(0),z(0); while (!infile.eof()) { nCount++; infile.getline(temp,256); //std::cout<<temp<<std::endl; std::sscanf(temp,"%f %f %f",&x,&y,&z); tempLasPoint.x = x; tempLasPoint.y = y; tempLasPoint.z = z; inputCloud.push_back(tempLasPoint); } infile.close(); std::cout<<"have read "<<nCount<<" points.\nDone."<<std::endl; return true; } bool writeTXTPointData(const char* filename,const std::vector<LasPoint> &outputCloud) /* todo: write point data of txt formate from a point cloud vector out: date: 2015.3.9 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin to write..."<<std::endl; std::ofstream outfile; outfile.open(filename); if (outfile.fail()) { std::cout<<"bad filename"<<std::endl; return false; } for (std::vector<LasPoint>::const_iterator it = outputCloud.begin();it!=outputCloud.end();++it) { //outfile.setprecision(2); //std::setprecision(2); outfile<<std::setprecision(2)<<std::fixed<<it->x<<" "<<it->y<<" "<<it->z<<"\n"; } outfile.close(); std::cout<<"have write "<<outputCloud.size()<<" points.\nDone."<<std::endl; return true; } bool writeTXTPointData(const char* filename,const std::vector<LasPoint> &outputCloud , const std::vector<int> &index) { std::cout<<"begin to write..."<<std::endl; std::ofstream outfile; outfile.open(filename); if (outfile.fail()) { std::cout<<"bad filename"<<std::endl; return false; } const LasPoint *ptempLasPoint; int count = 0; for (std::vector<int>::const_iterator it = index.begin() ; it != index.end() ; it++ ) { ptempLasPoint = &outputCloud[*it]; outfile<<std::setprecision(2)<<std::fixed<<ptempLasPoint->x<<" "<<ptempLasPoint->y<<" "<<ptempLasPoint->z<<"\n"; count++; } outfile.close(); std::cout<<"have write "<<count<<" points.\nDone."<<std::endl; return true; } bool createGride(const std::vector<LasPoint> &inputCloud, int &ncols,int &nrows, float &maxx,float &minx,float &maxy,float &miny,float &maxz,float &minz, const float cellsize, GrideIndex* &pGrideIndex) /* todo: create a gride of a point cloud out: size and range of the gride date: 2015.3.8 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin create gride..."<<std::endl; maxx = inputCloud[0].x; maxy = inputCloud[0].y; maxz = inputCloud[0].z; minx = inputCloud[0].x; miny = inputCloud[0].y; minz = inputCloud[0].z; for ( std::vector<LasPoint>::const_iterator it = inputCloud.begin(); it != inputCloud.end(); ++it) { if (it->x > maxx) { maxx = it->x; } if (it->x < minx) { minx = it->x; } if (it->y > maxy) { maxy = it->y; } if (it->y < miny) { miny = it->y; } if (it->z > maxz) { maxz = it->z; } if (it->z < minz) { minz = it->z; } } ncols = (maxx - minx)/cellsize + 1; nrows = (maxy - miny)/cellsize + 1; pGrideIndex = new GrideIndex[ncols*nrows]; int nCount = 0; for ( std::vector<LasPoint>::const_iterator it = inputCloud.begin(); it != inputCloud.end(); ++it) { int tempCol,tempRow; tempCol = (it->x - minx)/cellsize; tempRow = (it->y - miny)/cellsize; pGrideIndex[tempCol + tempRow*ncols].ptIndex.push_back(nCount); nCount++; } std::cout<<"have created a "<<nrows<<" * "<<ncols<<" gride.\nDone."<<std::endl; return true; } bool raster2asc(const char* filename, const float *rasterData, const int nrows, const int ncols, const float xllcorner,const float yllcorner, const float cellsize) /* todo: write raster data to a asc file date: 2015.3.9 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin to write asc file..."<<std::endl; std::ofstream outfile; outfile.open(filename); if (outfile.fail()) { std::cout<<"bad filename"<<std::endl; } outfile<<"ncols "<<ncols<<"\n"; outfile<<"nrows "<<nrows<<"\n"; outfile<<"xllcorner "<<xllcorner<<"\n"; outfile<<"yllcorner "<<yllcorner<<"\n"; outfile<<"cellsize "<<cellsize<<"\n"; outfile<<"NODATA_value "<<-9999<<"\n"; for (int i = nrows-1 ; i >= 0 ; i-- ) { for (int j = 0 ; j < ncols ; j++ ) { outfile<<std::setprecision(2)<<std::fixed<<rasterData[i*ncols+j]<<" "; } outfile<<"\n"; } std::cout<<"have written asc file.\nDone."<<std::endl; return true; } float getMinZvalueofRasterCell(const LiDARBaseTools::GrideIndex* pGrideIndex, const int nrows,const int ncols, const std::vector<LiDARBaseTools::LasPoint> &inputCloud, const int i ,const int j) /* todo: get mini Z value of points in a Raster cell date: 2015.3.9 author: JianPing(lijianping@whu.edu.cn) see: */ { float minZ = inputCloud[pGrideIndex[i*ncols+j].ptIndex[0]].z; float tempZ; for (std::vector<int>::const_iterator it = pGrideIndex[i*ncols+j].ptIndex.begin(); it!=pGrideIndex[i*ncols+j].ptIndex.end();++it) { tempZ = inputCloud[*it].z; if (minZ>tempZ) { minZ = tempZ; } } return minZ; } bool CreateBreakCluster(const float *rasterData, const int nrows, const int ncols, std::vector<std::vector<int>> &cluster_result) /* todo: cluster nodata areas in a raster date: 2015.3.10 author: JianPing(lijianping@whu.edu.cn) see: */ { bool* breakMask = new bool[nrows*ncols]; for (int i=0;i<nrows*ncols;i++) { breakMask[i] = false; } //ҵݸ for (int i=0;i<nrows;i++) { for (int j=0;j<ncols;j++) { if (std::fabs((rasterData[i*ncols+j] - NODATA)) < eps ) { breakMask[i*ncols+j] = true; } } } //о bool* breakMaskCopy = new bool[nrows*ncols]; for (int i=0;i<nrows*ncols;i++ ) { breakMaskCopy[i] = false; } std::deque<int> seed_x;// std::deque<int> seed_y;// //ռݸ for (int i=0;i<nrows;i++) { for (int j=0;j<ncols;j++) { if (breakMask[i*ncols+j]) { seed_x.push_back(j); seed_y.push_back(i); } } } std::vector<int> tempCluster; std::deque<int> tempseed_x; std::deque<int> tempseed_y;//ǰ while (seed_x.size()>0) { int x_num,y_num; x_num = seed_x.front(); y_num = seed_y.front(); //жϵǰǷѾ if (breakMaskCopy[y_num*ncols+x_num]) { seed_x.pop_front(); seed_y.pop_front(); continue; } else { seed_x.pop_front(); seed_y.pop_front(); } tempseed_x.push_back(x_num); tempseed_y.push_back(y_num); tempCluster.push_back(y_num*ncols+x_num); breakMaskCopy[y_num*ncols+x_num] = true;//õǰѾ while (tempseed_x.size()>0) { x_num = tempseed_x.front(); tempseed_x.pop_front(); y_num = tempseed_y.front(); tempseed_y.pop_front(); for (int i=y_num-1;i<=y_num+1;i++)//8 { if (i<0||i>=nrows) continue; for (int j=x_num-1;j<=x_num+1;j++) { if(j<0||j>=ncols) continue; if (breakMaskCopy[i*ncols+j]) continue; if (breakMask[i*ncols+j]) { tempseed_x.push_back(j); tempseed_y.push_back(i); tempCluster.push_back(i*ncols+j); breakMaskCopy[i*ncols+j] = true; } } } } cluster_result.push_back(tempCluster); tempCluster.clear(); } seed_x.clear(); seed_y.clear(); delete[] breakMaskCopy; delete[] breakMask; return true; } bool Ruster(std::vector<std::vector<int>> &cluster_raster, std::vector<std::vector<int>> &rust_raster, std::vector<std::vector<int>> &boundary_raster, const int nrows,const int ncols) { bool* RustMask = new bool[ncols*nrows];//Ĥ¼ʴ std::vector<int> temp_cluster;//ǰʴ for(int i = 0;i<ncols*nrows;i++) { RustMask[i] = false; } for(int i= 0;i<cluster_raster.size();i++)//ҵʴ㣬¼Ĥ { temp_cluster = cluster_raster[i]; for(int j = 0;j<temp_cluster.size();j++) { RustMask[temp_cluster[j]] = true; } temp_cluster.clear(); } std::vector<int> temp_rust_raster;//ǰʴ std::vector<int> temp_boundary_raster;//ǰʴ߽ for(int i= 0;i<cluster_raster.size();i++)//ʴ { temp_cluster = cluster_raster[i];//ǰʴ for(int j = 0;j<temp_cluster.size();j++) { int num_row,num_col; num_row = temp_cluster[j]/ncols; num_col = temp_cluster[j]%ncols; bool flag = true; for(int ii = num_row-1;ii<=num_row+1;ii++)// { if(ii<0||ii>=nrows) continue; for(int jj = num_col-1;jj<=num_col+1;jj++) { if(jj<0||jj>=ncols) continue; if(!RustMask[ii*ncols+jj]) { flag = false; break; } } if(!flag) { break; } } if(flag) { temp_rust_raster.push_back(num_row*ncols+num_col); } else { temp_boundary_raster.push_back(num_row*ncols+num_col); } } if(temp_rust_raster.size()) rust_raster.push_back(temp_rust_raster); if(temp_boundary_raster.size()) boundary_raster.push_back(temp_boundary_raster); temp_cluster.clear(); temp_rust_raster.clear(); temp_boundary_raster.clear(); } delete[] RustMask; return true; } inline float getAverageValueof3x3RasterWindow(const float *rasterData,const int nrows,const int ncols, const int row, const int col) /* todo: transform grideIndex to a raster date: 2015.3.10 author: JianPing(lijianping@whu.edu.cn) see: */ { float sum = 0; int count = 0; for (int i = row-1 ; i<=row+1 ; i++) { if (i<0 || i>=nrows) { continue; } for (int j = col-1 ; j<= col+1 ; j++) { if (j<0 || j>=ncols) { continue; } if (std::fabs(rasterData[j+i*ncols]-NODATA)<eps) { continue; } sum += rasterData[j+i*ncols]; count++; } } return sum/count; } bool grideIndex2raster(const std::vector<LasPoint> &inputCloud, const GrideIndex* pGrideIndex, const int nrows,const int ncols, float *&rasterData) /* todo: transform grideIndex to a raster date: 2015.3.10 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin to transform gride to a raster..."<<std::endl; rasterData = new float[nrows*ncols]; for (int i = 0 ; i< ncols*nrows ; ++i) { rasterData[i] = NODATA;//init } const std::vector<int> *ptempIndex; for (int i = 0 ; i < nrows ; ++i)//init the raster with the lowest value of the cell { for (int j = 0 ; j < ncols ; ++j) { ptempIndex = &(pGrideIndex[j+i*ncols].ptIndex); if(0 == ptempIndex->size()) { rasterData[j+i*ncols] = NODATA; } else { rasterData[j+i*ncols] = getMinZvalueofRasterCell(pGrideIndex, nrows,ncols,inputCloud,i,j); } } } //cluster nodata value std::vector<std::vector<int>> cluster_result;//restore the index set of nodata value in the raw raster CreateBreakCluster(rasterData,nrows,ncols,cluster_result); //Ruster std::vector<std::vector<int>> rust_begin,rust_result,rust_boundary; rust_result = cluster_result; while(rust_result.size()) { rust_begin = rust_result; rust_result.clear(); rust_boundary.clear(); Ruster(rust_begin,rust_result,rust_boundary,nrows,ncols); int row,col; for (std::vector<std::vector<int>>::iterator it_i = rust_boundary.begin() ; it_i!=rust_boundary.end();++it_i) { for (std::vector<int>::iterator it_j = it_i->begin(); it_j!=it_i->end();++it_j) { row = (*it_j)/ncols; col = (*it_j)-row*ncols; rasterData[*it_j] = getAverageValueof3x3RasterWindow(rasterData,nrows,ncols,row,col); } } /*for(int i = 0;i<rust_boundary.size();i++) { for(int j = 0;j<rust_boundary[i].size();j++) { IDW_Interpolate_break(rust_boundary[i][j],this->radius); } }*/ } std::cout<<"transform raster success!\nDone."<<std::endl; return true; } bool lidarRaster2demRaster(const float *raster,const int nrows,const int ncols, const int *flag, float *&demraster) /* todo: transform the lidar measurements to dem raster according to the flag(0-nonground points) date: 2015.3.12 author: JianPing(lijianping@whu.edu.cn) see: */ { std::cout<<"begin to create dem..."<<std::endl; demraster = new float[nrows*ncols]; for (int i = 0 ; i < nrows*ncols ; i++) { if (flag[i]>0) { demraster[i] = NODATA; } else { demraster[i] = raster[i]; } } //cluster nodata value std::vector<std::vector<int>> cluster_result;//restore the index set of nodata value in the raw raster CreateBreakCluster(demraster,nrows,ncols,cluster_result); //Ruster std::vector<std::vector<int>> rust_begin,rust_result,rust_boundary; rust_result = cluster_result; while(rust_result.size()) { rust_begin = rust_result; rust_result.clear(); rust_boundary.clear(); Ruster(rust_begin,rust_result,rust_boundary,nrows,ncols); int row,col; for (std::vector<std::vector<int>>::iterator it_i = rust_boundary.begin() ; it_i!=rust_boundary.end();++it_i) { for (std::vector<int>::iterator it_j = it_i->begin(); it_j!=it_i->end();++it_j) { row = (*it_j)/ncols; col = (*it_j)-row*ncols; demraster[*it_j] = getAverageValueof3x3RasterWindow(demraster,nrows,ncols,row,col); } } } std::cout<<"have created dem.\n"<<std::endl; return true; } } #endif
Java
WINDOWS-1252
1,145
2.71875
3
[]
no_license
package org.crazyit.app.oneNentityId; import java.util.Date; import org.crazyit.app.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; /** * Description: * <br/>վ: <a href="http://www.crazyit.org">Java</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class OrderManager { public static void main(String[] args) { OrderManager mgr = new OrderManager(); mgr.createAndStoreOrder(); HibernateUtil.sessionFactory.close(); } private void createAndStoreOrder() { Session sess = HibernateUtil.currentSession(); Transaction tx = sess.beginTransaction(); Order order = new Order(new Date()); Product p1 = new Product(""); Product p2 = new Product("ʾ"); OrderItem item1 = new OrderItem(order , p1 , 50); OrderItem item2 = new OrderItem(order , p2 , 18); sess.save(order); sess.save(p1); sess.save(p2); sess.save(item1); sess.save(item2); tx.commit(); HibernateUtil.closeSession(); } }
PHP
UTF-8
682
2.765625
3
[ "MIT" ]
permissive
<?php //--> namespace Journal\Repositories\Tag; /** * Interface TagRepositoryInterface * @package Journal\Repositories\Tag */ interface TagRepositoryInterface { /** * @param $tag * @return \Journal\Tag */ public function create($tag); /** * @return \Journal\Tag */ public function all(); /** * @param $id * @return \Journal\Tag */ public function findById($id); /** * @param $slug * @return \Journal\Tag */ public function findBySlug($slug); /** * @param $id * @param $numberOfPosts * @return \Journal\Post */ public function getPosts($id, $numberOfPosts); }
Java
UTF-8
9,775
2.109375
2
[]
no_license
package im.goody.android.screens.main; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import java.util.List; import im.goody.android.BR; import im.goody.android.R; import im.goody.android.data.dto.Deal; import im.goody.android.data.dto.Location; import im.goody.android.data.network.res.EventStateRes; import im.goody.android.data.network.res.ParticipateRes; import im.goody.android.databinding.ItemEventBinding; import im.goody.android.databinding.ItemPostBinding; import im.goody.android.screens.main.MainItemMenu.ChangeState; import im.goody.android.utils.NetUtils; import im.goody.android.utils.TextUtils; import io.reactivex.Observable; import okhttp3.ResponseBody; @SuppressWarnings("WeakerAccess") class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainHolder> { private static final int TYPE_POST = R.layout.item_post; private static final int TYPE_EVENT = R.layout.item_event; private List<MainItemViewModel> data; private MainItemHandler handler; MainAdapter(List<MainItemViewModel> data, MainItemHandler handler) { this.data = data; this.handler = handler; } @Override public MainHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); ViewDataBinding binding = DataBindingUtil.inflate(inflater, viewType, parent, false); return new MainHolder(binding); } @Override public void onBindViewHolder(MainHolder holder, int position) { holder.bind(data.get(position)); } @Override public int getItemCount() { if (data == null) return 0; return data.size(); } @Override public int getItemViewType(int position) { return data.get(position).getDeal().getEvent() == null ? TYPE_POST : TYPE_EVENT; } void addData(List<MainItemViewModel> items) { int size = getItemCount(); data.addAll(items); notifyItemRangeInserted(size, items.size()); } void removeItem(MainItemViewModel viewModel) { int position = data.indexOf(viewModel); data.remove(viewModel); notifyItemRemoved(position); } interface MainItemHandler { void report(long id); void showDetail(long id); void share(String text); void openMap(Location location); void openProfile(long id); Observable<Deal> like(long id); Observable<ParticipateRes> changeParticipateState(long id); Observable<EventStateRes> changeEventState(long id); void showEdit(Deal deal); void openPhoto(String imageUrl); Observable<ResponseBody> deletePost(long id); } class MainHolder extends RecyclerView.ViewHolder { private ViewDataBinding binding; MainHolder(ViewDataBinding binding) { super(binding.getRoot()); this.binding = binding; } void bind(MainItemViewModel model) { binding.setVariable(BR.viewModel, model); binding.executePendingBindings(); if (getItemViewType() == TYPE_POST) { bindPost(model); } else { bindEvent(model); } } private void bindEvent(MainItemViewModel viewModel) { Deal deal = viewModel.getDeal(); ItemEventBinding eventBinding = (ItemEventBinding) binding; eventBinding.itemEventContainer .setOnClickListener(v -> handler.showDetail(deal.getId())); eventBinding.actionPanel.panelItemComments .setOnClickListener(v -> handler.showDetail(deal.getId())); eventBinding.itemEventTitle.setOnClickListener(v -> handler.showDetail(deal.getId())); eventBinding.actionPanel.panelItemShare.setOnClickListener(v -> { String text = TextUtils.buildShareText(deal); handler.share(text); }); eventBinding.itemEventMenu.setOnClickListener(v -> { ChangeState changeState; if (!deal.isOwner()) { changeState = ChangeState.HIDDEN; } else if (deal.getEvent().isActive()) { changeState = ChangeState.CLOSE; } else { changeState = ChangeState.OPEN; } MainItemMenu menu = new MainItemMenu.Builder() .setChangeState(changeState) .setShowEdit(deal.isOwner()) .setShowDelete(deal.isOwner()) .build(); menu.show(v).subscribe(id -> { switch (id) { case R.id.action_report: handler.report(deal.getId()); break; case R.id.action_change_event_state: handler.changeEventState(deal.getId()) .subscribe(viewModel::changeEventState, Throwable::printStackTrace); break; case R.id.action_edit_post: handler.showEdit(deal); break; case R.id.action_delete_post: handler.deletePost(deal.getId()) .subscribe(response -> removeItem(viewModel), Throwable::printStackTrace); } }); }); eventBinding.itemEventLocation .setOnClickListener(v -> handler.openMap(deal.getLocation())); eventBinding.actionPanel.panelLikeContainer.setOnClickListener(v -> handler.like(deal.getId()).subscribe(response -> { viewModel.panelViewModel.isLiked.set(response.isLiked()); viewModel.panelViewModel.likedCount.set(response.getLikesCount()); }, Throwable::printStackTrace)); eventBinding.itemEventJoin.setOnClickListener(v -> handler.changeParticipateState(deal.getId()) .subscribe( response -> { viewModel.participates.set(response.isParticipates()); if (response.isParticipates()) { handler.showDetail(viewModel.getDeal().getId()); } }, Throwable::printStackTrace)); eventBinding.itemEventAvatar.setOnClickListener(v -> handler.openProfile(deal.getAuthor().getId())); eventBinding.itemEventImage.setOnClickListener(v -> handler.openPhoto(NetUtils.buildDealImageUrl(deal))); } private void bindPost(MainItemViewModel viewModel) { Deal deal = viewModel.getDeal(); ItemPostBinding postBinding = (ItemPostBinding) binding; postBinding.newsItemContainer .setOnClickListener(v -> handler.showDetail(deal.getId())); postBinding.actionPanel.panelItemComments .setOnClickListener(v -> handler.showDetail(deal.getId())); postBinding.actionPanel.panelItemShare.setOnClickListener(v -> { String text = TextUtils.buildShareText(deal); handler.share(text); }); postBinding.newItemMenu.setOnClickListener(v -> { MainItemMenu menu = new MainItemMenu.Builder() .setChangeState(ChangeState.HIDDEN) .setShowEdit(deal.isOwner()) .setShowDelete(deal.isOwner()) .build(); menu.show(v).subscribe(id -> { switch (id) { case R.id.action_report: handler.report(deal.getId()); break; case R.id.action_edit_post: handler.showEdit(deal); break; case R.id.action_delete_post: handler.deletePost(deal.getId()) .subscribe(response -> removeItem(viewModel), Throwable::printStackTrace); } }); }); postBinding.newsItemLocation .setOnClickListener(v -> handler.openMap(deal.getLocation())); postBinding.actionPanel.panelLikeContainer.setOnClickListener(v -> handler.like(deal.getId()).subscribe(response -> { viewModel.panelViewModel.isLiked.set(response.isLiked()); viewModel.panelViewModel.likedCount.set(response.getLikesCount()); }, Throwable::printStackTrace)); postBinding.newsItemUserAvatar.setOnClickListener(v -> handler.openProfile(deal.getAuthor().getId())); postBinding.newsItemImage.setOnClickListener(v -> handler.openPhoto(NetUtils.buildDealImageUrl(deal))); } } }
Python
UTF-8
873
2.90625
3
[]
no_license
# pip install openpyxl import openpyxl from openpyxl.styles import Font print(openpyxl.__version__) # wb = openpyxl.load_workbook("wb.xlsx") wb = openpyxl.Workbook() print(type(wb)) # sheet = wb.create_sheet("Sheet1") sheet = wb.active sheet.cell(row=1, column=1).value = 22 sheet.cell(row=1, column=2).value = "ChenMignxuan" sheet.cell(row=2, column=1).value = 99 sheet.cell(row=2, column=2).value = "Renj" sheet.cell(row=3, column=1).value = '=SUM(A1:A2)' print("max_row:", sheet.max_row, "max_column:", sheet.max_column) sheet.column_dimensions["A"].width = 20 sheet.column_dimensions["B"].width = 40 sheet.row_dimensions[1].height = 30 sheet["A1"].font = Font(sz=14, bold=True, italic=True) sheet.cell(1, 2).font = Font(sz=14, bold=True) print("max_row:", sheet.max_row, "max_column:", sheet.max_column) wb.save("wb.xlsx")
JavaScript
UTF-8
439
3.9375
4
[]
no_license
function countStringOccurences(text, word) { let count = 0; let matcher = ` ${word} `; let index = text.indexOf(matcher); while (index !== -1) { index = text.indexOf(matcher, index + 1); count++; } if (text.startsWith(word)) { count++ } if(text.endsWith(word)) { count++ } console.log(count); } countStringOccurences("This is a word and it also is a sentence", "is");
Java
UTF-8
4,163
2.359375
2
[]
no_license
package com.example.bookapp.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Cache; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import java.io.Serializable; import java.util.HashSet; import java.util.Objects; import java.util.Set; @Entity @Table(name = "administration_action") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Action implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "url") private String url; @Column(name = "method") private String method; @Column(name = "section") private String section; @JsonIgnore @ManyToMany(mappedBy = "actions", cascade = CascadeType.MERGE) private Set<Group> groups = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Action name(String name) { this.name = name; return this; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Action description(String description) { this.description = description; return this; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Action url(String url) { this.url = url; return this; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Action method(String method) { this.method = method; return this; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public Action section(String section) { this.section = section; return this; } public Set<Group> getGroups() { return groups; } public void setGroups(Set<Group> groups) { groups.forEach(this::addGroup); } public Action groups(Set<Group> groups) { groups.forEach(this::addGroup); return this; } public void addGroup(Group group) { groups.add(group); group.getActions().add(this); } public void removeGroup(Group group) { groups.remove(group); group.getActions().remove(this); } public void removeGroups() { new HashSet<>(groups).forEach(this::removeGroup); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Action action = (Action) o; if (action.id == null || id == null) { return false; } return Objects.equals(id, action.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Action{" + "id=" + id + ", name='" + name + "'" + ", description='" + description + "'" + ", url='" + url + "'" + ", method='" + method + "'" + ", section='" + section + "'" + '}'; } }
JavaScript
UTF-8
1,588
2.765625
3
[]
no_license
const mongoose = require('mongoose'); mongoose.connect( 'mongodb://54.219.128.69/SDC', { useNewUrlParser: true, useUnifiedTopology: true } ); const listingSchema = mongoose.Schema({ listingId: Number, price: Number, address: { street: String, city: String, state: String, zip: Number }, tags: { new: Boolean, sale: Boolean, sold: Boolean, construction: Boolean, }, images: [String] }); const ListingModel = mongoose.model('Listing', listingSchema); // METHODS HERE --- module.exports = { fetchOne: (num, callback) => { ListingModel.find({listingId:num}, callback) }, insertOne: (listing, callback) => { ListingModel.create(listing, (err) => { if (err) { console.log(err); } callback() }) } } // ---------------- module.exports.ListingModel = ListingModel; // necessary? // mongo stores as json // import from csv to mongo using method // csv need field headers // headers are keys // lines are values // how to handle nested? // UPDATED PLAN // creating csv // generate random data Subfunction // stringify arrays and objects // create obj stringify then save to csv // concat to one string // append long string to file // edge cases, arrays objects // importing to mongo, (doesn't scale well) // splitting entire file into array of lines // iterating over the lines array // assigning each index to values of and object // insert that object into mongo collection // import csv to mongo // parse string to array and object with json parse
Java
UTF-8
318
2.921875
3
[]
no_license
package java8.functionalinterface; interface sayable1{ void say(String msg); // abstract method } @FunctionalInterface interface Doable extends sayable1{ // Invalid '@FunctionalInterface' annotation; Doable is not a functional interface // void doIt(); //remove this comment. it shows error }
C#
UTF-8
1,358
3.6875
4
[]
no_license
using System; namespace Lesson_01_3EmployeeTest { class Employee { public string name; public Employee(string name) { this.name = name; } public virtual void Mark() { Console.WriteLine("9点打卡,{0}",name); } } class HR : Employee { public string major; public HR(string name,string major):base(name) { this.major = major; } } class Manager:Employee { public Manager(string name) : base(name) { } public override void Mark() { Console.WriteLine("11点打卡,{0}",name); //base.Mark(); } } class Programer : Employee { public Programer (string name) : base(name) { } public override void Mark() { Console.WriteLine("程序员不用打卡,{0}",name); //base.Mark(); } } class Program { static void Main(string[] args) { Employee[] employees = new Employee[3]; employees[0] = new HR("HR",""); employees[1] = new Manager("M"); employees[2] = new Programer("P"); foreach (var item in employees) { item.Mark(); } } } }
C++
UTF-8
2,511
2.828125
3
[ "BSL-1.0", "Zlib", "MIT" ]
permissive
#include <algorithm> #include <iostream> #include "Pathfinding.h" #include "RoadNode.h" #include "MstNode.h" #include "V2.h" namespace Pathfinding { std::vector<RoadNode*> PathFind(std::vector<std::vector<RoadNode*>> grid, int startX, int startY, int endX, int endY, int offsetPerRoadNode) { // Start, End RoadNode* start = grid[startY][startX]; RoadNode* end = grid[endY][endX]; // Null checks if (start == nullptr || end == nullptr) { return std::vector<RoadNode*>(); } //// We need not pathfind if the road doesn't meet a threshold length //if (V2::DistanceBetween(*start->position, *end->position) < 500) //{ // std::vector<RoadNode*> path; // path.push_back(start); // path.push_back(end); // return path; //} // Q : the set of all nodes std::vector<RoadNode*> Q; for (auto vec : grid) { for (auto node : vec) { node->distance = FLT_MAX; node->parent = nullptr; Q.push_back(node); } } // The start has a distance of 0 start->distance = 0; start->checked = true; while (!Q.empty()) { //u is node in Q with the smallest distance... // Sort it std::sort(Q.begin(), Q.end(), [end](const RoadNode* lhs, const RoadNode *rhs) -> bool { return (lhs->distance + V2::Length(*lhs->position - *end->position) < (rhs->distance + V2::Length(*rhs->position - *end->position))); }); // Pick the front RoadNode* u = Q.front(); // Remove u from Q Q.erase(std::remove(Q.begin(), Q.end(), u), Q.end()); // For each neighbour of u for (RoadNode* neighbour : u->GetNeighbors(grid)) { //if (neighbour->checked) continue; // Skip non-walkables // if (!neighbour->isWalkable) continue; //neighbour->checked = true; auto alt = neighbour->GetCost() + V2::Length(*neighbour->position - *end->position); if (alt < neighbour->distance) { neighbour->distance = alt; neighbour->parent = u; if (neighbour->position->x == end->position->x && neighbour->position->y == end->position->y) { return ReconstructPath(neighbour); } } } } } std::vector<RoadNode*> ReconstructPath(RoadNode* goal) { std::vector<RoadNode*> road = std::vector<RoadNode*>(); int counter = 0; do { // std::cout << "Rebuilding path counter: " << counter++ << std::endl; road.push_back(goal); goal = goal->parent; } while (goal->parent != nullptr && goal != goal->parent->parent); road.push_back(goal); return road; } }
PHP
UTF-8
4,710
3.125
3
[]
no_license
<?php namespace lib; /** * Configuration representation * * @throws \DomainException|\LengthException * @package Moss Core * @author Michal Wachowski <wachowski.michal@gmail.com> */ class Config { protected $cache; protected $debug; protected $namespaces = array(); protected $components = array(); protected $routes = array(); protected $directories = array(); protected $locales = array(); protected $listeners = array(); /** * Constructor * * @param string $path path to configuration file */ public function __construct($path) { $this->readXML($path); } /** * Reads configuration from XML file * * @throws \DomainException|\LengthException * @param string $path path to XML file * @return Config */ public function readXML($path) { if(empty($path)) { throw new \LengthException('File path not set'); } if(!is_file($path)) { throw new \DomainException(sprintf('XML file (%s) not found!', $path)); } $xml = new \SimpleXMLElement(file_get_contents($path)); if(!isset($xml->cache, $xml->debug, $xml->namespaces, $xml->components, $xml->routes, $xml->directories, $xml->locales)) { throw new \DomainException(sprintf('Incorrect file format (missing nodes) in %s!', $path)); } $this->cache = (int) $xml->cache == 1 || (string) $xml->cache == 'true'; $this->debug = (int) $xml->debug == 1 || (string) $xml->debug == 'true'; $this->directories = (array) $xml->directories->children(); $this->components = (array) $xml->components->children(); $this->routes = (array) $xml->routes->children(); $this->locales = (array) $xml->locales->children(); $this->listeners = (array) $xml->listeners->children(); $nsxml = new \SimpleXMLElement(file_get_contents((string) $xml->namespaces)); foreach($nsxml as $namespace) { $this->namespaces[(string) $namespace->attributes()->namespace] = (string) $namespace->attributes()->path; }; return $this; } /** * Returns true if cache enabled * * @return bool */ public function isCacheMode() { return (bool) $this->cache; } /** * Returns true if debug enabled * * @return bool */ public function isDebugMode() { return (bool) $this->debug; } /** * Returns path to namespace * * @param string $namespaceName * @return string|bool */ public function getNamespace($namespaceName) { if(isset($this->namespaces[$namespaceName])) { return $this->namespaces[$namespaceName]; } return false; } /** * Returns all defined namespaces * * @return array */ public function getNamespaces() { return $this->namespaces; } /** * Returns path to component definitions in XML * * @param string $componentName component definitions identifier * @return string|bool */ public function getComponent($componentName) { if(isset($this->components[$componentName])) { return $this->components[$componentName]; } return false; } /** * Returns all defined component definitions paths * * @return array */ public function getComponents() { return $this->components; } /** * Returns path to route definitions in XML * * @param string $routeName route definitions identifier * @return array|bool */ public function getRoute($routeName) { if(isset($this->routes[$routeName])) { return $this->routes[$routeName]; } return false; } /** * Returns all defined routes definitions paths * * @return array */ public function getRoutes() { return $this->routes; } /** * Returns path to directory * * @param string $directory directory identifier * @return array|bool */ public function getDirectory($directory) { if(isset($this->directories[$directory])) { return $this->directories[$directory]; } return false; } /** * Returns all directory paths * * @return array */ public function getDirectories() { return $this->directories; } /** * Returns path to locale definitions * * @param string $locale locale identifier * @return array|bool */ public function getLocale($locale) { if(isset($this->locales[$locale])) { return $this->locales[$locale]; } return false; } /** * Returns all defined locale definition paths * * @return array */ public function getLocales() { return $this->locales; } /** * Returns path to listener definition * * @param string $listener definition identifier * @return array|bool */ public function getListener($listener) { if(isset($this->listeners[$listener])) { return $this->listeners[$listener]; } return false; } /** * Returns all listener definition paths * @return array */ public function getListeners() { return $this->listeners; } }
Java
UTF-8
1,659
1.890625
2
[ "MIT" ]
permissive
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package com.microsoft.azure.sdk.iot.android.helper; import com.microsoft.appcenter.espresso.Factory; import com.microsoft.appcenter.espresso.ReportHelper; import com.microsoft.azure.sdk.iot.common.helpers.BasicTierOnlyRule; import com.microsoft.azure.sdk.iot.common.helpers.ConditionalIgnoreRule; import org.junit.After; import org.junit.Rule; import org.junit.Test; // This class is to add a dummy test for every TestGroup. Currently, App Center errors out // when a TestGroup did not execute any actual tests. public class DummyAndroidRunner { @Rule public ReportHelper reportHelper = Factory.getReportHelper(); @After public void labelSnapshot() { reportHelper.label("Stopping App"); } @TestGroup1 @TestGroup2 @TestGroup3 @TestGroup4 @TestGroup5 @TestGroup6 @TestGroup7 @TestGroup8 @TestGroup9 @TestGroup10 @TestGroup11 @TestGroup12 @TestGroup13 @TestGroup14 @TestGroup15 @TestGroup16 @TestGroup17 @TestGroup18 @TestGroup19 @TestGroup20 @TestGroup21 @TestGroup22 @TestGroup23 @TestGroup24 @TestGroup25 @TestGroup26 @TestGroup27 @TestGroup28 @TestGroup29 @TestGroup30 @TestGroup31 @TestGroup32 @TestGroup33 @TestGroup34 @TestGroup35 @TestGroup36 @TestGroup37 @TestGroup38 @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BasicTierOnlyRule.class) public void dummyTest() { } }
Java
UTF-8
6,740
3.765625
4
[ "MIT" ]
permissive
package datastructures; /** * This class implements bilinear interpolation methods for 3d points and scalars. * * f(x,y) = f(0,0)(1-x)*(1-y) + f(1,0)*(1-x)*y + f(0,1)*x*(1-y) + f(1,1)*x*y * f(x,y) = [1-x, x] * [f(0,0) f(0,1); f(1,0) f(1,1)] * [1-y, y]' * * Reason of why do we multiply f0 by 1-x (instead of x): Given * o--------o---o * f0 x f1 * * then, the interpolated value of f(x) is * f0*(1-x) + f1. * Reason: the point x is further away from f0 than from f1, * Thus, the weight f0 has less impact on the result than the weight f1. * It's influence is in fact distance between the weights minus its location. * Which is for the normalized case 1-x. * This is why we apply (1-x) to f0. * */ public class Interpolator { /** * Compute bilinear interpolated value in a scalar field for a given query position. * * f(x,y) = f00*(1-dx)*(1-dy) + f10*(1-dx)*y + f01*x*(1-dy) + f11*dx*dy * where dx = x - floor(x) and dy = y - floor(y) * * @param data target flow direction values * @param x corresponds to row index * @param y corresponds to column index * @return interpolated flow value */ public double interpolatedValueAt(double[][] data, double x, double y) { int m = data.length; int n = data[0].length; // check for overflows if (x > m-1 || y > n-1) { throw new ArrayIndexOutOfBoundsException("Dimensions (m,n)=("+m+","+n+") but accessing (x,y)=("+x+","+y+")" ); } // assign lower interpolation value lookup coordinates int px_i = (int) Math.floor(x); int py_i = (int) Math.floor(y); // assign upper interpolation value lookup coordinates int px_i2 = px_i + 1; int py_i2 = py_i + 1; // compute interpolation weights double dx = x - px_i; double dy = y - py_i; // get interpolation values. double f_00 = data[px_i][py_i]; double f_01 = saveGetAt(data, px_i, py_i2); // data[px_i][py_i2]; double f_10 = saveGetAt(data, px_i2, py_i); // data[px_i2][py_i]; double f_11 = saveGetAt(data, px_i2, py_i2); // data[px_i2][py_i2]; // compute bilinear interpolated value double sum = 0d; sum += f_00*(1.0d-dx)*(1.0d-dy); sum += f_01*(1.0d-dx)*dy; sum += f_10*dx*(1.0d-dy); sum += f_11*dx*dy; return sum; } /** * Compute bilinear interpolated 3d point given a 2d array of 3d points for a given location. * * @param data matrix containing 3d points * @param x row idx * @param y column idx * @return bilinear interpolated 3d point */ public Point3d interpolatedValueAt(Point3d[][] data, double x, double y) { int m = data.length; int n = data[0].length; if (x > m-1 || y > n-1) { throw new ArrayIndexOutOfBoundsException("Dimensions (m,n)=("+m+","+n+") but accessing (x,y)=("+x+","+y+")" ); } int px_i = (int) Math.floor(x); int py_i = (int) Math.floor(y); int px_i2 = px_i + 1; int py_i2 = py_i + 1; double dx = x - px_i; double dy = y - py_i; Point3d f_00 = data[px_i][py_i]; Point3d f_01 = saveGetAt(data, px_i, py_i2); // data[px_i][py_i2]; Point3d f_10 = saveGetAt(data, px_i2, py_i); // data[px_i2][py_i]; Point3d f_11 = saveGetAt(data, px_i2, py_i2); // data[px_i2][py_i2]; double i_x = bilinearInterpolatedValue(f_00.x(), f_01.x(), f_10.x(), f_11.x(), dx, dy); double i_y = bilinearInterpolatedValue(f_00.y(), f_01.y(), f_10.y(), f_11.y(), dx, dy); double i_z = bilinearInterpolatedValue(f_00.z(), f_01.z(), f_10.z(), f_11.z(), dx, dy); return new Point3d(i_x, i_y, i_z); } /** * Apply the bilinear combination scheme. * * @param f_00 lookup value left top * @param f_01 lookup value right top * @param f_10 lookup value left bottom * @param f_11 lookup value right bottom * @param dx weight width * @param dy weight height * @return interpolated value */ private double bilinearInterpolatedValue(double f_00, double f_01, double f_10, double f_11, double dx, double dy) { double sum = 0d; sum += f_00*(1.0d-dx)*(1.0d-dy); sum += f_01*(1.0d-dx)*dy; sum += f_10*dx*(1.0d-dy); sum += f_11*dx*dy; return sum; } /** * Get the exact value at a given location (not interpolated). * In case we query for an in-existent location, then the value 0 is returned. * * @param data 2d array * @param idx row idx * @param idy column idx * @return value at given lookup positions. */ protected double saveGetAt(double[][] data, int idx, int idy) { int m = data.length; int n = data[0].length; if (idx == m || idy == n) { return 0d; } return data[idx][idy]; } /** * Get the exact 3d point at a given location (not interpolated). * In case we query for an in-existent location, then the zero point is returned. * * @param data 2d array * @param idx row idx * @param idy column idx * @return 3d point at given lookup positions. */ protected Point3d saveGetAt(Point3d[][] data, int idx, int idy) { int m = data.length; int n = data[0].length; if (idx == m || idy == n) { return new Point3d(0,0,0); } return data[idx][idy]; } /** * Checks whether a given interpolation point is equal to a given reference value. * * This method is used to check depth fields whether the exhibit invalid depth information * at a certain location (i.e. are equal the value 0). * * @param data 2d array * @param x row idx * @param y column idx * @param refValue reference value we want to check for. * @return true if any interpolation point is equal to the given reference value, * false otherwise. */ public boolean interpolAtEqVal(double[][] data, double x, double y, double refValue) { int px_i = (int) Math.floor(x); int py_i = (int) Math.floor(y); int px_i2 = px_i + 1; int py_i2 = py_i + 1; double f_00 = data[px_i][py_i]; double f_01 = saveGetAt(data, px_i, py_i2); // data[px_i][py_i2]; double f_10 = saveGetAt(data, px_i2, py_i); // data[px_i2][py_i]; double f_11 = saveGetAt(data, px_i2, py_i2); // data[px_i2][py_i2]; if (f_00 == refValue || f_01 == refValue || f_10 == refValue || f_11 == refValue) { return true; } return false; } }
PHP
UTF-8
10,488
2.8125
3
[]
no_license
<?php /** * Class for handling Do Not Loan actions * * @author Matthew Jump <matthew.jump@sellingsource.com> */ class Do_Not_Loan { /** * Database connection * * @var DB_Database_1 */ protected $db; /** * Holds information retrieved by Get_DNL_Info * * @var array */ protected $dnl_info; /** * Constructor for the Do_Not_Loan object * * @param DB_Database_1 $db * @return void */ public function __construct(DB_Database_1 $db) { $this->db = $db; } /** * Sets a do not loan flag for a company_id on SSN * * @param int $company_id * @param string $category * @param string $explanation * @param int $agent_id * @param string $ssn * @param string $other_reason * @return bool */ public function Set_Do_Not_Loan($company_id, $category, $explanation, $agent_id, $ssn, $other_reason) { $mod_dnlf_cat = ECash::getFactory()->getReferenceModel('doNotLoanFlagCategory'); $mod_dnlf_cat->loadBy(array('name' => $category)); $mod_dnlf = ECash::getFactory()->getModel('doNotLoanFlag'); $mod_dnlf->ssn = $ssn; $mod_dnlf->company_id = $company_id; $mod_dnlf->category_id = $mod_dnlf_cat->category_id; $mod_dnlf->other_reason = $other_reason; $mod_dnlf->explanation = $explanation; $mod_dnlf->active_status = 'active'; $mod_dnlf->agent_id = $agent_id; $mod_dnlf->date_created = time(); $mod_dnlf->date_modified = time(); $result = $mod_dnlf->save(); $this->clearDNLInfoCache(); return $result; } /** * Insert a do not loan flag override for company_id and SSN * * @param int $company_id * @param int $agent_id * @param int $ssn * @return bool */ public function Override_Do_Not_Loan($company_id, $agent_id, $ssn) { $mod_dnlf_over = ECash::getFactory()->getModel('doNotLoanFlagOverride'); $mod_dnlf_over->ssn = $ssn; $mod_dnlf_over->company_id = $company_id; $mod_dnlf_over->agent_id = $agent_id; $mod_dnlf_over->date_created = time(); $mod_dnlf_over->date_modified = time(); $result = $mod_dnlf_over->save(); $this->clearDNLInfoCache(); return $result; } /** * Checks if a DNL flag exists for an SSN for any company * * @param int $ssn * @return bool */ public function Does_SSN_In_Table($ssn) { $result = FALSE; $dnl_info = $this->Get_DNL_Info($ssn); $result = !empty($dnl_info); return $result; } /** * Checks if a DNL flag exists for an SSN for a company id * * @param int $ssn * @param int $company_id * @return bool */ public function Does_SSN_In_Table_For_Company($ssn, $company_id) { $result = FALSE; $dnl_info = $this->Get_DNL_Info($ssn); if (is_array($dnl_info)) { foreach ($dnl_info as $row) { if ($row->company_id == $company_id) { $result = TRUE; break; } } } return $result; } /** * Checks if a DNL flag exists for an SSN for company ids other than the specified * * @param int $ssn * @param int $company_id * @return bool */ public function Does_SSN_In_Table_For_Other_Company($ssn, $company_id) { $result = FALSE; $dnl_info = $this->Get_DNL_Info($ssn); if (is_array($dnl_info)) { foreach ($dnl_info as $row) { if ($row->company_id != $company_id) { $result = TRUE; break; } } } return $result; } /** * Checks if a DNL flag override exists for an SSN for a company * * @param int $ssn * @param int $company_id * @return bool */ public function Does_Override_Exists_For_Company($ssn, $company_id) { $result = FALSE; $overrides = ECash::getFactory()->getAppClient()->getDoNotLoanFlagOverrideAll($ssn); $overrides = isset($overrides->item) ? $overrides->item : array(); if (!is_array($overrides)) $overrides = array($overrides); $result = FALSE; if (!empty($overrides)) { foreach($overrides as $override) { if ($override->company_id == $company_id) { $result = TRUE; break; } } } return $result; } /** * Returns the Do Not Loan Flag information for the ssn * * @param string $ssn * @return array */ public function Get_DNL_Info($ssn) { if (isset($this->dnl_info[$ssn])) { $values = $this->dnl_info[$ssn]; } else { $dnlc_model = ECash::getFactory()->getReferenceModel("DoNotLoanFlagCategory"); $comp_model = ECash::getFactory()->getModel("Company"); $agent_model = ECash::getFactory()->getModel("Agent"); $as_values = ECash::getFactory()->getAppClient()->getDoNotLoanFlagAll($ssn); $as_values = isset($as_values->item) ? $as_values->item : $as_values; //if (!is_array($as_values)) $as_values = array($as_values); $values = array(); if (empty($as_values)) $as_values = array(); foreach ($as_values as $value) { if (!empty($value->active_status)) { $agt_loaded = $agent_model->loadBy(array('agent_id' => $value->modifying_agent_id)); $value->agent_id = $value->modifying_agent_id; $value->name_last = ($agt_loaded) ? $agent_model->name_last : 'Unknown'; $value->name_first = ($agt_loaded) ? $agent_model->name_first : 'Unknown'; $com_loaded = $comp_model->loadBy(array('company_id' => $value->company_id)); $value->company_name = ($com_loaded) ? $comp_model->name : NULL; $value->name_short = ($com_loaded) ? $comp_model->name_short : NULL; $value->name = $value->category; $value->active_status = ($value->active_status) ? 'active' : 'inactive'; $value->date_created = date('Y-m-d H:i:s',strtotime($value->date_created)); $value->date_modified = date('Y-m-d H:i:s',strtotime($value->date_modified)); $values[] = $value; } } $this->dnl_info[$ssn] = $values; } return $values; } /** * Clear (DELETE) all do not loan flags by ssn and company_id * * @param int $ssn * @return void */ public function clearDoNotLoan($ssn, $company_id) { $do_not_loan_model = ECash::getFactory()->getModel('DoNotLoanFlag'); if($do_not_loan_model->loadBy(array('ssn' => $snn, 'company_id' => $company_id))) { $do_not_loan_model->delete(); } ECash::getFactory()->getAppClient()->deleteDoNotLoanFlag($company_id, $ssn); $this->clearDNLInfoCache(); } /** * Set all do not loan flags to inactive * * @param int $ssn * @param int $company_id * @param int $agent_id * @return void */ public function Set_DNL_Inactive($ssn, $company_id, $agent_id) { $do_not_loan_model = ECash::getFactory()->getModel('DoNotLoanFlag'); if($do_not_loan_model->loadBy(array('ssn' => $snn, 'company_id' => $company_id, 'active_status' => 'active'))) { $do_not_loan_model->active_status = 'inactive'; $do_not_loan_model->agent_id = $agent_id; $do_not_loan_model->save(); } ECash::getFactory()->getAppClient()->deleteDoNotLoanFlag($company_id, $ssn); $this->clearDNLInfoCache(); } /** * Remove do not loan override flag by company id for an ssn * * @param int $ssn * @param int $company_id * @return bool */ public function Remove_Override_DNL($ssn, $company_id) { $result = TRUE; $mod_dnl_over = ECash::getFactory()->getModel('DoNotLoanFlagOverride'); if ($mod_dnl_over->loadBy(array('ssn' => $ssn, 'company_id' => $company_id))) { $result = $mod_dnl_over->delete(); } else { /** * It is remotely possible that DNL will not be loadable from ldb but still exist * inside of the app service. If that is the case loadBy will return false (the model * will not be deletable) and this call should take care of any lingering flags in the * app service. When this is exclusively app service this call will be all you need. */ ECash::getFactory()->getAppClient()->deleteDoNotLoanFlagOverride($company_id, $ssn); } $this->clearDNLInfoCache(); return $result; } /** * Clears any loaded DNL info so when it is read it must reload first * This should be done after every action that modifies this data in the DB if possible * * @return void */ protected function clearDNLInfoCache() { $this->dnl_info = NULL; } /** * Get available DNL categories from the ECash DB * * @return array */ public function Get_Category_Info() { $query = " SELECT name FROM do_not_loan_flag_category WHERE active_status='active' "; $st = $this->db->query($query); return $st->fetchAll(PDO::FETCH_OBJ); } public function Add_To_DNL_Audit($company_id, $ssn, $table_name, $column_name, $value_before, $value_after, $agent_id) { $do_not_loan_audit_model = ECash::getFactory()->getModel('DoNotLoanAudit'); $do_not_loan_audit_model->date_created = time(); $do_not_loan_audit_model->company_id = $company_id; $do_not_loan_audit_model->ssn = $ssn; $do_not_loan_audit_model->table_name = $table_name; $do_not_loan_audit_model->column_name = $column_name; $do_not_loan_audit_model->value_before = $value_before; $do_not_loan_audit_model->value_after = $value_after; $do_not_loan_audit_model->agent_id = $agent_id; return $do_not_loan_audit_model->save(); } public function Get_DNL_Audit_Log($ssn) { $agent_model = ECash::getFactory()->getModel("Agent"); $log_entries = ECash::getFactory()->getAppClient()->getDoNotLoanAudit($ssn); if(empty($log_entries)) return array(); foreach($log_entries as $entry) { if(empty($entry)) continue; $loaded = $agent_model->loadBy(array('agent_id' => $entry->modifying_agent_id)); $entry->date_created = date('Y-m-d H:i:s', strtotime($entry->date_created)); $entry->table_name = $entry->table_name; $entry->value_before = $entry->old_value; $entry->value_after = $entry->new_value; $entry->agent_id = $entry->modifying_agent_id; $entry->name_first = ($loaded) ? $agent_model->name_first : NULL; $entry->name_last = ($loaded) ? $agent_model->name_last : NULL; } return $log_entries; } /** * Get DNL override flag for ssn if it exists * * @param int $ssn * @return array */ public function Get_DNL_Override_Info($ssn) { $mod_company = ECash::getFactory()->getModel('Company'); $values = ECash::getFactory()->getAppClient()->getDoNotLoanFlagOverrideAll($ssn); $values = isset($values->item) ? $values->item : array(); if (!is_array($values)) $values = array($values); $results = array(); if (!empty($values)) { foreach($values as $value) { $mod_company->loadBy(array('company_id'=>$value->company_id)); $result->name_short = $mod_company->name_short; $result->name = $mod_company->name; $results[] = $result; } } return $results; } } ?>
Python
UTF-8
788
2.75
3
[]
no_license
import numpy as np import pandas as pd l= np.random.randint(low=0,high=10,size=(5,5)) df1=pd.DataFrame(data=l) df2=pd.DataFrame(data=l,columns=['punt1','punt2','punt3','punt4','punt5']) df3=pd.DataFrame(data=l,columns=['punt1','punt2','punt3','punt4','punt5'],index=['est1','est2','est3','est4','est5']) df1.rename(index={0:"a",1:"b",2:"c",3:"d",4:"e"}) df1.rename(index={"a":"a",1:"b",2:"c",3:"d",4:"e"}) df1 docentes=pd.read_csv('Docentes_De_Planta.csv') docentes.head() docentes.tail() docentes.columns docentes.index docentes.describe() docentes.dtypes docentes=pd.read_csv('Docentes_De_Planta.csv',index_col='Facultad') docentes.plot(figsize=(10,15)) docentes['DOCTORADO'].plot(figsize=(10,15)) docentes['DOCTORADO'].value_counts().plot(kind = 'bar') docentes['HONORIS CAUSA'] = range(39)
Java
UTF-8
8,126
1.570313
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2015, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 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 * HOLDER 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. */ package no.nordicsemi.android.nrftoolbox.uart; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.TransitionDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.widget.SlidingPaneLayout; import android.view.View; import java.util.UUID; import no.nordicsemi.android.nrftoolbox.R; import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; public class UARTActivity extends BleProfileServiceReadyActivity<UARTService.UARTBinder> implements UARTControlFragment.ControlFragmentListener, UARTInterface { private final static String SIS_EDIT_MODE = "sis_edit_mode"; private SlidingPaneLayout mSlider; private UARTService.UARTBinder mServiceBinder; private boolean mEditMode; @Override protected Class<? extends BleProfileService> getServiceClass() { return UARTService.class; } @Override protected void onServiceBinded(final UARTService.UARTBinder binder) { mServiceBinder = binder; } @Override protected void onServiceUnbinded() { mServiceBinder = null; } @Override protected void onCreateView(final Bundle savedInstanceState) { setContentView(R.layout.activity_feature_uart); // Setup the sliding pane if it exists final SlidingPaneLayout slidingPane = mSlider = (SlidingPaneLayout) findViewById(R.id.sliding_pane); if (slidingPane != null) { slidingPane.setSliderFadeColor(Color.TRANSPARENT); slidingPane.setShadowResourceLeft(R.drawable.shadow_r); slidingPane.setPanelSlideListener(new SlidingPaneLayout.SimplePanelSlideListener() { @Override public void onPanelClosed(final View panel) { // Close the keyboard final UARTLogFragment logFragment = (UARTLogFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_log); logFragment.onFragmentHidden(); } }); } } @Override protected void onRestoreInstanceState(final @NonNull Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mEditMode = savedInstanceState.getBoolean(SIS_EDIT_MODE); setEditMode(mEditMode, false); } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(SIS_EDIT_MODE, mEditMode); } @Override protected boolean onOptionsItemSelected(int itemId) { switch (itemId) { case R.id.action_show_log: mSlider.openPane(); return true; } return false; } @Override protected int getLoggerProfileTitle() { return R.string.uart_feature_title; } @Override protected Uri getLocalAuthorityLogger() { return UARTLocalLogContentProvider.AUTHORITY_URI; } @Override protected void setDefaultUI() { // empty } @Override public void onServicesDiscovered(final boolean optionalServicesFound) { // do nothing } @Override public void onDeviceSelected(final BluetoothDevice device, final String name) { // The super method starts the service super.onDeviceSelected(device, name); // Notify the log fragment about it final UARTLogFragment logFragment = (UARTLogFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_log); logFragment.onServiceStarted(); } @Override protected int getDefaultDeviceName() { return R.string.uart_default_name; } @Override protected int getAboutTextId() { return R.string.uart_about_text; } @Override protected UUID getFilterUUID() { return null; // not used } @Override protected boolean isDiscoverableRequired() { return false; } @Override public void send(final String text) { if (mServiceBinder != null) mServiceBinder.send(text); } @Override public void setEditMode(final boolean editMode) { setEditMode(editMode, true); } @Override public void onBackPressed() { if (mSlider != null && mSlider.isOpen()) { mSlider.closePane(); return; } if (mEditMode) { final UARTControlFragment fragment = (UARTControlFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_control); fragment.setEditMode(false); return; } super.onBackPressed(); } /** * Updates the ActionBar background color depending on whether we are in edit mode or not. * * @param editMode * <code>true</code> to show edit mode, <code>false</code> otherwise * @param change * if <code>true</code> the background will change with animation, otherwise immediately */ @SuppressLint("NewApi") private void setEditMode(final boolean editMode, final boolean change) { mEditMode = editMode; if (!change) { final ColorDrawable color = new ColorDrawable(); int darkColor = 0; if (editMode) { color.setColor(getResources().getColor(R.color.orange)); darkColor = getResources().getColor(R.color.dark_orange); } else { color.setColor(getResources().getColor(R.color.actionBarColor)); darkColor = getResources().getColor(R.color.actionBarColorDark); } getSupportActionBar().setBackgroundDrawable(color); // Since Lollipop the status bar color may also be changed if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getWindow().setStatusBarColor(darkColor); } else { final TransitionDrawable transition = (TransitionDrawable) getResources().getDrawable( editMode ? R.drawable.start_edit_mode : R.drawable.stop_edit_mode); transition.setCrossFadeEnabled(true); getSupportActionBar().setBackgroundDrawable(transition); transition.startTransition(200); // Since Lollipop the status bar color may also be changed if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final int colorFrom = getResources().getColor(editMode ? R.color.actionBarColorDark : R.color.dark_orange); final int colorTo = getResources().getColor(!editMode ? R.color.actionBarColorDark : R.color.dark_orange); final ValueAnimator anim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo); anim.setDuration(200); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { getWindow().setStatusBarColor((Integer) animation.getAnimatedValue()); } }); anim.start(); } if (mSlider != null && editMode) { mSlider.closePane(); } } } }
C++
UTF-8
948
3.390625
3
[]
no_license
#include <ctime> #include <iostream> using namespace std; int p[] = {1, 2, 3, 5, 7, 11, 13, 17}; bool ispand(long long n) { int b, d, m = 0; while (n > 0) { d = n % 10; // Get last digit of n b = 1 << d; if ((m & b) == b) // if d has been encountered before return false; m |= b; n = n / 10; } return true; } long long f(const long long n, const int d) { // Check if last three digits of n are divisible by p[d] if ((n % 1000) % p[d] > 0) return 0; // Check if n is, so far, pandigital if (!ispand(n)) return 0; // d = 7 -> n contains the digits 0 through 9 // Furthermore, it satisfies all conditions. if (d == 7) return n; long long sum = 0; for (int i = 0; i < 10; i++) sum += f(n*10+i, d+1); return sum; } int main (int argc, char* argv[]) { long long sum = 0; for (int i = 102; i < 988; i++) sum += f(i, 0); cout << sum << endl; return 0; }
Python
UTF-8
1,497
3.953125
4
[]
no_license
a = [1, 5, 6, 3, 6, 9, 11, 20, 12, 4] b = [7, 4, 5, 6, 7, 1, 12, 5, 9, 8] print('a = ', a) print('b = ', b) # Menyisipkan nilai ke dalam indeks print('\nMeyisipkan nilai 10 ke dalam indeks ke 3 dari a, dan 15 ke dalam indeks 2 dari b') a.insert(3, 10) b.insert(2, 15) print('a = ', a) print('b = ', b) # Menyisipkan nilai ke dalam indeks print('\nMenyisipkan nila 4 ke indeks terakhir dari a, dan 8 ke indeks terakhir dari b') a.append(4) b.append(8) print('a = ', a) print('b = ', b) # Melakukan sorting print('\nKemudian menyorting secara ascending pada list a dan b') a.sort() b.sort() print('a = ', a) print('b = ', b) # Membuat sublist print('\nMembuat list c yang elemennya merupakan sublist dari a (mulai dari indeks ke 0 s/d 7), dan list d yang elemennya merupakan sublist dari b (mulai indeks ke 2 s/d 9)') c = a[:8] d = b[2:10] print('c = ', c) print('d = ', d) # Mendapatkan list dengan penjumlahan print('\nLangkah untuk mendapatkan list e yang elemennya merupakan hasil penjumlahan dari setiap elemen c dan d yang bersesuaian indeksnya') e = [] n = 0 for n in range (len(c)): indeks = c[n] + d[n] e = e + [indeks] print('e = ', e) # Mengubah ke bentuk tuple print('\nMengubah list ke dalam bentuk tuple') Tuple = tuple(e) print('e = ', Tuple) # Mencari nilai min, maks, dan jumlah print('\n') minimal = min(Tuple) maksimal = max(Tuple) jmlh = sum(Tuple) print('Nilai minimal : ', minimal) print('Nilai maksimal : ', maksimal) print('Jumlah seluruh elemen e : ', jmlh)
Java
UTF-8
562
2.9375
3
[]
no_license
package com.war.game.entities; import com.war.util.BattleGameUtil; class Location { private int row; private int column; private String location; public Location(String location) { this.location=location; String[] locationArr = location.split(""); row = BattleGameUtil.getNumericValueString(locationArr[0]); column = BattleGameUtil.getNumericValueString(locationArr[1]); } public int getRow() { return this.row-1; } public int getColumn() { return this.column-1; } @Override public String toString() { return this.location; } }
Shell
UTF-8
900
3.375
3
[ "MIT" ]
permissive
#!/bin/bash set -e USER_ID=${LOCAL_USER_ID:-9001} if [[ -z $(grep -E "pyfunceble:x:${USER_ID}" /etc/passwd) ]] then if [[ ! -d /home/pyfunceble ]] then useradd --shell /bin/bash -u $USER_ID -o -c "PyFunceble user" -m pyfunceble else useradd --shell /bin/bash -u $USER_ID -o -c "PyFunceble user" pyfunceble fi fi export HOME=/home/pyfunceble export PYFUNCEBLE_BASE_DIR="${HOME}" export PYFUNCEBLE_CONFIG_DIR="${PYFUNCEBLE_BASE_DIR}/config" export PYFUNCEBLE_RUN_DIR="${PYFUNCEBLE_BASE_DIR}/run" export PYFUNCEBLE_FILES_DIR="${PYFUNCEBLE_BASE_DIR}/files" export PYFUNCEBLE_AUTO_CONFIGURATION="YES" export PYFUNCEBLE_CONFIG_DIR="${PYFUNCEBLE_CONFIG_DIR}" if [[ "${1:0:1}" == "/" ]] then exec gosu pyfunceble ${@} elif [[ $(command -v ${1%% *} 2>/dev/null) ]] then exec gosu pyfunceble ${@} else exec gosu pyfunceble /usr/local/bin/pyfunceble.sh ${@} fi
Ruby
UTF-8
934
3.21875
3
[]
no_license
require 'csv' class Cookbook attr_accessor :recipes, :csv_file_path def initialize(csv_file_path) @recipes = [] @csv_file_path = csv_file_path @csv_options = { col_sep: ',', force_quotes: true, quote_char: '"' } CSV.foreach(@csv_file_path) do |row| @recipes << Recipe.new(name: row[0], description: row[1], time: row[2], dif: row[3]) end end def all return @recipes end def add_recipe(recipe) @recipes << recipe # save recipes to CSV csv_loop end def remove_recipe(recipe_index) @recipes.delete_at(recipe_index) csv_loop end def done(index) @recipes[index].mark_as_done! csv_loop end private def csv_loop CSV.open(@csv_file_path, 'w', @csv_options) do |csv_object| @recipes.each do |row_array| csv_object << [row_array.name, row_array.description, row_array.time, row_array.done, row_array.dif] end end end end
PHP
UTF-8
1,960
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; class AnswerTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { App\Models\Answer::create( ['text' => 'Николай', 'question_id' => 1] ); App\Models\Answer::create( ['text' => 'Эдуард', 'is_true' => true, 'question_id' => 1] ); App\Models\Answer::create( ['text' => 'Александр', 'question_id' => 1] ); App\Models\Answer::create( ['text' => '10', 'question_id' => 2] ); App\Models\Answer::create( ['text' => '11', 'question_id' => 2] ); App\Models\Answer::create( ['text' => '23', 'is_true' => true, 'question_id' => 2] ); App\Models\Answer::create( ['text' => 'Москва', 'is_true' => true, 'question_id' => 3] ); App\Models\Answer::create( ['text' => 'Екатеренбург', 'is_true' => true, 'question_id' => 3] ); App\Models\Answer::create( ['text' => 'Киев', 'question_id' => 3] ); App\Models\Answer::create( ['text' => '1', 'is_true' => true, 'order_number' => 1, 'question_id' => 4] ); App\Models\Answer::create( ['text' => '2', 'is_true' => true, 'order_number' => 2, 'question_id' => 4] ); App\Models\Answer::create( ['text' => '3', 'is_true' => true, 'order_number' => 3 , 'question_id' => 4] ); } }
JavaScript
UTF-8
661
2.59375
3
[ "MIT" ]
permissive
/*jshint unused:false */ /** * Dynamic grid with Masonry */ var Masonry = function() {}; Masonry.prototype = { $container: $('#Masonry'), init: function() { // add els needed by masonry for better fluid calculations this.$container.prepend('<div class="Masonry-gridSizer"></div><div class="Masonry-gutterSizer"></div>'); // enable masonry after images are loaded this.$container.imagesLoaded( this.runMasonry() ); }, runMasonry: function() { this.$container.masonry({ columnWidth: '.Masonry-gridSizer', gutter: '.Masonry-gutterSizer', itemSelector: '.Masonry-item' }).addClass('is-active'); } }; var masonry = new Masonry();
Markdown
UTF-8
9,101
2.875
3
[]
no_license
--- layout: post title: 第二百五十五节 秋赋(二十) category: 3 path: 2011-1-4-3-25500.md tag: [normal] --- 二用晋和王兆敏面面相觑,纹事情汛真没法“就众么公当下王兆敏道:“这个”办案侦辑拿人都要出签子火牌,诸位不是大明人士,又无功名、差遣在身” “此事当然还是以县里为主了”熊卜佑道,“我等不过从旁协助。” 王兆敏想所谓“从旁协助”其实竟贼还是想要掌握此事的处理权一这倒也好。这个烫手的山芋干脆就丢给原主去处理好了。他也想看看。澳洲人的葫芦里到底卖得是什么药。 吴明晋咳嗽了一声,推辞自己身体不适要先回去休憩片刻。熊卜估知道这是当官的表示“此事你们只管去干。但是与我无关”的一种做派,下面的事情,只要和王兆敏谈就是了。这也是官场上常用的法子。 王兆敏想此事办理,断然不能让澳洲人自己来搞坐堂审理之类的事情,唯一的法子就是委托县衙里的一名官员出面。由澳洲人在背后指挥就是。 “来人,请孙老爷来。”王兆敏吩咐道。 这个差使当仁不让的落到了典史的头上。典史是明代开始才有的官儿。是从宋元以来的县尉衍生过来的,主管的职责是大抵是狱囚警逻之类的治安工作,在没有巡检司分管的地方,也负责巡防、弹压、捕盗的事务?此事交给他办职责名正言顺。 典史的级别很低,连从九品的最低一级官品也轮不上,算是“未入流”不过这个,未入流还是“官”照例要朝廷除授的。 当典史的人,都是些最不得意的读书人。多数是从“监生”中的选授的。如果说举人考不上进士,还能“大挑”当县令、县承之类的官职,监生就只能混个主簿、教谕、导和典史这样的微末之员了。而且升迁的希望很 所以本县的孙典史孙瑞伍就成了一个典型一切向钱看的官了。可惜本地实在太穷,地方势力和土匪又厉害,他这个典史的油水实在有限。 澳洲人的到来给孙瑞伍带来了财运。因为他品级低微,常常被当作替死鬼给吴明晋打发去为澳洲人出头办事。每次办事。照例会有一笔好处。东门市上的种种享受让他更加难以自拔。于是孙典史就在在金钱贿赔和生活享用的双重刺激下越陷越深了。澳洲人每有什么行动,他总是第一个出现,办事极其殷勤。以至于在县里被人笑称为“澳洲典史” 孙瑞伍自己倒是乏不在乎。每天在东门市“享受生活”和独孤求婚很是相得。两人时常一起“腐败”这位监生对自己度过的圣贤之书早就忘得一干二净,把华夷之防丢到九霄云外去。 “不行”没想到熊卜佑一反常态的表示反对。“王师爷。孙典史品级低微,这可是牵涉到本县借伸大户们的案子,若没有一个相当的人物出面主持,恐怕人心难安啊?” “那,熊老爷的意思是?” “还是请吴县承出面主持为好,孙老爷协办。” “有理,有理。”王兆敏想这也算有些道理。反正只要不是自己老爷出面就好,孙典史还是吴县承都没关系。 当下叫人把二位找来,将事情关照了一番。孙典史听了要为澳洲人办案。马上一力应承,倒是吴亚,想了片亥才道:“几位首长,这次刀箭入户恐吓诸仲的事情,案子本身原没什么,只是事情难办”王兆敏咳嗽了一声,说:既然你们谈公事,我就不再打扰了。当下也溜了出去。 “事情难办,我略有耳闻。”熊卜估说,“不过此事事关重大。还是要一查到底,给县里一个交代才是。 “是,是,既然熊首长这么说,我等一力照办就是。”吴亚知道这事情里其实没自己什么事,自己和典史就是来当招牌的。“不知道周首长打算在哪里办公?” “当然是在县衙里,就用二堂吧” “不妥不妥”吴亚摇头道,“周首长在大明并无功名,算是布衣,擅用二堂,本身就是犯法。再者” 再者吴明晋总归是个“百里候”不能象个小厮一样随传随到。而且升堂审案在过去也是很严肃重大的事情。不能太随便了。 “我看,不如在花厅办案。”孙典史道。 “我亦有此意。”吴亚点点头。 花厅属于内衙范畴,不过。县内但凡牵涉到风化的案子或者和诸伸大户有关的案子,一般都在花厅内审理,并不在大堂二堂公开审理。为得是照顾当事人的颜面。 因为属于内衙范畴,并非朝廷经制之地 “好”熊卜估点点头,“就这么办吧。”他拱了拱手:“此案涉及甚广,事机须秘,一会我们会在县衙关防,请诸个莫要惊扰。” “关防?”吴亚和孙瑞伍都没料到还有这一招,不由大惊失色。这是要干吗? “母庸担心”熊卜估温语宽慰,“这也是不得已,哈哈。”说着,他打了一个电话: “开始吧。” 驻守在县衙外的几十名警卫人员随即全部调入衙门内,将各出入口和衙署内的要地完全控制住。县衙里的人,许进不许出。 这时候,根据熊卜估打来的电话,早就准备完毕的陆军的三支小队迅速的开到了临高县的三座城门。随即控制了城门。他们并不明目张胆的接管城防,而是驻扎在城门口后的藏兵洞内,监视民壮。 每支小分队的士官们已经认了好几个星期人脸。现在他们已经把临高县内的胥吏和手下的“做公得”狐群狗党的面孔都记住了,邬德给他们的命令是:这些人只许进城不许出城。 “如果有人要出城,直接扣押送到县衙,明白吗?” “是!明白了。” 县衙里,随着关键部门被人控制,正在县衙内办公的胥吏们感到不安,纷纷出来打听探视。孙瑞伍只得出来安抚众人,要他们不要惊慌。 周洞天关照人把皂班班头叫来。 皂班的班头林长三是个三十多岁的精悍汉子,刀条脸,一双小眼睛很是有神。双手胳膊肌肉发达。不愧是以行刑见长的老皂隶。 到得花厅上,见过礼。林长三眼见花厅上面端坐着本县的两位老爷,一个三四十岁的澳洲人坐下下首的位置上,双目冰冷,一看就是个,极不好惹的人物。 周洞天审视了一眼皂班头子,“把名册给我拿来!传齐全班的皂隶,我要点卯。” “是,是”林长三赶紧出去吩咐。一会,皂隶们都来齐了。 周洞天打开名册,吃了一惊。原来这名册上密密麻麻,在册的皂隶有五六十人之多,而站在下面听候点卯的不过二十来人。 “怎么,人没来齐?”周洞天问。 “老爷有所不知”林长三小心翼翼道,“名册上的数目是不作数的,这都是挂名的皂隶。” 因为在衙门当衙役享有免疫免赋的好处,有些人就出点钱把自己的名字挂在衙役名册上,实际上从来不来衙门当差。 “名字下面有领银子数目的,才是当差的。” 周洞天一数,领银子的一共有二十四个人。点卯下去,人都来齐了。 “每人立玄准备一套皂隶的衣服出来。马上!” 众人面面相觑,不知道这是要干行么。林长三望着孙典史,孙瑞伍不耐烦的一挥手:“叫你们预备就赶快预备,罗嗦什么!” “回老爷小的只有这身公服啊。” “那就脱下来!”孙瑞伍呵异道。 众皂隶只得照办,不一会就把衣服凑齐了。 这批衣服转瞬就穿到了他们带来的政保速成练班里学员身上。 “好了,大伙手脚麻利点!把衣服都换上。”尤国团吆喝着。 尤国团是保卫总署下的一个工作人员。此公在现代时空是一默默无闻的小市民。但是到了口世纪却成了一个暴力手段至上的鼓吹者。他一贯主张只有最残酷无情的手段才能有效的进行统治。原本他在陆军服役,后来政保总署认为此人在陆军内会造成“不良倾向”就把他干脆调入了本部门。 果然,到了政保总署让他如鱼得水。很快就以其残忍的言论让同事们侧目。当然他的残忍作风暂时还没机会来表现。 “好了,现在你们就是县衙的皂隶了,按照事先的方案,把各个要点守好!” 片亥的工夫,临高县城和临高县衙就完全被穿越集团控制住了。 皂班的衙役们,挤挤簇簇的站在花厅里,很是不安的看着发出奇怪命令的周洞天。 林长三更是一脸惶恐巴结的模样。就差没有五体投地了。让周洞天心中一阵的暗自冷笑:“想用这种把戏骗人,装人畜无害?可惜,老子不是自以为浑身放王八气的小白。”“诸位”周洞天缓缓道,“你们都是累世传承的祖业,用刑拷问最拿手不过,明日问案的时候,还有多多偏劳了!”
C++
UTF-8
1,396
2.6875
3
[]
no_license
#pragma once #include "Game/Entity.hpp" #include "Game/ActorDefinition.hpp" #include "Game/RaycastResult.hpp" #include "Game/Item.hpp" class Actor : public Entity { public: Actor(ActorDefinition* actorDef); ~Actor(){}; void Update(float timeDelta); void Render(); void UpdatePlayerInput(float timeDelta); void UpdateEnemy(float timeDelta); void Attack(); bool HasLineOfSight(const Vector2& startPos, const Vector2& endPos) const; RaycastResult Actor::Raycast(const Vector2& startPos, const Vector2& direction, float maxDistance ) const; //TODO: could use this later to determine which projectile they should fire based on abilities/etc //void SetProjectileType(ActorDefinition* newActorDefintion){ m_actorDef = newActorDefintion;} //void Render(); public: //Actor actions bool m_isActorTryingToAttack = false; bool m_isActorTryingToInteract = false; bool m_isActorTryingToUsePotion = false; bool m_isTryingToDropEquipmentItem = false; bool m_wasJustHit = false; float m_currentHitCooldown = 0.0f; const float m_secondsToShowHitDetection= .25f; //actor info bool m_isReadyToAttack = true; bool m_isAttacking = false; float m_shootCooldown = 0.f; float m_goalCooldown = 0.f; Vector2 m_shootDirection = Vector2(0.f, 0.f); ActorDefinition* m_actorDef = nullptr; const float m_actorGoalCooldownInSeconds = 3.f; Stats m_stats; std::vector<Item*> m_equippedItems; };
Markdown
UTF-8
729
2.71875
3
[]
no_license
<div dir = "rtl"> # تمرين مسار الأندرويد الأول 💚 ## التمرين سهل و بسيط نشوف فيه قوة تركيز طلبة الأندرويد في الشرح اليوم 💪🏻 ### الخطوات <br> &#x202b; 1. ➕ أجمع رقمين و أظهر الناتج <br> &#x202b; 2. ✖ أضرب رقمين وأظهر الناتج <br> &#x202b; 3. 🤔 قارن رقمين وأظهر النتيجة ## بونص! عرف إسمك الأول في متغير و أسم عائلتك في متغير <br> ثم استخدم عملية الجمع لطباعة الأسم الاول مع العائلة <br> مساعدة خفيفة : لا تنسى المسافة في الطباعه 😉 </div>
Java
UTF-8
2,783
1.820313
2
[]
no_license
package org.zdesk.config; import javax.servlet.Filter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration //@EnableOAuth2Sso @EnableOAuth2Client public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired OAuth2ClientContext oauth2ClientContext; @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests().antMatchers("/index.html", "/home.html", "/code", "/", "/intralogin", "/media").permitAll() .anyRequest().authenticated().and().csrf().disable() .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class); // @formatter:on } private Filter ssoFilter() { OAuth2ClientAuthenticationProcessingFilter zdeskAuthFilter = new OAuth2ClientAuthenticationProcessingFilter("/media"); OAuth2RestTemplate zdeskTemplate = new OAuth2RestTemplate(zdesk(), oauth2ClientContext); zdeskAuthFilter.setRestTemplate(zdeskTemplate); UserInfoTokenServices tokenServices = new UserInfoTokenServices(zdeskResource().getUserInfoUri(), zdesk().getClientId()); tokenServices.setRestTemplate(zdeskTemplate); zdeskAuthFilter.setTokenServices(tokenServices); return zdeskAuthFilter; } @Bean @ConfigurationProperties("zdesk.client") public AuthorizationCodeResourceDetails zdesk() { System.out.println((new AuthorizationCodeResourceDetails().getClientId())); return new AuthorizationCodeResourceDetails(); } @Bean @ConfigurationProperties("zdesk.resource") public ResourceServerProperties zdeskResource() { return new ResourceServerProperties(); } }
Markdown
UTF-8
4,272
2.953125
3
[ "MIT" ]
permissive
## [自定义View 一: attr 详解](https://blog.csdn.net/qq_30552993/article/details/55258076) ### 1 res/values/attrs.xml ```xml <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="View名称"> <attr name="textColor" format="color"/> <attr name="textSize" format="dimension"/> </declare-styleable> </resources> ``` 注意: format有以下几种类型及读取 序号 | format取值| format说明 |format读取 -- | --| -- | -- 1 |reference |资源ID |attrs.getResourceId(R.styleable.***View名称_attr名称***,  默认值); 2 |color |颜色值 |attrs.getColor(R.styleable.***View名称_attr名称***, 默认值); 3 |boolean |布尔值 |attrs.getBoolean(R.styleable.***View名称_attr名称***, 默认值); 4 |dimension| 尺寸值 |attrs.getDimension(R.styleable.***View名称_attr名称***, 默认值); 5 |float |浮点值 |attrs.getFloat(R.styleable.***View名称_attr名称***, 默认值); 6 |integer |整型值 |attrs.getInteger(R.styleable.***View名称_attr名称***, 默认值); 7 |string |字符串 |attrs.getString(R.styleable.***View名称_attr名称***); 8 |fraction |百分比(%) |attrs.getString(R.styleable.***View名称_attr名称***); 9 |enum |枚举值 |attrs.getInt(R.styleable.***View名称_attr名称***, 默认值); 10 |flag |位或运算 |attrs.getInt(R.styleable.***View名称_attr名称****, 默认值); ### 2 Found item Attr/xxx more than one time (1)在 attr 中不同 View 引用相同属性名字(**textColor**) ```xml <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="View名称"> <attr name="textColor" format="color"/> <attr name="textSize" format="dimension"/> </declare-styleable> <declare-styleable name="View2名称"> <attr name="textColor" format="color"/> <attr name="hint" format="reference" /> </declare-styleable> </resources> ``` (2)错误提示 ``` Error:Execution failed for task ':包路径:mergeReleaseResources'. > 本地包路径\src\main\res\values\attrs.xml: Error: Found item Attr/textColor more than one time ``` (3)解决方式 ```xml <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="textColor" format="color"/> <declare-styleable name="View名称"> <attr name="textColor"/> <attr name="textSize" format="dimension"/> </declare-styleable> <declare-styleable name="View2名称"> <attr name="textColor"/> <attr name="hint" format="reference" /> </declare-styleable> </resources> ``` ### 3 enum / flag (1)下面就列举 flag (enum也类似) ```xml <declare-styleable name = "View名称"> <attr name="inputType"> <flag name = "text" value = "0" /> <flag name = "number" value = "1" /> <flag name = "textPassword" value = "2" /> <flag name = "numberPassword" value = "3" /> <flag name = "numberDecimal" value = "4" /> </attr> </declare-styleable> ``` (2)这里是我在自定义一个EditText的时候,为了设置输入内容的类型 > 调用方法 ```java setInputType(attrs.getInt(R.styleable.View名称_inputType, 0)); ``` ```java public void setInputType(int type) { switch (type) { case 0: mEditText.setInputType(InputType.TYPE_CLASS_TEXT); break; case 1: mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL); break; case 2: mEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); break; case 3: mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD); break; case 4: mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); break; } } ``` ### 4 属性的定义与使用 (1)属性定义 ```xml <declare-styleable name = "名称"> <attr name = "itemTextColor" format = "color" /> </declare-styleable> ``` (2)属性使用 ```xml <TextView android:layout_width = "42dip" android:layout_height = "42dip" android:itemTextColor = "#00FF00"/> ```
Markdown
UTF-8
640
2.65625
3
[]
no_license
# Algoritmos de entrevistas Hola amigo desarrollador web, estos son algunos ejercicios que a lo largo de mi carrera me han pedido resolver, no estoy en contra de las pruebas, pero si estoy en contra de las pruebas que no se apegan a la realidad ¿cuando en tu vida has necesitado el código para obtener números primos? estoy seguro que casi o nunca. Esto también es para ti empresario que cree que es inteligente usar este tipo de pruebas, NO, no es inteligente tus pruebas deben ser enfocadas a lo que haces, a lo que usas. Trate de optimizar el código en la mayor parte aunque estoy seguro que algo se me habrá escapado, saludos.
Java
UTF-8
15,338
1.90625
2
[]
no_license
package com.example.mohan.bbms; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.method.PasswordTransformationMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONException; import org.json.JSONObject; import java.util.Objects; import cz.msebera.android.httpclient.Header; public class login extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar); TextView tx = (TextView) findViewById(R.id.mytext); tx.setText("Login"); Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Billabong.ttf"); tx.setTypeface(custom_font); Button login = (Button) findViewById(R.id.buttonLogin); final EditText number = (EditText) findViewById(R.id.editTextNumber); final EditText password = (EditText) findViewById(R.id.editTextPassword); TextView forgot = (TextView) findViewById(R.id.forgot); CheckBox show = (CheckBox) findViewById(R.id.show); show.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { password.setTransformationMethod(null); } else { password.setTransformationMethod(PasswordTransformationMethod.getInstance()); } } }); forgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.number, null, true); final EditText number = alertLayout.findViewById(R.id.num); final Button cancel = alertLayout.findViewById(R.id.cancel); final Button ok = alertLayout.findViewById(R.id.ok); AlertDialog.Builder alert = new AlertDialog.Builder(login.this); alert.setView(alertLayout); alert.setCancelable(false); final AlertDialog dialog = alert.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); number.setMaxEms(10); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String num = number.getText().toString(); if (num.length() != 10) { Toast.makeText(login.this, "Enter a valid number", Toast.LENGTH_SHORT).show(); } else { dialog.dismiss(); checkNumber(num); } } }); } }); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String num = number.getText().toString().trim(); String pass = password.getText().toString().trim(); if (num.length() != 10) { Toast.makeText(login.this, "Invalid number", Toast.LENGTH_SHORT).show(); } else { if (pass.length() < 6) { Toast.makeText(login.this, "Password must have at least 6 digits", Toast.LENGTH_SHORT).show(); } else { signin(num, pass); } } } }); } private void signin(final String number, String pass) { final ProgressDialog progressDialog = ProgressDialog.show(login.this, null, "Signing in...", false, false); RequestParams params = new RequestParams(); params.put("number", number); params.put("password", pass); String url = "https://blood-help-india.herokuapp.com/login.php"; AsyncHttpClient client = new AsyncHttpClient(); client.get(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { progressDialog.dismiss(); Log.i("---------success------", "---------success------" + String.valueOf(response)); try { if (Objects.equals(response.getString("status"), "success")) { SharedPreferences sharedPreferences = login.this.getSharedPreferences("loginStatus", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("isLoggedIn", true); editor.putString("number", number); editor.putString("utype", response.getString("utype")); editor.apply(); Intent intent = new Intent(getApplicationContext(), availableRequests.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); change(intent); } else { Toast.makeText(login.this, response.getString("status"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e1) { e1.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject response) { progressDialog.dismiss(); Log.i("---------fail----------", "---------fail------" + response); Toast.makeText(login.this, "network error", Toast.LENGTH_SHORT).show(); } }); } void checkNumber(final String num) { final ProgressDialog progressDialog = ProgressDialog.show(login.this, null, "Checking...", false, false); RequestParams params = new RequestParams(); params.put("number", num); String url = "https://blood-help-india.herokuapp.com/forgototp.php"; AsyncHttpClient client = new AsyncHttpClient(); client.get(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { progressDialog.dismiss(); Log.i("---------success------", "---------success------" + String.valueOf(response)); try { if (Objects.equals(response.getString("status"), "success")) { verify(num, response.getString("otp")); } else { Toast.makeText(login.this, response.getString("result"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e1) { e1.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject response) { progressDialog.dismiss(); Log.i("---------fail----------", "---------fail------" + response); Toast.makeText(login.this, "Server error", Toast.LENGTH_SHORT).show(); } }); } private void verify(final String num, final String Otp) { LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.otp, null, true); final EditText number = alertLayout.findViewById(R.id.num); final Button cancel = alertLayout.findViewById(R.id.cancel); final Button ok = alertLayout.findViewById(R.id.ok); AlertDialog.Builder alert = new AlertDialog.Builder(login.this); alert.setView(alertLayout); alert.setCancelable(false); final AlertDialog dialog = alert.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); number.setMaxEms(6); number.setText(Otp); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); abort(num); } }); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String otp = number.getText().toString(); if (otp.length() != 6) { Toast.makeText(login.this, "Enter correct OTP", Toast.LENGTH_SHORT).show(); } else { final ProgressDialog progressDialog = ProgressDialog.show(login.this, null, "Verifying OTP...", false, false); RequestParams params = new RequestParams(); params.put("otp", otp); params.put("number", num); String url = "https://blood-help-india.herokuapp.com/forgot.php"; AsyncHttpClient client = new AsyncHttpClient(); client.get(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { dialog.dismiss(); progressDialog.dismiss(); Log.i("---------success------", "---------success------" + String.valueOf(response)); try { if (Objects.equals(response.getString("status"), "success")) { String mypin = null; try { mypin = response.getString("result"); } catch (JSONException e) { e.printStackTrace(); } LayoutInflater inflater = getLayoutInflater(); View alertLayout = inflater.inflate(R.layout.pin, null, true); final TextView myp = alertLayout.findViewById(R.id.showpin); final Button ok = alertLayout.findViewById(R.id.ok); AlertDialog.Builder alert = new AlertDialog.Builder(login.this); alert.setView(alertLayout); alert.setCancelable(false); final AlertDialog dialog = alert.create(); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); myp.setText("Your new password is " + mypin); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } else { Toast.makeText(login.this, response.getString("result"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e1) { e1.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject response) { progressDialog.dismiss(); Log.i("---------fail----------", "---------fail------" + response); Toast.makeText(login.this, "Server error", Toast.LENGTH_SHORT).show(); } }); } } }); } private void abort(String num) { final ProgressDialog progressDialog = ProgressDialog.show(login.this, null, "Rolling back changes...", false, false); RequestParams params = new RequestParams(); params.put("number", num); String url = "https://blood-help-india.herokuapp.com/abort.php"; AsyncHttpClient client = new AsyncHttpClient(); client.get(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { progressDialog.dismiss(); Log.i("---------success------", "---------success------" + String.valueOf(response)); try { if (Objects.equals(response.getString("status"), "success")) { Toast.makeText(login.this, "Process aborted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(login.this, "Server error", Toast.LENGTH_SHORT).show(); } } catch (JSONException e1) { e1.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject response) { progressDialog.dismiss(); Log.i("---------fail----------", "---------fail------" + response); Toast.makeText(login.this, "Server error", Toast.LENGTH_SHORT).show(); } }); } private void change(final Intent intent){ new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(intent); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } }, 1); } }
C++
UTF-8
543
2.953125
3
[]
no_license
// Lab 0b, The "Hello, World" Program, part b // Programmer: Kevin Wong // Editor(s) used: Codeblocks // Compiler(s) used: GNU GCC Compiler #include <iostream> using namespace std; int main() { // print student and program information cout << "Lab 0b, The Hello, World Program, part b\n"; cout << "Programmer: Kevin Wong\n"; cout << "Editor(s) used: Codeblocks\n"; cout << "Compiler(s) used: GNU GCC Compiler\n"; cout << "File: " << __FILE__ << endl; cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl; }
Python
UTF-8
1,650
3.234375
3
[]
no_license
import sys from collections import deque '''CONSTANTS''' '''VARIABLES''' N, M = 0, 0 numbers = [] left, right = 0, 0 count = 0 '''UTILS''' class SegmentTree: def __init__(self, arr) -> None: self.n = len(arr) self.tree = [0] * self.n * 2 self.build(arr) def build(self, arr): for i in range(self.n, self.n*2): self.tree[i] = arr[i-self.n] for i in range(self.n-1, 0, -1): self.tree[i] = self.tree[2*i] + self.tree[2*i+1] def update(self, index, value): index += self.n while index > 1: self.tree[index // 2] = self.tree[index] + self.tree[index^1] index //= 2 def query(self, _from, _to): ret = 0 _from += self.n _to += self.n while _from < _to: if _from % 2: ret += self.tree[_from] _from += 1 if _to % 2: _to -= 1 ret += self.tree[_to] _from >>= 1 _to >>= 1 return ret def __str__(self) -> str: return "{}".format(self.tree) '''INPUT''' N, M = list(map(int, sys.stdin.readline().split())) numbers = list(map(int, sys.stdin.readline().split())) '''COMPUTE''' tree = SegmentTree(numbers) while left <= right: _sum = tree.query(left, right) if right < N and _sum <= M: right += 1 else: left += 1 if _sum == M: count += 1 '''OUTPUT''' print(count)
Java
UTF-8
1,970
2.875
3
[]
no_license
package org.petehering.txtadv.core; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.petehering.txtadv.Command; import org.petehering.txtadv.Door; import org.petehering.txtadv.Item; import org.petehering.txtadv.Model; import org.petehering.txtadv.Player; import org.petehering.txtadv.Room; public class Look implements Command { @Override public List<String> execute (Model model, String[] args) { List<String> response = new ArrayList<>(); Player p = model.getPlayer(); Room r = model.getRooms().get(p.getLocation()); Set<Item> c = r.getContents(); response.add("the " + r.getName() + " " + r.getDescription()); Map<String, Integer> count = new TreeMap<>(); for(Item it : c) { String name = it.getName(); if(!count.containsKey(name)) { count.put(name, 1); } else { count.put(name, count.get(name) + 1); } } if(!count.isEmpty()) { response.add("you see:"); for(String name : count.keySet()) { response.add(" " + count.get(name) + " " + name); } } door("north", r.getNorth(), model, response); door("south", r.getSouth(), model, response); door("east", r.getEast(), model, response); door("west", r.getWest(), model, response); return response; } private void door(String dir, Door d, Model m, List<String> response) { if(d == null || d.getHidden()) { return; } String line = "to the " + dir + " is a " + d.getDescription(); if(!d.getClosed()) { line += " to the " + m.getRooms().get(d.getDestination()).getName(); } response.add(line); } }