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
JavaScript
UTF-8
1,810
2.828125
3
[]
no_license
import React,{useState,useEffect} from 'react' import './weather.css' import Weathercard from './Weathercard' const Weather = () => { const [searchValue, setSearchValue] = useState("kathmandu") const [weatherInfo,setWeatherInfo] = useState("{}") const getWeatherInfo = async() => { try{ let url = `https://api.openweathermap.org/data/2.5/weather?q=${searchValue}&units=metric&appid=8bfa174e261bc0ce737a6d9502794f7a` let res = await fetch(url) let data = await res.json(); // data may find or not so we use await / fetch returns promise const {temp,humidity,pressure }= data.main; const{main: weathermood} = data.weather[0]; const {name} = data; const {speed} = data.wind; const {country,sunset} = data.sys; const myNewWeatherInfo = { temp,humidity,pressure,weathermood,name,speed,country,sunset, } setWeatherInfo(myNewWeatherInfo); } catch(error) { console.log(error) } } useEffect(() => { getWeatherInfo(); //When we refresh page for the first time, getweatherInfo will run. }, []); return ( <> <div className="wrap"> <div className="search"> <input type="search" placeholder="Search" autoFocus id="Search" className="searchTerm" value ={searchValue } onChange ={(event)=>setSearchValue(event.target.value)} /> <button className="searchButton" type="button" onClick={getWeatherInfo} > Search </button> </div> </div> <Weathercard weatherInfo ={weatherInfo} /> </> ) } export default Weather
JavaScript
UTF-8
1,304
2.59375
3
[]
no_license
import React, { Component ,Fragment} from "react"; import Breadcrumb from "react-bootstrap/Breadcrumb"; import Spinner from "react-bootstrap/Spinner"; class Perfil extends Component { constructor(props) { super(props); /* Estado */ this.state = { usuario: {}, isLoading:true }; } componentDidMount() { console.log(this.props); const id = this.props.match.params.id; fetch(`https://jsonplaceholder.typicode.com/users/${id}`) .then(response => response.json()) .then(data => this.setState({ usuario: data ,isLoading:false})) .catch(error => { console.log(error); }); } render() { const usuario = this.state.usuario; const { isLoading } = this.state; return ( <Fragment> <Breadcrumb> <Breadcrumb.Item href="/home">Home</Breadcrumb.Item> <Breadcrumb.Item active>Perfil</Breadcrumb.Item> </Breadcrumb> <h1>Perfil Usuario</h1> {!isLoading ? <Fragment><h5>{usuario.name}</h5> <h5>{usuario.email}</h5> <h5>{usuario.username}</h5></Fragment>:<Spinner animation="border" role="status"> <span className="sr-only">Cargando...</span> </Spinner>} </Fragment> ); } } export default Perfil;
C
UTF-8
458
3.03125
3
[]
no_license
#include<stdio.h> int main() { int arr[10],i,j,n,temp,num; printf("enter the value of n"); scanf("%d",&n); printf("enter the value one by one"); for(i=0;i<n;i++); { scanf("%d",&arr[i]); } printf("enter the input arr[i]"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<num;i++) { for(j=0;i<(num-i-1);j++) { if (arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } printf("sorted array is:"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } } } }
Markdown
UTF-8
2,039
2.578125
3
[ "MIT" ]
permissive
# Cours Exploration du Web ## IMT Atlantique [ELU 525](https://portail.telecom-bretagne.eu/portal/pls/portal/pkg_df.programmes.SHOW_FICHE?p_id_mod_er=32168) * Première session : Avril - Juin 2018 * Seconde session : octobre - décembre 2018 ## Avertissement Ce site est un site web qui sera progressivement construit pendant le cours. Très dépouillé au début, nous verrons ce qu'il en est à la fin. Il est donc à la fois support de cours, défini de manière collaborative, et le projet transverse du cours, au sens site construit pendant le cours. ## Objectifs du cours Explorer ce qu'est le web, ses fondements, les techniques sous-jacentes, des outils, et les usages. # Contenus proposés par les étudiants 1. [Les bases de HTML5 et de CSS3 !](cours/html.md) 1. [Recherche sur le Web](cours/Recherche_sur_le_Web.md) 1. [Web Profond](cours/deepweb.md) 1. [Sécurité sur le Web](cours/MenacesDuWeb.md) 1. [Initiation au Javascript](cours/javascript.md) 1. [Bootstrap](cours/Bootstrap.md) 1. [Django](cours/django.md) 1. [Rampant et Grattant](cours/Crawling_et_scraping.md) 1. [Sessions précédentes](cours/index.md) # Présentation du cours Présentation du cours en quelques diapositives : <iframe src="//www.slideshare.net/slideshow/embed_code/key/nNUgizR6I3FFpP" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe> <div style="margin-bottom:5px"> <strong> [Présentation du cours](https://www.slideshare.net/jm.gilliot/explorweb-introduction-automne-2018) Un rapport d'étonnement en guise d'introduction : <iframe src="//www.slideshare.net/slideshow/embed_code/key/1JFQv8Q6bi87NU" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe> [Apprendre en 2018](https://www.slideshare.net/jm.gilliot/apprendre-en-2018-86532227)
C
UTF-8
249
3.515625
4
[]
no_license
#include <stdio.h> int main() { printf("Size of short int is %lu\n", sizeof(short int)); printf("Size of int is %lu\n", sizeof(int)); printf("Size of long int is %lu\n", sizeof(long int)); int num = 0; printf("%d\n", num); return 0; }
PHP
UTF-8
810
2.546875
3
[]
no_license
<?php namespace Tests\Unit\Models; use App\Models\Plateau; use App\Models\Rover; use App\Repositories\RoverRepository; use Exception; use Tests\TestCase; class RoverRepositoryTest extends TestCase { /** * @test * @throws Exception */ public function test_turn_left() { $x = random_int(1, 100); $y = random_int(1, 100); $plateau = new Plateau($x, $y); $plateau->save(); $rover = new Rover($plateau->getId(), 'S', $x, $y); $rover->save(); $roverRepo = new RoverRepository($rover); $roverRepo->turn('L'); $this->assertSame($rover->find($rover->getId())->getDirection(), 'E'); } // public function test_turn_right() // { // // } // // public function test_turn_move() // { // // } }
Java
UTF-8
765
3.375
3
[]
no_license
package com.week3; import java.util.Scanner; class point { double x,y ; public point(double a,double b) { this.x = a ; this.y = b ; } public point() { } void distance(point p1,point p2) { double dis = Math.sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y)); System.out.println(dis); } } public class q3_2 { public static void main(String[] args) { double x1,x2,y1,y2 ; Scanner sc = new Scanner(System.in); x1 = sc.nextDouble(); y1 = sc.nextDouble(); x2 = sc.nextDouble(); y2 = sc.nextDouble(); point a1 = new point(x1,y1); point a2 = new point(x2,y2); point p3 = new point(); p3.distance(a1,a2); } }
Markdown
UTF-8
2,650
2.84375
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "Catching Up With New Broadband Methods" author: "Dave Jacoby" date: "2021-08-31 23:28:31 -0400" categories: "" --- I've written on this before, but can't think of where I wrote it or how to find it. But my thoughts, until now, were that before the year 2000, there were three wires that came to your home: electricity, telephone, and cable TV. [You can put Internet over power lines](https://en.wikipedia.org/wiki/Broadband_over_power_lines) but there are issues, so you don't see it much. But you _can_ put Internet over the phone line, and you can put Internet over the cable. This has made two sets of local internet monopolies: the phone companies and the cable companies. There are companies who will hook up fiber-optic Internet to your homes. I have friends who use that service, and there's an awful lot of dark fiber out there, waiting for us to move up to needing it. But it isn't common, because this means that there have to be backhoes going all over cities to allow the new fiber to be run all over, and any other options would require the same thing. But most houses get wired for phone and cable when they're made, so those runs already exist. If I was in city government, i would be unsure about letting more than a few of those go on in my city, which is why, most of the time, there's a local cable monopoly and a local telephone monopoly, and your only choices are between those. In _my_ case, the choice was was between the cable-based choice that my apartment complex offered and the telephony option now that Frontier had bought out Verizon's landline component, but I found that TMobile was offering broadband at _much_ better speeds than I had before. When the boxes came, I started worrying about where the phone jacks were, because with the bookcases in the house, the spots on the walls where they would be are covered up. I didn't worry long, because in skimming the users' guide, I saw the crucial line: > _**Note:** Battery and sim card are pre-installed._ I had thought that mobile-phone internet would be the way to get around local internet monopolies, and here it is, in my house! I max out at 30 Mbps around here, but often get closer to 5-10. I've seen Kbps readings on [Fast.com](https://fast.com/) when I wanted good bits, and I've used my phone as a mobile hotspot when things have just absolutely sucked. I'm seeing 110 Mbps. I'm not 100% transferred, but it looks good so far. #### If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo.](https://github.com/jacoby/jacoby.github.io)
Java
UTF-8
1,122
3.140625
3
[]
no_license
package com.ailo.zombies.effect; import com.ailo.zombies.entity.InfectableThing; import com.ailo.zombies.entity.Thing; import java.util.Objects; import static java.lang.String.format; public class InfectionStatusEffect implements StatusEffect { private final String movementInstruction; public InfectionStatusEffect(String movementInstruction) { this.movementInstruction = movementInstruction; } @Override public void apply(Thing thing) { if (thing instanceof InfectableThing) { ((InfectableThing) thing).turnToZombie(movementInstruction); } else { throw new IllegalArgumentException(format("[%s] is not infectable", thing)); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InfectionStatusEffect that = (InfectionStatusEffect) o; return Objects.equals(movementInstruction, that.movementInstruction); } @Override public int hashCode() { return Objects.hash(movementInstruction); } }
PHP
UTF-8
1,236
2.59375
3
[]
no_license
<?php class YourActiveRecordClass extends TRecord { const TABLENAME = 'tablename'; const PRIMARYKEY= 'id'; const IDPOLICY = 'max'; // {max, serial} public function __construct($id = NULL) { parent::__construct($id); parent::addAttribute('name'); } public function onBeforeLoad($id) { file_put_contents('/tmp/log.txt', "onBeforeLoad: $id\n", FILE_APPEND); } public function onAfterLoad($object) { file_put_contents('/tmp/log.txt', 'onAfterLoad:' . json_encode($object)."\n", FILE_APPEND); } public function onBeforeStore($object) { file_put_contents('/tmp/log.txt', 'onBeforeStore:' . json_encode($object)."\n", FILE_APPEND); } public function onAfterStore($object) { file_put_contents('/tmp/log.txt', 'onAfterStore:' . json_encode($object)."\n", FILE_APPEND); } public function onBeforeDelete($object) { file_put_contents('/tmp/log.txt', 'onBeforeDelete:' . json_encode($object)."\n", FILE_APPEND); } public function onAfterDelete($object) { file_put_contents('/tmp/log.txt', 'onAfterDelete:' . json_encode($object)."\n", FILE_APPEND); } }
Markdown
UTF-8
1,485
2.65625
3
[]
no_license
# New York Taxi Pipeline ## Pipeline Usage ### requirements: ``` Docker + Docker-compose ``` ### Installation - Clone repository `git clone https://github.com/robomillo/new_york_taxis.git` - Navigate to root of directory - run `docker-compose up`. (if airflow webserver gets stuck in a cycle of restarting, run `docker-compose down -v && docker-compose up` ) ### Shortcuts In order to reduce the size data downloaded and processed for the sake of speed, I have restricted the data to a monthly dataset in 2019 only. ### Running Pipeline - Navigate to [http://localhost:8080](http://localhost:8080) - default credentials for airflow: user=`airflow` password=`airflow` - Ensure dag is active ![dag.png](./static/dag.png) - Click to trigger dag run: ![trigger.png](./static/trigger.png) ## Helper queries All the transformational queries can be found in [./dags/transform_taxi_data/create_datasets.sql](dags/transform_taxi_data/create_datasets.sql) Question 2.1 ``` SELECT * FROM datasets.popular_dest_zones_by_total_passengers WHERE drop_off_location = 'Chinatown' AND pick_up_month = '2019-09' AND total_passengers_rank <= 10 ``` Question 2.2 ``` SELECT * FROM datasets.popular_dest_boroughs_by_ride_count WHERE pick_up_borough = 'Manhattan' AND pick_up_month = '2019-08' and total_trips_rank <= 10; ``` Question 3 ``` select * from datasets.historical_rankings; ``` Question 4 ``` select * from datasets.current_month_ranked_trips; ```
Python
UTF-8
2,267
3.203125
3
[]
no_license
import random # import matplotlib.pyplot as plt class node: interset = 100 def __init__(self, status, value): self.infected = status self.value = value k =0.96 currentTimes = 0 nodes = [] isolated = 0 amount = int(input("输入节点总数:")) infected = int(input("输入感染的节点数:")) tempY=[] tempX=[] valueX=[] valueY=[] for i in range(0, amount): valueRand=random.randint(0,10) if i < infected: nodes.append(node(True, valueRand)) else: nodes.append(node(False, valueRand)) while isolated < infected & infected != amount: isolated = 0 for key in range(amount): #currentNode = 0 currentNode = random.randint(0, amount - 1) while currentNode == key: currentNode = random.randint(0, amount - 1) average = (nodes[key].value+nodes[currentNode].value)/2 nodes[key].value=average nodes[currentNode].value=average if nodes[key].infected == True: if nodes[key].interset == 0: isolated = isolated + 1 if nodes[currentNode].infected == False: lottery = random.randint(0, 99) if lottery < nodes[key].interset: nodes[currentNode].infected = True infected = infected + 1 else: nodes[key].interset = nodes[key].interset *k else: if nodes[currentNode].infected == True: lottery = random.randint(0, 99) if lottery < nodes[currentNode].interset: nodes[key].infected = True infected = infected + 1 print("Round" + str(currentTimes + 1)) print("感染:" + str(infected)) print("Isolated:" + str(isolated)) currentTimes = currentTimes+ 1 tempY.append(infected) tempX.append(currentTimes) i=1 for key in nodes: valueY.append(key.value) valueX.append(i) i=i+1 valueX.append(i) valueY.append(10) valueX.append(i+1) valueY.append(0) plt.subplot(121) plt.plot(valueX,valueY,'ro') plt.subplot(122) plt.plot(tempX,tempY,'ro') plt.show()
C++
UTF-8
2,218
2.890625
3
[]
no_license
#ifndef TREEVIEWER_H #define TREEVIEWER_H #include <GL/glew.h> #include <GLFW/glfw3.h> #include "../tree/Tree.h" #include <iostream> #include <math.h> using namespace std; class TreeViewer; TreeViewer *globalViewer; void error_callback(int i, const char *message) { cout << "Error: " << message << endl; } void window_resize_callback(GLFWwindow *window, int width, int height); class TreeViewer { GLFWwindow *window; int width, height; float angle; unique_ptr<MeshCollection> meshes; public: TreeViewer() { angle = 0; glfwSetErrorCallback(&error_callback); glfwInit(); this->window = glfwCreateWindow(800, 600, "Tree Generator", NULL, NULL); if (!this->window) { cout << "Failed to create window" << endl; glfwTerminate(); exit(1); } glfwMakeContextCurrent(this->window); glfwSetWindowSizeCallback(this->window, &window_resize_callback); glewInit(); glfwGetFramebufferSize(this->window, &this->width, &this->height); glViewport(0, 0, this->width, this->height); globalViewer = this; } ~TreeViewer() { glfwTerminate(); } void Resize(int width, int height) { this->width = width; this->height = height; glViewport(0, 0, this->width, this->height); } void AddTree(Tree *tree) { this->meshes.reset(new MeshCollection()); tree->draw(this->meshes.get()); } void draw() { this->angle += 0.003; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluPerspective(10.0f, (float)width/(float)height, 1, 100); gluLookAt( 5.0f, 90*sin(angle), 60*cos(angle), 5.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); this->meshes->draw(); glFlush(); glfwSwapBuffers(this->window); glfwPollEvents(); } }; void window_resize_callback(GLFWwindow *window, int width, int height) { if (globalViewer) { cout << "Resize" << endl; globalViewer->Resize(width, height); } } #endif
Python
UTF-8
1,855
2.78125
3
[]
no_license
from BasicDatabase.db_operations import DBOperation, SetOperation, UnsetOperation from BasicDatabase.errors import NoOpenTransactionError class Database: def __init__(self): self._persistent_dict: dict = {} self.open_transactions = [] @property def _db(self): db = self._persistent_dict.copy() if self.open_transactions: for transaction in self.open_transactions: for operation in transaction: db = operation.run(db) return db def _add_operation(self, operation: DBOperation): if self.open_transactions: last_open_transaction = self.open_transactions[-1] last_open_transaction.append(operation) else: self._persistent_dict = operation.run(self._persistent_dict) def set(self, key, value): self._add_operation(SetOperation(key, value)) def get(self, key): return self._db.get(key, 'NULL') def unset(self, key): self._add_operation(UnsetOperation(key)) def begin_transaction(self): new_transaction_operation_list = [] self.open_transactions.append(new_transaction_operation_list) def num_equal_to(self, searched_value): value_list = list(self._db.values()) return value_list.count(searched_value) def rollback(self): self._raise_error_if_no_transactions() self.open_transactions.pop() def commit(self): self._raise_error_if_no_transactions() for transaction in self.open_transactions: for operation in transaction: self._persistent_dict = operation.run(self._persistent_dict) self.open_transactions = [] def _raise_error_if_no_transactions(self): if len(self.open_transactions) == 0: raise NoOpenTransactionError
JavaScript
UTF-8
1,949
2.765625
3
[]
no_license
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { navigate } from '@reach/router'; const SearchComponenet = (props) => { const [formState, setFormState] = useState ({ id: props.id, category: props.category }); const [responsedata, setResponseData] = useState ([]); const onChangeHandler = e => { setFormState({ ...formState, [e.target.name] : e.target.value }); }; const onSubmitHandler = e => { e.preventDefault(); axios.get(`https://swapi.dev/api/${formState.category}/${formState.id}`) .then(response=>{setResponseData(response.data)}) .catch(err => console.log(err)); navigate(`/${formState.category}/${formState.id}`) }; useEffect(()=>{ axios.get(`https://swapi.dev/api/${formState.category}/${formState.id}`) .then(response=>{setResponseData(response.data)}) .catch(err => { console.log(err); alert("These are not the droids you are looking for"); }); }, []); return( <div> <h1>Luke APIwalker</h1> <form onSubmit={onSubmitHandler}> <label>Search For: </label> <select name="category" onChange={onChangeHandler}> <option value="people">Person</option> <option value="planets">Planet</option> <option value="starships">Starship</option> </select> <br/> <label>ID: </label> <input type="text" name="id" onChange={onChangeHandler}/> <br/> <input type="submit"/> </form> <br></br> {Object.keys(responsedata).map((item) => <p>{item}: {responsedata[item]}</p> )} </div> ) } export default SearchComponenet;
Markdown
UTF-8
524
2.53125
3
[ "MIT" ]
permissive
# A Simple Neural Attentive Meta-Learner implementation in PyTorch A PyTorch implementation of the SNAIL building blocks. This module implements the three blocks in [_A Simple Neural Attentive Meta-Learner_](https://openreview.net/forum?id=B1DmUzWAW&noteId=B1DmUzWAW) by Mishra et al. The three building blocks are the following: - A dense block, built with causal convolutions. - A TC Block, built with a stack of dense blocks. - An attention block, similar to the attention mechanism described by Vaswani et al (2017).
Java
UTF-8
1,205
3.4375
3
[]
no_license
package com.sda.socketExample; import java.io.*; import java.net.Socket; public class Client { private Socket socket = null; public Client(String host, int port) { while (true) { try { socket = new Socket(host, port); //take input from terminal PrintWriter writer = new PrintWriter(socket.getOutputStream(),true); BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in)); String userInput = userInputBR.readLine(); writer.println(userInput); System.out.println("Sent Message " + userInput); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("Received Message: " + reader.readLine()); if ("exit".equalsIgnoreCase(userInput)) { socket.close(); break; } } catch (IOException e) { System.out.println(e); } } } public static void main(String args[]){ Client client = new Client("192.168.1.197",8082); } }
Java
UTF-8
302
1.875
2
[]
no_license
package com.scuse.mapper; import com.scuse.entity.Register; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RegisterMapper { int insert(Register record); int insertSelective(Register record); List<Register> selectByCandId(int id); }
C++
UTF-8
2,399
3.15625
3
[]
no_license
/** @file main.cpp @author Gregório da Luz @date February 2021 @brief main.cpp for Othello game **/ #include <iostream> #include "Game.h" using namespace std; #define WHITE 1 #define BLACK 2 int main() { Game othello; Player white(WHITE); Player black(BLACK); int user_input_x = -1; int user_input_y = -1; bool allowed = false; while (!othello.getEnd()) { othello.printBoard(); othello.Info(); //while the slot is not allowed or not free, keep asking the user for input while (!allowed) { user_input_x = -1; user_input_y = -1; while (!othello.goodInput(user_input_x, user_input_y)) {//cheking if it is inside the range of 0 to 7 index cout << "Write the x coord you want to place your disk:\n"; cin >> user_input_x; cout << "Write the y coord you want to place your disk:\n"; cin >> user_input_y; } if (othello.freeSlot(user_input_x, user_input_y)) { allowed = othello.allowedSlot(user_input_x, user_input_y); } } allowed = false; // setting it as false again for the next turn othello.settingNewDisk(user_input_x, user_input_y); //keeping record of how many disks each player still has if (othello.getWhoseTurn() == 'B') { black.oneLessDisk();} else { white.oneLessDisk();} // if we have reached 60 disks on the board we avoid the normal procedure and set the end if (othello.getDiskCounter() <= 60) { othello.flipWhoseTurnAndOpponent(); if (othello.noPossibleMove()) { othello.setEnd(true); } } else { othello.setEnd(true); } //showing results and asking if the player wants to play again if (othello.getEnd()) { othello.theWinnerIs(); if (othello.playAgain()) { black.resetDisks(); white.resetDisks(); } } //checking if the player needs disks from the opponent to play else { if (othello.getWhoseTurn() == 'B' && black.getDisksAvailable() == 0) { black.giveMeOneDisk(white); } else if (othello.getWhoseTurn() == 'W' && white.getDisksAvailable() == 0) { white.giveMeOneDisk(black); } } } }
Python
UTF-8
2,832
2.65625
3
[]
no_license
import boto3 import os from botocore.exceptions import ClientError # Code adjusted from https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html class SendEmail: # Send notification to recipient def send(RECIPIENT): # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. SENDER = os.environ["EMAIL_SENDER"] # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable, and the # ConfigurationSetName=CONFIGURATION_SET argument below. # CONFIGURATION_SET = "ConfigSet" # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = os.environ["AWS_REGION"] # The subject line for the email. SUBJECT = "Story Evolution Tracker Update" # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Story Evolution Tracker Update") # The HTML body of the email. BODY_HTML = """<html> <head></head> <body> <h1>Story Evolution Tracker Update</h1> <p>One of your Bookmarked stories has updated. Visit Story Evolution Tracker to view update.</p> </body> </html> """ # The character encoding for the email. CHARSET = "UTF-8" # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) # Try to send the email. try: #Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': [ RECIPIENT, ], }, Message={ 'Body': { 'Html': { 'Charset': CHARSET, 'Data': BODY_HTML, }, 'Text': { 'Charset': CHARSET, 'Data': BODY_TEXT, }, }, 'Subject': { 'Charset': CHARSET, 'Data': SUBJECT, }, }, Source=SENDER, # If you are not using a configuration set, comment or delete the # following line # ConfigurationSetName=CONFIGURATION_SET, ) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:"), print(response['MessageId'])
Python
UTF-8
1,142
4.03125
4
[ "MIT" ]
permissive
#!/usr/bin/env python3 def solution(array): """ When splitting the array in two parts a and b, with array = a + b, returns the minimal difference that can be achieved between the sum of elements in a and the sum of elements in b. Solution using Dynamic Programming. """ # left_side[i] is the sum of elements in array from index 0 up to i left_side = [None] * (len(array)-1) # right_side[i] is the sum of elements in array from index i + 1 up to n - 1 right_side = [None] * (len(array)-1) # We initialize the left side array with the first element and the right side with the last element left_side[0] = array[0] right_side[len(array) - 2] = array[len(array) - 1] # Storing all sums for the left and right side, to use the last calculated value to calculate the next sum for i in range(1, len(array)-1): left_side[i] = left_side[i - 1] + array[i] right_side[len(array) - i - 2] = right_side[len(array) - i -1] + array[len(array) - i - 1] # Finally, returns the minimal value for the given function return min([abs(left_side[i] - right_side[i]) for i in range(len(array) - 1)])
Markdown
UTF-8
308
2.578125
3
[]
no_license
## 组别管理 组别管理通过将节点分组的形式来管理,通过这种方式,将同一用途的节点划分到相同的组。 ![](/assets/V6.118042601.png) * “组别名称”:用户自定义的名称 * “组类型”:节点属于的组类型,类型包括节点组,规则组
PHP
UTF-8
4,829
2.609375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: 0300962 * Date: 06-Apr-18 * Time: 3:43 PM */ if (session_status() === PHP_SESSION_NONE) { session_start(); } ?> <html lang="en"> <head> <link rel="stylesheet" href = "CSS/message.css" type="text/css"> <script> function changemsg(event, threadNo) { //Used to flick between messaging threads var msgtab, msgpane; //Clears all open tabs msgpane = document.getElementsByClassName("threadContainer"); for (var i=0; i < msgpane.length; i++) { msgpane[i].style.display = "none"; } //Sets all tabs as inactive msgtab = document.getElementsByClassName("msgtab"); for (var j=0; j < msgtab.length; j++) { msgtab[j].className =msgtab[j].className.replace(" active", ""); } //Sets message thread to be visible and tab active document.getElementById(threadNo).style.display = "block"; event.currentTarget.className += " active"; } </script> </head> <body> <div class = "container" id="links"> <?php /* Have to check for login status */ if(isset($_SESSION['logged-in']) && ($_SESSION['logged-in'] == TRUE)){ include_once 'Scripts/connection.php'; /* Gets list of projects that user is associated with */ $sql = "SELECT DISTINCT P.projectNo as projectNo, P.name as name FROM Messages M, Projects P WHERE M.projectNo = P.projectNo AND (fromUserNo = {$_SESSION['userno']} OR toUserNo = {$_SESSION['userno']})"; $result = mysqli_query($dbcon, $sql); $projects = array(); while ($row = mysqli_fetch_array($result)) { /* Creates navigation button for each project thread */ echo "<div class='threadTitle'><div id='button{$row['projectNo']}' class='msgtab' onclick='changemsg(event, {$row['projectNo']})'>{$row['name']}</div></div>"; $projects[] = $row['projectNo']; /* Logs each project number user is associated with */ } echo "</div><div class = 'container'>"; if (count($projects) == 0) { /* Placeholder for no messages found */ echo "<br/><div class='error_box'>You have no messages! Users must be associated with a project in order to send messages.</div><br/>"; } foreach ($projects as $no => $pno) { /* Populates message threads with messages, newest at the top. */ /* Gets message content */ $sql = "SELECT * FROM Messages WHERE projectNo = {$pno} AND (fromUserNo = {$_SESSION['userno']} OR toUserNo = {$_SESSION['userno']} ) ORDER BY projectNo ASC, msgDate DESC, messageNo DESC"; $result = mysqli_query($dbcon, $sql); $tabNo = 0; /* New message form */ echo "<div class='threadContainer' id='{$pno}'>"; echo "<form name='message{$pno}' action='Scripts/messaging.php?project={$pno}' method='post'>"; echo "<textarea title='message' name='message' rows='5' cols='60' maxlength='500'></textarea><br/>"; echo "<input name='submit' type='submit' value='Send!'></form><br/>"; /* Threaded message display */ echo "<div class='messages'>"; while ($row = mysqli_fetch_array($result)) { $tabNo = $row['projectNo']; if ($row['fromUserNo'] == $_SESSION['userno']) { /* Sets position & colour of messages */ echo "<div class='rhs'>"; echo "<h4>Sent {$row['msgDate']}</h4>"; } else { echo "<div class='lhs'>"; echo "<h4>Received {$row['msgDate']}</h4>"; } echo "<p>{$row['message']}</p>"; echo "</div>"; } echo "</div></div>"; } if(isset($_GET['project'])) { /* User is coming from a project 'Contact' button */ /* Clicks the tab for the selected message thread */ echo "<script> document.getElementById('button{$_GET['project']}').click(); </script>"; } else { if (count($projects) != 0) { /* Clicks the first tab in the list by default, if there are messages */ echo "<script> document.getElementById('button{$projects[0]}').click(); </script>"; } } } else { /* Unauthorised access */ echo "<div class='error_box'>Error - User must be logged-in to use messaging!<br/></div></div>"; } ?>
Go
UTF-8
1,230
2.9375
3
[ "BSD-2-Clause" ]
permissive
package gorest import ( "encoding/json" "github.com/dimonrus/porterr" "net/http" ) // New Json Response without error func NewOkJsonResponse(message interface{}, data interface{}, meta interface{}) *JsonResponse { return &JsonResponse{HttpCode: http.StatusOK, Message: message, Data: data, Meta: meta} } // New Json Response with error func NewErrorJsonResponse(e porterr.IError) *JsonResponse { httpCode := http.StatusInternalServerError if e.GetHTTP() >= http.StatusBadRequest && e.GetHTTP() <= http.StatusNetworkAuthenticationRequired { httpCode = e.GetHTTP() } return &JsonResponse{HttpCode: httpCode, Error: e} } // Send response to client func Send(writer http.ResponseWriter, response *JsonResponse) { SendJson(writer, response.HttpCode, response) } // Sent json into http writer func SendJson(writer http.ResponseWriter, httpCode int, data interface{}) { writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(httpCode) if data == nil { return } body, err := json.Marshal(data) if err != nil { _, err := writer.Write([]byte("JSON marshal failed: " + err.Error())) if err != nil { panic(err) } return } _, err = writer.Write(body) if err != nil { panic(err) } }
Java
UTF-8
2,099
2.828125
3
[]
no_license
package com.kingschan.blog.common.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; //import org.aspectj.lang.annotation.Aspect; //import org.springframework.stereotype.Component; /** * * <pre> * 类名称:ErrorLogAdvice * 类描述: * 创建人:陈国祥 (kingschan) * 创建时间:2015-4-8 下午7:47:01 * 修改人:Administrator * 修改时间:2015-4-8 下午7:47:01 * 修改备注: * @version V1.0 * </pre> */ //@Component("ErrorLogAdvice") //@Aspect public class ErrorLogAdvice { // @Before("execution(* com.kingschan.blog..*.*(..))") public void before(){ System.out.println("@before"); } /** * 目标方法正常完成后,会被调用 * @param args 目录方法的返回值 */ // @AfterReturning(returning="args",pointcut="execution(* com.kingschan.blog..*.*(..))") public void AfterReturning(Object args){ System.out.println("@AfterReturning 获取目录方法返回值:"+args); System.out.println(""); } // @AfterThrowing(throwing="ex",pointcut="execution(* com.kingschan.blog..*.*(..))") public void AfterThrowing(JoinPoint joinPoint,Throwable ex){ System.out.println("目标方法抛出的异常@AfterThrowing:"+ex); } /** * 与@AfterReturning的区别 * 不管方法是否正常结束它都会调用 */ // @After("execution(* com.kingschan.blog..*.*(..))") public void after(){ System.out.println("@after"); } /** * 可以决定方法在何时执行,甚至可以完全阻止目标方法执行 * @throws Throwable */ // @Around("execution(* com.kingschan.blog..*.*(..))") public Object around(ProceedingJoinPoint jp) throws Throwable{ System.out.println(String.format("@Around:参数:%s | 目标%s | getthis:%s", jp.getArgs().toString(),jp.getTarget().getClass().getName(),jp.getThis())); Object o =jp.proceed(); //jp.proceed(xxx); 还可以改变参数 return o; } }
C#
UTF-8
492
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace MarsRoverLibrary { public class SurfaceFactory { public static ISurface CreateSurface(string Coordinates) { Validation.ValidateCoordinates(Coordinates); string[] coordinates = Coordinates.Split(' '); int x = Convert.ToInt32(coordinates[0]); int y = Convert.ToInt32(coordinates[1]); return new Surface(x, y); } } }
Java
UTF-8
148
1.664063
2
[ "Apache-2.0" ]
permissive
package com.elepy.describers.props; import com.elepy.describers.Property; public interface PropertyConfig { void config(Property property); }
C#
UTF-8
1,237
2.578125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AskTheCode.Common; namespace AskTheCode.ControlFlowGraphs.Cli { internal struct BuildNodeId : IOrdinalId<BuildNodeId> { private readonly int value; #if DEBUG private readonly bool isValid; #endif public BuildNodeId(int value) { this.value = value; #if DEBUG this.isValid = true; #endif } public bool IsValid { get { #if DEBUG return this.isValid; #else return true; #endif } } public int Value { get { return this.value; } } public bool Equals(BuildNodeId other) { return this.Value == other.Value; } internal class Provider : IIdProvider<BuildNodeId> { private OrdinalIdValueGenerator valueGenerator = new OrdinalIdValueGenerator(); public BuildNodeId GenerateNewId() { int id = this.valueGenerator.GenerateNextIdValue(); return new BuildNodeId(id); } } } }
Java
UTF-8
1,095
2.1875
2
[]
no_license
package pl.testeroprogramowania.pages; import net.serenitybdd.core.Serenity; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.pages.PageObject; public class MyAccountPage extends PageObject { @FindBy(id = "reg_email") private WebElementFacade regEmailInput; @FindBy(id = "reg_password") private WebElementFacade regPasswordInput; @FindBy(name = "register") private WebElementFacade registerButton; @FindBy(xpath = "//ul[@class='woocommerce-error']//li") private WebElementFacade errorMessage; public void registerUser(String email, String password) { regEmailInput.type(email); Serenity.takeScreenshot(); Serenity.recordReportData().withTitle("Email and Password").andContents(email + " and " + password); withAction().moveToElement(registerButton).build().perform(); regPasswordInput.typeAndEnter(password); } public void checkErrorMessage(String message) { errorMessage.shouldContainText(message); } }
Java
UTF-8
9,351
2.375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package InterfazGrafica; import java.awt.Toolkit; /** * * @author Luis Vasquez */ public class crearEstudiante extends javax.swing.JFrame { /** * Creates new form crearEstudiante */ public crearEstudiante() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("NombreEstudiante:"); jLabel2.setText("ApellidoEstudiante:"); jLabel3.setText("Matricula:"); jLabel4.setText("Semestre de Ingreso:"); jButton1.setText("Aceptar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField1KeyTyped(evt); } }); jTextField2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField2KeyTyped(evt); } }); jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } }); jTextField3.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField3KeyTyped(evt); } }); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup() .addGap(154, 154, 154) .addComponent(jButton1))) .addContainerGap(89, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(jButton1) .addContainerGap(90, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField3ActionPerformed private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped // TODO add your handling code here: if(jt1>10){ evt.consume(); }else if(!(Character.isLetter(evt.getKeyChar()))){ evt.consume(); Toolkit.getDefaultToolkit().beep(); }else{ jt1++; } }//GEN-LAST:event_jTextField1KeyTyped private void jTextField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyTyped // TODO add your handling code here: if(jt2>10){ evt.consume(); }else if(!(Character.isLetter(evt.getKeyChar()))){ evt.consume(); Toolkit.getDefaultToolkit().beep(); }else{ jt2++; } }//GEN-LAST:event_jTextField2KeyTyped private void jTextField3KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField3KeyTyped // TODO add your handling code here: if(jt3>10){ evt.consume(); }else if(!(Character.isDigit(evt.getKeyChar()))){ evt.consume(); Toolkit.getDefaultToolkit().beep(); }else{ jt3++; } }//GEN-LAST:event_jTextField3KeyTyped int jt1=0; int jt2=0; int jt3=0; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables }
JavaScript
UTF-8
821
2.703125
3
[]
no_license
import React from 'react'; class Form2Information extends React.Component { render() { let nameValueArray = []; for (let i = 0; i < this.props.numCategories; i++) { nameValueArray.push(<NameValueField key={i}/>); } return ( <div className="information__form2"> <h2>Enter the name of the first Category, followed by a comma and space, and finally the value of the Category:</h2> {nameValueArray} </div> ) } } class NameValueField extends React.Component { render() { return( <> <div className="information__id"> <label htmlFor="chartID">ID, value: </label> <input type="text" name="chartID" id="chartID" required></input> </div> </> ) } } export default Form2Information;
Markdown
UTF-8
1,696
2.75
3
[ "MIT" ]
permissive
# Ansible Role: artifactory_exporter ## Description Deploy prometheus [artifactory_exporter](https://github.com/peimanja/artifactory_exporter) using ansible. ## Requirements - Ansible >= 2.9 (It might work on previous versions, but we cannot guarantee it) ## Role Variables All variables which can be overridden are stored in [defaults/main.yml](defaults/main.yml) file as well as in table below. | Name | Default Value | Description | | -------------- | ------------- | -----------------------------------| | `artifactory_exporter_version` | 0.5.1 | artifactory_exporter package version | | `artifactory_exporter_web_listen_address` | "0.0.0.0:9531" | Address on which artifactory_exporter will listen | | `artifactory_scrape_uri` | http://localhost:8081/artifactory | URI of the Artifactory instance | | `artifactory_auth` | basic | Authentication method to use [basic|token] | | `artifactory_user` | prometheus | User to access Artifactory (artifactory_auth=basic) | | `artifactory_password` | 'ChangeMe' | Password of the user accessing Artifactory (artifactory_auth=basic) | | `artifactory_bearer_token` | xxxxxxxxxxxxxxxxxxxxx | Access token for accessing Artifactory (artifactory_auth=token) | | `artifactory_ssl_verify` | false | Verify SSL certificate if HTTPS is used | | `artifactory_timeout` | 5s | Scrap Timeout | | `artifactory_exporter_config_flags_extra` | {} | Additional configuration flags passed at startup to artifactory_exporter binary | ## Example ### Playbook Use it in a playbook as follows: ```yaml - hosts: all roles: - artifactory_exporter vars: artifactory_scrape_uri: http://artifactory.example.com:8080 ```
Java
UTF-8
4,441
2.0625
2
[]
no_license
package com.drore.controller; import com.alibaba.fastjson.JSONObject; import com.drore.cloud.sdk.common.resp.RestMessage; import com.drore.cloud.sdk.domain.Pagination; import com.drore.cloud.sdk.util.LogbackLogger; import com.drore.model.LeaseInfo; import com.drore.service.LeaseService; import com.drore.util.JSONObjResult; import com.drore.util.PageUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * Created by wangl on 2017/8/31 0031. */ @Api(value = "招租-王璐") @RestController @RequestMapping("/cms/lease") public class LeaseController { @Autowired private LeaseService leaseService; @ApiOperation(value = "添加招租信息",notes = "添加招租信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "id",dataType = "string",required = false), @ApiImplicitParam(name = "title",value = "标题",dataType = "string",required = true), @ApiImplicitParam(name = "type",value = "类型",dataType = "string",required = true), @ApiImplicitParam(name = "contactTel",value = "联系方式",dataType = "string",required = true), @ApiImplicitParam(name = "themePic",value = "主图",dataType = "string",required = true), @ApiImplicitParam(name = "area",value = "面积",dataType = "double",required = true), @ApiImplicitParam(name = "price",value = "价格(万元/年)",dataType = "double",required = true), @ApiImplicitParam(name = "address",value = "地址",dataType = "string",required = true), @ApiImplicitParam(name = "latitude",value = "纬度",dataType = "string",required = true), @ApiImplicitParam(name = "longitude",value = "经度",dataType = "string",required = true), @ApiImplicitParam(name = "describes",value = "描述",dataType = "string",required = true), @ApiImplicitParam(name = "pics",value = "图集",dataType = "string",required = true), @ApiImplicitParam(name = "otherPrice",value = "价格(元/天)",dataType = "string",required = true) }) @PostMapping("/addOrUpdate") public JSONObject addLeasing(@Valid LeaseInfo leaseInfo){ RestMessage restMessage = leaseService.addOrUpdate(leaseInfo); return JSONObjResult.toJSONObj(restMessage); } @ApiOperation(value = "招租信息列表",notes = "招租信息列表") @ApiImplicitParams({ @ApiImplicitParam(name = "title",value = "标题",dataType = "string",required = true), @ApiImplicitParam(name = "startTime",value = "开始时间",dataType = "string",required = true), @ApiImplicitParam(name = "endTime",value = "结束时间",dataType = "string",required = true) }) @GetMapping("/leasingList") public JSONObject leasingList(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, @Valid LeaseInfo leaseInfo){ String logMsg = "分页查询"; LogbackLogger.info(logMsg); Pagination pagination = new Pagination(pageSize, pageNo); pagination = leaseService.leasingList(pagination, leaseInfo); return JSONObjResult.toJSONObj(new PageUtil(pagination), true, "查询成功"); } @ApiOperation(value = "详情",notes = "详情") @ApiImplicitParam(name = "id",value = "id",dataType = "string",required = true) @GetMapping("/detail") public JSONObject detail(String id){ RestMessage restMessage = leaseService.detail(id); return JSONObjResult.toJSONObj(restMessage); } @ApiOperation(value = "发布/撤下",notes = "发布/撤下") @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "id",dataType = "string",required = true), @ApiImplicitParam(name = "status",value = "Y/N",dataType = "string",required = true) }) @PostMapping("/setIsPublish") public JSONObject setIsPublish(String id,String status){ RestMessage restMessage = leaseService.setIsPublish(id,status); return JSONObjResult.toJSONObj(restMessage); } }
Python
UTF-8
2,197
3.15625
3
[]
no_license
import pandas as pd BASE_DIR = './data' # County_cd,State_nm,County_nm,2006,2007,2008,2009,2010,2011,2012 def fetch_data(): # Load the data to be processed file_name="{}/pills_sold_by_county_and_years.csv".format(BASE_DIR) data_set = pd.read_csv(file_name, sep=',',converters={'County_cd': lambda x: str(x), '2006': lambda x: convert_pills(x), '2007': lambda x: convert_pills(x), '2008': lambda x: convert_pills(x), '2009': lambda x: convert_pills(x), '2010': lambda x: convert_pills(x), '2011': lambda x: convert_pills(x), '2012': lambda x: convert_pills(x)}) print(data_set.columns) print("data_set (rows, columns) {}\n".format(data_set.shape)) print("data_set missing values \n{}\n".format(data_set.isnull().sum())) return data_set def convert_pills(x): ret_val=0 try: ret_val = int(float(x)) if ret_val < 0: ret_val = 0 except: pass print(ret_val) return ret_val # County_cd,State_nm,County_nm,2006,2007,2008,2009,2010,2011,2012 # county_id,State_nm,County_nm,avgerage_pills def clean_data(data_set): data_set['total'] = data_set['2006'] + \ data_set['2007'] + \ data_set['2008'] + \ data_set['2009'] + \ data_set['2010'] + \ data_set['2011'] + \ data_set['2012'] data_set['avgerage_pills'] = round(data_set['total'] / 7, 0) data_set = data_set.drop(['2006','2007','2008','2009','2010','2011','2012','total'], axis=1) return data_set if __name__=='__main__': data_set = fetch_data() data_set = clean_data(data_set) file_name = "{}/pills_per_person_average_2006_2012.csv".format(BASE_DIR) data_set.to_csv(file_name, index=None, header=True)
PHP
UTF-8
478
2.578125
3
[]
no_license
<?php /** * Articles Models */ class ArticleCategories extends Eloquent { /** * @var array */ protected $fillable = array('id', 'parent_id', 'title', 'main_image', 'description', 'keywords', 'permalink'); /** * The database table used by the model. * * @var string */ protected $table = 'article_categories'; public function subcategories() { return $this->belongsTo('ArticleCategories', 'parent_id'); } }
JavaScript
UTF-8
2,967
2.765625
3
[]
no_license
//Dependencies var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var exphbs = require('express-handlebars'); const mongoose = require('mongoose'); var request = require('request'); var morgan = require('morgan'); var axios = require('axios'); var cheerio = require('cheerio'); var PORT = process.env.PORT || 3000; var Article = require('./models/Articles.js'); require('./public/app.js'); require('dotenv').config(); // log every request to the console app.use(morgan('dev')); mongoose.connect('mongodb://localhost/my_database'); // setting handlebars app.engine('handlebars', exphbs({ defaultLayout: 'main' })); app.set('view engine', 'handlebars'); // Use body-parser for handling form submissions app.use(bodyParser.urlencoded({ extended: false })); // Use express.static to serve the public folder as a static directory app.use(express.static("/public")); // If deployed, use the deployed database. Otherwise use the local mongoHeadlines database var MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/mongoHeadlines"; // Set mongoose to leverage built in JavaScript ES6 Promises // Connect to the Mongo DB mongoose.Promise = Promise; mongoose.connect(MONGODB_URI, { useMongoClient: true }); var db = mongoose.connection; //render handlebars page app.get('/', (req, res) => { res.render('index.handlebars'); console.log('working'); }); // Show any mongoose errors db.on("error", (error) => { console.log("Mongoose Error: ", error); }); // Once logged in to the db through mongoose, log a success message db.once("open", () => { console.log("Mongoose connection successful.", db); }); //function for scraping the website for articles app.get("/scrape", (req, res) => { axios.get("http://www.latimes.com/").then((response) => { var $ = cheerio.load(response.data); $('article h2').each((i, element) => { var result = {}; result.title = $(this) .children('a') .text(); result.summary = $(this) .children('a') .text(); result.link = $(this) .children('a') .attr('href'); db.Article.create(result).then ((dbArticle) => { console.log(dbArticle); }) .catch((err) => { return res.json(err); }); }); res.send('complete'); }); }); //function for getting articles from db app.get("/articles", (req, res) => { db.Article.find({}) .then(function(dbArticle) { // If we were able to successfully find Articles, send them back to the client res.json(dbArticle); }) .catch(function(err) { res.json(err); }); }); // server listener app.listen(PORT, function () { console.log("App listening on PORT " + PORT); });
Swift
UTF-8
2,435
2.84375
3
[]
no_license
// // AddOrderViewController.swift // CoffeeOrderApp // // Created by Veldanov, Anton on 9/17/20. // import UIKit class AddOrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private var viewModel = AddCoffeeOrderViewModel() private var coffeeSizesSegmentedControl: UISegmentedControl! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() setupUI() } private func setupUI(){ coffeeSizesSegmentedControl = UISegmentedControl(items: viewModel.sizes) coffeeSizesSegmentedControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(coffeeSizesSegmentedControl) coffeeSizesSegmentedControl.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: 20).isActive = true coffeeSizesSegmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.types.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CoffeeOrderTypeTableViewCell", for: indexPath) cell.textLabel?.text = viewModel.types[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.accessoryType = .none } @IBAction func save(){ let name = nameTextField.text let email = emailTextField.text let coffeeSize = coffeeSizesSegmentedControl.titleForSegment(at: coffeeSizesSegmentedControl.selectedSegmentIndex) guard let indexPath = tableView.indexPathForSelectedRow else { fatalError("Error in selecting coffee") } viewModel.name = name viewModel.email = email viewModel.selectedSize = coffeeSize viewModel.selectedType = viewModel.types[indexPath.row] } }
JavaScript
UTF-8
6,087
3.03125
3
[]
no_license
var scores =[0,0]; var roundscore = 0; var activePlayer = 0; var dice; var gameplaying=true; var store =0; //document.querySelector('#current-'+ activePlayer).textContent = dice; document.querySelector('.dice').style.display = 'none'; document.getElementById('score-0').textContent = '0'; document.getElementById('score-1').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; function btn(){ if(gameplaying) { dice=Math.floor(Math.random()*6)+1; //display var diceDom=document.querySelector('.dice'); diceDom.style.display='block'; if(dice== 1){ diceDom.src='dice-'+ dice+ '.png'; //next player roundscore=0; if(activePlayer ==0) { document.querySelector('#current-'+ activePlayer).textContent = roundscore; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); activePlayer =1; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); } else{ document.querySelector('#current-'+ activePlayer).textContent = roundscore; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); activePlayer = 0; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); } roundscore=0; store=0; } else{ diceDom.src='dice-'+ dice+ '.jpg'; //add score roundscore+=dice; if(dice==6 && store==6) { roundscore=0; if(activePlayer ==0) { document.querySelector('#current-'+ activePlayer).textContent = roundscore; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); activePlayer =1; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); } else{ document.querySelector('#current-'+ activePlayer).textContent = roundscore; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); activePlayer = 0; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); } } document.querySelector('#current-'+ activePlayer).textContent = roundscore; } store = roundscore; // round score if only v not rolled a one } } function btn2(){ if(activePlayer ==0) { scores[0]+=roundscore; roundscore=0; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); document.querySelector('#current-'+ activePlayer).textContent = roundscore; if(scores[activePlayer]>=20) { document.querySelector('#name-'+ activePlayer).textContent= 'WINNER !!!!'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner'); document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active'); document.getElementById('score-0').textContent= scores[0]; gameplaying=false; } else { activePlayer =1; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); document.getElementById('score-0').textContent= scores[0]; } } else{ // This is a great project. scores[1]+=roundscore; roundscore=0; document.querySelector('.player-'+ activePlayer +'-panel').classList.remove('active'); document.querySelector('#current-'+ activePlayer).textContent = roundscore; if(scores[activePlayer]>=20) { document.querySelector('#name-'+ activePlayer).textContent= 'WINNER !!!!'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner'); document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active'); document.getElementById('score-1').textContent= scores[1]; gameplaying=false; } else{ activePlayer = 0; document.querySelector('.player-'+ activePlayer +'-panel').classList.add('active'); document.getElementById('score-1').textContent= scores[1]; } } } function btn3(){ scores=[0,0]; roundscore=0; activePlayer = 0; document.querySelector('#current-'+ 0).textContent = '0'; document.querySelector('#current-'+ 1).textContent = '0'; document.getElementById('score-0').textContent= '0'; document.getElementById('score-1').textContent= '0'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-'+ 0 +'-panel').classList.add('active'); document.querySelector('.player-'+ 1 +'-panel').classList.remove('active'); document.querySelector('#name-'+ 0).textContent= 'Player 1'; document.querySelector('#name-'+ 1).textContent= 'Player 2'; document.querySelector('.player-0-panel').classList.remove('winner'); document.querySelector('.player-1-panel').classList.remove('winner'); document.querySelector('.player-0-panel').classList.add('active'); gameplaying=true; } document.querySelector('.btn-hold').addEventListener('click',btn2); document.querySelector('.btn-roll').addEventListener('click',btn); document.querySelector('.btn-new').addEventListener('click',btn3);
PHP
UTF-8
967
3.40625
3
[]
no_license
<?php //Gestion de la connexion à la base Class ConnectionFactory { public static $cnx; //--------------------------------------------------------- /* méthode reçoit un tableau contenant les paramètres de connexion, établit cette connexion en créant un objet PDO, stocke cet objet dans une variable statique et la retourne en résultat. */ public static function makeConnection($config) { $init = parse_ini_file($config); $serveur = $init["host"]; $base = $init["name"]; $user = $init["user"]; $pass = $init["pass"]; $type = $init["type"]; $dsn = "$type:host=$serveur;dbname=$base"; $db = new \PDO($dsn,$user,$pass); self::$cnx = $db; return self::$cnx; } //--------------------------------------------------------- /* méthode retourne le contenu de la variable statique */ public static function getConnection(){ return self::$cnx; } //--------------------------------------------------------- }
SQL
UTF-8
2,093
3.78125
4
[ "Apache-2.0" ]
permissive
create database lowcode; use lowcode; -- ------------------------------------------------ -- 基本权限配置表 -- ------------------------------------------------ create table user ( id int unsigned auto_increment comment '自增主键' primary key, user_id varchar(32) not null comment '用户标识', user_name varchar(32) not null comment '用户名称', remark varchar(64) not null comment '用户描述', status varchar(1) not null default 'S' comment '用户状态', app_name varchar(64) not null default 'system' comment '应用名称', operator_name varchar(64) not null default 'system' comment '操作员名称', create_time timestamp default CURRENT_TIMESTAMP not null comment '创建时间戳', update_time timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间戳' ) comment '用户表' ENGINE=Innodb default charset=UTF8 auto_increment=1; create unique index uk_user_id on user (app_name, user_id) comment '标识索引'; -- ------------------------------------------------ -- 枚举映射表 -- ------------------------------------------------ create table lc_enum_mapping ( id int unsigned auto_increment comment '自增主键' primary key, table_name varchar(32) not null comment '表名称', column_name varchar(64) not null comment '字段名称', `key` varchar(64) not null comment '字段编码', label varchar(64) not null comment '字段显示', create_time timestamp default CURRENT_TIMESTAMP not null comment '创建时间戳', update_time timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间戳' ) comment '枚举映射表' ENGINE=Innodb default charset=UTF8 auto_increment=1; create unique index ix_lc_enum_mapping on lc_enum_mapping (table_name, column_name, `key`) comment '标识索引'; insert into lc_enum_mapping (table_name, column_name, `key`, label) values ('user', 'status', 'S', '正常'); insert into lc_enum_mapping (table_name, column_name, `key`, label) values ('user', 'status', 'F', '失效');
Ruby
UTF-8
128
3.296875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) index = 0 a = [] while array[index] do puts a.push array[index] ** 2 index += 1 end a end
Python
UTF-8
551
4.25
4
[]
no_license
#La funcion input se utiliza cuando queremos interactuar con el usuario #se declara dos variables donde se le pide al usuario su nombre y su apellido nombre=input("Nombre:") apellidos=input("Apellidos:") #se concatena los dos valores str que otorga el usuario #declaramos otra variable donde se guardara el nombre y apellido para poder unirlos #"" son para otorgar un espacio nombreCompleto=nombre+" "+apellidos #.upper es utilizado para representar las variables en mayusculas nombreCompleto=nombreCompleto.upper() print(nombreCompleto)
Java
UTF-8
6,984
2.265625
2
[]
no_license
package com.sos.jitl.checkrunhistory; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import sos.util.SOSDate; public class JobHistoryHelper { public String getDuration(LocalDateTime parStart, LocalDateTime parEnd) { if (parStart == null || parEnd == null){ return ""; } Instant instant = parStart.toInstant(ZoneOffset.UTC); Date start = Date.from(instant); instant = parEnd.toInstant(ZoneOffset.UTC); Date end = Date.from(instant); if (start == null || end == null) { return ""; } else { Calendar cal_1 = new GregorianCalendar(); Calendar cal_2 = new GregorianCalendar(); cal_1.setTime(start); cal_2.setTime(end); long time = cal_2.getTime().getTime() - cal_1.getTime().getTime(); time /= 1000; long seconds = time % 60; time /= 60; long minutes = time % 60; time /= 60; long hours = time % 24; time /= 24; long days = time; Calendar calendar = GregorianCalendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, (int) hours); calendar.set(Calendar.MINUTE, (int) minutes); calendar.set(Calendar.SECOND, (int) seconds); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); String d = ""; if (days > 0) { d = String.format("%sd " + formatter.format(calendar.getTime()), days); } else { d = formatter.format(calendar.getTime()); } return d; } } public String getOrderId(String jobChainAndOrder) { return getParameter(jobChainAndOrder); } public String getJobChainName(String jobChainAndOrder) { return getMethodName(jobChainAndOrder); } public String getParameter(String p) { p = p.trim(); String s = ""; Pattern pattern = Pattern.compile("^.*\\(([^\\)]*)\\)$", Pattern.DOTALL + Pattern.MULTILINE); Matcher matcher = pattern.matcher(p); if (matcher.find()) { s = matcher.group(1).trim(); } return s; } public String getMethodName(String p) { p = p.trim(); String s = p; Pattern pattern = Pattern.compile("^([^\\(]*)\\(.*\\)$", Pattern.DOTALL + Pattern.MULTILINE); Matcher matcher = pattern.matcher(p); if (matcher.find()) { s = matcher.group(1).trim(); } return s.trim(); } protected boolean isAfter(LocalDateTime timeToTest, String time) { if (time.length() == 8) { time = "0:" + time; } if (timeToTest == null) { return false; } JobSchedulerCheckRunHistoryOptions options = new JobSchedulerCheckRunHistoryOptions(); options.start_time.setValue(time); ZonedDateTime zdt = ZonedDateTime.of(timeToTest, ZoneId.systemDefault()); GregorianCalendar cal = GregorianCalendar.from(zdt); DateTime limit = new DateTime(options.start_time.getDateObject()); DateTime ended = new DateTime(cal.getTime()); return limit.toLocalDateTime().isBefore(ended.toLocalDateTime()); } protected boolean isToday(LocalDateTime d) { LocalDateTime today = LocalDateTime.now(); if (d == null) { return false; } else { return today.getDayOfYear() == d.getDayOfYear(); } } public String getParameter(String defaultValue, String p) { String param = getParameter(p); if (param.isEmpty()) { param = defaultValue; } return param; } protected int big2int(BigInteger b) { if (b == null) { return -1; } else { return b.intValue(); } } protected LocalDateTime getDateFromString(String inDateTime) throws Exception { LocalDateTime dateResult = null; Date date = null; if (inDateTime != null) { if (inDateTime.endsWith("Z")) { DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'H:mm:ss.SSSZ"); DateTime dateTime = dateTimeFormatter.parseDateTime(inDateTime.replaceFirst("Z", "+00:00")); date = dateTime.toDate(); } else { date = SOSDate.getDate(inDateTime, SOSDate.dateTimeFormat); } dateResult = LocalDateTime.ofInstant(date.toInstant(), java.time.ZoneId.systemDefault()); return dateResult; } else { return null; } } public boolean isInTimeLimit(String timeLimit, String endTime) { if ("".equals(timeLimit)) { return true; } String localTimeLimit = timeLimit; if (!timeLimit.contains("..")) { localTimeLimit = ".." + localTimeLimit; } String from = localTimeLimit.replaceAll("^(.*)\\.\\..*$", "$1"); String to = localTimeLimit.replaceAll("^.*\\.\\.(.*)$", "$1"); if ("".equals(from)) { from = "00:00:00"; } if (from.length() == 8) { from = "0:" + from; } if (to.length() == 8) { to = "0:" + to; } JobSchedulerCheckRunHistoryOptions options = new JobSchedulerCheckRunHistoryOptions(); options.start_time.setValue(from); options.end_time.setValue(to); if ("".equals(to)) { DateTime fromDate = new DateTime(options.start_time.getDateObject()); DateTime ended = new DateTime(endTime); DateTime toDate = ended; return (ended.toLocalDateTime().isEqual(toDate.toLocalDateTime()) || ended.toLocalDateTime().isBefore(toDate.toLocalDateTime())) && (ended.toLocalDateTime().isEqual(fromDate.toLocalDateTime()) || ended.toLocalDateTime().isAfter(fromDate.toLocalDateTime())); } else { DateTime fromDate = new DateTime(options.start_time.getDateObject()); DateTime ended = new DateTime(endTime); DateTime toDate = new DateTime(options.end_time.getDateObject()); return (ended.toLocalDateTime().isEqual(toDate.toLocalDateTime()) || ended.toLocalDateTime().isBefore(toDate.toLocalDateTime())) && (ended.toLocalDateTime().isEqual(fromDate.toLocalDateTime()) || ended.toLocalDateTime().isAfter(fromDate.toLocalDateTime())); } } }
JavaScript
UTF-8
1,313
2.5625
3
[ "MIT" ]
permissive
const redis = require('./redis'); const R = require('ramda'); const KEY_PREFIX = 'games-'; const GAME_LIFETIME_MINS = 15; function getGameKey(key) { return KEY_PREFIX + key; } module.exports = function(app) { app.get('/games', function (req, res) { redis.keys(KEY_PREFIX + '*') .then(keys => Promise.all(keys.map(redis.get))) .then(result => res.status(200).json(result)) .catch(err => res.status(500).json({})); }) app.get('/games/:id', function (req, res) { redis.get(getGameKey(req.params.id)) .then(result => R.isNil(result) ? res.status(404).json({}) : res.status(200).json(result)) .catch(err => res.status(500).json({})); }) app.post('/games/:id', function (req, res) { const gameKey = (getGameKey(req.params.id)); redis.set(gameKey, req.body) .then(redis.expire(gameKey, GAME_LIFETIME_MINS)) .then(result => res.status(201).json(req.body)) .catch(err => res.status(500).json({})); }) app.put('/games/:id', function (req, res) { const gameKey = (getGameKey(req.params.id)); redis.set(gameKey, req.body) .then(redis.expire(gameKey, GAME_LIFETIME_MINS)) .then(result => res.status(200).json(result)) .catch(err => res.status(500).json({})); }); };
Java
UTF-8
527
1.8125
2
[]
no_license
package com.ssh.dao; import java.util.List; import com.ssh.model.Nav; public interface NavDAO { void save(Nav transientInstance); void delete(Nav persistentInstance); Nav findById(java.lang.Integer id); List<Nav> findByExample(Nav instance); List findByProperty(String propertyName, Object value); List<Nav> findByText(Object text); List<Nav> findByState(Object state); List<Nav> findByIconCls(Object iconCls); List<Nav> findByUrl(Object url); List<Nav> findByNid(Object nid); List findAll(int nid); }
Python
UTF-8
2,917
3.46875
3
[ "Apache-2.0" ]
permissive
import numpy import random from enum import Enum class Grid: def __init__(self, tuples=None): if tuples: self.grid = numpy.array(tuples) else: self.grid = numpy.zeros((4, 4)) def get_array(self): return self.grid def fill_random(self): empty_cells = [] for p, value in numpy.ndenumerate(self.grid): if value == 0: empty_cells.append(p) if empty_cells: cell = random.choice(empty_cells) if random.random() > 0.1: val = 2 else: val = 4 self.grid[cell] = val print("filled " + str(cell) + " to: " + str(val)) def shift(self, dir): size = len(self.grid) shifted_tiles = dict() merged = set() if dir == Direction.UP: for y in range(size): for x in range(size): dest = self.shift_tile(x, y, dir, merged) if dest: shifted_tiles[(x, y)] = dest elif dir == Direction.DOWN: for y in range(size): for x in range(size): dest = self.shift_tile(x, size - 1 - y, dir, merged) if dest: shifted_tiles[(x, size - 1 - y)] = dest elif dir == Direction.RIGHT: for x in range(size): for y in range(size): dest = self.shift_tile(size - 1 - x, y, dir, merged) if dest: shifted_tiles[(size - 1 - x, y)] = dest elif dir == Direction.LEFT: for x in range(size): for y in range(size): dest = self.shift_tile(x, y, dir, merged) if dest: shifted_tiles[(x, y)] = dest return shifted_tiles def shift_tile(self, x, y, dir, merged): curr_tile = self.grid[y][x] if curr_tile == 0: return prev = (x, y) next = (x + dir.value[0], y + dir.value[1]) while self.in_bounds(next[0], next[1]) and next not in merged: next_tile = self.grid[next[1]][next[0]] if next_tile == 0: prev = next next = (next[0] + dir.value[0], next[1] + dir.value[1]) elif next_tile != curr_tile: break elif next_tile == curr_tile: prev = next curr_tile *= 2 merged.add(prev) break if (x, y) != prev: self.grid[prev[1]][prev[0]] = curr_tile self.grid[y][x] = 0 return prev else: return None def in_bounds(self, x, y): return x >= 0 and y >= 0 and x < self.grid.shape[1] and y < self.grid.shape[0] def __str__(self): return str(self.grid) class Direction(Enum): UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) if __name__ == "__main__": grid = Grid([ (0, 0, 16, 0), (0, 8, 0, 0), (0, 0, 0, 0), (0, 0, 16, 0) ]) print(grid) print(grid.shift(Direction.DOWN)) print(grid.fill_random()) print(grid.fill_random()) print(grid.fill_random()) print(grid.fill_random()) print(grid.fill_random()) print(grid.fill_random()) print(grid)
PHP
UTF-8
2,170
2.796875
3
[]
no_license
<?php // Name: Deep Patel // Date: 03/22/2015 // Class: CMSC331 // Project1: Allows COEIT students to make an individual or group appointment, // or cancel any or all of the previous appointments // // loggedIn.php: User Logged In successfully! // Now the user may manage the appointments by given tasks to perform // the tasks include: 1) make an individual appointment => redirects to individual.php // 2) make a group appointment => redirects to showDates.php // if the user has previously made an appointment then // 3) cancel an appointment => redirects to cancelAppointment.php // // The user still has options to: logout at anytime ==> redirects to logout.php ==> destroys session, cookies ==> automatically redirects to index.php // // // File Header! // //include the header of the page include("headersFooters/loggedInHeader.php"); //include the navigation bar include("navigation/navigationBar.php"); // File Body! ?> <div id="section"> <div id="taskBox"> <form action="?" name="appointment" id="appointment" method="POST"> <div class="student_info"> <fieldset> <div class="center"><div class="legendFont">Which of the following tasks would you like to perform?</div></div> <br> <table> <span class="error"><font color="red" size="2"><?php echo $error_msg; ?></font></span> <div id="radio"> <input type="radio" name="appointment" value="Individual">Make an individual appointment</input><br> <input type="radio" name="appointment" value="Group">Make a group appointment</input><br> <?php if($previous_appt == true) { ?> <input type="radio" name="appointment" value="Cancel">Cancel an appointment</input><br> <?php } ?> </div> </table> </fieldset> </div> <div id="taskButton"> <input type="submit" name="continue" id="continue" value="Continue" /> </div> </form> </div> </div> <?php // File Footer! //include the footer include("headersFooters/footer.php"); ?>
Python
UTF-8
8,895
3.046875
3
[ "MIT" ]
permissive
#!/usr/bin/env python """Utility and General purpose functions.""" import inspect import warnings import os import re import shatter.constants as cts __author__ = 'juan pablo isaza' def read_file(absolute_path): """ :param absolute_path: string path. :return: list with lines of the file. """ return [line.rstrip('\n') for line in open(absolute_path)] def delete_file(filename): """ :param filename: relative path to file. """ if os.path.exists(filename): os.remove(filename) return True return False def write_file(filename, the_list): """ :param filename: relative path to file. :param the_list: new file information. :return: void """ new_file = open(filename, 'a') for item in the_list: new_file.write("%s\n" % item) def rewrite_file(filename, the_list): """ Delete and write again :param filename: relative path to file. :param the_list: new file information. :return: void """ delete_file(filename) write_file(filename, the_list) def bit_in_string(string): """ Contains a bit in the string :param string: arbitrary string :return: boolean """ return ('0' in string) or ('1' in string) def string_has_bits_for_and(str_bits, index): """ Returns true if finds a bit, before and after index. :param index: int :param str_bits: string :return: boolean """ str_start = str_bits[:index] str_end = str_bits[index:] return index > 0 and bit_in_string(str_start) and bit_in_string(str_end) def from_bool_to_bit(boolean): """ Conversion from boolean to bit :param boolean: True or False :return: '1' or '0' """ if boolean: return "1" else: return "0" def get_function_path(f): """ Passes the internal func_code to a attribute called internal_code on the wrapper. Then we call the wrapper attribute which throws metadata of the internal function, and gets the path. :param f: function :return: path """ # does the wrapper is defining the new attribute, to expose internal func_code? or use std func_code if no decorator code = f.internal_code if hasattr(f, cts.INTERNAL_CODE) else f.__code__ return code.co_filename def valid_function(f): """ Validates function. Returns warning if it is not a function or it doesn't have a decorator. :param f: function :return: passes, raises warning or raises TypeError """ if not hasattr(f, '__call__'): raise TypeError('{} is not a valid function.'.format(f)) if not hasattr(f, cts.INTERNAL_CODE): warnings.warn('Function {} has no decorator, reading can be harder!!!'.format(f.__name__), UserWarning) return True def get_function_line_number(f, file_code): """ Returns first line number for decorated and un-decorated methods. -1 if not found. :param f: function. :param file_code: the code as a list where each element is a line. :return: the line of the file(starting in zero), 0 if not found! """ for index, line in enumerate(file_code): pattern = re.compile(cts.PARTICULAR_DEFINITION.pattern.format(name=f.__name__)) definition = re.search(pattern, line) if definition: return index return -1 def get_function_inputs(f): """ Given function signatures gets the name of the function. :param f: a callable function :return: input names on a tuple. """ if hasattr(f, cts.INTERNAL_PARAMETERS): # 'internal_parameters' is defined inside the solver() annotation, see solver.py for details. return f.internal_parameters else: return f.__code__.co_varnames def get_function_code(start, file_code): """ Gets the source code of function. Opt for not using inspect package because it doesn't work with decorators :param start: the starting line number, of the function :param file_code: the source file lines :return: code. """ def not_space_nor_comment(line): return len(line.strip()) > 0 and line.strip()[0] != '#' def inside_function(line_indent, f_indent): return len(line_indent) > len(f_indent) + 3 base_indent = re.search(cts.INDENT, file_code[start]).group() end = start for index, l in enumerate(file_code[start + 1:]): l_indent = re.search(cts.INDENT, l).group() # decides if adding to function is required: no black space or comment if not_space_nor_comment(l): if inside_function(l_indent, base_indent): end = index + start + 2 # only add code if non-comment or empty spaces are inside function else: # end of function if found lower indent that is not a blank space and not a comment break return file_code[start:end] def var_is_true(var): """ Returns True if var= True, else False. Remember here that 1 is a almost True value but in this case should return False. :param var: any variable. :return: boolean """ return var and isinstance(var, bool) def var_is_false(var): """ Returns True if var = False, else False. Remember here that 1 is a almost True value but in this case should return False. :param var: any variable. :return: boolean """ return not var and isinstance(var, bool) def has_true_key(d): """ Returns True only if it has a True value as key. Has to be done this way because Python confuses '0' and '1' with False and True. :param d: dict() :return: boolean """ for key in d: if var_is_true(key): return True return False def has_return(implementation, definition): """ Finds if the implementation already has a return. :param implementation: array with code implementation :param definition: function definition :return: Boolean """ last_line = implementation[-1] indent = get_indent_from_definition(definition) pattern = r"^{indent} return".format(indent=indent) return re.search(pattern, last_line) is not None def has_false_key(d): """ Returns True only if it has a False value as key. Has to be done this way because Python confuses '0' and '1' with False and True. :param d: dict() :return: boolean """ for key in d: if var_is_false(key): return True return False def var_is_1(var): """ Boolean if var is equal to 1 and not True. :param var: variable :return: boolean """ if var and not isinstance(var, bool): return True return False def var_is_0(var): """ Boolean if var is equal to 0 and not False. :param var: variable :return: boolean """ if not var and not isinstance(var, bool): return True return False def get_indent_from_definition(definition): """ Uses regex to get the indent :param definition: of a function :return: indent as string """ return re.search(cts.INDENT, definition).group() def is_function(f): """ Is it a function? :param f: function :return: boolean """ return hasattr(f, '__call__') def remove_list_from_list(all_list, list_to_remove): """ :param all_list: original list :param list_to_remove: elements that will be removed from the original list. :return: subtracted list """ return [value for value in all_list if value not in list_to_remove] def is_private_call(): """ Searches in the stack for places where the package is. If there is something then the function is being called privately from inside the package, otherwise it is called from outside the package. :return: boolean """ p_name = '/{}/'.format(cts.PACKAGE_NAME) p = re.match(r'^.*' + p_name, inspect.stack()[0].filename).group() # the number 2 in 'inspect.stack()[2:]' is because we are not looking inside is_private_call() function nor one # level above it, where its suppose to tell us if that function is being called privately or publicly. return any(re.match(p, frame.filename) is not None for frame in inspect.stack()[2:]) def name_in_frame(var, frame): """ Looks at the locals of the frame and searches in it for var. :param var: variable to get name from. :param frame: a inspect frame :return: list with strings. """ callers_local_vars = frame.f_locals.items() return [var_name for var_name, var_val in callers_local_vars if var_val is var] def retrieve_name(var): """ Gets the name of var. Does it from the out most frame inner-wards. :param var: variable to get name from. :return: string """ for fi in reversed(inspect.stack()): names = name_in_frame(var, fi.frame) if len(names) > 0: return names[0]
C++
UTF-8
663
3.125
3
[]
no_license
#include<iostream> using namespace std; int &test (int arr[],int &position){ int data= arr[position]; //position = position +1; return arr[position]; } void test1 (int *p){ cout<<*p<<endl; *p=40; } int main(){ int a=10; int &b=a; int *c=&a; *c=20; int **pp=&c; int ***ppp=&pp; cout<<*pp<<endl; cout<<&a<<endl; cout<<**ppp<<endl; return 0; int arr[10]={0,1,2,3,4,5,6,7}; int *p=arr; cout<<*(p+3)<<endl; cout<<p[3]<<endl; test1(c); cout<<*c<<endl; /*int d=arr[3]; cout<<d<<endl; int pos=4; int &d1=test(arr,pos); d1=12; cout<<arr[4]<<endl;*/ }
Java
GB18030
16,982
2.140625
2
[]
no_license
package db_12306.gui; import java.io.IOException; import java.sql.SQLException; import db_12306.db_operation_update.DatabaseOperation; import db_12306.gui.view.AdministratorPageController; import db_12306.gui.view.LoginviewController; import db_12306.gui.view.NormalUserPageController; import db_12306.gui.view.SignUpController; import db_12306.gui.view.BuyTicket.BuyTicketviewController; import db_12306.gui.view.BuyTicket.TravelRecommendviewController; import db_12306.gui.view.ModifyStation.ModifyStationviewController; import db_12306.gui.view.OperateTrain.DeleteTrainviewController; import db_12306.gui.view.OperateTrain.InsertTrainviewController; import db_12306.gui.view.OperateTrain.OperateTrainviewController; import db_12306.gui.view.OrderQueryandRefund.OrderQueryviewController; import db_12306.gui.view.Query.QueryviewController; import db_12306.gui.view.Query.StationQueryviewController; import db_12306.gui.view.Query.TrainNumberviewController; import db_12306.gui.view.Query.TrainStopStationviewController; import db_12306.gui.view.UserInfoModify.UserInfoModifyviewController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.stage.Modality; import javafx.stage.Stage; public class MainApp extends Application { private Stage primaryStage; private BorderPane rootLayout; public String currentaccount; DatabaseOperation d; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { d = new DatabaseOperation(); this.primaryStage = primaryStage; this.primaryStage.setTitle("12306"); this.primaryStage.getIcons().add(new Image("file:resources/images/icon.png")); initRootLayout(); showLoginview(); } public Stage getPrimaryStage() { return primaryStage; } public void initRootLayout() { try { // Load root layout from fxml file. FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml")); rootLayout = (BorderPane) loader.load(); // Show the scene containing the root layout. Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); primaryStage.show(); } catch (IOException e) { e.printStackTrace(); } } public void showLoginview() { try { //load view FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/Loginview.fxml")); AnchorPane Loginview = (AnchorPane) loader.load(); // Set stage rootLayout.setCenter(Loginview); //set controller LoginviewController controller = loader.getController(); controller.setMainApp(this); controller.setDatabasePOperation(d); } catch (IOException e) { e.printStackTrace(); } } public void showSignUpview() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/SignUpview.fxml")); AnchorPane page = (AnchorPane) loader.load(); Stage signupStage = new Stage(); signupStage.setTitle("12306-ע"); signupStage.initModality(Modality.WINDOW_MODAL); signupStage.initOwner(primaryStage); signupStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(page); signupStage.setScene(scene); SignUpController controller = loader.getController(); controller.setDialogStage(signupStage); controller.setDatabasePOperation(d); signupStage.showAndWait(); } public void showNormalUserPage() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/NormalUserPage.fxml")); AnchorPane NormalUserPage = (AnchorPane) loader.load(); rootLayout.setCenter(NormalUserPage); primaryStage.setTitle("12306"); NormalUserPageController controller = loader.getController(); controller.setMainApp(this); controller.changeAccountLabel(); } catch (IOException e) { e.printStackTrace(); } } public void showQueryview() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/Query/Queryview.fxml")); AnchorPane Queryview = (AnchorPane) loader.load(); Stage QueryviewStage = new Stage(); QueryviewStage.setTitle("12306-ѯ"); QueryviewStage.initModality(Modality.WINDOW_MODAL); QueryviewStage.initOwner(primaryStage); QueryviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(Queryview); QueryviewStage.setScene(scene); QueryviewController controller = loader.getController(); controller.setDialogStage(QueryviewStage); controller.setMainApp(this); QueryviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showStationQueryview(Stage iniOwner) { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/Query/StationQueryview.fxml")); AnchorPane page = (AnchorPane) loader.load(); Stage StationStage = new Stage(); StationStage.setTitle("12306-վѯ"); StationStage.initModality(Modality.WINDOW_MODAL); StationStage.initOwner(iniOwner); StationStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(page); StationStage.setScene(scene); StationQueryviewController controller = loader.getController(); controller.setDialogStage(StationStage); controller.setDatabasePOperation(d); StationStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showTrainNumberQueryview(Stage iniOwner) { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/Query/TrainNumberQueryview.fxml")); AnchorPane page = (AnchorPane) loader.load(); Stage TrainStage = new Stage(); TrainStage.setTitle("12306-гѯ"); TrainStage.initModality(Modality.WINDOW_MODAL); TrainStage.initOwner(iniOwner); TrainStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(page); TrainStage.setScene(scene); TrainNumberviewController controller = loader.getController(); controller.setDialogStage(TrainStage); controller.setDatabasePOperation(d); TrainStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showTrainStopStationQueryview(Stage iniOwner) { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/Query/TrainStopStationQueryview.fxml")); AnchorPane page = (AnchorPane) loader.load(); Stage TrainStage = new Stage(); TrainStage.setTitle("12306-гѯ"); TrainStage.initModality(Modality.WINDOW_MODAL); TrainStage.initOwner(iniOwner); TrainStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(page); TrainStage.setScene(scene); TrainStopStationviewController controller = loader.getController(); controller.setDialogStage(TrainStage); controller.setDatabasePOperation(d); TrainStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showBuyTicketview() throws NumberFormatException, SQLException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/BuyTicket/BuyTicketview.fxml")); AnchorPane BuyTicketview = (AnchorPane) loader.load(); Stage BuyTicketviewStage = new Stage(); BuyTicketviewStage.setTitle("12306-Ʊ"); BuyTicketviewStage.initModality(Modality.WINDOW_MODAL); BuyTicketviewStage.initOwner(primaryStage); BuyTicketviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(BuyTicketview); BuyTicketviewStage.setScene(scene); BuyTicketviewController controller = loader.getController(); controller.setDialogStage(BuyTicketviewStage); controller.setDatabasePOperation(d); controller.setuserID(currentaccount); controller.setMainApp(this); BuyTicketviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showTravelRecommendview(BuyTicketviewController b,String routine) throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/BuyTicket/TravelRecommendview.fxml")); AnchorPane TravelRecommendview = (AnchorPane) loader.load(); Stage TravelRecommendviewStage = new Stage(); TravelRecommendviewStage.setTitle("12306-Ʊ-гƼ"); TravelRecommendviewStage.initModality(Modality.WINDOW_MODAL); TravelRecommendviewStage.initOwner(primaryStage); TravelRecommendviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(TravelRecommendview); TravelRecommendviewStage.setScene(scene); TravelRecommendviewController controller = loader.getController(); controller.setDialogStage(TravelRecommendviewStage); controller.setDatabasePOperation(d); controller.setBuyTicket(b); controller.setroutine(routine); controller.setLabel(); TravelRecommendviewStage.showAndWait(); } public void showOrderQueryview() throws NumberFormatException, SQLException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/OrderQueryandRefund/OrderQueryview.fxml")); AnchorPane OrderQueryview = (AnchorPane) loader.load(); Stage OrderQueryviewStage = new Stage(); OrderQueryviewStage.setTitle("12306-ѯƱ"); OrderQueryviewStage.initModality(Modality.WINDOW_MODAL); OrderQueryviewStage.initOwner(primaryStage); OrderQueryviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(OrderQueryview); OrderQueryviewStage.setScene(scene); OrderQueryviewController controller = loader.getController(); controller.setDialogStage(OrderQueryviewStage); controller.setMainApp(this); controller.setDatabasePOperation(d); controller.setuserID(this); controller.showOrders(); OrderQueryviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showAdministratorPage() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/AdministratorPage.fxml")); AnchorPane AdministratorPage = (AnchorPane) loader.load(); rootLayout.setCenter(AdministratorPage); primaryStage.setTitle("12306Ա"); AdministratorPageController controller = loader.getController(); controller.setMainApp(this); controller.changeAccountLabel(); } catch (IOException e) { e.printStackTrace(); } } public void showModifyStationview() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/ModifyStation/ModifyStationview.fxml")); AnchorPane ModifyStation = (AnchorPane) loader.load(); Stage ModifyStationStage = new Stage(); ModifyStationStage.setTitle("12306-޸ijվϢԱ"); ModifyStationStage.initModality(Modality.WINDOW_MODAL); ModifyStationStage.initOwner(primaryStage); ModifyStationStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(ModifyStation); ModifyStationStage.setScene(scene); ModifyStationviewController controller = loader.getController(); controller.setDialogStage(ModifyStationStage); controller.setDatabasePOperation(d); ModifyStationStage.showAndWait(); } public void showOperateTrainview() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/OperateTrain/OperateTrainview.fxml")); AnchorPane OperateTrainview = (AnchorPane) loader.load(); Stage OperateTrainviewStage = new Stage(); OperateTrainviewStage.setTitle("12306-޸гϢԱ"); OperateTrainviewStage.initModality(Modality.WINDOW_MODAL); OperateTrainviewStage.initOwner(primaryStage); OperateTrainviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(OperateTrainview); OperateTrainviewStage.setScene(scene); OperateTrainviewController controller = loader.getController(); controller.setDialogStage(OperateTrainviewStage); controller.setMainApp(this); OperateTrainviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showInsertTrainview(Stage parentStage) { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/OperateTrain/InsertTrainview.fxml")); AnchorPane InsertTrainview = (AnchorPane) loader.load(); Stage InsertTrainviewStage = new Stage(); InsertTrainviewStage.setTitle("12306-޸гϢ-гԱ"); InsertTrainviewStage.initModality(Modality.WINDOW_MODAL); InsertTrainviewStage.initOwner(parentStage); InsertTrainviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(InsertTrainview); InsertTrainviewStage.setScene(scene); InsertTrainviewController controller = loader.getController(); controller.setDialogStage(InsertTrainviewStage); controller.setDatabasePOperation(d); InsertTrainviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showDeleteTrainview(Stage parentStage) { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/OperateTrain/DeleteTrainview.fxml")); AnchorPane DeleteTrainview = (AnchorPane) loader.load(); Stage DeleteTrainviewStage = new Stage(); DeleteTrainviewStage.setTitle("12306-޸гϢ-עгԱ"); DeleteTrainviewStage.initModality(Modality.WINDOW_MODAL); DeleteTrainviewStage.initOwner(parentStage); DeleteTrainviewStage.getIcons().add(new Image("file:resources/images/icon.png")); Scene scene = new Scene(DeleteTrainview); DeleteTrainviewStage.setScene(scene); DeleteTrainviewController controller = loader.getController(); controller.setDialogStage(DeleteTrainviewStage); controller.setDatabasePOperation(d); DeleteTrainviewStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void showUserInfoModifyview() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(MainApp.class.getResource("view/UserInfoModify/UserInfoModifyview.fxml")); AnchorPane UserInfoModifyview = (AnchorPane) loader.load(); rootLayout.setCenter(UserInfoModifyview); primaryStage.setTitle("12306-޸ûϢ"); UserInfoModifyviewController controller = loader.getController(); controller.setDatabasePOperation(d); controller.setMainApp(this); } }
Markdown
UTF-8
33,889
3.0625
3
[]
no_license
### Questions * ### Objectives YWBAT * compare and contrast the various methods for SVMs * implement SVMs using sklearn * use model analysis to tailor SVM ### Outline - Introduce dataset - Go through various svm models and their use case - Tweak SVMs to suit the problem ### What do SVMs do? SVMs (Support Vector Machines) are machine learning models that divide data by using 'support vectors' to create decision boundaries. The sensitivity (or lack thereof) of your boundaries depends on you. Low Sensitivity boundaries are often wide High Sensitivity boundaries are very narrow ### The 'Vector' Part of SVMs is the data. (x-values). ### When? Why? SVMs are great to use anytime you want decisions to be made by using boundaries. One example is finding points that are closest to the boundary and then using those points in your training set. Boundaries are very helpful for classification, but also helpful for finding training points. Build a model - classify new points and evaluate our classification - if points weren't classified correctly we took their distance from the mislabeled class boundary - add those points to our training set ```python import pandas as pd import numpy as np from sklearn.datasets import make_circles, make_blobs, make_moons from sklearn.svm import SVC, LinearSVC, NuSVC from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score, classification_report from sklearn.model_selection import train_test_split from mlxtend.plotting import plot_decision_regions import matplotlib.pyplot as plt import seaborn as sns ``` ```python def plot_groups(x, y): plt.figure(figsize=(8, 8)) plt.grid(linestyle='dashed') color_dict = {0: 'g', 1: 'purple'} colors = ['g' if l == 0 else 'purple' for l in y] plt.scatter(x[:, 0], x[:, 1], c=colors, s=60, alpha=0.5) plt.xlabel("X1") plt.ylabel("X2") plt.show() def plot_groups3(x, y): plt.figure(figsize=(8, 8)) plt.grid(linestyle='dashed') color_dict = {0: 'g', 1: 'purple', 2: 'yellow'} colors = [color_dict[l] for l in y] plt.scatter(x[:, 0], x[:, 1], c=colors, alpha=0.5, s=60) plt.xlabel("X1") plt.ylabel("X2") plt.show() def plot_svm_groups(x, y, clf): plt.figure(figsize=(8, 5)) plt.grid() plot_decision_regions(x, y, clf, colors='green,purple,yellow', scatter_kwargs={"s": 100, "alpha": 0.5}) plt.xlabel("X1") plt.ylabel("X2") plt.title("SVM Decision Boundary") plt.show() def print_report(ytrain, ytest, ytrain_pred, ytest_pred): report = classification_report(ytrain, ytrain_pred) print("Train Scores\n" + "-"*50) print(report) accuracy = accuracy_score(ytrain, ytrain_pred) print(f"Train Accuracy: {accuracy}") report = classification_report(ytest, ytest_pred) print("Test Scores\n" + "-"*50) print(report) accuracy = accuracy_score(ytest, ytest_pred) print(f"Test Accuracy: {accuracy}") ``` ## Linear SVM ![](images/svm-linear.png) ```python x, y = make_blobs(n_samples=500, n_features=2, centers=2, cluster_std=4.5) ``` ```python plot_groups(x, y) ``` ![png](lesson-plan_files/lesson-plan_9_0.png) ```python xtrain, xtest, ytrain, ytest = train_test_split(x, y) ``` # SVMs are a family of models * kernels * linear kernel * sigmoid kernel * polynomial kernel * rbf (radial basis function) * maps data into higher dimension ```python clf = LinearSVC() clf.fit(xtrain, ytrain) ``` /Users/rafael/anaconda3/envs/flatiron-env/lib/python3.6/site-packages/sklearn/svm/_base.py:947: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. "the number of iterations.", ConvergenceWarning) LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, intercept_scaling=1, loss='squared_hinge', max_iter=1000, multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, verbose=0) ```python plot_svm_groups(x, y, clf) ``` ![png](lesson-plan_files/lesson-plan_13_0.png) ```python clf = LinearSVC() clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` /Users/rafael/anaconda3/envs/flatiron-env/lib/python3.6/site-packages/sklearn/svm/_base.py:947: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. "the number of iterations.", ConvergenceWarning) ![png](lesson-plan_files/lesson-plan_14_1.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.95 0.95 0.95 185 1 0.95 0.95 0.95 190 accuracy 0.95 375 macro avg 0.95 0.95 0.95 375 weighted avg 0.95 0.95 0.95 375 Train Accuracy: 0.9493333333333334 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.97 0.94 0.95 65 1 0.94 0.97 0.95 60 accuracy 0.95 125 macro avg 0.95 0.95 0.95 125 weighted avg 0.95 0.95 0.95 125 Test Accuracy: 0.952 ```python clf = SVC(kernel='sigmoid') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_15_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.92 0.92 0.92 185 1 0.92 0.93 0.92 190 accuracy 0.92 375 macro avg 0.92 0.92 0.92 375 weighted avg 0.92 0.92 0.92 375 Train Accuracy: 0.9226666666666666 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.92 0.91 0.91 65 1 0.90 0.92 0.91 60 accuracy 0.91 125 macro avg 0.91 0.91 0.91 125 weighted avg 0.91 0.91 0.91 125 Test Accuracy: 0.912 ```python clf = SVC(kernel='poly') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_16_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.89 0.98 0.93 185 1 0.98 0.88 0.93 190 accuracy 0.93 375 macro avg 0.93 0.93 0.93 375 weighted avg 0.93 0.93 0.93 375 Train Accuracy: 0.928 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.94 0.97 0.95 65 1 0.97 0.93 0.95 60 accuracy 0.95 125 macro avg 0.95 0.95 0.95 125 weighted avg 0.95 0.95 0.95 125 Test Accuracy: 0.952 ### let's look at RBF (Radial Basis Function) - most popular svm - project your data into a higher dimension and separate it there ```python clf = SVC(kernel='rbf') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_18_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.95 0.95 0.95 185 1 0.95 0.95 0.95 190 accuracy 0.95 375 macro avg 0.95 0.95 0.95 375 weighted avg 0.95 0.95 0.95 375 Train Accuracy: 0.9493333333333334 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.97 0.95 0.96 65 1 0.95 0.97 0.96 60 accuracy 0.96 125 macro avg 0.96 0.96 0.96 125 weighted avg 0.96 0.96 0.96 125 Test Accuracy: 0.96 ```python ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) ``` ```python print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` Train Scores -------------------------------------------------- precision recall f1-score support 0 0.95 0.95 0.95 185 1 0.95 0.95 0.95 190 accuracy 0.95 375 macro avg 0.95 0.95 0.95 375 weighted avg 0.95 0.95 0.95 375 Train Accuracy: 0.9493333333333334 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.97 0.95 0.96 65 1 0.95 0.97 0.96 60 accuracy 0.96 125 macro avg 0.96 0.96 0.96 125 weighted avg 0.96 0.96 0.96 125 Test Accuracy: 0.96 ```python clf.predict(np.array([[0, 5]])) ``` array([0]) ```python clf.decision_function(np.array([[-20, 20]])) ``` array([-0.15603795]) ### Thoughts - Training data is probably coming from the overlaps - Testing data is probably from the outside of each group ## RBF SVM ![](images/svm-euc.png) ```python x, y = make_circles(n_samples=2000, shuffle=True, noise=0.1) plot_groups(x, y) ``` ![png](lesson-plan_files/lesson-plan_25_0.png) ```python ``` ```python xtrain, xtest, ytrain, ytest = train_test_split(x, y) ``` ### Linear SVM ```python clf = LinearSVC() clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_29_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.50 0.56 0.52 751 1 0.49 0.44 0.46 749 accuracy 0.50 1500 macro avg 0.50 0.50 0.49 1500 weighted avg 0.50 0.50 0.49 1500 Train Accuracy: 0.49533333333333335 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.49 0.55 0.52 249 1 0.49 0.43 0.46 251 accuracy 0.49 500 macro avg 0.49 0.49 0.49 500 weighted avg 0.49 0.49 0.49 500 Test Accuracy: 0.492 ### RBF ```python clf = SVC(kernel='rbf') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_31_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.84 0.85 0.85 751 1 0.85 0.84 0.84 749 accuracy 0.85 1500 macro avg 0.85 0.85 0.85 1500 weighted avg 0.85 0.85 0.85 1500 Train Accuracy: 0.846 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.80 0.83 0.81 249 1 0.82 0.80 0.81 251 accuracy 0.81 500 macro avg 0.81 0.81 0.81 500 weighted avg 0.81 0.81 0.81 500 Test Accuracy: 0.812 ### Thoughts - When do use this? - When the boundary isn't linear, when you cannot separate the data in the current dimensions. ## Sigmoidal SVM ```python x, y = make_moons(n_samples=2000, noise=0.10) ``` ```python plot_groups(x, y) ``` ![png](lesson-plan_files/lesson-plan_35_0.png) ```python xtrain, xtest, ytrain, ytest = train_test_split(x, y) ``` ```python clf = SVC(kernel='sigmoid') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_37_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.64 0.64 0.64 749 1 0.64 0.64 0.64 751 accuracy 0.64 1500 macro avg 0.64 0.64 0.64 1500 weighted avg 0.64 0.64 0.64 1500 Train Accuracy: 0.6406666666666667 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.63 0.67 0.65 251 1 0.64 0.60 0.62 249 accuracy 0.64 500 macro avg 0.64 0.64 0.64 500 weighted avg 0.64 0.64 0.64 500 Test Accuracy: 0.636 ### RBF ```python clf = SVC(kernel='rbf') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_39_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 749 1 1.00 1.00 1.00 751 accuracy 1.00 1500 macro avg 1.00 1.00 1.00 1500 weighted avg 1.00 1.00 1.00 1500 Train Accuracy: 0.9993333333333333 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 251 1 1.00 1.00 1.00 249 accuracy 1.00 500 macro avg 1.00 1.00 1.00 500 weighted avg 1.00 1.00 1.00 500 Test Accuracy: 1.0 ### Linear ```python clf = LinearSVC() clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_41_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.88 0.88 0.88 749 1 0.88 0.88 0.88 751 accuracy 0.88 1500 macro avg 0.88 0.88 0.88 1500 weighted avg 0.88 0.88 0.88 1500 Train Accuracy: 0.8833333333333333 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.86 0.84 0.85 251 1 0.85 0.86 0.85 249 accuracy 0.85 500 macro avg 0.85 0.85 0.85 500 weighted avg 0.85 0.85 0.85 500 Test Accuracy: 0.852 ## Polynomial SVM ```python clf = SVC(kernel='poly', degree=3, gamma='auto') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_43_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.99 0.88 0.93 749 1 0.89 0.99 0.94 751 accuracy 0.93 1500 macro avg 0.94 0.93 0.93 1500 weighted avg 0.94 0.93 0.93 1500 Train Accuracy: 0.9333333333333333 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 0.84 0.91 251 1 0.86 1.00 0.92 249 accuracy 0.92 500 macro avg 0.93 0.92 0.92 500 weighted avg 0.93 0.92 0.92 500 Test Accuracy: 0.916 ### Thoughts? ```python x, y = make_blobs(n_samples=3000, n_features=2, centers=3, cluster_std=1.8) plot_groups3(x, y) ``` ![png](lesson-plan_files/lesson-plan_45_0.png) ## Let's try all types of SVMs ```python xtrain, xtest, ytrain, ytest = train_test_split(x, y) ``` ### Linear ```python for degree in range(1, 10): print(f"degree = {degree}") print("-"*50) clf = SVC(kernel='poly', degree=degree) clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) print("\n\n") ``` degree = 1 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_1.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 1.00 1.00 739 2 1.00 1.00 1.00 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9991111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 240 1 1.00 1.00 1.00 261 2 1.00 1.00 1.00 249 accuracy 1.00 750 macro avg 1.00 1.00 1.00 750 weighted avg 1.00 1.00 1.00 750 Test Accuracy: 1.0 degree = 2 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_3.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.94 0.96 0.95 760 1 0.92 0.90 0.91 739 2 0.96 0.96 0.96 751 accuracy 0.94 2250 macro avg 0.94 0.94 0.94 2250 weighted avg 0.94 0.94 0.94 2250 Train Accuracy: 0.9404444444444444 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.94 0.95 0.95 240 1 0.93 0.89 0.91 261 2 0.94 0.97 0.96 249 accuracy 0.94 750 macro avg 0.94 0.94 0.94 750 weighted avg 0.94 0.94 0.94 750 Test Accuracy: 0.9373333333333334 degree = 3 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_5.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 1.00 1.00 739 2 1.00 1.00 1.00 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9991111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 240 1 1.00 1.00 1.00 261 2 1.00 1.00 1.00 249 accuracy 1.00 750 macro avg 1.00 1.00 1.00 750 weighted avg 1.00 1.00 1.00 750 Test Accuracy: 0.9986666666666667 degree = 4 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_7.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.93 0.96 0.95 760 1 0.93 0.87 0.90 739 2 0.95 0.97 0.96 751 accuracy 0.93 2250 macro avg 0.93 0.93 0.93 2250 weighted avg 0.93 0.93 0.93 2250 Train Accuracy: 0.9337777777777778 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.93 0.97 0.95 240 1 0.95 0.85 0.90 261 2 0.92 0.98 0.95 249 accuracy 0.93 750 macro avg 0.93 0.94 0.93 750 weighted avg 0.93 0.93 0.93 750 Test Accuracy: 0.9333333333333333 degree = 5 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_9.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 0.99 0.99 739 2 0.99 1.00 0.99 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9951111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.98 1.00 0.99 240 1 1.00 0.98 0.99 261 2 1.00 1.00 1.00 249 accuracy 0.99 750 macro avg 0.99 0.99 0.99 750 weighted avg 0.99 0.99 0.99 750 Test Accuracy: 0.9946666666666667 degree = 6 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_11.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.91 0.97 0.94 760 1 0.94 0.82 0.88 739 2 0.93 0.97 0.95 751 accuracy 0.92 2250 macro avg 0.93 0.92 0.92 2250 weighted avg 0.92 0.92 0.92 2250 Train Accuracy: 0.924 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.90 0.98 0.94 240 1 0.96 0.81 0.88 261 2 0.91 0.98 0.94 249 accuracy 0.92 750 macro avg 0.92 0.92 0.92 750 weighted avg 0.92 0.92 0.92 750 Test Accuracy: 0.9213333333333333 degree = 7 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_13.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.99 0.99 0.99 760 1 1.00 0.96 0.98 739 2 0.97 1.00 0.98 751 accuracy 0.98 2250 macro avg 0.98 0.98 0.98 2250 weighted avg 0.98 0.98 0.98 2250 Train Accuracy: 0.984 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.99 0.99 0.99 240 1 1.00 0.95 0.98 261 2 0.96 1.00 0.98 249 accuracy 0.98 750 macro avg 0.98 0.98 0.98 750 weighted avg 0.98 0.98 0.98 750 Test Accuracy: 0.9813333333333333 degree = 8 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_15.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.89 0.96 0.92 760 1 0.95 0.77 0.85 739 2 0.88 0.98 0.93 751 accuracy 0.90 2250 macro avg 0.91 0.90 0.90 2250 weighted avg 0.91 0.90 0.90 2250 Train Accuracy: 0.9017777777777778 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.89 0.97 0.93 240 1 0.98 0.75 0.85 261 2 0.85 0.99 0.92 249 accuracy 0.90 750 macro avg 0.91 0.90 0.90 750 weighted avg 0.91 0.90 0.90 750 Test Accuracy: 0.9013333333333333 degree = 9 -------------------------------------------------- ![png](lesson-plan_files/lesson-plan_49_17.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 0.98 0.99 0.99 760 1 1.00 0.94 0.97 739 2 0.96 1.00 0.98 751 accuracy 0.98 2250 macro avg 0.98 0.98 0.98 2250 weighted avg 0.98 0.98 0.98 2250 Train Accuracy: 0.9777777777777777 Test Scores -------------------------------------------------- precision recall f1-score support 0 0.96 0.99 0.98 240 1 1.00 0.92 0.96 261 2 0.95 1.00 0.97 249 accuracy 0.97 750 macro avg 0.97 0.97 0.97 750 weighted avg 0.97 0.97 0.97 750 Test Accuracy: 0.9693333333333334 ### Polynomial (3) ```python clf = SVC(kernel='poly', degree=3) clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_51_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 1.00 1.00 739 2 1.00 1.00 1.00 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9991111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 240 1 1.00 1.00 1.00 261 2 1.00 1.00 1.00 249 accuracy 1.00 750 macro avg 1.00 1.00 1.00 750 weighted avg 1.00 1.00 1.00 750 Test Accuracy: 0.9986666666666667 ### RBF ```python clf = SVC(kernel='rbf') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_53_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 1.00 1.00 739 2 1.00 1.00 1.00 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9991111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 240 1 1.00 1.00 1.00 261 2 1.00 1.00 1.00 249 accuracy 1.00 750 macro avg 1.00 1.00 1.00 750 weighted avg 1.00 1.00 1.00 750 Test Accuracy: 1.0 ### Sigmoidal ```python clf = SVC(kernel='sigmoid') clf.fit(xtrain, ytrain) ytrain_pred = clf.predict(xtrain) ytest_pred = clf.predict(xtest) plot_svm_groups(x, y, clf) print_report(ytrain, ytest, ytrain_pred, ytest_pred) ``` ![png](lesson-plan_files/lesson-plan_55_0.png) Train Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 760 1 1.00 1.00 1.00 739 2 1.00 1.00 1.00 751 accuracy 1.00 2250 macro avg 1.00 1.00 1.00 2250 weighted avg 1.00 1.00 1.00 2250 Train Accuracy: 0.9991111111111111 Test Scores -------------------------------------------------- precision recall f1-score support 0 1.00 1.00 1.00 240 1 1.00 1.00 1.00 261 2 1.00 1.00 1.00 249 accuracy 1.00 750 macro avg 1.00 1.00 1.00 750 weighted avg 1.00 1.00 1.00 750 Test Accuracy: 1.0 ### Assessment
C#
UTF-8
3,002
2.890625
3
[]
no_license
using Backend; using Objects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Logic { public class PeekFilter { public string[,] PeekArray(SRTMtile tile, Coordinates coordinates, int range) { //Make values ascending float[] ycoordinatesASC = (float[])tile.ycoordinates.Reverse().ToArray(); float[] xcoordinatesASC = (float[])tile.xcoordinates; //Starting threads GetClosest gety = new GetClosest(); GetClosest getx = new GetClosest(); Thread getyThread = new Thread(() => { gety = new GetClosest(coordinates.y, ycoordinatesASC); }); Thread getxThread = new Thread(() => { getx = new GetClosest(coordinates.x, xcoordinatesASC); }); getyThread.Start(); getxThread.Start(); getyThread.Join(); //Getting y-values int starty = gety.index - 1 - range; float miny = ycoordinatesASC[starty]; int endy = gety.index + 1 + range; float maxy = ycoordinatesASC[endy]; getxThread.Join(); //Getting x-values int startx = getx.index - 1 - range; float minx = xcoordinatesASC[startx]; int endx = getx.index + 1 + range; float maxx = xcoordinatesASC[endx]; OSMreader or = new OSMreader(); List<Peek> peeks = or.peeks; List<Peek> filteredPeeks = new List<Peek>(); //filtering peeks foreach (Peek peek in peeks) { if ((miny <= peek.coordinates.y) && (maxy >= peek.coordinates.y)) { if ((minx <= peek.coordinates.x) && (maxx >= peek.coordinates.x)) { filteredPeeks.Add(peek); } } } //Put in stringarray, simmilar to heights array string[,] peekMatrix = new string[(range * 2 + 1), (range * 2 + 1)]; foreach (Peek peek in filteredPeeks) { GetClosest closesty = new GetClosest(); GetClosest closestx = new GetClosest(); Thread closestyThread = new Thread(() => { closesty = new GetClosest(peek.coordinates.y, ycoordinatesASC); }); Thread closestxThread = new Thread(() => { closestx = new GetClosest(peek.coordinates.x, xcoordinatesASC); }); closestyThread.Start(); closestxThread.Start(); closestyThread.Join(); closestxThread.Join(); int y = closesty.index - starty - 1; int x = closestx.index - startx - 1; //reverse y back //y = (range * 2) - y; peekMatrix[y, x] = peek.name; } return peekMatrix; } } }
Markdown
UTF-8
7,744
2.78125
3
[]
no_license
七五 两人以快速的脚程,奔向太湖双蚊的秘窟、绕渔村走了两趟,除了一些老少妇隘夕)人连噶个少年也没留下,能提刀弄棍做贼的人都跑光了,显然在他前来讨口供之后,水贼们知道不妙,躲到别处避祸去了。 他俩却没发现‘不远处小山脊上的树林里,有人居高临下监视村中的动静,他俩却看不见藏在林中,不言不动向下窥伺的人。 小姑娘的行囊留在莫厘镇的客店,必须返回客店取行囊,约定在杨湾霍然的泊舟处见面,一同乘船离开东山,他不再前往西山游览了。 小姑娘兴高采烈走了,他一身轻松前往泊舟处等候。 泅州水怪三个人,到达莫厘镇不敢停留,穿越市街奔向码头,急于雇船离去。 码头停泊了不少大小船只,其中有不少是华丽的画肪,那是有钱的大户,雇用的中型游湖船,并非有粉头的风月舟,当然免不了有些人携妓游湖。 码头人声嘈杂,游客们上上下下,刚进入码头栅口,劈面碰上两名穿得体面,气概不凡的中年游客,与一位明眸皓齿”灵秀脱俗的穿月白衫裙少女,似乎刚由船上下来,要出栅往镇上走。 妇女应该走在男人身后的、这是礼俗。 但两位中年仕绅型的人,却走在少女身后,像保缥随从,可知少女的身份比男士高,才能有资格走弯前面。 泅州水怪一马当先人栅,眼睛在一排大小船只上探索,找回程的船只,只要能立即离去,什么船都好,必要时可使用强制手段达到目的。 “你,站住!” 那位生了一双鹰目,留了大八字胡的仕绅,突然横跨一步,拦住去路冷然叱喝,不怒而威盛气凌人。 另一位中年人,阴森的目光盯着姓柯的少妇,以及假和尚南人屠,似乎他们如果有任何异动,皆可能受到有效的控制,目光像在审贼。 少女则含笑俏立,满面春风一团和气,不像个练武的人,而是灵秀的大家淑女,罗衣胜雪俏然卓立,还真有几分不属于世俗的出尘之美。 泅州水怪三个人,携有用布卷藏的刀剑。少女与两个中年人,则两手空空没佩有兵刃。 怪眼一翻,泅州水怪狠盯着对方,眼中有极端警戒的神情,也有即将爆发的怒火。 “干什么。”泅州水怪也气冲冲反问。 “你是泅州水怪陈百川?” “咦!你……” “你其他的人呢?”中年人逼问。 “关你什么事?” “闭嘴!”中年人沉叱。 既然要询问,却又要对方闭嘴,闭嘴如何口答?霸道得很。 “咦!你……”泅州水怪吓了一跳,对方的威严神态还真令人心悸不安。 “你替古凌风几个人办事,将功赎罪在外活动了一段时日,现在你好像不在他们身边了,为何?是不是胆大包天叛逃了?” 泅州水怪脸色泛灰,打一冷战退了两步。 “说!”中年人逼进两步厉声问。 “我……我我……” “我要剥你的皮。” 南人屠哼了一声,被中年人这句话激怒了,快速地打开卷着刽刀的布中,要准备行凶了。 “你一动刀。一定死。”另一位中年人阴森森他说,但背着手并无进一步行动的表示。 姓柯的少妇,袖套内滑下一枚六寸扁针藏在掌心。 “你这位大嫂的可爱织手,千万不要乱抬,好吗?” 少女悦耳的嗓音极为娇柔,脸上的笑容更可爱了,但语意却含有强力的警告味,似已知道少妇手中有乾坤,一眼便看出少妇的心意:“我姓贝,是一个疑心很大的人。 南人屠心中一寒,不敢拔刀。 姓柯的少妇也脸色一变,手上的劲道消散。 “古……古大人五……五位老爷,早些天失……失了踪……” 泅州水怪不住发抖,语音断断续续:“小的改跟在黄…… 黄永昌几位大人手……手下当……当差,替……替黄大人奔……奔走,效大马之劳。小的天胆,也……也不敢叛……叛逃。” “……什么?古大人他们失踪了?如何失踪的?说!” “我们到嘉兴,找神鳖讨取冷面煞星的下落。从泅州水怪不再发抖,定下心神为自己的生死挣扎,“冷面煞星在嘉兴西水驿、劫走了宁府抄没的两箱珍宝,结果来了一个蒙面人,把我们杀得落花流水,小的跌落水中逃得性命,其他的人四散逃命下落不明。小的……” “且慢!那蒙面人是何来路?” 既然是蒙面人,怎知是何来路? “不知道,小的听到有人叫他是笑魔君。那人的笑声威力惊人,人耳如五雷击顶门。 “笑魔君?这人目下在镇江附近活动,并没甫来呀! “小的不知道是不是他。” “你没找古大人。” “小的找了好几天,毫无音讯,只好动身回南京,在苏州又碰上黄大人,要小的找一些朋友,查冷面煞星的下落,据说躲在大湖附近。可是,相助的太湖双蚊出了意外,昨天咱们前往梅坞,找金笛飞仙相助,本来已完全控制了梅坞.……” 泅州水怪这次实话实说,将经过说了,而有关古大人的前一段叙述;却有一半是假的。 古大人一群人已经死了,他一清二楚,却说是失踪,以推卸责任; 要让对方知道他见机入水逃走,后果不问可知。 “该死的,你根本不该带古大人黄大人,来找什么冷面煞星,追查宁府的失宝。” 中年人怒声斥责:“宁府的珍宝并没被盗劫走,而是接收押送的人监守自盗。长上在南京,仅要你负责快马船在德州被劫的美女金珠:你却带了人追查其他的珍宝…… “大爷明鉴)小的身不由已,古大人和黄大人不愿在查快马船被劫的事上费心,J、的那敢不遵?他们只想就近追查其他的……” “罢了!长上本来就知道你们靠不住。” 中年人显然不想追究下文:“现在跟我去见长上。” “长上也来了?” “对,在船上。” 中年人向左方百步外的一艘快船一指:“我们已经查出,登上快马船抢劫的人中,有一股人最为瞟悍泼野,首脑叫飞天猴向仲权。这人的贼伙中,有几个是大湖附近的独行盗,你既然在太湖一带活动,正好派得上用场,长上会重用你的,跟我走。” 泅州水怪的惶恐神情,南人屠与柯少妇心中有数,这三个男女大有来头,在船上的那位长上,更是权势极大的可怕人物,怎敢抗拒中年人的要求?乖乖地跟在泅州水怪身后,前往船上听候长上的摆布。 上次在德州抢劫快马船,泅州水怪因对付霍然,而耽误了片刻,因而没赶上登船抢劫,等于是失败了,金珠美女一无所得。 塞翁失马,岂知非福?他来不及登船,抢不到金珠美女,却因祸得福,追查失宝的负责秘探找找他,要求他合作,追查金珠美女的下落。 控制他的人,却志不在查快马船被劫的金珠美女,可能知道远走天涯海角追查困难重重,便利用他招引人手,就近追查其他的失宝,也藉机在苏杭搜刮勒索,反而把追查快马船被劫的事置于脑后。 这次,泅州水怪不能再不务正业了,必须把全部精力放在追查快马船被劫的金珠美女上啦!这位“长上”,正是查捕抢劫快马船盗群的主事人之一。
Markdown
UTF-8
1,426
2.625
3
[]
no_license
# Below are the places where you can learn Android Dev: - Udacity NanoDegree Courses + Other Related: - It is a set of 9 courses from Udacity: - List: - [User Interface](https://classroom.udacity.com/courses/ud834) - [User Input](https://classroom.udacity.com/courses/ud836) - [Multiscreen apps](https://classroom.udacity.com/courses/ud839) - [Networking course](https://classroom.udacity.com/courses/ud843) - [Data storage course](https://classroom.udacity.com/courses/ud845) - [Developing Android apps course](https://classroom.udacity.com/courses/ud851) - [Advanced Android app dev](https://classroom.udacity.com/courses/ud855) - [Firebase in a weekend](https://classroom.udacity.com/courses/ud0352) - [Material Design Course](https://classroom.udacity.com/courses/ud862) - Udemy Android Development Course - [Link](https://drive.google.com/drive/folders/1b0Zt0f4mz2e7j8lIaFkBDo-cQu3F9bYI?usp=sharing) - Android Development courses on YouTube - [Link](https://www.youtube.com/playlist?list=PLknSwrodgQ72X4sKpzf5vT8kY80HKcUSe) (Language used - English) - [Link](https://www.youtube.com/playlist?list=PLUhfM8afLE_Ok-0Lx2v9hfrmbxi3GgsX1) (Language used - Hindi) - Github [UltimateAndroidResource](https://github.com/aritraroy/UltimateAndroidReference.githttps://github.com/aritraroy/UltimateAndroidReference.git) - GoTo youtube channels for Android: - Philip Lackner - Coding in Flow
C++
UTF-8
1,409
2.765625
3
[]
no_license
#ifndef REGIMOT_H_REGIMOT #define REGIMOT_H_REGIMOT #include<iostream> #include "Estate.h" using namespace std; class RealEstates { private: Estate **estates; int capacity; int current; protected: void Erase(); void Copy(const RealEstates& x); void resize(); void printEstatesByTypeAndVip(const char * typeOfEstate) const; RealEstates* Clone()const; public: RealEstates(); RealEstates(Estate** estates); RealEstates(const RealEstates &estate); ~RealEstates(); RealEstates & operator=(const RealEstates &estate); Estate* getEstateByPosition(int); void addEstate(Estate*); void newPrice(double); void printEstatesByType(const char * typeOfEstate) const; int getCurrent(); bool sortEstatesByLowerPrice()const; bool removeEstate(Estate*); void printEstatesByTypeAndLowestPrice(const char*)const; void printEstatesFromLowestPrice()const; void printByPriceRange(double,double)const; void printEstatesByTown(char* town)const; void printBySpaceRange(double,double)const; void print()const; void printEstatesLowestPriceByVipAndType(const char*)const; void printEstatesFromLowestPriceByVip()const; void printByPriceRangeByVip(double,double)const; void printEstatesByTownByVip(char* town)const; void printBySpaceRangeByVip(double,double)const; void printEstatesByVip()const; }; #endif
Java
UTF-8
11,194
1.882813
2
[]
no_license
package app.utic.appventas; import android.content.ContentValues; import android.content.DialogInterface; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.appventas.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; public class SalidaActivity extends AppCompatActivity { private String usuario; //se declara variable a recibir usuario del login static String HOST = LoginActivity.HOST; String TABLA = "api/"; String ENLACE = HOST+TABLA; EditText et_codigo, fechaSalida, codtipob, et_chapa, et_cliente, et_tiempo; Integer idEliminar, idTipoB, idZona; Button registrar, buscar, eliminar, modificar; RequestQueue request, requestQueue; @Override public void onBackPressed (){ finish(); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_salida); et_codigo = (EditText) findViewById(R.id.txt_codigo); et_chapa = (EditText) findViewById(R.id.txt_chapa); et_cliente = (EditText) findViewById(R.id.txt_cliente); et_tiempo = (EditText) findViewById(R.id.txt_tiempo); fechaSalida = findViewById(R.id.txt_fecha); fechaSalida.setText(ParametrosGlobales.completarFecha("dd/MM/yyyy")); registrar = (Button) findViewById(R.id.btnRegistrar); modificar = (Button) findViewById(R.id.btnModificar); eliminar = (Button) findViewById(R.id.btnEliminar); buscar = (Button) findViewById(R.id.bt_buscar); et_codigo.setEnabled(false); fechaSalida.setEnabled(false); } public void Eliminar(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(SalidaActivity.this); builder.setMessage("¿Desea Eliminar este registro?").setPositiveButton("Si", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: String URL = ENLACE+"bahia.php?accion=delete&id_bahia="+et_codigo.getText().toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject parentObject = new JSONObject(response); if (parentObject.getString("status").equals("success")){ String message = parentObject.getString("message"); et_codigo.setText(""); Toast.makeText(SalidaActivity.this, message, Toast.LENGTH_SHORT).show(); }else { String message = parentObject.getString("message"); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Sin conexion a Internet", Toast.LENGTH_LONG).show(); } }); requestQueue = Volley.newRequestQueue(SalidaActivity.this); requestQueue.add(stringRequest); Cancelar(); break; case DialogInterface.BUTTON_NEGATIVE: Cancelar(); break; } } }; public void Modificar(View view) { String chapa = et_chapa.getText().toString(); String tiempo = et_tiempo.getText().toString(); if(chapa.isEmpty() || tiempo.isEmpty()){ Toast.makeText(getApplicationContext(), "Debe completar todos los campos", Toast.LENGTH_LONG).show(); et_chapa.requestFocus(); } else { final String URL = ENLACE+"entrada.php?accion=update&chapa="+et_chapa.getText().toString()+ "&tiempo="+et_tiempo.getText().toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject parentObject = new JSONObject(response); if (parentObject.getString("status").equals("success")){ String message = parentObject.getString("message"); et_codigo.setText(""); et_chapa.setText(""); et_cliente.setText(""); et_tiempo.setText(""); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); }else { String message = parentObject.getString("message"); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), URL, Toast.LENGTH_LONG).show(); } }); requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } } public void BuscarV(View view) { String URL = ENLACE+"entrada.php?accion=searchSalida&chapa="+et_chapa.getText().toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject parentObject = new JSONObject(response); if (parentObject.getString("status").equals("success")){ String tiempo = parentObject.getString("horas"); String nombres = parentObject.getString("nombres"); et_cliente.setText(nombres); et_tiempo.setText(tiempo); //txtDescripcion.setText(""); Toast.makeText(SalidaActivity.this, "Recuperado", Toast.LENGTH_SHORT).show(); // et_descrimarca.setSelection(et_descrimarca.getText().toString().length()); } else { Toast.makeText(getApplicationContext(), "No Existe1", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "No Existe2", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Sin conexion a Internet", Toast.LENGTH_LONG).show(); } }); requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } public void Cancelar() { et_codigo.setText(""); registrar.setEnabled(true); modificar.setEnabled(false); eliminar.setEnabled(false); } public void CancelarBoton(View view) { et_codigo.setText(""); registrar.setEnabled(true); modificar.setEnabled(false); eliminar.setEnabled(false); } public void Recuperar() { String URL = ENLACE+"bahia.php?accion=search&id_bahia="+et_codigo.getText().toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject parentObject = new JSONObject(response); if (parentObject.getString("status").equals("success")){ String descripcion = parentObject.getString("nom_bahia"); String tipo_bahia = parentObject.getString("id_tipbahia"); String zona = parentObject.getString("id_zona"); //txtDescripcion.setText(""); //Toast.makeText(Marcas3Activity.this, "Recuperado", Toast.LENGTH_SHORT).show(); modificar.setEnabled(true); eliminar.setEnabled(true); registrar.setEnabled(false); // et_descrimarca.setSelection(et_descrimarca.getText().toString().length()); } else { Toast.makeText(getApplicationContext(), "No Existe1", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "No Existe2", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Sin conexion a Internet", Toast.LENGTH_LONG).show(); } }); requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } }
Shell
UTF-8
1,227
2.921875
3
[]
no_license
#!/bin/bash if [ $# != 2 ] then echo -n "\n******************** This program is used for CHD ****************************\n" echo -n " Usage: bash $0 <bin_dir> <result_dir(abs_path)>\n" echo -n " exmaple: bash $0 /home/bioadmin/YingyingXia/bin/CHD ./xxx/xxx/***\n" echo -n "******************************************************************************\n\n" exit 1 fi bin_dir=$1 result_dir=$2 run_id=`basename $result_dir` site=`dirname $result_dir` site=`basename $site` echo $run_id echo $site cd $result_dir #perl $bin_dir/scr/unzip_file.pl $result_dir perl $bin_dir/parallel_logRR.pl $result_dir $bin_dir/LOGRR perl get_YCM_JiaYin.pl $result_dir $bin_dir $site $run_id if [ -f $result_dir/index2id_YCM.txt ] then bash $bin_dir/YCM/YCM/scripts/batch_YCM.sh $result_dir $result_dir perl $bin_dir/YCM/mail_YCMresult.pl $result_dir fi perl $bin_dir/Auto_DNAcopy_BreakPoints.pl $result_dir $bin_dir/BreakPoints $bin_dir/DatabaseAnn perl $bin_dir/Upload_Scripts/upload_chd_info_SiteCommon.pl $result_dir $bin_dir/Upload_Scripts python /home/bioadmin/YingyingXia/project/CHD/get_sampleinfo.py $result_dir/index2id.txt $site $run_id $result_dir/sample_info.txt #perl $bin_dir/scr/create_zip.pl $result_dir
JavaScript
UTF-8
1,577
3.46875
3
[]
no_license
function start_quiz(){ var score = 0; var q1 = document.getElementById("q1").value; var q2 = document.getElementById("q2").value; var q3 = document.getElementById("q3").value; var q4 = document.getElementById("q4").value; var q5 = document.getElementById("q5").value; var a1 = document.getElementById("a1").value; var a2 = document.getElementById("a2").value; var a3 = document.getElementById("a3").value; var a4 = document.getElementById("a4").value; var a5 = document.getElementById("a5").value; var questions = [ { prompt: q1, answer: a1 }, { prompt: q2, answer: a2 }, { prompt: q3, answer: a3 }, { prompt: q4, answer: a4 }, { prompt: q5, answer: a5 }, ] for(var i = 0; i< 5; i++){ var response = window.prompt(questions[i].prompt); if(response == questions[i].answer){ score++; alert("You got it correct"); }else{ alert("You got it wrong"); } } alert("You got " + score + "/ 5" ); var percentage = score/5 * 100; if(percentage >=50 && percentage<=75){ alert("Nice try, but you can do a bit better.") }else if(percentage>=75){ alert("You did amazing. Well done.") }else{ alert("Nice try. You can do much better.") } }
Markdown
UTF-8
3,892
2.546875
3
[]
no_license
# Reproducible Research: Peer Assessment 1 ```r library(dplyr) ``` ``` ## Warning: package 'dplyr' was built under R version 3.2.2 ``` ``` ## ## Attaching package: 'dplyr' ``` ``` ## The following objects are masked from 'package:stats': ## ## filter, lag ``` ``` ## The following objects are masked from 'package:base': ## ## intersect, setdiff, setequal, union ``` ```r library(ggplot2) ``` ``` ## Warning: package 'ggplot2' was built under R version 3.2.3 ``` ```r library(scales) ``` ``` ## Warning: package 'scales' was built under R version 3.2.3 ``` ## Loading and preprocessing the data ```r content <- read.csv("repdata_data_activity/activity.csv") stepsPerDay <- content %>% group_by(date) %>% summarise(stepSum = sum(steps, na.rm = TRUE)) stepsPerInterval <- content %>% group_by(interval) %>% summarise(stepSum = sum(steps, na.rm = TRUE)) #create reference Date (01.01.1970) stepsPerInterval$interval <- as.POSIXct(paste("1970/01/01", sprintf("%04d", stepsPerInterval$interval)), format = "%Y/%m/%d %H%M") ``` ## What is mean total number of steps taken per day? ```r hist(stepsPerDay$stepSum, xlab = "Steps per day", main = "Histogram of total number of steps per day") ``` ![](PA1_template_files/figure-html/unnamed-chunk-3-1.png) ```r summary(stepsPerDay$stepSum) ``` ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## 0 6778 10400 9354 12810 21190 ``` ## What is the average daily activity pattern? ```r ggplot(stepsPerInterval, aes(interval, stepSum)) + geom_line() + scale_x_datetime(breaks = date_breaks("2 hour"), labels = date_format("%H:%M")) + labs(x = "time", y = "Steps (sum over 5min interval)") ``` ![](PA1_template_files/figure-html/unnamed-chunk-4-1.png) ```r stepsPerInterval$interval[which(stepsPerInterval$stepSum == max(stepsPerInterval$stepSum))] ``` ``` ## [1] "1970-01-01 08:35:00 CET" ``` ## Imputing missing values ```r sum(is.na(content$steps)) ``` ``` ## [1] 2304 ``` replace 'NA' with average for that day ```r contentComplete <- content idxNA <- which(is.na(contentComplete$steps)) contentComplete$steps[idxNA] <- stepsPerDay$stepSum[ sapply(contentComplete$date[idxNA], function(i) which(stepsPerDay$date == i))] ``` repeat analysis from the start with filled data ```r stepsPerDayComplete <- contentComplete %>% group_by(date) %>% summarise(stepSum = sum(steps, na.rm = TRUE)) hist(stepsPerDayComplete$stepSum, xlab = "Steps per day", main = "Histogram of total number of steps per day (completed dataset)") ``` ![](PA1_template_files/figure-html/unnamed-chunk-7-1.png) ```r summary(stepsPerDayComplete$stepSum) ``` ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## 0 6778 10400 9354 12810 21190 ``` Mean/Median should stay equal or increase with the chosen strategy (replace with daily average). Reason is that the total number of steps should increase if there was at least one value for that day. Days with only NA will still have 0 total steps. ## Are there differences in activity patterns between weekdays and weekends? ```r contentComplete$daytype <- factor(ifelse(as.POSIXlt(content$date)$wd %in% c(0,6), 0, 1), labels = c("weekend", "weekday")) stepsPerIntervalComplete <- contentComplete %>% group_by(interval, daytype) %>% summarise(stepSum = sum(steps, na.rm = TRUE)) #create reference Date (01.01.1970) stepsPerIntervalComplete$interval <- as.POSIXct(paste("1970/01/01", sprintf("%04d", stepsPerIntervalComplete$interval)), format = "%Y/%m/%d %H%M") ggplot(stepsPerIntervalComplete, aes(interval, stepSum)) + geom_line() + facet_grid(daytype~.) + scale_x_datetime(breaks = date_breaks("2 hour"), labels = date_format("%H:%M")) + labs(x = "time", y = "Steps (sum over 5min interval)") ``` ![](PA1_template_files/figure-html/unnamed-chunk-8-1.png)
C#
UTF-8
1,542
3.109375
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blindspot.ViewModels { /// <summary> /// Contains a collection of BufferLists /// </summary> public class BufferListCollection : List<BufferList> { private int _currentListIndex; public int CurrentListIndex { get { return _currentListIndex; } set { if (value >= this.Count) { throw new IndexOutOfRangeException("The current index is set higher than the number of items in the buffer"); } _currentListIndex = value; } } public BufferList CurrentList { get { if (this.Count > 0) { return this[CurrentListIndex]; } return new BufferList("No buffers loaded in session"); } } public void NextList() { if (CurrentListIndex < this.Count - 1) { CurrentListIndex++; } else { CurrentListIndex = 0; } } public void PreviousList() { if (CurrentListIndex > 0) { CurrentListIndex--; } else { CurrentListIndex = this.Count - 1; } } } }
C++
UTF-8
688
3.34375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int largestSubarraySum1(int *arr,int n) { //Prefix Sum technique int ps[100]; ps[0]=arr[0]; for(int i=1;i<n;i++) { ps[i]=ps[i-1]+arr[i]; } // Largest sum int largest_sum=0; for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { int subarray_sum=i>0?ps[j]-ps[i-1]:ps[j]; // Check for largest sum largest_sum = max(largest_sum,subarray_sum); } } return largest_sum; } int main() { //Array Containing int arr[] = {-2,3,4.-1,5,-12,6,1,3}; int n = sizeof(arr)/sizeof(int); cout<<largestSubarraySum1(arr,n)<<endl; }
Java
UTF-8
1,487
1.960938
2
[]
no_license
package com.hxgd.onemap.entity; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Route { @Id private Integer id; /** * 路线名称 */ private String name; /** * 路线描述 */ private String content; /** * 水泥厂 */ private Integer cement; /** * 标段 */ private Integer section; /** * 车辆类型 */ @Column(name = "car_type") private Integer carType; /** * 标准里程(km) */ private Float mile; /** * 单趟承运时间(min) */ private Float time; /** * 装货超时(min) */ @Column(name = "up_time") private Float upTime; /** * 卸货超时(min) */ @Column(name = "down_time") private Float downTime; /** * 单趟工资(元) */ private Float wage; /** * 单趟油耗(L) */ private Float oil; /** * 收费 */ private Float fee; /** * 物资公司 */ @Column(name = "mat_id") private Integer matId; /** * 是否可用 */ private Integer fit; /** * 负责车队 */ @Column(name = "moto_id") private Integer motoId; /** * 提货账号 */ private String accout; }
PHP
UTF-8
697
2.578125
3
[]
no_license
<?php /** * Table Definition for html */ require_once 'DB/DataObject.php'; class DataObjects_Html extends DB_DataObject { ###START_AUTOCODE /* the code below is auto generated do not remove the above tag */ public $__table = 'html'; // table name public $html_id; // int(4) primary_key not_null unsigned public $htmlText; // text public $name; // varchar(200) /* Static get */ function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('DataObjects_Html',$k,$v); } /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE }
Python
UTF-8
2,828
3.328125
3
[]
no_license
import numpy as np import re import itertools import nltk from string import digits from collections import Counter def clean_str(string): """ Regex used to seperate compound words Original from : https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py Input: string Output: string without compound words """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r",", " , ", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\(", " \( ", string) string = re.sub(r"\)", " \) ", string) string = re.sub(r"\?", " \? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower() def load_data_and_labels(strong_file, weak_file): """ Loads examples from files. Splits data into strong and weak classifcations. Input: files of strong and weak words Output: list of words and classifications """ # Load data from files strong_examples = list(open(strong_file, "r").readlines()) strong_examples = [s.strip() for s in strong_examples] weak_examples = list(open(weak_file, "r").readlines()) weak_examples = [s.strip() for s in weak_examples] # Split by words split_text_s = strong_examples split_text_s = [nltk.pos_tag(nltk.word_tokenize(clean_str(x))) for x in split_text_s] split_text_w = weak_examples split_text_w = [nltk.pos_tag(nltk.word_tokenize(clean_str(x))) for x in split_text_w] split_text_combined = split_text_s + split_text_w updated_list = [] for item in split_text_combined: sub_list = [] for subitem in item: sub_list.append(subitem[1]) sub_string = " ".join(sub_list) updated_list.append(sub_string) # Generate labels strong_labels = [[0, 1] for _ in split_text_s] weak_labels = [[1, 0] for _ in split_text_w] y = np.concatenate([strong_labels, weak_labels], 0) return [updated_list, y] def batch_iter(data, batch_size, num_epochs, shuffle=True): """ Generates a batch iterator for a dataset. """ data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/batch_size) + 1 for epoch in range(num_epochs): # Shuffle the data at each epoch if shuffle: shuffle_indices = np.random.permutation(np.arange(data_size)) shuffled_data = data[shuffle_indices] else: shuffled_data = data for batch_num in range(num_batches_per_epoch): start_index = batch_num * batch_size end_index = min((batch_num + 1) * batch_size, data_size) #min of batch size or data size yield shuffled_data[start_index:end_index] #yield until out of range
Markdown
UTF-8
5,968
2.875
3
[]
no_license
# Slowfast Model tutorial ## Basics Requirement: - Python >3.7 - Pytorch: >=1.9 - Pytorchvideo - Torchvision >= 0.10.0 ### Bringing slowfast model There is two ways we can bring a slowfast model with random weights initialised. - **torch.load**: Will give us the model directly. ``` model_name = "slowfast_r50" # or "slowfast_r101" model = torch.hub.load("facebookresearch/pytorchvideo", model=model_name, pretrained=False) ``` To take the pretrained weights ``` model_name = "slowfast_r50" # or "slowfast_r101" model = torch.hub.load("facebookresearch/pytorchvideo", model=model_name, pretrained=True) ``` We can verify the model by checking the model variable. We can use the following setup to count the parameter numbers. ``` def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(count_parameters(model)) ``` - **create_slowfast** ``` import pytorchvideo.models as models from pytorchvideo.models import create_slowfast model = create_slowfast(model_depth=50) # Alternative 18, 101, 152 ``` The created model should have equal number of parameters as earlier. To load the pretrained weight we require to download the weights from the [link](https://pytorchvideo.readthedocs.io/en/latest/model_zoo.html) and load the weights. We can use the followings to load the weights. ``` pretrain = 1 if pretrain == 1: wt = torch.load("../Directory/SLOWFAST_8x8_R50.pyth") model.load_state_dict(wt["model_state"]) ``` However, to load the model zoo weight of slowfast 100 model do the followings ``` model = create_slowfast(model_depth=101, slowfast_fusion_conv_kernel_size = (5, 1, 1,)) ``` ### Inferring using the model The pytorchvideo slowfast model takes list (formatted in a specific way) as input. It builds upon a class called *multiPathWayWithFuse* that takes list as input. Anyways, we require to do the following to infer using the model ``` #%% Defining functions from pytorchvideo.transforms import UniformTemporalSubsample transform1=Compose( [UniformTemporalSubsample(num_frames), PackPathway()]) #%% Input processing ipt_vid_frm = 64_consecutive_video_frame # shape of (3, 64, 224, 224) f = transform1(ipt_vid_frm) f = [_.to(device)[None, ...] for _ in f] output = model(f) ``` **Interesting fact**: The model execution change the shape of input *f* since *f* is a list and when we process python list inside another function the list changes accordingly. ## Intermediate ### Batch Data processing One issue I faces is to batching the data for the model to train/infer. Here's my code to solve the issue. ``` device = 'cuda:0' # 'cpu' #%% Defining requirement def sf_data_ready(vdat): transform1=Compose( [ UniformTemporalSubsample(num_frames), # Lambda(lambda x: x/255.0), # NormalizeVideo(mean, std), # ShortSideScale( # size=side_size # ), # CenterCropVideo(crop_size), PackPathway() ] ) s2 =[[], []] for i in range(vdat.shape[0]): f = transform1(vdat[i]) f = [_.to(device)[None, ...] for _ in f] s2[0].append(f[0]) s2[1].append(f[1]) for i in range(2):s2[i] = torch.cat((s2[i][0:])) return s2 #%% Implementation video_batch= torch.rand(BS, 3, 64, 224, 224) # BS = Batch size inputs = sf_data_ready(video_batch) outputs = model(inputs) ``` ### Modifying Model Structure We can build our custom slowfast model by providing different arguments choice for the create_slowfast model as enlisted in the [docs](https://pytorchvideo.readthedocs.io/en/latest/_modules/pytorchvideo/models/slowfast.html#create_slowfast). The list is exhaustive however, we will go over as much as we can, - slowfast_channel_reduction_ratio: Corresponds to the inverse of the channel reduction ratio, beta between the Slow and Fast pathways. Default: (8, ) - the Higher value would give model with lower params (fast channel reduces) ``` slowfast = create_slowfast(slowfast_channel_reduction_ratio= (v_r,)) # v_r <=64 ``` - slowfast_conv_channel_fusion_ratio (int): Ratio of channel dimensions between the Slow and Fast pathways. Default: 2 - Note: the higher, the number of parameter increases (can go super high although should not) - DEPRECATED slowfast_fusion_conv_kernel_size (tuple): the convolutional kernel size used for fusion. [self-explained] - DEPRECATED slowfast_fusion_conv_stride (tuple): the convolutional stride size used for fusion. [self-explained] Well, the idea is we can go over this and create a customized model. One drawback of such approach is that we might not have the pretrained weights for our custom model! Here is some args to look at: **input_channel**: May allow color and gray scale simultaneously, **model_depth**: Model depth (18, 50, 101, 151), **head**: Do we want the projection after the final fusion. ## Advanced The interesting fact that, SF model works with varying input size of (224, 224) or (256, 256). How is this possible even we have linear layer in the later section? Shouldn't we encounter matrix multiplication error?? - Well, they use **torch.nn.AdaptiveAvgPool3d** to create uniform shape at the later stage (before linear layer). ### Modifying Model structure Heavily We can also enter the layers and modify them as we suit as example below ``` model.blocks[6] = nn.Sequential(*list(model.blocks[6].children())[:-2], nn.AdaptiveAvgPool3d(1), nn.Flatten(), nn.Linear(in_features=2304, out_features=1000, bias=True), nn.ReLU() ) ``` We can only change the linear layer too. ``` model.blocks[6].proj = nn.Linear(in_features=2304, out_features=1000) ``` However, beware of the following [bug](https://discuss.pytorch.org/t/pytorch-is-allowing-incorrect-matrix-multiplication-when-using-cuda/130664) of pytorch 1.9 version. Happy coding.
Rust
UTF-8
3,837
3.0625
3
[ "MIT" ]
permissive
extern crate crypto; use v3::types::*; use v3::errors::{Result, Error, ErrorKind}; use self::crypto::aes; use self::crypto::blockmodes; use self::crypto::buffer::{WriteBuffer, ReadBuffer, RefReadBuffer, RefWriteBuffer, BufferResult}; /// A "Decryptor", which is nothing more than a data structure to keep around the RNCryptor context pub struct Decryptor { pub version: u8, pub options: u8, encryption_salt: EncryptionSalt, hmac_salt: HMACSalt, encryption_key: EncryptionKey, pub hmac_key: HMACKey, iv: IV, } impl Decryptor { /// Builds a "Decryptor" out of a password and a message (to decrypt). pub fn from(password: &str, message: &[u8]) -> Result<Decryptor> { let msg_len = message.len(); if msg_len < 66 { return Err(Error::new(ErrorKind::NotEnoughInput(msg_len), "Decryption failed, not enough input.".to_owned())); } let version = message[0]; let options = message[1]; let encryption_salt = Salt(message[2..10].to_vec()); let hmac_salt = Salt(message[10..18].to_vec()); let iv = IV::from(message[18..34].to_vec()); let encryption_key = EncryptionKey::new(&encryption_salt, password.as_bytes()); let hmac_key = HMACKey::new(&hmac_salt, password.as_bytes()); Ok(Decryptor { version: version, options: options, encryption_salt: encryption_salt, encryption_key: encryption_key, hmac_key: hmac_key, hmac_salt: hmac_salt, iv: iv, }) } fn plain_text(&self, cipher_text: &[u8]) -> Result<Message> { let iv = self.iv.to_vec(); let key = self.encryption_key.to_vec(); let mut decryptor = aes::cbc_decryptor( aes::KeySize::KeySize256, key, iv, blockmodes::PkcsPadding); // Usage taken from: https://github.com/DaGenix/rust-crypto/blob/master/examples/symmetriccipher.rs let mut final_result = Vec::<u8>::new(); let mut buffer = [0; 4096]; let mut write_buffer = RefWriteBuffer::new(&mut buffer); let mut read_buffer = RefReadBuffer::new(cipher_text); loop { let result = try!(decryptor.decrypt(&mut read_buffer, &mut write_buffer, true) .map_err(ErrorKind::DecryptionFailed)); final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i)); match result { BufferResult::BufferUnderflow => break, BufferResult::BufferOverflow => { } } } Ok(final_result) } /// Decrypts a `cipher_text`, returning a `Message` or an `Error`. pub fn decrypt(&self, cipher_text: &[u8]) -> Result<Message> { let mut header: Vec<u8> = Vec::new(); header.push(3); header.push(1); header.extend(self.encryption_salt.as_slice().iter()); header.extend(self.hmac_salt.as_slice().iter()); header.extend(self.iv.as_slice().iter()); //TODO: Do not depend from drain, as this is O(n). let mut cipher_text_vec = Vec::from(&cipher_text[34..]); let hmac_position = cipher_text_vec.len() - 32; let hmac0 = cipher_text_vec.drain(hmac_position..).collect(); let encrypted = cipher_text_vec.as_slice(); let message = try!(self.plain_text(encrypted)); let hmac = HMAC(hmac0); let computed_hmac = try!(HMAC::new(&Header(header), cipher_text_vec.as_slice(), &self.hmac_key)); match hmac.is_equal_in_consistent_time_to(&computed_hmac) { true => Ok(message), false => Err(Error::new(ErrorKind::HMACValidationFailed, "HMAC mismatch.".to_owned())), } } }
Java
UTF-8
795
2.078125
2
[]
no_license
package dev.chel_shev.tg_bot_quickstart.entity; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; @Entity @Data @Table(name = "user") @NoArgsConstructor public class UserEntity { @Id @GeneratedValue private Long id; private String firstName; private String lastName; private String userName; private Long chatId; @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InquiryEntity> inquiryList; public UserEntity(Long id, String firstName, String lastName, String userName, Long chatId) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.userName = userName; this.chatId = chatId; } }
Java
UTF-8
472
2.265625
2
[]
no_license
package mobomobo.dto; public class BookBestCommentLike { private int commentno; private int userno; @Override public String toString() { return "BookBestCommentLike [commentno=" + commentno + ", userno=" + userno + "]"; } public int getCommentno() { return commentno; } public void setCommentno(int commentno) { this.commentno = commentno; } public int getUserno() { return userno; } public void setUserno(int userno) { this.userno = userno; } }
Markdown
UTF-8
858
2.578125
3
[]
no_license
# REPL REPL enviroment to play with Elixir & Erlang, Mix project. ``` # Erlang erl # Elixir iex # With Mix project loaded iex -S mix # With Phoenix server started iex -S mix phx.server ``` # Debugging ## IO.inspect Simply prints out given data ``` IO.inspect(some_data, label: "A label") ``` ## IEx.pry or halt a execution and jump in to interact with the debugged code: ``` require IEx IEx.pry ``` Source: https://elixir-lang.org/getting-started/debugging.html ## `observer` GUI tool In `iex` session, you can invoke `:observer.start` to start the GUI tool for observing the Erlang system. There you can see the stats of the system, the supervision tree, processes information, etc,. # Code formatting Some text editors or IDEs have plugins to support this. If you want to format the code manually via terminal, you can run: ``` mix format ```
JavaScript
UTF-8
1,652
3
3
[]
no_license
/** * This reducer adds or updates state keys for action types with * async suffixes and does nothing for other action types. * Then, make-action-creator selectors may access specific actions * statuses and error messages easily. */ export const reducer = (state = {}, action) => { if (isAsync(action.type)) { const { base, sub } = breakAction(action.type); return { ...state, [base]: { status: sub === 'START' ? 'pending' : (sub === 'SUCCESS' ? 'success' : 'failure'), error: sub === 'FAILURE' ? getErrorMessage(action.payload) : null, response: ((sub === 'SUCCESS' || sub === 'FAILURE') && action.payload) ? action.payload : null } }; } if (action.type === 'CLEAR_STATUS') { return { ...state, [action.actionType]: undefined }; } return state; }; // Returs true if action type has an async suffix. function isAsync (type) { return ['START', 'SUCCESS', 'FAILURE'].indexOf(type.slice(type.lastIndexOf('_') + 1)) >= 0; } // Returns action type base (without suffix) and sub-action type suffix. function breakAction (type) { return { base: type.slice(0, type.lastIndexOf('_')), sub: type.slice(type.lastIndexOf('_') + 1) }; } // Find the error message. function getErrorMessage (payload) { if (!payload) { return null; } if (typeof payload === 'string') { return payload; } if (typeof payload.error === 'string') { return payload.error; } if (typeof payload.message === 'string') { return payload.message; } if (payload.error && payload.error.message) { return payload.error.message; } return null; }
C++
UTF-8
479
3.234375
3
[]
no_license
/*OVERLOADING OF FUNCTION*/ #include<iostream> #include<conio.h> using namespace std; add(int a) { cout<<"a+a="<<a+a<<endl; } add(int a,int b)//number of parameters { cout<<"a+b="<<a+b<<endl; } add(int a,float c)//type of parameters { cout<<"a+c="<<a+c<<endl; } add(float c,int a)//sequence of parameters { cout<<"a+c="<<a+c<<endl; } main() { int a,b; float c; cout<<"a="; cin>>a; cout<<"b="; cin>>b; cout<<"c="; cin>>c; add(a); add(a,b); add(a,c); add(c,a); }
JavaScript
UTF-8
3,913
2.65625
3
[]
no_license
/** * Level state. */ function Level() { Phaser.State.call(this); } /** @type Phaser.State */ var proto = Object.create(Phaser.State); Level.prototype = proto; Level.prototype.create = function() { this.game.score = 0; this.gameover = false; this.physics.startSystem(Phaser.Physics.ARCADE); this.player = this.add.sprite(this.world.cemerX,600,"ship"); this.player.anchor.set(0.5,0.5); this.player.animations.add("fly"); this.player.play("fly",12,true); this.player.smoothed = false; this.player.scale.set(2); this.physics.enable(this.player,Phaser.Physics.ARCADE); this.player.body.collideWorldBounds = true; this.player.body.allowGravity = false; this.player.body.maxVelocity.setTo(200,2000); this.createAlien(); this.createWeapon(); this.scoreText = this.add.text(32,0,' '+this.game.score,{fill: 'white'}); this.scoreText.z = 10; //this.addMonkey(); //this.moveMonkey(); this.input.keyboard.addKeyCapture([ Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.SPACEBAR, Phaser.Keyboard.X]); this.player,inputEnabled = true; this.player.events.onInputDown.add(this.fireWeapon,this); }; Level.prototype.update = function() { if(this.gameover) return; if(this.input.keyboard.isDown(Phaser.Keyboard.LEFT)){ this.player.body.acceleration.x = -600; }else if (this.input.keyboard.isDown(Phaser.Keyboard.RIGHT)){ this.player.body.acceleration.x = 600; }else{ this.player.body.velocity.setTo(0,0); this.player.body.acceleration.setTo(0,0); } }; Level.prototype.createWeapon = function() { this.weapon = this.add.weapon(10,"weapon",1); this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.weapon.trackSprite(this.player,-20,-30); this.weapon.bulletSpeed = 500; this.weapon.fireAngle = 270; this.weapon.rate = 600; this.weapon2 = this.add.weapon(10,"weapon2",2); this.weapon2.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.weapon2.trackSprite(this.player,-20,-30); this.weapon2.bulletSpeed = 500; this.weapon2.fireAngle = 270; this.weapon2.rate = 600; }; Level.prototype.fireWeapon = function() { // stop all monkey's movements //this.tweens.removeAll(); this.weapon.fire(); this.weapon2.fire(); /* // rotate monkey var twn = this.add.tween(this.monkey); twn.to({ angle : this.monkey.angle + 360 }, 1000, "Linear", true); // scale monkey twn = this.add.tween(this.monkey.scale); twn.to({ x : 0.1, y : 0.1 }, 1000, "Linear", true); // when tween completes, quit the game twn.onComplete.addOnce(this.quitGame, this);*/ }; Level.prototype.createAlien = function(){ this.aliens = this.add.group(this.game.world,'aliens',false,true,Phaser.Physics.ARCADE); this.aliens.z = 100; for(i=0;i<30;i++){ a = this.aliens.create(Math.random()*300,-Math.random()*300,"aliens"); a.animations.add("fly").play(12,true); a.anchor.set(0.5); a.body.velocity.y = 50; tw = this.add.tween(a); var nx = 20+Math.random()*300; var nt = Math.random()*500; tw.to({x:nx},1000+nt,"Sine",true,0,Number.MAX_VALUE,true); if(Math.random()>0.5) a.body.angularVelocity = 60; else a.body.angularVelocity = -60; } }; Level.prototype.update = function(){ if(this.gameover) return; if(this.input.keyboard.isDown(Phaser.Keyboard.LEFT)){ this.player.body.acceleration.x = -600; }else if(this.input.keyboard.isDown(Phaser.Keyboard.RIGHT)){ this.player.body.acceleration.x = 600; }else{ this.player.body.velocity.setTo(0, 0); this.player.body.acceleration.setTo(0, 0); } if(this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)){ this.fireWeapon();} this.aliens.forEachAlive(function(a){ if(a.y > this.world.height) a.y = -Math.random() * 300; },this); }; Level.prototype.quitGame = function() { this.game.state.start("Menu"); };
C++
UTF-8
644
3.21875
3
[]
no_license
// Author: Chris Darnell // Date: 6/2/2016 // Description: Project 10.a - Board.hpp #ifndef Board_hpp #define Board_hpp #include <iostream> #include <cstdlib> using namespace std; // Write a class called Board that represents a tic-tac-toe board. It should have a 3x3 array as a data member, which will store the locations of the players' moves. enum gameStatus {X_WON, O_WON, DRAW, UNFINISHED}; class Board { private: gameStatus status; char board[3][3]; int moveX, moveY; public: Board(); void print(); bool makeMove(char, int, int); gameStatus gameState(); }; #endif /* Board_hpp */
C++
UTF-8
3,151
2.71875
3
[]
no_license
/* Copyright (c) 2015, Elias Aebi 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. */ #pragma once #include <cstdio> #include <cstdlib> #include <cstring> class Character { char c; public: Character (char c): c(c) {} operator char () const { return c; } bool is_whitespace () const { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ','; } bool is_alphabetic () const { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } bool is_numeric () const { return c >= '0' && c <= '9'; } bool is_alphanumeric () const { return is_alphabetic() || is_numeric(); } }; class String { char* data; public: String (const char* file_name) { FILE* file = fopen (file_name, "r"); if (!file) { data = nullptr; fprintf (stderr, "error: cannot open file\n"); return; } fseek (file, 0, SEEK_END); int length = ftell (file); rewind (file); data = (char*) malloc (length+1); fread (data, 1, length, file); data[length] = '\0'; fclose (file); } ~String () { free (data); } Character operator [] (int i) const { return data[i]; } const char* get_data () const { return data; } }; class Substring { const char* start; int length; public: Substring (const char* start, int length): start(start), length(length) {} Substring (const char* string): start(string), length(strlen(string)) {} void write (FILE* file) const { fwrite (start, 1, length, file); } bool operator == (const Substring& s) const { if (length != s.length) return false; return strncmp (start, s.start, length) == 0; } bool operator < (const Substring& s) const { int r = strncmp (start, s.start, length < s.length ? length : s.length); if (r == 0) return length < s.length; else return r < 0; } };
PHP
UTF-8
2,797
2.625
3
[]
no_license
<?php namespace Entities; use Doctrine\ORM\Mapping as ORM; use Ilmatar\BaseEntity; use Ilmatar\Exception\TranslatedException; /** * Permission */ class Permission extends BaseEntity { //Test PHPUnit ImportHelper, name don't exist. public static $allowedFieldsToImport = ['type.code']; const ACCESS_READ = 0; const ACCESS_READWRITE = 1; /** * @var integer */ private $id; /** * @var integer */ private $type = self::ACCESS_READ; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set type * * @param integer $type * @return Permission */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return integer */ public function getType() { return $this->type; } /** * @var \Entities\Role */ private $role; /** * @var \Entities\Functionality */ private $functionality; /** * Set role * * @param \Entities\Role $role * @return Permission */ public function setRole(\Entities\Role $role = null) { $this->role = $role; return $this; } /** * Get role * * @return \Entities\Role */ public function getRole() { return $this->role; } /** * Set functionality * * @param \Entities\Functionality $functionality * @return Permission */ public function setFunctionality(\Entities\Functionality $functionality = null) { $this->functionality = $functionality; return $this; } /** * Get functionality * * @return \Entities\Functionality */ public function getFunctionality() { return $this->functionality; } public function setReadOn() { $this->type = self::ACCESS_READ; } public function setWriteOn() { $this->type = self::ACCESS_READWRITE; } public function isWriteOn() { return ($this->type == self::ACCESS_READWRITE); } public function isReadOn() { //if this perm exists, there is at least the R right return true; } /** * @ORM\PrePersist */ public function assertValidPermission() { if (!in_array($this->type, array_keys(self::getAllTypes()))) { throw new TranslatedException('The field "%s" must be valid.', array('trans:Type')); } } public static function getAllTypes() { return array( self::ACCESS_READ => 'Read', self::ACCESS_READWRITE => 'Read + Write' ); } }
Python
UTF-8
2,631
3.671875
4
[]
no_license
from random import random from scipy.stats.distributions import chi2 import math N = 50 P = 0.7 CANT = 10 def generator_v_a_bin(n, p): ''' Esta funcion simplemente me genera un valor de la variable aleatoria binomial(n,p) ''' U = random() c = p / float(1-p) i = 0 pr = (1-p)**n F = pr while (U > F): pr = ((c*(n-i))/float(i+1))*pr F = F + pr i += 1 X = i return X def generator_vector(cant): ''' Esta funcion genera un vector de valores de observaciones para cada valor en el rango de la binomial. Se simula cant veces y cada resultado se guarda en su celda correspondiente ''' vector = [0,0,0,0,0,0] for _ in range(cant): value = generator_v_a_bin(N, P) vector[value] += 1 return vector def generator_media(values): media = 0 n = len(values) for i in range(n): media += values[i] return media/ float(n) def generator_variance(values, media): n = len(values) varizance = 0 for i in range(n): varizance += (values[i] - media)**2 varizance = varizance/ float(n - 1) return varizance def generator_v_binomiales(cant): values = [] for _ in range(cant): U = generator_v_a_bin(N, P) values.append(U) return values values = generator_v_binomiales(CANT) print "values", values media = generator_media(values) print "media: ", media variance = generator_variance(values, media) print "variance: ", variance def generator_probs(): ''' Esta funcion me genera el vector de probabilidades para mi v.a. binomial(n,p) ''' probs = [] for i in range(N+1): prob_i = binomial(N, i) * (P**i) * ((1-P)**(N-i)) probs.append(prob_i) return probs def binomial(n,k): ''' Simplement calcula el binomio de newton para los valores n, k ''' fact = math.factorial return fact(n)/float(fact(k)*fact(n-k)) def generator_T(values, probs): ''' Esta funcion genera mi estadistico T en base a la muestra y a las probabilidades que tiene cada valor en el rango ''' resultado = 0 n = sum(values) for i in range(len(values)): resultado += ((values[i] - n*probs[i])**2)/float(n*probs[i]) return resultado def valor_p(T): return chi2.sf(T,N-1) #new_values = generator_vector(CANT) #probs = generator_probs() #T = generator_T(new_values, probs) #print new_values #print T #print valor_p(T) def generator_T_prom(times, value): ''' En el caso de que mi primer T valor estimado este cerca de un valor critico, simulamos ''' promedio = 0 for _ in range(times): vector = generator_vector(CANT) T = generator_T(vector, probs) if T > value: promedio += 1 promedio = promedio / float(times) return promedio #print generator_T_prom(40, 10.8057930007)
Python
UTF-8
9,004
2.78125
3
[]
no_license
import sqlite3 from sqlite3 import Error from datetime import datetime from time import sleep acc_index = 100 database = r"bank_management.db" # creates Object_1 database if it doesn't exist, or creates Object_1 connection if the database exists def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create Object_1 table from the create_table_sql statement :param conn: Connection object :param create_table_sql: Object_1 CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def creare_cont(connection): """Functia va lua inputurile de mai jos si va crea un cont.""" print('Creare cont nou...') proprietar = input("Titularul contului: ") sinput = True while sinput is True: try: sold = int(input("Suma depusa (sold initial, doar suma intreaga): ")) sinput = False except ValueError: print("Valoarea introdusa nu este valida!") print("Introduceti o suma intreaga, multiplu de 1!") tip_cont = input("Introduceti tipul contului (curent/economii): ") azi = datetime.now() # creez data de astazi folosind datetime dc = azi.strftime("%d/%m/%Y %H:%M:%S") # formatez azi in formatul dd/mm/YY H:M:S # print(type(dc)) data_crearii = dc data_ultimei_modificari = dc account = (proprietar, sold, tip_cont, data_crearii, data_ultimei_modificari) sql = '''INSERT INTO conturi(proprietar, sold, tip_cont, data_crearii, data_ultimei_modificari) VALUES (?,?,?,?,?)''' cur = connection.cursor() cur.execute(sql, account) # print(cur.lastrowid) return cur.lastrowid def afisare(conn): cur = conn.cursor() cur.execute("SELECT * FROM conturi") rows = cur.fetchall() for row in rows: print(f'Numar cont: {row[0]}\nNume: {row[1]}\nSold: {row[2]}') print() def extras(conn): # identific contul, specific numarul lui print("Extras de cont...") loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") print("Introduceti o suma intreaga, multiplu de 1!") cur = conn.cursor() cur.execute("SELECT * FROM conturi WHERE numar_cont=?", (nrcont,)) rows = cur.fetchall() for row in rows: print(f'Numar cont: {row[0]}') print(f'Nume: {row[1]}') print(f'Sold: {row[2]}') print(f'Tip cont: {row[3]}') print(f'Data crearii: {row[4]}') print(f'Data ultimei modificari: {row[5]}') print() def update_cont(conn, cont): sql = '''UPDATE conturi SET sold = ?, data_ultimei_modificari = ? WHERE numar_cont = ?''' cur = conn.cursor() cur.execute(sql, cont) conn.commit() def depunere(conn, suma): # identific contul, specific numarul lui loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") print("Introduceti o suma intreaga, multiplu de 1!") # citesc datele din cont cur = conn.cursor() cur.execute("SELECT * FROM conturi WHERE numar_cont=?", (nrcont,)) # creez o variabila in care o sa stochez datele contului - tip tuple rows = cur.fetchall() sold_actual = rows[0][2] sold_modificat = sold_actual + suma azi = datetime.now().strftime("%d/%m/%Y %H:%M:%S") # modific soldul update_cont(conn, (sold_modificat, azi, nrcont)) def retragere(conn, suma): # identific contul, specific numarul lui loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") print("Introduceti o suma intreaga, multiplu de 1!") # citesc datele din cont cur = conn.cursor() cur.execute("SELECT * FROM conturi WHERE numar_cont=?", (nrcont,)) # creez o variabila in care o sa stochez datele contului - tip tuple rows = cur.fetchall() sold_actual = rows[0][2] sold_modificat = sold_actual - suma azi = datetime.now().strftime("%d/%m/%Y %H:%M:%S") # modific soldul update_cont(conn, (sold_modificat, azi, nrcont)) def deleteAcc(conn): print("Inchidere cont...") loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") sql = 'DELETE FROM conturi WHERE numar_cont=?' cur = conn.cursor() cur.execute(sql, (nrcont,)) conn.commit() def update_proprietar(conn): loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") proprietar = input("Introduceti numele proprietarului: ") azi = datetime.now().strftime("%d/%m/%Y %H:%M:%S") sql = '''UPDATE conturi SET proprietar = ?, data_ultimei_modificari = ? WHERE numar_cont = ?''' cur = conn.cursor() cur.execute(sql, (proprietar, azi, nrcont)) conn.commit() def update_tip_cont(conn): loop = True while loop is True: try: nrcont = int(input("Introduceti numarul contului: ")) loop = False except ValueError: print("Valoarea introdusa nu este valida!") tipcont = input("Introduceti tipul contului: ") azi = datetime.now().strftime("%d/%m/%Y %H:%M:%S") sql = '''UPDATE conturi SET tip_cont = ?, data_ultimei_modificari = ? WHERE numar_cont = ?''' cur = conn.cursor() cur.execute(sql, (tipcont, azi, nrcont)) conn.commit() sql_create_table = """CREATE TABLE IF NOT EXISTS conturi ( numar_cont integer PRIMARY KEY, proprietar text NOT NULL, sold integer, tip_cont text NOT NULL, data_crearii text NOT NULL, data_ultimei_modificari text NOT NULL ); """ conn = create_connection(database) if conn is not None: create_table(conn, sql_create_table) else: print("Error! Cannot create the database connection.") print("******************************************************************************************************") print('Bank Management Soft v1.2 beta') print("******************************************************************************************************") running = True while running == True: print() print("MENU") print('1. Adauga cont nou') print('2. Depune numerar') print('3. Retrage numerar') print('4. Extras de cont') print('5. Afisare conturi') print('6. Inchide cont') print('7. Modifica cont') print('8. Exit') print("------------------------------------------------------------------------------------------------------") opt = input("Alegeti una din optiunile de mai sus: ") if opt == '1': creare_cont(conn) elif opt == '2': suma = int(input("Introduceti suma depusa: ")) depunere(conn, suma) elif opt == '3': suma2 = int(input("Introduceti suma retrasa: ")) retragere(conn, suma2) elif opt == '4': extras(conn) elif opt == '5': afisare(conn) elif opt == '6': deleteAcc(conn) elif opt == '7': print('Selectati una din urmatoarele optiuni:') print('1. Modificare nume proprietar') print('2. Modificare tip cont') opt7 = input('Optiune: ') if opt7 == '1': update_proprietar(conn) elif opt7 == '2': update_tip_cont(conn) else: print('Optiunea nu este valida') elif opt == '8': print("Inchidere program...") sleep(1.5) running = False else: print('Optiunea nu este valida!') print("Alegeti una din optiunile de mai sus prin tastarea numarului corespondent.")
Python
UTF-8
1,232
2.921875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from io import BytesIO import tarfile from urllib.request import urlopen url = 'http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz' b = BytesIO(urlopen(url).read()) fpath = 'CaliforniaHousing/cal_housing.data' with tarfile.open(mode='r', fileobj=b) as archive: housing = np.loadtxt(archive.extractfile(fpath), delimiter=',') value = housing[:,-1] pop,age = housing[:,[4,7]].T def add_innerbox(ax,text): ax.text(.55,.8,text, horizontalalignment='center', transform=ax.transAxes, bbox=dict(facecolor='white',alpha=0.6), fontsize=12.5) gridsize = (3,2) fig = plt.figure(figsize=(12,8)) ax1 = plt.subplot2grid(gridsize,(0,0),colspan=2, rowspan=2) ax2 = plt.subplot2grid(gridsize,(2,0)) ax3 = plt.subplot2grid(gridsize,(2,1)) ax1.set_title('Home value as a function of home age (x) & area population (y)', fontsize=14) sctr = ax1.scatter(x=age,y=pop,c=value,cmap='RdYlGn') plt.colorbar(sctr,ax=ax1,format='$%d') ax1.set_yscale('log') ax2.hist(age,bins='auto') ax3.hist(pop,bins='auto',log=True) add_innerbox(ax2,'Histogram: home age') add_innerbox(ax3,'Histogram: area population (log scl.)') plt.show()
Markdown
UTF-8
831
2.875
3
[]
no_license
# daily_account_book 基于nebulas的日常记账本小程序 网址:http://www.luoam.com/daily_account_book/index.html 记账本这个小东西,我们平时生活中也用得到,而且记账是一个好习惯。 基于星云链开发这个日常记账本,具有一些优点: 1. 账单信息保存在星云链,账单信息不可更改,一点记了一笔,就永久存在了。 2. 账单数据永久在线,无论何时何地,可以随时从星云链上把所有自己记过的账单下载下来。 3. 无限制的记账,不用担心账本用完了,也就是永远不需要换账本。 。。。 目前,主要提供了NAS,美元以及人民币作为记账单位。 可以批量查看所有的账单 ![accountbooks](https://raw.githubusercontent.com/luoam/daily_account_book/master/img/books.PNG)
Python
UTF-8
4,036
2.53125
3
[]
no_license
# 1012.py import cv2 import numpy as np #1 roi = None drag_start = None mouse_status = 0 tracking_start = False def onMouse(event, x,y, flags, param = None): global roi global drag_start global mouse_status global tracking_start if event == cv2.EVENT_LBUTTONDOWN: drag_start = (x,y) mouse_status = 1 tracking_start = False elif event == cv2.EVENT_MOUSEMOVE: if flags == cv2.EVENT_FLAG_LBUTTON: xmin = min(x, drag_start[0]) ymin = min(y, drag_start[1]) xmax = max(x, drag_start[0]) ymax = max(y, drag_start[1]) roi = (xmin, ymin, xmax, ymax) mouse_status = 2 # dragging elif event == cv2.EVENT_LBUTTONUP: mouse_status = 3 # complete #2 cv2.namedWindow('tracking') cv2.setMouseCallback('tracking', onMouse) cap = cv2.VideoCapture('../data/ball.wmv') if ( not cap.isOpened() ): print('Error opening video.') h,w = (int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))) roi_mask = np.zeros((h,w), dtype = np.uint8) term_crit = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 10, 1) #3: Kalman filter setup q = 1e-5 # process noise covariance r = 0.01 # measurement noise covariance, 1, 0.0001 dt = 1 KF = cv2.KalmanFilter(4,2,0) KF.transitionMatrix = np.array([[1,0,dt,0], [0,1,0,dt], [0,0,1,0], [0,0,0,1]], np.float32) # A KF.measurementMatrix = np.array([[1,0,0,0], [0,1,0,0]], np.float32) # H #4 t = 0 while True: ret, frame = cap.read() if not ret: break t += 1 print('t = ', t) frame2 = frame.copy() # CamShift hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, (0, 60, 32), (180, 255, 255)) if mouse_status == 2: x1,y1,x2,y2 = roi cv2.rectangle(frame, (x1,y1), (x2,y2), (0,0,255), 2) if mouse_status == 3: print('initialize...') mouse_status = 0 x1,y1,x2,y2 = roi mask_roi = mask[y1:y2, x1:x2] hsv_roi = hsv[y1:y2, x1:x2] hist_roi = cv2.calcHist([hsv_roi], [0], mask_roi, [16], [0,180]) cv2.normalize(hist_roi, hist_roi, 0, 255, cv2.NORM_MINMAX) H1 = hist_roi.copy() cv2.normalize(H1, H1, 0.0, 1.0, cv2.NORM_MINMAX) track_win = (x1,y1,x2-x1,y2-y1) # meanShift #4-1: Kalman filter initialize KF.processNoiseCov = q * np.eye(4, dtype = np.float32) # Q KF.measurementNoiseCov = r * np.eye(2, dtype = np.float32) # R KF.errorCovPost = np.eye(4, dtype = np.float32) # P0 = I x,y,w,h = track_win cx = x+w / 2 cy = y+h / 2 KF.statePost = np.array([[cx],[cy],[0.],[0.]], dtype = np.float32) tracking_start = True if tracking_start: #4-2 predict = KF.predict() #4-3: CamShift tracking backP = cv2.calcBackProject([hsv], [0], hist_roi, [0,180], 1) backP &= mask track_box, track_win = cv2.CamShift(backP, track_win, term_crit) cv2.ellipse(frame, track_box, (0,0,255), 2) cx,cy = track_box[0] cv2.circle(frame, (round(cx), round(cy)), 5, (0,0,255), -1) ## pts = cv2.boxPoints(track_box) ## pts = np.int0(pts) # np.int32 ## dst = cv2.polylines(frame2, [pts], True, (0,0,255), 2) #4-4: Kalman correct z = np.array([cx,cy], dtype = np.float32) # measurement # error here estimate = KF.correct(z) estimate = np.int0(estimate) #4-5 cx2,cy2 = estimate[0][0], estimate[1][0] track_box2 = ((cx2,cy2), track_box[1], track_box[2]) cv2.ellipse(frame, track_box2, (255,0,0), 2) cv2.circle(frame, (cx2,cy2), 5, (255,0,0), -1) ## track_win = x2,y2,w,h cv2.imshow('tracking', frame) # meanShift key = cv2.waitKey(25) if key == 27: break if cap.isOpened(): cap.release() cv2.destroyAllWindows()
Go
UTF-8
3,462
2.671875
3
[]
no_license
package io /* #cgo CFLAGS: -std=c99 #cgo LDFLAGS: -lcomedi -lm #include "io.h" #include "channels.h" #include "elev.h" */ import "C" import "Heisprosjekt/src" import "fmt" import "time" import "os" /* Name-conventions: FC = From Controller TC = To Controller */ type Command struct{ CommandType int SetValue int Floor int ButtonType int } const( SET_BUTTON_LAMP = 0 SET_MOTOR_DIR = 1 SET_FLOOR_INDICATOR_LAMP = 2 SET_DOOR_OPEN_LAMP = 3 ) func InitIo(chCommandFC chan Command, chOrderTC chan src.ButtonOrder, chFloorTC chan int){ err := C.elev_init() if err < 0 { fmt.Println("Could not initialize hardware") os.Exit(1) } var chOrder = make(chan src.ButtonOrder) var chFloor = make(chan int) go ioManager(chCommandFC,chOrderTC,chFloorTC,chOrder,chFloor) go pollFloor(chFloor) go pollOrder(chOrder) } func ioManager( chCommandFC chan Command, chOrderTC chan src.ButtonOrder,chFloorTC chan int, chOrder chan src.ButtonOrder, chFloor chan int){ for{ select{ case order := <- chOrder: chOrderTC <- order case floor := <- chFloor: chFloorTC <- floor case command := <- chCommandFC: runCommand(command) } } } func pollOrder(chOrder chan src.ButtonOrder){ var isButtonPushed[src.N_FLOORS][3]bool for{ for floor := 0; floor < src.N_FLOORS; floor++{ if(floor < src.N_FLOORS-1){ if(isNewOrder(floor, src.BUTTON_UP,&isButtonPushed)){ chOrder <- src.ButtonOrder{floor, src.BUTTON_UP} } } if(floor > 0){ if(isNewOrder(floor, src.BUTTON_DOWN,&isButtonPushed)){ chOrder <- src.ButtonOrder{floor, src.BUTTON_DOWN} } } if(isNewOrder(floor, src.BUTTON_INSIDE, &isButtonPushed)){ chOrder <- src.ButtonOrder{floor, src.BUTTON_INSIDE} } } time.Sleep(10*time.Millisecond) } } func isNewOrder(floor int, buttonType int, isButtonPushed *[src.N_FLOORS][3]bool) bool{ if (C.elev_get_button_signal(C.elev_button_type_t(buttonType), C.int(floor)) == 1 && !isButtonPushed[floor][buttonType]) { isButtonPushed[floor][buttonType] = true return true }else if(C.elev_get_button_signal(C.elev_button_type_t(buttonType), C.int(floor)) == 0 && isButtonPushed[floor][buttonType]){ isButtonPushed[floor][buttonType] = false return false } return false } func pollFloor(chFloor chan int){ previousFloor := -1 for { floor := int(C.elev_get_floor_sensor_signal()) if floor != -1 && floor != previousFloor{ chFloor <- floor previousFloor = floor } time.Sleep(50*time.Millisecond) } } func runCommand(command Command){ switch command.CommandType{ case SET_MOTOR_DIR: C.elev_set_motor_direction(C.elev_motor_direction_t(command.SetValue)) case SET_BUTTON_LAMP: switch command.ButtonType{ case src.BUTTON_UP: if(command.Floor < src.N_FLOORS-1) { C.elev_set_button_lamp(C.elev_button_type_t(command.ButtonType), C.int(command.Floor), C.int(command.SetValue)) } case src.BUTTON_DOWN: if(command.Floor > 0){ C.elev_set_button_lamp(C.elev_button_type_t(command.ButtonType), C.int(command.Floor), C.int(command.SetValue)) } case src.BUTTON_INSIDE: C.elev_set_button_lamp(C.elev_button_type_t(command.ButtonType), C.int(command.Floor), C.int(command.SetValue)) } case SET_FLOOR_INDICATOR_LAMP: C.elev_set_floor_indicator(C.int(command.Floor)) case SET_DOOR_OPEN_LAMP: C.elev_set_door_open_lamp(C.int(command.SetValue)) } }
SQL
UTF-8
1,189
4.1875
4
[ "MIT" ]
permissive
-- perform a SELECT query on Orders table available in the database SNOWFLAKE_DEMO_DB, schema TPCH_SF1000. select * from "SNOWFLAKE_SAMPLE_DATA"."TPCH_SF1000"."ORDERS" sample row (1000 rows); --execute a count on the O_CUSTKEY column while applying grouping on O_ORDERPRIORITY. select O_ORDERPRIORITY ,count(O_CUSTKEY) from "SNOWFLAKE_SAMPLE_DATA"."TPCH_SF1000"."ORDERS" group by 1 order by 1; --to stop Snowflake from using results from cache , we shall change one setting. We shall alter the session and set USE_CACHED_RESULT to FALSE first ALTER SESSION SET USE_CACHED_RESULT = FALSE; --calculate the same count but with a variation this time. We will apply a DISTINCT on the O_CUSTKEY column, so that customers with repeat orders are counted once. SELECT O_ORDERPRIORITY ,count(DISTINCT O_CUSTKEY) from "SNOWFLAKE_SAMPLE_DATA"."TPCH_SF1000"."ORDERS" group by 1 order by 1; --try the same thing but this time, we shall use the APPROX_COUNT_DISTINCT function on the O_CUSTKEY column, rather than the COUNT(DISTINCT …) function used in step 3. select O_ORDERPRIORITY ,APPROX_COUNT_DISTINCT(O_CUSTKEY) from "SNOWFLAKE_SAMPLE_DATA"."TPCH_SF100"."ORDERS" group by 1 order by 1;
Markdown
UTF-8
25,601
3.375
3
[ "MIT" ]
permissive
--- path: '/Algorithm-Design-Manual--Chapter-Six' cover: '../Programming-Foundations-Coding-Efficiency/speed.jpg' slug: 'Algorithm-Design-Manual--Chapter-Six' date: '2019-01-18' title: 'Algorithm Design Manual:' chapter: 'Chapter Six' subtitle: 'Weighted Graph Algorithms' tags: ['algorithms', 'graphs', 'Algorithm Design Manual'] published: true --- Chapter 5's graph data structure quietly supported edge-weighted graphs, but we'll make it explicit for this chapter. The adjacency list structure consists of an array of linked lists where the outgoing edges from vertex.x appear in the list edges[x] ```c typedef struct { edgenode *edges[MAXV+1]; /* adjacency info */ int degree[MAXV+1]; /* outdegree of each vertex */ int nvertices; /* number of vertices in graph */ int nedges; /* number of edges in graph */ int directed; /* is the graph directed? */ } graph; ``` Each edgenode is a record with three fields: first describing second endpoint of the edge (y), second enabling us to annotate the edge with a weight (weight) and third to annotate the next edge in the list (nex): ```c typedef struct { int y; /* adjacency info */ int weight; /* edge weight, if any */ struct edgenode *next; /* next edge in list */ } edgenode; ``` ### Minimum Spanning Trees A spanning tree of a graph G = (V, E) is a subset of edges from E forming a tree connecting all vertices of V. For edge-weighted graphs, a tree whose sum of edge weights is as small as possible is a minimum spanning tree. There can be more than one minimum spanning tree in a graph. All spanning trees of an unweighted graph are minimum spanning trees. ### Prim's Algorithm Starts from one vertex and grows the rest of the tree one edge at a time until all vertices included Prim-MST(G) &nbsp;&nbsp;&nbsp;&nbsp;Select an arbitrary vertex s to start the tree from &nbsp;&nbsp;&nbsp;&nbsp;While (therre are still nontree vertices) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Select the edge of minimum weight between a tree and nontree vertex &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add the selected edge and vertex to the tree T<sub>prim</sub> ```c prim(graph *g, int start) { int i; /* counter */ edgenode *p; /* temporary pointer */ bool intree[MAXV+1]; /* is the vertex in the tree yet? */ int distance[MAXV+1]; /* cost of adding to tree */ int v; /* current vertex to process */ int w; /* candidate next vertex */ int weight; /* edge weight */ int dist; /* best current distance from start */ for (i = 1; i <= g->nvertices; i++) { intree[i] = False distance[i] = MAXINT; parent[i] = -1; } distance[start] = 0; v = start; while (intree[v] == False) { intree[v] = True; p = g->edges[v]; while (p != NULL) { w = p->y; weight = p->weight; if ((distance[w] > weight) && (intree[v] == False)) { distance[w] = weight; parent[w] = v; } p = p->next; } v = 1; dist = MAXINT; for (i = 1; i <= g->nvertices; i++) if ((intree[i] == False) && (dist > distance[i])) { dist = distance[i]; v = i; } } } ``` This is an O(n<sup>2</sup>) implementation. Priority-queue data structures lead to an O(m + n lg n) implementation by making it faster to find the minimum cost edge to expand the tree at each iteration. ### Kruskal's Algorithm Builds up connected components of vertices, culminating in the minimum spanning tree. Initially, each vertex forms its own separate component in the tree to be. The algorithm repeatedly considers the lightest remaining edge and tests whether its two endpoints lie within the same connected component. If so, the edge will be discarded because adding it would create a cycle in the tree to be. If the endpoints are in different components, we insert the edge and merge the two components into one. Since each connected component is always a tree, don't have to test for cycles. Kruskal-MST(G) &nbsp;&nbsp;&nbsp;&nbsp;Put the edges in a prirority queue ordered by weight &nbsp;&nbsp;&nbsp;&nbsp;count = 0 &nbsp;&nbsp;&nbsp;&nbsp;while (count < n-1) do &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;get next edge(v, w) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (component(v) does not equal component(w)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add to T<sub>kruskal</sub> What is the time complexity? - Sorting the m edges takes O(m lg m) time - The for loop makes m iterations, each testing the connectivity of two trees plus an edge. In the most simple-minded approach, this can be implemented by breadth-first or depth-first search in a sparse graph with at most n edges and n vertices, thus yielding an O(mn) algorithm. Faster implementation results if we can implement the component test in faster than O(n) time. Union-find is a data structure that can support such queries in O(lg n) time, allowing Kruskal's algorithm to run in O(m lg m) time, faster than Prim's for sparse graphs. ```c kruskal(graph *g) { int i; /* counter */ set_union s; /* set union data structure */ edge_pair e[MAXV+1]; /* array of edges data structure */ bool weight_compare(); set_union_init(&s, g->nvertices); to_edge_array(g, e); /* sort edges by increasing cost */ qsort(&e, g->nedges, sizeof(edge_pair), weight_compare); for (i = 0; i < (g->nedges); i++) { if (!same_component(s, e[i].x, e[i].y)) { printf("edge (%d, %d) in MST\n", e[i].x, e[i].y); union_sets(&s, e[i].x, e[i].y); } } } ``` ### Union-Find Data Structure A set partition is a partitioning of the elements of some universal set (say integers 1 to n) into a collection of disjointed subsets. Each element must be in exactly one subset. The connected components in a graph can be represented as a set partition. For Kruskal's algorithm to run efficiently, we need a data structure that efficiently supports the following operations: - _Same component(V<sub>1</sub>, V<sub>2</sub>)_ - Do vertices V<sub>1</sub> and V<sub>2</sub> occur in the same connected component of the current graph? - _Merge components(C<sub>1</sub>, C<sub>2</sub>)_ - Merge the given pair of connected components into one component in response to an edge between them. The union-find data structure represents each subset as a "backwards" tree, with pointers from a node to its parent. Each node of this tree contains a set el.ement and the name of the set is taken from the key at the root. ```c typedef struct { int p[SET_SIZE+1]; /* parent element */ int size[SET_SIZE+1]; /* number of elements in subtree */ int n; /* number of elements in set */ } set_union; ``` We implement desired ops in terms of operations _union_ and _find_: - _Find(i)_ - Find the root of tree containing element _i_ by walking up the parent pointers until there is nowhere to go. Return the lable of the root. - _Union(i, j)_ - Link the root of one of the trees (say containing i) to the root of the tree containing the other (say j) so _find(i)_ now equals _find(j)_. To minimize tree height, it is better to make the smaller tree the subtree of the larger one. The height of all the nodes in the root subtree stay the same while the height of the nodes merged into the tree all increase by one. Thus, merging in the smaller tree leaves the height unchanged on the larger set of vertices ```c set_union_init(set_union *s, int n) { int i; /* counter */ for (i = 1; i <= n; i++) { s->p[i] = i; s->size[i] = 1; } s->n = n; } int find(set_union *s, int x) { if (s->p[x] == x) return x; else return find(s, s->p[x]); } int union_sets(set_union *s, int s1, int s2) { int r1, r2; /* roots of sets */ r1 = find(s, s1); r2 = find(s, s2); if (r1 == r2) return; /* already in same set */ if (s->size[r1] >= s->size[r2]) { s->size[r1] = s->size[r1] + s->size[r2]; s->p[r2] = r1; } else { s->size[r2] = s->size[r1] + s->size[r2]; s->p[r1] = r2; } } bool same_component(set_union *s, int s1, int s2) { return (find(s, s1) == find(s, s2)) } ``` On each union, the tree with fewer nodes becomes the child. Only when merging two height 2 trees do we get a tree of height 3 (now with four nodes). At most, we can do lg<sub>2</sub>n doublings to use up all n nodes, so we can do both unions and finds in O(log n) time. ### Variations on Minimum Spanning Trees - _Maximum Spanning Trees_ - The maximum spanning tree of any graph can be found by simply negating the weights of all edges and running Prim's algorithm. The most negative tree in the negated graph is the maximum spanning tree in the original. Most graph algorithms do not adapt so easily to negative numbers. - _Minimum Product Spanning Trees_ - Since lg(a <sup>.</sup> b) = lg(a) + lg(b), the minimum spanning tree on a graph whose edge weights are replaced with their logarithms gives the minimum product spanning tree on the original graph - _Minimum Bottleneck Spanning Tree_ - Tree that minimizes the maximum edge weight over all trees The minimum spanning tree of a graph is unique if all m edge weights in the graph are distinct. Otherwise, the way Prim's/Kruskal's algorithms break ties determines which minimum spanning tree is returned. Two variants of minimum spanning tree not solvable with these techniques: - _Steiner tree_ - If you want to wire a bunch of houses together but have the freedom to add extra intermediate vertices to serve as a shared junction - _Low-degree Spanning Tree_ - If you want to find the minimum spanning tree where the highest degree node in the tree is small. The lowest max-degree tree possible would be a simple path and have n-2 nodes of degree 2 with two endpoints of degree 1. A path that visits each vertex once is called a Hamiltonian path. ### Shortest Paths A path is a sequence of edges connecting two vertices. The shortest path from _s_ to _t_ in an unweighted graph can be constructed using a breadth-first search from _s_. ### Dijkstra's Algorithm The method of choice for finding the shortest path in an edge and/or vertex-weighted graph. Given a particular start vertex _s_, it finds the shortest path from _s_ to every other vertex in the graph, including your desired destination _A_. Dijkstra's Algorithm proceeds in a series of rounds where each round establishes the shortest path from _s_ to some new vertex. Specifically, _x_ is the vertex that minimizes the _dist(s, v<sub>1</sub>) + w(v<sub>1</sub>, x)_ over all unfinished 1 ≤ _i_ ≤ _n_ where _w(i, j)_ is the length of the edge from _i_ to _j_ and _dist(i, j)_ is the length of the shortest path between them. ShortestPath-Dijkstra(G, s, t) &nbsp;&nbsp;&nbsp;&nbsp;known = {s) &nbsp;&nbsp;&nbsp;&nbsp; for i = 1 to n, dist[i] = infinity &nbsp;&nbsp;&nbsp;&nbsp; for each edge (s, v), dist[v] = w(s, v) &nbsp;&nbsp;&nbsp;&nbsp; last = s &nbsp;&nbsp;&nbsp;&nbsp;while (last does not equal t) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;select v<sub>next</sub>, the unkonwn vertex minimizing dist[v] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for each edge(v<sub>next, x), dist[x] = min[dist[x], dist[v<sub>next</sub>] + w(v<sub>next</sub>, x)] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;last = v<sub>next</sub> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;known = known U {v<sub>next</sub>} In each iteration, we add one vertex to the tree of vertices for which we know the shortest path from _s_. We keep track of best path seen for all vertices outside the tree and insert them in order of increasing cost. ```c dijkstra(graph *g, int start) { int i; /* counter */ edgenode *p; /* temporary pointer */ bool intree[MAXV+1]; /* is the vertex in the tree yet? */ int distance[MAXV+1]; /* distance vertex is from start */ int v; /* current vertex to process */ int w; /* candidate next vertex */ int weight; /* edge weight */ int dist; /* best current distance from start */ for (i = 1; i <= g->nvertices; i++) { intree[i] = False; distance[i] = MAXINT; parent[i] = -1; } distance[start] = 0; v = start; while (intree[v] == False) { intree[v] = True p = g->edges[v]; while (p != NULL) { w = p->y; weight = p->weight; if (distance[w] > (distance[v] + weight)) { distance[w] = distance[v] + weight; parent[w] = v; } p = p->next; } v = 1; dist = MAXINT; for (i = 1; i <= g->nvertices; i++) if ((intree[i] == False) && (dist > distance[i])) { dist = distance[i]; v = i; } } } ``` Finds more than shortest path, from _s_ to _t_, finds the shortest path from _s_ to all other vertices. Dijkstra works correctly only on graphs without negative-cost edges. As implemented, the run-time complexity is (On<sup>2</sup>). The length of the shortest path from start to a given vertex _t_ is exactly the value of distance[t]. To find the actual path, we follow the backward parent pointers from _t_ until we hit start (or -1 if no such path exists) ### Stop and Think: Shortest Path with Node Costs _Problem_: We are given a graph whose weights are on the vertices instead of the edges. Thus, the cost of a path from _x_ to _y_ is the sum of the weights of all vertices on the path. Give an efficient algorithm for finding the shortest paths. _Solution_: You could modify Dijkstra by replacing all references to the weight of an edge with the weight of the destination vertex, which can be looked up as needed from an array of vertex weights. You could also opt to leave Dijkstra intact and construct an edge-weighted graph on which Dijkstra will give a desired answer. Set the weight of each directed edge (i, j) in the input graph to the cost of vertex j. ### All-Pairs Shortest Path Floyd's all-pairs shortest-path algorithm is a slick way to create a nxn distance matrix from the origiinal weight matrix of the graph ```c typedef struct { int weight[MAXV+1]; /* adjacency/weight info */ int nvertices; /* number of vertices in the graph */ } adjacency_matrix; ``` We should initialize each non-edge to MAXINT. This way, we can test whether it is present and automatically ignore it in shortest-path computations since only real edges will be used, provided MAXINT is greater than the diameter of your graph. _Diameter_ being the longest shortest-path distance over all pairs of vertices. There are several ways to characterize the shortest path between two nodes in a graph. The Floyd-Warshall algorithm starts by numbering the vertices of the graph from 1 to _n_. We use the numbers not to label vertices but to order them. When k=0, we are allowed no intermediate vertices, so the only allowed paths are the original edges on the graph. Thus the initial all-pairs shortest-path matrix consists of the initial adjacency matrix. We perform n iterations where the _kth_ iteration allows only the first _k_ vertices as possible intermediate steps on the path between each pair of vertices _x_ and _y_. ```c floyd(adjacency_matrix *g) { int i, j; /* dimension counters */ int k; /* intedrmediate vertex counter */ int through_k; /* distance through vertex */ for (k = 1; k <= g->nvertices; k++) for (i = 1; i <= g->nvertices; i++) for (j = 1; j <= g->nvertices; j++) { through_k = g->weight[i][k] + g->weight[k][j]; if (through_k < g->weight[i][j]) g->weight[i][j] = through_k; } } ``` Floyd-Warshall all-pairs shortest-path runs in O(n<sup>3</sup>) time which is asymptotically no better than _n_ calls to Dijkstra's algorithm, but the loops are so tight and program so short that it runs better in practice. It is one of the rare graph algorithms that works better on adjacency matrixes than adjacency lists. Output of Floyd's algorithm does not enable the reconstruction of the actual path between any given pair of vertices, but these paths can be recovered if we retain a parent matrix _P_ of the last intermediate vertex used for each vertex pair (x, y). If the value is _k_, the shortest path from _x_ to _y_ is the concatenation of the shortest path from _x_ to _k_ and the shortest path from _k_ to _y_, whcih can be reconstructed recursively given matrix _P_. ### Transitive Closure: _Blackmail graph_: There is a directed edge (i, j) if person _i_ has sensitive-enough private information on person _j_ so that _i_ can get _j_ to do anything he wants. You want to hire one of the _n_ people to be your personal representative. Who has the most power in terms of blackmail potential? Simple answer would be vertex of highest degree. But if Steve can only blackmail Miguel and Miguel can blackmail everybody else, you want to hire Steve. ### Network Flows and Bipartite Matching Edge-weighted graphs can be interpreted as a network of pipes where the weight of edge (i,j) determines the capacity of the pipe. Capacities can be thoguht of as a function of the cross-sectional area of the pipe. A wide pipe might be able to carry 10 units of flow at a time whereas a narrower pipe may only be able to carry 5 units. The network flow problem asks for the maximum amount of flow which can be sent from vertices _s_ to _t_ in a given weighted graph _G_ while respecting the maximum capacities of each pipe. ### Bipartite Matching A _matching_ in a graph _G = (V, E)_ is a subset of edges E' ⸦ E such that no two Edges of E' share a vertex. A matching pairs off certain vertices such that every vertex is in, at most, one such pair. Graph _G_ is bipartite or _two-colorable_ if the vertices can be divided into two sets, _L_ and _R_ such that all edges in _G_ have one vertex in _L_ and one vertex in _R_. The largest bipartite matching can be found using network flow. Create a source node _s_ that is connected to every vertex in _L_ by an edge of weight 1. Create a sink node _t_ and connect it to every vertex in _R_ by an edge of weight 1. Assign each edge in the bipartite graph _G_ a weight of 1. The maximum flow _s_ to _t_ defines the largest matching in _G_. ### Computing Network Flows It can be shown that the flow through a network is optimal if and only if it contains no _augmenting path_. Since each augmentation adds to the flow, we must eventually find the global maximum. The key structure is the residual flow graph, denoted as _R(G, f)_ where _G_ is the input graph and _f_ is the current flow through _G_. This directed edge-weighted _R(G, f)_ contains the same vertices as _G_. For each edge (i, j) is _G_ with capacity _c(i, j)_ and flow _f(i, j)_. _R(G, f)_ may contain two edges: <br/> (i) an edge _(i, j)_ with weight _c(i, j) - f(i, j)_, if _c(i, j) - f(i, j)_ > 0 and <br/> (ii) an edge _(j, i)_ with weight _f(i, j)_, if _f(i, j)_ > 0 The prescence of edge (i, j) in the residual graph indicates that positive flow can be pushed from _i_ to _j_. The weight of the edge gives the exact amount that can be pushed. A path in the residual graph from _s_ to _t_ implies that more flow can be pushed from _s_ to _t_ and the minimum edge weight on the path defines the amount of extra flow that can be pushed. ### Take Home: The maximum flow from _s_ to _t_ always equals the weight of the minimum s-t cut. Thus, flow algorithms can be used to solve general edge and vertex connectivity problems in graphs. ```c typedef struct { int v; /* neighboring vertex */ int capacity; /* capacity of edge */ int flow; /* flow through edge */ int residual; /* residual capacity of edge */ struct edgenode *next; /* next edge in list */ } edgenode; ``` We use breadth-first search to look for any path from source to sink that increases the total flow, and use it to augment the total. We terminate with the optimal flow when no such augmenting path exists. ```c netflow(flow_graph *g, int source, int sink) { int volume; /* weight of the augmenting path */ add_residual_edges(g); initialize_search(g); bfs(g, source); volume = path_volume(g, source, sink, parent); while (volume > 0) { augment_path(g, source, sink, parent, volume); initialize_search(g); bfs(g, source); volume = path_volume(g, source, sink, parent); } } ``` Any augmenting path from source to sink increases the flow, so we can use bfs to find such a path in the appropriate graph. We only consider network edges that have remaining capacity (positive residual flow). This helps bfs distinguish between saturated and unsaturated edges. ```c bool valid_edge(edgenode *e) { if (e->residual > 0) return true; else return false; } ``` Augmenting a path transfers the maximum possible volume from the residual capacity into positive flow. This amount is limited by the path-edge with the smallest amount of residual capacity just as the rate of which traffic can flow is limited by the most congested point. ```c int path_volume(flow_graph *g, int start, int end, int parents[]) { edgenode *e; /* edge in question */ edgenode *find_edge(); if (parents[end] == -1) return 0; e = find_edge(g, parents[end], end); if (start == parents[end]) return e->residual; else return (min (path_volume(g, start, parents[end], parents), e->residual)); } edgenode *find_edge(flow_graph *g, int x, int y) { edgenode *p; /* temporary pointer */ p = g->edges[x]; while (p != NULL) { if (p->v == y) return p; p = p->next; } return NULL; } ``` Sending an additional unit of flow along directed edge (i, j) reduces the residual capacity of edge (i, j) but increases the residual capacity of edge (j, i). Thus, the act of augmenting a path requires modifying both forward and reverse edges for each link on the path. ```c augment_path(flow_graph *g, int start, int end, int parents[], int volume) { edgenode *e; /* edge in question */ edgenode *find_edge(); if (start == end) return; e = find_edge(g, parents[end], end); e->flow += volume; e->residual -= volume; e = find_edge(g, end, parents[end]); e->residual += volume; augment_path(g, start, parents[end], parents, volume); } ``` Initializing the graph requires creating directed flow edges (i, j) and (j, i) for each network edge e = (i, j). Initial flows are set to 0. The initial residual flows of (i, j) is set to the capacity of e, while the initial flow of (j, i) is set to 0. ### Design Graphs, not Algorithms The secret is learning to design graphs, not algorithms - The maximum spanning tree can be found by negating the edge weights of input graph _G_ and using a minimum spanning tree algorithm in the result. The most negative weight spanning tree is the maximum weight tree in _G_. - To solve bipartite matching, we can construct a special network flow graph such that the maximum flow corresponds to a maximum cardinality matching. ### Stop and Think: The Pink Panther's Passport in Peril _Problem_: Algorithm to design natural routes for video game characters to follow through obstacle-filled rooms _Solution_: In trying to create natural paths, we would mimic actions of intelligent beings, which move lazily and/or efficiently. This lends to shortest path problem. Could lay out a grid of points in the room and create vertexes for each grid point valid for character movement (i.e., not containing an obstacle). ### Sotp and Think: Ordering the Sequence: _Problem_: DNA sequencing separates data consisting of small fragments where we know certain fragments lie to the left of a given fragment and others lie to the right of a given fragment - How can we find a consistent ordering of the fragments from left to right? _Solution_: Create directed graph. Each fragment assigned a unique vertex. Insert directed edge _(l, f)_ from any fragment _l_ that is forced to be to the left of _f_ and a directed edge _(f, r)_ to any fragment _r_ forced to be to the right of _f_. ### Stop and Think: Bucketing Rectangles _Problem_: Given an arbitrary set of rectangles on a plane, how can you distribute them into a minimum number of buckets such that no subset of rectangles in any given bucket intersects another? _Solution_: Graph. Each vertex is a rectangle- edge if rectangles intersect. Each bucket is an independent set of rectangles so no overlap between any two. ### Stop and Think: Names in Collision _Problem_: How can you meaningfully shorten filenames so they don't collide? _Solution_: Bipartite graph with vertices corresponding to original file names and a collection of appropriate shortenings for each name. Add edge between original and shortened name. Look for a set of _n_ edges that have no vertices in common ### Stop and Think: Separate the Text _Problem_: How do we do line segmentation? _Solution_: Treat each pixel in the image as a vertex in the graph with edge between neighboring pixels. Weight of edges should be proportioned to how dark the pixels are. Seek a relatively straight path that avoids as much blackness as possible. ### Take Home: Designing novel graph algorithms is very hard, so don't do it. Instead, try to design graphs that enable you to use classical algorithms to model your problem.
Java
UTF-8
158
1.65625
2
[]
no_license
package com.qingbo.sell.enums; /** * @Auther: gaoqingbo * @Date: 2018/11/7 17:42 * @Description: */ public interface CodeEnum { Integer getCode(); }
TypeScript
UTF-8
407
3.0625
3
[]
no_license
import * as fs from 'fs' //in // 5 // 4 2 5 1 3 //out // 3 const input: string[] = fs.readFileSync('/dev/stdin', 'utf8').split('\n'); const n: number = parseInt(input[0]); const p: number[] = input[1].split(' ').map(Number); let result: number = 0; let min :number = Infinity; for (let i: number = 0; i < n; i++) { if (min > p[i]) { result++; min = p[i]; } } console.log(result);
PHP
UTF-8
1,748
2.953125
3
[]
no_license
<?php /** */ class core { /** * Core constructor */ function __construct() { //_set_error_handler( array(&$this, 'throwError')); } /** * Create a new DB connection, or continues an existing * one if present */ function &db(){ $dbConnect = new dbconnector; return $dbConnect; } /* Severity is 1 or 2 (fatal or non-fatal) */ function errormsg($message, $severity = 1){ $this->throwError($severity, $message, basename($_SERVER['PHP_SELF']), null, null); if ($severity == 1){ die(); } } /** * For internal system errors */ function throwError ($error_type, $error_msg, $error_file, $error_line = null, $error_context = null) { // Display messages if (error_reporting() AND $error_type != E_NOTICE){ echo '<table cellpadding="2" cellspacing="0" class="alert_red"><tr><td>'; echo '<p>Sorry, an error occurred.</p>'; if ($error_file != null){ echo "<p>FILE: $error_file, LINE: $error_line</p>"; } echo '<p>ERROR: '.$error_msg.'</p>'; //print_r($error_context); echo '</td></tr></table>'; } } } /** * set_error_handler that works with all versions of php * Source: http://mojavi.org/forum/viewtopic.php?t=57&sid=896a45f2b500927c634d3f8d4fec67d4 */ function _set_error_handler($arg) { if (is_array($arg)) { if (phpversion() >= '4.3.0') { set_error_handler($arg); } else { $GLOBALS['_error_handler_hook_obj'] =& $arg[0]; $GLOBALS['_error_handler_hook_method'] = $arg[1]; set_error_handler('error_handler_callback'); } } else if (is_string($arg)) { set_error_handler($arg); } else { trigger_error("Wrong argument type for _set_error_handler", E_USER_ERROR); } } ?>
Java
UTF-8
934
1.929688
2
[]
no_license
/** * * Project Name: Geniisys Web * Version: * Author: Computer Professionals, Inc. * */ package com.geniisys.giac.dao; import java.sql.SQLException; import java.util.Map; /** * The Interface GIACModulesDAO. */ public interface GIACModulesDAO { /** * Validates user module function. * @param userid, moduleaccess, modulename * @return String * @throws SQLException the sQL exception */ String validateUserFunc(Map<String, Object> param) throws SQLException; String validateUserFunc2(Map<String, Object> params) throws SQLException; String validateUserFunc3(Map<String, Object> params) throws SQLException; void saveGiacs317(Map<String, Object> params) throws SQLException; String valDeleteRec(Integer moduleId) throws SQLException; void valAddRec(Map<String, Object> param) throws SQLException; Map<String, Object> validateGiacs317ScreenRepTag(Map<String, Object> params) throws SQLException; }
JavaScript
UTF-8
727
2.65625
3
[]
no_license
import React, { Component } from 'react'; import Car from './Car.js' function searchingFor(term){ return function(x){ return x.name.toLowerCase().includes(term.toLowerCase()) || !term; } } class Cars extends Component { handleDelete(id){ this.props.handleDelete(id); } onUpdate(car){ this.props.onUpdate(car) } render() { var term = this.props.term var cars = this.props.cars.filter(searchingFor(term)).map((car) => { return( <Car car={car} key={car.id} handleDelete={this.handleDelete.bind(this, car.id)} handleUpdate ={this.onUpdate.bind(this)}/> )}); return ( <tbody> {cars} </tbody> ); } } export default Cars;
Shell
WINDOWS-1252
23,246
3.234375
3
[]
no_license
#!/bin/bash # $Id: snapshot.sh 10857 2007-05-19 03:01:32Z bberndt $ # # Copyright 2008, Sun Microsystems, Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # # 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. # # # Neither the name of Sun Microsystems, Inc. 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 OWNER # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # if [ "$1" = "" ] || [ "$1" == "-h" ] || [ "$1" == "-help" ] || [ "$1" == "--help" ] then echo "HC Snapshot Tool" echo "----------------" echo "Usage: snapshot mode clustername [snapshotname] [snapshottype] [node] [disk] [map]" echo " mode : save, restore, list, delete, deletedata" echo " restore is not possible from a live snapshot, only from result of copy or move" echo " clustername : name of the cluster (ex. dev318) used to snapshot/restore its audit DB" echo " use keyword (nodb) if you do not want to do anything to the audit DB" echo " snapshotname : name to give the snapshot for save, restore or delete" echo " snapshottype : type of snapshot activity: copy,move or live, default is move" echo " live will checkpoint existing data without copy, and skip hadb and system metadata caches" echo " node : limit snapshot to this node, give 3-digit node id (ex. 107), default is all nodes" echo " disk : limit snapshot to this disk, give 1-digit disk id (ex. 2), default is all disks" echo " map : limit snapshot to this layout map, give 4-digit map id (ex. 0234), default is all maps" echo "" exit 0 fi MODE=$1 CLUSTER_NAME=$2 SNAPSHOT=$3 TYPE=$4 MYNODE=$5 MYDISK=$6 MYMAP=$7 # Some lookups are done on node 101, disk 0 by default, unless user specified disk/node id if [ "$MYNODE" != "" ]; then N=$MYNODE else N=101 fi if [ "$MYDISK" != "" ]; then D=$MYDISK else D=0 fi # Parse layout map ID into 2-level dir names if [ "$MYMAP" != "" ]; then # pad map ID with zeros: 23 -> 0023 while [ `echo -n $MYMAP |wc -c |tr -d ' '` -lt 4 ]; do MYMAP=0$MYMAP done HIDIR=`echo $MYMAP | cut -c 1-2` LODIR=`echo $MYMAP | cut -c 3-4` else DIR=`echo {0..9}{0..9}` HIDIR=$DIR LODIR=$DIR fi # Statics DISK_IDS=( "c0t0" "c0t1" "c1t0" "c1t1" ) AUDIT_HOST=10.7.228.25 # hc-dev3 SNAP_RE="^[a-zA-Z_0-9]*$" if [ "$MODE" != "save" ] && [ "$MODE" != "restore" ] && [ "$MODE" != "list" ] && [ "$MODE" != "delete" ] && [ "$MODE" != "deletedata" ] then echo "Bad MODE: $MODE only 'save','restore','list','delete','deletedata' accepted." exit -1 fi if [ "$TYPE" != "" ] && [ "$TYPE" != "copy" ] && [ "$TYPE" != "move" ] && [ "$TYPE" != "live" ] then echo "Bad TYPE: $TYPE only 'copy', 'move' and 'live' accepted." exit -1 fi if [ "$TYPE" == "" ]; then TYPE=move # default fi if [ "$TYPE" == "copy" ]; then echo "Using copy mode instead of moving, this may take a while..." fi if [ "$SNAPSHOT" == "" ] then if [ "$MODE" != "list" ] && [ "$MODE" != "deletedata" ] then echo "Please specify a snapshot name." exit -1 fi fi if [ "$MYDISK" != "" ]; then if [ "$MYDISK" != "0" ] && [ "$MYDISK" != "1" ] && [ "$MYDISK" != "2" ] && [ "$MYDISK" != 3 ] then echo "Invalid disk ID [$MYDISK], select from 0, 1, 2 3." exit -1 fi DISKS=$MYDISK else DISKS="0 1 2 3" fi # verify snapshot name is a valid name for filesystem and db usage echo $SNAPSHOT | grep "$SNAP_RE" > /dev/null 2>&1 if [ $? != 0 ] then echo "Snapshot name must contain only letters, numbers and underscores. Regular expression to match: $SNAP_RE" exit -1 fi initNodes() { ALLNODES="" NUM_NODES=0 MYNODE_OK=0 echo -n "Calculating nodes in ring..." # Figure out which nodes are alive via ping with 1-second timeout for NODE in {101..116} do echo -n "." ping -c 1 hcb$NODE 1 > /dev/null 2>&1 if [ $? == 0 ]; then NODE_OK=1 ALLNODES="$ALLNODES $NODE" NUM_NODES=`expr $NUM_NODES + 1` else NODE_OK=0 fi if [ "$NODE" == "$MYNODE" ]; then MYNODE_OK=$NODE_OK fi done echo "[$ALLNODES]. done." if [ "$MYNODE" != "" ]; then ALLNODES=$MYNODE fi } abortUnlessYes() { read ANSWER if [ "$ANSWER" != "y" ] then echo "Aborted by user." exit -1 fi } confirmState() { echo "You have $NUM_NODES nodes and $NUM_DISKS mounted disks, is this correct? (y/n) " abortUnlessYes if [ "$MYNODE" != "" ]; then echo -n "You selected node $MYNODE, its state is " if [ "$MYNODE_OK" == "1" ]; then echo -n "online, " else echo -n "offline, " fi echo "is this correct? (y/n) " abortUnlessYes fi if [ "$MYDISK" != "" ]; then echo -n "You selected disk $MYDISK, its state is " if [ "$MYDISK_OK" == "1" ]; then echo -n "mounted, " else echo -n "not mounted, " fi echo "is this correct? (y/n) " abortUnlessYes fi } verifyHCIsDown() { if [ "$TYPE" == "live" ] then echo "Live checkpoint mode in use, will assume HC is running..." return 0 fi for NODE in $ALLNODES do ssh hcb$NODE "ps -ef | grep java | grep -v grep" > /dev/null 2>&1 if [ $? == 0 ] then echo "There are java processes running on node hcb$NODE, please turn off honeycomb first." exit -1 fi done } mountAllDisks() { if [ "$TYPE" == "live" ] then echo "Live checkpoint mode in use, will assume all disks are mounted." return 0 fi echo -n "Mounting data slices [$DISKS] on nodes [$ALLNODES]." for NODE in $ALLNODES do ssh hcb$NODE "mkdir /data > /dev/null 2>&1" for DISK in $DISKS do #echo "/usr/sbin/mount -F ufs /dev/dsk/c${DISK}d0s4 /data/$DISK" (ssh hcb$NODE "mkdir /data/$DISK ; /usr/sbin/mount -F ufs /dev/dsk/${DISK_IDS[$DISK]}d0s4 /data/$DISK" > /dev/null 2>&1 ; echo -n ".") & done done wait echo ". done." } initDisks() { NUM_DISKS=0 echo -n "Verifying number of disks mounted..." for NODE in $ALLNODES do ssh hcb$NODE "mkdir /data > /dev/null 2>&1" for DISK in $DISKS do echo -n "." ssh hcb$NODE "mount | grep ^/data/$DISK" > /dev/null 2>&1 if [ $? == 0 ] then DISK_OK=1 NUM_DISKS=`expr $NUM_DISKS + 1` else DISK_OK=0 fi if [ "$NODE" == "$MYNODE" ]; then if [ "$DISK" == "$MYDISK" ]; then MYDISK_OK=$DISK_OK fi fi done done echo ". done" } verifySnapshot() { for NODE in $ALLNODES do for DISK in $DISKS do if [ "$2" == "true" ] then ssh hcb$NODE "ls /data/$DISK/.snapshots/$1" > /dev/null 2>&1 if [ $? != 0 ] then echo "WARNING: Snapshot does not exist on hcb$NODE disk $DISK with that name." fi # TODO: Check that snapshot is of restorable type (not result of live checkpoint) else ssh hcb$NODE "ls /data/$DISK/.snapshots/$1" > /dev/null 2>&1 if [ $? == 0 ] then echo "Snapshot exists on hcb$NODE disk $DISK with that name." exit -1 fi fi done done } createDirectories() { echo -n "Initializing snapshot directories." for NODE in $ALLNODES do for DISK in $DISKS do (ssh hcb$NODE "mkdir /data/$DISK/.snapshots" > /dev/null 2>&1 ; echo -n ".") & done done wait echo ". done." } init() { initDB initNodes verifyHCIsDown mountAllDisks initDisks confirmState createDirectories } calcTimeForCopy() { MYSNAPSHOT=$1 # empty if we calculate to save a snapshot, set on restore if [ "$TYPE" == "move" ] || [ "$TYPE" == "live" ]; then # skip calculation, move is instantaneous, live checkpoint is just an ls return fi # use DATASPACE from disk D of node N (default is 101:0) OCCUPIEDSPACE=`ssh hcb$N "df -k /data/$D" | grep data | awk '{print $3}'` SNAPSHOTSPACE=`ssh hcb$N "du -sk /data/$D/.snapshots/$MYSNAPSHOT" | awk '{print $1}'` DATASPACE=`expr $OCCUPIEDSPACE - $SNAPSHOTSPACE` # 20 (MB / s) = 1228800 / minute if [ "$MODE" == "save" ] then TIMETOCOPY=`expr $DATASPACE / 1228800` else # restore TIMETOCOPY=`expr $SNAPSHOTSPACE / 1228800` fi if [ "$TIMETOCOPY" == "0" ]; then TIMETOCOPY=1 fi echo "Copying will take around $TIMETOCOPY minutes." echo "Would you like to continue ? (y/n) " abortUnlessYes return } verifySpaceForCopy() { MYSNAPSHOT=$1 # empty if we verify before saving snapshot, set on restore if [ "$TYPE" == "move" ] || [ "$TYPE" == "live" ]; then # skip verification, move doesn't take any space and live checkpoint just needs space for ls return fi echo -n "Verifying disk space for copying snapshot..." for NODE in $ALLNODES do for DISK in $DISKS do # space occupied in kilobytes ( local FREESPACE=`ssh hcb$NODE "df -k /data/$DISK | grep dev " | awk '{print $4}'` local OCCUPIEDSPACE=`ssh hcb$NODE "df -k /data/$DISK" | grep data | awk '{print $3}'` local SNAPSHOTSPACE=`ssh hcb$NODE "du -sk /data/$DISK/.snapshots/$MYSNAPSHOT" | awk '{print $1}'` local DATASPACE=`expr $OCCUPIEDSPACE - $SNAPSHOTSPACE` if [ "$MODE" == "save" ] && [ "$DATASPACE" -gt "$FREESPACE" ] then echo "Insufficient space on hcb$NODE disk $DISK to save snapshot: data space $DATASPACE kb, free $FREESPACE kb." exit -1 fi if [ "$MODE" == "restore" ] && [ "$SNAPSHOTSPACE" -gt "$FREESPACE" ] then echo "Insufficient space on hcb$NODE disk $DISK to save snapshot: data space $DATASPACE kb, free $FREESPACE kb." exit -1 fi echo -n "." ) & done done wait echo ". done" } initDB() { if [ "$CLUSTER_NAME" == "nodb" ]; then SNAPSHOTDB="" return else SNAPSHOTDB="${CLUSTER_NAME}_$SNAPSHOT" fi ssh postgres@$AUDIT_HOST "psql -U system -c '' " > /dev/null 2>&1 if [ $? != 0 ] then echo "Audit database manager does not have database and user system. please correct this." echo "To setup the user and db login as postgres user and use the commands createuser and createdb." echo "Would you like me to continue otherwise, without audit db snapshotting? (y/n) " abortUnlessYes fi ping $AUDIT_HOST > /dev/null 2>&1 if [ $? != 0 ] then echo "Audit host unavailable, would you like to continue without audit db snapshotting? (y/n) " abortUnlessYes fi } saveConfig() { # TODO: Use /config instead of /data/0 if [ "$MYNODE" != "" ]; then return fi NODE=$1 ssh hcb$NODE "mkdir /data/0/.snapshots/$SNAPSHOT" > /dev/null 2>&1 ssh hcb$NODE "tar cvf /data/0/.snapshots/$SNAPSHOT/.config.tar /config > /dev/null" if [ $? != 0 ] then echo "Problem saving config on node $NODE... Quiting." exit -1 fi } restoreConfig() { # TODO: Use /config instead of /data/0 if [ "$MYNODE" != "" ]; then return fi NODE=$1 ssh hcb$NODE "rm -rf /config/*; tar xvf /data/0/.snapshots/$SNAPSHOT/.config.tar -c /config > /dev/null" if [ $? != 0 ] then echo "Problem restoring config on node $NODE... Quiting." exit -1 fi } dropCurrentAuditDB() { echo "Recreating auditdb on hc-dev3." ssh postgres@$AUDIT_HOST "./dbscript.sh -r -c $CLUSTER_NAME" > /dev/null 2>&1 } dropSnapshotAuditDB() { # if database exists ssh postgres@$AUDIT_HOST "psql -U system -l | grep $SNAPSHOTDB" > /dev/null 2>&1 if [ $? == 0 ] then echo "Dropping snapshot on hc-dev3." ssh postgres@$AUDIT_HOST "dropdb -U system $SNAPSHOTDB" > /dev/null 2>&1 ssh postgres@$AUDIT_HOST "dropuser -U system $SNAPSHOTDB" > /dev/null 2>&1 fi } saveCopyAuditDB() { echo "Copying auditdb for $CLUSTER_NAME to $SNAPSHOTDB." # if database exists ssh postgres@$AUDIT_HOST "psql -U system $CLUSTERNAME -c ''" > /dev/null 2>&1 if [ $? == 0 ]; then ssh postgres@$AUDIT_HOST "dropdb -U system $SNAPSHOTDB ; createdb -U $CLUSTER_NAME $SNAPSHOTDB" > /dev/null 2>&1 ssh postgres@$AUDIT_HOST "pg_dump -Ft -U $CLUSTER_NAME $CLUSTER_NAME > $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null ssh postgres@$AUDIT_HOST "pg_restore -U $CLUSTER_NAME -d $SNAPSHOTDB $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null ssh postgres@$AUDIT_HOST "rm -f $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null else echo "Audit DB not found for cluster $CLUSTER_NAME, cannot save snapshot." fi } saveMoveAuditDB() { echo "Moving auditdb for $CLUSTER_NAME to $SNAPSHOTDB." # if database exists ssh postgres@$AUDIT_HOST "psql -U system $CLUSTERNAME -c ''" > /dev/null 2>&1 if [ $? == 0 ]; then ssh postgres@$AUDIT_HOST "psql -U $CLUSTER_NAME -c \"ALTER DATABASE $CLUSTER_NAME RENAME TO $SNAPSHOTDB\"" > /dev/null echo "Recreating empty audit db for $CLUSTER_NAME on hc-dev3" ssh postgres@$AUDIT_HOST "~/dbscript.sh -c $CLUSTER_NAME -r" > /dev/null 2>&1 else echo "Audit DB not found for cluster $CLUSTER_NAME, cannot save snapshot." fi } restoreCopyAuditDB() { echo "Copying auditdb from $SNAPSHOTDB to $CLUSTER_NAME." # if database exists ssh postgres@$AUDIT_HOST "psql -U system $SNAPSHOTDB -c ''" > /dev/null 2>&1 if [ $? == 0 ]; then ssh postgres@$AUDIT_HOST "dropdb -U system $CLUSTER_NAME ; createdb -U $CLUSTER_NAME $CLUSTER_NAME" > /dev/null 2>&1 ssh postgres@$AUDIT_HOST "pg_dump -Ft -U system $SNAPSHOTDB > $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null ssh postgres@$AUDIT_HOST "pg_restore -U $CLUSTER_NAME -d $CLUSTER_NAME $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null ssh postgres@$AUDIT_HOST "rm -f $SNAPSHOTDB.$CLUSTER_NAME.tar" > /dev/null else echo "Audit db not found for snapshot $SNAPSHOTDB, cannot restore from snapshot." fi } restoreMoveAuditDB() { echo "Restoring database on hc-dev3 from $SNAPSHOTDB." # if database exists ssh postgres@$AUDIT_HOST "psql -U system $SNAPSHOTDB -c ''" > /dev/null 2>&1 if [ $? == 0 ]; then ssh postgres@$AUDIT_HOST "dropdb -U system $CLUSTER_NAME" > /dev/null 2>&1 ssh postgres@$AUDIT_HOST "psql -U system -c \"ALTER DATABASE $SNAPSHOTDB RENAME TO $CLUSTER_NAME\"" > /dev/null ssh postgres@$AUDIT_HOST "psql -U system -c \"ALTER DATABASE $CLUSTER_NAME OWNER TO $CLUSTER_NAME\"" > /dev/null else echo "Audit db not found for snapshot $SNAPSHOTDB, cannot restore from snapshot." fi } if [ "$MODE" == "deletedata" ] then init echo "Are you sure you want to delete data ? (y/n) " abortUnlessYes echo -n "Deleting data from disks [$DISKS] on nodes [$ALLNODES] ..." for NODE in $ALLNODES do for DISK in $DISKS do (ssh hcb$NODE "rm -fr /data/$DISK/*" > /dev/null 2>&1; echo -n ".") & done done wait echo ". done." if [ "$SNAPSHOTDB" != "" ]; then dropCurrentAuditDB fi fi if [ "$MODE" == "delete" ] then initDB initNodes mountAllDisks initDisks confirmState echo "Are you sure you want to delete snapshot: $SNAPSHOT ? (y/n) " abortUnlessYes echo -n "Deleting Snapshot: $SNAPSHOT from disks [$DISKS] on nodes [$ALLNODES] ..." for NODE in $ALLNODES do for DISK in $DISKS do echo -n "." ssh hcb$NODE "rm -fr /data/$DISK/.snapshots/$SNAPSHOT" > /dev/null 2>&1 & done done wait echo ". done." if [ "$SNAPSHOTDB" != "" ]; then dropSnapshotAuditDB fi fi if [ "$MODE" == "list" ] then ssh hcb$N "/usr/sbin/mount -F ufs /dev/dsk/c${D}d0s4 /data/$D" > /dev/null 2>&1 echo "Available Snapshots (listed from node $N disk $D):" SNAPSHOTS=`ssh hcb$N "ls /data/${D}/.snapshots/ 2> /dev/null" | awk '{print "* ",$1}'` if [ "$SNAPSHOTS" == "" ] then echo "None." exit 0 else echo "$SNAPSHOTS" fi fi if [ "$MODE" == "save" ] then init verifySnapshot "$SNAPSHOT" "false" verifySpaceForCopy calcTimeForCopy echo -n "Taking Snapshot of $TYPE type: $SNAPSHOT" if [ "$MYMAP" != "" ]; then echo -n " on layout map ID $MYMAP ..." else echo -n " on all layout maps 00/00 - 99/99 ..." fi for NODE in $ALLNODES do saveConfig $NODE for DISK in $DISKS do ssh hcb$NODE "mkdir /data/$DISK/.snapshots/$SNAPSHOT" > /dev/null 2>&1 #echo "Snapshot $SNAPSHOT on node $NODE disk $DISK" echo -n "." # save ls listing for this mapid SRC="/data/$DISK/" DST="/data/$DISK/.snapshots/$SNAPSHOT/" ssh hcb$NODE "for DIR1 in $HIDIR ; do for DIR2 in $LODIR; do ls $SRC/\$DIR1/\$DIR2 > $DST/.ls.\$DIR1.\$DIR2; done; done" > /dev/null 2>&1 & # for copy or move, put data into the snapshot if [ "$TYPE" == "copy" ] then if [ "$MYMAP" != "" ]; then ssh hcb$NODE "mkdir -p /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR" FILES=`ssh hcb$NODE ls /data/$DISK/$HIDIR/$LODIR` if [ "$FILES" != "" ]; then ssh hcb$NODE "cp -fr /data/$DISK/$HIDIR/$LODIR/* /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR/" & fi else ssh hcb$NODE "cp -fr /data/$DISK/* /data/$DISK/.snapshots/$SNAPSHOT" & fi elif [ "$TYPE" == "move" ] then if [ "$MYMAP" != "" ]; then ssh hcb$NODE "mkdir -p /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR" FILES=`ssh hcb$NODE ls /data/$DISK/$HIDIR/$LODIR` if [ "$FILES" != "" ]; then ssh hcb$NODE "mv /data/$DISK/$HIDIR/$LODIR/* /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR/" & fi else ssh hcb$NODE "mv /data/$DISK/* /data/$DISK/.snapshots/$SNAPSHOT" & fi else echo "..." # For live checkpoint, not saving actual data in the snapshot, only .ls # TODO: Identify the snapshot as "not restorable" fi done done wait echo ". done." for NODE in $ALLNODES do for DISK in $DISKS do ssh hcb$NODE "ls -l /data/$DISK/.snapshots/$SNAPSHOT/.ls.??.?? | awk '{if (\$5 == 0) {print \$9}}' | xargs rm -f" & done wait done if [ "$SNAPSHOTDB" != "" ]; then if [ "$TYPE" == "copy" ] || [ "$TYPE" == "live" ]; then saveCopyAuditDB else saveMoveAuditDB fi fi fi if [ "$MODE" == "restore" ] then init verifySnapshot "$SNAPSHOT" "true" calcTimeForCopy verifySpaceForCopy $SNAPSHOT if [ "$TYPE" == "copy" ] || [ "$TYPE" == "move" ] then echo "Deleting current files in preparation for restore" for NODE in $ALLNODES do for DISK in $DISKS do # this doesn't delete the .snapshot subdirs themselves! ssh hcb$NODE "rm -rf /data/$DISK/*" & done done wait fi echo -n "Restoring Snapshot: $SNAPSHOT..." for NODE in $ALLNODES do restoreConfig $NODE for DISK in $DISKS do #echo "Restoring $SNAPSHOT on node hcb$NODE disk $DISK" echo -n "." if [ "$TYPE" == "copy" ] then if [ "$MYMAP" != "" ]; then ssh hcb$NODE "mkdir -p /data/$DISK/$HIDIR/$LODIR" FILES=`ssh hcb$NODE ls /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR` if [ "$FILES" != "" ]; then ssh hcb$NODE "cp -fr /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR/* /data/$DISK/$HIDIR/$LODIR/" & fi else ssh hcb$NODE "cp -fr /data/$DISK/.snapshots/$SNAPSHOT/* /data/$DISK/" & fi else if [ "$MYMAP" != "" ]; then ssh hcb$NODE "mkdir -p /data/$DISK/$HIDIR/$LODIR" FILES=`ssh hcb$NODE ls /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR` if [ "$FILES" != "" ]; then ssh hcb$NODE "mv /data/$DISK/.snapshots/$SNAPSHOT/$HIDIR/$LODIR/* /data/$DISK/$HIDIR/$LODIR/ ; rm -fr /data/$DISK/.snapshots/$SNAPSHOT" & fi else ssh hcb$NODE "mv /data/$DISK/.snapshots/$SNAPSHOT/* /data/$DISK/ ; rm -fr /data/$DISK/.snapshots/$SNAPSHOT" & fi fi done done wait echo ". done." if [ "$SNAPSHOTDB" != "" ]; then if [ "$TYPE" == "copy" ]; then restoreCopyAuditDB else restoreMoveAuditDB fi fi fi
Java
UTF-8
3,043
2.953125
3
[]
no_license
package client; import data.Offer; import data.Request; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.*; public class UdpClientSocket { private DatagramSocket clientSocket; byte[] receiveData; byte[] sendData; public Socket clientTCPSocket; public UdpClientSocket() throws Exception { sendData = new Request().getBytes(); receiveData = new byte[26]; } public void sendReceiveAndHandleMessage() throws IOException { clientSocket = new DatagramSocket(); clientSocket.setSoTimeout(1000); InetAddress IPAddress = InetAddress.getByName("255.255.255.255"); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6000); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); Offer offerRequest = new Offer(receivePacket.getData()); System.out.println("FROM SERVER:" + offerRequest); clientSocket.close(); openTcpConnection(offerRequest); } private void openTcpConnection(Offer offerRequest) throws IOException { System.out.println("Try to open clientTCPSocket"); System.out.println("IP :" + offerRequest.getIpString() + ":" + offerRequest.getPort()); while(isTcpClose()) { try { clientTCPSocket = new Socket(); clientTCPSocket.connect(new InetSocketAddress(offerRequest.getIpString(), offerRequest.getPort()), 200); }catch (SocketTimeoutException e) { } } System.out.println("clientTCPSocket open "); } public void sendUserMessage() throws IOException { BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in)); DataOutputStream outToServer = new DataOutputStream(clientTCPSocket.getOutputStream()); System.out.println("Hey There Send A message!!!!"); String sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); } public void sendServerMessage(String clientSentence) throws IOException { DataOutputStream outToServer = new DataOutputStream(clientTCPSocket.getOutputStream()); clientSentence=changeString(clientSentence); outToServer.writeBytes(clientSentence + '\n'); } String changeString(String s) { char[] characters = s.toCharArray(); int rand = (int)(Math.random() * s.length()); characters[rand] = '_'; return new String(characters); } public boolean isTcpClose() { return clientTCPSocket == null || !clientTCPSocket.isBound(); } public boolean isUdpClose(){ return clientSocket == null || clientSocket.isClosed(); } public void closeUdp(){ if(clientSocket != null) clientSocket.close(); clientSocket = null; } }
C++
UTF-8
1,443
3.765625
4
[]
no_license
/* Next larger Send Feedback Given a generic tree and an integer n. Find and return the node with next larger element in the Tree i.e. find a node with value just greater than n. Return NULL if no node is present with the value greater than n. Input Format : Line 1 : Integer n Line 2 : Elements in level order form separated by space (as per done in class). Order is - Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element Output Format : Node with value just greater than n. Sample Input 1 : 18 10 3 20 30 40 2 40 50 0 0 0 0 Sample Output 1 : 20 Sample Input 2 : 21 10 3 20 30 40 2 40 50 0 0 0 0 Sample Output 2: 30 */ void util(TreeNode<int>* root, TreeNode<int>**resNode, int n) { if(root==NULL) return; if(root->data > n){ if(!*resNode || (*resNode)->data > root->data) *resNode = root; } int numChild = root->children.size(); for(int i=0;i<numChild;i++){ util(root->children[i], resNode, n); } } TreeNode<int>* nextLargerElement(TreeNode<int> *root, int n) { /* Don't write main(). * Don't read input, it is passed as function argument. * Return output and don't print it. * Taking input and printing output is handled automatically. */ if(root==NULL) return NULL; TreeNode<int>* resNode = NULL; util(root, &resNode, n); return resNode; }
JavaScript
UTF-8
3,211
2.59375
3
[]
no_license
const BASE_URL = 'https://kapi-lineas-ruddy.now.sh/api'; //const BASE_URL = 'http://localhost:3001'; const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); const randomNumber = (min = 0, max = 1) => Math.floor(Math.random() * (max - min + 1)) + min; const simulateNetworkLatency = (min = 30, max = 1500) => delay(randomNumber(min, max)); async function callApi(endpoint, options = {}) { await simulateNetworkLatency(); options.headers = { //Puede ser consumida desde cualquier lugar //'Access-Control-Allow-Origin': '*', //Cabeceras permitidas //'Access-Control-Allow-Headers': 'X-API-KEY,Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method', //Metodos Permitidos //'Access-Control-Allow-Methods':'GET,POST,PUT,DELETE', //'Allow':'GET,POST,PUT,DELETE', "Content-Type": "application/json", Accept: 'application/json', }; const url = BASE_URL + endpoint; const response = await fetch(url, options); /*.then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));*/ const data = await response.json(); return data; } const api = { lineas: { list() { let data = callApi('/lineas', { method: 'GET', redirect: 'follow', }); return data; }, create(linea) { // throw new Error('500: Server error'); return callApi(`/lineas/new`, { method: 'POST', body: JSON.stringify(linea), }); }, read(lineaId) { let data = callApi(`/lineas/${lineaId}`, { method: 'GET', redirect: 'follow' }); return data; }, update(lineaId, updates) { let myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); let raw = JSON.stringify({_id:updates._id,linea:updates.linea,usuario:updates.usuario,usufecha:updates.usufecha,usuhora:updates.usuhora,numero:updates.numero}); let requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; return fetch("https://kapi-lineas-ruddy.now.sh/api/lineas/"+lineaId+"/update", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); /* return callApi(`/lineas/${lineaId}/update`, { method: 'POST', body: JSON.stringify(linea), //mode: 'CORS', redirect: 'follow', });*/ }, // Lo hubiera llamado `delete`, pero `delete` es un keyword en JavaScript asi que no es buena idea :P remove(lineaId) { var raw = ""; var requestOptions = { method: 'POST', body: raw, redirect: 'follow' }; return fetch("https://kapi-lineas-ruddy.now.sh/api/lineas/"+lineaId+"/remove", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); /*return callApi(`/lineas/${lineaId}/remove`, { method: 'POST', redirect: 'follow' });*/ }, }, }; export default api;
Java
UTF-8
453
2.078125
2
[]
no_license
package com.cyb.jetty.demo.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { @Value("${value}") private String value; @GetMapping("/") public String home() { return "Hello, World!"; } @GetMapping("value") public String value() { return value; } }
Python
UTF-8
1,355
2.96875
3
[]
no_license
import os import shelve def search(d, query): Found_List=[] dict1_words=shelve.open(d) if ("or" in query) and ("and" not in query): #"OR" search query.remove("or") print("Performing OR search for: ", query) for phrase in query: if (phrase in dict1_words): querylist=[] querylist=querylist+dict1_words[phrase] querylist=list(set(querylist)) for phrase in querylist: print("Found in ... ",phrase,'\n') elif("and" in query) or (len(query)>1 and ("and" not in query)and("or" not in query)): if "and" in query: query.remove("and") if "or" in query: query.remove("or") print ("Performing AND search for: ",query) list_dict=dict1_words[query[0]] for word1 in query[1:]: list_dict1=dict1_words[a] list_dict=list(set(list_dict).intersection(list_dict1)) for word2 in list_dict1: print("Found in ...", word2, '\n') elif((len(query)==1) and ("and" not in query)and("or" not in query)): print ("Searching for: ",query) dict1_words[query[0]]=list(set(dict1_words[query[0]])) for word3 in dict1_words[query[0]]: print("Found in...", word3,'\n')
PHP
UTF-8
387
2.59375
3
[]
no_license
<?php namespace Vellum\Actions; class BaseAction { public function getAttributes($data) { if(count($this->attributes($data)) === 0) { return null; } return arrayToHtmlAttributes($this->attributes($data)); } public function getStyles($style = 'normal') { return implode(' ', $this->styles()[$style]); } }
JavaScript
UTF-8
1,671
2.53125
3
[]
no_license
const express = require("express"); const path = require('path'); const port = 9000; const db = require('./config/mongoose') const Contacts = require('./models/contacts'); const app = express(); app.use(express.urlencoded()); app.use(express.static('assets')); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, "views")); app.get('/', function(req, res){ Contacts.find({}, function(err, Contacts){ if(err){ console.log('error in fatching contacts from db'); return; } return res.render('contact', { title : "Contact List", Contact : Contacts }) }) }) app.post('/create-contact', function(req, res){ // console.log(req.body); Contacts.create({ name: req.body.name, phone: req.body.phone }, function(err, newContact){ if (err){ console.log("error in creating contact", err); return; } // console.log(newContact); return res.redirect('back'); }) }) app.get('/delete-contact/', function(req, res){ // console.log(req.query); // get the id from query inthe url let id = req.query.id; // find the contact in the database using id and delete Contacts.findByIdAndDelete(id, function(err){ if (err){ console.log('err in deleting object form database'); return; } return res.redirect('back'); }) }) app.listen(port, function(err){ if (err){ console.log("Error in running the server :", port); return; } console.log('Express server is running on the port : ', port); });
C#
UTF-8
12,611
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; namespace MyHome { // キャラクタークラス public class Player { // 読み込んだ画像位置 internal double mX, mY; internal double num = 0; int count = 0; //アニメーション用カウント internal double subX, subY; BitmapImage[] r_mPicture = new BitmapImage[6]; // キャラクタ右用 BitmapImage[] l_mPicture = new BitmapImage[6]; // キャラクタ左用 //プレイヤーの横幅と縦幅用の変数 internal double Width, Height; //重力 double Gravity = 0.5; //加速度 double mVelocity = 0; //地面判定 bool mOnTheGround; bool mSpaceKeyFlag = true; //梯子にいるかの状態判断 bool mOnTheLadder = false; //歩数計 int walkcounter = 1; //足音の引数 static int k = 0; public Player() { //初期化 mX = mY = 0; // カレントディレクトリは、bin/debugフォルダなので1つ上にたどってから string cwd = System.IO.Directory.GetCurrentDirectory(); //キャラクター:右向き string[] r_path = new[]{ System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r00.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r01.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r02.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r03.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r04.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\right\\r05.gif"}; //キャラクター:左向き string[] l_path = new[]{ System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l00.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l01.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l02.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l03.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l04.gif", System.IO.Directory.GetParent(cwd) + "\\img\\chara\\left\\l05.gif"}; for (int i = 0; i < 6; ++i) { r_mPicture[i] = new BitmapImage(new Uri(r_path[i])); l_mPicture[i] = new BitmapImage(new Uri(l_path[i])); } } // アニメーション public void move() { //プレイヤーの横幅と縦幅を定める Width = mX + 25; Height = mY + 44; ////GameStageクラス梯子判定メソッドにPlayerの座標を渡す mOnTheLadder = GameStage.ladder(this.mX, this.mY, Width, Height); //梯子マスの範囲にいる時 if (mOnTheLadder) { moveOnTheLadder(); } //梯子マスの範囲にいない時 else { moveNormally(); } switch (Selector.num) { case 1: if (num == 0) { mX = mY = 0; StageState.mLever = false; StageState.mCrackCheck = false; num++; } break; case 2: if (num == 1) { mX = mY = 0; StageState.mLever = false; StageState.mCrackCheck = false; num++; } break; case 3: if (num == 2) { mX = 46; mY = 0; StageState.mLever = false; StageState.mCrackCheck = false; num++; } break; case 4: if (num == 3) { mX = mY = 0; StageState.mLever = false; StageState.mCrackCheck = false; num = 0; } break; } double newX, newY, centerX, centerY; newX = mX; double aniX = mX, aniY = mY; //左右の動き if (KeyState.Left) { newX = mX - 3; ++walkcounter; if (mOnTheGround == true) { if (walkcounter % 25 == 0) { k = 1; Sound.Play(k); } } } else { newX = mX; } if (KeyState.Right) { newX = mX + 3; ++walkcounter; if (mOnTheGround == true) { if (walkcounter % 25 == 0) { k = 1; Sound.Play(k); } } } //ジャンプキー if (KeyState.Space) { if (!mSpaceKeyFlag) { if (mOnTheGround) { mVelocity -= 7.7; mOnTheGround = false; } } mSpaceKeyFlag = true; } else { mSpaceKeyFlag = false; } //中心X座標を算出 centerX = newX + 12; //壁チェック //壁に挟まれるシチュエーションはとりあえず考慮しない //よって左右一択とする(右優先) double wallX; wallX = GameStage.R_HitCheck(centerX + 1.0, mY, newX + 24, mY + 44); if (newX + 25 > wallX) { newX = wallX - 25; } else { wallX = GameStage.L_HitCheck(newX, mY, centerX, mY + 44); if (newX < wallX) { newX = wallX; } } //死亡 if (wallX == 1000) { StageState.mStage_num = 1; } //ジャンプ制御 double old = mVelocity; mVelocity += Gravity; newY = mY + (mVelocity + old) / 2; //中心Y座標チェック centerY = newY + 22; //天井チェック double ceil = GameStage.T_HitCheck(newX, newY, newX + 24, centerY); if (ceil == 1000) { StageState.mStage_num = 1; } if (ceil > newY) { newY = ceil; } //梯子チェック bool bLadder = false; bLadder = GameStage.ladder(newX, newY, newX + 44, newY + 44); //床チェック double floor = GameStage.B_HitCheck(newX, centerY + 1.0, newX + 24, newY + 44); if (newY >= floor) { if (!bLadder) { //梯子に乗っていなければブロックに乗る newY = floor; } else if (mY < floor) { //落ちてきて梯子に乗ったとき newY = floor; } else if (newY > mY) { //落下させない newY = mY; } mVelocity = 0; mOnTheGround = true; } mX = newX; mY = aniY = newY; //キャラクタ動き if (aniX != mX) { ++count; aniX = mX; this.mX = aniX; this.mY = aniY; if (count >= 59) { count = 0; } } if (this.mY >= 700 && !(Selector.num == 4)) { KeyState.Enter = true; } if (Selector.num == 4) { if (this.mY >= 555) { this.mY = 555; } if (wallX == 1001) { StageState.mStage_num = 2; } } if (this.mY <= 0) { this.mY = 0; } } //梯子マス範囲内では、上下動あり、重力働かず public void moveOnTheLadder() { Gravity = 0; mVelocity = 0; if (KeyState.Up) { double newY = mY - 4; double floor = GameStage.B_HitCheck(this.mX, this.mY, this.mX + 24, mY + 44, true); double top = GameStage.T_HitCheck(this.mX, this.mY - 2, this.mX + 24, mY + 43); if (floor > newY) { newY = floor; } if (top > newY) { newY = top; } mY = newY; } if (KeyState.Down) { double newY = mY + 4; //床チェック double floor = GameStage.B_HitCheck(this.mX + 3, newY + 16, this.mX + 27, newY + 47, false); if (floor < newY) { newY = floor; } mY = newY; } } //梯子の上でない時のmoveメソッド・梯子に乗ってない時(梯子マス範囲外時)は梯子を床として判定 public void moveNormally() { //梯子以外でも下がるバグが出ないための処置 bool ladderCheck = GameStage.ladder(this.mX, this.mY, Width, Height + 5); //重力が無くなったままにならない為の処理 Gravity = 0.5; if (KeyState.Down) { //空中で下キーを押しても落下速度をいじらせないための処理 if (mOnTheGround == false) { KeyState.Down = false; } if (ladderCheck) { //キーを押している間だけ重力がなくなる Gravity = 0; mVelocity = 0; subY = 5; mY += subY; } } } // 描画 public void draw(DrawingContext dc) { if (KeyState.Right) { dc.DrawImage(r_mPicture[count / 10], new Rect( Math.Floor(this.mX), Math.Floor(this.mY), r_mPicture[count / 10].Width, r_mPicture[count / 10].Height)); } if (KeyState.Left) { dc.DrawImage(l_mPicture[count / 10], new Rect( Math.Floor(this.mX), Math.Floor(this.mY), l_mPicture[count / 10].Width, l_mPicture[count / 10].Height)); } else { dc.DrawImage(r_mPicture[count / 10], new Rect( Math.Floor(this.mX), Math.Floor(this.mY), r_mPicture[count / 10].Width, r_mPicture[count / 10].Height)); } } } }
Java
UTF-8
1,648
1.890625
2
[]
no_license
package com.msk.ssc.logic; import com.hoperun.jdbc.mybatis.BaseDao; import com.msk.common.base.BaseLogic; import com.msk.common.logic.CommonLogic; import com.msk.ssc.bean.SSC1130801RsBean; import com.msk.ssc.bean.SSC1130801RsParam; import com.msk.ssc.bean.SSC11308RsBean; import com.msk.ssc.bean.SSC11308RsParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * 付款记录 */ @Service public class SSC1130801Logic extends BaseLogic { /** Logger */ private Logger logger = LoggerFactory.getLogger(SSC1130801Logic.class); @Autowired private CommonLogic commonLogic; @Autowired @Override public void setBaseDao(BaseDao baseDao) { super.setBaseDao(baseDao); } interface SqlId { String FIND_PAYMENT_INFO_BY_PAYMENT_ID = "findPaymentInfoById"; } @Transactional(readOnly = true) public SSC1130801RsBean findPaymentInfoBase(SSC1130801RsParam param){ return super.findOne(SqlId.FIND_PAYMENT_INFO_BY_PAYMENT_ID,param); } @Transactional public int savePaymentInfo(SSC1130801RsBean bean){ return super.save(bean); } @Transactional public int modifyPaymentInfo(SSC1130801RsBean bean){ // 排他检测 if(bean.getVer()!=null){ super.versionValidator("SSC_PAYMENT_INFO", new String[]{"PAYMENT_ID"}, new Object[]{bean.getPaymentId()}, bean.getVer()); } return super.modify(bean); } }
C
UTF-8
1,930
2.75
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <nng/nng.h> #include <nng/protocol/pair0/pair.h> #define NODE0 "node0" #define NODE1 "node1" void fatal(const char *func, int rv) { fprintf(stderr, "%s: %s\n", func, nng_strerror(rv)); exit(1); } int send_name(nng_socket sock, char *name) { int rv; printf("%s: SENDING \"%s\"\n", name, name); if ((rv = nng_send(sock, name, strlen(name) + 1, 0)) != 0) { fatal("nng_send", rv); } return (rv); } int recv_name(nng_socket sock, char *name) { char *buf = NULL; int rv; size_t sz; if ((rv = nng_recv(sock, &buf, &sz, NNG_FLAG_ALLOC)) == 0) { printf("%s: RECEIVED \"%s\"\n", name, buf); nng_free(buf, sz); } return (rv); } int send_recv(nng_socket sock, char *name) { int rv; if ((rv = nng_setopt_ms(sock, NNG_OPT_RECVTIMEO, 100)) != 0) { fatal("nng_setopt_ms", rv); } for (;;) { recv_name(sock, name); sleep(1); send_name(sock, name); } } int node0(const char *url) { nng_socket sock; int rv; if ((rv = nng_pair0_open(&sock)) != 0) { fatal("nng_pair0_open", rv); } if ((rv = nng_listen(sock, url, NULL, 0)) != 0) { fatal("nng_listen", rv); } return (send_recv(sock, NODE0)); } int node1(const char *url) { nng_socket sock; int rv; sleep(1); if ((rv = nng_pair0_open(&sock)) != 0) { fatal("nng_pair0_open", rv); } if ((rv = nng_dial(sock, url, NULL, 0)) != 0) { fatal("nng_dial", rv); } return (send_recv(sock, NODE1)); } int main(int argc, char **argv) { if ((argc > 1) && (strcmp(NODE0, argv[1]) == 0)) return (node0(argv[2])); if ((argc > 1) && (strcmp(NODE1, argv[1]) == 0)) return (node1(argv[2])); fprintf(stderr, "Usage: pair %s|%s <URL> <ARG> ...\n", NODE0, NODE1); return 1; }
JavaScript
UTF-8
6,743
2.515625
3
[]
no_license
/** * * @author Алексей */ function ControlsView() { var self = this , model = P.loadModel(this.constructor.name) , form = P.loadForm(this.constructor.name, model); self.show = function (panel) { panel ? panel.add(form.view, new P.Anchors(2, null, 2, 2, null, 2)) : form.show(); initControlCombos(); }; function initControlCombos() { initTaskStatusCombo(); initWarrantStatusCombo(); } var taskExecStatuses = []; function initTaskStatusCombo() { oc.getPoliceTaskExec( function (statuses) { taskExecStatuses = []; statuses.forEach(function (status) { taskExecStatuses.push(status); }); form.cmbTaskStatus.displayList = taskExecStatuses; form.cmbTaskStatus.displayField = "description"; }, function (e) { P.Logger.severe(e); }); } var warrantStatuses = []; function initWarrantStatusCombo() { oc.getTransportStatuses( function (statuses) { warrantStatuses = []; statuses.forEach(function (status) { warrantStatuses.push(status); }); form.cmbWarrantStatus.displayList = warrantStatuses; form.cmbWarrantStatus.displayField = "description"; }, function (e) { P.Logger.severe(e); }); } /** * Снимает все наряды с проишествия * @param {type} event * @returns {undefined} */ form.btnRemoveAllWarrants.onActionPerformed = function (event) { var selectedTasks = API.selectedTasks;// form.grdTasks.selected; if (selectedTasks.length !== 1) { alert("Необходимо выбрать одно происшествие"); return; } oc.removeWarrant( null, selectedTasks[0].id, new Date(), function () { API.updateTasks(); API.updateWarrants(); alert("Операция выполнена"); }, function (e) { P.Logger.severe(e); }); }; /** * Снимает с проишествия выбранный наряд * @param {type} event * @returns {undefined} */ form.btnRemoveWarrant.onActionPerformed = function (event) { var selectedWarrants = API.selectedWarrants;//form.grdWarrants.selected; var selectedTasks = API.selectedTasks;//form.grdTasks.selected; if (selectedWarrants.length !== 1 || selectedTasks.length !== 1) { alert("Необходимо выбрать происшествие и наряд"); return; } if (selectedWarrants[0].curentTaskId != null && selectedWarrants[0].curentTaskId == selectedTasks[0].id) { oc.removeWarrant( selectedWarrants[0].id, selectedTasks[0].id, new Date(), function () { API.updateTasks(); API.updateWarrants(); alert("Операция выполнена"); }, function (e) { P.Logger.severe(e); }); } else alert("Необходимо выбрать связанные происшествие и наряд"); }; /** * Задать наряд на проишествие * @param {type} event * @returns {undefined} * TODO проверять выбрано ли одно проишествие, и если выбрано несколько нарядов пробегаться по всем */ form.btnSetWarrant.onActionPerformed = function (event) { var selectedWarrants = API.selectedWarrants;//form.grdWarrants.selected; var selectedTasks = API.selectedTasks;//form.grdTasks.selected; if (selectedWarrants.length !== 1 || selectedTasks.length !== 1) { alert("Необходимо выбрать происшествие и наряд"); return; } oc.setWarrant( selectedWarrants[0].id, selectedTasks[0].id, new Date(), function () { API.updateTasks(); API.updateWarrants(); alert("Операция привязки выполнена"); }, function (e) { P.Logger.severe(e); }); }; /** * Сменить статус наряда * @param {type} event * @returns {undefined} */ form.btnChangeSelectedWarrantsStatus.onActionPerformed = function (event) { var selectedWarrants = API.selectedWarrants;//form.grdWarrants.selected; if (!selectedWarrants.length) { alert("Необходимо выбрать наряды"); return; } var selectedWarrantStatus = form.cmbWarrantStatus.value; if (!selectedWarrantStatus) { alert("Необходимо выбрать статус наряда"); return; } oc.changePoliceWarrantsStatus( selectedWarrants, selectedWarrantStatus, function () { }, function (e) { P.Logger.severe(e); }); }; /** * Сменить статус проишествия * @param {type} event * @returns {undefined} */ form.btnChangeSelectedTasksStatus.onActionPerformed = function (event) { var selectedTasks = API.selectedTasks;//form.grdTasks.selected; if (!selectedTasks.length) { alert("Необходимо выбрать происшествия"); return; } var selectedTaskStatus = form.cmbTaskStatus.value; if (!selectedTaskStatus) { alert("Необходимо выбрать статус происшествия"); return; } oc.changePoliceTasksStatus( selectedTasks, selectedTaskStatus, function () { }, function (e) { P.Logger.severe(e); }); }; }