branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># CSV_tool CSV_tool My first python project. Sorry for the bad coding ;) Frank <file_sep># -*- coding: utf-8 -*- ''' Created on 24.02.2015 version: 0.0.1 @author: frank ''' import tkMessageBox from tkFileDialog import * from Tkinter import * ## Tkinter importieren def buttonBeendenClick(): if tkMessageBox.askyesno('Beenden', 'Soll das Programm wirklich beendet werden?'): root.quit() root.destroy() root=Tk() ## Wurzelfenster! root.title('CSV-Datei: Kommas gegen Semikolons tauschen!') ## Titel festlegen textfenster = Text(root,background='grey') ## Ein Textfenster erzeugen textfenster.pack() ## und anzeigen labelHinweis = Label(master=root, text='Programm um eine .csv Datei von Google in eine\r.csv-Datei für den Import in myrcm vorzubereiten!', fg='white', bg='gray', font=('Arial', 12)) labelHinweis.place(x=80, y=0, width=420, height=120) #import tkMessageBox tkMessageBox.showinfo('Quelldatei','Bitte die Quelldatei auswählen!') # Datei zum Lesen oeffnen, mit Kontrolle ob Datei lesbar. Ansonsten exit() myPath = askopenfilename(filetypes=[("Quelldatei", ".csv")]) try: fobj_in = open(str(myPath),"r") except IOError: print "Error: can\'t find file or read data" tkMessageBox.showerror("Error", "Can't read file!") exit() else: print "Written content in the file successfully" #import tkMessageBox tkMessageBox.showinfo('Zieldatei','Bitte die Zieldatei auswählen!') # Datei zum Schreiben oeffnen. myPath2 = asksaveasfilename(filetypes=[("Zieldatei", ".csv")]) fobj_out = open(str(myPath2),"w") # Variable i definieren i = 1 # For-Schleife for line in fobj_in: #print line.rstrip() #schreibt jede gefundene Zeile in die Konsole zeile = line.replace(",", ";") fobj_out.write(str(i) + ": " + zeile) # schreibt jede geaenderte Zeile in die neue Datei print zeile.rstrip() #schreibt jede geaenderte Zeile in die Konsole i = i + 1 # Dateien wieder schliessen fobj_in.close() fobj_out.close() # Button Beenden buttonBeenden = Button(master=root, bg='#FBD975', text='Programm beenden?', command=buttonBeendenClick) buttonBeenden.place(x=164, y=94, width=240, height=27) root.mainloop()
826396f7baaea8e19edc5c781a1d9bffa90b235d
[ "Markdown", "Python" ]
2
Markdown
bullet64/CSV_tool
9b14ae4f5aaa75f883ebea7383416a6f6685ba73
467ae2eceee1de5ba041a79fdaddfd53727a39c7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SelinaNo { public static class GameConstants { public const double MAX_SPEED = 0.35; public const int SCREEN_WIDTH = 1280; public const int SCREEN_HEIGHT = 720; public const int RESIZE_FACTOR = 2; //Scoreboard Information public const int SCOREBOARD_X = 50; public const int SCOREBOARD_Y = 20; public const string SCORE_PREFIX = "Score: "; public const int HEALTH_X = SCREEN_WIDTH - 250; public const int HEALTH_Y = 20; public const string HEALTH_PREFIX = "Health: "; public const int INITIAL_HEALTH = 100; } } <file_sep># SelenaNo This is the game that I am making based on Becky and Selena. Because I am bored and think it will be fun. <file_sep>using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using SelinaNo; namespace SelinaNo { /// <summary> /// This is the main type for your game. /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; #region Sprites and Rectangles // Declaring Selina texture and rectangle Texture2D selinaSprite; static Rectangle selinaRect; // Declaring Bex's texture Texture2D bexSprite; //Declaring Laser Sprite public static Texture2D laserSprite; //Title Sprite Texture2D titleSprite; Rectangle titleRect; #endregion //Declaring the List of Bex List<Becky> bexList = new List<Becky>(); static List<Projectile> projectileList = new List<Projectile>(); //Declaring the ONE random that will be used the entire game. Random rand = new Random(); //Declaring the sound effects SoundEffect merhSound; SoundEffect yumSound; SoundEffect hitSound; //Declaring Scoreboard Font SpriteFont scoreboardFont; Vector2 scoreboardLoc = new Vector2(GameConstants.SCOREBOARD_X, GameConstants.SCOREBOARD_Y); Vector2 healthLoc = new Vector2(GameConstants.HEALTH_X, GameConstants.HEALTH_Y); //Declaring Scoreboard static int score = 0; string scoreMessage = GameConstants.SCORE_PREFIX + score.ToString(); //Declaring the Health static int health = GameConstants.INITIAL_HEALTH; string healthMessage = GameConstants.HEALTH_PREFIX + health.ToString(); bool selinaAlive = true; //Declaring a simple vector2 for text alignment Vector2 size; //Declaring the initial GameState static GameState currentState = GameState.MainMenu; public static int Health { get { return health; } set { health = value; if (health < 0) { health = 0; } if (health > GameConstants.INITIAL_HEALTH) { health = GameConstants.INITIAL_HEALTH; } } } public static Rectangle SelinaHitBox { get { return selinaRect; } } public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferHeight = GameConstants.SCREEN_HEIGHT; graphics.PreferredBackBufferWidth = GameConstants.SCREEN_WIDTH; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); //Loading Font scoreboardFont = Content.Load<SpriteFont>(@"Fonts\scoreboardFont"); //Loading the Selina Sprite selinaSprite = Content.Load<Texture2D>(@"Sprites\Selina"); //Loading Laser Sprite laserSprite = Content.Load<Texture2D>(@"Sprites\laser"); //Loading Title Sprite titleSprite = Content.Load<Texture2D>(@"Sprites\title"); titleRect = new Rectangle(GameConstants.SCREEN_WIDTH / 2 - titleSprite.Width / 2, 100, titleSprite.Width, titleSprite.Height); //Loading the sound effects merhSound = Content.Load<SoundEffect>(@"Sounds\Merh"); yumSound = Content.Load<SoundEffect>(@"Sounds\Yum"); hitSound = Content.Load<SoundEffect>(@"Sounds\Explosion"); SoundEffect.MasterVolume = 0.5f; //Positioning stuff. This will be useful a lot. int halfSelinaX = selinaSprite.Width / 2; int halfSelinaY = selinaSprite.Height / 2; //Using Resize factor so we can play with the size of Selina. selinaRect = new Rectangle(GameConstants.SCREEN_WIDTH / 2 - halfSelinaX / GameConstants.RESIZE_FACTOR, GameConstants.SCREEN_HEIGHT / 2 - halfSelinaY / GameConstants.RESIZE_FACTOR, selinaSprite.Width / GameConstants.RESIZE_FACTOR, selinaSprite.Height / GameConstants.RESIZE_FACTOR); //Loading the Bex Sprite bexSprite = Content.Load<Texture2D>(@"Sprites\Bex"); //Spawn the first Bex spawnBex(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); if (currentState == GameState.MainMenu) if (Keyboard.GetState().IsKeyDown(Keys.Tab)){ currentState = GameState.Playing; } if (currentState == GameState.Playing){ if (selinaAlive) { #region Selina Movement // Selina Update Position based on mouse location MouseState mouse = Mouse.GetState(); selinaRect.X = mouse.X - (selinaSprite.Width / (2 * GameConstants.RESIZE_FACTOR)); selinaRect.Y = mouse.Y - (selinaSprite.Height / (2 * GameConstants.RESIZE_FACTOR)); //Clamping Selina to the Screen if (selinaRect.Left < 0) { selinaRect.X = 0; } if (selinaRect.Top < 0) { selinaRect.Y = 0; } if (selinaRect.Right > GameConstants.SCREEN_WIDTH) { selinaRect.X = GameConstants.SCREEN_WIDTH - selinaSprite.Width / GameConstants.RESIZE_FACTOR; } if (selinaRect.Bottom > GameConstants.SCREEN_HEIGHT) { selinaRect.Y = GameConstants.SCREEN_HEIGHT - selinaSprite.Height / GameConstants.RESIZE_FACTOR; } #endregion //Handling Collisions foreach (Becky bex in bexList) { if (selinaRect.Contains(bex.CollisionRectangle)) { yumSound.Play(); bex.Active = false; score += 10; scoreMessage = GameConstants.SCORE_PREFIX + score.ToString(); } } } #region Code Related to Becky //Adding new Becky if (bexList.Count < 10) { spawnBex(); } //Removing Dead Beckys for (int i = bexList.Count - 1; i >= 0; i--) { if (!bexList[i].Active) { bexList.RemoveAt(i); } } foreach (Becky bex in bexList) { bex.Update(gameTime); } #endregion foreach (Projectile projectile in projectileList) { projectile.Update(gameTime); } //Removing Dead Projectiles for (int k = projectileList.Count - 1; k >= 0; k--) { if (!projectileList[k].Active) { projectileList.RemoveAt(k); } } //Handling Collisions foreach (Projectile projectile in projectileList) { if (selinaRect.Contains(projectile.CollisionRectangle)) { hitSound.Play(); projectile.Active = false; Health -= 5; healthMessage = GameConstants.HEALTH_PREFIX + Health.ToString(); checkDeath(); } } } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { spriteBatch.Begin(); if (currentState == GameState.Playing) { GraphicsDevice.Clear(Color.CornflowerBlue); //Drawing the Becky's foreach (Becky bex in bexList) { bex.Draw(spriteBatch); } //Drawing the Projectiles foreach (Projectile projectile in projectileList) { projectile.Draw(spriteBatch); } //Drawing Selina spriteBatch.Draw(selinaSprite, selinaRect, Color.White); //Drawing the ScoreBoard and Health spriteBatch.DrawString(scoreboardFont, scoreMessage, scoreboardLoc, Color.White); spriteBatch.DrawString(scoreboardFont, healthMessage, healthLoc, Color.White); } if (currentState == GameState.MainMenu) { GraphicsDevice.Clear(Color.Black); spriteBatch.Draw(titleSprite, titleRect, Color.White); string message = "Press Tab to Play!"; size = scoreboardFont.MeasureString(message); spriteBatch.DrawString(scoreboardFont, message, new Vector2(GameConstants.SCREEN_WIDTH / 2 - size.X/2, 3*GameConstants.SCREEN_HEIGHT/4), Color.White); } if (currentState == GameState.LostNoHigh) { GraphicsDevice.Clear(Color.Black); string message = "You Lost!\nYour score was " + score.ToString() + "\nPress Escape to Quit"; size = scoreboardFont.MeasureString(message); spriteBatch.DrawString(scoreboardFont, message, new Vector2(GameConstants.SCREEN_WIDTH / 2 - size.X / 2, GameConstants.SCREEN_HEIGHT/2 - size.Y / 2), Color.White); } spriteBatch.End(); base.Draw(gameTime); } private void spawnBex() { int BexX = rand.Next(0, GameConstants.SCREEN_WIDTH - bexSprite.Width); int BexY = rand.Next(0, GameConstants.SCREEN_HEIGHT - bexSprite.Height); Becky Bex = new Becky(bexSprite, BexX, BexY, rand, merhSound); bexList.Add(Bex); } public static void addProjectile(Projectile projectile) { projectileList.Add(projectile); } public void checkDeath() { if (Health == 0) { currentState = GameState.LostNoHigh; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SelenaNo { class BeckyTemplate { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SelinaNo { public enum GameState { MainMenu, Playing, LostNoHigh, LostHigh, DisplayScores } }
525da0431726039f9a4625380980d42bc8d21212
[ "Markdown", "C#" ]
5
C#
Roymond35/SelenaNo
7c52771dd30427ce32c74a01ad6f0fa3884e3b97
01dc7cfb7ace0d92e5da2a0594c2b2edaa676f75
refs/heads/main
<repo_name>Yuu2002/react-tutorial<file_sep>/src/components/Button.jsx import React from "react"; import clsx from "clsx"; export const Button = (props) => { return ( <div className="navigation-button-group"> <button className={clsx( "navigation-button", props.isActive ? "navigation-active-button" : null )} onClick={props.onClick} > {props.children} </button> <span className={props.isActive ? "navigation-active-bar" : null} /> </div> ); }; <file_sep>/src/components/Progress.jsx import * as React from "react"; import CircularProgress from "@mui/material/CircularProgress"; export const Progress = () => { return ( <div className="progress-content"> <CircularProgress /> </div> ); }; <file_sep>/src/components/Header.jsx import React from "react"; import logo from "../assets/logo.svg"; import { Navigation } from "./Navigation"; export const Header = (props) => { const path = window.location.pathname; return ( <header className="header"> <div className="header-container"> <a href={path}> <div className="header-title"> <img src={logo} className="react-logo" alt="logo" /> <h1>React</h1> </div> </a> <Navigation {...props} /> </div> </header> ); }; <file_sep>/src/components/index.js export { Button } from "./Button"; export { FetchAPI } from "./FetchAPI"; export { Footer } from "./Footer"; export { Header } from "./Header"; export { Main } from "./Main"; export { Navigation } from "./Navigation"; export { Progress } from "./Progress"; <file_sep>/src/components/Navigation.jsx import React from "react"; import { Button } from "./Button"; export const Navigation = (props) => { return ( <div className="navigation"> {props.navigations.map((item, index) => ( <span key={item.title}> <Button isActive={props.activeIndex === index} onClick={() => props.onClick(index)} > {item.title} </Button> </span> ))} </div> ); };
40c5a814a12c4ea1c6e1e4a2e193b7f52eda23b3
[ "JavaScript" ]
5
JavaScript
Yuu2002/react-tutorial
8a2d5240fc4a7669fcda70d96f989d6e1b39a105
963c236a13a45b7237a6387aaa499b0ed247f018
refs/heads/master
<file_sep># ImagePicker Using UIImagePickerController. <file_sep>// // ImageObject.swift // ImagePicker // // Created by <NAME> on 1/20/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation // always have an object for5 all data - used to sved data struct ImageObject: Codable { let imageData: Data // UIImage needs to be converted to data - after retrieving - API changes to UIImage let date: Date let identifier = UUID().uuidString // crteates a quick ID on any object } <file_sep>// // ViewController.swift // ImagePicker // // Created by <NAME> on 1/20/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import AVFoundation // we want to AVMakeRect to maintain size ratio class ImagesViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! private var imageObjects = [ImageObject]() private let imagePickerController = UIImagePickerController() private let dataPersistence = PersistenceHelper(filename: "images.plist") private var selectedImage : UIImage? { didSet { // gets called when image is selected appendNewPhotoToCollection() } } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self loadImageObjects() // set UIImagePickerController delegate as this view controller imagePickerController.delegate = self } private func loadImageObjects() { do { imageObjects = try dataPersistence.loadEvents() } catch { print("loading objects error: \(error)") } } // MARK: - appendNewPhotoToCollection private func appendNewPhotoToCollection() { guard let image = selectedImage, // jpegData(compressionQuality: 1.0) converts UIImage to Data let imageData = image.jpegData(compressionQuality: 1.0) else { print("Image is nil") return } print("original image size is \(image.size)") // resize image let size = UIScreen.main.bounds.size // we will maintain the aspect ratio of the image let rect = AVMakeRect(aspectRatio: image.size, insideRect: CGRect(origin: CGPoint.zero, size: size)) // resize image let resizeImage = image.resizeImage(to: rect.size.width, height: rect.size.height) print("resize image size is \(resizeImage.size)") // jpegData(compressionQuality: 1.0) converts UIImage to Data guard let resizedImageData = resizeImage.jpegData(compressionQuality: 1.0) else { return } // create an image object using image let thisImageObject = ImageObject(imageData: imageData, date: Date()) // insert new image object in to imageObjects imageObjects.insert(thisImageObject, at: 0) // create an indexPath for insertion into collection view let indexPath = IndexPath(row: 0, section: 0) // insert new cell into collection view collectionView.insertItems(at: [indexPath]) // persist image object to documents directory do { try dataPersistence.create(item: thisImageObject) } catch { print("saving error \(error)") } } @IBAction func addPictureButtonPressed(_ sender: UIBarButtonItem) { // presents an action sheet to the user // actions: camera, photo library, cancel // alert dialog in center \\ let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // handler - is what happens after user selects object (camera) let cameraAction = UIAlertAction(title: "Camera", style: .default) { [weak self] alertAction in self?.showImageController(isCameraSelected: true) } // if source type is photoLibrary - closure is handled let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default) { [weak self] alertAction in self?.showImageController(isCameraSelected: false) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) // check i fcamera is available, if camera is not available // the app will crash if UIImagePickerController.isSourceTypeAvailable(.camera) { alertController.addAction(cameraAction) } alertController.addAction(photoLibraryAction) alertController.addAction(cancelAction) present(alertController, animated: true) } private func showImageController(isCameraSelected: Bool) { // source type default will be .photoLibrary imagePickerController.sourceType = .photoLibrary if isCameraSelected { imagePickerController.sourceType = .camera } present(imagePickerController, animated: true) } } // MARK: - UICollectionViewDataSource extension ImagesViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageObjects.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as? ImageCell else { fatalError("could not downcast to an ImageCell") } let imageObject = imageObjects[indexPath.row] cell.configureCell(imageObject: imageObject) // step 4 - creating custom delegation - set delegate object // similar to tableView.delegate = self cell.delegate = self return cell } } // MARK: - UICollectionViewDelegateFlowLayout extension ImagesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxWidth: CGFloat = UIScreen.main.bounds.size.width let itemWidth: CGFloat = maxWidth * 0.80 return CGSize(width: itemWidth, height: itemWidth) } } extension ImagesViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { imagePickerController.dismiss(animated: true) } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // we need to acess the UIImagePickerController.InfoKey.orginalImage key to gety the // UIImage that we selected guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { print("image selected not found") return // no need for fatal error = app doesnt need to crsh kif no image loaded } selectedImage = image imagePickerController.dismiss(animated: true) } } // step 6: creating custom delegation - conform to delegate extension ImagesViewController : ImageCellDelegate { func didLongPress(_ imageCell: ImageCell) { print("cell was selected") guard let indexPath = collectionView.indexPath(for: imageCell) else { return } // present an action sheet // actions: delete, cancel let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { [weak self] alertAction in self?.deleteImageObject(indexPath: indexPath) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alertController.addAction(deleteAction) alertController.addAction(cancelAction) present(alertController, animated: true) } private func deleteImageObject(indexPath: IndexPath) { // delete image object from documents library do { try dataPersistence.delete(event: indexPath.row) } catch { print("Delete Error: \(error)") } imageObjects.remove(at: indexPath.row) collectionView.deleteItems(at: [indexPath]) } } // more about resizin images - recommended watch // more here: https://nshipster.com/image-resizing/ // MARK: - UIImage extension extension UIImage { func resizeImage(to width: CGFloat, height: CGFloat) -> UIImage { let size = CGSize(width: width, height: height) let renderer = UIGraphicsImageRenderer(size: size) return renderer.image { (context) in self.draw(in: CGRect(origin: .zero, size: size)) } } }
d1e659165407b32c061b036f0c4d1f0f14ca13e6
[ "Markdown", "Swift" ]
3
Markdown
EricDavenport/ImagePicker
18db9d69fe8d74af83315f6301ad9f1ca46724e2
3321f8ab04548b7530536e29d75e4d9ddb1bff24
refs/heads/master
<repo_name>m-enani/a3<file_sep>/app/Http/Controllers/Restaurants.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class Restaurants extends Controller { public function index(){ return view('welcome'); } public function search(Request $request) { # store search results $filteredRestaurants = []; # validate form options $this->validate($request, [ 'budget' => 'required', 'dineInOrOut' => 'required', 'waitTime' => 'required|numeric', ]); $restaurantsRawData = file_get_contents(database_path().'/restaurants.json'); $restaurants = json_decode($restaurantsRawData, true); foreach($restaurants as $restaurant) { # filter if no cuisine type is selected if (strtolower($request->input('cuisineType')) == 'any' && $request->input('budget') == $restaurant['price'] && $request->input('dineInOrOut') == $restaurant['dining'] && $request->input('waitTime') >= $restaurant['wait_time']){ $filteredRestaurants[] = $restaurant; } # filter on all forms else if (strtolower($request->input('cuisineType')) == $restaurant['type'] && $request->input('budget') == $restaurant['price'] && $request->input('dineInOrOut') == $restaurant['dining'] && $request->input('waitTime') >= $restaurant['wait_time']){ $filteredRestaurants[] = $restaurant; } } # sort the array by restaurant name $filteredRestaurants = array_values(array_sort($filteredRestaurants, function ($value) { return $value['name']; })); # retain data on next view $request->flash(); # return search results and counter(used for displaying option number) return view('restaurants.search', [ 'filteredRestaurants' => $filteredRestaurants, 'counter' => '1', ]); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/search', 'Restaurants@search'); Route::get('/', 'Restaurants@index');
5a5f8eefeda7e910c087a8888213eec2d7dd60e6
[ "PHP" ]
2
PHP
m-enani/a3
d26dd8e05e5f6910b329c42dbd9b366b44e97f18
b6eb70a38420e01ee04d8aba43115ad16e3b35af
refs/heads/master
<repo_name>psymike/tapout-api<file_sep>/spec/support/test_web_server.rb # frozen_string_literal: true require 'sinatra/base' class TestWebServer < Sinatra::Base get '/api/v1/campaigns' do json_response 200 end get '/api/v1/campaigns/:id' do json_response 200, params['id'] end private def json_response(response_code, id = nil) content_type :json status response_code if id JSON.parse(File.open(File.dirname(__FILE__) + '/../fixtures/campaign_data.json', 'rb').read).detect do |e| Integer(e['id']) == Integer(id) end else JSON.parse(File.open(File.dirname(__FILE__) + '/../fixtures/campaign_data.json', 'rb').read) end.to_json end end <file_sep>/spec/models/campaign_qualification_spec.rb # frozen_string_literal: true require 'rails_helper' RSpec.describe CampaignQualification, type: :model do let(:campaign_qualification) { create(:campaign_qualification) } it 'only shows the required fields' do expect(campaign_qualification.as_json.keys).not_to include(%w[created_at updated_at campaign_quota_id]) end end <file_sep>/spec/support/api_helper.rb # frozen_string_literal: true module ApiHelper def json_response # punting on memoizing for now. we can find a solution later that memoizes # per request_id or something similar JSON.parse(@response.body) end end <file_sep>/app/jobs/tap_research_import_job.rb # frozen_string_literal: true class TapResearchImportJob < ApplicationJob queue_as :default def perform(*_args) TapResearchService.pull_campaigns end end <file_sep>/spec/factories/campaigns.rb # frozen_string_literal: true FactoryBot.define do factory :campaign do length_of_interview { rand(1..20) } cpi { rand(1.to_f..3.to_f).to_s.first(4) } name { "#{FFaker::Company.name} Campaign" } end end <file_sep>/spec/services/tap_research_service_spec.rb # frozen_string_literal: true require 'rails_helper' describe TapResearchService do let(:campaigns_json) { build(:campaigns_json) } before do # set the api url here because we want to use the web server: TestWebServer Rails.configuration.api_base_url = 'localhost' end describe 'instance methods' do subject { described_class.new } context 'Inserting data' do it 'inserts campaigns when called but only once' do expect { subject.pull_campaigns }.to change { Campaign.count }.by(9) expect { subject.pull_campaigns }.to change { Campaign.count }.by(0) end it 'inserts campaigns -> campaign_quotas when called but only once' do expect { subject.pull_campaigns }.to change { CampaignQuota.count }.by(7) expect { subject.pull_campaigns }.to change { CampaignQuota.count }.by(0) end it 'inserts campaign_quotas -> campaign_qualifications when called but only once' do expect { subject.pull_campaigns }.to change { CampaignQualification.count }.by(8) expect { subject.pull_campaigns }.to change { CampaignQualification.count }.by(0) end end context 'Updating data' do it 'updates campaign attributes' do campaign = create(:campaign, id: 278_562, name: 'Test name') expect { subject.pull_campaigns }.to change { campaign.reload.name } expect { subject.pull_campaigns }.to change { Campaign.count }.by(0) end it 'updates campaign_quota -> campaign_qualifications when called' do campaign_qualification = create(:campaign_qualification, question_id: 42, pre_codes: [100, 200, 300], campaign_quota: create(:campaign_quota, id: 1_118_454, campaign: create(:campaign, id: 278_562))) expect { subject.pull_campaigns }.to change { campaign_qualification.reload.pre_codes } expect { subject.pull_campaigns }.to change { CampaignQualification.count }.by(0) end end end end <file_sep>/spec/factories/campaign_quota.rb # frozen_string_literal: true FactoryBot.define do factory :campaign_quota do association :campaign end end <file_sep>/spec/factories/campaign_qualifications.rb # frozen_string_literal: true FactoryBot.define do factory :campaign_qualification do question_id { rand(1..1_000) } pre_codes { [1, 2, 3] } association :campaign_quota end end <file_sep>/app/models/application_record.rb # frozen_string_literal: true class ApplicationRecord < ActiveRecord::Base self.abstract_class = true connects_to database: { writing: :primary, reading: :readonly } # Why? So we can keep upstream relationships without doing ID swaps. Keeps rails rails def self.attributes_protected_by_default # default is ["id", "type"] ['type'] end end <file_sep>/spec/controllers/campaigns_controller_spec.rb # frozen_string_literal: true require 'rails_helper' describe CampaignsController, type: :controller do before do TapResearchService.pull_campaigns end it 'responds with the correct ID first' do get :ordered_campaigns, format: :json expect(json_response.first['id']).to eq(278_564) end end <file_sep>/config/routes.rb # frozen_string_literal: true Rails.application.routes.draw do namespace 'campaigns' do get 'ordered_campaigns', to: 'ordered_campaigns' end end <file_sep>/db/structure.sql SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); SET check_function_bodies = false; SET xmloption = content; SET client_min_messages = warning; SET row_security = off; SET default_tablespace = ''; SET default_table_access_method = heap; -- -- Name: ar_internal_metadata; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.ar_internal_metadata ( key character varying NOT NULL, value character varying, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: campaign_qualifications; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.campaign_qualifications ( id bigint NOT NULL, campaign_quota_id bigint NOT NULL, question_id integer NOT NULL, pre_codes integer[] DEFAULT '{}'::integer[], created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: campaign_qualifications_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE public.campaign_qualifications_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: campaign_qualifications_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE public.campaign_qualifications_id_seq OWNED BY public.campaign_qualifications.id; -- -- Name: campaign_quota; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.campaign_quota ( id bigint NOT NULL, campaign_id bigint NOT NULL, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: campaign_quota_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE public.campaign_quota_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: campaign_quota_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE public.campaign_quota_id_seq OWNED BY public.campaign_quota.id; -- -- Name: campaigns; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.campaigns ( id bigint NOT NULL, length_of_interview integer NOT NULL, cpi character varying NOT NULL, name character varying NOT NULL, created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL ); -- -- Name: campaigns_id_seq; Type: SEQUENCE; Schema: public; Owner: - -- CREATE SEQUENCE public.campaigns_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; -- -- Name: campaigns_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - -- ALTER SEQUENCE public.campaigns_id_seq OWNED BY public.campaigns.id; -- -- Name: schema_migrations; Type: TABLE; Schema: public; Owner: - -- CREATE TABLE public.schema_migrations ( version character varying NOT NULL ); -- -- Name: campaign_qualifications id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_qualifications ALTER COLUMN id SET DEFAULT nextval('public.campaign_qualifications_id_seq'::regclass); -- -- Name: campaign_quota id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_quota ALTER COLUMN id SET DEFAULT nextval('public.campaign_quota_id_seq'::regclass); -- -- Name: campaigns id; Type: DEFAULT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaigns ALTER COLUMN id SET DEFAULT nextval('public.campaigns_id_seq'::regclass); -- -- Name: ar_internal_metadata ar_internal_metadata_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.ar_internal_metadata ADD CONSTRAINT ar_internal_metadata_pkey PRIMARY KEY (key); -- -- Name: campaign_qualifications campaign_qualifications_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_qualifications ADD CONSTRAINT campaign_qualifications_pkey PRIMARY KEY (id); -- -- Name: campaign_quota campaign_quota_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_quota ADD CONSTRAINT campaign_quota_pkey PRIMARY KEY (id); -- -- Name: campaigns campaigns_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaigns ADD CONSTRAINT campaigns_pkey PRIMARY KEY (id); -- -- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.schema_migrations ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version); -- -- Name: cqa_question_id_campaign_quota_id; Type: INDEX; Schema: public; Owner: - -- CREATE UNIQUE INDEX cqa_question_id_campaign_quota_id ON public.campaign_qualifications USING btree (question_id, campaign_quota_id); -- -- Name: index_campaign_qualifications_on_campaign_quota_id; Type: INDEX; Schema: public; Owner: - -- CREATE INDEX index_campaign_qualifications_on_campaign_quota_id ON public.campaign_qualifications USING btree (campaign_quota_id); -- -- Name: index_campaign_quota_on_campaign_id; Type: INDEX; Schema: public; Owner: - -- CREATE INDEX index_campaign_quota_on_campaign_id ON public.campaign_quota USING btree (campaign_id); -- -- Name: campaign_quota fk_rails_3e78d37def; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_quota ADD CONSTRAINT fk_rails_3e78d37def FOREIGN KEY (campaign_id) REFERENCES public.campaigns(id); -- -- Name: campaign_qualifications fk_rails_9586a32292; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.campaign_qualifications ADD CONSTRAINT fk_rails_9586a32292 FOREIGN KEY (campaign_quota_id) REFERENCES public.campaign_quota(id); -- -- PostgreSQL database dump complete -- SET search_path TO "$user", public; INSERT INTO "schema_migrations" (version) VALUES ('20210311214814'), ('20210311221540'), ('20210311235637'); <file_sep>/app/models/campaign.rb # frozen_string_literal: true class Campaign < ApplicationRecord has_many :campaign_quotas, inverse_of: :campaign, dependent: :destroy has_many :campaign_qualifications, through: :campaign_quotas validates :name, :cpi, :length_of_interview, presence: true def as_json(options = {}) super(options.merge(except: %w[created_at updated_at])) end end <file_sep>/app/models/campaign_qualification.rb # frozen_string_literal: true class CampaignQualification < ApplicationRecord belongs_to :campaign_quota, touch: true def as_json(options = {}) # don't merge options here, they are not needed and extra stuff was # pp options super(options.merge(except: %w[created_at updated_at campaign_quota_id id])) end end <file_sep>/spec/models/campaign_quota_spec.rb # frozen_string_literal: true require 'rails_helper' RSpec.describe CampaignQuota, type: :model do let(:campaign_quota) { create(:campaign_quota) } it 'only shows the required fields' do expect(campaign_quota.as_json.keys).not_to include(%w[created_at updated_at campaign_id]) end end <file_sep>/spec/models/campaign_spec.rb # frozen_string_literal: true require 'rails_helper' RSpec.describe Campaign, type: :model do let(:campaign) { create(:campaign) } it 'only shows the required fields' do # since we are removing some fields, lets check them here. expect(campaign.as_json.keys).not_to include(%w[created_at updated_at]) end end <file_sep>/lib/tasks/import_data.rake # frozen_string_literal: true namespace :import_data do desc 'Get all of our campaigns from TapResearch and insert them 👍' task run: :environment do TapResearchService.pull_campaigns end end <file_sep>/spec/jobs/tap_research_import_job_spec.rb # frozen_string_literal: true require 'rails_helper' require 'sidekiq/testing' require 'sidekiq/testing/inline' Sidekiq::Testing.fake! RSpec.describe TapResearchImportJob, type: :job do include ActiveJob::TestHelper context 'in the instance' do it 'hits the service' do # this is all we're doing here, the service itself will be tested in its own context expect(TapResearchService).to receive(:pull_campaigns) described_class.new.perform end end context 'running the job' do it 'enqueues a job to default queue' do job = described_class.perform_later expect(job.queue_name).to eq('default') end it 'queues up a job in the queue' do expect do described_class.perform_later end.to change { enqueued_jobs.size }.by(1) end end end <file_sep>/README.md # README ## Run it Running the following will seed data and start the server. `./bin/setup && foreman start` There is a rake task that can bee ran to re-import the seed data: `rails import_data:run` ### Architecture There are 3 main components: Web server, Postgres instance, and redis. Redis is used for storing background jobs (we're not using cache, so this is its only purpose) When `foreman` is run, it will start the web server and it will start the sidekiq server. Using sidekiq-cron, we are able to have a job that runs every 30 minutes to re-populate the data. Due to sidekiq, the project requires redis. If redis does not exist on your system, the project will still run via `./bin/setup && ./bin/rails s` > Database The project uses postgreSQL for the datastore and `pre_codes` is serialized with an array column. ### Performance / Scalability * Database connection splitting for reads and writes * Currently both set to the same db * API-only app config * Gets rid of unneeded middleware. I also removed mail, storage, and view modules we don't need. > There are a bunch of other ways to go about this but this makes sense as not to bloat the project. [Horizontal Sharding](https://github.com/rails/rails/pull/38531) is interesting but sharding can be too much work, given that this app will be read heavy and scalable through replicas. ## Set it up First, install 'em with [Homebrew](https://brew.sh): ```bash brew install postgres redis ``` Then set them up to automatically start and [run in the background](https://thoughtbot.com/blog/starting-and-stopping-background-services-with-homebrew) every time you turn on your computer: ```bash brew services start postgres brew services start redis ``` > This is optional: > > * Then create a user for the Postgres database. > * The password for the user is just "<PASSWORD>" (without the quotes). You want to answer **yes** to making it a superuser. > ```bash > createuser --interactive --pwprompt tapout > ``` ### 2. Install Ruby dependencies tapout-api depends on a specific version of Ruby. The best way to do this is to use `rvm` (Ruby Version Manager). To install `rvm`, first make sure you have `gpg`: ```bash brew install gpg ``` Then, from a new terminal tab, follow the instructions on [rvm.io](https://rvm.io/rvm/install) to finish installing the latest stable release of the `rvm` command-line tool. Check the version of Ruby that tapout-api relies on (`cat .ruby-version`), then open another new terminal tab and install that particular version of Ruby using RVM. For example: ```bash rvm install `cat .ruby-version` ``` Now open a new terminal tab one more time, and `cd` out and then back into your local `tapout-api` directory one more time to trigger the creation of a gemset. Next, reinstall the `bundler` gem: ```bash gem install bundler ``` And last but not least, install tapout-api's local Ruby dependencies: ```bash bundle install ``` <file_sep>/app/models/campaign_quota.rb # frozen_string_literal: true class CampaignQuota < ApplicationRecord belongs_to :campaign, inverse_of: :campaign_quotas, touch: true has_many :campaign_qualifications, inverse_of: :campaign_quota, dependent: :destroy def as_json(options = {}) super(options.merge(except: %w[created_at updated_at campaign_id])) end end <file_sep>/app/controllers/campaigns_controller.rb # frozen_string_literal: true class CampaignsController < ApplicationController def ordered_campaigns resp = Campaign .includes(:campaign_qualifications, :campaign_quotas) .joins('left join campaign_quota cqa on cqa.campaign_id = campaigns.id') .joins('left join campaign_qualifications cqb on cqb.campaign_quota_id = cqa.id') .strict_loading.order('count(cqb.campaign_quota_id)') .group('campaigns.id') .collect do |camp| things = camp.campaign_quotas.collect { |e| e.as_json.merge(campaign_qualifications: camp.campaign_qualifications) } camp.as_json.merge(campaign_quotas: things) end render json: resp end end <file_sep>/app/services/tap_research_service.rb # frozen_string_literal: true class TapResearchService include HTTParty base_uri "https://#{Rails.configuration.api_base_url}" basic_auth Rails.application.credentials.tapresearch[:email], Rails.application.credentials.tapresearch[:api_token] def self.pull_campaigns new.pull_campaigns end def pull_campaigns campaigns.each do |campaign_json| # This is a little odd looking but what we're doing here is looking for a campaign. # If the campaign does not exist, then we create a new one. campaign = if (campaign = Campaign.find_by(id: campaign_json['id'])) campaign.update!(cpi: campaign_json['cpi'], length_of_interview: campaign_json['length_of_interview'], name: campaign_json['name']) campaign else Campaign.create!(id: campaign_json['id'], cpi: campaign_json['cpi'], length_of_interview: campaign_json['length_of_interview'], name: campaign_json['name']) end # Quotas are embedded in the campaign campaign_quotas = campaign(campaign.id)['campaign_quotas'] # Sometimes there is nothing next unless campaign_quotas.any? campaign_quotas.each do |campaign_quota| cq = CampaignQuota.create_or_find_by!(campaign_id: campaign.id, id: campaign_quota['id']) campaign_quota['campaign_qualifications'].each do |campaign_qualification| # and qualifications are embedded in the quota cqu = CampaignQualification.create_or_find_by!(question_id: campaign_qualification['question_id'], campaign_quota_id: cq.id) # these are just faster to update instead of doing a bunch of checks, we're mirroring data, not building it # so we'll not his this too much (i think, i mean this is an example app) cqu.update!(pre_codes: campaign_qualification['pre_codes']) end end end end def campaigns # We memoize these because the dataset is small. # If there was pagination or similar upstream, we may want to do this differently @campaigns ||= self.class.get('/api/v1/campaigns') end def campaign(id) self.class.get("/api/v1/campaigns/#{id}") end def all_quotas campaigns.collect do |campaign| self.class.get("/api/v1/campaigns/#{campaign['id']}")['campaign_quotas'] end end end <file_sep>/db/migrate/20210311235637_create_campaign_qualifications.rb # frozen_string_literal: true class CreateCampaignQualifications < ActiveRecord::Migration[6.1] def change create_table :campaign_qualifications do |t| t.references :campaign_quota, null: false, foreign_key: true t.integer :question_id, null: false t.integer :pre_codes, array: true, default: [] t.timestamps end add_index :campaign_qualifications, %i[question_id campaign_quota_id], unique: true, name: 'cqa_question_id_campaign_quota_id' end end
5eab6d55f910dae1768f6babf5ebc1ee269b2bd9
[ "Markdown", "SQL", "Ruby" ]
23
Ruby
psymike/tapout-api
27c94c4a736eff42b4e9764786ad54e3a9ce716c
b68aa8a6bd2181fec3224c398027f3ee383f00dd
refs/heads/master
<file_sep>#include <MQTTClient.h> // Be sure to install the MQTT client from Arduino Library Manager authored by <NAME> #include <MQTT.h> #include "heltec.h" // includes library that makes it easier to use OLED #include "WiFi.h" #include <ArduinoJson.h> #include <WiFiClientSecure.h> #include "dht11.h" #include "images.h" // Default Heltec images displayed on OLED #include "secrets.h" // Contains your wifi and AWS IoT credentials/config // The MQTT topics that this device should publish/subscribe #define AWS_IOT_PUBLISH_SHOCK_TOPIC "esp32/shockAlert" #define AWS_IOT_PUBLISH_SHADOW_TOPIC "$aws/things/esp32/shadow/update" #define AWS_IOT_SHADOW_DELTA_TOPIC "$aws/things/esp32/shadow/update/delta" #define AWS_IOT_SUBSCRIBE_TOPIC "esp32/alert" #define MESSAGE_IN_PIN 5 // LED with 100 ohm resistor that lights up when MQTT message received from AWS #define SHOCK_LED_PIN 17 // LED with 100ohm resistor that will light up when shock occurs #define SHOCK_SENSOR_PIN 35 // I used the shock sensor from this kit: https://www.amazon.com/kuman-K5-USFor-Raspberry-Projects-Tutorials/dp/B016D5L5KE #define LIGHT_LED_PIN 18 // Turn this off and on using device state from shadow; #define DHT11_PIN 14 // Temp/Humidity sensor void writeLine(String str, bool writeToSerial = true); dht11 DHT11; WiFiClientSecure net = WiFiClientSecure(); MQTTClient client = MQTTClient(256); int shockVal; // 1 if shock detected, 0 if not float humidity; // read from DHT11 float tempF; // read from DHT11 long previousMillis = 0; // will store last time shadow was updated long shadowInterval = 3000; // how often (ms) we update shadow bool lightEnabled = false; // the state.reported.lightEnabled value void setup() { setupDisplay(); setupPins(); connectAWS(); } void loop(){ client.loop(); // for MQTT to send/receive packets checkForShock(); unsigned long currentMillis = millis(); if(currentMillis - previousMillis > shadowInterval) { previousMillis = currentMillis; updateShadow(); } } void setupDisplay() { Serial.println("Setting up..."); Heltec.begin(true /*DisplayEnable Enable*/, false /*LoRa Enable*/, true /*Serial Enable*/); logo(); delay(300); Heltec.display->clear(); } void setupPins() { pinMode(SHOCK_LED_PIN, OUTPUT); pinMode(MESSAGE_IN_PIN, OUTPUT); pinMode(SHOCK_SENSOR_PIN,INPUT); pinMode(LIGHT_LED_PIN, OUTPUT); } void connectAWS() { WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); writeLine("Connecting to wifi..."); while (WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } // Configure WiFiClientSecure to use the AWS IoT device credentials net.setCACert(AWS_CERT_CA); net.setCertificate(AWS_CERT_CRT); net.setPrivateKey(AWS_CERT_PRIVATE); // Connect to the MQTT broker on the AWS endpoint we defined earlier client.begin(AWS_IOT_ENDPOINT, 8883, net); // Create a message handler client.onMessage(messageHandler); writeLine("Connecting to AWS..."); while (!client.connect(THINGNAME)) { Serial.print("."); delay(100); } if(!client.connected()){ Serial.println("AWS IoT Timeout!"); return; } // Subscribe to a topic client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC); client.subscribe(AWS_IOT_SHADOW_DELTA_TOPIC); writeLine("Connected to AWS!"); delay(2000); } void publishShockMessage() { StaticJsonDocument<200> doc; doc["time"] = millis(); doc["shockSensor"] = shockVal; char jsonBuffer[512]; serializeJson(doc, jsonBuffer); Serial.println("Publishing shock to IoT..."); client.publish(AWS_IOT_PUBLISH_SHOCK_TOPIC, jsonBuffer); } void messageHandler(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); if (topic == "esp32/alert") { handleAlertMessage(payload); } else if (topic == AWS_IOT_SHADOW_DELTA_TOPIC) { handleShadowDelta(payload); } } void handleShadowDelta(String &payload) { StaticJsonDocument<200> doc; deserializeJson(doc, payload); const char* error = doc["state"]["lightEnabled"]; if (error) { Serial.println("lightEnabled is not part of shadow delta..."); } else { Serial.println("toggling light..."); enableShadowLight(doc["state"]["lightEnabled"]); } //const boolean deltaLightEnabled = doc["state"]["lightEnabled"]; //if (deltaLightEnabled.isNull()) { // Serial.println("toggling light..."); // enableShadowLight(deltaLightEnabled); //} } void enableShadowLight(bool enabled) { if (enabled) { Serial.println("Turning light on."); digitalWrite(LIGHT_LED_PIN,HIGH); } else { Serial.println("Turning light off."); digitalWrite(LIGHT_LED_PIN,LOW); } lightEnabled = enabled; } // Just print received message to OLED display: void handleAlertMessage(String &payload) { StaticJsonDocument<200> doc; deserializeJson(doc, payload); const String message = doc["msg"]; digitalWrite(MESSAGE_IN_PIN,HIGH); writeLine(message); delay(2000); digitalWrite(MESSAGE_IN_PIN,LOW); } void logo(){ Heltec.display -> clear(); Heltec.display -> drawXbm(0,5,logo_width,logo_height,(const unsigned char *)logo_bits); Heltec.display -> display(); } // Write a line to both serial out and OLED display: void writeLine(String str, bool writeToSerial) { if (writeToSerial) { Serial.println(str); } Heltec.display -> clear(); Heltec.display -> drawString(10, 0, str); Heltec.display -> display(); } void checkForShock() { shockVal=digitalRead(SHOCK_SENSOR_PIN); if(shockVal==HIGH) { digitalWrite(SHOCK_LED_PIN,HIGH); writeLine("Disturbance in force!"); delay(1000); publishShockMessage(); digitalWrite(SHOCK_LED_PIN,LOW); } else { digitalWrite(SHOCK_LED_PIN,LOW); writeLine("No motion...", false); } } void readTempHumidity() { int chk = DHT11.read(DHT11_PIN); humidity = (float)DHT11.humidity; float tempC = (float)DHT11.temperature; tempF = tempC * 9/5 + 32; } void updateShadow() { readTempHumidity(); publishShadow(); } void publishShadow() { DynamicJsonDocument doc(200); JsonObject state = doc.createNestedObject("state"); JsonObject reported = state.createNestedObject("reported"); reported["time"] = millis(); reported["humidity"] = humidity; reported["tempFahrenheit"] = tempF; reported["lightEnabled"] = lightEnabled; char jsonBuffer[512]; serializeJson(doc, jsonBuffer); Serial.println("Publishing shadow to IoT..."); client.publish(AWS_IOT_PUBLISH_SHADOW_TOPIC, jsonBuffer); } <file_sep># Arduino + Heltec ESP 32 + AWS IoT - Shock Sensor This is a simple Arduino project that uses [this Heltec ESP 32 board](https://www.amazon.com/Development-0-96inch-Display-Arduino-Compatible/dp/B07428W8H3) with a built-in OLED display. I've wired the board with a [shock sensor from this kit](https://www.amazon.com/kuman-K5-USFor-Raspberry-Projects-Tutorials/dp/B016D5L5KE) and an LED with a 100 ohm resistor. When a shock (movement) is detected, the LED turns on and publishes a message to AWS IoT Core. Inspired by this blog: * https://aws.amazon.com/blogs/compute/building-an-aws-iot-core-device-using-aws-serverless-and-an-esp32/ ## Notes 1. The Heltec board does require some soldering. 2. Be sure to install the MQTT client from Arduino Library Manager authored by <NAME>. There are a lot of MQTT libraries for Arduino, and not all of them seem to support certificate-based authentication / mTLS needed by AWS IoT Core. 3. I've since added a DHT11 temp/humidity sensor that publishes these sensor values to AWS IoT shadow every few seconds. This is not yet reflected in the examples below. 4. Also since added a third LED that is meant to be toggled on/off using the AWS IoT device shadow. 4. At the moment, this is hacked together from various examples. Excuse the mess in `main.c`. # Demo Once the board turns on, it connects to WiFi and AWS IoT, and then waits for either the sensor to activate from motion or an incoming MQTT message from AWS IOT: ![](images/board1.jpg) If I physically move the board, the sensor activates, triggers a red LED, and publishes an MQTT message to the `esp32/shockAlert` topic in AWS IoT: ![](images/board2.jpg) Using the "Test" section of the AWS IoT Console to subscribe to this topic and see the message come in almost immediately: ![](images/web1.png) I can also use the IoT Console to publish messages. In this case, the device subscribes itself to the `esp32/alert` topic: ![](images/web2.png) And finally, the device is subscribed to the topic and will activate a yellow LED and show the received message on the OLED dispay: ![](images/board3.jpg)<file_sep>#include <pgmspace.h> #define SECRET #define THINGNAME "YOUR_THING_NAME" const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "<PASSWORD>PASSWORD"; const char AWS_IOT_ENDPOINT[] = "YOUR_IOT_ENDPOINT.iot.REGION.amazonaws.com"; // Amazon Root CA 1 // You can copy-paste this from this URL: // https://www.amazontrust.com/repository/AmazonRootCA1.pem static const char AWS_CERT_CA[] PROGMEM = R"EOF( -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- )EOF"; // Device Certificate // This is provided to you when you create your AWS IoT "Thing": static const char AWS_CERT_CRT[] PROGMEM = R"KEY( -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- )KEY"; // Device Private Key // This is provided to you when you create your AWS IoT "Thing": static const char AWS_CERT_PRIVATE[] PROGMEM = R"KEY( -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- )KEY";
227bf4c989f556d5cfe51fb9fec0dad7cfa210be
[ "Markdown", "C" ]
3
C
matwerber1/arduino-heltec-esp32-aws-iot-shock-sensor
0f1ca8c1a6438ad5c6dd46b194d1284164e73db2
caa9b83bbb9f1c52b7117432240bd9fcb4d06b0b
refs/heads/master
<repo_name>adamaveray/static-site-starter-template<file_sep>/dev/nunjucks/index.js const appendAssetHash = require('./../common/appendAssetHash'); module.exports = function(env) { env.addGlobal('asset', appendAssetHash); }; <file_sep>/dev/sass/index.js const appendAssetHash = require('./../common/appendAssetHash'); module.exports = function(sass) { const functions = {}; functions['asset($url)'] = (rawUrl) => { const newUrl = appendAssetHash(rawUrl.getValue()); return sass.types.String(newUrl); }; return functions; }; <file_sep>/dev/common/appendAssetHash.js const CRC32 = require('crc-32'); const fs = require('fs'); const path = require('path'); const isProduction = require('gulp-environment').production; const HASH_DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split(''); const hashCache = {}; function appendAssetHash(url) { if (!isProduction) { return url; } const filePath = path.join(__dirname, '../../dist', url); let hash = hashCache[url]; if (hash == null && fs.existsSync(filePath)) { const file = fs.readFileSync(filePath); // Get basic hash const hashRaw = (typeof file === 'string') ? CRC32.str(file) : CRC32.buf(file); let i = (hashRaw >>> 0); // Compress hash hash = ''; if (i === 0) { hash = HASH_DICTIONARY[0]; } else { const base = HASH_DICTIONARY.length; while (i > 0) { hash += HASH_DICTIONARY[i % base]; i = Math.floor(i / base); } } // Obfuscate hash hash = hash.split().reverse().join(''); hashCache[url] = hash; } if (hash != null) { url += `?v=${encodeURIComponent(hash)}`; } return url; } module.exports = (path) => appendAssetHash(path); <file_sep>/README.md Static Site Starter Template ============================ A starting point for a simple static site. ## Getting Started 1. Check out the repo: `git clone https://github.com/adamaveray/static-site-starter-template.git` 2. Set the site name and initial `templateVars` values in `package.json` 3. Install dependencies: `yarn` 4. Begin watch script & development server: `yarn run build & yarn run server & wait` 5. Auto-format and lint code after development: `yarn run format` and `yarn run lint` ----- ## Docs ### Inline critical SVGs To prevent separate requests for SVGs critical to the site layout, such as logos, replace `url(...)` with `inline-url(...)` in stylesheets. Inlining will only be performed for production builds. ### Auto asset versioning Automatic querystrings can be appended to asset links ... `{{ asset(...) }}` in Nunjucks templates. ### Generating multiple image sizes Images in the `src/img` directory will be automatically optimised and copied to the built `img` folder, however multiple sizes can be generated by declaring an entry in `dev/image-sizes.json`. Keys should be paths to the image (relative to the `src/img` directory), and values should be objects with the following format: - Keys are paths to output to (will be relative to the same directory). Prepending a path with `~` will append the remaining content to the name - Values are either: - A simple array: `[width: number, height: number, crop?: number]` (e.g. `[500, 300]`, `[250, 250, true]`) - An object with custom settings (see [available properties](https://github.com/dcgauld/gulp-responsive-images#options)) ```json { "example/full.jpg": { "thumb.jpg": [250, 250, true], "full.jpg": [1200, 800] } } ``` ### Copying additional static files Declare the files in `package.json` under `config` → `copyFiles`
74a9240136a763cff1c043a1f04da5af3ed4ed4f
[ "JavaScript", "Markdown" ]
4
JavaScript
adamaveray/static-site-starter-template
3bb7034ce8a0fbbd9e8638629431516c034c2037
e7025ac5fa22d184a9fca7d0c07f1f8bac47b407
refs/heads/master
<repo_name>Aragret/alya<file_sep>/create_cds_table.py #!/home/aragret/anaconda3/bin/python import os import re path = '/home/aragret/Alina/other_projects/alya/1_CDS_by_species' # path = '/home/aragret/Alina/other_projects/alya/noverlaps' with open('genes.txt', 'w') as outfile: for file in os.listdir(path): with open('1_CDS_by_species/{0}'.format(file)) as infile: for line in infile: if line[0] == '>': tab_split = line.split('\t') if tab_split[2] == 'translation': continue species = tab_split[1] gene = tab_split[0][1:] if re.match('[ATGC]+', line) != None: # print(line) outfile.write('{0}\t{1}\t{2}'.format(species, gene,line)) <file_sep>/cds_at_gc_skew.R rm(list=ls(all=TRUE)) # remove everything from R memory (old variables, datasets...) user = 'Alina' if (user == 'Alina') {setwd('/home/aragret/Alina/other_projects/alya/')} library(seqinr) ################################################################################ ### genes.txt is a result of create_cds_table.py script, which takes a directory with ### CDs and makes a table "species - gene - sequence" df = read.table('genes.txt', sep = '\t') VecOfSynFourFoldDegenerateSites = c('CTT','CTC','CTA','CTG','GTT','GTC','GTA','GTG','TCT','TCC','TCA','TCG','CCT','CCC','CCA','CCG','ACT','ACC','ACA','ACG','GCT','GCC','GCA','GCG','CGT','CGC','CGA','CGG','GGT','GGC','GGA','GGG') he <- c() for(i in 1:nrow(df)){ # i = 1 s <- s2c(as.character(df[i, 3])) #string into vector of chars Codons <- splitseq(s, 0, 3) #vector of chars into codons CodonsTable = data.frame(Codons) CodonsTable2 = CodonsTable[CodonsTable$Codons %in% VecOfSynFourFoldDegenerateSites,] four_fold_number = length(CodonsTable2) CodonsTable2 = paste(CodonsTable2, collapse="") if(CodonsTable2 == ''){ next } s <- s2c(CodonsTable2) Codons <- splitseq(s, 0, 3) nuctable = c() for (j in 1:length(Codons)){ nuctable = rbind( nuctable, s2c(Codons [j])[3]) } counts <- as.data.frame(table(nuctable)) str(counts) vec <- c("A", "T", "G", "C") counts <- counts[counts$nuctable %in% vec,] a = counts[counts$nuctable == 'A',]$Freq; t = counts[counts$nuctable == 'T',]$Freq g = counts[counts$nuctable == 'G',]$Freq; c = counts[counts$nuctable == 'C',]$Freq at_skew = (a - t) / (a + t) gc_skew = (g - c) / (g + c) he <- rbind(he, c(as.character(df[i, 1]), as.character(df[i,2]), at_skew, gc_skew, four_fold_number)) } he = as.data.frame(he) names(he) = c('Species', 'Gene', 'ATSkew', 'GCSkew', 'Sites_numbers') write.table(he, file='cds_at_gc_skew_with_sites_numbers.txt', quote = FALSE, sep = '\t', row.names = FALSE) summary(he[he$Gene == 'ATP8', 'ATSkew']) hist(as.numeric(as.character(he[he$Gene == 'ATP8', 'ATSkew']))) hist(as.numeric(as.character(he[he$Gene == 'ATP8', 'GCSkew']))) hist(as.numeric(as.character(he[he$Gene == 'CytB', 'ATSkew']))) hist(as.numeric(as.character(he[he$Gene == 'CytB', 'GCSkew'])))
45fa5cc909f260129c94d8fc7293adcfe9826104
[ "Python", "R" ]
2
Python
Aragret/alya
0e6d188a754fda67ac29dfc6f9e48537f8cb69a8
82df672c9ea866fb63f6ae1b20b07a625a603117
refs/heads/master
<repo_name>tlevine/recherchevirgule<file_sep>/search.py def search(db, column): this = summarise(column) those = db.something <file_sep>/connect.py import numpy def load(data): ''' [[str]] -> [numpy array] List of rows to list of numpy arrays, one numpy array per column, in order ''' for row in data: try: columns except NameError: columns = [[] * len(row)] for i, cell in enumerate(row): try: floatcell = float(cell) except TypeError: pass else: columns[i].append(floatcell) return map(summarize, columns) <file_sep>/statistics.py import numpy import scipy.stats as s modeprop = lambda v: s.mode(v)[1] / v.size names = ['mean', 'std', 'min', 'max', 'size'] stats = [ s.skew, s.kurtosis, modeprop, s.gmean, ] + [lambda v: getattr(v, name)() for name in names] def summarize(vector): ''' data vector -> features-of-data vector (Both are numpy vectors.) ''' return numpy.array(stat(vector) for stat in stats)
3a01004b999bf9d2e99fb2e2a9dec82b14309818
[ "Python" ]
3
Python
tlevine/recherchevirgule
acddc704fdb3a206feec43c344b907fff7fe49da
a7a321a223904ee6caf797adea85729b76c6753d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using NppPluginNET; using System.IO; namespace AutoIDs { public partial class frmMyDlg : Form { public string Mask { get { return tbMask.Text; } set { tbMask.Text = value; } } public string CurrentID { get { return tbCurrentId.Text; } set { tbCurrentId.Text = value; } } public frmMyDlg() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { Main.SaveConfigs(Mask); } private void btnRefresh_Click(object sender, EventArgs e) { Main.GetCurrentId(); Main.UpdateForm(); } } } <file_sep>using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using NppPluginNET; using System.Text.RegularExpressions; using System.Collections.Generic; namespace AutoIDs { class Main { #region " Fields " internal const string PluginName = "AutoIDs"; static string iniFilePath = null; static frmMyDlg frmMyDlg = null; static int idMyDlg = -1; static Bitmap tbBmp = Properties.Resources.star; static Bitmap tbBmp_tbTab = Properties.Resources.star_bmp; static Icon tbIcon = null; static bool _ShowConfig = false; static int _CurrentID; static string _Mask = @"sca_17296_"; #endregion #region " StartUp/CleanUp " internal static void CommandMenuInit() { _CurrentID = -1; StringBuilder sbIniFilePath = new StringBuilder(Win32.MAX_PATH); Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETPLUGINSCONFIGDIR, Win32.MAX_PATH, sbIniFilePath); iniFilePath = sbIniFilePath.ToString(); if (!Directory.Exists(iniFilePath)) Directory.CreateDirectory(iniFilePath); iniFilePath = Path.Combine(iniFilePath, PluginName + ".ini"); var sb = new StringBuilder(128); var res = Win32.GetPrivateProfileString("AutoIds", "Mask", null, sb, (uint)sb.Capacity, iniFilePath); _Mask = sb.ToString(); PluginBase.SetCommand(0, "Add ID", AddId, new ShortcutKey(false, true, false, Keys.I)); PluginBase.SetCommand(1, "Validate ID's", ValidateIds, new ShortcutKey(false, true, false, Keys.V)); PluginBase.SetCommand(2, "---", null); PluginBase.SetCommand(3, "Configure", myDockableDialog); idMyDlg = 1; frmMyDlg = new frmMyDlg(); frmMyDlg.Mask = _Mask; } internal static void SetToolBarIcon() { toolbarIcons tbIcons = new toolbarIcons(); tbIcons.hToolbarBmp = tbBmp.GetHbitmap(); IntPtr pTbIcons = Marshal.AllocHGlobal(Marshal.SizeOf(tbIcons)); Marshal.StructureToPtr(tbIcons, pTbIcons, false); Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_ADDTOOLBARICON, PluginBase._funcItems.Items[idMyDlg]._cmdID, pTbIcons); Marshal.FreeHGlobal(pTbIcons); } internal static void PluginCleanUp() { } #endregion #region " Menu functions " internal static void SaveConfigs(string mask) { _Mask = mask; Win32.WritePrivateProfileString("AutoIds", "Mask", _Mask, iniFilePath); } internal static void ValidateIds() { var hCurrentEditView = PluginBase.GetCurrentScintilla(); int length = (int)Win32.SendMessage(hCurrentEditView, SciMsg.SCI_GETLENGTH, 0, 0) + 1; StringBuilder sb = new StringBuilder(length); Win32.SendMessage(hCurrentEditView, SciMsg.SCI_GETTEXT, length, sb); var text = sb.ToString(); var mask = _Mask + @"(?'N'[\d]*)"; var regex = new Regex(mask); var matches = regex.Matches(text); List<string> values = new List<string>(); string result = ""; foreach (Match m in matches) { var v = m.Value; var n = m.Groups["N"].Value; if (values.Contains(n)) { result += string.Format("Duplicate Id {0}, line:{1} ", n, m.Index); } else { values.Add(n); } } if (result != "") { MessageBox.Show(result, "Auto Ids - Validations"); } else { MessageBox.Show("All OK!", "Auto Ids - Validations"); } } internal static void UpdateForm() { if (frmMyDlg != null) frmMyDlg.CurrentID = (_CurrentID + "").PadLeft(4, '0'); } internal static void GetCurrentId() { var hCurrentEditView = PluginBase.GetCurrentScintilla(); int length = (int)Win32.SendMessage(hCurrentEditView, SciMsg.SCI_GETLENGTH, 0, 0) + 1; StringBuilder sb = new StringBuilder(length); Win32.SendMessage(hCurrentEditView, SciMsg.SCI_GETTEXT, length, sb); var text = sb.ToString(); var mask = _Mask + @"(?'N'[\d]*)"; var regex = new Regex(mask); var matches = regex.Matches(text); _CurrentID = 0; foreach (Match m in matches) { var v = m.Value; var n = m.Groups["N"].Value; var intV = -1; if (int.TryParse(n, out intV)) { if (_CurrentID < intV) _CurrentID = intV; } } } internal static void AddId() { if (_CurrentID == -1) { GetCurrentId(); } if (_CurrentID > -1) { _CurrentID += 1; var hCurrentEditView = PluginBase.GetCurrentScintilla(); var newValue = _Mask + (_CurrentID + "").PadLeft(4, '0'); UpdateForm(); Win32.SendMessage(hCurrentEditView, SciMsg.SCI_BEGINUNDOACTION, 0, 0); Win32.SendMessage(hCurrentEditView, SciMsg.SCI_REPLACESEL, 0, newValue); Win32.SendMessage(hCurrentEditView, SciMsg.SCI_ENDUNDOACTION, 0, 0); } } internal static void myDockableDialog() { if (_ShowConfig == false) { _ShowConfig = true; using (Bitmap newBmp = new Bitmap(16, 16)) { Graphics g = Graphics.FromImage(newBmp); ColorMap[] colorMap = new ColorMap[1]; colorMap[0] = new ColorMap(); colorMap[0].OldColor = Color.Fuchsia; colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace); ImageAttributes attr = new ImageAttributes(); attr.SetRemapTable(colorMap); g.DrawImage(tbBmp_tbTab, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr); tbIcon = Icon.FromHandle(newBmp.GetHicon()); } NppTbData _nppTbData = new NppTbData(); _nppTbData.hClient = frmMyDlg.Handle; _nppTbData.pszName = "Auto IDs Configuration"; _nppTbData.dlgID = idMyDlg; _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR; _nppTbData.hIconTab = (uint)tbIcon.Handle; _nppTbData.pszModuleName = PluginName; IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData)); Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false); Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData); } else { Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMSHOW, 0, frmMyDlg.Handle); } } #endregion } }
e9f809eb79fe5616cbbee37998eccfa8231a29b5
[ "C#" ]
2
C#
Alpalhao/AutoIDs
e0955e50ccca65de7daab986e16e45c16bf81788
b2708116925a8b5c2be3e2f9fa97e6ff752bc7f6
refs/heads/master
<repo_name>citmp2015/server_config<file_sep>/hadoop/hadoop-env.sh export JAVA_HOME=/opt/jdk1.8.0_45 <file_sep>/.bash_aliases # ls aliases alias l='ls --color' alias ll='ls -la' alias lt='l -rt' alias la='l -A' alias llt='l -lrt' alias lla='l -lA' alias llat='l -lArt' alias h='history' # hadoop aliases unalias fs &> /dev/null alias fs="hadoop fs" unalias hls &> /dev/null alias hls="fs -ls" <file_sep>/README.md # Server config files for hadoop multi node cluster ## Install hadoop Clone git repo to your home folder `/home/vs_pj` `git clone https://github.com/citmp2015/server_config.git` Download hadoop to home folder `/home/vs_pj/` `wget http://apache.mirror.digionline.de/hadoop/core/stable/hadoop-2.7.1.tar.gz` Extract them `tar xzf hadoop-2.7.1.tar.gz` Rename the folder `mv hadoop-2.7.1 hadoop` Overwrite the .bashrc file with the one from the git repo and also place the .bash_aliases in your home folder `/home/vs_pj/`. `cp /home/vs_pj/server_config/.bashrc /home/vs_pj/` `cp /home/vs_pj/server_config/.bash_aliases /home/vs_pj/` Reload the .bashrc `source /home/vs_pj/.bashrc` ## Start configuring your hadoop environment. Copy all config files from the hadoop subfolder from the git repo to `/home/vs_pj/hadoop/etc/hadoop` `cp /home/vs_pj/server_config/hadoop/* /home/vs_pj/hadoop/etc/hadoop/` Create hadoop pid dir `mkdir /home/vs_pj/hadoop_pid` Change permission for the folder so that only the vs_pj user and group can write `chmod 770 /home/vs_pj/hadoop_pid` Create hadoop log dir `mkdir /home/vs_pj/hadoop_log` Create namenode dir on the root machine `mkdir /home/vs_pj/hadoop_namenode` Create datanode dir on the slaves machine `mkdir /home/vs_pj/hadoop_datanode` ### Attention! The `slaves` config file must be modified by hand. Un-/Comment the slaves you want. `nano /home/vs_pj/hadoop/etc/hadoop/slaves` You have also to configure the `core-site.xml` manually. Uncomment the master Namenode (asok05 or asok13) `nano /home/vs_pj/hadoop/etc/hadoop/core-site.xml` ## Additional stuff Fix some server pre-configs This overwrite wrong JAVA_HOME dependency `cp /home/vs_pj/server_config/java.sh /etc/profile.d/java.sh` ## Starting Hadoop Before you can start Hadoop you have to format the HDFS. Attention: All data in your (not existing) HDFS will be lost! Only on your Namenode (asok05 or asok13) `$HADOOP_HOME/bin/hdfs namenode -format <clustername>` Finally start the Hadoop Namenode (asok05 or asok13) `$HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start namenode` Start you Hadoop Datanodes (the other asoks) `$HADOOP_HOME/sbin/hadoop-daemons.sh --config $HADOOP_CONF_DIR --script hdfs start datanode` If you are done with that you can start all of the HDFS processes `$HADOOP_HOME/sbin/start-dfs.sh` Eventually you have to accept the `ECDSA key fingerprint` during this process. If you get the error message `xxx.xxx.xxx.xxx JAVA_HOME is not set and could not be found.` make sure that in the /home/vs_pj/hadoop/etc/hadoop/hadoop-env.sh file you an export to the correct path of your JAVA_HOME. If you want to stop HDFS `$HADOOP_HOME/sbin/stop-dfs.sh` ## Check you running HDFS instance Check you namenode (XY is the namenode server ip asok05 -> 34; asok13 -> 42) `http://130.149.248.XY:50070/dfshealth.html#tab-overview` ## Install flink Download flink to home folder `/home/vs_pj/` `wget http://apache.lauf-forum.at/flink/flink-0.9.1/flink-0.9.1-bin-hadoop27.tgz` Extract them `tar xzf flink-0.9.1-bin-hadoop27.tgz` Rename the folder `mv flink-0.9.1 flink` ## Start configuring your flink environment. Copy all config files from the flink subfolder from the git repo to `/home/vs_pj/flink/conf/` `cp /home/vs_pj/server_config/flink/* /home/vs_pj/flink/conf/` ### Attention! The `slaves` config file must be modified by hand. Un-/Comment the slaves you want. `nano /home/vs_pj/flink/conf/slaves` You have also to configure the `flink-conf.yaml` config file by hand. Un-/Comment the `jobmanager.rpc.address` you want in line 25 or line 28. `nano /home/vs_pj/flink/conf/flink-conf.yaml` ## Start flink Now the easy task `$FLINK_HOME/bin/start-cluster.sh` If you want to start the streaming mode `$FLINK_HOME/bin/start-cluster-streaming.sh` If you want to use the flink web-client you have to start them separately `$FLINK_HOME/bin/start-webclient.sh` Stop them with `$FLINK_HOME/bin/stop-webclient.sh` In addition to that you can stop flink `$FLINK_HOME/bin/stop-cluster.sh` And same for the streaming mode `$FLINK_HOME/bin/stop-cluster-streaming.sh` ## Check your running flink instance XY is the namenode server ip asok05 -> 34; asok13 -> 42 `http://130.149.248.XY:8081` Check the web-client `http://130.149.248.XY:8080`
318af7842a54a61d7bda64247bcc08fd752da81b
[ "Markdown", "Shell" ]
3
Shell
citmp2015/server_config
f9be331b38a516d5402aae953e31b43167909d49
f818a356ebe23ae6d95b962bab0a3809ae973e98
refs/heads/master
<file_sep>--- id: - 6448c55e-557c-4113-8c5b-0de969a7ddb9 name: <NAME> company: Tikal position: Mobile description: s subject: eee image: /img/moti-bar-tov.jpg language: he twitter: s linkedin: s --- <file_sep>import React from "react"; import styled from "styled-components"; import Fade from "react-reveal/Fade"; import {Devices} from "../layouts/styled-components"; const Person = ({first_name, last_name, company, image, position, subject, index = 0, onClickFunc = null}) => { return ( <Styles> <Fade key={first_name + last_name} top delay={(index + 1) * 200} distance="20px"> <div className="person" key={`${first_name}-${last_name}`} onClick={onClickFunc}> <div className="image" style={{backgroundImage: `url(..${image})`}}></div> <div className="overlay"> <span>{`${first_name} ${last_name}`}</span> <small>{company}</small> </div> </div> </Fade> </Styles> ); }; export default Person; const Styles = styled.li` list-style-type: none; min-width: 350px; .speakers { display: flex; flex-direction: row-reverse; list-style: none; padding: 0; flex-wrap: wrap; justify-content: center; } .person { position: relative; cursor: pointer; height: 407px; transition: all 0.5s ease; } .person .overlay { display: flex; flex-direction: column; justify-content: center; width: 100%; height: 100%; background: rgba(232, 114, 33, 0.84); position: absolute; top: 0; left: 0; opacity: 0; transition: all 0.5s ease; color: #ffffff; } .person:hover .overlay { opacity: 1; } .person .image { width: 100%; height: 100%; background-position: center; background-size: cover; } .person .overlay span { font-size: 20px; text-transform: uppercase; font-weight: 600; text-align: center; } .person .overlay small { font-size: 20px; font-weight: 400; text-align: center; } .person img { max-width: 100%; } @media (${Devices.mobile}) { width: 100%; margin: 0; } `; <file_sep>import React from "react"; import {Map, GoogleApiWrapper, Marker} from "google-maps-react"; const GoogleMap = props => { return ( <Map google={props.google} zoom={17} style={{width: "100%", height: "100%"}} initialCenter={{lat: 32.0647158, lng: 34.7632327}} styles={[{featureType: "poi", stylers: [{visibility: "off"}]}]} gestureHandling={"greedy"} scrollwheel={false} > <Marker position={{lat: 32.0647158, lng: 34.7632327}} /> </Map> ); }; export default GoogleApiWrapper({ apiKey: "<KEY>" })(GoogleMap); <file_sep>export default { // titleTemplate: "%s | Tech Radar Day 2020", openGraph: { type: "website", site_name: "Tech Radar Day 2020", url: "https://fullstackradar.tikalk.com", images: [{url: "https://fullstackradar.tikalk.com/img/seo/sharing-facebook.png"}] }, twitter: { cardType: "summary", site: "@tikalk" } }; <file_sep>--- name: chegg logo: /img/chegg.png type: exhibitor --- <file_sep># minisite This is a ministite starter based on [Nextjs](https://nextjs.org/) with Typescript. ## Development 1. Clone this repo 2. yarn install 3. yarn dev <file_sep>import React from "react"; import Styles from "../css/section-one"; import RadarLogo from "../../../components/RadarLogo"; import {logEvent} from "../../../helpers/analytics"; const SectionOne = () => { return ( <Styles> <div className="section-one"> <div className="section-one-container"> <RadarLogo /> <div className="text"> <h1> TECH RADAR <br /> DAY 2020 </h1> <h2>Full Day of Full Stack</h2> <h3> <div>May 18th, 2020</div> <div><NAME>, Tel-Aviv</div> <div className="discount-notification"> Early bird tickets are on sale now. <br /> Save up to <span className="orange">40%</span>. Valid Until March 1st. </div> </h3> <div className="get-tickets-btn"> <a href="https://www.eventbrite.com/e/tech-radar-day-2020-tickets-86701092301" target="_blank" onClick={() => { logEvent("Tickets", "Clicked", "Home page - fold"); }} > get tickets </a> </div> </div> </div> <svg className="icon-arrow-down" viewBox="0 0 32 32"> <use xlinkHref="../img/sprites.svg#icon-arrow-down"></use> </svg> </div> </Styles> ); }; export default SectionOne; <file_sep>import App, {Container} from "next/app"; import React from "react"; import {DefaultSeo} from "next-seo"; import SEO from "../seo.config"; export default class MyApp extends App { render() { const {Component, pageProps} = this.props; return ( <Container> <DefaultSeo {...SEO} /> <Component {...pageProps} /> </Container> ); } } <file_sep>--- time: '13:30 - 14:30' break: break_text: Lunch is_break: true --- <file_sep>--- name: solutu logo: /img/soluto.png type: media --- <file_sep>--- title: Regular 600 NIS tickets_left: Available end_date: until May 1st --- <file_sep>import React from "react"; import Styles from "../css/section-six"; import Fade from "react-reveal/Fade"; import {logEvent} from "../../../helpers/analytics"; import sortBy from "lodash.sortby"; import Person from "../../../components/Person"; const SectionSix = props => { const {speakers = []} = props; const sortedSpeakers = sortBy(speakers, ["first_name"]); return ( <Styles> <div className="section-six"> <h2>SPEAKERS</h2> <ul className="speakers"> {sortedSpeakers.map((speaker, index) => { const {first_name, last_name, image, company} = speaker; return <Person key={first_name + last_name} index={index} {...speaker} />; })} </ul> <a className="get-tickets-button" href="https://docs.google.com/forms/d/e/1FAIpQLScIajS252lrhkA8U92Gt3YlTFJClkOJjLjRdk3y-bbRs4DCqw/viewform" target="_blank" onClick={() => { logEvent("Become a Speaker", "Cliked", "Home page"); }} > BECOME A SPEAKER </a> </div> </Styles> ); }; export default SectionSix; <file_sep>--- time: '12:00 - 13:00' speeches: backend: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' devops: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' frontend: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' mobile: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' --- <file_sep>--- id: - 6e2aa95a-3a32-45db-abdb-2e14efd8f71d name: <NAME> company: Tikal position: backend description: c subject: ddd image: /img/haim-cohen.jpg language: he twitter: d linkedin: c --- <file_sep>--- id: - 3a287c8e-a88f-43cd-9010-521624d04599 name: <NAME> company: Tikal position: DevOps description: cc subject: jdkjd image: /img/haggai-philip-zagury.jpg language: he twitter: c linkedin: c --- <file_sep>import React, {useEffect, useState} from "react"; import Link from "next/link"; import {useRouter} from "next/router"; import {Devices} from "../layouts/styled-components"; import {logEvent} from "../helpers/analytics"; const links = [ {href: "/", label: "Home"}, {href: "/radar", label: "Tech Radar", showInMobile: false}, // { // href: // "https://www.youtube.com/channel/UCV7lV9Lq2sc7t0QEKS4xH7A/playlists?view=50&sort=dd&shelf_id=2", // label: "Videos", // target: "_blank" // }, {href: "https://2019.techradarday.com/", label: "2019", target: "_blank"} // { href: "/speakers", label: "Speakers" }, // { href: "/schedule", label: "Schedule" }, // { href: "/#sponsors", label: "Sponsors" }, ].map(link => ({ ...link, key: `nav-link-${link.href}-${link.label}` })); const Nav = () => { let [isScrolling, setScroll] = useState(false); let [mobileMenuIsOpen, toggleMobileMenu] = useState(false); useEffect(() => { window.onscroll = () => { setScroll(window.document.documentElement.scrollTop > 30); }; }, []); const onNavClicked = navLabel => { logEvent("Nav", "Clicked", navLabel); }; const router = useRouter(); return ( <nav className={isScrolling ? "scrolling" : ""}> <a className="logo" href="https://www.tikalk.com" target="_blank"> <img src="../img/logo_white.svg" /> </a> <svg className="menu-trigger-mobile" viewBox="0 0 32 32" onClick={() => toggleMobileMenu(state => !state)}> <use xlinkHref="../img/sprites.svg#icon-menu"></use> </svg> <ul className={mobileMenuIsOpen ? "open" : ""}> {links.map(({key, href, label, target = null, showInMobile = true}) => { const isActive = router.pathname === href; return ( <li key={key} className={!showInMobile ? "hide-in-mobile" : ""} onClick={() => onNavClicked(label)}> <Link href={href} prefetch={false}> <a className={isActive ? "active" : ""} target={target}> {label} </a> </Link> </li> ); })} </ul> <div className="buy-ticket-btn"> <a href="https://www.eventbrite.com/e/tech-radar-day-2020-tickets-86701092301" target="_blank" onClick={() => { logEvent("Tickets", "Clicked", "Navigation"); }} > GET TICKETS </a> </div> <style jsx>{` :global(body) { margin: 0; font-family: Montserrat; } nav { text-align: center; background-color: #363434; position: fixed; width: 100%; height: 96px; display: flex; align-items: center; justify-content: space-around; z-index: 999999; top: 0; } nav.scrolling { box-shadow: 1px 2px 8px -2px rgba(0, 0, 0, 0.8); } .logo { position: absolute; left: 10%; margin-top: -5px; } ul { display: flex; margin: 0; justify-content: flex-end; width: 50%; } nav > ul { padding: 4px 16px; margin-top: 3px; } li { display: flex; padding: 6px 8px; } li a { font-size: 16px; font-weight: 600; -webkit-transition: all 0.3s; transition: all 0.3s; text-transform: uppercase; color: #fff; text-decoration: none; } li a:hover, li a.active { text-decoration: none; color: #ff6f00; font-weight: 700; } nav .buy-ticket-btn { position: absolute; right: 7%; display: block; background: linear-gradient(90deg, #e87221 0%, #e9a35c 98%); border-radius: 34px; color: white; font-size: 15px; line-height: 15px; text-decoration: none; text-transform: uppercase; width: fit-content; height: fit-content; padding: 10px 17px; user-select: none; cursor: pointer; font-style: normal; font-weight: bold; transition: 1s all; } nav .buy-ticket-btn a { user-select: none; font-weight: 700; text-decoration: none; font-size: 15px; color: #ffffff; } .menu-trigger-mobile { display: none; } @media (${Devices.mobile}) { nav { height: 57px; } nav ul { transform: translateX(-100%); width: 256px; background: #363333; display: flex; flex-direction: column; position: fixed; top: 57px; left: 0; align-items: flex-startl; padding-top: 80px; transition: all 0.5s ease; height: auto; padding: 0 10px; text-align: right; } nav ul.open { transform: translateX(0); } .hide-in-mobile { display: none; } nav li a { color: #ffffff; font-size: 16px; padding: 7px 0; } .logo { top: 13px; z-index: 999999; left: initial; right: 0%; } .logo img { transform: scale(0.6); } .menu-trigger-mobile { width: 20px; height: 20px; fill: #ffffff; display: block; position: absolute; top: 18px; left: 23px; cursor: pointer; } nav .buy-ticket-btn { display: none; } } `}</style> </nav> ); }; export default Nav; <file_sep>--- title: 'DevOps in 2020: the new challenges' teaser: >- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. content: >- Duis aute irure dolor in reprehenderit in **voluptate** velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint _occaecat_ cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. date_published: 2020-01-30T09:49:34.677Z --- <file_sep>--- id: - 121711f5-37b6-4099-891f-58112cdfc58b name: <NAME> company: Tikal position: Tech Lead description: >- Lorem ipsum dolor sit amet, consdectetcur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Udt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. subject: abc image: /img/assaf-gannon.jpg language: he twitter: 'https://twitter.com' linkedin: 'https://www.linkedin.com' --- <file_sep>--- id: - 63f79636-06e5-4171-af89-5d7497eb3fc3 name: <NAME> company: Tikal position: Backend description: s subject: sksckds image: /img/yanai-franchi.jpg language: he --- <file_sep>--- id: - ff8442cf-9a42-4743-b311-8ca179e8397a name: <NAME> company: Tikal position: Frontend description: d subject: dkjdl image: /img/shavit-cohen.jpg language: he --- <file_sep>--- title: Early Bird 400 tickets_left: Only 50 Tickets! end_date: Available Until March 1st is_active: true --- <file_sep>import React from "react"; import Modal from "react-modal"; import styled from "styled-components"; import {Devices} from "../layouts/styled-components"; const SpeakerModal = props => { Modal.setAppElement("#__next"); const {first_name, last_name, image, position, company, description, linkedin, twitter} = props.speaker; const {onModalClosed} = props; const customStyles = { overlay: { backgroundColor: "rgba(0, 0, 0, 0.75)" }, content: { top: "50%", left: "50%", right: "auto", bottom: "auto", marginRight: "-50%", transform: "translate(-50%, -50%)", borderRadius: 16, maxWidth: "80%" } }; return ( <Modal isOpen={true} style={customStyles} contentLabel="Speaker Modal"> <Styles> <div className="wrapper"> <a className="close-modal" onClick={onModalClosed}> X </a> <div className="image"> <img src={image} /> </div> <div className="content"> <h3> {`${first_name} ${last_name}`} <span>{`${position}, ${company}`}</span> </h3> <p>{description}</p> <hr /> {(twitter || linkedin) && <span>{`Follow ${first_name}`}</span>} {twitter && ( <a href={twitter} target="_blank"> <img src="../img/twitter-icon.png" /> </a> )} {linkedin && ( <a href={linkedin} target="_blank"> <img src="../img/linkedin-icon.png" /> </a> )} </div> </div> </Styles> </Modal> ); }; export default SpeakerModal; const Styles = styled.div` .wrapper { display: flex; padding: 20px 50px; color: #2c2929; } .close-modal { position: absolute; top: 20px; right: 20px; font-size: 18px; cursor: pointer; transform: scaleX(1.2); } .image img { width: 150px; margin-right: 30px; } .content { max-width: 70%; } .content h3 { font-size: 20px; color: #f47720; font-weight: 900; margin-top: 0; } .content h3 span { font-weight: 300; } .content p { width: 440px; font-size: 16px; line-height: 20px; max-width: 100%; } .content hr { background: linear-gradient(178.52deg, #e87221 25.25%, #f5c653 94.44%); border: none; height: 1.5px; margin: 20px 0; } .content a { display: inline-flex; align-items: center; position: relative; top: 3px; } .content img { width: 20px; margin-left: 10px; } @media (${Devices.mobile}) { .wrapper { flex-direction: column; max-height: 400px; padding: 20px; padding: 20px; } .content { max-width: 100%; } .content span { display: inline-block; margin-bottom: 30px; } } `; <file_sep>import React from "react"; import styled from "styled-components"; import {Devices} from "../layouts/styled-components"; const RadarLogo = () => { return ( <Styles> <div className="radar-wrapper"> <div className="radar-outer"> <img className="text" /> <div className="radar"> <div className="cross-section"></div> <div className="spinner-outer"> <div className="spinner"></div> </div> <img className="octopus" /> </div> </div> </div> </Styles> ); }; export default RadarLogo; const Styles = styled.div` .radar-wrapper { width: 50%; height: 510px; position: relative; left: 0; top: 0; } .radar-outer { width: 490px; height: 490px; position: relative; } .radar-outer .text { width: 490px; height: 490px; position: absolute; top: 0; left: 0; content: url(../img/radar_text.png); } .radar-outer .radar { position: relative; height: 100%; width: 100%; border-radius: 50%; background: radial-gradient( ellipse at center, transparent 0%, transparent 0.5%, transparent 13%, #cccccc 13.5%, transparent 14%, transparent 25%, #cccccc 25.5%, transparent 26%, transparent 26%, transparent 35%, #cccccc 35.5%, transparent 36%, transparent 36%, transparent 46%, #cccccc 46.5%, transparent 47%, transparent 47%, transparent 58%, #cccccc 58.5%, transparent 59%, rgba(125, 185, 232, 0) 100% ); overflow: hidden; } .spinner-outer { position: absolute; width: 82%; height: 82%; border-radius: 50%; top: 44px; left: 45px; border: solid 1px transparent; overflow: hidden; -webkit-transform: translateZ(0); -webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%); } .radar-outer .spinner { position: absolute; height: 100%; width: 100%; margin: 50%; background: linear-gradient(55deg, rgba(0, 192, 0, 0) 30%, #ff6f00) 0% 0/50% 50%; background-repeat: no-repeat; transform-origin: 0 0; animation: scan 2s linear forwards; border-right: 1px solid #fe885f; } .radar-outer .octopus { position: absolute; margin: 60px 90px; content: url(../img/radar_timi.png); width: 65%; height: 65%; animation: elevate 2s ease-in-out forwards alternate; animation-iteration-count: 2; } @media (${Devices.laptop}) { transform: scale(0.7); } `; <file_sep>import React, {useEffect} from "react"; import styled from "styled-components"; import {Devices} from "../layouts/styled-components"; import RadarLogo from "./RadarLogo"; const Footer = () => { useEffect(() => { if (window.emailjs) { emailjs.init("user_dX7huKW88qxnJkjJ5XkRW"); } }, []); const onDetailsSubmit = e => { e.preventDefault(); const inputs = e.currentTarget; emailjs .send("gmail", "contact_us", { name: inputs[0].value, email: inputs[1].value, message: inputs[2].value, subject: "Fullstack Radar Day" }) .then( function(response) { alert("Thank you"); console.log(response); }, function(err) { alert("Sorry, message was not sent"); console.log(err); } ); }; return ( <Styles> <section className="footer"> <h2>GET IN TOUCH</h2> <h3>We are here to answer all your questions about Tech Radar Day 2020</h3> <div className="form-wrapper"> <form className="uppercase m-regular top-30" onSubmit={event => onDetailsSubmit(event)}> <div className="form-row"> <textarea id="msg" name="msg" placeholder="MESSAGE" required="required"></textarea> </div> <div className="form-row personal-details m-regular"> <input type="text" name="name" placeholder="NAME" required="required" /> <input type="email" name="email" placeholder="EMAIL" required="required" /> </div> <div className="form-row submit" id="fakeSubmitButton"> <div className="submit-text uppercase white"> <span>send</span> </div> <input id="submitButton" type="submit" value="send" /> </div> </form> <RadarLogo /> </div> <div className="social"> <a href="https://www.facebook.com/TikalKnowledge?fref=ts" target="_blank"> <img src="../img/facebook-icon.png" /> </a> <a href="https://twitter.com/tikalk" target="_blank"> <img src="../img/twitter-icon.png" /> </a> <a href="https://www.linkedin.com/company/tikal-knowledge/" target="_blank"> <img src="../img/linkedin-icon.png" /> </a> <a href="https://www.meetup.com/full-stack-developer-il/" target="_blank"> <img src="../img/meetup-icon.png" /> </a> </div> <img className="mobile-footer-logo" src="img/octopus contact.png" /> </section> </Styles> ); }; export default Footer; const Styles = styled.div` .footer { padding: 40px 52px 40px; background: #2c2929; position: relative; color: #ffffff; background: linear-gradient(0deg, #231f20, #231f20); } .footer h2 { font-style: normal; font-weight: 900; font-size: 50px; line-height: 50px; margin: 0; } h3 { width: 440px; font-style: normal; font-weight: 900; font-size: 20px; line-height: 23px; } .form-wrapper { display: flex; align-items: flex-start; justify-content: space-between; } .footer form { margin-top: 30px; text-transform: uppercase; width: 625px; display: flex; flex-direction: column; } .footer input, .footer textarea { background: transparent; color: white; font-style: normal; font-weight: normal; font-size: 16px; line-height: 20px; padding: 10px; resize: none; border: 2px solid #ffffff; box-sizing: border-box; border-radius: 16px; height: 64px; } .footer .form-row { display: flex; margin-bottom: 20px; } .footer input[type="text"] { margin-right: 10px; width: 165px; } input[type="text"], input[type="email"] { padding: 10px; font-size: 14px; color: white; width: 266px; } .personal-details { font-size: 24px; margin-bottom: 20px; } .footer textarea { width: 441px; height: 159px; } .submit { position: relative; background: white; color: black; border-radius: 34px; font-style: normal; font-weight: bold; font-size: 15px; padding: 10px 20px; width: fit-content; height: fit-content; cursor: pointer; } input[type="submit"] { position: absolute; opacity: 0; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer; } .black { color: black; } .submit:hover { filter: brightness(160%); } .social { display: flex; flex-direction: row; align-items: baseline; width: 240px; justify-content: space-between; } input::placeholder, textarea::placeholder { color: white; opacity: 1; } .form-wrapper .radar-wrapper { top: -110px; margin-right: 80px; } .mobile-footer-logo { display: none; } @media (${Devices.tablet}) { .radar-wrapper { display: none; } } @media (${Devices.mobile}) { .footer { padding: 40px 20px 150px; background: #2c2828; overflow: hidden; } .footer h2 { text-align: center; font-size: 30px; } .footer h3 { width: 100%; text-align: center; } .form-wrapper { flex-direction: row; } .radar-wrapper { display: none; } .footer form { width: 100%; margin-top: 20px; } .form-row { flex-direction: column; } .footer input[type="text"], .footer input[type="email"] { width: 100%; margin: 10px 0; } .footer textarea { width: 100%; } .personal-details { margin-bottom: 10px; } .form-row.submit { margin: 20px auto; margin-top: 0; } .social { bottom: 100px; right: 15px; margin: 0 auto; margin-top: 20px; text-align: center; } .mobile-footer-logo { position: absolute; bottom: -50px; left: 50%; transform: translate(-50%); display: block; } } `; <file_sep>--- id: - 85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d title: speech devops content: some content here... speakers: - '["3a287c8e-a88f-43cd-9010-521624d04599"]' - '["6e2aa95a-3a32-45db-abdb-2e14efd8f71d"]' --- <file_sep>--- time: '11:00 - 12:00' speeches: backend: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' devops: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' frontend: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' mobile: '["85157ca1-8dc9-4bf4-9dc8-9c334b8dd10d"]' --- <file_sep>--- title: Micro Services After Shock content: >- After many companies and organizations adopted the micro-service architecture it maybe is time to see how this architecture style has impacted not only the software but also other parts of the company and even in the whole industry. 1. Doing micro-services is very hard! 2. There seems to be a link between the software architecture style and the company structure. The more independent the individual teams are the more likely this architectural style will succeed. 3. Micro-service architecture facilitates the usage of multiple frameworks and languages. This empowerment allows teams to select the exact tools for the job. Nevertheless, a lot of care must be taken not to overwhelm people and the organization to a point of total chaos. Code reuse is not a bad thing. 4. As micro-services have advocated for smaller unit s of work, this has been taken further into different areas such as the micro-frontends and even serverless architectures. image: /img/stars.png tags: - Frontend - Backend - Devops --- <file_sep>--- id: - aa993bc5-550f-4f7c-ace2-035cff26a7c7 title: Welcome and Registartion --- <file_sep>--- id: - 7e6240bd-e362-4d79-b957-bdea3244edbe name: <NAME> company: Tikal position: backend description: a subject: dkjldkj image: /img/sigal-shaharabani.jpg language: he --- <file_sep>import styled from "styled-components"; import {Devices} from "../../../layouts/styled-components"; const Styles = styled.div` .section-eight { background: #ffffff; padding: 50px 0 60px 100px; text-align: left; color: #ffffff; background-image: url(/img/sponsors-bg.png); background-repeat: no-repeat; background-size: cover; background-position: right; } h2 { font-style: normal; font-weight: 900; font-size: 50px; line-height: 50px; margin-bottom: 27px; } p { width: 440px; font-family: Montserrat; font-style: normal; font-weight: normal; line-height: 20px; } .get-tickets-button { position: relative; display: block; background: linear-gradient(90deg, #e87221 0%, #e9a35c 98%); border-radius: 34px; color: white; font-size: 15px; line-height: 15px; text-decoration: none; text-transform: uppercase; width: fit-content; height: fit-content; padding: 10px 17px; user-select: none; cursor: pointer; font-style: normal; font-weight: bold; transition: 1s all; } p:nth-of-type(2) { font-weight: 600; font-size: 16px; line-height: 20px; } a { color: #f5c653; } .seperator { height: 1px; width: 440px; background-color: white; } .main-orgenizers { margin-top: 28px; margin-bottom: 57px; font-style: normal; font-weight: 600; font-size: 20px; line-height: 23px; display: flex; flex-direction: row; align-items: baseline; } .main-orgenizers > div { margin-right: 26px; } .white-logo { display: block; } .black-logo { display: none; } /* h2 { font-size: 50px; font-weight: 900; } h3 { margin-top: 30px; font-size: 20px; font-weight: normal; } .list-inline { margin: 0; padding-left: 0; list-style: none; margin-left: -5px; display: flex; justify-content: center; } .list-inline li { display: flex; position: relative; flex-direction: column; justify-content: center; align-items: center; width: 16%; max-width: 180px; margin: 13px 7px; min-height: 158px; border: solid 1px #cccccc; transition: all 0.3s; filter: grayscale(1); overflow: hidden; } .list-inline.sponsors li { min-height: 213px; } .hover14::before { position: absolute; top: 0; left: -75%; z-index: 2; display: block; content: ""; width: 50%; height: 100%; background: -webkit-linear-gradient( left, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.3) 100% ); background: linear-gradient( to right, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.3) 100% ); -webkit-transform: skewX(-25deg); transform: skewX(-25deg); } .hover14:hover::before { animation: shine 0.75s; } @keyframes shine { 100% { left: 125%; } } .list-inline li a { flex-grow: 2; display: flex; flex-direction: column; justify-content: space-around; cursor: pointer; } .list-inline li .partner-name { bottom: 8px; font-size: 12px; border-top: solid 0.5px #cccccc; width: 100%; line-height: 35px; } .list-inline li:hover { filter: grayscale(0); } .partner-logo { padding: 10px; } .partner-logo img { width: 100%; } .become-sponsor-btn { display: inline-block; text-decoration: none; font-size: 16px; padding: 8px 45px 8px 35px; background-color: #2c2929; user-select: none; cursor: pointer; color: #ffffff; margin: 10px; margin-top: 40px; }*/ @media (${Devices.mobile}) { .section-eight { background: #ffffff; width: 100%; padding: 50px 0 10px; color: #000000; text-align: center; } h2 { font-size: 30px; line-height: 50px; margin-bottom: 10px; } p { width: 100%; padding: 20px; box-sizing: border-box; } .get-tickets-button { margin: 0 auto; } .list-inline { flex-wrap: wrap; } .list-inline li { width: 40%; } .seperator { background: #000000; width: 80%; margin: 0 auto; } .main-orgenizers { align-items: center; flex-direction: column; } .main-orgenizers div { margin: 0; text-align: center; } .white-logo { display: none; } .black-logo { display: block; } } `; export default Styles; <file_sep>import styled from "styled-components"; import {Devices} from "../../../layouts/styled-components"; const Styles = styled.div` .section-four { position: relative; background: #ffffff; padding: 60px 0 80px; text-align: center; z-index: 0; } h2 { font-style: normal; font-weight: 900; font-size: 50px; line-height: 50px; text-align: center; letter-spacing: 0.451238px; text-transform: uppercase; margin: 0 0 46px; } .shadow-effect { position: relative; } .shadow-effect:before, .shadow-effect:after { z-index: -1; position: absolute; content: ""; bottom: 15px; width: 50%; top: 80%; max-width: 300px; background: #777; -webkit-box-shadow: 0 15px 10px #777; -moz-box-shadow: 0 15px 10px #777; box-shadow: 0 15px 10px #777; -webkit-transform: rotate(-3deg); -moz-transform: rotate(-3deg); -o-transform: rotate(-3deg); -ms-transform: rotate(-3deg); transform: rotate(-3deg); } .shadow-effect:after { -webkit-transform: rotate(3deg); -moz-transform: rotate(3deg); -o-transform: rotate(3deg); -ms-transform: rotate(3deg); transform: rotate(3deg); right: unset; transform: translateX(-100%) rotate(3deg); } @media (${Devices.tablet}) { h2 { font-size: 30px; line-height: 30px; margin: 0 20px 25px; } } @media (${Devices.mobile}) { .videoWrapper { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .videoWrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } } `; export default Styles; <file_sep>--- title: Replace Redux with React hooks teaser: >- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. content: >- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. date_published: 2020-01-30T09:49:34.677Z --- <file_sep>import React from "react"; import Styles from "../css/section-five"; import Domains from "../../../components/Domains"; const SectionFive = props => { return ( <Styles> <div className="section-five"> <h3>GET ON THE RADAR</h3> <h4 className="orange">Discover the Full Range of Full Stack </h4> <p> We designed Tech Radar Day to give you the best full stack hands-on experience. During the first part of the day, you'll hear excellent lectures from our keynote speakers. Right afterwards, we will split into 4 tracks, and run 4 different workshops on the most up-to-date technologies from the tech radar. </p> <Domains /> </div> </Styles> ); }; export default SectionFive; <file_sep>--- title: AIOps & Data Driven Approach content: >- What is AIOps? Put simply, AIOps is the application of machine learning (ML) and data science to IT operations problems. AIOps platforms combine big data and ML functionality to enhance and partially replace all primary IT operations functions, including availability and performance monitoring, event correlation and analysis, and IT service management and automation. In addition, we see more and more adoption of ML (and eventually some level of AI) on the day to day operations, which help build self-healing/self-maintained infrastructure, using advanced monitoring and tracing capabilities which were commoditized over the past decade and rapidly evolved with the popularity of Microservices and Cloud-Native technologies. Similarly, we also see a rise in AI-driven operations as part of the SDLC, in the form of IDE plugins/extensions & SaaS providing similar insights as part of the CI/CD processes. image: /img/alops.png tags: - Devops - Machine learning --- <file_sep>--- time: '9:30 - 10:00' principal_speech: '["5addc11b-1b91-4536-adc7-beec33b561b5"]' --- <file_sep>--- title: Polycloud Strategy content: >- “Polycloud Strategy” is an approach where companies/developers choose the right service for tasks, based on features capability, without consideration if he in the cloud provider that other services of your application using. The concept is choosing the right service for your tasks, across clouds provider. for example, your application running on AWS but you are using BigQuery of Google for your data analysts. This concept is starting to be adopted because the three major cloud providers have more or less the same services and you can leverage the difference of specific services that fit your needs. This concept is different from cloud-agnostic, You don’t try to create an application that, can run on any provider but using the best service that fits your needs. When using this “polycloud strategy”, You can find your self dealing with data transfer between cloud providers, which can be more expensive. image: /img/image.png tags: - Backend - Devops - Techniques - Platforms --- <file_sep>import React from "react"; import Styles from "../css/section-two"; import Fade from "react-reveal/Fade"; const SectionTwo = () => { return ( <Styles> <div className="section-two"> <Fade left distance="50px"> <h3>TECH RADAR DAY IN NUMBERS</h3> </Fade> <Fade top distance="50px" cascade> <div className="statistic"> <div> <img src="../img/people.svg" /> <h3>500+</h3> <h5>Attendees</h5> </div> <div> <img src="../img/hours.svg" /> <h3>20+</h3> <h5>Hours</h5> </div> <div> <img src="../img/speakers.svg" /> <h3>20+</h3> <h5>Speakers</h5> </div> <div> <img src="../img/tracks.svg" /> <h3>4</h3> <h5>Tech Tracks</h5> </div> </div> </Fade> </div> </Styles> ); }; export default SectionTwo; <file_sep>--- id: - 65b40500-7d31-4b96-aac7-b9a6f74ca666 name: <NAME> company: Tikal position: Mobile description: d subject: djkj image: /img/ronel-girat.jpg language: he --- <file_sep>--- time: '08:30 - 09:30' principal_speech: '["aa993bc5-550f-4f7c-ace2-035cff26a7c7"]' --- <file_sep>--- id: - 5addc11b-1b91-4536-adc7-beec33b561b5 title: Opening words content: Lorem Ipsum speakers: - '["7e6240bd-e362-4d79-b957-bdea3244edbe"]' --- <file_sep>import React from "react"; import Styles from "../css/section-eight"; import {logEvent} from "../../../helpers/analytics"; const SectionEight = props => { const {sponsors = []} = props; const sponsor = sponsors.filter(s => s.attributes.type === "sponsor"); const exhibitors = sponsors.filter(s => s.attributes.type === "exhibitor"); const media = sponsors.filter(s => s.attributes.type === "media"); return ( <Styles> <div className="section-eight" id="sponsors"> <h2>SPONSORS</h2> <p> Tech Radar Day 2020 is a unique opportunity to connect with our growing community. During the event, you will meet and engage with more than 500 developers from different domains and positions, from a wide range of startups and tech companies. </p> <a className="get-tickets-button m-semi-bold" href="https://docs.google.com/forms/d/e/1FAIpQLSdZP6u-sqo2-l-JfJNTtS0P5eAJ3yqD-CfwnhP32FcMIihS8w/viewform" target="_blank" onClick={() => { logEvent("Become a Sponsor", "Cliked", "Home page"); }} > BECOME A SPONSOR </a> <p> Tikal is open to creative sponsorship suggestions that retain our mission of providing the best possible experience for our community. Feel free to contact us for more details - <a href="mailto:<EMAIL>"><EMAIL></a> </p> <div className="seperator"></div> <div className="main-orgenizers"> <div>Main organizer: </div> <img src="/img/logo_white.svg" alt="logo" className="white-logo" /> <img src="/img/logo_black.svg" alt="logo" className="black-logo" /> </div> {/* <h2>ORGANIZERS</h2> <h3>MAIN ORGANIZER</h3> <ul className="list-inline"> <Partner key="tikal" name="tikal" logo="../img/tikal.png" link="http://www.tikalk.com" /> </ul> <h2>PARTNERS</h2> <h3>SPONSORS</h3> <ul className="list-inline sponsors"> {sponsor.map(partner => ( <Partner key={partner.attributes.name} {...partner.attributes} /> ))} </ul> <h3>EXHIBITORS</h3> <ul className="list-inline sponsors"> {exhibitors.map(partner => ( <Partner key={partner.attributes.name} {...partner.attributes} /> ))} </ul> <h3>MEDIA</h3> <ul className="list-inline media"> {media.map(partner => ( <Partner key={partner.attributes.name} {...partner.attributes} /> ))} </ul> <a className="become-sponsor-btn" href="/sponsor"> become a sponsor </a> */} </div> </Styles> ); }; export default SectionEight; const Partner = props => { const {name, logo, link} = props; return ( <li className="hover14"> <a href={link} target="_blank"> <div className="partner-logo"> <img src={logo} title={name} alt={name} /> </div> </a> <div className="partner-name">{name}</div> </li> ); }; <file_sep>--- first_name: Noah last_name: Ram position: Deveolper of life image: /img/05.png --- <file_sep>--- name: AlignTech logo: /img/alignteck.png link: 'https://www.aligntech.com/' type: sponsor --- <file_sep>--- name: <NAME> logo: /img/sedaily.png link: 'https://softwareengineeringdaily.com/' type: sponsor --- <file_sep>--- time: '10:00 - 10:30' break: break_text: Breakfast is_break: true --- <file_sep>window.addEventListener("click", onRadarClick); window.onunload = function(event) { window.removeEventListener("click", onRadarClick); }; var iFrame = null; var topics = {}; window.onRadarReady = function(iframe) { iFrame = iframe; iFrame.contentDocument.addEventListener("click", onIframeClicked); var checkLinks = this.setInterval(function() { var anchors = [].slice.call(iFrame.contentDocument.links); if (anchors.length > 0) { clearInterval(checkLinks); anchors.forEach(function(element) { element.setAttribute("target", "_blank"); }); var tables = iFrame.contentDocument.querySelectorAll(".quadrant-table"); tables.forEach(function(table) { setTableToDictionary(table); var newQuadArray = reorderRadarQuadrentContent(table); removeQuadrantChildren(table); newQuadArray = newQuadArray.reduce(function(acc, val) { return acc.concat(val); }, []); newQuadArray.forEach(function(item) { table.appendChild(item); table.addEventListener("click", onTableClick); }); }); var qudrants = iFrame.contentDocument.querySelectorAll(".quadrant-group"); qudrants = [].slice.call(qudrants); qudrants.forEach(function(q) { q.addEventListener("click", onQuadrentClick); }); var ulContents = iFrame.contentDocument.querySelectorAll("#radar div.quadrant-table ul"); ulContents = [].slice.call(ulContents); ulContents.forEach(function(ul) { ul.classList.add("ul-expanded"); ul.classList.add("ul-collapsed"); }); } }, 500); }; // Reordering radar table. // This part is done at runtime. Rings reordering is done in _plugins/tech_radar_loader.rb // Reordering is done according to 'order' array var order = ["try", "start", "keep", "stop"]; function removeQuadrantChildren(quad) { var children = [].slice.call(quad.children); children.forEach(function(c) { c.parentElement.removeChild(c); }); } function reorderRadarQuadrentContent(quad) { var qChildren = quad.childNodes; var tmp = []; var title = qChildren[0]; // Take h3,ul pairs for (var i = 1; i < qChildren.length; i += 2) { var child = qChildren[i]; var name = child.innerText; var idx = getIndexFor(name); tmp[idx] = [child, child.nextSibling]; } tmp.unshift(title); return tmp; } function onTableClick(event) { var target = event.target; console.log("onTableClick", target); if (target.tagName.toLowerCase() === "h3") { target.nextSibling.classList.toggle("ul-collapsed"); } } function onQuadrentClick(event) { var target = event.target; console.log("onQuadrentClick", target); if (target.tagName.toLowerCase() === "path") { var num = target.nextSibling.innerHTML; if (num) { topics[num].ul.classList.remove("ul-collapsed"); topics[num].content.classList.add("expanded"); } } } function getIndexFor(name) { var res = false; var i = 0; for (var i = 0; i < order.length; i++) { var item = order[i]; if (item.toLowerCase() === name.toLowerCase()) { res = true; break; } } return res ? i : -1; } function setTableToDictionary(table) { var titles = table.querySelectorAll(".blip-list-item"); titles = [].slice.call(titles); titles.forEach(function(title) { var num = title.innerText.substring(0, title.innerText.indexOf(".")); topics[num] = { ul: title.parentElement.parentElement, content: title.nextSibling }; }); } window.addEventListener("click", onRadarClick); var domainSelected = false; function onIframeClicked(event) { var target = event.target; var backButton = document.getElementById("showRadar"); var parentElement = target.parentElement; if (parentElement && parentElement.tagName === "g") { backButton.classList.add("home-link-show"); // if(domainSelected && parentElement.className.baseVal === 'blip-link'){ // var textElement = parentElement.children[1]; // var index = textElement.innerHtml; // } domainSelected = true; } else { if (target.classList.length > 0) { var className = target.className; if (className.includes("button")) { backButton.classList.add("home-link-show"); domainSelected = false; } } } } function onRadarClick(event) { var target = event.target; if (target.classList && target.classList.contains("domain-tab")) { var children = document.querySelectorAll("div.anchors .domain-tab"); target.classList.add("domain-tab-selected"); var length = children.length; for (var i = 0; i < length; i++) { var a = children[i]; if (a !== target) { a.classList.remove("domain-tab-selected"); } } var backButton = document.getElementById("showRadar"); backButton.classList.add("home-link-show"); } else if (target.id === "showRadar") { // The radar back button has the same class name as 'our' back button var backButton = iFrame.contentDocument.getElementsByClassName("home-link")[0]; if (backButton) { backButton.click(); target.classList.remove("home-link-show"); var children = document.querySelectorAll("div.anchors .domain-tab"); var length = children.length; for (var i = 0; i < length; i++) { var a = children[i]; a.classList.remove("domain-tab-selected"); } } } } window.initThoughtRadars = event => { // Radar iframe auto resize and preloader $(".thought-radar").each(function() { var $this = $(this); var sheet = $this.attr("data-sheet"); var iframe = $('<iframe frameborder="0"></iframe>').css("visibility", "hidden"); var loader = $('<div class="loader"><i class="glyphicon glyphicon-spin glyphicon-repeat"></i></div>'); var powered = $( '<div class="powered-by">Powered by <a href="https://github.com/thoughtworks/build-your-own-radar" target="_blank">ThoughtWorks</a></div>' ); $this .append(loader) .append(iframe) .append(powered); iframe[0].onload = function() { iframe.css("visibility", "visible"); setTimeout(function() { loader.hide(); }, 500); setInterval(function() { iframe.height(iframe[0] && iframe[0].contentWindow && iframe[0].contentWindow.document.body.scrollHeight); }, 100); window.onRadarReady(iframe[0]); }; iframe[0].src = "radar/radar.html?sheetId=" + encodeURIComponent(sheet); $("[data-radar-button]").on("click", function() { var which = $(this).attr("data-radar-button"); var button = $(iframe[0].contentWindow.document.getElementsByClassName("button")).filter("." + which)[0]; button.click(); }); }); }; <file_sep>--- title: Late Bird 800 NIS tickets_left: Available end_date: until may 17th --- <file_sep>import styled from "styled-components"; import {Devices} from "../../../layouts/styled-components"; const Styles = styled.div` .section-two { height: 275px; background: linear-gradient(178.52deg, #e87221 25.25%, #f5c653 94.44%); background-size: 100%; display: flex; flex-direction: column; align-items: center; } h3 { font-style: normal; font-size: 26px; line-height: 1.2; letter-spacing: 0.451238px; text-transform: uppercase; color: #ffffff; text-align: center; margin: 30px; margin-bottom: 0; font-weight: 900; } .black { color: #000000; } p { color: #ffffff; margin: 20px 0; line-height: 1.5; font-size: 16px; } .statistic { display: flex; color: #ffffff; justify-content: space-evenly; width: 80%; margin-top: 50px; } .statistic > div { width: 25%; text-align: center; } .statistic h3 { margin: 0; font-weight: 400; font-size: 26px; font-weight: 600; } .statistic h5 { font-size: 16px; line-height: 23px; font-weight: normal; text-align: center; margin: 0; } .statistic img { height: 68px; } @media (${Devices.mobile}) { .section-two { justify-content: flex-start; padding-top: 30px; height: 530px; } h3, h4 { font-size: 30px; text-align: center; line-height: 1.2; } p { font-size: 22px; line-height: 26px; text-align: center; padding: 0 8px; } .statistic { flex-wrap: wrap; } .statistic > div { width: 49%; margin-bottom: 50px; } } `; export default Styles; <file_sep>--- title: Remote Working & Distributed Teams content: >- Developers working together, remotely, from all around the world is becoming more popular for Software Development using Distributed team style which is composed of developers who work remotely from all around the world rather than being co-located in a single office. We believe companies all over the world will embrace more flexible and remote working styles. Here’s why we’ll see the rise of the distributed workforce: * It’s never been easier to work remotely, Today, technology connects us instantly. Video conferencing allows us to chat practically face-to-face, and group messaging tools put us in constant contact, whether our teams are in the same city or different time zones. * It’s harder than ever to attract and retain talent, distributed teams have a distinct advantage—they offer companies the ability to meet talent developers where they are. * Companies must be agile to survive, A distributed team structure can help companies work with more agility. Think about it: If your developers are working from locations all around the world, you’ll have people on the clock for more of each 24 hours. * The workplace is becoming more developers-centric, More people than ever want—and expect—flexible work arrangements. image: /img/chair.png tags: - Mobile - Techniques - Backend - Devops - Frontend --- <file_sep>--- name: Netflix logo: /img/netflix.png type: sponsor --- <file_sep>import React from "react"; import Styles from "../css/section-four"; const SectionFour = () => { return ( <Styles> <div className="section-four"> <h2> A Taste of <br /> Tech Radar Day 2019 </h2> <div className="videoWrapper shadow-effect"> <iframe width="560" height="315" src="https://www.youtube.com/embed/xjHOdXkN6P0" frameBorder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen="" ></iframe> </div> </div> </Styles> ); }; export default SectionFour; <file_sep>--- first_name: Noa last_name: Codebraker position: Coffe maker image: /img/06.png ---
910f98d128cbb64a2ac01ba8f380209909e864fc
[ "Markdown", "JavaScript" ]
52
Markdown
NahumLandau/netlify_cms_blog
12d5458653e0f6cadb5217878eacb24990329193
1d3ef34bb50a9fd138bc4824466def4f1ea4b3dd
refs/heads/master
<file_sep>package books; /** * @program JavaBooks * @description: 剪绳子 * @author: mf * @create: 2019/08/25 15:55 */ /* 给你一根长度为n的绳子,请把绳子剪成m段(m,n都是整数,n>1并且m>1), 每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]xk[1]x...xk[m]可能 的最大值乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别2、3、3的三段, 此时得到的最大乘积是18 */ public class T14 { public static void main(String[] args) { int max = maxProductAfterCutting1(4); System.out.println(max); int max1 = maxProductAfterCutting2(4); System.out.println(max1); } // 动态规划 private static int maxProductAfterCutting1(int length) { if (length < 2) return 0; if (length == 2) return 1; if (length == 3) return 2; int[] products = new int[length + 1]; products[0] = 0; products[1] = 1; // 长度为2... products[2] = 2; // 长度为3... products[3] = 3; // 长度为4... int max = 0; for (int i = 4; i <= length; i++) { max = 0; for (int j = 1; j <= i / 2; j++) { int product = products[j] * products[i - j]; max = max > product ? max : product; products[i] = max; } } max = products[length]; return max; } // 贪婪算法 public static int maxProductAfterCutting2(int length) { if (length < 2) return 0; if (length == 2) return 1; if (length == 3) return 2; // 尽可能剪3 int timesOf3 = length / 3; // 如果==1的话, 我就变为最后剩4 ,然后变2x2 if (length - timesOf3 * 3 == 1) timesOf3 -= 1; int timeOfs2 = (length - timesOf3 * 3) / 2; return (int)(Math.pow(3, timesOf3)) * (int)(Math.pow(2, timeOfs2)); } } <file_sep>## 引言 **JVM - 类加载机制** ## 类的生命周期 其中类加载的过程包括了`加载`、`验证`、`准备`、`解析`、`初始化`五个阶段。在这五个阶段中,`加载`、`验证`、`准备`和`初始化`这四个阶段发生的顺序是确定的,*而`解析`阶段则不一定,它在某些情况下可以在初始化阶段之后开始,这是为了支持Java语言的运行时绑定(也成为动态绑定或晚期绑定)*。另外注意这里的几个阶段是按顺序开始,而不是按顺序进行或完成,因为这些阶段通常都是互相交叉地混合进行的,通常在一个阶段执行的过程中调用或激活另一个阶段。 <!-- more --> ![](https://www.pdai.tech/_images/jvm/java_jvm_classload_2.png) ## 类的加载:查找并加载类的二进制数据 加载时类加载过程的第一个阶段,在加载阶段,虚拟机需要完成以下三件事情: - 通过一个类的全限定名来获取其定义的二进制字节流。 - 将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构。 - 在Java堆中生成一个代表这个类的java.lang.Class对象,作为对方法区中这些数据的访问入口。 ![](https://www.pdai.tech/_images/jvm/java_jvm_classload_1.png)相对于类加载的其他阶段而言,*加载阶段(准确地说,是加载阶段获取类的二进制字节流的动作)是可控性最强的阶段*,因为开发人员既可以使用系统提供的类加载器来完成加载,也可以自定义自己的类加载器来完成加载。 加载阶段完成后,虚拟机外部的 二进制字节流就按照虚拟机所需的格式存储在方法区之中,而且在Java堆中也创建一个`java.lang.Class`类的对象,这样便可以通过该对象访问方法区中的这些数据。 类加载器并不需要等到某个类被“首次主动使用”时再加载它,JVM规范允许类加载器在预料某个类将要被使用时就预先加载它,如果在预先加载的过程中遇到了.class文件缺失或存在错误,类加载器必须在程序首次主动使用该类时才报告错误(LinkageError错误)如果这个类一直没有被程序主动使用,那么类加载器就不会报告错误。 加载.class文件的方式 - 从本地系统中直接加载 - 通过网络下载.class文件 - 从zip,jar等归档文件中加载.class文件 - 从专有数据库中提取.class文件 - 将Java源文件动态编译为你.class文件 ### 验证:确保被加载的类的正确性 验证是连接阶段的第一步,这一阶段的目的是为了确保Class文件的字节流中包含的信息符合当前虚拟机的要求,并且不会危害虚拟机自身的安全。验证阶段大致会完成4个阶段的检验动作: - `文件格式验证`:验证字节流是否符合Class文件格式的规范;例如:是否以`0xCAFEBABE`开头、主次版本号是否在当前虚拟机的处理范围之内、常量池中的常量是否有不被支持的类型。 - `元数据验证`:对字节码描述的信息进行语义分析(注意:对比`javac`编译阶段的语义分析),以保证其描述的信息符合Java语言规范的要求;例如:这个类是否有父类,除了`java.lang.Object`之外。 - `字节码验证`:通过数据流和控制流分析,确定程序语义是合法的、符合逻辑的。 - `符号引用验证`:确保解析动作能正确执行。 验证阶段是非常重要的,但不是必须的,它对程序运行期没有影响,*如果所引用的类经过反复验证,那么可以考虑采用`-Xverifynone`参数来关闭大部分的类验证措施,以缩短虚拟机类加载的时间。* ### 准备:为类的静态变量分配内存,并将其初始化为默认值 准备阶段是正式为类变量分配内存并设置类变量初始值的阶段,**这些内存都将在方法区中分配**。对于该阶段有以下几点需要注意: - 这时候进行内存分配的仅包括类变量(`static`),而不包括实例变量,实例变量会在对象实例化时随着对象一块分配在Java堆中。 - 这里所设置的初始值通常情况下是数据类型默认的零值(如`0`、`0L`、`null`、`false`等),而不是被在Java代码中被显式地赋予的值。 假设一个类变量的定义为:`public static int value = 3`;那么变量value在准备阶段过后的初始值为`0`,而不是`3`,因为这时候尚未开始执行任何Java方法,而把value赋值为3的`put static`指令是在程序编译后,存放于类构造器`()`方法之中的,所以把value赋值为3的动作将在初始化阶段才会执行。 - 对基本数据类型来说,对于类变量(static)和全局变量,如果不显式地对其赋值而直接使用,则系统会为其赋予默认的零值,而对于局部变量来说,在使用前必须显式地为其赋值,否则编译时不通过。 - 对于同时被`static`和`final`修饰的常量,必须在声明的时候就为其显式地赋值,否则编译时不通过;而只被final修饰的常量则既可以在声明时显式地为其赋值,也可以在类初始化时显式地为其赋值,总之,在使用前必须为其显式地赋值,系统不会为其赋予默认零值。 - 对于引用数据类型`reference`来说,如数组引用、对象引用等,如果没有对其进行显式地赋值而直接使用,系统都会为其赋予默认的零值,即`null`。 - 如果在数组初始化时没有对数组中的各元素赋值,那么其中的元素将根据对应的数据类型而被赋予默认的零值。 - 如果类字段的字段属性表中存在ConstantValue属性,即同时被final和static修饰,那么在准备阶段变量value就会被初始化为ConstValue属性所指定的值。假设上面的类变量value被定义为:`public static final int value = 3;`编译时Javac将会为value生成ConstantValue属性,在准备阶段虚拟机就会根据ConstantValue的设置将value赋值为3。我们可以理解为`static final`常量在编译期就将其结果放入了调用它的类的常量池中 ### 解析:把类中的符号引用转换为直接引用 解析阶段是虚拟机将常量池内的符号引用替换为直接引用的过程,解析动作主要针对`类`或`接口`、`字段`、`类方法`、`接口方法`、`方法类型`、`方法句柄`和`调用点`限定符7类符号引用进行。符号引用就是一组符号来描述目标,可以是任何字面量。 `直接引用`就是直接指向目标的指针、相对偏移量或一个间接定位到目标的句柄。 ### 初始化 初始化,为类的静态变量赋予正确的初始值,JVM负责对类进行初始化,主要对类变量进行初始化。在Java中对类变量进行初始值设定有两种方式: - 声明类变量是指定初始值 - 使用静态代码块为类变量指定初始值 #### JVM初始化步骤 - 假如这个类还没有被加载和连接,则程序先加载并连接该类 - 假如该类的直接父类还没有被初始化,则先初始化其直接父类 - 假如类中有初始化语句,则系统依次执行这些初始化语句 #### 类初始化时机 只有当对类的主动使用的时候才会导致类的初始化,类的主动使用包括以下六种: - 创建类的实例,也就是new的方式 - 访问某个类或接口的静态变量,或者对该静态变量赋值 - 调用类的静态方法 - 反射 - 初始化某个类的子类,则其父类也会被初始化 - Java虚拟机启动时被标明为启动类的类,直接使用java.exe命令来运行某个主类 ### 使用 类访问方法区内的数据结构的接口, 对象是Heap区的数据。 ### 卸载 **Java虚拟机将结束生命周期的几种情况** - 执行了System.exit()方法 - 程序正常执行结束 - 程序在执行过程中遇到了异常或错误而异常终止 - 由于操作系统出现错误而导致Java虚拟机进程终止 ## 类加载器,JVM类加载机制 ### 类加载器的层次 ![](https://www.pdai.tech/_images/jvm/java_jvm_classload_3.png) 这里父类加载器并不是通过继承关系来实现的,而是采用组合实现的。 站在Java虚拟机的角度来讲,只存在两种不同的类加载器:启动类加载器:它使用C++实现(这里仅限于`Hotspot`,也就是JDK1.5之后默认的虚拟机,有很多其他的虚拟机是用Java语言实现的),是虚拟机自身的一部分;所有其他的类加载器:这些类加载器都由Java语言实现,独立于虚拟机之外,并且全部继承自抽象类`java.lang.ClassLoader`,这些类加载器需要由启动类加载器加载到内存中之后才能去加载其他的类。 ### 站在Java开发人员,类加载器可以大致划分为以下三类 `启动类加载器`:Bootstrap ClassLoader,负责加载存放在JDK\jre\lib(JDK代表JDK的安装目录,下同)下,或被-Xbootclasspath参数指定的路径中的,并且能被虚拟机识别的类库(如rt.jar,所有的java.*开头的类均被Bootstrap ClassLoader加载)。启动类加载器是无法被Java程序直接引用的。 `扩展类加载器`:Extension ClassLoader,该加载器由`sun.misc.Launcher$ExtClassLoader`实现,它负责加载JDK\jre\lib\ext目录中,或者由java.ext.dirs系统变量指定的路径中的所有类库(如javax.*开头的类),开发者可以直接使用扩展类加载器。 `应用程序类加载器`:Application ClassLoader,该类加载器由`sun.misc.Launcher$AppClassLoader`来实现,它负责加载用户类路径(ClassPath)所指定的类,开发者可以直接使用该类加载器,如果应用程序中没有自定义过自己的类加载器,一般情况下这个就是程序中默认的类加载器。 ### 类的加载 - 命令行启动应用时候由JVM初始化加载 - 通过Class.forName()方法动态加载 - 通过ClassLoader.loadClass()方法动态加载 ### JVM类加载机制 - `全盘负责`,当一个类加载器负责加载某个Class时,该Class所依赖的和引用的其他Class也将由该类加载器负责载入,除非显示使用另外一个类加载器来载入 - `父类委托`,先让父类加载器试图加载该类,只有在父类加载器无法加载该类时才尝试从自己的类路径中加载该类 - `缓存机制`,缓存机制将会保证所有加载过的Class都会被缓存,当程序中需要使用某个Class时,类加载器先从缓存区寻找该Class,只有缓存区不存在,系统才会读取该类对应的二进制数据,并将其转换成Class对象,存入缓存区。这就是为什么修改了Class后,必须重启JVM,程序的修改才会生效 - `双亲委派机制`, 如果一个类加载器收到了类加载的请求,它首先不会自己去尝试加载这个类,而是把请求委托给父加载器去完成,依次向上,因此,所有的类加载请求最终都应该被传递到顶层的启动类加载器中,只有当父加载器在它的搜索范围中没有找到所需的类时,即无法完成该加载,子加载器才会尝试自己去加载该类。 - 当AppClassLoader加载一个class时,它首先不会自己去尝试加载这个类,而是把类加载请求委派给父类加载器ExtClassLoader去完成。 - 当ExtClassLoader加载一个class时,它首先也不会自己去尝试加载这个类,而是把类加载请求委派给BootStrapClassLoader去完成。 - 如果BootStrapClassLoader加载失败(例如在$JAVA_HOME/jre/lib里未查找到该class),会使用ExtClassLoader来尝试加载; - 若ExtClassLoader也加载失败,则会使用AppClassLoader来加载,如果AppClassLoader也加载失败,则会报出异常ClassNotFoundException。 ```java public Class<?> loadClass(String name)throws ClassNotFoundException { return loadClass(name, false); } protected synchronized Class<?> loadClass(String name, boolean resolve)throws ClassNotFoundException { // 首先判断该类型是否已经被加载 Class c = findLoadedClass(name); if (c == null) { //如果没有被加载,就委托给父类加载或者委派给启动类加载器加载 try { if (parent != null) { //如果存在父类加载器,就委派给父类加载器加载 c = parent.loadClass(name, false); } else { //如果不存在父类加载器,就检查是否是由启动类加载器加载的类,通过调用本地方法native Class findBootstrapClass(String name) c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { // 如果父类加载器和启动类加载器都不能完成加载任务,才调用自身的加载功能 c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } ``` - **双亲委派优势** - 系统类防止内存中出现多份同样的字节码 - 保证Java程序安全稳定运行 ### 自定义类加载器 通常情况下,我们都是直接使用系统类加载器。但是,有的时候,我们也需要自定义类加载器。比如应用是通过网络来传输 Java 类的字节码,为保证安全性,这些字节码经过了加密处理,这时系统类加载器就无法对其进行加载,这样则需要自定义类加载器来实现。自定义类加载器一般都是继承自 ClassLoader 类,从上面对 loadClass 方法来分析来看,我们只需要重写 findClass 方法即可。 注意: - 这里传递的文件名需要是类的全限定性名称,即`com.pdai.jvm.classloader.Test2`格式的,因为 defineClass 方法是按这种格式进行处理的。 - 最好不要重写loadClass方法,因为这样容易破坏双亲委托模式。 - 这类Test 类本身可以被 AppClassLoader 类加载,因此我们不能把com/pdai/jvm/classloader/Test2.class 放在类路径下。否则,由于双亲委托机制的存在,会直接导致该类由 AppClassLoader 加载,而不会通过我们自定义类加载器来加载。<file_sep>- [类文件结构]() - [Class文件结构都有哪些?举点例子](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E6%96%87%E4%BB%B6%E7%BB%93%E6%9E%84.md#class%E6%96%87%E4%BB%B6%E7%BB%93%E6%9E%84%E6%80%BB%E7%BB%93) - [聊一聊对象头?](https://www.cnblogs.com/LemonFive/p/11246086.html) - [类加载过程]() - [加载](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B.md#%E5%8A%A0%E8%BD%BD) - [连接]() - [验证](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B.md#%E9%AA%8C%E8%AF%81) - [准备](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B.md#%E5%87%86%E5%A4%87) - [解析](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B.md#%E8%A7%A3%E6%9E%90) - [初始化](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B.md#%E5%88%9D%E5%A7%8B%E5%8C%96) - [类加载器都有哪些?](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8.md#%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8%E6%80%BB%E7%BB%93) - [聊一聊双亲委派机制](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E5%99%A8.md#%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE%E6%A8%A1%E5%9E%8B) - [JVM里的符号引用如何存储?](https://www.zhihu.com/question/30300585) - [JVM内存模型]() - [聊一聊JVM内存模型](/Jvm/Java面经-内存模型.md) - [堆的空间基本结构](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E6%8F%AD%E5%BC%80jvm%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E4%B8%8E%E5%9B%9E%E6%94%B6%E7%9A%84%E7%A5%9E%E7%A7%98%E9%9D%A2%E7%BA%B1) - [请你谈谈对OOM的认识](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/Java%E9%9D%A2%E7%BB%8F-%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B.md#%E8%AF%B7%E4%BD%A0%E8%B0%88%E8%B0%88%E5%AF%B9oom%E7%9A%84%E8%AE%A4%E8%AF%86) - [如何判断对象已经死亡?都有哪些方法?](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E5%AF%B9%E8%B1%A1%E5%B7%B2%E7%BB%8F%E6%AD%BB%E4%BA%A1) - [四大引用是什么?区别是什么?](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8) - [聊一聊垃圾收集算法?](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E7%AE%97%E6%B3%95) - [聊一聊垃圾收集器](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8) - [如何选择垃圾回收器](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6.md#%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9%E5%9E%83%E5%9C%BE%E9%80%89%E6%8B%A9%E5%99%A8) - [Java对象创建过程]() - [谈一谈创建过程](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA.md#%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%9B%E5%BB%BA) - [内存布局是怎么样的?](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA.md#%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80) - [对象的访问定位](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/JVM-%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA.md#%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AE%BF%E9%97%AE%E5%AE%9A%E4%BD%8D) - [JVM参数]() - [如何盘点查看JVM系统默认值](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/Java%E9%9D%A2%E7%BB%8F-JVM%E8%B0%83%E4%BC%98%E5%8F%82%E6%95%B0.md#%E5%A6%82%E4%BD%95%E7%9B%98%E7%82%B9%E6%9F%A5%E7%9C%8Bjvm%E7%B3%BB%E7%BB%9F%E9%BB%98%E8%AE%A4%E5%80%BC) - [你平时工作用过的JVM常用基本配置参数有哪些](https://github.com/DreamCats/JavaBooks/blob/master/Jvm/Java%E9%9D%A2%E7%BB%8F-JVM%E8%B0%83%E4%BC%98%E5%8F%82%E6%95%B0.md#%E4%BD%A0%E5%B9%B3%E6%97%B6%E5%B7%A5%E4%BD%9C%E7%94%A8%E8%BF%87%E7%9A%84jvm%E5%B8%B8%E7%94%A8%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE%E5%8F%82%E6%95%B0%E6%9C%89%E5%93%AA%E4%BA%9B) <file_sep>package web; /** * @program LeetNiu * @description: 数组中的逆序对 * @author: mf * @create: 2020/01/15 09:45 */ /** * 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。 * 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 */ public class T35 { private Integer count = 0; public int InversePairs(int [] array) { if (array == null || array.length == 0) return 0; mergeSort(array, 0, array.length - 1); return (count % 1000000007); } private void mergeSort(int[] array, int left, int right) { if (left < right) { int mid = (left + right) >> 1; mergeSort(array, left ,mid); mergeSort(array, mid + 1, right); merge(array, left, mid, right); } } private void merge(int[] array, int left, int mid, int right) { int[] help = new int[right - left + 1]; int i = 0; int p1 = left; int p2 = mid + 1; while(p1 <= mid && p2 <= right) { if(array[p1] > array[p2]) { help[i++] = array[p2++]; count += mid - p1 + 1; } else { help[i++] = array[p1++]; } } while(p1 <= mid) { help[i++] = array[p1++]; } while(p2 <= right) { help[i++] = array[p2++]; } for(int j = 0; j < help.length; j++) { array[left + j] = help[j]; } } } <file_sep>## 专题总结 **个人感觉以下熟能生巧就可以了,毕竟...** ## 链表 - [面试题06-从尾到头打印链表](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035) -->[题解](/src/subject/linked/T1.java) - [面试题22-链表中倒数第k个结点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) -->[题解](/src/subject/linked/T2.java) - [面试题24-反转链表](https://leetcode-cn.com/problems/reverse-linked-list/) -->[题解](/src/subject/linked/T3.java) - [面试题25-合并两个排序的链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/) -->[题解](/src/subject/linked/T4.java) - [面试题35-复杂链表的复制](https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/) -->[题解](./src/subject/linked/T5.java) - [面试题52-两个链表的第一个公共节点](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/) -->[题解](./src/subject/linked/T6.java) - [面试题18-删除链表的节点](https://leetcode-cn.com/problems/delete-node-in-a-linked-list/) -->[题解](./src/subject/linked/T7.java) ## 树 - 面试题07-重建二叉树 - 面试题26-树的子结构 - 面试题27-二叉树的镜像 - 面试题32-1 -从上往下打印二叉树 - 面试题33-二叉搜索树的后序遍历序列 - 面试题34-二叉树中和为某一值的路径 - 面试题36-二叉搜索树与双向链表 - 面试题55-1-二叉树的深度 - 面试题55-2-平衡二叉树 - 面试题28-对称的二叉树 - 面试题37-序列化二叉树 - 面试题54-二叉搜索树的第k大节点 ## Stack & Queue - 面试题09-用两个栈实现队列 - 面试题30-包含min函数的栈 - 面试题31-栈的压入、弹出序列 - 面试题58-1-翻转单词顺序 - 面试题59-1-滑动窗口的最大值 ## Heap - 面试题40-最小的K个数 ## 斐波那契数列 - 面试题10-1-斐波拉契数列 - 面试题10-2-青蛙跳台阶问题 ## 搜索算法 - 面试题04-二维数组中的查找 - 面试题11-旋转数组的最小数字(二分查找) - 面试题56-1-数组中数字出现的次数(二分查找) ## 动态规划 ## 位运算<file_sep>/** * @program JavaBooks * @description: 最大子序和 * @author: mf * @create: 2020/04/11 19:26 */ package subject.dp; /** * 输入: [-2,1,-3,4,-1,2,1,-5,4], * 输出: 6 * 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 */ public class T0 { public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) return 0; int max = nums[0]; int ans = nums[0]; for (int i = 1; i < nums.length; i++) { max = Math.max(max + nums[i], nums[i]); ans = Math.max(max, ans); } return ans; } } <file_sep>## 剑指offer(书的顺序) - [2、单例模式](/SwordOffer/src/books/T2.java) - [3、数组中重复的数字](/SwordOffer/src/books/T3.java) - [4、二维数组中的查找](/SwordOffer/src/books/T4.java) - [5、替换空格](/SwordOffer/src/books/T5.java) - [6、从尾到头打印链表](/SwordOffer/src/books/T6.java) - [7、重建二叉树](/SwordOffer/src/books/T7.java) - [9、用两个栈实现一个队列](/SwordOffer/src/books/T9.java) - [10、斐波那契数列 & 青蛙跳台阶](/SwordOffer/src/books/T10.java) - [11、旋转数组的最小数字](/SwordOffer/src/books/T11.java) - [12、矩阵中的路径](/SwordOffer/src/books/T12.java) - [13、机器人的运动范围](/SwordOffer/src/books/T13.java) - [14、剪绳子](/SwordOffer/src/books/T14.java) - [15、二进制中1的个数](/SwordOffer/src/books/T15.java) - [16、数值的整数次方](/SwordOffer/src/books/T16.java) - [17、打印从1到最大的n位数](/SwordOffer/src/books/T17.java) - [18、删除链表中的节点O(1)](/SwordOffer/src/books/T18.java) - [19、正则表达式](/SwordOffer/src/books/T19.java) - [20、表示数值的字符串](/SwordOffer/src/books/T20.java) - [21、调整数组顺序使奇数位于偶数前面](/SwordOffer/src/books/T21.java) - [22、链表中倒数第k个节点](/SwordOffer/src/books/T22.java) - [23、链表中环的入口节点](/SwordOffer/src/books/T23.java) - [24、反转链表](/SwordOffer/src/books/T24.java) - [25、合并两个排序的链表](/SwordOffer/src/books/T25.java) - [26、树的子结构](/SwordOffer/src/books/T26.java) - [27、树的镜像](/SwordOffer/src/books/T27.java) - [28、对称的二叉树](/SwordOffer/src/books/T28.java) - [29、顺时针打印矩阵](/SwordOffer/src/books/T29.java) - [30、包含min函数的栈](/SwordOffer/src/books/T30.java) - [31、栈的压入、弹出序列](/SwordOffer/src/books/T31.java) - [32、从上到下打印二叉树](/SwordOffer/src/books/T32.java) - [33、二叉搜索树的后序遍历序列](/SwordOffer/src/books/T33.java) - [34、二叉树中和为某一值的路径](/SwordOffer/src/books/T34.java) - [35、复杂链表的复制](/SwordOffer/src/books/T35.java) - [36、二叉搜索树与双向链表](/SwordOffer/src/books/T36.java) - [37、序列化二叉树](/SwordOffer/src/books/T37.java) - [38、字符串的排列](/SwordOffer/src/books/T38.java) - [39、数组中出现次数超过一半的数字](/SwordOffer/src/books/T39.java) - [40、最小的k个数](/SwordOffer/src/books/T40.java) - [41、数据流中的中位数](/SwordOffer/src/books/T41.java) - [42、连续子数组的最大和](/SwordOffer/src/books/T42.java) - [43、1~n整数中1出现的次数](/SwordOffer/src/books/T43.java) - [44、数字序列中某一位的数字](/SwordOffer/src/books/T44.java) - [45、把数组排成最小的数](/SwordOffer/src/books/T45.java) - [46、把数字翻译成字符串](/SwordOffer/src/books/T46.java) - [47、礼物的最大价值](/SwordOffer/src/books/T47.java) - [48、最长不含重复字符的子字符串](/SwordOffer/src/books/T48.java) - [49、丑数](/SwordOffer/src/books/T49.java) - [50、第一个只出现一次的字符](/SwordOffer/src/books/T50.java) - [51、数组中的逆序对](/SwordOffer/src/books/T51.java) - [52、两个链表的第一个公共节点](/SwordOffer/src/books/T52.java) - [53、在排序数组中查找数字](/SwordOffer/src/books/T53.java) - [54、二叉搜索树的第K大节点](/SwordOffer/src/books/T54.java) - [55、二叉树的深度](/SwordOffer/src/books/T55.java) - [56、数组中只出现一次的两个数字](/SwordOffer/src/books/T56.java) - [57、和为s的数字](/SwordOffer/src/books/T57.java) - [58、翻转字符串](/SwordOffer/src/books/T58.java) - [59、滑动窗口的最大值](/SwordOffer/src/books/T59.java) - [60、n个骰子的点数](/SwordOffer/src/books/T60.java) - [61、扑克牌中的顺子](/SwordOffer/src/books/T61.java) - [62、圆圈中最后剩下的数字](/SwordOffer/src/books/T62.java) - [63、股票的最大利润](/SwordOffer/src/books/T63.java) - [64、求1+2+...+n](/SwordOffer/src/books/T64.java) - [65、不用加减乘除做加法](/SwordOffer/src/books/T65.java) - [66、构建乘积数组](/SwordOffer/src/books/T66.java) ## 牛客网的顺序 | 序号 | 题目 | 语言 | 类型 | | :--------------------------------------: | :--------------------------: | ---------------------------------------- | ---------------------------------------- | | 1 | [二维数组中的查找](https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) | [java](/SwordOffer/src/web/T1.java) | 数组 | | 2 | [替换空格](https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) | [java](/SwordOffer/src/web/T2.java) | 字符串 | | 3 | [从尾到头打印链表](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T3.java) | 链表 | | 4 | [重建二叉树](https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T4.java) | 树 | | 5 | [用两个栈实现一个队列](https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T5.java) | 栈队列 | | 6 | [旋转数组的最小数字](https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba?tpId=13&tqId=11159&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T6.java) | 查找 | | 7 | [斐波那契数列](https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T7.java) | 递归 | | 8 | [跳台阶](https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&tqId=11161&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T8.java) | 递归 | | 9 | [变态跳台阶](https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387?tpId=13&tqId=11162&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T9.java)) | 贪心 | | 10 | [矩形覆盖](https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&tqId=11163&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T10.java) | 递归 | | 11 | [二进制1的个数](https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T11.java) | 二进制 | | 12 | [数值的整数次方](https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T12.java) |数学 | | 13 | [调整数组顺序使奇数位于偶数前面](https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&tqId=11166&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T13.java) | 数组 | | 14 | [链表中倒数第k个结点](https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T14.java) | 链表 | | 15 | [反转链表](https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T15.java) | 链表 | | 16 | [合并两个排序的链表](https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T16.java) | 链表 | | 17 | [树的子结构](https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T17.java) | 树 | | 18 | [二叉树的镜像](https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T18.java) | 树 | | 19 | [顺时针打印矩阵](/https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T19.java) | 数组 | | 20 | [包含min函数的栈](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T20.java) | 栈 | | 21 | [栈的压入、弹出序列](https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T21.java) | 栈 | | 22 | [从上往下打印二叉树](https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T22.java) | 队列/树 | | 23 | [二叉搜索树的后序遍历序列](https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T23.java) | 树 | | 24 | [二叉树中和为某一值的路径](https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T24.java) | 树 | | 25 | [复杂链表的复制](https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T25.java) | 链表 | | 26 | [二叉搜索树与双向链表](https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T26.java) | 链表/树 | | 27 | [字符串的排列](https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T27.java) | 字符串 | | 28 | [数组中出现次数超过一半的数字](https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T28.java) | 数组 | | 29 | [最小的k个数](https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T29.java) | 数组 | | 30 | [连续子数组的最大和](https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484?tpId=13&tqId=11183&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T30.java) | 数组 | | 31 | [整数中1出现的次数](https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&tqId=11184&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T31.java) | 查找 | | 32 | [把数组排成最小的数](https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T32.java) | 数组 | | 33 | [丑数](https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=13&tqId=11186&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T33.java) | 穷举 | | 34 | [第一个只出现一次的字符](https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T34.java) | | | 35 | [数组中的逆序对](https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T35.java) | 数组 | | 36 | [两个链表的第一个公共结点](https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T36.java) | 链表 | | 37 | [数字在排序数组中出现的次数](https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tqId=11190&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T37.java) | 数组 | | 38 | [二叉树的深度](https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T38.java) | 树 | | 39 | [平衡二叉树](https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T39.java) | 树 | | 40 | [数组中只出现一次的数字](https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T40.java) | 数组 | | 41 | [和为S的连续正数序列](https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T41.java) | 数组 | | 42 | [和为S的两个数字](https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T42.java) | 数组 | | 43 | [左旋转字符串](https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tqId=11196&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T43.java) | 字符串 | | 44 | [翻转单词顺序列](https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T44.java) | 字符串 | | 45 | [扑克牌顺序](https://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4?tpId=13&tqId=11198&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T45.java) | 字符串 | | 46 | [孩子们的游戏](https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11199&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T46.java) | 数学 | | 47 | [求1+2+3+...+n](https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&tqId=11200&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T47.java) | 进制转换 | | 48 | [不用加减乘除做加法](https://www.nowcoder.com/practice/59ac416b4b944300b617d4f7f111b215?tpId=13&tqId=11201&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T48.java) | 进制转换 | | 49 | [把字符串转成整数](https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T49.java) | 字符串 | | 50 | [数组中重复的数字](https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T50.java) | 数组 | | 51 | [构建乘积数组](https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T51.java) | 数组 | | 52 | [正则表达式匹配](https://www.nowcoder.com/practice/45327ae22b7b413ea21df13ee7d6429c?tpId=13&tqId=11205&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T52.java) | 字符串 | | 53 | [表示数值的字符串](https://www.nowcoder.com/practice/6f8c901d091949a5837e24bb82a731f2?tpId=13&tqId=11206&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T53.java) | 字符串 | | 54 | [字符流中第一个不重复的字符](https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T54.java) | 字符串 | | 55 | [链表中环的入口结点](https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T55.java) | 链表 | | 56 | [删除链表中重复的结点](https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T56.java) | 链表 | | 57 | [二叉树的下一个结点](https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?tpId=13&tqId=11210&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T57.java) | 树 | | 58 | [对称的二叉树](https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb?tpId=13&tqId=11211&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T58.java) | 树 | | 59 | [按之字形顺序打印二叉树](https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&tqId=11212&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T59.java) | 栈树 | | 60 | [把二叉树打印多行](https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T60.java) | 队列树 | | 61 | [序列化二叉树](nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&tqId=11214&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T61.java) | 队列树 | | 62 | [二叉搜索树的第k个结点](https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T62.java) | 栈树 | | 63 | [数据流中的中位数](https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&tqId=11216&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T63.java) | 进制转换 | | 64 | [滑动窗口的最大值](nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T64.java) | 数组 | | 65 | [矩阵中的路径](https://www.nowcoder.com/practice/c61c6999eecb4b8f88a98f66b273a3cc?tpId=13&tqId=11218&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T65.java) | 数组 | | 66 | [机器人的运动范围](https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T66.java) | 数组 | | 67 | [剪绳子](https://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8?tpId=13&tqId=33257&tPage=4&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) | [java](/SwordOffer/src/web/T67.java) | 贪心 | <file_sep>package web; /** * @program LeetNiu * @description: 矩阵中的路径 * @author: mf * @create: 2020/01/17 23:43 */ /** * 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 * 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。 * 如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 * 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径, * 但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。 */ public class T65 { public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { if (null == matrix || matrix.length == 0 || null == str || str.length == 0 || matrix.length != rows * cols || rows <= 0 || cols <= 0){ return false; } boolean[] visited = new boolean[rows * cols]; int[] pathLength = {0}; for (int i = 0; i <= rows - 1; i++){ for (int j = 0; j <= cols - 1; j++){ if (hasPathCore(matrix, rows, cols, str, i, j, visited, pathLength)) { return true; } } } return false; } public boolean hasPathCore(char[] matrix, int rows, int cols, char[] str,int row,int col, boolean[] visited,int[] pathLength) { boolean flag = false; if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row * cols + col] && matrix[row * cols + col] == str[pathLength[0]]) { pathLength[0]++; visited[row * cols + col] = true; if (pathLength[0] == str.length) { return true; } flag = hasPathCore(matrix, rows, cols, str, row, col + 1, visited, pathLength) || hasPathCore(matrix, rows, cols, str, row + 1, col, visited, pathLength) || hasPathCore(matrix, rows, cols, str, row, col - 1, visited, pathLength) || hasPathCore(matrix, rows, cols, str, row - 1, col, visited, pathLength); if (!flag) { pathLength[0]--; visited[row * cols + col] = false; } } return flag; } } <file_sep>## 引言 **线性表-位运算** ## 位元算的相关题目 <!-- more --> ### [136. 只出现一次的数字](https://leetcode-cn.com/problems/single-number/) 分析:异或 ```java class Solution { public int singleNumber(int[] nums) { if(nums.length == 1) return nums[0]; int ans = nums[0]; for(int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } } ``` #### [190. 颠倒二进制位](https://leetcode-cn.com/problems/reverse-bits/) ```java public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int a = 0; for (int i = 0; i <= 31; i++) { a = a + ((1 & (n >> i)) << (31 - i)); } return a; } } ``` ### [191. 位1的个数](https://leetcode-cn.com/problems/number-of-1-bits/) ```bash 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 ``` ```java public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ans = 0; while(n != 0) { n &= n - 1; ans++; } return ans; } } ``` ### [268. 缺失数字](https://leetcode-cn.com/problems/missing-number/) 分析:异或 ```java class Solution { public int missingNumber(int[] nums) { int ans = nums.length; for(int i = 0; i < nums.length; i++) { ans ^= nums[i]; ans ^= i; } return ans; } } ``` ### [371. 两整数之和](https://leetcode-cn.com/problems/sum-of-two-integers/) 分析:异或和与 ```java class Solution { public int getSum(int a, int b) { return b == 0 ? a : getSum(a^b, (a&b) << 1); } } ``` <file_sep>## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## 基本面试问题 - **介绍下 Java 内存区域(运行时数据区)** - **Java 对象的创建过程(五步,建议能默写出来并且要知道每一步虚拟机做了什么)** - **对象的访问定位的两种方式(句柄和直接指针两种方式)** - **String 类和常量池** - **8 种基本类型的包装类和常量池** ## 运行时数据区域 Java 虚拟机在执行 Java 程序的过程中会把它管理的内存划分成若干个不同的数据区域。JDK. 1.8 和之前的版本略有不同,下面会介绍到。 **JDK1.8之前** ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3/JVM%E8%BF%90%E8%A1%8C%E6%97%B6%E6%95%B0%E6%8D%AE%E5%8C%BA%E5%9F%9F.png) **JDK1.8之后** ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3Java%E8%BF%90%E8%A1%8C%E6%97%B6%E6%95%B0%E6%8D%AE%E5%8C%BA%E5%9F%9FJDK1.8.png) **线程私有的:** - 程序计数器 - 虚拟机栈 - 本地方法栈 **线程共享的:** - 堆 - 方法区 - 直接内存 (非运行时数据区的一部分) ### 程序计数器 程序计数器是一块较小的内存空间,可以看作是当前线程所执行的字节码的行号指示器。**字节码解释器工作时通过改变这个计数器的值来选取下一条需要执行的字节码指令,分支、循环、跳转、异常处理、线程恢复等功能都需要依赖这个计数器来完成。** 另外,**为了线程切换后能恢复到正确的执行位置,每条线程都需要有一个独立的程序计数器,各线程之间计数器互不影响,独立存储,我们称这类内存区域为“线程私有”的内存。** **从上面的介绍中我们知道程序计数器主要有两个作用:** 1. 字节码解释器通过改变程序计数器来依次读取指令,从而实现代码的流程控制,如:顺序执行、选择、循环、异常处理。 2. 在多线程的情况下,程序计数器用于记录当前线程执行的位置,从而当线程被切换回来的时候能够知道该线程上次运行到哪儿了。 **注意:程序计数器是唯一一个不会出现 OutOfMemoryError 的内存区域,它的生命周期随着线程的创建而创建,随着线程的结束而死亡。** ### Java虚拟机栈 **与程序计数器一样,Java 虚拟机栈也是线程私有的,它的生命周期和线程相同,描述的是 Java 方法执行的内存模型,每次方法调用的数据都是通过栈传递的。** **Java 内存可以粗糙的区分为堆内存(Heap)和栈内存 (Stack),其中栈就是现在说的虚拟机栈,或者说是虚拟机栈中局部变量表部分。** (实际上,Java 虚拟机栈是由一个个栈帧组成,而每个栈帧中都拥有:局部变量表、操作数栈、动态链接、方法出口信息。) **局部变量表主要存放了编译器可知的各种数据类型**(boolean、byte、char、short、int、float、long、double)、**对象引用**(reference 类型,它不同于对象本身,可能是一个指向对象起始地址的引用指针,也可能是指向一个代表对象的句柄或其他与此对象相关的位置)。 **Java 虚拟机栈会出现两种异常:StackOverFlowError 和 OutOfMemoryError。** - **StackOverFlowError:** 若 Java 虚拟机栈的内存大小不允许动态扩展,那么当线程请求栈的深度超过当前 Java 虚拟机栈的最大深度的时候,就抛出 StackOverFlowError 异常。 - **OutOfMemoryError:** 若 Java 虚拟机栈的内存大小允许动态扩展,且当线程请求栈时内存用完了,无法再动态扩展了,此时抛出 OutOfMemoryError 异常。 Java 虚拟机栈也是线程私有的,每个线程都有各自的 Java 虚拟机栈,而且随着线程的创建而创建,随着线程的死亡而死亡。 Java 栈可用类比数据结构中栈,Java 栈中保存的主要内容是栈帧,每一次函数调用都会有一个对应的栈帧被压入 Java 栈,每一个函数调用结束后,都会有一个栈帧被弹出。 Java 方法有两种返回方式: 1. return语句 2. 抛出异常。 ### 本地方法栈 和虚拟机栈所发挥的作用非常相似,区别是: **虚拟机栈为虚拟机执行 Java 方法 (也就是字节码)服务,而本地方法栈则为虚拟机使用到的 Native 方法服务。** 在 HotSpot 虚拟机中和 Java 虚拟机栈合二为一。 本地方法被执行的时候,在本地方法栈也会创建一个栈帧,用于存放该本地方法的局部变量表、操作数栈、动态链接、出口信息。 方法执行完毕后相应的栈帧也会出栈并释放内存空间,也会出现 StackOverFlowError 和 OutOfMemoryError 两种异常。 ### 堆 Java 虚拟机所管理的内存中最大的一块,Java 堆是所有线程共享的一块内存区域,在虚拟机启动时创建。**此内存区域的唯一目的就是存放对象实例,几乎所有的对象实例以及数组都在这里分配内存。** Java 堆是垃圾收集器管理的主要区域,因此也被称作**GC 堆(Garbage Collected Heap)**.从垃圾回收的角度,由于现在收集器基本都采用分代垃圾收集算法,所以 Java 堆还可以细分为:新生代和老年代:再细致一点有:Eden 空间、From Survivor、To Survivor 空间等。**进一步划分的目的是更好地回收内存,或者更快地分配内存。** ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3%E5%A0%86%E7%BB%93%E6%9E%84.png) 上图所示的 eden 区、s0 区、s1 区都属于新生代,tentired 区属于老年代。大部分情况,对象都会首先在 Eden 区域分配,在一次新生代垃圾回收后,如果对象还存活,则会进入 s0 或者 s1,并且对象的年龄还会加 1(Eden 区->Survivor 区后对象的初始年龄变为 1),当它的年龄增加到一定程度(默认为 15 岁),就会被晋升到老年代中。对象晋升到老年代的年龄阈值,可以通过参数 `-XX:MaxTenuringThreshold` 来设置。 ### 方法区 方法区与 Java 堆一样,是各个线程共享的内存区域,它用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。虽然 Java 虚拟机规范把方法区描述为堆的一个逻辑部分,但是它却有一个别名叫做 **Non-Heap(非堆)**,目的应该是与 Java 堆区分开来。 #### 方法区和永久代的关系 > 《Java 虚拟机规范》只是规定了有方法区这么个概念和它的作用,并没有规定如何去实现它。那么,在不同的 JVM 上方法区的实现肯定是不同的了。 **方法区和永久代的关系很像 Java 中接口和类的关系,类实现了接口,而永久代就是 HotSpot 虚拟机对虚拟机规范中方法区的一种实现方式。** 也就是说,永久代是 HotSpot 的概念,方法区是 Java 虚拟机规范中的定义,是一种规范,而永久代是一种实现,一个是标准一个是实现,其他的虚拟机实现并没有永久代这一说法。 JDK 1.8 之前永久代还没被彻底移除的时候通常通过下面这些参数来调节方法区大小 ``` -XX:PermSize=N //方法区 (永久代) 初始大小 -XX:MaxPermSize=N //方法区 (永久代) 最大大小,超过这个值将会抛出 OutOfMemoryError 异常:java.lang.OutOfMemoryError: PermGen ``` 相对而言,垃圾收集行为在这个区域是比较少出现的,但并非数据进入方法区后就“永久存在”了。 JDK 1.8 的时候,方法区(HotSpot 的永久代)被彻底移除了(JDK1.7 就已经开始了),取而代之是元空间,元空间使用的是直接内存。 下面是一些常用参数: ``` -XX:MetaspaceSize=N //设置 Metaspace 的初始(和最小大小) -XX:MaxMetaspaceSize=N //设置 Metaspace 的最大大小 ``` 与永久代很大的不同就是,如果不指定大小的话,随着更多类的创建,虚拟机会耗尽所有可用的系统内存。 #### 为什么要将永久代 (PermGen) 替换为元空间 (MetaSpace) 呢? 整个永久代有一个 JVM 本身设置固定大小上限,无法进行调整,而元空间使用的是直接内存,受本机可用内存的限制,并且永远不会得到 java.lang.OutOfMemoryError。你可以使用 `-XX:MaxMetaspaceSize` 标志设置最大元空间大小,默认值为 unlimited,这意味着它只受系统内存的限制。`-XX:MetaspaceSize` 调整标志定义元空间的初始大小如果未指定此标志,则 Metaspace 将根据运行时的应用程序需求动态地重新调整大小。 ### 运行时常量池 运行时常量池是方法区的一部分。Class 文件中除了有类的版本、字段、方法、接口等描述信息外,还有常量池信息(用于存放编译期生成的各种字面量和符号引用) 既然运行时常量池是方法区的一部分,自然受到方法区内存的限制,当常量池无法再申请到内存时会抛出 OutOfMemoryError 异常。 **JDK1.7 及之后版本的 JVM 已经将运行时常量池从方法区中移了出来,在 Java 堆(Heap)中开辟了一块区域存放运行时常量池。** ![参考-JavaGuide](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-14/26038433.jpg) ### 直接内存 **直接内存并不是虚拟机运行时数据区的一部分,也不是虚拟机规范中定义的内存区域,但是这部分内存也被频繁地使用。而且也可能导致 OutOfMemoryError 异常出现。** JDK1.4 中新加入的 **NIO(New Input/Output) 类**,引入了一种基于**通道(Channel)** 与**缓存区(Buffer)** 的 I/O 方式,它可以直接使用 Native 函数库直接分配堆外内存,然后通过一个存储在 Java 堆中的 DirectByteBuffer 对象作为这块内存的引用进行操作。这样就能在一些场景中显著提高性能,因为**避免了在 Java 堆和 Native 堆之间来回复制数据**。 本机直接内存的分配不会受到 Java 堆的限制,但是,既然是内存就会受到本机总内存大小以及处理器寻址空间的限制。 ## HotSpot虚拟机对象探秘 ### 对象的创建 大佬建议我们掌握每一步在做什么。 ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/Java%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%BF%87%E7%A8%8B.png) 1. 类加载检查,虚拟机遇到一条 new 指令时,首先将去检查这个指令的参数是否能在常量池中定位到这个类的符号引用,并且检查这个符号引用代表的类是否已被加载过、解析和初始化过。如果没有,那必须先执行相应的类加载过程。 2. 分配内存,在**类加载检查**通过后,接下来虚拟机将为新生对象**分配内存**。对象所需的内存大小在类加载完成后便可确定,为对象分配空间的任务等同于把一块确定大小的内存从 Java 堆中划分出来。**分配方式**有 **“指针碰撞”** 和 **“空闲列表”** 两种,**选择那种分配方式由 Java 堆是否规整决定,而 Java 堆是否规整又由所采用的垃圾收集器是否带有压缩整理功能决定**。 - **内存分配的两种方式:(补充内容,需要掌握)** - 选择以上两种方式中的哪一种,取决于 Java 堆内存是否规整。而 Java 堆内存是否规整,取决于 GC 收集器的算法是"标记-清除",还是"标记-整理"(也称作"标记-压缩"),值得注意的是,复制算法内存也是规整的 - ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F.png) - **内存分配并发问题(补充内容,需要掌握)** - 在创建对象的时候有一个很重要的问题,就是线程安全,因为在实际开发过程中,创建对象是很频繁的事情,作为虚拟机来说,必须要保证线程是安全的,通常来讲,虚拟机采用两种方式来保证线程安全: - **CAS+失败重试:** CAS 是乐观锁的一种实现方式。所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。**虚拟机采用 CAS 配上失败重试的方式保证更新操作的原子性。** - **TLAB:** 为每一个线程预先在 Eden 区分配一块儿内存,JVM 在给线程中的对象分配内存时,首先在 TLAB 分配,当对象大于 TLAB 中的剩余内存或 TLAB 的内存已用尽时,再采用上述的 CAS 进行内存分配 3. 初始化零值,内存分配完成后,虚拟机需要将分配到的内存空间都初始化为零值(不包括对象头),这一步操作保证了对象的实例字段在 Java 代码中可以不赋初始值就直接使用,程序能访问到这些字段的数据类型所对应的零值。 4. 设置对象头,初始化零值完成之后,**虚拟机要对对象进行必要的设置**,例如这个对象是那个类的实例、如何才能找到类的元数据信息、对象的哈希码、对象的 GC 分代年龄等信息。 **这些信息存放在对象头中。** 另外,根据虚拟机当前运行状态的不同,如是否启用偏向锁等,对象头会有不同的设置方式。 5. 执行init方法,在上面工作都完成之后,从虚拟机的视角来看,一个新的对象已经产生了,但从 Java 程序的视角来看,对象创建才刚开始,`` 方法还没有执行,所有的字段都还为零。所以一般来说,执行 new 指令之后会接着执行 `` 方法,把对象按照程序员的意愿进行初始化,这样一个真正可用的对象才算完全产生出来。 ### 对象的内存布局 在 Hotspot 虚拟机中,对象在内存中的布局可以分为 3 块区域:**对象头**、**实例数据**和**对齐填充**。 **Hotspot 虚拟机的对象头包括两部分信息**,**第一部分用于存储对象自身的自身运行时数据**(哈希码、GC 分代年龄、锁状态标志等等),**另一部分是类型指针**,即对象指向它的类元数据的指针,虚拟机通过这个指针来确定这个对象是那个类的实例。 **实例数据部分是对象真正存储的有效信息**,也是在程序中所定义的各种类型的字段内容。 **对齐填充部分不是必然存在的,也没有什么特别的含义,仅仅起占位作用。** 因为 Hotspot 虚拟机的自动内存管理系统要求对象起始地址必须是 8 字节的整数倍,换句话说就是对象的大小必须是 8 字节的整数倍。而对象头部分正好是 8 字节的倍数(1 倍或 2 倍),因此,当对象实例数据部分没有对齐时,就需要通过对齐填充来补全。 ### 对象的访问定位 建立对象就是为了使用对象,我们的 Java 程序通过栈上的 reference 数据来操作堆上的具体对象。对象的访问方式由虚拟机实现而定,目前主流的访问方式有**①使用句柄**和**②直接指针**两种: #### 使用句柄 如果使用句柄的话,那么 Java 堆中将会划分出一块内存来作为句柄池,reference 中存储的就是对象的句柄地址,而句柄中包含了对象实例数据与类型数据各自的具体地址信息; ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AE%BF%E9%97%AE%E5%AE%9A%E4%BD%8D-%E4%BD%BF%E7%94%A8%E5%8F%A5%E6%9F%84.png) #### 直接指针 如果使用直接指针访问,那么 Java 堆对象的布局中就必须考虑如何放置访问类型数据的相关信息,而 reference 中存储的直接就是对象的地址。 ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AE%BF%E9%97%AE%E5%AE%9A%E4%BD%8D-%E7%9B%B4%E6%8E%A5%E6%8C%87%E9%92%88.png) **这两种对象访问方式各有优势。使用句柄来访问的最大好处是 reference 中存储的是稳定的句柄地址,在对象被移动时只会改变句柄中的实例数据指针,而 reference 本身不需要修改。使用直接指针访问方式最大的好处就是速度快,它节省了一次指针定位的时间开销。** ## 重点补充内容 ### String类和常量池 **String 对象的两种创建方式:** ```java String str1 = "abcd";//先检查字符串常量池中有没有"abcd",如果字符串常量池中没有,则创建一个,然后 str1 指向字符串常量池中的对象,如果有,则直接将 str1 指向"abcd""; String str2 = new String("abcd");//堆中创建一个新的对象 String str3 = new String("abcd");//堆中创建一个新的对象 System.out.println(str1==str2);//false System.out.println(str2==str3);//false ``` 这两种不同的创建方法是有差别的。 - 第一种方式是在常量池中拿对象; - 第二种方式是直接在堆内存空间创建一个新的对象。 记住一点:**只要使用 new 方法,便需要创建新的对象。** ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3String-Pool-Java1-450x249.png) **String 类型的常量池比较特殊。它的主要使用方法有两种:** - 直接使用双引号声明出来的 String 对象会直接存储在常量池中。 - 如果不是用双引号声明的 String 对象,可以使用 String 提供的 intern 方法。String.intern() 是一个 Native 方法,它的作用是:如果运行时常量池中已经包含一个等于此 String 对象内容的字符串,则返回常量池中该字符串的引用;如果没有,JDK1.7之前(不包含1.7)的处理方式是在常量池中创建与此 String 内容相同的字符串,并返回常量池中创建的字符串的引用,JDK1.7以及之后的处理方式是在常量池中记录此字符串的引用,并返回该引用。 ```java String s1 = new String("计算机"); String s2 = s1.intern(); String s3 = "计算机"; System.out.println(s2);//计算机 System.out.println(s1 == s2);//false,因为一个是堆内存中的 String 对象一个是常量池中的 String 对象, System.out.println(s3 == s2);//true,因为两个都是常量池中的 String 对象 ``` **字符串拼接:** ```java String str1 = "str"; String str2 = "ing"; String str3 = "str" + "ing";//常量池中的对象 String str4 = str1 + str2; //在堆上创建的新的对象 String str5 = "string";//常量池中的对象 System.out.println(str3 == str4);//false System.out.println(str3 == str5);//true System.out.println(str4 == str5);//false ``` ![参考-JavaGuide](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8B%BC%E6%8E%A5.png) 尽量避免多个字符串拼接,因为这样会重新创建对象。如果需要改变字符串的话,可以使用 StringBuilder 或者 StringBuffer。 ### 8种基本类型的包装类和常量池 - **Java 基本类型的包装类的大部分都实现了常量池技术,即 Byte,Short,Integer,Long,Character,Boolean;这 5 种包装类默认创建了数值[-128,127] 的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。** - **两种浮点数类型的包装类 Float,Double 并没有实现常量池技术。** #### 应用场景 1. Integer i1=40;Java 在编译的时候会直接将代码封装成 Integer i1=Integer.valueOf(40);,从而使用常量池中的对象。 2. Integer i1 = new Integer(40);这种情况下会创建新的对象。 ```java Integer i1 = 40; Integer i2 = 40; Integer i3 = 0; Integer i4 = new Integer(40); Integer i5 = new Integer(40); Integer i6 = new Integer(0); System.out.println("i1=i2 " + (i1 == i2)); System.out.println("i1=i2+i3 " + (i1 == i2 + i3)); System.out.println("i1=i4 " + (i1 == i4)); System.out.println("i4=i5 " + (i4 == i5)); System.out.println("i4=i5+i6 " + (i4 == i5 + i6)); System.out.println("40=i5+i6 " + (40 == i5 + i6)); i1=i2 true i1=i2+i3 true i1=i4 false i4=i5 false i4=i5+i6 true 40=i5+i6 true ``` <file_sep>## 引言 **Java的集合框架,LinkedList源码解析等...** <!-- more --> ## 概述 *LinkedList*同时实现了*List*接口和*Deque*接口,也就是说它既可以看作一个顺序容器,又可以看作一个队列(*Queue*),同时又可以看作一个栈(*Stack*)。这样看来,*LinkedList*简直就是个全能冠军。当你需要使用栈或者队列时,可以考虑使用*LinkedList*,一方面是因为Java官方已经声明不建议使用*Stack*类,更遗憾的是,Java里根本没有一个叫做*Queue*的类(它是个接口名字)。关于栈或队列,现在的首选是*ArrayDeque*,它有着比*LinkedList*(当作栈或队列使用时)有着更好的性能。 ![LinkedList](https://www.pdai.tech/_images/collection/LinkedList_base.png) *LinkedList*的实现方式决定了所有跟下标相关的操作都是线性时间,而在首段或者末尾删除元素只需要常数时间。为追求效率*LinkedList*没有实现同步(synchronized),如果需要多个线程并发访问,可以先采用`Collections.synchronizedList()`方法对其进行包装。 ## LinkedLists实现 ### 底层数据结构 *LinkedList*底层**通过双向链表实现**,本节将着重讲解插入和删除元素时双向链表的维护过程,也即是之间解跟*List*接口相关的函数,而将*Queue*和*Stack*以及*Deque*相关的知识放在下一节讲。双向链表的每个节点用内部类*Node*表示。*LinkedList*通过`first`和`last`引用分别指向链表的第一个和最后一个元素。注意这里没有所谓的哑元,当链表为空的时候`first`和`last`都指向`null`。 ```java transient int size = 0; transient Node<E> first; transient Node<E> last; // Node是私有的内部类 private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } } ``` ### 构造函数 ```java public LinkedList() { } public LinkedList(Collection<? extends E> c) { this(); addAll(c); } ``` ### getFirst(),getLast() ```java public E getFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return f.item; } public E getLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return l.item; } ``` ### removeFirst(),removeLast(),remove(e),remove(index) `remove()`方法也有两个版本,一个是删除跟指定元素相等的第一个元素`remove(Object o)`,另一个是删除指定下标处的元素`remove(int index)`。 ![remove](https://www.pdai.tech/_images/collection/LinkedList_remove.png) 删除元素 - 指的是删除第一次出现的这个元素, 如果没有这个元素,则返回false;判读的依据是equals方法, 如果equals,则直接unlink这个node;由于LinkedList可存放null元素,故也可以删除第一次出现null的元素; ```java public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; if (prev == null) {// 第一个元素 first = next; } else { prev.next = next; x.prev = null; } if (next == null) {// 最后一个元素 last = prev; } else { next.prev = prev; x.next = null; } x.item = null; // GC size--; modCount++; return element; } ``` `remove(int index)`使用的是下标计数, 只需要判断该index是否有元素即可,如果有则直接unlink这个node。 ```java public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } ``` 删除head元素 ```java public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } private E unlinkFirst(Node<E> f) { // assert f == first && f != null; final E element = f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; } ``` 删除last元素 ```java public E removeLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } private E unlinkLast(Node<E> l) { // assert l == last && l != null; final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; } ``` ### add() *add()\*方法有两个版本,一个是`add(E e)`,该方法在\*LinkedList*的末尾插入元素,因为有`last`指向链表末尾,在末尾插入元素的花费是常数时间。只需要简单修改几个相关引用即可;另一个是`add(int index, E element)`,该方法是在指定下表处插入元素,需要先通过线性查找找到具体位置,然后修改相关引用完成插入操作。 ```java public boolean add(E e) { linkLast(e); return true; } void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } ``` ![](https://www.pdai.tech/_images/collection/LinkedList_add.png) `add(int index, E element)`, 当index==size时,等同于add(E e); 如果不是,则分两步:1.先根据index找到要插入的位置,即node(index)方法;2.修改引用,完成插入操作。 ```java public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } ``` 上面代码中的`node(int index)`函数有一点小小的trick,因为链表双向的,可以从开始往后找,也可以从结尾往前找,具体朝那个方向找取决于条件`index < (size >> 1)`,也即是index是靠近前端还是后端。从这里也可以看出,linkedList通过index检索元素的效率没有arrayList高。 ```java Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } } ``` ### addAll() addAll(index, c) 实现方式并不是直接调用add(index,e)来实现,主要是因为效率的问题,另一个是fail-fast中modCount只会增加1次; ```java public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); pred = succ.prev; } for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++; return true; } ``` ### clear() 为了让GC更快可以回收放置的元素,需要将node之间的引用关系赋空。 ```java public void clear() { // Clearing all of the links between nodes is "unnecessary", but: // - helps a generational GC if the discarded nodes inhabit // more than one generation // - is sure to free memory even if there is a reachable Iterator for (Node<E> x = first; x != null; ) { Node<E> next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; } ``` ### Positional Access 方法 通过index获取元素 ```java public E get(int index) { checkElementIndex(index); return node(index).item; } ``` 将某个位置的元素重新赋值 ```java public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; } ``` 将元素插入到指定index位置 ```java public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } ``` 删除指定位置的元素 ```java public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } ``` 其他位置的方法 ```java private boolean isElementIndex(int index) { return index >= 0 && index < size; } private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } ``` ### 查找操作 查找操作的本质是查找元素的下标: 查找第一次出现的index, 如果找不到返回-1; ```java public int indexOf(Object o) { int index = 0; if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; } ``` 查找最后一次出现的index, 如果找不到返回-1; ```java public int lastIndexOf(Object o) { int index = size; if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { index--; if (x.item == null) return index; } } else { for (Node<E> x = last; x != null; x = x.prev) { index--; if (o.equals(x.item)) return index; } } return -1; } ``` ### Queue方法 ```java public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } public E element() { return getFirst(); } public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } public E remove() { return removeFirst(); } public boolean offer(E e) { return add(e); } ``` ### Deque方法 ```java public boolean offerFirst(E e) { addFirst(e); return true; } public boolean offerLast(E e) { addLast(e); return true; } public E peekFirst() { final Node<E> f = first; return (f == null) ? null : f.item; } public E peekLast() { final Node<E> l = last; return (l == null) ? null : l.item; } public E pollFirst() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } public E pollLast() { final Node<E> l = last; return (l == null) ? null : unlinkLast(l); } public void push(E e) { addFirst(e); } public E pop() { return removeFirst(); } public boolean removeFirstOccurrence(Object o) { return remove(o); } public boolean removeLastOccurrence(Object o) { if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } ``` <file_sep>- [网络7层和4层的区别](https://juejin.im/post/59a0472f5188251240632f92) - **DNS** - [DNS是什么?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#dns%E6%98%AF) - [谈谈DNS解析过程](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#%E8%A7%A3%E6%9E%90%E8%BF%87%E7%A8%8B) - [DNS查询方式?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#%E6%9F%A5%E8%AF%A2%E6%96%B9%E5%BC%8F) - [DNS负载均衡](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#dns%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1) - [为什么域名解析用UDP协议?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%E7%94%A8udp%E5%8D%8F%E8%AE%AE) - [为什么区域传送用TCP协议?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-DNS%E6%98%AF%E5%B9%B2%E4%BB%80%E4%B9%88%E7%9A%84.md#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8C%BA%E5%9F%9F%E4%BC%A0%E9%80%81%E7%94%A8tcp%E5%8D%8F%E8%AE%AE) - **HTTP** - [请求和响应报文](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E8%AF%B7%E6%B1%82%E5%92%8C%E5%93%8D%E5%BA%94%E6%8A%A5%E6%96%87) - [HTTP请求方法](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#http%E6%96%B9%E6%B3%95) - [HTTP状态码](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#http%E7%8A%B6%E6%80%81%E7%A0%81) - [Cookies](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#cookies) - [Session](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#session) - [浏览器在与服务器建立了一个 TCP 连接后是否会在一个 HTTP 请求完成后断开?什么情况下会断开?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E4%BB%A3%E6%B5%8F%E8%A7%88%E5%99%A8%E5%9C%A8%E4%B8%8E%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%BB%BA%E7%AB%8B%E4%BA%86%E4%B8%80%E4%B8%AA-tcp-%E8%BF%9E%E6%8E%A5%E5%90%8E%E6%98%AF%E5%90%A6%E4%BC%9A%E5%9C%A8%E4%B8%80%E4%B8%AA-http-%E8%AF%B7%E6%B1%82%E5%AE%8C%E6%88%90%E5%90%8E%E6%96%AD%E5%BC%80%E4%BB%80%E4%B9%88%E6%83%85%E5%86%B5%E4%B8%8B%E4%BC%9A%E6%96%AD%E5%BC%80) - [一个 TCP 连接可以对应几个 HTTP 请求?]()如果维持连接,一个 TCP 连接是可以发送多个 HTTP 请求的。 - [一个 TCP 连接中 HTTP 请求发送可以一起发送么(比如一起发三个请求,再三个响应一起接收)](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E4%B8%80%E4%B8%AA-tcp-%E8%BF%9E%E6%8E%A5%E4%B8%AD-http-%E8%AF%B7%E6%B1%82%E5%8F%91%E9%80%81%E5%8F%AF%E4%BB%A5%E4%B8%80%E8%B5%B7%E5%8F%91%E9%80%81%E4%B9%88%E6%AF%94%E5%A6%82%E4%B8%80%E8%B5%B7%E5%8F%91%E4%B8%89%E4%B8%AA%E8%AF%B7%E6%B1%82%E5%86%8D%E4%B8%89%E4%B8%AA%E5%93%8D%E5%BA%94%E4%B8%80%E8%B5%B7%E6%8E%A5%E6%94%B6) - [为什么有的时候刷新页面不需要重新建立 SSL 连接?]()TCP 连接有的时候会被浏览器和服务端维持一段时间。TCP 不需要重新建立,SSL 自然也会用之前的。 - [浏览器对同一Host建立TCP连接到数量有没有限制?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E6%B5%8F%E8%A7%88%E5%99%A8%E5%AF%B9%E5%90%8C%E4%B8%80-host-%E5%BB%BA%E7%AB%8B-tcp-%E8%BF%9E%E6%8E%A5%E5%88%B0%E6%95%B0%E9%87%8F%E6%9C%89%E6%B2%A1%E6%9C%89%E9%99%90%E5%88%B6) - **HTTPS** - [HTTPS是什么](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#https) - [对称密钥加密](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E5%AF%B9%E7%A7%B0%E5%AF%86%E9%92%A5%E5%8A%A0%E5%AF%86) - [非对称密钥加密](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%AF%86%E9%92%A5%E5%8A%A0%E5%AF%86) - [HTTPS采用的加密方式](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C%E5%8E%9F%E7%90%86-http%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF.md#https%E9%87%87%E7%94%A8%E7%9A%84%E5%8A%A0%E5%AF%86%E6%96%B9%E5%BC%8F) - [HTTPS的缺点]()因为需要进行加密解密等过程,因此速度会更慢;需要支付证书授权的高额费用。<file_sep>import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @program JavaBooks * @description: 代理模式 * @author: mf * @create: 2019/10/02 10:04 */ /* 所谓代理模式是指客户端并不直接调用实际的对象,而是通过调用代理,来间接的调用实际的对象。 一般是因为客户端不想直接访问实际的对象,或者访问实际的对象存在困难,因此通过一个代理对象来完成间接的访问。 */ /* 静态代理 */ // 主题 interface Subject { void visit(); } // 实现subject的两个类 class RealSubject implements Subject { private String name = "<NAME>"; @Override public void visit() { System.out.println(name); } } class ProxySubject implements Subject { private Subject subject; public ProxySubject(Subject subject) { this.subject = subject; } @Override public void visit() { subject.visit(); } } /* 代理类接受一个Subject接口的对象,任何实现该接口的对象,都可以通过代理类进行代理,增加了通用性。 每一个代理类都必须实现一遍委托类(也就是realsubject)的接口,如果接口增加方法,则代理类也必须跟着修改。 代理类每一个接口对象对应一个委托对象,如果委托对象非常多,则静态代理类就非常臃肿,难以胜任。 */ /* 动态代理 动态代理是实现方式,是通过反射来实现的,借助Java自带的java.lang.reflect.Proxy,通过固定的规则生成。 */ class DynamicProxy implements InvocationHandler { private Object object; public DynamicProxy(Object object) { this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(object, args); return result; } } public class ProxyMode { public static void main(String[] args) { // 静态代理 ProxySubject proxySubject = new ProxySubject(new RealSubject()); proxySubject.visit(); // 动态代理 RealSubject realSubject = new RealSubject(); DynamicProxy dynamicProxy = new DynamicProxy(realSubject); ClassLoader classLoader = realSubject.getClass().getClassLoader(); Subject subject = (Subject) Proxy.newProxyInstance(classLoader, new Class[]{Subject.class}, dynamicProxy); subject.visit(); } } <file_sep>## 引言 **线性表-动态规划** ## 相关题目 ### [53. 最大子序和](https://leetcode-cn.com/problems/maximum-subarray/) <!-- more --> ```bash 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 ``` ```java class Solution { public int maxSubArray(int[] nums) { if(nums == null || nums.length == 0 ) return 0; int max = nums[0]; // 记录包含arr[i]的连续子数组的和的最大值 int ans = nums[0]; // 记录当前所有子数组的和的最大值 for(int i = 1; i < nums.length; i++) { max = Math.max(max + nums[i], nums[i]); ans = Math.max(max, ans); } return ans; } } ``` ### [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/) ```bash 输入: 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶 ``` ```java class Solution { public int climbStairs(int n) { if(n <= 2) return n; int pre2 = 1, pre1 = 2; for(int i = 3; i <= n; i++) { int cur = pre2 + pre1; pre2 = pre1; pre1 = cur; } return pre1; } } ``` ### [121. 买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/) ```bash 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 ``` ```java class Solution { public int maxProfit(int[] prices) { if(prices.length <= 1) return 0; int min = prices[0], max = 0; for(int i = 1; i < prices.length; i++){ max = Math.max(max, prices[i] - min); min = Math.min(min, prices[i]); } return max; } } ``` ### [198. 打家劫舍](https://leetcode-cn.com/problems/house-robber/) ```bash 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。   偷窃到的最高金额 = 1 + 3 = 4 。 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。   偷窃到的最高金额 = 2 + 9 + 1 = 12 。 ``` ```java class Solution { public int rob(int[] nums) { if(nums.length == 0) return 0; if(nums.length == 1) return nums[0]; int pre3 = 0, pre2 = 0, pre1 = 0; for (int i = 0; i < nums.length; i++) { int cur = Math.max(pre3, pre2) + nums[i]; pre3 = pre2; pre2 = pre1; pre1 = cur; } return Math.max(pre2, pre1); } } ``` ### [322.零钱兑换](https://leetcode-cn.com/problems/coin-change/) ``` 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 输入: coins = [1, 2, 5], amount = 11 输出: 3 解释: 11 = 5 + 5 + 1 输入: coins = [2], amount = 3 输出: -1 ``` ```java class Solution { public int coinChange(int[] coins, int amount) { // 初始化dp int[] dp = new int[amount + 1]; for (int i = 0; i <= amount; i++) { dp[i] = -1; } dp[0] = 0; // 金额为0的最优解 for (int i = 1; i <= amount; i++) { for (int j = 0; j < coins.length; j++) { if (i - coins[j] >= 0 && dp[i - coins[j]] != -1) { if (dp[i] == -1 || dp[i] > dp[i - coins[j]] + 1) { dp[i] = dp[i - coins[j]] + 1; } } } } return dp[amount]; } } ``` ### [300. 最长上升子序列](https://leetcode-cn.com/problems/longest-increasing-subsequence/) ``` 给定一个无序的整数数组,找到其中最长上升子序列的长度。 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 ``` ```java class Solution { public int lengthOfLIS(int[] nums) { if (nums.length == 0) return 0; int[] dp = new int[nums.length]; dp[0] = 1; int lis = 1; for (int i = 1; i < dp.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j] && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; } } lis = Math.max(lis, dp[i]); } return lis; } } ``` ### [64. 最小路径和](https://leetcode-cn.com/problems/minimum-path-sum/) ``` 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 输入: [ [1,3,1], [1,5,1], [4,2,1] ] 输出: 7 解释: 因为路径 1→3→1→1→1 的总和最小。 ``` ```java class Solution { public int minPathSum(int[][] grid) { if (grid.length == 0) return 0; int row = grid.length; int col = grid[0].length; // 定义dp int[][] dp = new int[row][col]; dp[0][0] = grid[0][0]; for(int i = 1; i < col; i++) { dp[0][i] = dp[0][i-1] + grid[0][i]; } //start for (int i = 1; i < row; i++) { dp[i][0] = dp[i-1][0] + grid[i][0]; for (int j = 1; j < col; j++) { dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + grid[i][j]; } } return dp[row-1][col-1]; } } ``` ### [152. 乘积最大子数组](https://leetcode-cn.com/problems/maximum-product-subarray/) ``` 给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字)。 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。 输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 ``` ```java class Solution { public int maxProduct(int[] nums) { if (nums.length == 0) return 0; int ans = Integer.MIN_VALUE; int[] dpMax = new int[nums.length + 1]; int[] dpMin = new int[nums.length + 1]; dpMax[0] = 1; dpMin[0] = 1; for (int i = 1; i <= nums.length; i++) { if (nums[i-1] < 0) { int temp = dpMax[i-1]; dpMax[i-1] = dpMin[i-1]; dpMin[i-1] = temp; } dpMax[i] = Math.max(dpMax[i-1]*nums[i-1], nums[i-1]); dpMin[i] = Math.min(dpMin[i-1]*nums[i-1], nums[i-1]); ans = Math.max(ans, dpMax[i]); } return ans; } } ``` ### [279. 完全平方数](https://leetcode-cn.com/problems/perfect-squares/) ``` 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 输入: n = 12 输出: 3 解释: 12 = 4 + 4 + 4. 输入: n = 13 输出: 2 解释: 13 = 4 + 9. ``` ```java class Solution { public int numSquares(int n) { int[] dp = new int[n+1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; int maxSIndex = (int) (Math.sqrt(n) + 1); int[] squareNum = new int[maxSIndex]; for (int i = 1; i < maxSIndex; i++) { squareNum[i] = i * i; } for (int i = 1; i <= n; i++) { for (int j = 1; j < maxSIndex; j++) { if (i < squareNum[j]) break; dp[i] = Math.min(dp[i], dp[i - squareNum[j]] + 1); } } return dp[n]; } } ``` <file_sep>package books; /** * @program JavaBooks * @description: 单例模式 * @author: mf * @create: 2019/08/15 15:53 */ /** * 饿汉 */ public class T2 { private static T2 instance = new T2(); private T2(){} public static T2 getInstance() { return instance; } } /** * 饿汉变种 */ class Singleton1 { private static Singleton1 instance = null; static { instance = new Singleton1(); } private Singleton1() {} public static Singleton1 getInstance() { return instance; } } /** * 懒汉 -- 线程不安全... */ class Singleton2 { private static Singleton2 instance = null; private Singleton2(){} public static Singleton2 getInstance() { if (instance == null){ instance = new Singleton2(); } return instance; } } /** * 懒汉 -- 线程安全, 但消耗资源较为严重 */ class Singleton3 { private static Singleton3 instance = null; private Singleton3() { } public static synchronized Singleton3 getInstance() { if (instance == null) { instance = new Singleton3(); } return instance; } } /** * 线程安全,双重校验 */ class Singleton4 { private static volatile Singleton4 instance = null; private Singleton4() { } public static Singleton4 getInstance() { if (instance == null) { synchronized (Singleton4.class) { if (instance == null) { instance = new Singleton4(); } } } return instance; } }<file_sep>package books; import java.util.Arrays; /** * @program JavaBooks * @description: 调整数组顺序使奇数位于偶数前面 * @author: mf * @create: 2019/09/02 09:47 */ /* 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, 使得所有奇数位于数组的前半部分 所有偶数位于数组的后半部分 */ public class T21 { public static void main(String[] args) { int[] arr = {2, 3, 6, 4, 7, 5}; reorderOddEven(arr); System.out.println(Arrays.toString(arr)); } private static void reorderOddEven(int[] arr) { if (arr == null || arr.length == 0) return; int p1 = 0; int p2 = arr.length - 1; while (p1 < p2) { // 向后移动p1, 直到指向偶数 根据题目的话,这里可扩展 while (p1 < p2 && (arr[p1] & 0x1) != 0) { p1++; } // 向前移动p2,直到指向奇数 同理 while (p1 < p2 && (arr[p2] & 0x1) != 1) { p2--; } if(p1 < p2) { swap(arr, p1, p2); } } } private static void swap(int[] arr, int p1, int p2) { int temp = arr[p1]; arr[p1] = arr[p2]; arr[p2] = temp; } } <file_sep>package books; /** * @program JavaBooks * @description: 股票的最大利润 * @author: mf * @create: 2019/10/09 16:18 */ /* 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票 一次可能获得的最大利润是多少?例如,一只股票在某些时间节点的价格为 {9, 11, 8, 5, 7, 12, 16, 14}。如果我们能在价格为5的时候买入并 在价格为16时卖出,则能收获最大的利润是11。 */ public class T63 { public static void main(String[] args) { int[] arr = {9, 11, 8, 5, 7, 12, 16, 14}; System.out.println(getMaxDiff(arr)); } private static int getMaxDiff(int[] arr) { if (arr == null || arr.length == 0) return 0; int min = arr[0]; int maxDiff = arr[1] - min; for (int i = 2; i < arr.length; i++) { min = arr[i - 1] < min ? arr[i - 1] : min; int currentDiff = arr[i] - min; maxDiff = currentDiff > maxDiff ? currentDiff : maxDiff; } return maxDiff; } } <file_sep>> 计算机网络,那是必问环节咯,而且问的也都很固定,也多看看以及理解理解。 ## 大纲 ![计算机网络](http://media.dreamcat.ink/uPic/计算机网络.png) ### 网络模型 ![分层模型](http://media.dreamcat.ink/uPic/分层模型.png) #### 简要概括 - 物理层:底层数据传输,如网线;网卡标准。 - 数据链路层:定义数据的基本格式,如何传输,如何标识;如网卡MAC地址。 - 网络层:定义IP编址,定义路由功能;如不同设备的数据转发。 - 传输层:端到端传输数据的基本功能;如 TCP、UDP。 - 会话层:控制应用程序之间会话能力;如不同软件数据分发给不同软件。 - 标识层:数据格式标识,基本压缩加密功能。 - 应用层:各种应用软件,包括 Web 应用。 #### 流程 比如,计算机 A 和 计算机 B 要进行信息交互,比如 A 上开发了一个网页,需要 B 去访问。B 发出一个请求给 A,那么请求数据从 B 的 **应用层开始向下传到表示层、再从表示层传到会话层直到物理层,通过物理层传递到 A,A 的物理层接到请求后将请求向上传递到自己的应用层,应用层再将要请求的数据向自己的物理层方向传递然后 B 接到数据传递数据到自己的应用层**。 说明: - 在四层,既传输层数据被称作**段**(Segments); - 三层网络层数据被称做**包**(Packages); - 二层数据链路层时数据被称为**帧**(Frames); - 一层物理层时数据被称为**比特流**(Bits)。 #### 常见的端口号和协议号 ![协议端口号](http://media.dreamcat.ink/uPic/EuHz2s.png) #### 总结 - 网络七层模型是一个标准,而非实现。 - 网络四层模型是一个实现的应用模型。 - 网络四层模型由七层模型简化合并而来。 #### ping命令基于哪一层协议的原理是什么? ping命令基于网络层的命令,是基于ICMP协议工作的。 ### DNS #### DNS是什么 **官方解释**:DNS(Domain Name System,域名系统),因特网上作为**域名和IP地址相互映射**的一个**分布式数据库**,能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的IP数串。通过主机名,最终得到该主机名对应的IP地址的过程叫做域名解析(或主机名解析)。 **通俗的讲**,我们更习惯于记住一个网站的名字,比如www.baidu.com,而不是记住它的ip地址,比如:192.168.127.12。 #### 谈谈DNS解析过程 ![DNS解析过程](http://media.dreamcat.ink/uPic/DNS解析过程.png) - 请求一旦发起,若是chrome浏览器,先在浏览器找之前**有没有缓存过的域名所对应的ip地址**,有的话,直接跳过dns解析了,若是没有,就会**找硬盘的hosts文件**,看看有没有,有的话,直接找到hosts文件里面的ip - 如果本地的hosts文件没有能的到对应的ip地址,浏览器会发出一个**dns请求到本地dns服务器**,**本地dns服务器一般都是你的网络接入服务器商提供**,比如中国电信,中国移动等。 - 查询你输入的网址的DNS请求到达本地DNS服务器之后,**本地DNS服务器会首先查询它的缓存记录**,如果缓存中有此条记录,就可以直接返回结果,此过程是**递归的方式进行查询**。如果没有,本地DNS服务器还要向**DNS根服务器**进行查询。 - 本地DNS服务器继续向域服务器发出请求,在这个例子中,请求的对象是.com域服务器。.com域服务器收到请求之后,也不会直接返回域名和IP地址的对应关系,而是告诉本地DNS服务器,你的域名的解析服务器的地址。 - 最后,本地DNS服务器向**域名的解析服务器**发出请求,这时就能收到一个域名和IP地址对应关系,本地DNS服务器不仅要把IP地址返回给用户电脑,还要把这个对应关系保存在缓存中,以备下次别的用户查询时,可以直接返回结果,加快网络访问。 #### DNS查询方式 ##### 递归解析 当局部DNS服务器自己不能回答客户机的DNS查询时,它就需要向其他DNS服务器进行查询。此时有两种方式。**局部DNS服务器自己负责向其他DNS服务器进行查询,一般是先向该域名的根域服务器查询,再由根域名服务器一级级向下查询**。最后得到的查询结果返回给局部DNS服务器,再由局部DNS服务器返回给客户端。 ##### 迭代解析 当局部DNS服务器自己不能回答客户机的DNS查询时,也可以通过迭代查询的方式进行解析。局部DNS服务器不是自己向其他DNS服务器进行查询,**而是把能解析该域名的其他DNS服务器的IP地址返回给客户端DNS程序**,客户端DNS程序再继续向这些DNS服务器进行查询,直到得到查询结果为止。也就是说,迭代解析只是帮你找到相关的服务器而已,而不会帮你去查。比如说:baidu.com的服务器ip地址在192.168.4.5这里,你自己去查吧,本人比较忙,只能帮你到这里了。 #### DNS负载均衡 当一个网站有足够多的用户的时候,假如每次请求的资源都位于同一台机器上面,那么这台机器随时可能会蹦掉。处理办法就是用DNS负载均衡技术,它的原理是在**DNS服务器中为同一个主机名配置多个IP地址,在应答DNS查询时,DNS服务器对每个查询将以DNS文件中主机记录的IP地址按顺序返回不同的解析结果,将客户端的访问引导到不同的机器上去,使得不同的客户端访问不同的服务器**,从而达到负载均衡的目的。例如可以根据每台机器的负载量,该机器离用户地理位置的距离等等。 #### 为什么域名解析用UDP协议? 因为UDP快啊!UDP的DNS协议只要一个请求、一个应答就好了。而使用基于TCP的DNS协议要三次握手、发送数据以及应答、四次挥手。但是UDP协议传输内容不能超过512字节。不过客户端向DNS服务器查询域名,一般返回的内容都不超过512字节,用UDP传输即可。 #### 为什么区域传送用TCP协议? 因为TCP协议可靠性好啊!你要从主DNS上复制内容啊,你用不可靠的UDP? 因为TCP协议传输的内容大啊,你用最大只能传512字节的UDP协议?万一同步的数据大于512字节,你怎么办? ### HTTP #### 请求和相应报文 ##### 请求报文 简单来说: - 请求行:Request Line - 请求头:Request Headers - 请求体:Request Body ##### 响应报文 简单来说: - 状态行:Status Line - 响应头:Response Headers - 响应体:Response Body #### HTTP请求方法 ##### GET > 获取资源 当前网络请求中,绝大部分使用的是 GET 方法。 ##### HEAD > 获取报文头部 和 GET 方法类似,但是不返回报文实体主体部分。 主要用于确认 URL 的有效性以及资源更新的日期时间等。 ##### POST > 传输实体主体 POST 主要用来传输数据,而 GET 主要用来获取资源。 更多 POST 与 GET 的比较见后 ##### PUT > 上传文件 由于自身不带验证机制,任何人都可以上传文件,因此存在安全性问题,一般不使用该方法。 ##### PATCH > 对资源进行部分修改 PUT 也可以用于修改资源,但是只能完全替代原始资源,PATCH 允许部分修改。 ##### DELETE > 删除文件 与 PUT 功能相反,并且同样不带验证机制。 ##### OPTINONS > 查询支持的方法 查询指定的 URL 能够支持的方法。 会返回 `Allow: GET, POST, HEAD, OPTIONS` 这样的内容。 ##### CONNECT > 要求在与代理服务器通信时建立隧道 使用 SSL(Secure Sockets Layer,安全套接层)和 TLS(Transport Layer Security,传输层安全)协议把通信内容加密后经网络隧道传输。 #### GET和POST的区别? 1. GET使用URL或Cookie传参,而POST将数据放在BODY中 2. GET方式提交的数据有长度限制,则POST的数据则可以非常大 3. POST比GET安全,因为数据在地址栏上不可见,没毛病 4. **本质区别**:GET请求是幂等性的,POST请求不是。 > 这里的幂等性:幂等性是指一次和多次请求某一个资源应该具有同样的副作用。简单来说意味着对同一URL的多个请求应该返回同样的结果。 正因为它们有这样的区别,所以不应该且**不能用get请求做数据的增删改这些有副作用的操作**。因为get请求是幂等的,**在网络不好的隧道中会尝试重试**。如果用get请求增数据,会有**重复操作**的风险,而这种重复操作可能会导致副作用(浏览器和操作系统并不知道你会用get请求去做增操作)。 #### HTTP状态码 | 状态码 | 类别 | 含义 | | ------ | -------------------------------- | -------------------------- | | 1XX | Informational(信息性状态码) | 接收的请求正在处理 | | 2XX | Success(成功状态码) | 请求正常处理完毕 | | 3XX | Redirection(重定向状态码) | 需要进行附加操作以完成请求 | | 4XX | Client Error(客户端错误状态码) | 服务器无法处理请求 | | 5XX | Server Error(服务器错误状态码) | 服务器处理请求出 | ##### 1xx 信息 **100 Continue** :表明到目前为止都很正常,客户端可以继续发送请求或者忽略这个响应。 ##### 2xx 成功 - **200 OK** - **204 No Content** :请求已经成功处理,但是返回的响应报文不包含实体的主体部分。一般在只需要从客户端往服务器发送信息,而不需要返回数据时使用。 - **206 Partial Content** :表示客户端进行了范围请求,响应报文包含由 Content-Range 指定范围的实体内容。 ##### 3xx 重定向 - **301 Moved Permanently** :永久性重定向 - **302 Found** :临时性重定向 - **303 See Other** :和 302 有着相同的功能,但是 303 明确要求客户端应该采用 GET 方法获取资源。 - **304 Not Modified** :如果请求报文首部包含一些条件,例如:If-Match,If-Modified-Since,If-None-Match,If-Range,If-Unmodified-Since,如果不满足条件,则服务器会返回 304 状态码。 - **307 Temporary Redirect** :临时重定向,与 302 的含义类似,但是 307 要求浏览器不会把重定向请求的 POST 方法改成 GET 方法。 ##### 4xx 客户端错误 - **400 Bad Request** :请求报文中存在语法错误。 - **401 Unauthorized** :该状态码表示发送的请求需要有认证信息(BASIC 认证、DIGEST 认证)。如果之前已进行过一次请求,则表示用户认证失败。 - **403 Forbidden** :请求被拒绝。 - **404 Not Found** ##### 5xx 服务器错误 - **500 Internal Server Error** :服务器正在执行请求时发生错误。 - **503 Service Unavailable** :服务器暂时处于超负载或正在进行停机维护,现在无法处理请求。 #### HTTP首部 > 这块有点多,可参考[http首部](https://github.com/DreamCats/JavaBooks/blob/master/Interview/network/计算机网络原理-http那些事儿.md#http首部) #### Cookies HTTP 协议是**无状态**的,主要是为了让 HTTP 协议尽可能简单,使得它能够处理大量事务。HTTP/1.1 引入 Cookie 来保存状态信息。 Cookie 是**服务器发送到用户浏览器并保存在本地的一小块数据**,它会在浏览器之后向同一服务器再次发起请求时被携带上,用于告知服务端两个请求是否来自同一浏览器。由于之后每次请求都会需要携带 Cookie 数据,因此会带来额外的性能开销(尤其是在移动环境下)。 Cookie 曾一度用于客户端数据的存储,因为当时并没有其它合适的存储办法而作为唯一的存储手段,但现在随着现代浏览器开始支持各种各样的存储方式,Cookie 渐渐被淘汰。新的浏览器 API 已经允许开发者直接将数据存储到本地,如使用 Web storage API(本地存储和会话存储)或 IndexedDB。 ##### 用途 - 会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息) - 个性化设置(如用户自定义设置、主题等) - 浏览器行为跟踪(如跟踪分析用户行为等) #### Session 除了可以将用户信息通过 Cookie 存储在用户浏览器中,也可以利用 Session 存储在服务器端,存储在服务器端的信息更加安全。 Session 可以存储在服务器上的文件、数据库或者内存中。也可以将 Session 存储在 Redis 这种内存型数据库中,效率会更高。 使用 Session 维护用户登录状态的过程如下: - 用户进行登录时,用户提交包含用户名和密码的表单,放入 HTTP 请求报文中; - 服务器验证该用户名和密码,如果正确则把用户信息存储到 Redis 中,它在 Redis 中的 Key 称为 Session ID; - 服务器返回的响应报文的 Set-Cookie 首部字段包含了这个 Session ID,客户端收到响应报文之后将该 Cookie 值存入浏览器中; - 客户端之后对同一个服务器进行请求时会包含该 Cookie 值,服务器收到之后提取出 Session ID,从 Redis 中取出用户信息,继续之前的业务操作。 **注意**:Session ID 的安全性问题,不能让它被恶意攻击者轻易获取,那么就不能产生一个容易被猜到的 Session ID 值。此外,还需要经常重新生成 Session ID。在对安全性要求极高的场景下,例如转账等操作,除了使用 Session 管理用户状态之外,还需要对用户进行重新验证,比如重新输入密码,或者使用短信验证码等方式。 #### Cookie和Session的选择 - Cookie 只能存储 ASCII 码字符串,而 Session 则可以存储任何类型的数据,因此在考虑数据复杂性时首选 Session; - Cookie 存储在浏览器中,容易被恶意查看。如果非要将一些隐私数据存在 Cookie 中,可以将 Cookie 值进行加密,然后在服务器进行解密; - 对于大型网站,如果用户所有的信息都存储在 Session 中,那么开销是非常大的,因此不建议将所有的用户信息都存储到 Session 中。 #### JWT JWT(json web token)是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准。 cookie+session这种模式通常是保存在**内存**中,而且服务从单服务到多服务会面临的session共享问题,随着用户量的增多,开销就会越大。而JWT不是这样的,**只需要服务端生成token,客户端保存这个token,每次请求携带这个token,服务端认证解析就可**。 **JWT的构成**: 第一部分我们称它为头部(header),第二部分我们称其为载荷(payload),第三部分是签证(signature)。详情请见[官网](https://jwt.io/introduction/) **JWT总结**: 1. 因为json的通用性,所以JWT是可以进行跨语言支持的,像JAVA,JavaScript,NodeJS,PHP等很多语言都可以使用。 2. payload部分,JWT可以在自身存储一些其他业务逻辑所必要的非敏感信息。 3. 便于传输,jwt的构成非常简单,字节占用很小,所以它是非常便于传输的。它不需要在服务端保存会话信息, 所以它易于应用的扩展。 #### 浏览器在与服务器建立了一个 TCP 连接后是否会在一个 HTTP 请求完成后断开?什么情况下会断开? 在 HTTP/1.0 中,一个服务器在发送完一个 HTTP 响应后,会断开 TCP 链接。但是这样每次请求都会重新建立和断开 TCP 连接,代价过大。所以虽然标准中没有设定,**某些服务器对 Connection: keep-alive 的 Header 进行了支持**。意思是说,完成这个 HTTP 请求之后,不要断开 HTTP 请求使用的 TCP 连接。这样的好处是连接可以被重新使用,之后发送 HTTP 请求的时候不需要重新建立 TCP 连接,以及如果维持连接,那么 SSL 的开销也可以避免。 **持久连接**:既然维持 TCP 连接好处这么多,HTTP/1.1 就把 Connection 头写进标准,并且默认开启持久连接,除非请求中写明 Connection: close,那么浏览器和服务器之间是会维持一段时间的 TCP 连接,不会一个请求结束就断掉。 默认情况下建立 TCP 连接不会断开,只有在请求报头中声明 Connection: close 才会在请求完成后关闭连接。 #### 一个TCP连接可以对应几个HTTP请求? 如果维持连接,一个 TCP 连接是可以发送多个 HTTP 请求的。 #### 一个 TCP 连接中 HTTP 请求发送可以一起发送么(比如一起发三个请求,再三个响应一起接收)? HTTP/1.1 存在一个问题,单个 TCP 连接在同一时刻只能处理一个请求,意思是说:两个请求的生命周期不能重叠,任意两个 HTTP 请求从开始到结束的时间在同一个 TCP 连接里不能重叠。 在 HTTP/1.1 存在 Pipelining 技术可以完成这个多个请求同时发送,但是由于浏览器默认关闭,所以可以认为这是不可行的。在 HTTP2 中由于 Multiplexing 特点的存在,多个 HTTP 请求可以在同一个 TCP 连接中并行进行。 那么在 HTTP/1.1 时代,浏览器是如何提高页面加载效率的呢?主要有下面两点: - 维持和服务器已经建立的 TCP 连接,在同一连接上顺序处理多个请求。 - 和服务器建立多个 TCP 连接。 #### 为什么有的时候刷新页面不需要重新建立 SSL 连接? TCP 连接有的时候会被浏览器和服务端维持一段时间。TCP 不需要重新建立,SSL 自然也会用之前的。 #### 浏览器对同一 Host 建立 TCP 连接到数量有没有限制? 假设我们还处在 HTTP/1.1 时代,那个时候没有多路传输,当浏览器拿到一个有几十张图片的网页该怎么办呢?肯定不能只开一个 TCP 连接顺序下载,那样用户肯定等的很难受,但是如果每个图片都开一个 TCP 连接发 HTTP 请求,那电脑或者服务器都可能受不了,要是有 1000 张图片的话总不能开 1000 个TCP 连接吧,你的电脑同意 NAT 也不一定会同意。 **有。Chrome 最多允许对同一个 Host 建立六个 TCP 连接。不同的浏览器有一些区别。** 如果图片都是 HTTPS 连接并且在同一个域名下,那么浏览器在 SSL 握手之后会和服务器商量能不能用 HTTP2,如果能的话就使用 Multiplexing 功能在这个连接上进行多路传输。不过也未必会所有挂在这个域名的资源都会使用一个 TCP 连接去获取,但是可以确定的是 Multiplexing 很可能会被用到。 如果发现用不了 HTTP2 呢?或者用不了 HTTPS(现实中的 HTTP2 都是在 HTTPS 上实现的,所以也就是只能使用 HTTP/1.1)。那浏览器就会在一个 HOST 上建立多个 TCP 连接,连接数量的最大限制取决于浏览器设置,这些连接会在空闲的时候被浏览器用来发送新的请求,如果所有的连接都正在发送请求呢?那其他的请求就只能等等了。 #### 在浏览器中输入url地址后显示主页的过程? > - 根据域名,进行DNS域名解析; > - 拿到解析的IP地址,建立TCP连接; > - 向IP地址,发送HTTP请求; > - 服务器处理请求; > - 返回响应结果; > - 关闭TCP连接; > - 浏览器解析HTML; > - 浏览器布局渲染; ### HTTPS #### HTTPS是什么 HTTPS 并不是新协议,而是让 **HTTP 先和 SSL(Secure Sockets Layer)通信,再由 SSL 和 TCP 通信,也就是说 HTTPS 使用了隧道进行通信**。通过使用 SSL,HTTPS 具有了加密(防窃听)、认证(防伪装)和完整性保护(防篡改)。 #### HTTP的缺点 - 使用明文进行通信,内容可能会被窃听; - 不验证通信方的身份,通信方的身份有可能遭遇伪装; - 无法证明报文的完整性,报文有可能遭篡改。 #### 对称密钥加密 对称密钥加密(Symmetric-Key Encryption),加密和解密使用同一密钥。 - 优点:运算速度快 - 缺点:无法安全地将密钥传输给通信方 #### 非对称密钥加密 非对称密钥加密,又称公开密钥加密(Public-Key Encryption),加密和解密使用不同的密钥。 公开密钥所有人都可以获得,**通信发送方获得接收方的公开密钥之后,就可以使用公开密钥进行加密**,**接收方收到通信内容后使用私有密钥解密**。 非对称密钥除了用来加密,还可以用来进行签名。因为私有密钥无法被其他人获取,因此通信发送方使用其私有密钥进行签名,通信接收方使用发送方的公开密钥对签名进行解密,就能判断这个签名是否正确。 - 优点:可以更安全地将公开密钥传输给通信发送方; - 缺点:运算速度慢。 #### HTTPS采用的加密方式 HTTPS 采用混合的加密机制,使用**非对称密钥加密用于传输对称密钥来保证传输过程的安全性**,之后使用**对称密钥加密进行通信来保证通信过程的效率**。 ![rsa原理](http://media.dreamcat.ink/uPic/rsa原理.png) 确保传输安全过程(其实就是rsa原理): 1. Client给出协议版本号、一个客户端生成的随机数(Client random),以及客户端支持的加密方法。 2. Server确认双方使用的加密方法,并给出数字证书、以及一个服务器生成的随机数(Server random)。 3. Client确认数字证书有效,然后生成呀一个新的随机数(Premaster secret),并使用数字证书中的公钥,加密这个随机数,发给Server。 4. Server使用自己的私钥,获取Client发来的随机数(Premaster secret)。 5. Client和Server根据约定的加密方法,使用前面的三个随机数,生成”对话密钥”(session key),用来加密接下来的整个对话过程。 #### 认证 通过使用 **证书** 来对通信方进行认证。 数字证书认证机构(CA,Certificate Authority)是客户端与服务器双方都可信赖的第三方机构。 服务器的运营人员向 CA 提出公开密钥的申请,CA 在判明提出申请者的身份之后,会对已申请的公开密钥做数字签名,然后分配这个已签名的公开密钥,并将该公开密钥放入公开密钥证书后绑定在一起。 进行 HTTPS 通信时,服务器会把证书发送给客户端。客户端取得其中的公开密钥之后,先使用数字签名进行验证,如果验证通过,就可以开始通信了。 #### HTTP的缺点 - 因为需要进行加密解密等过程,因此速度会更慢; - 需要支付证书授权的高额费用。 ### TCP/UDP #### TCP ##### TCP是什么? `TCP(Transmission Control Protocol 传输控制协议)`是一种面向连接的、可靠的、基于字节流的传输层通信协议。 ##### TCP头部报文 ###### source port 和 destination port > 两者分别为「源端口号」和「目的端口号」。源端口号就是指本地端口,目的端口就是远程端口。 可以这么理解,我们有很多软件,每个软件都对应一个端口,假如,你想和我数据交互,咱们得互相知道你我的端口号。 再来一个很官方的: > 扩展:应用程序的端口号和应用程序所在主机的 IP 地址统称为 socket(套接字),IP:端口号, 在互联网上 socket 唯一标识每一个应用程序,源端口+源IP+目的端口+目的IP称为”套接字对“,一对套接字就是一个连接,一个客户端与服务器之间的连接。 ###### Sequence Number > 称为「序列号」。用于 TCP 通信过程中某一传输方向上字节流的每个字节的编号,为了确保数据通信的有序性,避免网络中乱序的问题。接收端根据这个编号进行确认,保证分割的数据段在原始数据包的位置。初始序列号由自己定,而后绪的序列号由对端的 ACK 决定:SN_x = ACK_y (x 的序列号 = y 发给 x 的 ACK)。 说白了,类似于身份证一样,而且还得发送此时此刻的所在的位置,就相当于身份证上的地址一样。 ###### Acknowledge Number > 称为「确认序列号」。确认序列号是接收确认端所期望收到的下一序列号。确认序号应当是上次已成功收到数据字节序号加1,只有当标志位中的 ACK 标志为 1 时该确认序列号的字段才有效。主要用来解决不丢包的问题。 ###### TCP Flag `TCP` 首部中有 6 个标志比特,它们中的多个可同时被设置为 `1`,主要是用于操控 `TCP` 的状态机的,依次为`URG,ACK,PSH,RST,SYN,FIN`。 当然只介绍三个: 1. **ACK**:这个标识可以理解为发送端发送数据到接收端,发送的时候 ACK 为 0,标识接收端还未应答,一旦接收端接收数据之后,就将 ACK 置为 1,发送端接收到之后,就知道了接收端已经接收了数据。 2. **SYN**:表示「同步序列号」,是 TCP 握手的发送的第一个数据包。用来建立 TCP 的连接。SYN 标志位和 ACK 标志位搭配使用,当连接请求的时候,SYN=1,ACK=0连接被响应的时候,SYN=1,ACK=1;这个标志的数据包经常被用来进行端口扫描。扫描者发送一个只有 SYN 的数据包,如果对方主机响应了一个数据包回来 ,就表明这台主机存在这个端口。 3. **FIN**:表示发送端已经达到数据末尾,也就是说双方的数据传送完成,没有数据可以传送了,发送FIN标志位的 TCP 数据包后,连接将被断开。这个标志的数据包也经常被用于进行端口扫描。发送端只剩最后的一段数据了,同时要告诉接收端后边没有数据可以接受了,所以用FIN标识一下,接收端看到这个FIN之后,哦!这是接受的最后的数据,接受完就关闭了;**TCP四次分手必然问**。 ###### Window size > 称为滑动窗口大小。所说的滑动窗口,用来进行流量控制。 #### TCP三次握手 ![TCP三次握手](http://media.dreamcat.ink/uPic/TCP三次握手.svg) - **初始状态**:客户端处于 `closed(关闭)`状态,服务器处于 `listen(监听)` 状态。 - **第一次握手**:客户端发送请求报文将 `SYN = 1`同步序列号和初始化序列号`seq = x`发送给服务端,发送完之后客户端处于`SYN_Send`状态。(验证了客户端的发送能力和服务端的接收能力) - **第二次握手**:服务端受到 `SYN` 请求报文之后,如果同意连接,会以自己的同步序列号`SYN(服务端) = 1`、初始化序列号 `seq = y`和确认序列号(期望下次收到的数据包)`ack = x+ 1` 以及确认号`ACK = 1`报文作为应答,服务器为`SYN_Receive`状态。(问题来了,两次握手之后,站在客户端角度上思考:我发送和接收都ok,服务端的发送和接收也都ok。但是站在服务端的角度思考:哎呀,我服务端接收ok,但是我不清楚我的发送ok不ok呀,而且我还不知道你接受能力如何呢?所以老哥,你需要给我三次握手来传个话告诉我一声。你要是不告诉我,万一我认为你跑了,然后我可能出于安全性的考虑继续给你发一次,看看你回不回我。) - **第三次握手**: 客户端接收到服务端的 `SYN + ACK`之后,知道可以下次可以发送了下一序列的数据包了,然后发送同步序列号 `ack = y + 1`和数据包的序列号 `seq = x + 1`以及确认号`ACK = 1`确认包作为应答,客户端转为`established`状态。(分别站在双方的角度上思考,各自ok) #### TCP四次分手 ![TCP四次分手](http://media.dreamcat.ink/uPic/TCP四次分手.png) - **初始化状态**:客户端和服务端都在连接状态,接下来开始进行四次分手断开连接操作。 - **第一次分手**:第一次分手无论是客户端还是服务端都可以发起,因为 TCP 是全双工的。 > 假如客户端发送的数据已经发送完毕,发送FIN = 1 **告诉服务端,客户端所有数据已经全发完了**,**服务端你可以关闭接收了**,但是如果你们服务端有数据要发给客户端,客户端照样可以接收的。此时客户端处于FIN = 1等待服务端确认释放连接状态。 - **第二次分手**:服务端接收到客户端的释放请求连接之后,**知道客户端没有数据要发给自己了**,**然后服务端发送ACK = 1告诉客户端收到你发给我的信息**,此时服务端处于 CLOSE_WAIT 等待关闭状态。(服务端先回应给客户端一声,我知道了,但服务端的发送数据能力即将等待关闭,于是接下来第三次就来了。) - **第三次分手**:此时服务端向客户端把所有的数据发送完了,然后发送一个FIN = 1,**用于告诉客户端,服务端的所有数据发送完毕**,**客户端你也可以关闭接收数据连接了**。此时服务端状态处于LAST_ACK状态,来等待确认客户端是否收到了自己的请求。(服务端等客户端回复是否收到呢,不收到的话,服务端不知道客户端是不是挂掉了还是咋回事呢,所以服务端不敢关闭自己的接收能力,于是第四次就来了。) - **第四次分手**:此时如果客户端收到了服务端发送完的信息之后,就发送ACK = 1,告诉服务端,客户端已经收到了你的信息。**有一个 2 MSL 的延迟等待**。 ##### 为什么要有2MSL等待延迟? 对应这样一种情况,最后客户端发送的ACK = 1给服务端的**过程中丢失**了,服务端没收到,服务端怎么认为的?我已经发送完数据了,怎么客户端没回应我?是不是中途丢失了?然后服务端再次发起断开连接的请求,一个来回就是2MSL。 客户端给服务端发送的ACK = 1丢失,**服务端等待 1MSL没收到**,**然后重新发送消息需要1MSL**。如果再次接收到服务端的消息,则**重启2MSL计时器**,**发送确认请求**。客户端只需等待2MSL,如果没有再次收到服务端的消息,就说明服务端已经接收到自己确认消息;此时双方都关闭的连接,TCP 四次分手完毕 ##### 为什么四次分手? 任何一方都可以在数据传送结束后发出连接释放的通知,待对方确认后进入半关闭状态。当另一方也没有数据再发送的时候,则发出连接释放通知,对方确认后就完全关闭了TCP连接。举个例子:A 和 B 打电话,通话即将结束后,A 说“我没啥要说的了”,B回答“我知道了”,但是 B 可能还会有要说的话,A 不能要求 B 跟着自己的节奏结束通话,于是 B 可能又巴拉巴拉说了一通,最后 B 说“我说完了”,A 回答“知道了”,这样通话才算结束。 #### TCP粘包 **TCP粘包**是指发送方发送的若干包数据到接收方接收时粘成一包,从接收缓冲区看,后一包数据的头紧接着前一包数据的尾。 - 由TCP**连接复用**造成的粘包问题。 - 因为TCP默认会使用**Nagle算法**,此算法会导致粘包问题。 - 只有上一个分组得到确认,才会发送下一个分组; - 收集多个小分组,在一个确认到来时一起发送。 - **数据包过大**造成的粘包问题。 - 流量控制,**拥塞控制**也可能导致粘包。 - **接收方不及时接收缓冲区的包,造成多个包接收** **解决**: 1. **Nagle算法**问题导致的,需要结合应用场景适当关闭该算法 2. 尾部标记序列。通过特殊标识符表示数据包的边界,例如\n\r,\t,或者一些隐藏字符。 3. 头部标记分步接收。在TCP报文的头部加上表示数据长度。 4. 应用层发送数据时**定长**发送。 #### TCP 协议如何保证可靠传输? - **确认和重传**:接收方收到报文就会确认,发送方发送一段时间后没有收到确认就会重传。 - **数据校验**:TCP报文头有校验和,用于校验报文是否损坏。 - **数据合理分片和排序**:tcp会按最大传输单元(MTU)合理分片,接收方会缓存未按序到达的数据,重新排序后交给应用层。而UDP:IP数据报大于1500字节,大于MTU。这个时候发送方的IP层就需要分片,把数据报分成若干片,是的每一片都小于MTU。而接收方IP层则需要进行数据报的重组。由于UDP的特性,某一片数据丢失时,接收方便无法重组数据报,导致丢弃整个UDP数据报。 - **流量控制**:当接收方来不及处理发送方的数据,能通过滑动窗口,提示发送方降低发送的速率,防止包丢失。 - **拥塞控制**:当网络拥塞时,通过拥塞窗口,减少数据的发送,防止包丢失。 #### TCP 利用滑动窗口实现流量控制的机制? > 流量控制是为了控制发送方发送速率,保证接收方来得及接收。TCP 利用滑动窗口实现流量控制。 TCP 中采用滑动窗口来进行传输控制,滑动窗口的大小意味着**接收方还有多大的缓冲区可以用于接收数据**。发送方可以通过滑动窗口的大小来确定应该发送多少字节的数据。当滑动窗口为 0 时,发送方一般不能再发送数据报,但有两种情况除外,一种情况是可以发送紧急数据。 > 例如,允许用户终止在远端机上的运行进程。另一种情况是发送方可以发送一个 1 字节的数据报来通知接收方重新声明它希望接收的下一字节及发送方的滑动窗口大小。 #### TCP拥塞控制的机制以及算法? > 在某段时间,若对网络中某一资源的需求超过了该资源所能提供的可用部分,网络的性能就要变坏。这种情况就叫拥塞。 TCP 发送方要维持一个 **拥塞窗口(cwnd) 的状态变量**。拥塞控制窗口的大小**取决于网络的拥塞程度**,并且动态变化。发送方让自己的发送窗口取为拥塞窗口和接收方的接受窗口中较小的一个。TCP的拥塞控制采用了四种算法,即 **慢开始** 、 **拥塞避免** 、**快重传** 和 **快恢复**。在网络层也可以使路由器采用适当的分组丢弃策略(如主动队列管理 AQM),以减少网络拥塞的发生。 #### UDP 提供**无连接**的,尽最大努力的数据传输服务(**不保证数据传输的可靠性**)。 ##### UDP的特点 - UDP是**无连接的**; - UDP使用**尽最大努力交付**,即不保证可靠交付,因此主机不需要维持复杂的链接状态(这里面有许多参数); - UDP是**面向报文**的; - UDP**没有拥塞控制**,因此网络出现拥塞不会使源主机的发送速率降低(对实时应用很有用,如IP电话,实时视频会议等); - UDP**支持一对一、一对多、多对一和多对多**的交互通信; - UDP的**首部开销小**,只有8个字节,比TCP的20个字节的首部要短。 那么,再说一次TCP的特点: - **TCP是面向连接的**。(就好像打电话一样,通话前需要先拨号建立连接,通话结束后要挂机释放连接); - 每一条TCP连接只能有两个端点,每一条TCP连接只能是点对点的(**一对一**); - TCP**提供可靠交付的服务**。通过TCP连接传送的数据,无差错、不丢失、不重复、并且按序到达; - TCP**提供全双工通信**。TCP允许通信双方的应用进程在任何时候都能发送数据。TCP连接的两端都设有发送缓存和接收缓存,用来临时存放双方通信的数据; - **面向字节流**。TCP中的“流”(stream)指的是流入进程或从进程流出的字节序列。“面向字节流”的含义是:虽然应用程序和TCP的交互是一次一个数据块(大小不等),但TCP把应用程序交下来的数据仅仅看成是一连串的无结构的字节流。 <file_sep>/** * @program JavaBooks * @description: TransferDemo * @author: mf * @create: 2020/02/07 21:22 */ package com.transfer; /** * Java 程序设计语言总是采用按值调用。 * 也就是说,方法得到的是所有参数值的一个拷贝,也就是说,方法不能修改传递给它的任何参数变量的内容。 */ public class TransferDemo { public static void main(String[] args) { int num1 = 10; int num2 = 20; swap(num1, num2); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); // 通过上面例子,我们已经知道了一个方法不能修改一个基本数据类型的参数,而对象引用作为参数就不一样,请看 } private static void swap(int a, int b) { int temp = a; a = b; b = temp; System.out.println("a = " + a); System.out.println("b = " + b); } } <file_sep>/** * @program JavaBooks * @description: 工厂模式 * @author: mf * @create: 2019/09/30 09:59 */ /* 简单工厂模式 工厂模版模式 抽象工厂模式 说白了, 就是为解耦。。。 */ // 举个例子 abstract class INoodles { /** * 描述每种面条长什么样的... */ public abstract void desc(); } // 先来一份兰州拉面(具体产品类) class LzNoodles extends INoodles { @Override public void desc() { System.out.println("兰州拉面,成都的好贵 家里的才5-6块钱一碗"); } } // 程序员加班也的来一份泡面哈 (具体产品类) class PaoNoodles extends INoodles { @Override public void desc() { System.out.println("泡面可还行..."); } } // 家乡的杂酱面,那才叫好吃撒... class ZaNoodles extends INoodles { @Override public void desc() { System.out.println("杂酱面,嗯? 真香..."); } } // 开个面馆吧... 做生意 class SimpleNoodlesFactory { public static final int TYPE_LZ = 1; // 兰州拉面 public static final int TYPE_PAO = 2; // 泡面撒 public static final int TYPE_ZA = 3; // 杂酱面 // 提供静态方法 public static INoodles createNoodles(int type) { switch (type) { case TYPE_LZ:return new LzNoodles(); case TYPE_PAO:return new PaoNoodles(); case TYPE_ZA:return new ZaNoodles(); default:return new ZaNoodles(); } } } public class FactoryMode { public static void main(String[] args) { INoodles noodles = SimpleNoodlesFactory.createNoodles(SimpleNoodlesFactory.TYPE_ZA); noodles.desc(); } } <file_sep>## 引言 **sql-存储引擎** ## InnoDB 是 MySQL 默认的事务型存储引擎,只有在需要它不支持的特性时,才考虑使用其它存储引擎。 实现了四个标准的隔离级别,默认级别是可重复读(REPEATABLE READ)。在可重复读隔离级别下,通过多版本并发控制(MVCC)+ 间隙锁(Next-Key Locking)防止幻影读。 主索引是聚簇索引,在索引中保存了数据,从而避免直接读取磁盘,因此对查询性能有很大的提升。 内部做了很多优化,包括从磁盘读取数据时采用的可预测性读、能够加快读操作并且自动创建的自适应哈希索引、能够加速插入操作的插入缓冲区等。 <!-- more --> 支持真正的在线热备份。其它存储引擎不支持在线热备份,要获取一致性视图需要停止对所有表的写入,而在读写混合场景中,停止写入可能也意味着停止读取。 ## MyISAM 设计简单,数据以紧密格式存储。对于只读数据,或者表比较小、可以容忍修复操作,则依然可以使用它。 提供了大量的特性,包括压缩表、空间数据索引等。 不支持事务。 不支持行级锁,只能对整张表加锁,读取时会对需要读到的所有表加共享锁,写入时则对表加排它锁。但在表有读取操作的同时,也可以往表中插入新的记录,这被称为并发插入(CONCURRENT INSERT)。 可以手工或者自动执行检查和修复操作,但是和事务恢复以及崩溃恢复不同,可能导致一些数据丢失,而且修复操作是非常慢的。 如果指定了 DELAY_KEY_WRITE 选项,在每次修改执行完成时,不会立即将修改的索引数据写入磁盘,而是会写到内存中的键缓冲区,只有在清理键缓冲区或者关闭表的时候才会将对应的索引块写入磁盘。这种方式可以极大的提升写入性能,但是在数据库或者主机崩溃时会造成索引损坏,需要执行修复操作。 ## 比较 - 事务: InnoDB 是事务型的,可以使用 Commit 和 Rollback 语句。 - 并发: MyISAM 只支持表级锁,而 InnoDB 还支持行级锁。 - 外键: InnoDB 支持外键。 - 备份: InnoDB 支持在线热备份。 - 崩溃恢复: MyISAM 崩溃后发生损坏的概率比 InnoDB 高很多,而且恢复的速度也更慢。 - 其它特性: MyISAM 支持压缩表和空间数据索引。<file_sep>--- title: 个人吐血系列-总结Java多线程 date: 2020-03-25 23:07:33 tags: 多线程 categories: java-interview --- ## 大纲图 ![多线程](http://media.dreamcat.ink/uPic/多线程.png) ### 什么是线程和进程? #### 进程 进程是程序的一次执行过程,是系统运行程序的基本单位,因此进程是动态的。系统运行一个程序即是一个进程从创建,运行到消亡的过程。 比如:当我们启动 main 函数时其实就是启动了一个 JVM 的进程,而 main 函数所在的线程就是这个进程中的一个线程,也称主线程。 #### 线程 - 线程是一个比进程更小的执行单位 - 一个进程在其执行的过程中可以产生**多个线程** - 与进程不同的是同类的多个线程共享进程的**堆**和**方法区**资源,但每个线程有自己的**程序计数器**、**虚拟机栈**和**本地方法栈**,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程 ### 并发和并行的区别? #### **并发:同一时间段,多个任务都在执行 (单位时间内不一定同时执行);** #### **并行:单位时间内,多个任务同时执行。** ### 为什么使用多线程? - **从计算机底层来说:** 线程可以比作是轻量级的进程,是程序执行的最小单位,线程间的切换和调度的成本远远小于进程。另外,多核 CPU 时代意味着多个线程可以同时运行,这减少了线程上下文切换的开销。 - **从当代互联网发展趋势来说:**现在的系统动不动就要求百万级甚至千万级的并发量,而多线程并发编程正是开发高并发系统的基础,利用好多线程机制可以大大提高系统整体的并发能力以及性能。 ### 使用多线程可能会带来什么问题? 可能会带来**内存泄漏**、**上下文切换**、**死锁**有受限于硬件和软件的资源闲置问题。 ### 说说线程的生命周期? ![](https://www.pdai.tech/_images/pics/ace830df-9919-48ca-91b5-60b193f593d2.png) 线程创建之后它将处于`New`(新建)状态,调用 `start()` 方法后开始运行,线程这时候处于 `READY`(可运行) 状态。可运行状态的线程获得了 CPU 时间片(timeslice)后就处于 `RUNNING`(运行) 状态。 当线程执行 `wait()`方法之后,线程进入 `WAITING`(等待) 状态。进入等待状态的线程需要依靠其他线程的通知才能够返回到运行状态,而 `TIME_WAITING`(超时等待) 状态相当于在等待状态的基础上增加了超时限制,比如通过 `sleep(long millis)`方法或 `wait(long millis)`方法可以将 Java 线程置于 `TIMED WAITING` 状态。当超时时间到达后 Java 线程将会返回到 RUNNABLE 状态。当线程调用同步方法时,在没有获取到锁的情况下,线程将会进入到 `BLOCKED`(阻塞)状态。线程在执行 Runnable 的` run() `方法之后将会进入到 `TERMINATED`(终止) 状态。 ### 什么是上下文切换? 多线程编程中一般**线程的个数都大于 CPU 核心的个数**,而一个 CPU 核心在任意时刻只能被一个线程使用,为了让这些线程都能得到有效执行,CPU 采取的策略是为每个线程分配**时间片并轮转**的形式。当一个线程的时间片用完的时候就会重新处于就绪状态让给其他线程使用,这个过程就属于一次上下文切换。 实际上就是**任务从保存到再加载的过程就是一次上下文切换**。 上下文切换通常是计算密集型的。也就是说,它需要相当可观的处理器时间,在每秒几十上百次的切换中,每次切换都需要纳秒量级的时间。所以,上下文切换对系统来说意味着消耗大量的 CPU 时间,事实上,可能是操作系统中时间消耗最大的操作。 Linux 相比与其他操作系统(包括其他类 Unix 系统)有很多的优点,其中有一项就是,其上下文切换和模式切换的时间消耗非常少。 ### 什么是死锁?如何避免死锁? 如下图所示,线程 A 持有资源 2,线程 B 持有资源 1,他们同时都想申请对方的资源,所以这两个线程就会互相等待而进入死锁状态。 ![线程死锁示意图 ](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-4/2019-4%E6%AD%BB%E9%94%811.png) 学过操作系统的朋友都知道产生死锁必须具备以下四个条件: - 互斥条件:该资源任意一个时刻只由一个线程占用。(同一时刻,这个碗是我的,你不能碰) - 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。(我拿着这个碗一直不放) - 不剥夺条件:线程已获得的资源在末使用完之前不能被其他线程强行剥夺,只有自己使用完毕后才释放资源。(我碗中的饭没吃完,你不能抢,释放权是我自己的,我想什么时候放就什么时候放) - 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。(我拿了A碗,你拿了B碗,但是我还想要你的B碗,你还想我的A碗) ```java public class DeadLockDemo { private static Object resource1 = new Object();//资源 1 private static Object resource2 = new Object();//资源 2 public static void main(String[] args) { new Thread(() -> { synchronized (resource1) { System.out.println(Thread.currentThread() + "get resource1"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + "waiting get resource2"); synchronized (resource2) { System.out.println(Thread.currentThread() + "get resource2"); } } }, "线程 1").start(); new Thread(() -> { synchronized (resource2) { System.out.println(Thread.currentThread() + "get resource2"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + "waiting get resource1"); synchronized (resource1) { System.out.println(Thread.currentThread() + "get resource1"); } } }, "线程 2").start(); } } Thread[线程 1,5,main]get resource1 Thread[线程 2,5,main]get resource2 Thread[线程 1,5,main]waiting get resource2 Thread[线程 2,5,main]waiting get resource1 ``` 线程 A 通过 `synchronized (resource1)` 获得 resource1 的监视器锁,然后通过` Thread.sleep(1000);`让线程 A 休眠 1s 为的是让线程 B 得到执行然后获取到 resource2 的监视器锁。线程 A 和线程 B 休眠结束了都开始企图请求获取对方的资源,然后这两个线程就会陷入互相等待的状态,这也就产生了死锁。上面的例子符合产生死锁的四个必要条件。 #### 如何找到死锁 **通过jdk常用的命令jsp和jstack,jsp查看java程序的id,jstack查看方法的栈信息等。** ### 说说Sleep和Wait方法的区别 - 两者最主要的区别在于:**sleep 方法没有释放锁,而 wait 方法释放了锁** 。 - 两者都可以暂停线程的执行。 - Wait 通常被用于线程间交互/通信,sleep 通常被用于暂停执行。 - wait() 方法被调用后,线程不会自动苏醒,需要别的线程调用同一个对象上的 notify() 或者 notifyAll() 方法。sleep() 方法执行完成后,线程会自动苏醒。或者可以使用wait(long timeout)超时后线程会自动苏醒。 ### Synchronzed #### 使用方式 - **修饰实例方法,作用于当前对象实例加锁,进入同步代码前要获得当前对象实例的锁** - **修饰静态方法,作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁** 。 - **修饰代码块,指定加锁对象,对给定对象加锁,进入同步代码库前要获得给定对象的锁。** #### 单例 ```java public class Singleton { private volatile static Singleton uniqueInstance; // 第一步 private Singleton() { // 第二步,私有 } public static Singleton getUniqueInstance() { //先判断对象是否已经实例过,没有实例化过才进入加锁代码 if (uniqueInstance == null) { // 双重校验 //类对象加锁 synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } } ``` 注意:**uniqueInstance 采用 volatile 关键字修饰也是很有必要** uniqueInstance = new Singleton(); 这段代码其实是分为三步执行: 1. 为 uniqueInstance 分配内存空间 2. 初始化 uniqueInstance 3. 将 uniqueInstance 指向分配的内存地址 但是由于 JVM 具有指令重排的特性,执行顺序有可能变成 1->3->2。指令重排在单线程环境下不会出现问题,但是在多线程环境下会导致一个线程获得还没有初始化的实例。例如,线程 T1 执行了 1 和 3,此时 T2 调用 getUniqueInstance() 后发现 uniqueInstance 不为空,因此返回 uniqueInstance,但此时 uniqueInstance 还未被初始化。 #### Synchronized 和 ReenTrantLock 的对比 1. **两者都是可重入锁**:两者都是可重入锁。“可重入锁”概念是:自己可以再次获取自己的内部锁。比如一个线程获得了某个对象的锁,此时这个对象锁还没有释放,当其再次想要获取这个对象的锁的时候还是可以获取的,如果不可锁重入的话,就会造成死锁。同一个线程每次获取锁,锁的计数器都自增1,所以要等到锁的计数器下降为0时才能释放锁。 2. **Synchronized 依赖于 JVM 而 ReenTrantLock 依赖于 API**:synchronized 是依赖于 JVM 实现的,前面我们也讲到了 虚拟机团队在 JDK1.6 为 synchronized 关键字进行了很多优化,但是这些优化都是在虚拟机层面实现的,并没有直接暴露给我们。ReenTrantLock 是 JDK 层面实现的(也就是 API 层面,需要 lock() 和 unlock 方法配合 try/finally 语句块来完成),所以我们可以通过查看它的源代码,来看它是如何实现的。 3. **ReenTrantLock 比 Synchronized 增加了一些高级功能** 1. **等待可中断**:过lock.lockInterruptibly()来实现这个机制。也就是说正在等待的线程可以选择放弃等待,改为处理其他事情。 2. **可实现公平锁** 3. **可实现选择性通知(锁可以绑定多个条件)**:线程对象可以注册在指定的Condition中,从而可以有选择性的进行线程通知,在调度线程上更加灵活。 在使用notify/notifyAll()方法进行通知时,被通知的线程是由 JVM 选择的,用ReentrantLock类结合Condition实例可以实现“选择性通知” 4. **性能已不是选择标准**:在jdk1.6之前synchronized 关键字吞吐量随线程数的增加,下降得非常严重。1.6之后,**synchronized 和 ReenTrantLock 的性能基本是持平了。** #### 底层原理 **synchronized 关键字底层原理属于 JVM 层面。** 1. **synchronized 同步语句块的情况** **synchronized 同步语句块的实现使用的是 monitorenter 和 monitorexit 指令,其中 monitorenter 指令指向同步代码块的开始位置,monitorexit 指令则指明同步代码块的结束位置。** 当执行 monitorenter 指令时,线程试图获取锁也就是获取 monitor(monitor对象存在于每个Java对象的对象头中,synchronized 锁便是通过这种方式获取锁的,也是为什么Java中任意对象可以作为锁的原因) 的持有权.当计数器为0则可以成功获取,获取后将锁计数器设为1也就是加1。相应的在执行 monitorexit 指令后,将锁计数器设为0,表明锁被释放。如果获取对象锁失败,那当前线程就要阻塞等待,直到锁被另外一个线程释放为止。 2. **synchronized 修饰方法的的情况** synchronized 修饰的方法并没有 monitorenter 指令和 monitorexit 指令,取得代之的确实是 ACC_SYNCHRONIZED 标识,该标识指明了该方法是一个同步方法,JVM 通过该 ACC_SYNCHRONIZED 访问标志来辨别一个方法是否声明为同步方法,从而执行相应的同步调用。 #### 1.6版本的优化 在 Java 早期版本中,synchronized 属于重量级锁,效率低下,因为监视器锁(monitor)是依赖于底层的操作系统的 **Mutex Lock** 来实现的,Java 的线程是映射到操作系统的原生线程之上的。如果要挂起或者唤醒一个线程,都需要操作系统帮忙完成,而操作系统实现线程之间的切换时需要从用户态转换到内核态,这个状态之间的转换需要相对比较长的时间,时间成本相对较高,这也是为什么早期的 synchronized 效率低的原因。庆幸的是在 Java 6 之后 Java 官方对从 JVM 层面对synchronized 较大优化,所以现在的 synchronized 锁效率也优化得很不错了。JDK1.6对锁的实现引入了大量的优化,如自旋锁、适应性自旋锁、锁消除、锁粗化、偏向锁、轻量级锁等技术来减少锁操作的开销。 锁主要存在四中状态,依次是:**无锁状态、偏向锁状态、轻量级锁状态、重量级锁状态**,他们会随着竞争的激烈而逐渐升级。注意锁可以升级不可降级,这种策略是为了提高获得锁和释放锁的效率。 1. **偏向锁** **引入偏向锁的目的和引入轻量级锁的目的很像,他们都是为了没有多线程竞争的前提下,减少传统的重量级锁使用操作系统互斥量产生的性能消耗。但是不同是:轻量级锁在无竞争的情况下使用 CAS 操作去代替使用互斥量。而偏向锁在无竞争的情况下会把整个同步都消除掉**。 偏向锁的“偏”就是偏心的偏,它的意思是会偏向于第一个获得它的线程,如果在接下来的执行中,该锁没有被其他线程获取,那么持有偏向锁的线程就不需要进行同步! 但是对于锁竞争比较激烈的场合,偏向锁就失效了,因为这样场合极有可能每次申请锁的线程都是不相同的,因此这种场合下不应该使用偏向锁,否则会得不偿失,需要注意的是,偏向锁失败后,并不会立即膨胀为重量级锁,而是先升级为轻量级锁。 升级过程: 1. 访问Mark Word中偏向锁的标识是否设置成1,锁标识位是否为01,确认偏向状态 2. 如果为可偏向状态,则判断当前线程ID是否为偏向线程 3. 如果偏向线程未当前线程,则通过cas操作竞争锁,如果竞争成功则操作Mark Word中线程ID设置为当前线程ID 4. 如果cas偏向锁获取失败,则挂起当前偏向锁线程,偏向锁升级为轻量级锁。 2. **轻量级锁** 倘若偏向锁失败,虚拟机并不会立即升级为重量级锁,它还会尝试使用一种称为轻量级锁的优化手段(1.6之后加入的)。**轻量级锁不是为了代替重量级锁,它的本意是在没有多线程竞争的前提下,减少传统的重量级锁使用操作系统互斥量产生的性能消耗,因为使用轻量级锁时,不需要申请互斥量。另外,轻量级锁的加锁和解锁都用到了CAS操作。** **轻量级锁能够提升程序同步性能的依据是“对于绝大部分锁,在整个同步周期内都是不存在竞争的”,这是一个经验数据。如果没有竞争,轻量级锁使用 CAS 操作避免了使用互斥操作的开销。但如果存在锁竞争,除了互斥量开销外,还会额外发生CAS操作,因此在有锁竞争的情况下,轻量级锁比传统的重量级锁更慢!如果锁竞争激烈,那么轻量级将很快膨胀为重量级锁!** 升级过程: 1. 线程由偏向锁升级为轻量级锁时,会先把锁的对象头MarkWord复制一份到线程的栈帧中,建立一个名为锁记录空间(Lock Record),用于存储当前Mark Word的拷贝。 2. 虚拟机使用cas操作尝试将对象的Mark Word指向Lock Record的指针,并将Lock record里的owner指针指对象的Mark Word。 3. 如果cas操作成功,则该线程拥有了对象的轻量级锁。第二个线程cas自旋锁等待锁线程释放锁。 4. 如果多个线程竞争锁,轻量级锁要膨胀为重量级锁,Mark Word中存储的就是指向重量级锁(互斥量)的指针。其他等待线程进入阻塞状态。 3. **自旋锁和自适应自旋** 轻量级锁失败后,虚拟机为了避免线程真实地在操作系统层面挂起,还会进行一项称为自旋锁的优化手段。 互斥同步对性能最大的影响就是阻塞的实现,因为挂起线程/恢复线程的操作都需要转入内核态中完成(用户态转换到内核态会耗费时间)。 **一般线程持有锁的时间都不是太长,所以仅仅为了这一点时间去挂起线程/恢复线程是得不偿失的。** 所以,虚拟机的开发团队就这样去考虑:“我们能不能让后面来的请求获取锁的线程等待一会而不被挂起呢?看看持有锁的线程是否很快就会释放锁”。**为了让一个线程等待,我们只需要让线程执行一个忙循环(自旋),这项技术就叫做自旋**。 **在 JDK1.6 中引入了自适应的自旋锁。自适应的自旋锁带来的改进就是:自旋的时间不在固定了,而是和前一次同一个锁上的自旋时间以及锁的拥有者的状态来决定,虚拟机变得越来越“聪明”了**。 4. **锁消除** 锁消除理解起来很简单,它指的就是虚拟机即使编译器在运行时,如果检测到那些共享数据不可能存在竞争,那么就执行锁消除。锁消除可以节省毫无意义的请求锁的时间。 5. **锁粗化** 原则上,我们在编写代码的时候,总是推荐将同步块的作用范围限制得尽量小,——直在共享数据的实际作用域才进行同步,这样是为了使得需要同步的操作数量尽可能变小,如果存在锁竞争,那等待线程也能尽快拿到锁。 6. 总结升级过程: 1. 检测Mark Word里面是不是当前线程的ID,如果是,表示当前线程处于偏向锁 2. 如果不是,则使用CAS将当前线程的ID替换Mard Word,如果成功则表示当前线程获得偏向锁,置偏向标志位1 3. 如果失败,则说明发生竞争,撤销偏向锁,进而升级为轻量级锁。 4. 当前线程使用CAS将对象头的Mark Word替换为锁记录指针,如果成功,当前线程获得锁 5. 如果失败,表示其他线程竞争锁,当前线程便尝试使用自旋来获取锁。 6. 如果自旋成功则依然处于轻量级状态。 7. 如果自旋失败,则升级为重量级锁。 ### Volatile #### Volatile的特性 1. **可见性** **volatile的可见性是指当一个变量被volatile修饰后,这个变量就对所有线程均可见。白话点就是说当一个线程修改了一个volatile修饰的变量后,其他线程可以立刻得知这个变量的修改,拿到最这个变量最新的值。** ```java public class VolatileVisibleDemo { // private boolean isReady = true; private volatile boolean isReady = true; void m() { System.out.println(Thread.currentThread().getName() + " m start..."); while (isReady) { } System.out.println(Thread.currentThread().getName() + " m end..."); } public static void main(String[] args) { VolatileVisibleDemo demo = new VolatileVisibleDemo(); new Thread(() -> demo.m(), "t1").start(); try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();} demo.isReady = false; // 刚才一秒过后开始执行 } } ``` **分析:一开始isReady为true,m方法中的while会一直循环,而主线程开启开线程之后会延迟1s将isReady赋值为false,若不加volatile修饰,则程序一直在运行,若加了volatile修饰,则程序最后会输出t1 m end...** 2. **有序性** **有序性是指程序代码的执行是按照代码的实现顺序来按序执行的;volatile的有序性特性则是指禁止JVM指令重排优化。** ```java public class Singleton { private static Singleton instance = null; // valotile //private static volatile Singleton instance = null; private Singleton() { } // 私有 public static Singleton getInstance() { // 双重校验 //第一次判断 if(instance == null) { synchronized (Singleton.class) { // 加锁 if(instance == null) { //初始化,并非原子操作 instance = new Singleton(); // 这一行代码展开其实分三步走 } } } return instance; } } ``` **上面的代码是一个很常见的单例模式实现方式,但是上述代码在多线程环境下是有问题的。为什么呢,问题出在instance对象的初始化上,因为`instance = new Singleton();`这个初始化操作并不是原子的,在JVM上会对应下面的几条指令:** ``` memory =allocate(); //1. 分配对象的内存空间 ctorInstance(memory); //2. 初始化对象 instance =memory; //3. 设置instance指向刚分配的内存地址 ``` **上面三个指令中,步骤2依赖步骤1,但是步骤3不依赖步骤2,所以JVM可能针对他们进行指令重拍序优化,重排后的指令如下:** ``` memory =allocate(); //1. 分配对象的内存空间 instance =memory; //3. 设置instance指向刚分配的内存地址 ctorInstance(memory); //2. 初始化对象 ``` **这样优化之后,内存的初始化被放到了instance分配内存地址的后面,这样的话当线程1执行步骤3这段赋值指令后,刚好有另外一个线程2进入getInstance方法判断instance不为null,这个时候线程2拿到的instance对应的内存其实还未初始化,这个时候拿去使用就会导致出错。** **所以我们在用这种方式实现单例模式时,会使用volatile关键字修饰instance变量,这是因为volatile关键字除了可以保证变量可见性之外,还具有防止指令重排序的作用。当用volatile修饰instance之后,JVM执行时就不会对上面提到的初始化指令进行重排序优化,这样也就不会出现多线程安全问题了。** 3. **不能保证原子性** **volatile关键字能保证变量的可见性和代码的有序性,但是不能保证变量的原子性,下面我再举一个volatile与原子性的例子:** ```java public class VolatileAtomicDemo { public static volatile int count = 0; public static void increase() { count++; } public static void main(String[] args) { Thread[] threads = new Thread[20]; for(int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { for(int j = 0; j < 1000; j++) { increase(); } }); threads[i].start(); } //等待所有累加线程结束 while (Thread.activeCount() > 1) { Thread.yield(); } System.out.println(count); } } ``` **上面这段代码创建了20个线程,每个线程对变量count进行1000次自增操作,如果这段代码并发正常的话,结果应该是20000,但实际运行过程中经常会出现小于20000的结果,因为count++这个自增操作不是原子操作。**[看图](https://www.processon.com/view/link/5e130e51e4b07db4cfac9d2c) ##### 内存屏障 **Java的Volatile的特征是任何读都能读到最新值,本质上是JVM通过内存屏障来实现的;为了实现volatile内存语义,JMM会分别限制重排序类型。下面是JMM针对编译器制定的volatile重排序规则表:** | 是否能重排序 | 第二个操作 | | | | :----------: | :--------: | :--------: | :--------: | | 第一个操作 | 普通读/写 | volatile读 | volatile写 | | 普通读/写 | | | no | | volatile读 | no | no | no | | volatile写 | | no | no | **从上表我们可以看出:** - 当第二个操作是volatile写时,不管第一个操作是什么,都不能重排序。这个规则确保volatile写之前的操作不会被编译器重排序到volatile写之后。 - 当第一个操作是volatile读时,不管第二个操作是什么,都不能重排序。这个规则确保volatile读之后的操作不会被编译器重排序到volatile读之前。 - 当第一个操作是volatile写,第二个操作是volatile读时,不能重排序。 **为了实现volatile的内存语义,编译器在生成字节码时,会在指令序列中插入内存屏障来禁止特定类型的处理器重排序。对于编译器来说,发现一个最优布置来最小化插入屏障的总数几乎不可能,为此,JMM采取保守策略。下面是基于保守策略的JMM内存屏障插入策略:** - 在每个volatile写操作的前面插入一个StoreStore屏障。 - 在每个volatile写操作的后面插入一个StoreLoad屏障。 - 在每个volatile读操作的后面插入一个LoadLoad屏障。 - 在每个volatile读操作的后面插入一个LoadStore屏障。 **volatile写插入内存指令图:** ![volatile](https://image-static.segmentfault.com/416/041/416041851-5ac871370fec9_articlex) **上图中的StoreStore屏障可以保证在volatile写之前,其前面的所有普通写操作已经对任意处理器可见了。这是因为StoreStore屏障将保障上面所有的普通写在volatile写之前刷新到主内存。** **这里比较有意思的是volatile写后面的StoreLoad屏障。这个屏障的作用是避免volatile写与后面可能有的volatile读/写操作重排序。因为编译器常常无法准确判断在一个volatile写的后面,是否需要插入一个StoreLoad屏障(比如,一个volatile写之后方法立即return)。为了保证能正确实现volatile的内存语义,JMM在这里采取了保守策略:在每个volatile写的后面或在每个volatile读的前面插入一个StoreLoad屏障。从整体执行效率的角度考虑,JMM选择了在每个volatile写的后面插入一个StoreLoad屏障。因为volatile写-读内存语义的常见使用模式是:一个写线程写volatile变量,多个读线程读同一个volatile变量。当读线程的数量大大超过写线程时,选择在volatile写之后插入StoreLoad屏障将带来可观的执行效率的提升。从这里我们可以看到JMM在实现上的一个特点:首先确保正确性,然后再去追求执行效率。** **volatile读插入内存指令图:** ![volatile读](https://image-static.segmentfault.com/288/764/2887649856-5ac871c442f52_articlex) **上图中的LoadLoad屏障用来禁止处理器把上面的volatile读与下面的普通读重排序。LoadStore屏障用来禁止处理器把上面的volatile读与下面的普通写重排序。** **上述volatile写和volatile读的内存屏障插入策略非常保守。在实际执行时,只要不改变volatile写-读的内存语义,编译器可以根据具体情况省略不必要的屏障。下面我们通过具体的示例代码来说明:** ```java class VolatileBarrierExample { int a; volatile int v1 = 1; volatile int v2 = 2; void readAndWrite() { int i = v1; //第一个volatile读 int j = v2; // 第二个volatile读 a = i + j; //普通写 v1 = i + 1; // 第一个volatile写 v2 = j * 2; //第二个 volatile写 } } ``` **针对readAndWrite()方法,编译器在生成字节码时可以做如下的优化:** ![readAndWrite](https://image-static.segmentfault.com/178/456/1784565222-5ac871e5e6dec_articlex) **注意,最后的StoreLoad屏障不能省略。因为第二个volatile写之后,方法立即return。此时编译器可能无法准确断定后面是否会有volatile读或写,为了安全起见,编译器常常会在这里插入一个StoreLoad屏障。** #### volatile汇编 ```java 0x000000011214bb49: mov %rdi,%rax 0x000000011214bb4c: dec %eax 0x000000011214bb4e: mov %eax,0x10(%rsi) 0x000000011214bb51: lock addl $0x0,(%rsp) ;*putfield v1 ; - com.earnfish.VolatileBarrierExample::readAndWrite@21 (line 35) 0x000000011214bb56: imul %edi,%ebx 0x000000011214bb59: mov %ebx,0x14(%rsi) 0x000000011214bb5c: lock addl $0x0,(%rsp) ;*putfield v2 ; - com.earnfish.VolatileBarrierExample::readAndWrite@28 (line 36) ``` ```java v1 = i - 1; // 第一个volatile写 v2 = j * i; // 第二个volatile写 ``` **可见其本质是通过一个lock指令来实现的。那么lock是什么意思呢?** **它的作用是使得本CPU的Cache写入了内存,该写入动作也会引起别的CPU invalidate其Cache。所以通过这样一个空操作,可让前面volatile变量的修改对其他CPU立即可见。** - 锁住内存 - 任何读必须在写完成之后再执行 - 使其它线程这个值的栈缓存失效 ### CAS **我们在读Concurrent包下的类的源码时,发现无论是**ReenterLock内部的AQS,还是各种Atomic开头的原子类,内部都应用到了`CAS` ```java public class Test { public AtomicInteger i; public void add() { i.getAndIncrement(); } } ``` **我们来看`getAndIncrement`的内部:** ```java public final int getAndIncrement() { return unsafe.getAndAddInt(this, valueOffset, 1); } ``` **再深入到`getAndAddInt`():** ```java public final int getAndAddInt(Object var1, long var2, int var4) { int var5; do { var5 = this.getIntVolatile(var1, var2); } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4)); return var5; } ``` **现在重点来了,`compareAndSwapInt(var1, var2, var5, var5 + var4)`其实换成`compareAndSwapInt(obj, offset, expect, update)`比较清楚,意思就是如果`obj`内的`value`和`expect`相等,就证明没有其他线程改变过这个变量,那么就更新它为`update`,如果这一步的`CAS`没有成功,那就采用自旋的方式继续进行`CAS`操作,取出乍一看这也是两个步骤了啊,其实在`JNI`里是借助于一个`CPU`指令完成的。所以还是原子操作。** #### CAS底层 ```c UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) UnsafeWrapper("Unsafe_CompareAndSwapInt"); oop p = JNIHandles::resolve(obj); jint* addr = (jint *) index_oop_from_field_offset_long(p, offset); return (jint)(Atomic::cmpxchg(x, addr, e)) == e; UNSAFE_END ``` **p是取出的对象,addr是p中offset处的地址,最后调用了`Atomic::cmpxchg(x, addr, e)`, 其中参数x是即将更新的值,参数e是原内存的值。代码中能看到cmpxchg有基于各个平台的实现。** #### ABA问题 描述: 第一个线程取到了变量 x 的值 A,然后巴拉巴拉干别的事,总之就是只拿到了变量 x 的值 A。这段时间内第二个线程也取到了变量 x 的值 A,然后把变量 x 的值改为 B,然后巴拉巴拉干别的事,最后又把变量 x 的值变为 A (相当于还原了)。在这之后第一个线程终于进行了变量 x 的操作,但是此时变量 x 的值还是 A,所以 compareAndSet 操作是成功。 **目前在JDK的atomic包里提供了一个类`AtomicStampedReference`来解决ABA问题。** ```java public class ABADemo { static AtomicInteger atomicInteger = new AtomicInteger(100); static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1); public static void main(String[] args) { System.out.println("=====ABA的问题产生====="); new Thread(() -> { atomicInteger.compareAndSet(100, 101); atomicInteger.compareAndSet(101, 100); }, "t1").start(); new Thread(() -> { // 保证线程1完成一次ABA问题 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicInteger.compareAndSet(100, 2020) + " " + atomicInteger.get()); }, "t2").start(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("=====解决ABA的问题====="); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); // 第一次获取版本号 System.out.println(Thread.currentThread().getName() + " 第1次版本号" + stamp); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t第2次版本号" + atomicStampedReference.getStamp()); atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t第3次版本号" + atomicStampedReference.getStamp()); }, "t3").start(); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); System.out.println(Thread.currentThread().getName() + "\t第1次版本号" + stamp); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } boolean result = atomicStampedReference.compareAndSet(100, 2020, stamp, stamp + 1); System.out.println(Thread.currentThread().getName() + "\t修改是否成功" + result + "\t当前最新实际版本号:" + atomicStampedReference.getStamp()); System.out.println(Thread.currentThread().getName() + "\t当前最新实际值:" + atomicStampedReference.getReference()); }, "t4").start(); } } ``` ### ThreadLocal **如果想实现每一个线程都有自己的专属本地变量该如何解决呢?** JDK中提供的`ThreadLocal`类正是为了解决这样的问题。 **`ThreadLocal`类主要解决的就是让每个线程绑定自己的值,可以将`ThreadLocal`类形象的比喻成存放数据的盒子,盒子中可以存储每个线程的私有数据。****如果你创建了一个`ThreadLocal`变量,那么访问这个变量的每个线程都会有这个变量的本地副本,这也是`ThreadLocal`变量名的由来。他们可以使用 `get()` 和 `set()` 方法来获取默认值或将其值更改为当前线程所存的副本的值,从而避免了线程安全问题。** #### 原理 ```java public class Thread implements Runnable { ...... //与此线程有关的ThreadLocal值。由ThreadLocal类维护 ThreadLocal.ThreadLocalMap threadLocals = null; //与此线程有关的InheritableThreadLocal值。由InheritableThreadLocal类维护 ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; ...... } ``` 从上面`Thread`类 源代码可以看出`Thread` 类中有一个 `threadLocals` 和 一个 `inheritableThreadLocals` 变量,它们都是 `ThreadLocalMap` 类型的变量,我们可以把 `ThreadLocalMap` 理解为`ThreadLocal` 类实现的定制化的 `HashMap`。默认情况下这两个变量都是null,只有当前线程调用 `ThreadLocal` 类的 `set`或`get`方法时才创建它们,实际上调用这两个方法的时候,我们调用的是`ThreadLocalMap`类对应的 `get()`、`set() `方法。 `ThreadLocal`类的`set()`方法 ```java public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } ``` **最终的变量是放在了当前线程的 `ThreadLocalMap` 中,并不是存在 `ThreadLocal` 上,ThreadLocal 可以理解为只是ThreadLocalMap的封装,传递了变量值。** **每个Thread中都具备一个ThreadLocalMap,而ThreadLocalMap可以存储以ThreadLocal为key的键值对。** 比如我们在同一个线程中声明了两个 `ThreadLocal` 对象的话,会使用 `Thread`内部都是使用仅有那个`ThreadLocalMap` 存放数据的,`ThreadLocalMap`的 key 就是 `ThreadLocal`对象,value 就是 `ThreadLocal` 对象调用`set`方法设置的值。`ThreadLocal` 是 map结构是为了让每个线程可以关联多个 `ThreadLocal`变量。这也就解释了ThreadLocal声明的变量为什么在每一个线程都有自己的专属本地变量。 #### 内存泄露 `ThreadLocalMap` 中使用的 key 为 `ThreadLocal` 的弱引用,而 value 是强引用。所以,如果 `ThreadLocal` 没有被外部强引用的情况下,在垃圾回收的时候会 key 会被清理掉,而 value 不会被清理掉。这样一来,`ThreadLocalMap` 中就会出现key为null的Entry。假如我们不做任何措施的话,value 永远无法被GC 回收,这个时候就可能会产生内存泄露。ThreadLocalMap实现中已经考虑了这种情况,在调用 `set()`、`get()`、`remove()` 方法的时候,会清理掉 key 为 null 的记录。使用完 `ThreadLocal`方法后 最好手动调用`remove()`方法 ### 并发集合容器 #### 为什么说ArrayList线程不安全? **看add方法的源码** ```java public boolean add(E e) { /** * 添加一个元素时,做了如下两步操作 * 1.判断列表的capacity容量是否足够,是否需要扩容 * 2.真正将元素放在列表的元素数组里面 */ ensureCapacityInternal(size + 1); // Increments modCount!! // 可能因为该操作,导致下一步发生数组越界 elementData[size++] = e; // 可能null值 return true; } ``` **数组越界** 1. 列表大小为9,即size=9 2. 线程A开始进入add方法,这时它获取到size的值为9,调用ensureCapacityInternal方法进行容量判断。 3. 线程B此时也进入add方法,它获取到size的值也为9,也开始调用ensureCapacityInternal方法。 4. 线程A发现需求大小为10,而elementData的大小就为10,可以容纳。于是它不再扩容,返回。 5. 线程B也发现需求大小为10,也可以容纳,返回。 6. 线程A开始进行设置值操作, elementData[size++] = e 操作。此时size变为10。 7. 线程B也开始进行设置值操作,它尝试设置elementData[10] = e,而elementData没有进行过扩容,它的下标最大为9。于是此时会报出一个数组越界的异常ArrayIndexOutOfBoundsException. **null值情况** **elementData[size++] = e不是一个原子操作**: 1. elementData[size] = e; 2. size = size + 1; 逻辑: 1. 列表大小为0,即size=0 2. 线程A开始添加一个元素,值为A。此时它执行第一条操作,将A放在了elementData下标为0的位置上。 3. 接着线程B刚好也要开始添加一个值为B的元素,且走到了第一步操作。此时线程B获取到size的值依然为0,于是它将B也放在了elementData下标为0的位置上。 4. 线程A开始将size的值增加为1 5. 线程B开始将size的值增加为2 **这样线程AB执行完毕后,理想中情况为size为2,elementData下标0的位置为A,下标1的位置为B。而实际情况变成了size为2,elementData下标为0的位置变成了B,下标1的位置上什么都没有。并且后续除非使用set方法修改此位置的值,否则将一直为null,因为size为2,添加元素时会从下标为2的位置上开始。** #### 解决非安全集合的并发都有哪些? [ArrayList->Vector->SynchronizedList->CopyOnWriteArrayList](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/src/com/juc/collectiontest/ContainerNotSafeDemo.java) [ArraySet->SynchronizedSet->CopyOnWriteArraySet](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/src/com/juc/collectiontest/HashSetTest.java) [HashMap->SynchronizedMap->ConcurrentHashMap](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/src/com/juc/collectiontest/MapSafe.java) ### 并发同步容器 #### AQS原理 AQS 使用一个 int 成员变量来表示同步状态,通过内置的 FIFO 队列来完成获取资源线程的排队工作。AQS 使用 CAS 对该同步状态进行原子操作实现对其值的修改。 ```java private volatile int state;//共享变量,使用volatile修饰保证线程可见性 ``` 状态信息通过 protected 类型的`getState`,`setState`,`compareAndSetState`进行操作 ```java //返回同步状态的当前值 protected final int getState() { return state; } // 设置同步状态的值 protected final void setState(int newState) { state = newState; } //原子地(CAS操作)将同步状态值设置为给定值update如果当前同步状态的值等于expect(期望值) protected final boolean compareAndSetState(int expect, int update) { return unsafe.compareAndSwapInt(this, stateOffset, expect, update); } ``` **AQS 定义两种资源共享方式** 1. **Exclusive**(独占)只有一个线程能执行,如 ReentrantLock。又可分为公平锁和非公平锁,ReentrantLock 同时支持两种锁。 总结:公平锁和非公平锁只有两处不同: 1. 非公平锁在调用 lock 后,首先就会调用 CAS 进行一次抢锁,如果这个时候恰巧锁没有被占用,那么直接就获取到锁返回了。 2. 非公平锁在 CAS 失败后,和公平锁一样都会进入到 tryAcquire 方法,在 tryAcquire 方法中,如果发现锁这个时候被释放了(state == 0),非公平锁会直接 CAS 抢锁,但是公平锁会判断等待队列是否有线程处于等待状态,如果有则不去抢锁,乖乖排到后面。 2. **Share**(共享)多个线程可同时执行,如 Semaphore/CountDownLatch。Semaphore、 CyclicBarrier、ReadWriteLock 。 **AQS 使用了模板方法模式,自定义同步器时需要重写下面几个 AQS 提供的模板方法:** ```java isHeldExclusively()//该线程是否正在独占资源。只有用到condition才需要去实现它。 tryAcquire(int)//独占方式。尝试获取资源,成功则返回true,失败则返回false。 tryRelease(int)//独占方式。尝试释放资源,成功则返回true,失败则返回false。 tryAcquireShared(int)//共享方式。尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。 tryReleaseShared(int)//共享方式。尝试释放资源,成功则返回true,失败则返回false。 ``` #### CountDownLatch CountDownLatch是共享锁的一种实现,它默认构造 AQS 的 state 值为 count。当线程使用countDown方法时,其实使用了`tryReleaseShared`方法以CAS的操作来减少state,直至state为0就代表所有的线程都调用了countDown方法。当调用await方法的时候,如果state不为0,就代表仍然有线程没有调用countDown方法,那么就把已经调用过countDown的线程都放入阻塞队列Park,并自旋CAS判断state == 0,直至最后一个线程调用了countDown,使得state == 0,于是阻塞的线程便判断成功,全部往下执行。 三种用法: 1. 某一线程在开始运行前等待 n 个线程执行完毕。将 CountDownLatch 的计数器初始化为 n :`new CountDownLatch(n)`,每当一个任务线程执行完毕,就将计数器减 1 `countdownlatch.countDown()`,当计数器的值变为 0 时,在`CountDownLatch上 await()` 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。 2. 实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。做法是初始化一个共享的 `CountDownLatch` 对象,将其计数器初始化为 1 :`new CountDownLatch(1)`,多个线程在开始执行任务前首先 `coundownlatch.await()`,当主线程调用 countDown() 时,计数器变为 0,多个线程同时被唤醒。 3. 死锁检测:一个非常方便的使用场景是,你可以使用 n 个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁。 ```java public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { countDownLatchTest(); // general(); } public static void general() { for (int i = 0; i < 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " 上完自习,离开教师"); }, "Thread --> " + i).start(); } while (Thread.activeCount() > 2) { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " ====班长最后走人"); } } public static void countDownLatchTest() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " 上完自习,离开教师"); countDownLatch.countDown(); }, "Thread --> " + i).start(); } countDownLatch.await(); System.out.println(Thread.currentThread().getName() + " ====班长最后走人"); } } ``` #### CyclicBarrier CyclicBarrier 的字面意思是可循环使用(Cyclic)的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活。CyclicBarrier 默认的构造方法是 `CyclicBarrier(int parties)`,其参数表示屏障拦截的线程数量,每个线程调用`await`方法告诉 CyclicBarrier 我已经到达了屏障,然后当前线程被阻塞。 ```java public class CyclicBarrierDemo { public static void main(String[] args) { cyclicBarrierTest(); } public static void cyclicBarrierTest() { CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> { System.out.println("====召唤神龙===="); }); for (int i = 0; i < 7; i++) { final int tempInt = i; new Thread(() -> { System.out.println(Thread.currentThread().getName() + " 收集到第" + tempInt + "颗龙珠"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }, "" + i).start(); } } } ``` 当调用 `CyclicBarrier` 对象调用 `await()` 方法时,实际上调用的是`dowait(false, 0L)`方法。 `await()` 方法就像树立起一个栅栏的行为一样,将线程挡住了,当拦住的线程数量达到 parties 的值时,栅栏才会打开,线程才得以通过执行。 ```java // 当线程数量或者请求数量达到 count 时 await 之后的方法才会被执行。上面的示例中 count 的值就为 5。 private int count; /** * Main barrier code, covering the various policies. */ private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this.lock; // 锁住 lock.lock(); try { final Generation g = generation; if (g.broken) throw new BrokenBarrierException(); // 如果线程中断了,抛出异常 if (Thread.interrupted()) { breakBarrier(); throw new InterruptedException(); } // cout减1 int index = --count; // 当 count 数量减为 0 之后说明最后一个线程已经到达栅栏了,也就是达到了可以执行await 方法之后的条件 if (index == 0) { // tripped boolean ranAction = false; try { final Runnable command = barrierCommand; if (command != null) command.run(); ranAction = true; // 将 count 重置为 parties 属性的初始化值 // 唤醒之前等待的线程 // 下一波执行开始 nextGeneration(); return 0; } finally { if (!ranAction) breakBarrier(); } } // loop until tripped, broken, interrupted, or timed out for (;;) { try { if (!timed) trip.await(); else if (nanos > 0L) nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { if (g == generation && ! g.broken) { breakBarrier(); throw ie; } else { // We're about to finish waiting even if we had not // been interrupted, so this interrupt is deemed to // "belong" to subsequent execution. Thread.currentThread().interrupt(); } } if (g.broken) throw new BrokenBarrierException(); if (g != generation) return index; if (timed && nanos <= 0L) { breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); } } ``` 总结:`CyclicBarrier` 内部通过一个 count 变量作为计数器,cout 的初始值为 parties 属性的初始化值,每当一个线程到了栅栏这里了,那么就将计数器减一。如果 count 值为 0 了,表示这是这一代最后一个线程到达栅栏,就尝试执行我们构造方法中输入的任务。 #### Semaphore **synchronized 和 ReentrantLock 都是一次只允许一个线程访问某个资源,Semaphore(信号量)可以指定多个线程同时访问某个资源。** ```java public class SemaphoreDemo { public static void main(String[] args) { Semaphore semaphore = new Semaphore(3);// 模拟三个停车位 for (int i = 0; i < 6; i++) { // 模拟6部汽车 new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " 抢到车位"); // 停车3s try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 停车3s后离开车位"); } catch (Exception e) { e.printStackTrace(); } finally { semaphore.release(); } }, "Car " + i).start(); } } } ``` ### 阻塞队列 - ArrayBlockingQueue:由数组结构组成的有界阻塞队列. - LinkedBlockingQueue:由链表结构组成的有界(但大小默认值Integer>MAX_VALUE)阻塞队列. - PriorityBlockingQueue:支持优先级排序的无界阻塞队列. - DelayQueue:使用优先级队列实现的延迟无界阻塞队列. - SynchronousQueue:不存储元素的阻塞队列,也即是单个元素的队列. - LinkedTransferQueue:由链表结构组成的无界阻塞队列. - LinkedBlockingDuque:由链表结构组成的双向阻塞队列. - 抛出异常方法:add remove - 不抛异常:offer poll - 阻塞 put take - 带时间 offer poll #### 生产者消费者 synchronized版本的生产者和消费者,比较繁琐 ```java public class ProdConsumerSynchronized { private final LinkedList<String> lists = new LinkedList<>(); public synchronized void put(String s) { while (lists.size() != 0) { // 用while怕有存在虚拟唤醒线程 // 满了, 不生产了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(s); System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst()); this.notifyAll(); // 这里可是通知所有被挂起的线程,包括其他的生产者线程 } public synchronized void get() { while (lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst()); this.notifyAll(); // 通知所有被wait挂起的线程 用notify可能就死锁了。 } public static void main(String[] args) { ProdConsumerSynchronized prodConsumerSynchronized = new ProdConsumerSynchronized(); // 启动消费者线程 for (int i = 0; i < 5; i++) { new Thread(prodConsumerSynchronized::get, "ConsA" + i).start(); } // 启动生产者线程 for (int i = 0; i < 5; i++) { int tempI = i; new Thread(() -> { prodConsumerSynchronized.put("" + tempI); }, "ProdA" + i).start(); } } } ``` ReentrantLock ```java public class ProdConsumerReentrantLock { private LinkedList<String> lists = new LinkedList<>(); private Lock lock = new ReentrantLock(); private Condition prod = lock.newCondition(); private Condition cons = lock.newCondition(); public void put(String s) { lock.lock(); try { // 1. 判断 while (lists.size() != 0) { // 等待不能生产 prod.await(); } // 2.干活 lists.add(s); System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst()); // 3. 通知 cons.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void get() { lock.lock(); try { // 1. 判断 while (lists.size() == 0) { // 等待不能消费 cons.await(); } // 2.干活 System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst()); // 3. 通知 prod.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { ProdConsumerReentrantLock prodConsumerReentrantLock = new ProdConsumerReentrantLock(); for (int i = 0; i < 5; i++) { int tempI = i; new Thread(() -> { prodConsumerReentrantLock.put(tempI + ""); }, "ProdA" + i).start(); } for (int i = 0; i < 5; i++) { new Thread(prodConsumerReentrantLock::get, "ConsA" + i).start(); } } } ``` BlockingQueue ```java public class ProdConsumerBlockingQueue { private volatile boolean flag = true; private AtomicInteger atomicInteger = new AtomicInteger(); BlockingQueue<String> blockingQueue = null; public ProdConsumerBlockingQueue(BlockingQueue<String> blockingQueue) { this.blockingQueue = blockingQueue; } public void myProd() throws Exception { String data = null; boolean retValue; while (flag) { data = atomicInteger.incrementAndGet() + ""; retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS); if (retValue) { System.out.println(Thread.currentThread().getName() + " 插入队列" + data + " 成功"); } else { System.out.println(Thread.currentThread().getName() + " 插入队列" + data + " 失败"); } TimeUnit.SECONDS.sleep(1); } System.out.println(Thread.currentThread().getName() + " 大老板叫停了,flag=false,生产结束"); } public void myConsumer() throws Exception { String result = null; while (flag) { result = blockingQueue.poll(2, TimeUnit.SECONDS); if (null == result || result.equalsIgnoreCase("")) { flag = false; System.out.println(Thread.currentThread().getName() + " 超过2s没有取到蛋糕,消费退出"); return; } System.out.println(Thread.currentThread().getName() + " 消费队列" + result + "成功"); } } public void stop() { flag = false; } public static void main(String[] args) { ProdConsumerBlockingQueue prodConsumerBlockingQueue = new ProdConsumerBlockingQueue(new ArrayBlockingQueue<>(10)); new Thread(() -> { System.out.println(Thread.currentThread().getName() + " 生产线程启动"); try { prodConsumerBlockingQueue.myProd(); } catch (Exception e) { e.printStackTrace(); } }, "Prod").start(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + " 消费线程启动"); try { prodConsumerBlockingQueue.myConsumer(); } catch (Exception e) { e.printStackTrace(); } }, "Consumer").start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("5s后main叫停,线程结束"); prodConsumerBlockingQueue.stop(); } } ``` ### 线程池 #### 线程池的好处 - **降低资源消耗**。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。 - **提高响应速度**。当任务到达时,任务可以不需要的等到线程创建就能立即执行。 - **提高线程的可管理性**。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。 #### FixedThreadPool `FixedThreadPool` 被称为可重用固定线程数的线程池。通过 Executors 类中的相关源代码来看一下相关实现: ```java /** * 创建一个可重用固定数量线程的线程池 */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } ``` **从上面源代码可以看出新创建的 `FixedThreadPool` 的 `corePoolSize` 和 `maximumPoolSize` 都被设置为 nThreads,这个 nThreads 参数是我们使用的时候自己传递的。** 1. 如果当前运行的线程数小于 corePoolSize, 如果再来新任务的话,就创建新的线程来执行任务; 2. 当前运行的线程数等于 corePoolSize 后, 如果再来新任务的话,会将任务加入 `LinkedBlockingQueue`; 3. 线程池中的线程执行完 手头的任务后,会在循环中反复从 `LinkedBlockingQueue` 中获取任务来执行; 不推荐使用 **`FixedThreadPool` 使用无界队列 `LinkedBlockingQueue`(队列的容量为 Intger.MAX_VALUE)作为线程池的工作队列会对线程池带来如下影响 :** 1. 当线程池中的线程数达到 `corePoolSize` 后,新任务将在无界队列中等待,因此线程池中的线程数不会超过 corePoolSize; 2. 由于使用无界队列时 `maximumPoolSize` 将是一个无效参数,因为不可能存在任务队列满的情况。所以,通过创建 `FixedThreadPool`的源码可以看出创建的 `FixedThreadPool` 的 `corePoolSize` 和 `maximumPoolSize` 被设置为同一个值。 3. 由于 1 和 2,使用无界队列时 `keepAliveTime` 将是一个无效参数; 4. 运行中的 `FixedThreadPool`(未执行 `shutdown()`或 `shutdownNow()`)不会拒绝任务,在任务比较多的时候会导致 OOM(内存溢出)。 #### SingleThreadExecutor ```java /** *返回只有一个线程的线程池 */ public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory)); } ``` 和上面一个差不多,只不过core和max都被设置为1 #### CachedThreadPool ```java /** * 创建一个线程池,根据需要创建新线程,但会在先前构建的线程可用时重用它。 */ public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); } ``` `CachedThreadPool` 的` corePoolSize` 被设置为空(0),`maximumPoolSize `被设置为 Integer.MAX.VALUE,即它是无界的,这也就意味着如果主线程提交任务的速度高于 `maximumPool` 中线程处理任务的速度时,`CachedThreadPool` 会不断创建新的线程。极端情况下,这样会导致耗尽 cpu 和内存资源。 1. 首先执行 `SynchronousQueue.offer(Runnable task)` 提交任务到任务队列。如果当前 `maximumPool` 中有闲线程正在执行 `SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)`,那么主线程执行 offer 操作与空闲线程执行的 `poll` 操作配对成功,主线程把任务交给空闲线程执行,`execute()`方法执行完成,否则执行下面的步骤 2; 2. 当初始 `maximumPool` 为空,或者 `maximumPool` 中没有空闲线程时,将没有线程执行 `SynchronousQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)`。这种情况下,步骤 1 将失败,此时 `CachedThreadPool` 会创建新线程执行任务,execute 方法执行完成; #### ScheduledThreadPoolExecutor省略,基本不会用 #### ThreadPoolExecutor(重点) ```java /** * 用给定的初始参数创建一个新的ThreadPoolExecutor。 */ public ThreadPoolExecutor(int corePoolSize,//线程池的核心线程数量 int maximumPoolSize,//线程池的最大线程数 long keepAliveTime,//当线程数大于核心线程数时,多余的空闲线程存活的最长时间 TimeUnit unit,//时间单位 BlockingQueue<Runnable> workQueue,//任务队列,用来储存等待执行任务的队列 ThreadFactory threadFactory,//线程工厂,用来创建线程,一般默认即可 RejectedExecutionHandler handler//拒绝策略,当提交的任务过多而不能及时处理时,我们可以定制策略来处理任务 ) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; } ``` **`ThreadPoolExecutor` 3 个最重要的参数:** - **`corePoolSize` :** 核心线程数线程数定义了最小可以同时运行的线程数量。 - **`maximumPoolSize` :** 当队列中存放的任务达到队列容量的时候,当前可以同时运行的线程数量变为最大线程数。 - **`workQueue`:** 当新任务来的时候会先判断当前运行的线程数量是否达到核心线程数,如果达到的话,信任就会被存放在队列中。 `ThreadPoolExecutor`其他常见参数: - **`keepAliveTime`**:当线程池中的线程数量大于 `corePoolSize` 的时候,如果这时没有新的任务提交,核心线程外的线程不会立即销毁,而是会等待,直到等待的时间超过了 `keepAliveTime`才会被回收销毁; - **`unit`** : `keepAliveTime` 参数的时间单位。 - **`threadFactory`** :executor 创建新线程的时候会用到。 - **`handler`** :饱和策略。关于饱和策略下面单独介绍一下. ![线程池各个参数的关系](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/线程池各个参数的关系.jpg) 如果当前同时运行的线程数量达到最大线程数量并且队列也已经被放满了任时,`ThreadPoolTaskExecutor` 定义一些策略: - **`ThreadPoolExecutor.AbortPolicy`**:抛出 `RejectedExecutionException`来拒绝新任务的处理。 - **`ThreadPoolExecutor.CallerRunsPolicy`**:调用执行自己的线程运行任务。您不会任务请求。但是这种策略会降低对于新任务提交速度,影响程序的整体性能。另外,这个策略喜欢增加队列容量。如果您的应用程序可以承受此延迟并且你不能任务丢弃任何一个任务请求的话,你可以选择这个策略。 - **`ThreadPoolExecutor.DiscardPolicy`:** 不处理新任务,直接丢弃掉。 - **`ThreadPoolExecutor.DiscardOldestPolicy`:** 此策略将丢弃最早的未处理的任务请求。 > Spring 通过 `ThreadPoolTaskExecutor` 或者我们直接通过 `ThreadPoolExecutor` 的构造函数创建线程池的时候,当我们不指定 `RejectedExecutionHandler` 饱和策略的话来配置线程池的时候默认使用的是 `ThreadPoolExecutor.AbortPolicy`。在默认情况下,`ThreadPoolExecutor` 将抛出 `RejectedExecutionException` 来拒绝新来的任务 ,这代表你将丢失对这个任务的处理。 对于可伸缩的应用程序,建议使用 `ThreadPoolExecutor.CallerRunsPolicy`。当最大池被填满时,此策略为我们提供可伸缩队列。(这个直接查看 `ThreadPoolExecutor` 的构造函数源码就可以看出,比较简单的原因,这里就不贴代码了。) > Executors 返回线程池对象的弊端如下: > > - **`FixedThreadPool` 和 `SingleThreadExecutor`** : 允许请求的队列长度为 Integer.MAX_VALUE,可能堆积大量的请求,从而导致 OOM。 > - **CachedThreadPool 和 ScheduledThreadPool** : 允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。 ```java public class ThreadPoolExecutorDemo { public static void main(String[] args) { ExecutorService threadpools = new ThreadPoolExecutor( 3, 5, 1l, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); //new ThreadPoolExecutor.AbortPolicy(); //new ThreadPoolExecutor.CallerRunsPolicy(); //new ThreadPoolExecutor.DiscardOldestPolicy(); //new ThreadPoolExecutor.DiscardPolicy(); try { for (int i = 0; i < 8; i++) { threadpools.execute(() -> { System.out.println(Thread.currentThread().getName() + "\t办理业务"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadpools.shutdown(); } } } ``` ### Java锁机制 #### 公平锁/非公平锁 **公平锁指多个线程按照申请锁的顺序来获取锁。非公平锁指多个线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取锁。有可能,会造成优先级反转或者饥饿现象(很长时间都没获取到锁-非洲人...),ReentrantLock,了解一下。** #### 可重入锁 **可重入锁又名递归锁,是指在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁,典型的synchronized,了解一下** ```java synchronized void setA() throws Exception { Thread.sleep(1000); setB(); // 因为获取了setA()的锁,此时调用setB()将会自动获取setB()的锁,如果不自动获取的话方法B将不会执行 } synchronized void setB() throws Exception { Thread.sleep(1000); } ``` #### 独享锁/共享锁 - 独享锁:是指该锁一次只能被一个线程所持有。 - 共享锁:是该锁可被多个线程所持有。 #### 互斥锁/读写锁 **上面讲的独享锁/共享锁就是一种广义的说法,互斥锁/读写锁就是其具体的实现** #### 乐观锁/悲观锁 1. **乐观锁与悲观锁不是指具体的什么类型的锁,而是指看待兵法同步的角度。** 2. **悲观锁认为对于同一个人数据的并发操作,一定是会发生修改的,哪怕没有修改,也会认为修改。因此对于同一个数据的并发操作,悲观锁采取加锁的形式。悲观的认为,不加锁的并发操作一定会出现问题。** 3. **乐观锁则认为对于同一个数据的并发操作,是不会发生修改的。在更新数据的时候,会采用尝试更新,不断重新的方式更新数据。乐观的认为,不加锁的并发操作时没有事情的。** 4. **悲观锁适合写操作非常多的场景,乐观锁适合读操作非常多的场景,不加锁带来大量的性能提升。** 5. **悲观锁在Java中的使用,就是利用各种锁。乐观锁在Java中的使用,是无锁编程,常常采用的是CAS算法,典型的例子就是原子类,通过CAS自旋实现原子类操作的更新。重量级锁是悲观锁的一种,自旋锁、轻量级锁与偏向锁属于乐观锁** #### 分段锁 1. **分段锁其实是一种锁的设计,并不是具体的一种锁,对于ConcurrentHashMap而言,其并发的实现就是通过分段锁的形式来哦实现高效的并发操作。** 2. ** 以ConcurrentHashMap来说一下分段锁的含义以及设计思想,ConcurrentHashMap中的分段锁称为Segment,它即类似于HashMap(JDK7与JDK8中HashMap的实现)的结构,即内部拥有一个Entry数组,数组中的每个元素又是一个链表;同时又是ReentrantLock(Segment继承了ReentrantLock)** 3. **当需要put元素的时候,并不是对整个hashmap进行加锁,而是先通过hashcode来知道他要放在那一个分段中,然后对这个分段进行加锁,所以当多线程put的时候,只要不是放在一个分段中,就实现了真正的并行的插入。但是,在统计size的时候,可就是获取hashmap全局信息的时候,就需要获取所有的分段锁才能统计。** 4. **分段锁的设计目的是细化锁的粒度,当操作不需要更新整个数组的时候,就仅仅针对数组中的一项进行加锁操作。** #### 偏向锁/轻量级锁/重量级锁 1. **这三种锁是锁的状态,并且是针对Synchronized。在Java5通过引入锁升级的机制来实现高效Synchronized。这三种锁的状态是通过对象监视器在对象头中的字段来表明的。偏向锁是指一段同步代码一直被一个线程所访问,那么该线程会自动获取锁。降低获取锁的代价。** 2. **偏向锁的适用场景:始终只有一个线程在执行代码块,在它没有执行完释放锁之前,没有其它线程去执行同步快,在锁无竞争的情况下使用,一旦有了竞争就升级为轻量级锁,升级为轻量级锁的时候需要撤销偏向锁,撤销偏向锁的时候会导致stop the word操作;在有锁竞争时,偏向锁会多做很多额外操作,尤其是撤销偏向锁的时候会导致进入安全点,安全点会导致stw,导致性能下降,这种情况下应当禁用。** 3. **轻量级锁是指当锁是偏向锁的时候,被另一个线程锁访问,偏向锁就会升级为轻量级锁,其他线程会通过自选的形式尝试获取锁,不会阻塞,提高性能。** 4. **重量级锁是指当锁为轻量级锁的时候,另一个线程虽然是自旋,但自旋不会一直持续下去,当自旋一定次数的时候,还没有获取到锁,就会进入阻塞,该锁膨胀为重量级锁。重量级锁会让其他申请的线程进入阻塞,性能降低。** #### 自旋锁 1. **在Java中,自旋锁是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。** 2. **自旋锁原理非常简单,如果持有锁的线程能在很短时间内释放锁资源,那么那些等待竞争锁的线程就不需要做内核态和用户态之间的切换进入阻塞挂起状态,它们只需要等一等(自旋),等持有锁的线程释放锁后即可立即获取锁,这样就避免用户线程和内核的切换的消耗。** 3. **自旋锁尽可能的减少线程的阻塞,适用于锁的竞争不激烈,且占用锁时间非常短的代码来说性能能大幅度的提升,因为自旋的消耗会小于线程阻塞挂起再唤醒的操作的消耗。** 4. **但是如果锁的竞争激烈,或者持有锁的线程需要长时间占用锁执行同步块,这时候就不适用使用自旋锁了,因为自旋锁在获取锁前一直都是占用cpu做无用功,同时有大量线程在竞争一个锁,会导致获取锁的时间很长,线程自旋的消耗大于线程阻塞挂起操作的消耗,其它需要cpu的线程又不能获取到cpu,造成cpu的浪费。** #### Java锁总结 **Java锁机制可归为Sychornized锁和Lock锁两类。Synchronized是基于JVM来保证数据同步的,而Lock则是硬件层面,依赖特殊的CPU指令来实现数据同步的。** - Synchronized是一个非公平、悲观、独享、互斥、可重入的重量级锁。 - ReentrantLock是一个默认非公平但可实现公平的、悲观、独享、互斥、可重入、重量级锁。 - ReentrantReadWriteLock是一个默认非公平但可实现公平的、悲观、写独享、读共享、读写、可重入、重量级锁。<file_sep>package normal; /** * @program JavaBooks * @description: 104. 二叉树的最大深度 * @author: mf * @create: 2019/11/08 15:23 */ /* 题目:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/ 类型:树 难度:easy */ /* 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 */ public class MaxDepth { public static void main(String[] args) { } private static int maxDepth(TreeNode root) { return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } } <file_sep>/** * @program JavaBooks * @description: 只出现一次的数字 * @author: mf * @create: 2020/04/11 18:05 */ package subject.bit; /** * 输入: [2,2,1] * 输出: 1 * 输入: [4,1,2,1,2] * 输出: 4 */ public class T2 { public int singleNumber(int[] nums) { if (nums.length == 1) return nums[0]; int ans = nums[0]; for (int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } } <file_sep>package books; /** * @program JavaBooks * @description: 二叉树 * @author: mf * @create: 2019/09/06 10:05 */ public class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } // 给定一个前序和中序数组,生成一颗二叉树 // 根据T7笔试题 public static TreeNode setBinaryTree(int[] pre, int[] in) { TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1); return root; } private static TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { if (startPre > endPre || startIn > endIn) { return null; } TreeNode root = new TreeNode(pre[startPre]); for (int i = startIn; i <= endIn; i++) { if (in[i] == pre[startPre]) { root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1); root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn); } } return root; } // 递归打印前序 public static void preOrderRe(TreeNode root) { System.out.println(root.val); TreeNode leftNode = root.left; if (leftNode != null) { preOrderRe(leftNode); } TreeNode rightNode = root.right; if (rightNode != null) { preOrderRe(rightNode); } } // 递归打印中序 public static void midOrderRe(TreeNode node) { if (node == null) { return; } else { midOrderRe(node.left); System.out.println(node.val); midOrderRe(node.right); } } // 递归打印后序 public static void postOrderRe(TreeNode node) { if (node == null) { return; } else { postOrderRe(node.left); postOrderRe(node.right); System.out.println(node.val); } } } <file_sep>## 引言 **Java的集合框架,ArrayList源码解析等...** <!-- more --> ## 概述 - *ArrayList*实现了*List*接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入`null`元素,底层通过**数组实现**。 - 除该类未实现同步外,其余跟*Vector*大致相同。 - 每个*ArrayList*都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多于当前容量。 - 当向容器中添加元素时,如果容量不足,容器会自动增大底层数组的大小。 - 前面已经提过,Java泛型只是编译器提供的语法糖,所以这里的数组是一个Object数组,以便能够容纳任何类型的对象。 ![](https://www.pdai.tech/_images/collection/ArrayList_base.png) - size(), isEmpty(), get(), set()方法均能在常数时间内完成,add()方法的时间开销跟插入位置有关,addAll()方法的时间开销跟添加元素的个数成正比。其余方法大都是线性时间。 - 为追求效率,ArrayList没有实现同步(synchronized),如果需要多个线程并发访问,用户可以手动同步,也可使用Vector替代。 ## ArrayList的实现 ### 底层数据结构 ```java transient Object[] elementData; // Object 数组 private int size; // 大小 ``` ### 构造函数 ```java // 参数为容量的构造参数 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; // 默认 } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } // 无参的构造参数 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; // 默认容量 } public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } } ``` ### 自动扩容 - 每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。 - 数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。 - 数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的1.5倍。 - 这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。 - 当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就指定其容量,以避免数组扩容的发生。 - 或者根据实际需求,通过调用ensureCapacity方法来手动增加ArrayList实例的容量。 - ```java public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } ``` - ![扩容](https://www.pdai.tech/_images/collection/ArrayList_grow.png) ### add(),addAll() - 跟C++ 的*vector*不同,*ArrayList*没有`push_back()`方法,对应的方法是`add(E e)`,*ArrayList*也没有`insert()`方法,对应的方法是`add(int index, E e)`。 - 这两个方法都是向容器中添加新元素,这可能会导致*capacity*不足,因此在添加元素之前,都需要进行剩余空间检查,如果需要则自动扩容。扩容操作最终是通过`grow()`方法完成的。 - ```java public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } ``` - ![add](https://www.pdai.tech/_images/collection/ArrayList_add.png) - `add(int index, E e)`需要先对元素进行移动,然后完成插入操作,也就意味着该方法有着线性的时间复杂度。 - `addAll()`方法能够一次添加多个元素,根据位置不同也有两个把本,一个是在末尾添加的`addAll(Collection<? extends E> c)`方法,一个是从指定位置开始插入的`addAll(int index, Collection<? extends E> c)`方法。跟`add()`方法类似,在插入之前也需要进行空间检查,如果需要则自动扩容;如果从指定位置插入,也会存在移动元素的情况。 `addAll()`的时间复杂度不仅跟插入元素的多少有关,也跟插入的位置相关。 - ```java public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } ``` ### set() 既然底层是一个数组*ArrayList*的`set()`方法也就变得非常简单,直接对数组的指定位置赋值即可。 ```java public E set(int index, E element) { rangeCheck(index);//下标越界检查 E oldValue = elementData(index); elementData[index] = element;//赋值到指定位置,复制的仅仅是引用 return oldValue; } ``` ### get() `get()`方法同样很简单,唯一要注意的是由于底层数组是Object[],得到元素后需要进行类型转换。 ```java public E get(int index) { rangeCheck(index); return (E) elementData[index];//注意类型转换 } ``` ### remove() `remove()`方法也有两个版本,一个是`remove(int index)`删除指定位置的元素,另一个是`remove(Object o)`删除第一个满足`o.equals(elementData[index])`的元素。删除操作是`add()`操作的逆过程,需要将删除点之后的元素向前移动一个位置。需要注意的是为了让GC起作用,必须显式的为最后一个位置赋`null`值。 ```java public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; //清除该位置的引用,让GC起作用 return oldValue; } ``` 关于Java GC这里需要特别说明一下,**有了垃圾收集器并不意味着一定不会有内存泄漏**。对象能否被GC的依据是是否还有引用指向它,上面代码中如果不手动赋`null`值,除非对应的位置被其他元素覆盖,否则原来的对象就一直不会被回收。 ### trimToSize() ArrayList还给我们提供了将底层数组的容量调整为当前列表保存的实际元素的大小的功能。它可以通过trimToSize方法来实现。代码如下: ```java public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } ``` ### indexOf(), lastIndexOf() ```java public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } ``` ### Fail-Fast机制: ArrayList也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。<file_sep>## 引言 ## 场景 > **面试官:"知道事务的四大特性么?"** > > **你:"懂,ACID嘛,原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)!"** > > **面试官:"你们是用mysql数据库吧,能简单说说innodb中怎么实现这四大特性的么?“ 你:"我只知道隔离性是怎么做的balabala~~"** > **面试官:"还是回去等通知吧~"** <!-- more --> ## 举例 我们以从A账户转账50元到B账户为例进行说明一下ACID,四大特性。 ## 原子性 根据定义,原子性是指一个事务是一个不可分割的工作单位,其中的操作要么都做,要么都不做。即要么转账成功,要么转账失败,是不存在中间的状态! **如果无法保证原子性会怎么样?** OK,就会出现**数据不一致**的情形,A账户减去50元,而B账户增加50元操作失败。系统将无故丢失50元~ ## 隔离性 根据定义,隔离性是指多个事务并发执行的时候,事务内部的操作与其他事务是隔离的,并发执行的各个事务之间不能互相干扰。 **如果无法保证隔离性会怎么样?** OK,假设A账户有200元,B账户0元。A账户往B账户转账两次,金额为50元,分别在两个事务中执行。如果无法保证隔离性,会出现下面的情形 ![](https://pic2.zhimg.com/80/v2-e2e899c5187386e58d495a755894f635_hd.jpg) 如图所示,如果不保证隔离性,A扣款两次,而B只加款一次,凭空消失了50元,依然出现了**数据不一致**的情形! ## 持久性 根据定义,持久性是指事务一旦提交,它对数据库的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。 **如果无法保证持久性会怎么样?** 在Mysql中,为了解决CPU和磁盘速度不一致问题,Mysql是将磁盘上的数据加载到内存,对内存进行操作,然后再回写磁盘。好,假设此时宕机了,在内存中修改的数据全部丢失了,持久性就无法保证。 设想一下,系统提示你转账成功。但是你发现金额没有发生任何改变,此时数据出现了不合法的数据状态,我们将这种状态认为是**数据不一致**的情形。 ## 一致性 根据定义,一致性是指事务执行前后,数据处于一种合法的状态,这种状态是语义上的而不是语法上的。 那什么是合法的数据状态呢? oK,这个状态是满足预定的约束就叫做合法的状态,再通俗一点,这状态是由你自己来定义的。满足这个状态,数据就是一致的,不满足这个状态,数据就是不一致的! **如果无法保证一致性会怎么样?** - 例一:A账户有200元,转账300元出去,此时A账户余额为-100元。你自然就发现了此时数据是不一致的,为什么呢?因为你定义了一个状态,余额这列必须大于0。 - 例二:A账户200元,转账50元给B账户,A账户的钱扣了,但是B账户因为各种意外,余额并没有增加。你也知道此时数据是不一致的,为什么呢?因为你定义了一个状态,要求A+B的余额必须不变。 ## 解答 #### 问题一:Mysql怎么保证一致性的? OK,这个问题分为两个层面来说。 从数据库层面,数据库通过原子性、隔离性、持久性来保证一致性。也就是说ACID四大特性之中,C(一致性)是目的,A(原子性)、I(隔离性)、D(持久性)是手段,是为了保证一致性,数据库提供的手段。数据库必须要实现AID三大特性,才有可能实现一致性。例如,原子性无法保证,显然一致性也无法保证。 但是,如果你在事务里故意写出违反约束的代码,一致性还是无法保证的。例如,你在转账的例子中,你的代码里故意不给B账户加钱,那一致性还是无法保证。因此,还必须从应用层角度考虑。 从应用层面,通过代码判断数据库数据是否有效,然后决定回滚还是提交数据! #### 问题二: Mysql怎么保证原子性的? OK,是利用Innodb的`undo log`。 `undo log`名为回滚日志,是实现原子性的关键,当事务回滚时能够撤销所有已经成功执行的sql语句,他需要记录你要回滚的相应日志信息。 例如 - (1)当你delete一条数据的时候,就需要记录这条数据的信息,回滚的时候,insert这条旧数据 - (2)当你update一条数据的时候,就需要记录之前的旧值,回滚的时候,根据旧值执行update操作 - (3)当年insert一条数据的时候,就需要这条记录的主键,回滚的时候,根据主键执行delete操作 `undo log`记录了这些回滚需要的信息,当事务执行失败或调用了rollback,导致事务需要回滚,便可以利用undo log中的信息将数据回滚到修改之前的样子。 #### 问题三: Mysql怎么保证持久性的? OK,是利用Innodb的`redo log`。 正如之前说的,Mysql是先把磁盘上的数据加载到内存中,在内存中对数据进行修改,再刷回磁盘上。如果此时突然宕机,内存中的数据就会丢失。 *怎么解决这个问题?* 简单啊,事务提交前直接把数据写入磁盘就行啊。 *这么做有什么问题?* - 只修改一个页面里的一个字节,就要将整个页面刷入磁盘,太浪费资源了。毕竟一个页面16kb大小,你只改其中一点点东西,就要将16kb的内容刷入磁盘,听着也不合理。 - 毕竟一个事务里的SQL可能牵涉到多个数据页的修改,而这些数据页可能不是相邻的,也就是属于随机IO。显然操作随机IO,速度会比较慢。 于是,决定采用`redo log`解决上面的问题。当做数据修改的时候,不仅在内存中操作,还会在`redo log`中记录这次操作。当事务提交的时候,会将`redo log`日志进行刷盘(`redo log`一部分在内存中,一部分在磁盘上)。当数据库宕机重启的时候,会将`redo log`中的内容恢复到数据库中,再根据`undo log`和`binlog`内容决定回滚数据还是提交数据。 **采用redo log的好处?** 其实好处就是将`redo log`进行刷盘比对数据页刷盘效率高,具体表现如下 - `redo log`体积小,毕竟只记录了哪一页修改了啥,因此体积小,刷盘快。 - `redo log`是一直往末尾进行追加,属于顺序IO。效率显然比随机IO来的快。 #### 问题四: Mysql怎么保证隔离性的? OK,利用的是锁和MVCC机制。还是拿转账例子来说明,有一个账户表如下 表名`t_balance` ![](https://pic4.zhimg.com/80/v2-86bedce66efcc4a3b90d09740163e3a7_hd.jpg) 其中id是主键,user_id为账户名,balance为余额。还是以转账两次为例,如下图所示 ![](https://pic2.zhimg.com/80/v2-9e136615fa9a741763dfc7ba2f976a99_hd.jpg) 至于MVCC,即多版本并发控制(Multi Version Concurrency Control),一个行记录数据有多个版本对快照数据,这些快照数据在`undo log`中。 如果一个事务读取的行正在做DELELE或者UPDATE操作,读取操作不会等行上的锁释放,而是读取该行的快照版本。 由于MVCC机制在可重复读(Repeateable Read)和读已提交(Read Commited)的MVCC表现形式不同,就不赘述了。 但是有一点说明一下,在事务隔离级别为读已提交(Read Commited)时,一个事务能够读到另一个事务已经提交的数据,是不满足隔离性的。但是当事务隔离级别为可重复读(Repeateable Read)中,是满足隔离性的。<file_sep>/** * @program JavaBooks * @description: 从尾到头打印链表 * @author: mf * @create: 2020/03/06 18:40 */ package subject.linked; import java.util.ArrayList; import java.util.Stack; /** * 原先: * 1->2->3->4 * 之后: * 1<-2<-3<-4 */ public class T1 { ArrayList<Integer> list = new ArrayList(); /** * 递归 * @param listNode * @return */ public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if (listNode != null) { this.printListFromTailToHead(listNode.next); list.add(listNode.val); } return list; } /** * 栈试试 * @param listNode * @return */ public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) { Stack<Integer> stack = new Stack<>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.empty()) { list.add(stack.pop()); } return list; } } <file_sep>- [数据库引擎innodb与myisam的区别?](/Interview/mysql/sql-存储引擎.md) - [Mysql的ACID原理](/Interview/mysql/Mysql中ACID的原理.md) - [并发事务带来的问题](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E5%B9%B6%E5%8F%91%E4%BA%8B%E5%8A%A1%E5%B8%A6%E6%9D%A5%E7%9A%84%E9%97%AE%E9%A2%98) - [数据库的隔离级别](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9A%84%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB) - [为什么使用索引?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95) - [索引这么多优点,为什么不对表中的每一个列创建一个索引呢?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E7%B4%A2%E5%BC%95%E8%BF%99%E4%B9%88%E5%A4%9A%E4%BC%98%E7%82%B9%E4%B8%BA%E4%BB%80%E4%B9%88%E4%B8%8D%E5%AF%B9%E8%A1%A8%E4%B8%AD%E7%9A%84%E6%AF%8F%E4%B8%80%E4%B8%AA%E5%88%97%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E7%B4%A2%E5%BC%95%E5%91%A2) - [索引如如何提高查询速度的?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E7%B4%A2%E5%BC%95%E5%A6%82%E5%A6%82%E4%BD%95%E6%8F%90%E9%AB%98%E6%9F%A5%E8%AF%A2%E9%80%9F%E5%BA%A6%E7%9A%84) - [使用索引的注意事项?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95%E7%9A%84%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9) - [Mysql索引主要使用的两种数据结构](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#mysql%E7%B4%A2%E5%BC%95%E4%B8%BB%E8%A6%81%E4%BD%BF%E7%94%A8%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84) - [MyISAM和InnoDB实现BTree索引方式的区别](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#myisam%E5%92%8Cinnodb%E5%AE%9E%E7%8E%B0btree%E7%B4%A2%E5%BC%95%E6%96%B9%E5%BC%8F%E7%9A%84%E5%8C%BA%E5%88%AB) - [数据库结构优化](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E6%95%B0%E6%8D%AE%E5%BA%93%E7%BB%93%E6%9E%84%E4%BC%98%E5%8C%96) - [主键 超键 候选键 外键是什么](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E4%B8%BB%E9%94%AE-%E8%B6%85%E9%94%AE-%E5%80%99%E9%80%89%E9%94%AE-%E5%A4%96%E9%94%AE%E6%98%AF%E4%BB%80%E4%B9%88) - [drop,delete与truncate的区别](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#dropdelete%E4%B8%8Etruncate%E7%9A%84%E5%8C%BA%E5%88%AB) - [视图的作用,视图可以更改么?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E8%A7%86%E5%9B%BE%E7%9A%84%E4%BD%9C%E7%94%A8%E8%A7%86%E5%9B%BE%E5%8F%AF%E4%BB%A5%E6%9B%B4%E6%94%B9%E4%B9%88) - [数据库范式](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E6%95%B0%E6%8D%AE%E5%BA%93%E8%8C%83%E5%BC%8F) - [什么是覆盖索引?](https://github.com/DreamCats/JavaBooks/blob/master/Interview/mysql/Mysql-%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E7%9A%84%E9%97%AE%E9%A2%98.md#%E4%BB%80%E4%B9%88%E6%98%AF%E8%A6%86%E7%9B%96%E7%B4%A2%E5%BC%95)<file_sep>package normal; import java.util.HashMap; /** * @program JavaBooks * @description: 136.只出现一次的数字 * @author: mf * @create: 2019/11/06 09:49 */ /* 题目:https://leetcode-cn.com/problems/single-number/ 类型:哈希 难度:easy */ /* 输入: [2,2,1] 输出: 1 输入: [4,1,2,1,2] 输出: 4 */ /* 对于这道题,也可以异或 */ public class SingleNumber { public static void main(String[] args) { int[] arr = {2,2,1}; // System.out.println(singleNumber(arr)); System.out.println(singleNumber2(arr)); } /** * 哈希 * @param nums * @return */ private static int singleNumber(int[] nums) { if (nums.length == 1) return nums[0]; HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } for (Integer key : map.keySet()) { if (map.get(key) == 1) { return key; } } return 0; } /** * 异或 * @param nums * @return */ private static int singleNumber2(int[] nums) { if (nums.length == 1) return nums[0]; int ans = nums[0]; for (int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } } <file_sep>/** * @program JavaBooks * @description: 打家劫舍 * @author: mf * @create: 2020/04/14 15:29 */ package subject.dp; /** * 输入: [1,2,3,1] * 输出: 4 * 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 *   偷窃到的最高金额 = 1 + 3 = 4 。 * 输入: [2,7,9,3,1] * 输出: 12 * 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 *   偷窃到的最高金额 = 2 + 9 + 1 = 12 。 */ public class T3 { public int rob(int[] nums) { if (nums.length == 0) return 0; if (nums.length == 1) return nums[0]; int pre3 = 0, pre2 = 0, pre1 = 0; for (int i = 0; i < nums.length; i++) { int cur = Math.max(pre3, pre2) + nums[i]; pre3 = pre2; pre2 = pre1; pre1 = cur; } return Math.max(pre2, pre1); } } <file_sep>## 美团一面 ### 自我介绍 + 项目简单介绍 略 ### 集合有哪些 - Set - TreeSet - HashSet - LinkedHashSet - List - ArrayList - Vector - LinkedList - Map - TreeMap - HashMap - HashTable ### ArrayList和LinkedList区别 - ArrayList实现了List接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入null元素,底层通过数组实现。 - LinkedList同时实现了List接口和Deque接口,也就是说它既可以看作一个顺序容器,又可以看作一个队列(Queue),同时又可以看作一个栈(Stack)。LinkedList底层通过双向链表实现。 ### hashmap怎么扩容(多线程扩容为什么会死循环),put过程 #### 扩容 > resize() 1. 创建一个新的Entry空数组,长度是原来的2倍。 2. 遍历原Entry数组,把所有的Entry重新Hash到新数组里。为什么要重新Hash呢?因为长度扩大以后,Hash的规则也随之改变了。 **多线程问题**: > 多个线程并发进行时,因为一个线程先期完成了扩容,将原Map的链表重新散列到自己的表中,并且链表变成了倒序,后一个线程再扩容时,又进行自己的散列,再次将倒序链表变为正序链表。于是形成了一个环形链表,当get表中不存在的元素时,造成死循环。 #### put 1. 1.7 - 判断当前数组是否需要初始化 - 如果key为空,则put一个空值进去 - 根据key计算hashcode - 根据计算的hashcode定位index的桶 - 如果桶是一个链表,则需要遍历判断里面的hashcode、key是否和传入的key相等,如果相等则进行覆盖,并返回原来的值 - 如果桶是空的,说明当前位置没有数据存入,此时新增一个Entry对象写入当前位置。 2. 1.8 - 判断当前桶是否为空,空的就需要初始化(resize中会判断是否进行初始化)。 - 根据当前key的hashcode定位到具体的桶中并判断是否为空,为空则表明没有Hash冲突,就直接在当前位置创建一个新桶。 - 如果当前桶有值(Hash冲突),那么就要比较当前桶中的key、key的hashcode与写入的key是否相等,相等就赋值给e,在第8步的时候会统一进行赋值及返回。 - 如果当前桶为「红黑树」,那就要按照红黑树的方式写入数据。 - 如果是个链表,就需要将当前的key、value封装称一个新节点写入到当前桶的后面形成链表。 - 接着判断当前链表的大小是否「大于预设的阈值」,大于就要转换成为「红黑树」 - 如果在遍历过程中找到key相同时直接退出遍历。 - 如果e != null就相当于存在相同的key,那就需要将值覆盖。 - 最后判断是否需要进行扩容。 ### concurrentHashMap 1.7和1.8 1. 1.7 - 唯一的区别就是其中的核心数据如 value ,以及链表都是 volatile 修饰的,保证了获取时的可见性。 - ConcurrentHashMap 采用了「分段锁」技术,其中 Segment 继承于 ReentrantLock。 - 不会像HashTable那样不管是put还是get操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。 - 每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment。 put: - 将当前的Segment中的table通过key的hashcode定位到HashEntry - 遍历该HashEntry,如果不为空则判断传入的key和当前遍历的key是否相等,相等则覆盖旧的value - 不为空则需要新建一个HashEntry并加入到Segment中,同时会先判断是否需要扩容 - 最后会解除在1中所获取当前Segment的锁。 2. 1.8 - 其中抛弃了原有的 Segment 分段锁,而采用了 CAS + synchronized 来保证并发安全性 put: - 根据key计算出hashcode - 判断是否需要进行初始化 - f即为当前key定位出的Node,如果为空表示当前位置可以写入数据,利用CAS尝试写入,失败则自旋保证成功。 - 如果当前位置的hashcode == MOVED == -1,则需要进行扩容。 - 如果都不满足,则利用synchronized锁写入数据 - 如果数量大于TREEIFY_THRESHOLD 则要转换为红黑树。 ### 接口和抽象类区别 - 接口的方法默认是 public,所有方法在接口中不能有实现(Java 8 开始接口方法可以有默认实现),而抽象类可以有非抽象的方法。 - 接口中除了static、final变量,不能有其他变量,而抽象类中则不一定。 - 一个类可以实现多个接口,但只能实现一个抽象类。接口自己本身可以通过implement关键字扩展多个接口。 - 接口方法默认修饰符是public,抽象方法可以有public、protected和default这些修饰符(抽象方法就是为了被重写所以不能使用private关键字修饰!)。 - 从设计层面来说,抽象是对类的抽象,是一种模板设计,而接口是对行为的抽象,是一种行为的规范。 ### JVM内存分区 ![1.8前](https://user-gold-cdn.xitu.io/2020/3/31/17130c2c0a57c0f7?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) ![1.8后](https://user-gold-cdn.xitu.io/2020/3/31/17130c2c0bed60c9?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) ### 新生代:eden,survivor_from, survivor_to 大部分情况,对象都会首先在 Eden 区域分配,在一次新生代垃圾回收后,如果对象还存活,则会进入 s1("To"),并且对象的年龄还会加 1(Eden 区->Survivor 区后对象的初始年龄变为 1),当它的年龄增加到一定程度(默认为 15 岁),就会被晋升到老年代中。 对象晋升到老年代的年龄阈值,可以通过参数 -XX:MaxTenuringThreshold 来设置。经过这次GC后,Eden区和"From"区已经被清空。这个时候,"From"和"To"会交换他们的角色,也就是新的"To"就是上次GC前的“From”,新的"From"就是上次GC前的"To"。 不管怎样,都会保证名为To的Survivor区域是空的。Minor GC会一直重复这样的过程,直到“To”区被填满,"To"区被填满之后,会将所有对象移动到年老代中。 ### 垃圾回收算法 - 标记-清除 该算法分为“标记”和“清除”阶段:首先标记出所有需要回收的对象,在标记完成后统一回收所有被标记的对象。它是最基础的收集算法,后续的算法都是对其不足进行改进得到。这种垃圾收集算法会带来两个明显的问题: - 效率问题 - 空间问题(标记清除后会产生大量不连续的碎片) - 标记-整理 根据老年代的特点提出的一种标记算法,标记过程仍然与“标记-清除”算法一样,但后续步骤不是直接对可回收对象回收,而是让所有存活的对象向一端移动,然后直接清理掉端边界以外的内存。 - 复制 为了解决效率问题,“复制”收集算法出现了。它可以将内存分为大小相同的两块,每次使用其中的一块。当这一块的内存使用完后,就将还存活的对象复制到另一块去,然后再把使用的空间一次清理掉。这样就使每次的内存回收都是对内存区间的一半进行回收。 - 分代 比如在新生代中,每次收集都会有大量对象死去,所以可以选择复制算法,只需要付出少量对象的复制成本就可以完成每次垃圾收集。而老年代的对象存活几率是比较高的,而且没有额外的空间对它进行分配担保,所以我们必须选择“标记-清除”或“标记-整理”算法进行垃圾收集。 ### PretenureSizeThreshold,maxTenuringThreshold **默认15** ### JVM调优 [参考](https://juejin.im/post/5e8344486fb9a03c786ef885#heading-61) ### 如何判断对象是否应该被回收 (引用计数法,可达性分析) ### root根包括哪些 - 虚拟机栈(栈帧中的局部变量区,也叫局部变量表)中应用的对象。 - 方法区中的类静态属性引用的对象 - 方法区中常量引用的对象 - 本地方法栈中JNI(native方法)引用的对象 ### CMS回收过程,优缺点 - 初始标记:暂停所有的其他线程,并记录下直接与 root 相连的对象,速度很快 ; - 并发标记:同时开启 GC 和用户线程,用一个闭包结构去记录可达对象。但在这个阶段结束,这个闭包结构并不能保证包含当前所有的可达对象。因为用户线程可能会不断的更新引用域,所以 GC 线程无法保证可达性分析的实时性。所以这个算法里会跟踪记录这些发生引用更新的地方。 - 重新标记:重新标记阶段就是为了修正并发标记期间因为用户程序继续运行而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段的时间稍长,远远比并发标记阶段时间短 - 并发清除:开启用户线程,同时 GC 线程开始对为标记的区域做清扫。 #### 优点 - 并发收集 - 低停顿 #### 缺点 - 对CPU敏感 - 无法处理浮动垃圾 - 使用的标记-清除算法会带来大量的空间碎片 ### G1回收过程 - 初始标记 - 并发标记 - 最终标记 - 筛选标记 ### 类加载过程(加载,验证,准备,解析,初始化) - 加载 - 验证 - 准备 - 解析 - 初始化 ### 双亲委派优点 双亲委派模型保证了Java程序的稳定运行,可以避免类的重复加载(JVM 区分不同类的方式不仅仅根据类名,相同的类文件被不同的类加载器加载产生的是两个不同的类),也保证了 Java 的核心 API 不被篡改。 ### 七层模型 - 物理层:底层数据传输,如网线;网卡标准。 - 数据链路层:定义数据的基本格式,如何传输,如何标识;如网卡MAC地址。 - 网络层:定义IP编址,定义路由功能;如不同设备的数据转发。 - 传输层:端到端传输数据的基本功能;如 TCP、UDP。 - 会话层:控制应用程序之间会话能力;如不同软件数据分发给不同软件。 - 标识层:数据格式标识,基本压缩加密功能。 - 应用层:各种应用软件,包括 Web 应用。 ### 四次分手 - 客户端-发送一个 FIN,用来关闭客户端到服务器的数据传送 - 服务器-收到这个 FIN,它发回一 个 ACK,确认序号为收到的序号加1 。和 SYN 一样,一个 FIN 将占用一个序号 - 服务器-关闭与客户端的连接,发送一个FIN给客户端 - 客户端-发回 ACK 报文确认,并将确认序号设置为收到序号加1 > 任何一方都可以在数据传送结束后发出连接释放的通知,待对方确认后进入半关闭状态。当另一方也没有数据再发送的时候,则发出连接释放通知,对方确认后就完全关闭了TCP连接。举个例子:A 和 B 打电话,通话即将结束后,A 说“我没啥要说的了”,B回答“我知道了”,但是 B 可能还会有要说的话,A 不能要求 B 跟着自己的节奏结束通话,于是 B 可能又巴拉巴拉说了一通,最后 B 说“我说完了”,A 回答“知道了”,这样通话才算结束。 ### 为什么TCP能保证不丢失 - 滑动窗口 - 拥塞控制 ### HTTP和HTTPS的区别 - HTTP协议是超文本传输协议的缩写,英文是Hyper Text Transfer Protocol。它是从WEB服务器传输超文本标记语言(HTML)到本地浏览器的传送协议。 - HTTP是一个基于TCP/IP通信协议来传递数据的协议,传输的数据类型为HTML 文件,、图片文件, 查询结果等。 - HTTPS 并不是新协议,而是让 HTTP 先和 SSL(Secure Sockets Layer)通信,再由 SSL 和 TCP 通信,也就是说 HTTPS 使用了隧道进行通信。通过使用 SSL,HTTPS 具有了加密(防窃听)、认证(防伪装)和完整性保护(防篡改)。 ### GET和POST区别 - GET使用URL或Cookie传参,而POST将数据放在BODY中 - GET方式提交的数据有长度限制,则POST的数据则可以非常大 - POST比GET安全,因为数据在地址栏上不可见,没毛病 - 本质区别:GET请求是幂等性的,POST请求不是。 > 这里的幂等性:幂等性是指一次和多次请求某一个资源应该具有同样的副作用。简单来说意味着对同一URL的多个请求应该返回同样的结果。 ### 索引数据结构 - hash - b+ ### 为什么用B+树而不用hash和B-Tree - 利用Hash需要把数据全部加载到内存中,如果数据量大,是一件很消耗内存的事,而采用B+树,是基于按照节点分段加载,由此减少内存消耗。 - 和业务场景有段,对于唯一查找(查找一个值),Hash确实更快,但数据库中经常查询多条数据,这时候由于B+数据的有序性,与叶子节点又有链表相连,他的查询效率会比Hash快的多。 - b+树的非叶子节点不保存数据,只保存子树的临界值(最大或者最小),所以同样大小的节点,b+树相对于b树能够有更多的分支,使得这棵树更加矮胖,查询时做的IO操作次数也更少。 ### InooDB和MyISAM的区别(事务,聚集索引,锁的粒度等) - 事务: InnoDB 是事务型的,可以使用 Commit 和 Rollback 语句。 - 并发: MyISAM 只支持表级锁,而 InnoDB 还支持行级锁。 - 外键: InnoDB 支持外键。 - 备份: InnoDB 支持在线热备份。 - 崩溃恢复: MyISAM 崩溃后发生损坏的概率比 InnoDB 高很多,而且恢复的速度也更慢。 - 其它特性: MyISAM 支持压缩表和空间数据索引。 ### 最左匹配是什么意思,联合索引建立索引过程 > MySQL中的索引可以以一定顺序引用多个列,这种索引叫做联合索引一般的,一个联合索引是一个有序元组<a1, a2, …, an>,其中各个元素均为数据表的一列。另外,单列索引可以看成联合索引元素数为1的特例。 索引匹配的最左原则具体是说,假如索引列分别为A,B,C,顺序也是A,B,C: ``` - 那么查询的时候,如果查询【A】【A,B】 【A,B,C】,那么可以通过索引查询 - 如果查询的时候,采用【A,C】,那么C这个虽然是索引,但是由于中间缺失了B,因此C这个索引是用不到的,只能用到A索引 - 如果查询的时候,采用【B】 【B,C】 【C】,由于没有用到第一列索引,不是最左前缀,那么后面的索引也是用不到了 - 如果查询的时候,采用范围查询,并且是最左前缀,也就是第一列索引,那么可以用到索引,但是范围后面的列无法用到索引 ``` ### 独占锁,共享锁,乐观锁讲一下 - 独享锁:是指该锁一次只能被一个线程所持有。 - 共享锁:是该锁可被多个线程所持有。 - 乐观锁则认为对于同一个数据的并发操作,是不会发生修改的。在更新数据的时候,会采用尝试更新,不断重新的方式更新数据。乐观的认为,不加锁的并发操作时没有事情的。常常采用的是CAS算法,典型的例子就是原子类,通过CAS自旋实现原子类操作的更新。 ### NIO是什么? NIO是一种同步非阻塞的I/O模型,在Java 1.4 中引入了NIO框架,对应 java.nio 包,提供了 Channel , Selector,Buffer等抽象。 NIO中的N可以理解为Non-blocking,不单纯是New。它支持面向缓冲的,基于通道的I/O操作方法。 NIO提供了与传统BIO模型中的 Socket 和 ServerSocket 相对应的 SocketChannel 和 ServerSocketChannel 两种不同的套接字通道实现,两种通道都支持阻塞和非阻塞两种模式。 阻塞模式使用就像传统中的支持一样,比较简单,但是性能和可靠性都不好;非阻塞模式正好与之相反。对于低负载、低并发的应用程序,可以使用同步阻塞I/O来提升开发速率和更好的维护性; 对于高负载、高并发的(网络)应用,应使用 NIO 的非阻塞模式来开发 ### Redis线程模型?多路复用讲一下,为什么redis很快 > redis 内部使用文件事件处理器 file event handler,这个文件事件处理器是「单线程」的,所以 redis 才叫做单线程的模型。它采用 IO 多路复用机制同时监听多个 socket,根据 socket 上的事件来选择对应的事件处理器进行处理。 文件事件处理器的结构包含 4 个部分: - 多个 socket - IO多路复用程序 - 文件事件分派器 - 事件处理器(连接应答处理器、命令请求处理器、命令回复处理器) ### 线程和进程概念 #### 进程 进程是程序的一次执行过程,是系统运行程序的基本单位,因此进程是动态的。系统运行一个程序即是一个进程从创建,运行到消亡的过程。 #### 线程 - 线程是一个比进程更小的执行单位 - 一个进程在其执行的过程中可以产生多个线程 - 与进程不同的是同类的多个线程共享进程的堆和方法区资源,但每个线程有自己的程序计数器、虚拟机栈和本地方法栈,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程 ### 虚拟内存讲一下(分页) 分页存储管理: - 将用户程序的地址空间分成若干个固定大小区域,称为页,同时将内存空间分成对应大小物理块。系统中维护一个页表,通过页与物理块的对应,完成逻辑地址到物理地址(实际内存的地址,比如内存条)的映射。 - 当进程访问某个逻辑地址中数据,分页系统地址变换机构,用页号检索页表,如果页号大于或等于页表长度,则产生地址越界中断。否则将页表初始地址与页号和页表项长度乘积相加得到页表物理号的地址,获取到物理块号。再将物理块得到的地址与页内地址组合得到物理地址。 - 如果选择的页面太小,虽然可以提高内存利用率,但是每个进程使用过多页面,导致页表过长。降低页面换入换出效率。 ### synchronized和Lock的区别 - 两者都是可重入锁:两者都是可重入锁。“可重入锁”概念是:自己可以再次获取自己的内部锁。比如一个线程获得了某个对象的锁,此时这个对象锁还没有释放,当其再次想要获取这个对象的锁的时候还是可以获取的,如果不可锁重入的话,就会造成死锁。同一个线程每次获取锁,锁的计数器都自增1,所以要等到锁的计数器下降为0时才能释放锁。 - Synchronized 依赖于 JVM 而 ReenTrantLock 依赖于 API:synchronized 是依赖于 JVM 实现的,前面我们也讲到了 虚拟机团队在 JDK1.6 为 synchronized 关键字进行了很多优化,但是这些优化都是在虚拟机层面实现的,并没有直接暴露给我们。ReenTrantLock 是 JDK 层面实现的(也就是 API 层面,需要 lock() 和 unlock 方法配合 try/finally 语句块来完成),所以我们可以通过查看它的源代码,来看它是如何实现的。 - ReenTrantLock 比 Synchronized 增加了一些高级功能 - 等待可中断:过lock.lockInterruptibly()来实现这个机制。也就是说正在等待的线程可以选择放弃等待,改为处理其他事情。 - 可实现公平锁 - 可实现选择性通知(锁可以绑定多个条件):线程对象可以注册在指定的Condition中,从而可以有选择性的进行线程通知,在调度线程上更加灵活。 在使用notify/notifyAll()方法进行通知时,被通知的线程是由 JVM 选择的,用ReentrantLock类结合Condition实例可以实现“选择性通知” - 性能已不是选择标准:在jdk1.6之前synchronized 关键字吞吐量随线程数的增加,下降得非常严重。1.6之后,synchronized 和 ReenTrantLock 的性能基本是持平了。 ### volatile的作用 - 可序性(禁止重排) - 可见性 - 不能保证原子性 ### 长度为n的数组乱序存放着0至n-1. 现在只能进行0与其他数的交换,完成以下函数 ```java public class Solution { /** * 交换数组里n和0的位置 * * @param array * 数组 * @param len * 数组长度 * @param n * 和0交换的数 */ // 不要修改以下函数内容 public void swapWithZero(int[] array, int len, int n) { Main.SwapWithZero(array, len, n); } // 不要修改以上函数内容 /** * 通过调用swapWithZero方法来排 * * @param array * 存储有[0,n)的数组 * @param len * 数组长度 */ public void sort(int[] array, int len) { // 完成这个函数 for (int i = len - 1; i >=0; i--) { if (array[i] == i) continue; swapWithZero(array, len, array[i]); swapWithZero(array, len, i); } } } // 0,1,3,2 // 2,1,3,0 // 2,1,0,3 // 0,1,2,3 ``` ## 美团二面 ### synchronized底层实现 - synchronized 同步语句块的情况 > synchronized 同步语句块的实现使用的是 monitorenter 和 monitorexit 指令,其中 monitorenter 指令指向同步代码块的开始位置,monitorexit 指令则指明同步代码块的结束位置。 > 当执行 monitorenter 指令时,线程试图获取锁也就是获取 monitor(monitor对象存在于每个Java对象的对象头中,synchronized 锁便是通过这种方式获取锁的,也是为什么Java中任意对象可以作为锁的原因) 的持有权.当计数器为0则可以成功获取,获取后将锁计数器设为1也就是加1。 > 相应的在执行 monitorexit 指令后,将锁计数器设为0,表明锁被释放。如果获取对象锁失败,那当前线程就要阻塞等待,直到锁被另外一个线程释放为止。 - synchronized 修饰方法的的情况 > synchronized 修饰的方法并没有 monitorenter 指令和 monitorexit 指令,取得代之的确实是 ACC_SYNCHRONIZED 标识,该标识指明了该方法是一个同步方法,JVM 通过该 ACC_SYNCHRONIZED 访问标志来辨别一个方法是否声明为同步方法,从而执行相应的同步调用。 #### 1.6之后的优化 > JDK1.6对锁的实现引入了大量的优化,如自旋锁、适应性自旋锁、锁消除、锁粗化、偏向锁、轻量级锁等技术来减少锁操作的开销。 锁主要存在四中状态,依次是:「无锁状态、偏向锁状态、轻量级锁状态、重量级锁状态」,他们会随着竞争的激烈而逐渐升级。注意锁可以升级不可降级,这种策略是为了提高获得锁和释放锁的效率。 1. 偏向锁 - 引入偏向锁的目的和引入轻量级锁的目的很像,他们都是为了没有多线程竞争的前提下,减少传统的重量级锁使用操作系统互斥量产生的性能消耗。但是不同是:轻量级锁在无竞争的情况下使用 CAS 操作去代替使用互斥量。而偏向锁在无竞争的情况下会把整个同步都消除掉。 - 偏向锁的“偏”就是偏心的偏,它的意思是会偏向于第一个获得它的线程,如果在接下来的执行中,该锁没有被其他线程获取,那么持有偏向锁的线程就不需要进行同步! - 但是对于锁竞争比较激烈的场合,偏向锁就失效了,因为这样场合极有可能每次申请锁的线程都是不相同的,因此这种场合下不应该使用偏向锁,否则会得不偿失,需要注意的是,偏向锁失败后,并不会立即膨胀为重量级锁,而是先升级为轻量级锁。 **升级过程**: - 访问Mark Word中偏向锁的标识是否设置成1,锁标识位是否为01,确认偏向状态 - 如果为可偏向状态,则判断当前线程ID是否为偏向线程 - 如果偏向线程未当前线程,则通过cas操作竞争锁,如果竞争成功则操作Mark Word中线程ID设置为当前线程ID - 如果cas偏向锁获取失败,则挂起当前偏向锁线程,偏向锁升级为轻量级锁。 2. 轻量级锁 - 轻量级锁不是为了代替重量级锁,它的本意是在没有多线程竞争的前提下,减少传统的重量级锁使用操作系统互斥量产生的性能消耗,因为使用轻量级锁时,不需要申请互斥量。另外,轻量级锁的加锁和解锁都用到了CAS操作。 - 如果没有竞争,轻量级锁使用 CAS 操作避免了使用互斥操作的开销。但如果存在锁竞争,除了互斥量开销外,还会额外发生CAS操作,因此在有锁竞争的情况下,轻量级锁比传统的重量级锁更慢!如果锁竞争激烈,那么轻量级将很快膨胀为重量级锁! **升级过程**: - 线程由偏向锁升级为轻量级锁时,会先把锁的对象头MarkWord复制一份到线程的栈帧中,建立一个名为锁记录空间(Lock Record),用于存储当前Mark Word的拷贝。 - 虚拟机使用cas操作尝试将对象的Mark Word指向Lock Record的指针,并将Lock record里的owner指针指对象的Mark Word。 - 如果cas操作成功,则该线程拥有了对象的轻量级锁。第二个线程cas自旋锁等待锁线程释放锁。 - 如果多个线程竞争锁,轻量级锁要膨胀为重量级锁,Mark Word中存储的就是指向重量级锁(互斥量)的指针。其他等待线程进入阻塞状态。 ### AQS底层实现(非公平锁,公平锁) > ReentrantLock的公平锁和非公平锁 学习AQS的时候,了解到AQS依赖于内部的FIFO同步队列来完成同步状态的管理,当前线程获取同步状态失败时,同步器会将当前线程以及等待状态等信息构造成一个Node对象并将其加入到同步队列,同时会阻塞当前线程,当同步状态释放时,会把首节点中的线程唤醒,使其再次尝试获取同步状态。 - ReentrantLock 默认采用非公平锁,除非在构造方法中传入参数 true 。 ```java //默认 public ReentrantLock() { sync = new NonfairSync(); } //传入true or false public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } ``` #### 公平锁lock方法 ```java static final class FairSync extends Sync { final void lock() { acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { // 1. 和非公平锁相比,这里多了一个判断:是否有线程在等待 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } ``` > 我们可以看到,在注释1的位置,有个!hasQueuedPredecessors()条件,意思是说当前同步队列没有前驱节点(也就是没有线程在等待)时才会去compareAndSetState(0, acquires)使用CAS修改同步状态变量。所以就实现了公平锁,根据线程发出请求的顺序获取锁。 #### 非公平锁的lock方法 ```java static final class NonfairSync extends Sync { final void lock() { // 2. 和公平锁相比,这里会直接先进行一次CAS,成功就返回了 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } /** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //3.这里也是直接CAS,没有判断前面是否还有节点。 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } ``` > 非公平锁的实现在刚进入lock方法时会直接使用一次CAS去尝试获取锁,不成功才会到acquire方法中,如注释2。而在nonfairTryAcquire方法中并没有判断是否有前驱节点在等待,直接CAS尝试获取锁,如注释3。由此实现了非公平锁。 #### 总结 > 非公平锁和公平锁的两处不同: 1. 非公平锁在调用 lock 后,首先就会调用 CAS 进行一次抢锁,如果这个时候恰巧锁没有被占用,那么直接就获取到锁返回了。 ### Spring Ioc,AOP介绍 #### Ioc - IoC(Inverse of Control:控制反转)是一种设计思想,就是将原本在程序中手动创建对象的控制权,交由Spring框架来管理。 IoC 在其他语言中也有应用,并非 Spring 特有。 IoC 容器是 Spring 用来实现 IoC 的载体,IoC 容器实际上就是个Map(key,value),Map中存放的是各种对象。 - 将对象之间的相互依赖关系交给 IoC 容器来管理,并由 IoC 容器完成对象的注入。这样可以很大程度上简化应用的开发,把应用从复杂的依赖关系中解放出来。 - IoC 容器就像是一个工厂一样,当我们需要创建一个对象的时候,只需要配置好配置文件/注解即可,完全不用考虑对象是如何被创建出来的。 推荐阅读:[https://www.zhihu.com/question/23277575/answer/169698662](https://www.zhihu.com/question/23277575/answer/169698662) #### AOP - AOP(Aspect-Oriented Programming:面向切面编程)能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。 - Spring AOP就是基于动态代理的,如果要代理的对象,实现了某个接口,那么Spring AOP会使用JDK Proxy,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用Cglib ,这时候Spring AOP会使用 Cglib 生成一个被代理对象的子类来作为代理。 ### Spring用到了什么设计模式 - 工厂设计模式 : Spring使用工厂模式通过 BeanFactory、ApplicationContext 创建 bean 对象。 - 代理设计模式 : Spring AOP 功能的实现。 - 单例设计模式 : Spring 中的 Bean 默认都是单例的。 - 模板方法模式 : Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。 - 适配器模式 :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配Controller。 - 等等...... ### 单例为什么加锁,volatile什么作用 - 如果单例不加锁,在高并发情况下可能出现多个实例的情况 - volatile的有序性特性则是指禁止JVM指令重排优化。因为实例初始化的时候,并非原子性,如 ``` memory =allocate(); //1. 分配对象的内存空间 ctorInstance(memory); //2. 初始化对象 instance =memory; //3. 设置instance指向刚分配的内存地址 ``` 上面三个指令中,步骤2依赖步骤1,但是步骤3不依赖步骤2,所以JVM可能针对他们进行指令重拍序优化,重排后的指令如下: ``` memory =allocate(); //1. 分配对象的内存空间 instance =memory; //3. 设置instance指向刚分配的内存地址 ctorInstance(memory); //2. 初始化对象 ``` > 这样优化之后,内存的初始化被放到了instance分配内存地址的后面,这样的话当线程1执行步骤3这段赋值指令后,刚好有另外一个线程2进入getInstance方法判断instance不为null,这个时候线程2拿到的instance对应的内存其实还未初始化,这个时候拿去使用就会导致出错。 **所以我们在用这种方式实现单例模式时,会使用volatile关键字修饰instance变量,这是因为volatile关键字除了可以保证变量可见性之外,还具有防止指令重排序的作用。当用volatile修饰instance之后,JVM执行时就不会对上面提到的初始化指令进行重排序优化,这样也就不会出现多线程安全问题了**。 ### hashmap什么时候用到了红黑树 当 HashMap 中有大量的元素都存放到同一个桶中时,这个桶下有一条长长的链表,这个时候 HashMap 就相当于一个单链表,假如单链表有 n 个元素,遍历的时间复杂度就是 O(n),完全失去了它的优势。 针对这种情况,JDK 1.8 中引入了 红黑树(查找时间复杂度为 O(logn))来优化这个问题。 - [参考](https://blog.csdn.net/wushiwude/article/details/75331926) ### 介绍红黑树特点(不是严格意义平衡,插入删除最多两次自旋,时间复杂度O(logn)等),为什么不用AVL树 - 每个结点要么是红的要么是黑的。(红或黑) - 根结点是黑的。 (根黑) - 每个叶结点(叶结点即指树尾端NIL指针或NULL结点)都是黑的。 (叶黑) - 如果一个结点是红的,那么它的两个儿子都是黑的。 (红子黑) - 对于任意结点而言,其到叶结点树尾端NIL指针的每条路径都包含相同数目的黑结点。(路径下黑相同) 为什么不用AVL: - AVL树更加严格平衡,因此可以提供更快的查找效果。因此,对于查找密集型任务,使用AVL树。 - 对于插入密集型任务,请使用红黑树。' - AVL树在每个节点存储平衡因子。这需要。但是,如果我们知道将插入树中的键总是大于零,我们可以使用键的符号位来存储红黑树的颜色信息。因此,在这种情况下,红黑树占用,因此与AVL树相比更有效和有用。 - 通常, AVL树的旋转比红黑树的旋转更难实现和调试。 - 因此,红黑树更加通用,它们在添加、删除和查找方面表现相对较好,但AVL树的查找速度更快,代价是添加/删除速度较慢。 ## 美团三面 ### 介绍了两个项目 略 ### 看过阿里电商的项目结构吗?(没有,随便说了说我的项目怎么做的) 略 ### 怎么解决超卖(答:redis + mysql乐观锁) ### 职业规划 + 想成为tech lead应该应该具备什么条件 略<file_sep>package books; import java.util.Stack; /** * @program JavaBooks * @description: 链表中倒数第K个节点 * @author: mf * @create: 2019/09/03 09:32 */ /* 输入一个链表,输出该链表中倒数第K个节点。为了符合大多数 人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。 例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3 、4、5、6。这个链表的倒数第3个节点是值为4的节点。链表的定义如下: */ /* 思路 准备两个指针p1 p2 当p1++ 到k的时候,p2开始++ 当当尾节点的时候,p2正好是倒数k个节点 n-k+1 追赶思路。。。 */ public class T22 { public static void main(String[] args) { ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); ListNode listNode4 = new ListNode(4); ListNode listNode5 = new ListNode(5); listNode1.next = listNode2; listNode2.next = listNode3; listNode3.next = listNode4; listNode4.next = listNode5; ListNode kNode = findKthToTail(listNode1, 6); System.out.println(kNode.value); } /** * 快慢指针问题 * @param headListNode * @param k * @return */ public static ListNode findKthToTail(ListNode headListNode, int k) { if (headListNode == null || k == 0 ) return null; // ListNode pNode = headListNode; ListNode kNode = headListNode; int p1 = 0; while (pNode != null) { if (p1 > k - 1) { // 当p1走完k-1步,那么kNode开始走 kNode = kNode.next; } pNode = pNode.next; p1++; } if (p1 >= k) { return kNode; } return null; } /** * 栈 * @param headListNode * @param k * @return */ public static ListNode findKthToTail2(ListNode headListNode, int k) { if(headListNode == null || k <= 0) return null; Stack<ListNode> stack = new Stack<>(); ListNode root = headListNode; while(root != null) { stack.push(root); root = root.next; } int temp = 0; while(!stack.isEmpty()) { ListNode listNode = stack.pop(); temp++; if (temp == k) { return listNode; } } return null; } } <file_sep>/** * @program JavaBooks * @description: 验证回文串 * @author: mf * @create: 2020/04/09 17:13 */ package subject.dpointer; /** * 输入: "A man, a plan, a canal: Panama" * 输出: true * 输入: "race a car" * 输出: false */ public class T5 { public boolean isPalindrome(String s) { if (s.equals("")) return true; s.toLowerCase(); char[] chars = s.toCharArray(); int l = 0, r = chars.length - 1; while (l <= r) { if (chars[l] == chars[r]) { l++; r--; }else if (!((chars[l] >= 'a' && chars[l] <= 'z') || (chars[l] >= '0' && chars[l] >= '9'))) { l++; } else if (!((chars[r] >= 'a' && chars[r] <= 'z') || (chars[r] >= '0' && chars[r] >= '9'))) { r--; } else { return false; } } return true; } } <file_sep>## 引言 **sql-数据库系统原理** ## 事务 ### 概念 事务指的是满足 ACID 特性的一组操作,可以通过 Commit 提交一个事务,也可以使用 Rollback 进行回滚。 ### ACID #### 原子性(Atomicity) 事务被视为不可分割的最小单元,事务的所有操作要么全部提交成功,要么全部失败回滚。 回滚可以用日志来实现,日志记录着事务所执行的修改操作,在回滚时反向执行这些修改操作即可。 <!-- more --> #### 一致性(Consistency) 数据库在事务执行前后都保持一致性状态。在一致性状态下,所有事务对一个数据的读取结果都是相同的。 #### 隔离性(Isolation) 一个事务所做的修改在最终提交以前,对其它事务是不可见的。 #### 持久性(Durability) 一旦事务提交,则其所做的修改将会永远保存到数据库中。即使系统发生崩溃,事务执行的结果也不能丢失。 可以通过数据库备份和恢复来实现,在系统发生崩溃时,使用备份的数据库进行数据恢复。 事务的 ACID 特性概念简单,但不是很好理解,主要是因为这几个特性不是一种平级关系: - 只有满足一致性,事务的执行结果才是正确的。 - 在无并发的情况下,事务串行执行,隔离性一定能够满足。此时只要能满足原子性,就一定能满足一致性。 - 在并发的情况下,多个事务并行执行,事务不仅要满足原子性,还需要满足隔离性,才能满足一致性。 - 事务满足持久化是为了能应对数据库崩溃的情况。 ![](https://www.pdai.tech/_images/pics/a58e294a-615d-4ea0-9fbf-064a6daec4b2.png) ### AUTOCOMMIT MySQL 默认采用自动提交模式。也就是说,如果不显式使用`START TRANSACTION`语句来开始一个事务,那么每个查询都会被当做一个事务自动提交。 ## 并发一致性问题 在并发环境下,事务的隔离性很难保证,因此会出现很多并发一致性问题。 ### 丢弃修改 T1 和 T2 两个事务都对一个数据进行修改,T1 先修改,T2 随后修改,T2 的修改覆盖了 T1 的修改。 ![](https://www.pdai.tech/_images/pics/88ff46b3-028a-4dbb-a572-1f062b8b96d3.png) ### 读脏数据 T1 修改一个数据,T2 随后读取这个数据。如果 T1 撤销了这次修改,那么 T2 读取的数据是脏数据。 ![](https://www.pdai.tech/_images/pics/dd782132-d830-4c55-9884-cfac0a541b8e.png) ### 不可重复读 T2 读取一个数据,T1 对该数据做了修改。如果 T2 再次读取这个数据,此时读取的结果和第一次读取的结果不同。 ![](https://www.pdai.tech/_images/pics/c8d18ca9-0b09-441a-9a0c-fb063630d708.png) ### 幻影读 T1 读取某个范围的数据,T2 在这个范围内插入新的数据,T1 再次读取这个范围的数据,此时读取的结果和和第一次读取的结果不同。 ![](https://www.pdai.tech/_images/pics/72fe492e-f1cb-4cfc-92f8-412fb3ae6fec.png) 产生并发不一致性问题主要原因是破坏了事务的隔离性,解决方法是通过并发控制来保证隔离性。并发控制可以通过封锁来实现,但是封锁操作需要用户自己控制,相当复杂。数据库管理系统提供了事务的隔离级别,让用户以一种更轻松的方式处理并发一致性问题。 ## 锁 ### 封锁粒度 MySQL 中提供了两种封锁粒度: 行级锁以及表级锁。 应该尽量只锁定需要修改的那部分数据,而不是所有的资源。锁定的数据量越少,发生锁争用的可能就越小,系统的并发程度就越高。 但是加锁需要消耗资源,锁的各种操作(包括获取锁、释放锁、以及检查锁状态)都会增加系统开销。因此封锁粒度越小,系统开销就越大。 ### 封锁类型 #### 读写锁 - 排它锁(Exclusive),简写为 X 锁,又称写锁。 - 共享锁(Shared),简写为 S 锁,又称读锁。 有以下两个规定: - 一个事务对数据对象 A 加了 X 锁,就可以对 A 进行读取和更新。加锁期间其它事务不能对 A 加任何锁。 - 一个事务对数据对象 A 加了 S 锁,可以对 A 进行读取操作,但是不能进行更新操作。加锁期间其它事务能对 A 加 S 锁,但是不能加 X 锁。 #### 意向锁 使用意向锁(Intention Locks)可以更容易地支持多粒度封锁。 在存在行级锁和表级锁的情况下,事务 T 想要对表 A 加 X 锁,就需要先检测是否有其它事务对表 A 或者表 A 中的任意一行加了锁,那么就需要对表 A 的每一行都检测一次,这是非常耗时的。 意向锁在原来的 X/S 锁之上引入了 IX/IS,IX/IS 都是表锁,用来表示一个事务想要在表中的某个数据行上加 X 锁或 S 锁。有以下两个规定: - 一个事务在获得某个数据行对象的 S 锁之前,必须先获得表的 IS 锁或者更强的锁; - 一个事务在获得某个数据行对象的 X 锁之前,必须先获得表的 IX 锁。 通过引入意向锁,事务 T 想要对表 A 加 X 锁,只需要先检测是否有其它事务对表 A 加了 X/IX/S/IS 锁,如果加了就表示有其它事务正在使用这个表或者表中某一行的锁,因此事务 T 加 X 锁失败。 - 任意 IS/IX 锁之间都是兼容的,因为它们只是表示想要对表加锁,而不是真正加锁; - S 锁只与 S 锁和 IS 锁兼容,也就是说事务 T 想要对数据行加 S 锁,其它事务可以已经获得对表或者表中的行的 S 锁。 ### 封锁协议 #### 三级封锁协议 ##### 一级封锁协议 事务 T 要修改数据 A 时必须加 X 锁,直到 T 结束才释放锁。 可以解决丢失修改问题,因为不能同时有两个事务对同一个数据进行修改,那么事务的修改就不会被覆盖。 | T1 | T2 | | :---------: | :---------: | | lock-x(A) | | | read A=20 | | | | lock-x(A) | | | wait | | write A=19 | | | commit | | | Unlock-x(A) | | | | obtain | | | read A = 19 | | | write A=21 | | | commit | | | unlock-x(A) | ##### 二级封锁协议 在一级的基础上,要求读取数据 A 时必须加 S 锁,读取完马上释放 S 锁。 可以解决读脏数据问题,因为如果一个事务在对数据 A 进行修改,根据 1 级封锁协议,会加 X 锁,那么就不能再加 S 锁了,也就是不会读入数据。 | T1 | T2 | | :---------: | :---------: | | lock-x(A) | | | read A=20 | | | write A=19 | | | | lock-s(A) | | | wait | | rollback | | | A=20 | . | | unlock-x(A) | | | | obtain | | | read A=20 | | | commit | | | unlock-s(A) | ##### 三级封锁协议 在二级的基础上,要求读取数据 A 时必须加 S 锁,直到事务结束了才能释放 S 锁。 可以解决不可重复读的问题,因为读 A 时,其它事务不能对 A 加 X 锁,从而避免了在读的期间数据发生改变。 | T1 | T2 | | :---------: | :---------: | | lock-s(A) | | | read A=20 | | | | lock-x(A) | | | wait | | read A=20 | | | commit | | | unlock-s(A) | | | | obtain | | | read A=20 | | | write A=19 | | | commit | | | unlock-X(A) | #### 两段锁协议 加锁和解锁分为两个阶段进行。 可串行化调度是指,通过并发控制,使得并发执行的事务结果与某个串行执行的事务结果相同。 事务遵循两段锁协议是保证可串行化调度的充分条件。例如以下操作满足两段锁协议,它是可串行化调度。 但不是必要条件,例如以下操作不满足两段锁协议,但是它还是可串行化调度。 ### Mysql隐式与显式锁定 MySQL 的 InnoDB 存储引擎采用两段锁协议,会根据隔离级别在需要的时候自动加锁,并且所有的锁都是在同一时刻被释放,这被称为隐式锁定。 ## 隔离级别 ### 未提交读(READ UNCOMMITTED) 事务中的修改,即使没有提交,对其它事务也是可见的。 ### 提交读(READ COMMITTED) 一个事务只能读取已经提交的事务所做的修改。换句话说,一个事务所做的修改在提交之前对其它事务是不可见的。 ### 可重复读(REPEATABLE READ) 保证在同一个事务中多次读取同样数据的结果是一样的。 ### 可串行化(SERIALIZABLE) 强制事务串行执行。 | 隔离级别 | 脏读 | 不可重复读 | 幻影读 | | :------: | :--: | :--------: | :----: | | 未提交读 | √ | √ | √ | | 提交读 | × | √ | √ | | 可重复读 | × | × | √ | | 可串行化 | × | × | × | ## 多版本并发控制 多版本并发控制(Multi-Version Concurrency Control, MVCC)是 MySQL 的 InnoDB 存储引擎实现隔离级别的一种具体方式,用于实现提交读和可重复读这两种隔离级别。而未提交读隔离级别总是读取最新的数据行,无需使用 MVCC。可串行化隔离级别需要对所有读取的行都加锁,单纯使用 MVCC 无法实现。 ### 版本号 - 系统版本号: 是一个递增的数字,每开始一个新的事务,系统版本号就会自动递增。 - 事务版本号: 事务开始时的系统版本号。 ### 隐藏的列 MVCC 在每行记录后面都保存着两个隐藏的列,用来存储两个版本号: - 创建版本号: 指示创建一个数据行的快照时的系统版本号; - 删除版本号: 如果该快照的删除版本号大于当前事务版本号表示该快照有效,否则表示该快照已经被删除了。 ### Undo日志 MVCC 使用到的快照存储在 Undo 日志中,该日志通过回滚指针把一个数据行(Record)的所有快照连接起来。 ![](https://www.pdai.tech/_images/pics/e41405a8-7c05-4f70-8092-e961e28d3112.jpg) ### 实现过程 以下实现过程针对可重复读隔离级别。 当开始新一个事务时,该事务的版本号肯定会大于当前所有数据行快照的创建版本号,理解这一点很关键。 #### SELECT 多个事务必须读取到同一个数据行的快照,并且这个快照是距离现在最近的一个有效快照。但是也有例外,如果有一个事务正在修改该数据行,那么它可以读取事务本身所做的修改,而不用和其它事务的读取结果一致。 把没有对一个数据行做修改的事务称为 T,T 所要读取的数据行快照的创建版本号必须小于 T 的版本号,因为如果大于或者等于 T 的版本号,那么表示该数据行快照是其它事务的最新修改,因此不能去读取它。除此之外,T 所要读取的数据行快照的删除版本号必须大于 T 的版本号,因为如果小于等于 T 的版本号,那么表示该数据行快照是已经被删除的,不应该去读取它。 #### INSERT 将当前系统版本号作为数据行快照的创建版本号。 #### DELETE 将当前系统版本号作为数据行快照的删除版本号。 #### UPDATE 将当前系统版本号作为更新前的数据行快照的删除版本号,并将当前系统版本号作为更新后的数据行快照的创建版本号。可以理解为先执行 DELETE 后执行 INSERT。 ### 快照读与当前读 #### 快照读 使用 MVCC 读取的是快照中的数据,这样可以减少加锁所带来的开销。 `select * from table ...;` #### 当前读 读取的是最新的数据,需要加锁。以下第一个语句需要加 S 锁,其它都需要加 X 锁。 ```mysql select * from table where ? lock in share mode; select * from table where ? for update; insert; update; delete; ``` ## Next-Key Locks Next-Key Locks 是 MySQL 的 InnoDB 存储引擎的一种锁实现。 MVCC 不能解决幻读的问题,Next-Key Locks 就是为了解决这个问题而存在的。在可重复读(REPEATABLE READ)隔离级别下,使用 MVCC + Next-Key Locks 可以解决幻读问题。 ### Record Locks 锁定一个记录上的索引,而不是记录本身。 如果表没有设置索引,InnoDB 会自动在主键上创建隐藏的聚簇索引,因此 Record Locks 依然可以使用。 ### Gap Locks 锁定索引之间的间隙,但是不包含索引本身。例如当一个事务执行以下语句,其它事务就不能在 t.c 中插入 15。 `SELECT c FROM t WHERE c BETWEEN 10 and 20 FOR UPDATE;` ### Next-Key Locks 它是 Record Locks 和 Gap Locks 的结合,不仅锁定一个记录上的索引,也锁定索引之间的间隙。例如一个索引包含以下值: 10, 11, 13, and 20,那么就需要锁定以下区间: ```mysql (negative infinity, 10] (10, 11] (11, 13] (13, 20] (20, positive infinity) ``` ## 面试常问的几个问题 ### 数据库引擎innodb与myisam的区别? [InnoDB和MyISAM比较](http://dreamcat.ink/2019/11/15/sql-notes/1/) ### 4大特性 [Mysql的ACID原理](http://dreamcat.ink/2019/11/20/sql-notes/1/) ### 数据库的隔离级别 1. 未提交读,事务中发生了修改,即使没有提交,其他事务也是可见的,比如对于一个数A原来50修改为100,但是我还没有提交修改,另一个事务看到这个修改,而这个时候原事务发生了回滚,这时候A还是50,但是另一个事务看到的A是100. 2. 提交读,对于一个事务从开始直到提交之前,所做的任何修改是其他事务不可见的,举例就是对于一个数A原来是50,然后提交修改成100,这个时候另一个事务在A提交修改之前,读取的A是50,刚读取完,A就被修改成100,这个时候另一个事务再进行读取发现A就突然变成100了; 3. 可重复读,就是对一个记录读取多次的记录是相同的,比如对于一个数A读取的话一直是A,前后两次读取的A是一致的; 4. 可重复读,就是对一个记录读取多次的记录是相同的,比如对于一个数A读取的话一直是A,前后两次读取的A是一致的; ### 索引的分为哪几类? - 分为聚集索引和非聚集索引 - 非聚集索引又有唯一索引,普通索引,主键索引,和全文索引。 ### 聚集索引是什么? 聚集索引是数据行的物理顺序与列值(一般是主键的那一列)的逻辑顺序相同,也就是说索引中的顺序也就是在内存中顺序。 ### 主键 超键 候选键 外键是什么 #### 定义 超键:在关系中能唯一标识元组的属性集称为关系模式的超键 候选键:不含有多余属性的超键称为候选键。也就是在候选键中,若再删除属性,就不是键了! 主键:用户选作元组标识的一个候选键程序主键 外键:如果关系模式R中属性K是其它模式的主键,那么k在模式R中称为外键。 #### 举例 | 学号 | 姓名 | 性别 | 年龄 | 系别 | 专业 | | -------- | ------ | ---- | ---- | ------ | -------- | | 20020612 | 李辉 | 男 | 20 | 计算机 | 软件开发 | | 20060613 | 张明 | 男 | 18 | 计算机 | 软件开发 | | 20060614 | 王小玉 | 女 | 19 | 物理 | 力学 | | 20060615 | 李淑华 | 女 | 17 | 生物 | 动物学 | | 20060616 | 赵静 | 男 | 21 | 化学 | 食品化学 | | 20060617 | 赵静 | 女 | 20 | 生物 | 植物学 | 1. 超键:于是我们从例子中可以发现 学号是标识学生实体的唯一标识。那么该元组的超键就为学号。除此之外我们还可以把它跟其他属性组合起来,比如:(`学号`,`性别`),(`学号`,`年龄`) 2. 候选键:根据例子可知,学号是一个可以唯一标识元组的唯一标识,因此学号是一个候选键,实际上,候选键是超键的子集,比如 (学号,年龄)是超键,但是它不是候选键。因为它还有了额外的属性。 3. 主键:简单的说,例子中的元组的候选键为学号,但是我们选定他作为该元组的唯一标识,那么学号就为主键。 4. 外键是相对于主键的,比如在学生记录里,主键为学号,在成绩单表中也有学号字段,因此学号为成绩单表的外键,为学生表的主键。 #### 总结 **主键为候选键的子集,候选键为超键的子集,而外键的确定是相对于主键的。** ### 视图的作用,视图可以更改么? 视图是虚拟的表,与包含数据的表不一样,视图只包含使用时动态检索数据的查询;不包含任何列或数据。使用视图可以简化复杂的sql操作,隐藏具体的细节,保护数据;视图创建后,可以使用与表相同的方式利用它们。 视图不能被索引,也不能有关联的触发器或默认值,如果视图本身内有order by 则对视图再次order by将被覆盖。 创建视图:`create view xxx as xxxx` 对于某些视图比如未使用联结子查询分组聚集函数Distinct Union等,是可以对其更新的,对视图的更新将对基表进行更新;但是视图主要用于简化检索,保护数据,并不用于更新,而且大部分视图都不可以更新。 ### drop,delete与truncate的区别 drop直接删掉表;truncate删除表中数据,再插入时自增长id又从1开始 ;delete删除表中数据,可以加where字句。 1. DELETE语句执行删除的过程是每次从表中删除一行,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作。TRUNCATE TABLE 则一次性地从表中删除所有的数据并不把单独的删除操作记录记入日志保存,删除行是不能恢复的。并且在删除的过程中不会激活与表有关的删除触发器。执行速度快。 2. 表和索引所占空间。当表被TRUNCATE 后,这个表和索引所占用的空间会恢复到初始大小,而DELETE操作不会减少表或索引所占用的空间。drop语句将表所占用的空间全释放掉。 3. 一般而言,drop > truncate > delete 4. 应用范围。TRUNCATE 只能对TABLE;DELETE可以是table和view 5. TRUNCATE 和DELETE只删除数据,而DROP则删除整个表(结构和数据)。 6. truncate与不带where的delete :只删除数据,而不删除表的结构(定义)drop语句将删除表的结构被依赖的约束(constrain),触发器(trigger)索引(index);依赖于该表的存储过程/函数将被保留,但其状态会变为:invalid。 7. delete语句为DML(Data Manipulation Language),这个操作会被放到 rollback segment中,事务提交后才生效。如果有相应的 tigger,执行的时候将被触发。 8. truncate、drop是DDL(Data Define Language),操作立即生效,原数据不放到 rollback segment中,不能回滚 9. 在没有备份情况下,谨慎使用 drop 与 truncate。要删除部分数据行采用delete且注意结合where来约束影响范围。回滚段要足够大。要删除表用drop;若想保留表而将表中数据删除,如果于事务无关,用truncate即可实现。如果和事务有关,或老是想触发trigger,还是用delete。 10. Truncate table 表名 速度快,而且效率高,因为: truncate table 在功能上与不带 WHERE 子句的 DELETE 语句相同:二者均删除表中的全部行。但 TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少。DELETE 语句每次删除一行,并在事务日志中为所删除的每行记录一项。TRUNCATE TABLE 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放。 11. TRUNCATE TABLE 删除表中的所有行,但表结构及其列、约束、索引等保持不变。新行标识所用的计数值重置为该列的种子。如果想保留标识计数值,请改用 DELETE。如果要删除表定义及其数据,请使用 DROP TABLE 语句。 12. 对于由 FOREIGN KEY 约束引用的表,不能使用 TRUNCATE TABLE,而应使用不带 WHERE 子句的 DELETE 语句。由于 TRUNCATE TABLE 不记录在日志中,所以它不能激活触发器。 ### 数据库范式 #### 第一范式 在任何一个关系数据库中,第一范式(1NF)是对关系模式的基本要求,不满足第一范式(1NF)的数据库就不是关系数据库。 所谓第一范式(1NF)是指数据库表的每一列都是不可分割的基本数据项,同一列中不能有多个值,即实体中的某个属性不能有多个值或者不能有重复的属性。如果出现重复的属性,就可能需要定义一个新的实体,新的实体由重复的属性构成,新实体与原实体之间为一对多关系。在第一范式(1NF)中表的每一行只包含一个实例的信息。简而言之,**第一范式就是无重复的列**。 #### 第二范式 第二范式(2NF)是在第一范式(1NF)的基础上建立起来的,即满足第二范式(2NF)必须先满足第一范式(1NF)。第二范式(2NF)要求数据库表中的每个实例或行必须可以被惟一地区分。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。这个惟一属性列被称为主关键字或主键、主码。 第二范式(2NF)要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体,新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,**第二范式就是非主属性非部分依赖于主关键字**。 #### 第三范式 满足第三范式(3NF)必须先满足第二范式(2NF)。简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主关键字信息。例如,存在一个部门信息表,其中每个部门有部门编号(dept_id)、部门名称、部门简介等信息。那么在员工信息表中列出部门编号后就不能再将部门名称、部门简介等与部门有关的信息再加入员工信息表中。如果不存在部门信息表,则根据第三范式(3NF)也应该构建它,否则就会有大量的数据冗余。简而言之,第三范式就是属性不依赖于其它非主属性。(我的理解是消除冗余) ### 数据库优化的思路 #### SQL语句优化 - 应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。 - 应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:`select id from t where num is null` ;可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:`select id from t where num=0` - 很多时候用 exists 代替 in 是一个好的选择。 - 用Where子句替换HAVING 子句 因为HAVING 只会在检索出所有记录之后才对结果集进行过滤。 #### 索引优化 #### 数据库结构优化 - 范式优化: 比如消除冗余(节省空间。。) - 反范式优化:比如适当加冗余等(减少join) - 拆分表:分区将数据在物理上分隔开,不同分区的数据可以制定保存在处于不同磁盘上的数据文件里。这样,当对这个表进行查询时,只需要在表分区中进行扫描,而不必进行全表扫描,明显缩短了查询时间,另外处于不同磁盘的分区也将对这个表的数据传输分散在不同的磁盘I/O,一个精心设置的分区可以将数据传输对磁盘I/O竞争均匀地分散开。对数据量大的时时表可采取此方法。可按月自动建表分区。 - 拆分其实又分垂直拆分和水平拆分: - 案例: 简单购物系统暂设涉及如下表: - 1.产品表(数据量10w,稳定) - 2.订单表(数据量200w,且有增长趋势) - 3.用户表 (数据量100w,且有增长趋势) - 以mysql为例讲述下水平拆分和垂直拆分,mysql能容忍的数量级在百万静态数据可以到千万 - **垂直拆分:** - 解决问题:表与表之间的io竞争 - 不解决问题:单表中数据量增长出现的压力 - 方案: 把产品表和用户表放到一个server上 订单表单独放到一个server上 - **水平拆分:** - 解决问题:单表中数据量增长出现的压力 - 不解决问题:表与表之间的io争夺 - 方案:**用户表** 通过性别拆分为男用户表和女用户表,**订单表** 通过已完成和完成中拆分为已完成订单和未完成订单,**产品表** 未完成订单放一个server上,已完成订单表盒男用户表放一个server上,女用户表放一个server上(女的爱购物 哈哈)。 #### 服务器硬件优化 多花钱 ### 存储过程与触发器的区别 触发器与存储过程非常相似,触发器也是SQL语句集,两者唯一的区别是触发器不能用EXECUTE语句调用,而是在用户执行Transact-SQL语句时自动触发(激活)执行。 触发器是在一个修改了指定表中的数据时执行的存储过程。 通常通过创建触发器来强制实现不同表中的逻辑相关数据的引用完整性和一致性。由于用户不能绕过触发器,所以可以用它来强制实施复杂的业务规则,以确保数据的完整性。 触发器不同于存储过程,触发器主要是通过事件执行触发而被执行的,而存储过程可以通过存储过程名称名字而直接调用。当对某一表进行诸如UPDATE、INSERT、DELETE这些操作时,SQLSERVER就会自动执行触发器所定义的SQL语句,从而确保对数据的处理必须符合这些SQL语句所定义的规则。<file_sep>--- title: JVM-类文件结构 author: DreamCat id: 2 date: 2019-11-26 17:02:11 tags: JVM categories: Java --- ## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## 概述 在 Java 中,JVM 可以理解的代码就叫做`字节码`(即扩展名为 `.class` 的文件),它不面向任何特定的处理器,只面向虚拟机。Java 语言通过字节码的方式,在一定程度上解决了传统解释型语言执行效率低的问题,同时又保留了解释型语言可移植的特点。所以 Java 程序运行时比较高效,而且,由于字节码并不针对一种特定的机器,因此,Java 程序无须重新编译便可在多种不同操作系统的计算机上运行。 **可以说`.class`文件是不同的语言在 Java 虚拟机之间的重要桥梁,同时也是支持 Java 跨平台很重要的一个原因。** ## Class文件结构总结 根据 Java 虚拟机规范,类文件由单个 ClassFile 结构组成: ```java ClassFile { u4 magic; //Class 文件的标志 u2 minor_version;//Class 的小版本号 u2 major_version;//Class 的大版本号 u2 constant_pool_count;//常量池的数量 cp_info constant_pool[constant_pool_count-1];//常量池 u2 access_flags;//Class 的访问标记 u2 this_class;//当前类 u2 super_class;//父类 u2 interfaces_count;//接口 u2 interfaces[interfaces_count];//一个类可以实现多个接口 u2 fields_count;//Class 文件的字段属性 field_info fields[fields_count];//一个类会可以有个字段 u2 methods_count;//Class 文件的方法数量 method_info methods[methods_count];//一个类可以有个多个方法 u2 attributes_count;//此类的属性表中的属性数 attribute_info attributes[attributes_count];//属性表集合 } ``` 下面详细介绍一下 Class 文件结构涉及到的一些组件。 **Class文件字节码结构组织示意图** (之前在网上保存的,非常不错,原出处不明): ![参考-JavaGuide-类文件字节码结构组织示意图](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/类文件字节码结构组织示意图.png) ### 魔数 ` u4 magic; //Class 文件的标志` 每个 Class 文件的头四个字节称为魔数(Magic Number),它的唯一作用是**确定这个文件是否为一个能被虚拟机接收的 Class 文件**。 ### Class文件版本 ```java u2 minor_version;//Class 的小版本号 u2 major_version;//Class 的大版本号 ``` 紧接着魔数的四个字节存储的是 Class 文件的版本号:第五和第六是**次版本号**,第七和第八是**主版本号**。 高版本的 Java 虚拟机可以执行低版本编译器生成的 Class 文件,但是低版本的 Java 虚拟机不能执行高版本编译器生成的 Class 文件。所以,我们在实际开发的时候要确保开发的的 JDK 版本和生产环境的 JDK 版本保持一致。 ### 常量池 ```java u2 constant_pool_count;//常量池的数量 cp_info constant_pool[constant_pool_count-1];//常量池 ``` 紧接着主次版本号之后的是常量池,常量池的数量是 constant_pool_count-1(**常量池计数器是从1开始计数的,将第0项常量空出来是有特殊考虑的,索引值为0代表“不引用任何一个常量池项”**)。 常量池主要存放两大常量:字面量和符号引用。字面量比较接近于 Java 语言层面的的常量概念,如文本字符串、声明为 final 的常量值等。而符号引用则属于编译原理方面的概念。包括下面三类常量: - 类和接口的全限定名 - 字段的名称和描述符 - 方法的名称和描述符 常量池中每一项常量都是一个表,这14种表有一个共同的特点:**开始的第一位是一个 u1 类型的标志位 -tag 来标识常量的类型,代表当前这个常量属于哪种常量类型.** ### 访问标志 在常量池结束之后,紧接着的两个字节代表访问标志,这个标志用于识别一些类或者接口层次的访问信息,包括:这个 Class 是类还是接口,是否为 public 或者 abstract 类型,如果是类的话是否声明为 final 等等。 ### 当前类索引,父类索引与接口索引集合 ```java u2 this_class;//当前类 u2 super_class;//父类 u2 interfaces_count;//接口 u2 interfaces[interfaces_count];//一个雷可以实现多个接口 ``` **类索引用于确定这个类的全限定名,父类索引用于确定这个类的父类的全限定名,由于 Java 语言的单继承,所以父类索引只有一个,除了 `java.lang.Object` 之外,所有的 java 类都有父类,因此除了 `java.lang.Object` 外,所有 Java 类的父类索引都不为 0。** **接口索引集合用来描述这个类实现了那些接口,这些被实现的接口将按`implents`(如果这个类本身是接口的话则是`extends`) 后的接口顺序从左到右排列在接口索引集合中。** ### 字段表集合 ```java u2 fields_count;//Class 文件的字段的个数 field_info fields[fields_count];//一个类会可以有个字段 ``` 字段表(field info)用于描述接口或类中声明的变量。字段包括类级变量以及实例变量,但不包括在方法内部声明的局部变量. ### 方法表集合 ```java u2 methods_count;//Class 文件的方法的数量 method_info methods[methods_count];//一个类可以有个多个方法 ``` methods_count 表示方法的数量,而 method_info 表示的方法表。 Class 文件存储格式中对方法的描述与对字段的描述几乎采用了完全一致的方式。方法表的结构如同字段表一样,依次包括了访问标志、名称索引、描述符索引、属性表集合几项。 ### 属性表集合 ```java u2 attributes_count;//此类的属性表中的属性数 attribute_info attributes[attributes_count];//属性表集合 ``` 在 Class 文件,字段表,方法表中都可以携带自己的属性表集合,以用于描述某些场景专有的信息。与 Class 文件中其它的数据项目要求的顺序、长度和内容不同,属性表集合的限制稍微宽松一些,不再要求各个属性表具有严格的顺序,并且只要不与已有的属性名重复,任何人实现的编译器都可以向属性表中写 入自己定义的属性信息,Java 虚拟机运行时会忽略掉它不认识的属性。<file_sep>/** * @program JavaBooks * @description: 装饰器模式 * @author: mf * @create: 2019/10/05 16:46 */ /* 按照单一职责原则,某一个对象只专注于干一件事,而如果要扩展其职能的话,不如想办法分离出一个类来“包装”这个对象,而这个扩展出的类则专注于实现扩展功能。 装饰器模式就可以将新功能动态地附加于现有对象而不改变现有对象的功能。 代理模式专注于对被代理对象的访问; 装饰器模式专注于对被装饰对象附加额外功能。 */ /* 假如有这样的一个需求 假设我去买咖啡,首先服务员给我冲了一杯原味咖啡,我希望服务员给我加些牛奶和白糖混合入原味咖啡中。使用装饰器模式就可以解决这个问题。 */ /** * 咖啡 */ interface Coffee { // 获取价格 double getCost(); // 获取配料 String getIngredients(); } /** * 原味咖啡 * cost:1 * 配料:只有咖啡 */ class SimpleCoffee implements Coffee { @Override public double getCost() { return 1; } @Override public String getIngredients() { return "Coffee"; } } /** * 咖啡对象的装饰器类 * 定义一个Coffe对象的引用,在构造器中进行初始化。并且将getCost()和getIntegredients()方法转发给被装饰对象。 */ abstract class CoffeeDecorator implements Coffee { protected final Coffee decoratedCoffee; /** * 在构造方法中,初始化咖啡对象的引用 */ protected CoffeeDecorator(Coffee coffee) { this.decoratedCoffee = coffee; } /** * 装饰器父类中直接转发"请求"至引用对象 */ public double getCost() { return decoratedCoffee.getCost(); } public String getIngredients() { return decoratedCoffee.getIngredients(); } } // 具体的装饰器类,负责往咖啡中“添加”牛奶,注意看getCost()方法和getIngredients()方法,可以在转发请求之前或者之后,增加功能。 // 如果是代理模式,这里的结构就有所不同,通常代理模式根据运行时的条件来判断是否转发请求。 /** * 此装饰类混合"牛奶"到原味咖啡中 */ class WithMilk extends CoffeeDecorator { public WithMilk(Coffee coffee) { super(coffee); } @Override public double getCost() { double additionalCost = 0.5; return super.getCost() + additionalCost; } @Override public String getIngredients() { String additionalIngredient = "milk"; return super.getIngredients() + ", " + additionalIngredient; } } class WithSugar extends CoffeeDecorator { public WithSugar(Coffee coffee) { super(coffee); } @Override public double getCost() { return super.getCost() + 1; } @Override public String getIngredients() { return super.getIngredients() + ", Sugar"; } } public class DecoratorMode { static void print(Coffee c) { System.out.println("花费了: " + c.getCost()); System.out.println("配料: " + c.getIngredients()); System.out.println("============"); } public static void main(String[] args) { //原味咖啡 Coffee c = new SimpleCoffee(); print(c); //增加牛奶的咖啡 c = new WithMilk(c); print(c); //再加一点糖 c = new WithSugar(c); print(c); } } <file_sep>> 个人感觉JVM这一块,了解和背的知识点挺多,代码并不是特别多,主要是后期调优,需要大量的经验罢了。不过JVM这一块一定要深刻理解。 ## 大纲图 ![JVM面试](http://media.dreamcat.ink/uPic/JVM面试.png) ### 类文件结构 #### 概述 在 Java 中,JVM 可以理解的代码就叫做`字节码`(即扩展名为 `.class` 的文件),它不面向任何特定的处理器,只面向虚拟机。Java 语言通过字节码的方式,在一定程度上解决了传统解释型语言执行效率低的问题,同时又保留了解释型语言可移植的特点。所以 Java 程序运行时比较高效,而且,由于字节码并不针对一种特定的机器,因此,Java 程序无须重新编译便可在多种不同操作系统的计算机上运行。 **可以说`.class`文件是不同的语言在 Java 虚拟机之间的重要桥梁,同时也是支持 Java 跨平台很重要的一个原因。** #### 类文件总结构 ```java ClassFile { u4 magic; // 魔数 Class 文件的标志 这都没话可说的 u2 minor_version;//Class 的小版本号 u2 major_version;//Class 的大版本号 u2 constant_pool_count;//常量池的数量 cp_info constant_pool[constant_pool_count-1];//常量池 待会说 u2 access_flags;//Class 的访问标记 u2 this_class;//当前类 u2 super_class;//父类 u2 interfaces_count;//接口 u2 interfaces[interfaces_count];//一个类可以实现多个接口 u2 fields_count;//Class 文件的字段属性 field_info fields[fields_count];//一个类会可以有个字段 描述接口或类中声明的变量 但不包括在方法内部声明的局部变量. u2 methods_count;//Class 文件的方法数量 method_info methods[methods_count];//一个类可以有个多个方法 和字段表性质一样 u2 attributes_count;//此类的属性表中的属性数 attribute_info attributes[attributes_count];//属性表集合 } ``` #### 静态常量池 常量池主要存放两大常量:**字面量和符号引用**。字面量比较接近于 Java 语言层面的的常量概念,如文本字符串、声明为 final 的常量值等。而符号引用则属于编译原理方面的概念。包括下面三类常量: - 类和接口的全限定名 - 字段的名称和描述符 - 方法的名称和描述符 常量池的好处:常量池是为了避免频繁的创建和销毁对象而影响系统性能,其实现了对象的共享。 举个例子:字符串常量池,在编译阶段就把所有的字符串文字放到一个常量池中。 1. 节省内存空间:常量池中所有相同的字符串常量被合并,只占用一个空间。 2. 节省运行时间:比较字符串时,==比equals()快。对于两个引用变量,只用==判断引用是否相等,也就可以判断实际值是否相等。 静态常量池用于存放编译期生成的各种**字面量和符号引用**,这部分内容将在类加载后存放到方法区的**运行时常量池**中。其中符号引用其实引用的就是常量池里面的字符串,但**符号引用不是直接存储字符串,而是存储字符串在常量池里的索引**。 当Class文件被加载完成后,java虚拟机会将静态常量池里的内容转移到运行时常量池里,在静态常量池的**符号引用有一部分是会被转变为直接引用**的,比如说类的静态方法或私有方法,实例构造方法,父类方法,这是因为这些方法不能被重写其他版本,所以能在加载的时候就可以将符号引用转变为直接引用,而其他的一些方法是在这个方法被第一次调用的时候才会将符号引用转变为直接引用的。 #### 运行时常量池 运行时常量池(Runtime Constant Pool)是**方法区**的一部分。对于运行时常量池,Java虚拟机规范没有做任何细节的要求,不同的提供商实现的虚拟机可以按照自己的需要来实现这个内存区域。不过,一般来说,除了保存Class文件中描述的符号引用外,还会把翻译出来的直接引用也存储在运行时常量池中。 运行时常量池还有个更重要的的特征:**动态性**。Java要求,编译期的常量池的内容可以进入运行时常量池,运行时产生的常量也可以放入池中。常用的是String类的intern()方法。 既然运行时常量池是方法区的一部分自然会受到方法区内存的限制,当常量池无法再申请到内存时会抛出**OutOfMemoryError**异常。 #### 字符串常量池 字符串常量池存在运行时常量池之中(在JDK7之前存在运行时常量池之中,在JDK7已经将其转移到堆中)。 字符串常量池的存在使JVM提高了性能和减少了内存开销。 1. 每当我们使用字面量(String s=“1”;)创建字符串常量时,JVM会首先检查字符串常量池,如果该字符串已经存在常量池中,那么就将此字符串对象的地址赋值给引用s(引用s在Java栈。如果字符串不存在常量池中,就会实例化该字符串并且将其放到常量池中,并将此字符串对象的地址赋值给引用s(引用s在Java栈中)。 2. 每当我们使用关键字new(String s=new String(”1”);)创建字符串常量时,JVM会首先检查字符串常量池,如果该字符串已经存在常量池中,那么不再在字符串常量池创建该字符串对象,而直接堆中创建该对象的副本,然后将堆中对象的地址赋值给引用s,如果字符串不存在常量池中,就会实例化该字符串并且将其放到常量池中,然后在堆中创建该对象的副本,然后将堆中对象的地址赋值给引用s。 #### 三者关系 JVM在执行某个类的时候,必须经过加载、连接、初始化,而连接又包括验证、准备、解析三个阶段。 静态常量池用于存放编译期生成的各种字面量和符号引用,而当类加载到内存中后,jvm就会将静态常量池中的内容存放到运行时常量池中。而字符串常量池存的是引用值,其存在于运行时常量池之中。 #### 版本变化 ##### 1.6 - 静态常量池在Class文件中。 - 运行时常量池在Perm Gen区(也就是方法区)中。(所谓的方法区是在Java堆的一个逻辑部分,为了与Java堆区别开来,也称其为非堆(Non-Heap),那么Perm Gen(永久代)区也被视为方法区的一种实现。) - 字符串常量池在运行时常量池中。 ##### 1.7 - 静态常量池在Class文件中。 - 运行时常量池依然在Perm Gen区(也就是方法区)中。在JDK7版本中,永久代的转移工作就已经开始了,将譬如符号引用(Symbols)转移到了native heap;字面量(interned strings)转移到了java heap;类的静态变量(class statics)转移到了java heap。但是运行时常量池依然还存在,只是很多内容被转移,其只存着这些被转移的引用。网上流传的一些测试运行时常量池转移的方式或者代码,其实是对字符串常量池转移的测试。 - 字符串常量池被分配到了Java堆的主要部分(known as the young and old generations)。也就是字符串常量池从运行时常量池分离出来了。 ##### 1.8 - 静态常量池在Class文件中。 - JVM已经将运行时常量池从方法区中移了出来,在Java 堆(Heap)中开辟了一块区域存放运行时常量池。同时永久代被移除,以元空间代替。元空间并不在虚拟机中,而是使用本地内存。因此,默认情况下,元空间的大小仅受本地内存限制。其主要用于存放一些元数据。 - 字符串常量池存在于Java堆中。 ### 类加载过程 系统加载 Class 类型的文件主要三步:**加载->连接->初始化**。连接过程又可分为三步:**验证->准备->解析**。 ![类加载过程](http://media.dreamcat.ink/uPic/类加载过程.png) #### 加载 类加载过程的第一步,主要完成下面3件事情: 1. 通过全类名获取定义此类的二进制字节流 2. 将字节流所代表的静态存储结构转换为方法区的运行时数据结构 3. 在内存中生成一个代表该类的 Class 对象,作为方法区这些数据的访问入口 加载阶段和连接阶段的部分内容是交叉进行的,加载阶段尚未结束,连接阶段可能就已经开始了。 #### 验证 - 文件格式验证:主要验证Class文件是否规范等。 - 元数据验证:对字节码描述的信息语义分析等。 - 字节码验证:确保语义是ok的。 - 符号引用验证:确保解析动作能执行。 #### 准备 **准备阶段是正式为类变量分配内存并设置类变量初始值的阶段**,这些内存都将在方法区中分配。对于该阶段有以下几点需要注意: 1. 这时候进行内存分配的仅包括类变量(static),而不包括实例变量,实例变量会在对象实例化时随着对象一块分配在 Java 堆中。 2. 这里所设置的初始值"通常情况"下是数据类型默认的零值(如0、0L、null、false等),比如我们定义了`public static int value=111` ,那么 value 变量在准备阶段的初始值就是 0 而不是111(初始化阶段才会复制)。特殊情况:比如给 value 变量加上了 fianl 关键字`public static final int value=111` ,那么准备阶段 value 的值就被复制为 111。 #### 解析 解析阶段是虚拟机将常量池内的符号引用替换为直接引用的过程。解析动作主要针对类或接口、字段、类方法、接口方法、方法类型、方法句柄和调用限定符7类符号引用进行。 符号引用就是一组符号来描述目标,可以是任何字面量。**直接引用**就是直接指向目标的指针、相对偏移量或一个间接定位到目标的句柄。在程序实际运行时,只有符号引用是不够的,举个例子:在程序执行方法时,系统需要明确知道这个方法所在的位置。Java 虚拟机为每个类都准备了一张方法表来存放类中所有的方法。当需要调用一个类的方法的时候,只要知道这个方法在方发表中的偏移量就可以直接调用该方法了。通过解析操作符号引用就可以直接转变为目标方法在类中方法表的位置,从而使得方法可以被调用。 综上,解析阶段是虚拟机将常量池内的符号引用替换为直接引用的过程,也就是得到类或者字段、方法在内存中的指针或者偏移量。 #### 初始化 初始化是类加载的最后一步,也是真正执行类中定义的 Java 程序代码(字节码),初始化阶段是执行类构造器 `<clinit> ()`方法的过程。 对于`<clinit>()` 方法的调用,虚拟机会自己确保其在多线程环境中的安全性。因为 `<clinit>()` 方法是带锁线程安全,所以在多线程环境下进行类初始化的话可能会引起死锁,并且这种死锁很难被发现。 对于初始化阶段,虚拟机严格规范了有且只有5种情况下,必须对类进行初始化: 1. 当遇到 new 、 getstatic、putstatic或invokestatic 这4条直接码指令时,比如 new 一个类,读取一个静态字段(未被 final 修饰)、或调用一个类的静态方法时。 2. 使用 `java.lang.reflect` 包的方法对类进行反射调用时 ,如果类没初始化,需要触发其初始化。 3. 初始化一个类,如果其父类还未初始化,则先触发该父类的初始化。 4. 当虚拟机启动时,用户需要定义一个要执行的主类 (包含 main 方法的那个类),虚拟机会先初始化这个类。 5. 当使用 JDK1.7 的动态动态语言时,如果一个 MethodHandle 实例的最后解析结构为 REF_getStatic、REF_putStatic、REF_invokeStatic、的方法句柄,并且这个句柄没有初始化,则需要先触发器初始化。 ### 类加载器 JVM 中内置了三个重要的 ClassLoader,除了 BootstrapClassLoader 其他类加载器均由 Java 实现且全部继承自`java.lang.ClassLoader`: 1. **BootstrapClassLoader(启动类加载器)** :最顶层的加载类,由C++实现,负责加载 `%JAVA_HOME%/lib`目录下的jar包和类或者或被 `-Xbootclasspath`参数指定的路径中的所有类。 2. **ExtensionClassLoader(扩展类加载器)** :主要负责加载目录 `%JRE_HOME%/lib/ext` 目录下的jar包和类,或被 `java.ext.dirs` 系统变量所指定的路径下的jar包。 3. **AppClassLoader(应用程序类加载器)** :面向我们用户的加载器,负责加载当前应用classpath下的所有jar包和类。 #### 双亲委派 每一个类都有一个对应它的类加载器。系统中的 ClassLoder 在协同工作的时候会默认使用 **双亲委派模型** 。即在类加载的时候,系统会首先判断当前类是否被加载过。已经被加载的类会直接返回,否则才会尝试加载。加载的时候,首先会把该请求委派该父类加载器的 `loadClass()` 处理,因此所有的请求最终都应该传送到顶层的启动类加载器 `BootstrapClassLoader` 中。当父类加载器无法处理时,才由自己来处理。当父类加载器为null时,会使用启动类加载器 `BootstrapClassLoader` 作为父类加载器。 ![ClassLoader](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/classloader_WPS图片.png) ```java public class ClassLoaderDemo { public static void main(String[] args) { System.out.println("ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader()); System.out.println("The Parent of ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader().getParent()); System.out.println("The GrandParent of ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader().getParent().getParent()); } } // ClassLodarDemo's ClassLoader is sun.misc.Launcher$AppClassLoader@18b4aac2 // The Parent of ClassLodarDemo's ClassLoader is sun.misc.Launcher$ExtClassLoader@1b6d3586 // The GrandParent of ClassLodarDemo's ClassLoader is null ``` `AppClassLoader`的父类加载器为`ExtClassLoader` `ExtClassLoader`的父类加载器为null,**null并不代表`ExtClassLoader`没有父类加载器,而是 `BootstrapClassLoader`** 。 其实这个双亲翻译的容易让别人误解,我们一般理解的双亲都是父母,这里的双亲更多地表达的是“父母这一辈”的人而已,并不是说真的有一个 Mother ClassLoader 和一个 Father ClassLoader 。另外,类加载器之间的“父子”关系也不是通过继承来体现的,是由“优先级”来决定。 **双亲委派的好处**: 双亲委派模型保证了Java程序的稳定运行,可以避免类的重复加载(JVM 区分不同类的方式不仅仅根据类名,相同的类文件被不同的类加载器加载产生的是两个不同的类),也保证了 Java 的核心 API 不被篡改。如果没有使用双亲委派模型,而是每个类加载器加载自己的话就会出现一些问题,比如我们编写一个称为 `java.lang.Object` 类的话,那么程序运行的时候,系统就会出现多个不同的 `Object` 类。 #### 自定义类加载器 除了 `BootstrapClassLoader` 其他类加载器均由 Java 实现且全部继承自`java.lang.ClassLoader`。如果我们要自定义自己的类加载器,很明显需要继承 `ClassLoader`。 ### jvm内存(运行时区域) #### 1.8之前 ![参考-JavaGuide-内存区域](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3/JVM%E8%BF%90%E8%A1%8C%E6%97%B6%E6%95%B0%E6%8D%AE%E5%8C%BA%E5%9F%9F.png) #### 1.8之后 ![参考-JavaGuide-内存区域](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3Java%E8%BF%90%E8%A1%8C%E6%97%B6%E6%95%B0%E6%8D%AE%E5%8C%BA%E5%9F%9FJDK1.8.png) 按照1.8进行总结 **线程私有的:** - 程序计数器 - 虚拟机栈 - 本地方法栈 **线程共享的:** - 堆 - 直接内存 (非运行时数据区的一部分) #### 程序计数器 说白了就是 1. 字节码解释器通过改变程序计数器来依次读取指令,从而实现代码的流程控制,如:顺序执行、选择、循环、异常处理。 2. 在多线程的情况下,程序计数器用于记录当前线程执行的位置,从而当线程被切换回来的时候能够知道该线程上次运行到哪儿了。 **注意:程序计数器是唯一一个不会出现 OutOfMemoryError 的内存区域,它的生命周期随着线程的创建而创建,随着线程的结束而死亡。** #### Java虚拟机栈 与程序计数器一样,Java 虚拟机栈也是线程**私有**的,它的生命周期和线程相同,描述的是 Java **方法执行的内存模型**,每次方法调用的数据都是通过栈传递的。 **Java 内存可以粗糙的区分为堆内存(Heap)和栈内存 (Stack),其中栈就是现在说的虚拟机栈,或者说是虚拟机栈中局部变量表部分。** - 局部变量表 - 操作数栈 - 8大基本类型 - 对象引用:可能是一个指向对象起始地址的引用指针,也可能是指向一个代表对象的句柄或其他与此对象相关的位置 - 动态链接 - 方法出口 **Java 虚拟机栈会出现两种异常:StackOverFlowError 和 OutOfMemoryError。** - **StackOverFlowError:** 若 Java 虚拟机栈的内存大小不允许动态扩展,那么当线程请求栈的深度超过当前 Java 虚拟机栈的最大深度的时候,就抛出 StackOverFlowError 异常。 - **OutOfMemoryError:** 若 Java 虚拟机栈的内存大小允许动态扩展,且当线程请求栈时内存用完了,无法再动态扩展了,此时抛出 OutOfMemoryError 异常。 Java 虚拟机栈也是线程私有的,每个线程都有各自的 Java 虚拟机栈,而且随着线程的创建而创建,随着线程的死亡而死亡。 Java 栈可用类比数据结构中栈,Java 栈中保存的主要内容是栈帧,每一次函数调用都会有一个对应的栈帧被压入 Java 栈,每一个函数调用结束后,都会有一个栈帧被弹出。 #### 本地方法栈 和虚拟机栈所发挥的作用非常相似,区别是: **虚拟机栈为虚拟机执行 Java 方法 (也就是字节码)服务,而本地方法栈则为虚拟机使用到的 Native 方法服务。** 其他和Java虚拟机差不多的 #### 堆 Java 虚拟机所管理的内存中最大的一块,Java 堆是所有线程共享的一块内存区域,在虚拟机启动时创建。**此内存区域的唯一目的就是存放对象实例,几乎所有的对象实例以及数组都在这里分配内存。** Java 堆是垃圾收集器管理的主要区域,因此也被称作**GC 堆(Garbage Collected Heap)**.从垃圾回收的角度,由于现在收集器基本都采用分代垃圾收集算法,所以 Java 堆还可以细分为:新生代和老年代:再细致一点有:Eden 空间、From Survivor、To Survivor 空间等。**进一步划分的目的是更好地回收内存,或者更快地分配内存。** ![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3%E5%A0%86%E7%BB%93%E6%9E%84.png) 上图所示的 eden 区、s0("From") 区、s1("To") 区都属于新生代,tentired 区属于老年代。大部分情况,对象都会首先在 Eden 区域分配,在一次新生代垃圾回收后,如果对象还存活,则会进入 s1("To"),并且对象的年龄还会加 1(Eden 区->Survivor 区后对象的初始年龄变为 1),当它的年龄增加到一定程度(默认为 15 岁),就会被晋升到老年代中。对象晋升到老年代的年龄阈值,可以通过参数 `-XX:MaxTenuringThreshold` 来设置。经过这次GC后,Eden区和"From"区已经被清空。这个时候,"From"和"To"会交换他们的角色,也就是新的"To"就是上次GC前的“From”,新的"From"就是上次GC前的"To"。不管怎样,都会保证名为To的Survivor区域是空的。Minor GC会一直重复这样的过程,直到“To”区被填满,"To"区被填满之后,会将所有对象移动到年老代中。 #### 方法区 方法区与 Java 堆一样,是各个线程共享的内存区域,它用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。虽然 Java 虚拟机规范把方法区描述为堆的一个逻辑部分,但是它却有一个别名叫做 **Non-Heap(非堆)**,目的应该是与 Java 堆区分开来。 JDK 1.8 的时候,方法区(HotSpot 的永久代)被彻底移除了(JDK1.7 就已经开始了),取而代之是元空间,元空间使用的是直接内存。 #### 运行时常量池 运行时常量池是方法区的一部分。Class 文件中除了有类的版本、字段、方法、接口等描述信息外,还有常量池信息(用于存放编译期生成的各种字面量和符号引用)以及符号引用替换为直接引用。JDK1.8 及之后版本的 JVM 已经将运行时常量池从方法区中移了出来,在 Java 堆(Heap)中开辟了一块区域存放运行时常量池。 #### 直接内存 直接内存并不是虚拟机运行时数据区的一部分,也不是虚拟机规范中定义的内存区域,但是这部分内存也被频繁地使用。而且也可能导致 OutOfMemoryError 异常出现。本机直接内存的分配不会受到 Java 堆的限制,但是,既然是内存就会受到本机总内存大小以及处理器寻址空间的限制。 #### 对象创建 ![参考-JavaGuide-对象创建的过程](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/Java%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%BF%87%E7%A8%8B.png) 1. 类加载检查,虚拟机遇到一条 new 指令时,首先将去检查这个指令的参数是否能在常量池中定位到这个类的符号引用,并且检查这个符号引用代表的类是否已被加载过、解析和初始化过。如果没有,那必须先执行相应的类加载过程。 2. 分配内存,在**类加载检查**通过后,接下来虚拟机将为新生对象**分配内存**。对象所需的内存大小在类加载完成后便可确定,为对象分配空间的任务等同于把一块确定大小的内存从 Java 堆中划分出来。**分配方式**有 **“指针碰撞”** 和 **“空闲列表”** 两种,**选择那种分配方式由 Java 堆是否规整决定,而 Java 堆是否规整又由所采用的垃圾收集器是否带有压缩整理功能决定**。 1. **内存分配的两种方式:(补充内容,需要掌握)** - 选择以上两种方式中的哪一种,取决于 Java 堆内存是否规整。而 Java 堆内存是否规整,取决于 GC 收集器的算法是"标记-清除",还是"标记-整理"(也称作"标记-压缩"),值得注意的是,复制算法内存也是规整的 - ![参考-JavaGuide-内存分配](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F.png) 2. **内存分配并发问题(补充内容,需要掌握)** - **CAS+失败重试:** CAS 是乐观锁的一种实现方式。所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。**虚拟机采用 CAS 配上失败重试的方式保证更新操作的原子性。** - **TLAB:** 为每一个线程预先在 Eden 区分配一块儿内存,JVM 在给线程中的对象分配内存时,首先在 TLAB 分配,当对象大于 TLAB 中的剩余内存或 TLAB 的内存已用尽时,再采用上述的 CAS 进行内存分配 3. 初始化零值,内存分配完成后,虚拟机需要将分配到的内存空间都初始化为零值(不包括对象头),这一步操作保证了对象的实例字段在 Java 代码中可以不赋初始值就直接使用,程序能访问到这些字段的数据类型所对应的零值。 4. 设置对象头,初始化零值完成之后,**虚拟机要对对象进行必要的设置**,例如这个对象是那个类的实例、如何才能找到类的元数据信息、对象的哈希码、对象的 GC 分代年龄等信息。 **这些信息存放在对象头中。** 另外,根据虚拟机当前运行状态的不同,如是否启用偏向锁等,对象头会有不同的设置方式。 5. 执行init方法,在上面工作都完成之后,从虚拟机的视角来看,一个新的对象已经产生了,但从 Java 程序的视角来看,对象创建才刚开始,`` 方法还没有执行,所有的字段都还为零。所以一般来说,执行 new 指令之后会接着执行 `` 方法,把对象按照程序员的意愿进行初始化,这样一个真正可用的对象才算完全产生出来。 ##### 内存布局 在 Hotspot 虚拟机中,对象在内存中的布局可以分为 3 块区域:**对象头**、**实例数据**和**对齐填充**。 **Hotspot 虚拟机的对象头包括两部分信息**,**第一部分用于存储对象自身的自身运行时数据**(哈希码、GC 分代年龄、锁状态标志等等),**另一部分是类型指针**,即对象指向它的类元数据的指针,虚拟机通过这个指针来确定这个对象是那个类的实例。 **实例数据部分是对象真正存储的有效信息**,也是在程序中所定义的各种类型的字段内容。 **对齐填充部分不是必然存在的,也没有什么特别的含义,仅仅起占位作用。** 因为 Hotspot 虚拟机的自动内存管理系统要求对象起始地址必须是 8 字节的整数倍,换句话说就是对象的大小必须是 8 字节的整数倍。而对象头部分正好是 8 字节的倍数(1 倍或 2 倍),因此,当对象实例数据部分没有对齐时,就需要通过对齐填充来补全。 ##### 对象的访问方式 建立对象就是为了使用对象,我们的 Java 程序通过栈上的 reference 数据来操作堆上的具体对象。对象的访问方式由虚拟机实现而定,目前主流的访问方式有**①使用句柄**和**②直接指针**两种: ###### 使用句柄 如果使用句柄的话,那么 Java 堆中将会划分出一块内存来作为句柄池,reference 中存储的就是对象的句柄地址,而句柄中包含了对象实例数据与类型数据各自的具体地址信息; ![参考-JavaGuide-句柄](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AE%BF%E9%97%AE%E5%AE%9A%E4%BD%8D-%E4%BD%BF%E7%94%A8%E5%8F%A5%E6%9F%84.png) ###### 直接指针 如果使用直接指针访问,那么 Java 堆对象的布局中就必须考虑如何放置访问类型数据的相关信息,而 reference 中存储的直接就是对象的地址。 ![参考-JavaGuide-直接指针](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%AE%BF%E9%97%AE%E5%AE%9A%E4%BD%8D-%E7%9B%B4%E6%8E%A5%E6%8C%87%E9%92%88.png) 这两种对象访问方式各有优势。使用句柄来访问的最大好处是 reference 中存储的是**稳定**的句柄地址,在对象被移动时只会改变句柄中的实例数据指针,而 **reference 本身不需要修改**。使用直接指针访问方式最大的好处就是**速度快**,它节省了一次指针定位的时间开销。 ### 垃圾回收 Java 堆是垃圾收集器管理的主要区域,因此也被称作**GC 堆(Garbage Collected Heap)**.从垃圾回收的角度,由于现在收集器基本都采用分代垃圾收集算法,所以 Java 堆还可以细分为:新生代和老年代:再细致一点有:Eden 空间、From Survivor、To Survivor 空间等。**进一步划分的目的是更好地回收内存,或者更快地分配内存。** #### 对象优先在Eden区分配 目前主流的垃圾收集器都会采用分代回收算法,因此需要将堆内存分为新生代和老年代,这样我们就可以根据各个年代的特点选择合适的垃圾收集算法。 大多数情况下,对象在新生代中 eden 区分配。当 eden 区没有足够空间进行分配时,虚拟机将发起一次 Minor GC.下面我们来进行实际测试以下。 在测试之前我们先来看看 **Minor GC 和 Full GC 有什么不同呢?** - **新生代 GC(Minor GC)**:指发生新生代的的垃圾收集动作,Minor GC 非常频繁,回收速度一般也比较快。 - **老年代 GC(Major GC/Full GC)**:指发生在老年代的 GC,出现了 Major GC 经常会伴随至少一次的 Minor GC(并非绝对),Major GC 的速度一般会比 Minor GC 的慢 10 倍以上。 #### 大对象直接进入老年代 大对象就是需要大量连续内存空间的对象(比如:字符串、数组)。 **为什么要这样呢?**为了避免为大对象分配内存时由于分配担保机制带来的复制而降低效率。 #### 长期存活的对象进入老年代 如果对象在 Eden 出生并经过第一次 Minor GC 后仍然能够存活,并且能被 Survivor 容纳的话,将被移动到 Survivor 空间中,并将对象年龄设为 1.对象在 Survivor 中每熬过一次 MinorGC,年龄就增加 1 岁,当它的年龄增加到一定程度(默认为 15 岁),就会被晋升到老年代中。对象晋升到老年代的年龄阈值,可以通过参数 `-XX:MaxTenuringThreshold` 来设置。 #### 如何判断对象死亡 ![参考-JavaGuide-对象死亡](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/11034259.jpg) ##### 引用计数法 给对象中添加一个引用计数器,每当有一个地方引用它,计数器就加 1;当引用失效,计数器就减 1;任何时候计数器为 0 的对象就是不可能再被使用的。 **这个方法实现简单,效率高,但是目前主流的虚拟机中并没有选择这个算法来管理内存,其最主要的原因是它很难解决对象之间相互循环引用的问题。** 所谓对象之间的相互引用问题,如下面代码所示:除了对象 objA 和 objB 相互引用着对方之外,这两个对象之间再无任何引用。但是他们因为互相引用对方,导致它们的引用计数器都不为 0,于是引用计数算法无法通知 GC 回收器回收他们。 ```java public class ReferenceCountingGc { Object instance = null; public static void main(String[] args) { ReferenceCountingGc objA = new ReferenceCountingGc(); ReferenceCountingGc objB = new ReferenceCountingGc(); objA.instance = objB; // 循环引用 objB.instance = objA; // 循环引用 objA = null; objB = null; } } ``` ##### 可达性分析 这个算法的基本思想就是通过一系列的称为 **“GC Roots”** 的对象作为起点,从这些节点开始向下搜索,节点所走过的路径称为引用链,当一个对象到 GC Roots 没有任何引用链相连的话,则证明此对象是不可用的。 ![参考-JavaGuide-可达性分析算法 ](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/72762049.jpg) 哪些可以作为GC Roots的根 - 虚拟机栈(栈帧中的局部变量区,也叫局部变量表)中应用的对象。 - 方法区中的类静态属性引用的对象 - 方法区中常量引用的对象 - 本地方法栈中JNI(native方法)引用的对象 在这里就聊一下引用 ##### 四大引用 **1.强引用(StrongReference)** 以前我们使用的大部分引用实际上都是强引用,这是使用最普遍的引用。如果一个对象具有强引用,那就类似于**必不可少的生活用品**,垃圾回收器绝不会回收它。当内存空间不足,Java 虚拟机宁愿抛出 OutOfMemoryError 错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足问题。 **2.软引用(SoftReference)** 如果一个对象只具有软引用,那就类似于**可有可无的生活用品**。如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。 软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,JAVA 虚拟机就会把这个软引用加入到与之关联的引用队列中。 **3.弱引用(WeakReference)** 如果一个对象只具有弱引用,那就类似于**可有可无的生活用品**。弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程, 因此不一定会很快发现那些只具有弱引用的对象。 弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java 虚拟机就会把这个弱引用加入到与之关联的引用队列中。 **4.虚引用(PhantomReference)** "虚引用"顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。 **虚引用主要用来跟踪对象被垃圾回收的活动**。 **虚引用与软引用和弱引用的一个区别在于:** 虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。 ##### 不可达的对象并非“非死不可” 即使在可达性分析法中不可达的对象,也并非是“非死不可”的,这时候它们暂时处于“缓刑阶段”,要真正宣告一个对象死亡,至少要经历两次标记过程;可达性分析法中不可达的对象被第一次标记并且进行一次筛选,筛选的条件是此对象是否有必要执行 finalize 方法。当对象没有覆盖 finalize 方法,或 finalize 方法已经被虚拟机调用过时,虚拟机将这两种情况视为没有必要执行。 被判定为需要执行的对象将会被放在一个队列中进行第二次标记,除非这个对象与引用链上的任何一个对象建立关联,否则就会被真的回收。 ##### 如何判断一个常量是废弃常量 运行时常量池主要回收的是废弃的常量。那么,我们如何判断一个常量是废弃常量呢? 假如在常量池中存在字符串 "abc",如果当前没有任何 String 对象引用该字符串常量的话,就说明常量 "abc" 就是废弃常量,如果这时发生内存回收的话而且有必要的话,"abc" 就会被系统清理出常量池。 ##### 如何判断一个类是无用的类 判定一个常量是否是“废弃常量”比较简单,而要判定一个类是否是“无用的类”的条件则相对苛刻许多。类需要同时满足下面 3 个条件才能算是 **“无用的类”** : - 该类所有的实例都已经被回收,也就是 Java 堆中不存在该类的任何实例。 - 加载该类的 ClassLoader 已经被回收。 - 该类对应的 java.lang.Class 对象没有在任何地方被引用,无法在任何地方通过反射访问该类的方法。 虚拟机可以对满足上述 3 个条件的无用类进行回收,这里说的仅仅是“可以”,而并不是和对象一样不使用了就会必然被回收。 #### 垃圾回收算法 ##### 标记-清除算法 该算法分为“标记”和“清除”阶段:首先标记出所有需要回收的对象,在标记完成后统一回收所有被标记的对象。它是最基础的收集算法,后续的算法都是对其不足进行改进得到。这种垃圾收集算法会带来两个明显的问题: 1. 效率问题 2. 空间问题(标记清除后会产生大量不连续的碎片) <img src="http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/63707281.jpg" alt="公众号" width="500px"> ##### 标记-整理算法 根据老年代的特点提出的一种标记算法,标记过程仍然与“标记-清除”算法一样,但后续步骤不是直接对可回收对象回收,而是让所有存活的对象向一端移动,然后直接清理掉端边界以外的内存。 ![标记-整理](https://www.pdai.tech/_images/pics/902b83ab-8054-4bd2-898f-9a4a0fe52830.jpg) ##### 复制算法 为了解决效率问题,“复制”收集算法出现了。它可以将内存分为大小相同的两块,每次使用其中的一块。当这一块的内存使用完后,就将还存活的对象复制到另一块去,然后再把使用的空间一次清理掉。这样就使每次的内存回收都是对内存区间的一半进行回收。 <img src="http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/90984624.jpg" alt="公众号" width="500px"> #### 分代收集算法 **比如在新生代中,每次收集都会有大量对象死去,所以可以选择复制算法,只需要付出少量对象的复制成本就可以完成每次垃圾收集。而老年代的对象存活几率是比较高的,而且没有额外的空间对它进行分配担保,所以我们必须选择“标记-清除”或“标记-整理”算法进行垃圾收集。** ### 垃圾收集器 - Serial收集器 - ParNew收集器 - Parallel Scavenge收集器 - CMS收集器 - G1收集器 #### Serial收集器 Serial(串行)收集器收集器是最基本、历史最悠久的垃圾收集器了。大家看名字就知道这个收集器是一个单线程收集器了。它的 **“单线程”** 的意义不仅仅意味着它只会使用一条垃圾收集线程去完成垃圾收集工作,更重要的是它在进行垃圾收集工作的时候必须暂停其他所有的工作线程( **"Stop The World"** ),直到它收集结束。 **新生代采用复制算法,老年代采用标记-整理算法。** ![ Serial 收集器 ](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/46873026.jpg) 虚拟机的设计者们当然知道 Stop The World 带来的不良用户体验,所以在后续的垃圾收集器设计中停顿时间在不断缩短(仍然还有停顿,寻找最优秀的垃圾收集器的过程仍然在继续)。 但是 Serial 收集器有没有优于其他垃圾收集器的地方呢?当然有,它**简单而高效(与其他收集器的单线程相比)**。Serial 收集器由于没有线程交互的开销,自然可以获得很高的单线程收集效率。Serial 收集器对于运行在 Client 模式下的虚拟机来说是个不错的选择。 #### ParNew收集器 **ParNew 收集器其实就是 Serial 收集器的多线程版本,除了使用多线程进行垃圾收集外,其余行为(控制参数、收集算法、回收策略等等)和 Serial 收集器完全一样。** **新生代采用复制算法,老年代采用标记-整理算法。** ![ParNew 收集器 ](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/22018368.jpg) 它是许多运行在 Server 模式下的虚拟机的首要选择,除了 Serial 收集器外,只有它能与 CMS 收集器(真正意义上的并发收集器,后面会介绍到)配合工作。 **并行和并发概念补充:** - **并行(Parallel)** :指多条垃圾收集线程并行工作,但此时用户线程仍然处于等待状态。 - **并发(Concurrent)**:指用户线程与垃圾收集线程同时执行(但不一定是并行,可能会交替执行),用户程序在继续运行,而垃圾收集器运行在另一个 CPU 上。 #### Parallel Scavenge收集器 Parallel Scavenge 收集器也是使用复制算法的多线程收集器,它看上去几乎和ParNew都一样。 **Parallel Scavenge 收集器关注点是吞吐量(高效率的利用 CPU)。CMS 等垃圾收集器的关注点更多的是用户线程的停顿时间(提高用户体验)。所谓吞吐量就是 CPU 中用于运行用户代码的时间与 CPU 总消耗时间的比值。** Parallel Scavenge 收集器提供了很多参数供用户找到最合适的停顿时间或最大吞吐量,如果对于收集器运作不太了解的话,手工优化存在困难的话可以选择把内存管理优化交给虚拟机去完成也是一个不错的选择。 **新生代采用复制算法,老年代采用标记-整理算法。** #### Serial Old 收集器 **Serial 收集器的老年代版本**,它同样是一个单线程收集器。它主要有两大用途:一种用途是在 JDK1.5 以及以前的版本中与 Parallel Scavenge 收集器搭配使用,另一种用途是作为 CMS 收集器的后备方案。 #### Parallel Old 收集器 **Parallel Scavenge 收集器的老年代版本**。使用多线程和“标记-整理”算法。在注重吞吐量以及 CPU 资源的场合,都可以优先考虑 Parallel Scavenge 收集器和 Parallel Old 收集器。 #### CMS收集器 **CMS(Concurrent Mark Sweep)收集器是一种以获取最短回收停顿时间为目标的收集器。它非常符合在注重用户体验的应用上使用。** **CMS(Concurrent Mark Sweep)收集器是 HotSpot 虚拟机第一款真正意义上的并发收集器,它第一次实现了让垃圾收集线程与用户线程(基本上)同时工作。** 从名字中的**Mark Sweep**这两个词可以看出,CMS 收集器是一种 **“标记-清除”算法**实现的,它的运作过程相比于前面几种垃圾收集器来说更加复杂一些。整个过程分为四个步骤: - **初始标记:** 暂停所有的其他线程,并记录下直接与 root 相连的对象,速度很快 ; - **并发标记:** 同时开启 GC 和用户线程,用一个闭包结构去记录可达对象。但在这个阶段结束,这个闭包结构并不能保证包含当前所有的可达对象。因为用户线程可能会不断的更新引用域,所以 GC 线程无法保证可达性分析的实时性。所以这个算法里会跟踪记录这些发生引用更新的地方。 - **重新标记:** 重新标记阶段就是为了修正并发标记期间因为用户程序继续运行而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段的时间稍长,远远比并发标记阶段时间短 - **并发清除:** 开启用户线程,同时 GC 线程开始对为标记的区域做清扫。 ![CMS 垃圾收集器 ](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-8-27/82825079.jpg) 从它的名字就可以看出它是一款优秀的垃圾收集器,主要优点:**并发收集、低停顿**。但是它有下面三个明显的缺点: - **对 CPU 资源敏感;** - **无法处理浮动垃圾;** - **它使用的回收算法-“标记-清除”算法会导致收集结束时会有大量空间碎片产生。** #### G1收集器 **G1 (Garbage-First) 是一款面向服务器的垃圾收集器,主要针对配备多颗处理器及大容量内存的机器. 以极高概率满足 GC 停顿时间要求的同时,还具备高吞吐量性能特征.** 被视为 JDK1.7 中 HotSpot 虚拟机的一个重要进化特征。它具备一下特点: - **并行与并发**:G1 能充分利用 CPU、多核环境下的硬件优势,使用多个 CPU(CPU 或者 CPU 核心)来缩短 Stop-The-World 停顿时间。部分其他收集器原本需要停顿 Java 线程执行的 GC 动作,G1 收集器仍然可以通过并发的方式让 java 程序继续执行。 - **分代收集**:虽然 G1 可以不需要其他收集器配合就能独立管理整个 GC 堆,但是还是保留了分代的概念。 - **空间整合**:与 CMS 的“标记--清理”算法不同,G1 从整体来看是基于“标记整理”算法实现的收集器;从局部上来看是基于“复制”算法实现的。 - **可预测的停顿**:这是 G1 相对于 CMS 的另一个大优势,降低停顿时间是 G1 和 CMS 共同的关注点,但 G1 除了追求低停顿外,还能建立可预测的停顿时间模型,能让使用者明确指定在一个长度为 M 毫秒的时间片段内。 G1 收集器的运作大致分为以下几个步骤: - **初始标记** - **并发标记** - **最终标记** - **筛选回收** **G1 收集器在后台维护了一个优先列表,每次根据允许的收集时间,优先选择回收价值最大的 Region(这也就是它的名字 Garbage-First 的由来)**。这种使用 Region 划分内存空间以及有优先级的区域回收方式,保证了 GF 收集器在有限时间内可以尽可能高的收集效率(把内存化整为零)。 #### 如何选择垃圾回收器 - 单CPU或小内存,单机内存 -XX:+UseSerialGC - 多CPU,需要最大吞吐量,如后台计算型应用 -XX:+UseParallelGC -XX:+UseParallelOldGC - 多CPU,最求低停顿时间,需快速相应,如互联网应用 -XX:+ParNewGC -XX:+UseConcMarkSweepGC | 参数 | 新生代垃圾收集器 | 新生代算法 | 老年代垃圾收集器 | 老年代算法 | | --------------------------------- | ------------------ | ------------------ | ------------------------------------------------------------ | ---------- | | UseSerialGC | SerialGC | 复制 | SerialOldGC | 标整 | | UseParNewGC | ParNew | 复制 | SerialOldGC | 标整 | | UseParallelGC<br>UseParallelOldGC | Parallel[Scavenge] | 复制 | Parallel Old | 标整 | | UseConcMarkSweepGC | ParNew | 复制 | CMS+Serial Old的收集器组合(Serial Old 作为CMS出错的后备收集器) | 标清 | | UseG1GC | G1整体上采用标整 | 局部是通过复制算法 | | | ### JVM调优参数 > 这里只介绍一些常用的,还有更多的后续讲解... ```shell -Xms128m -Xmx4096m -Xss1024K -XX:MetaspaceSize=512m -XX:+PrintCommandLineFlags -XX:+PrintGCDetails -XX:+UseSerialGC ``` - -Xms:初始大小内存,默认为物理内存1/64,等价于-XX:InitialHeapSize - -Xmx:最大分配内存,默认物理内存1/4,等价于-XX:MaxHeapSize - -Xss:设置单个线程栈的大小,默认542K~1024K ,等价于-XX:ThreadStackSize - -Xmn:设置年轻代的大小 - -XX:MetaspaceSize:设置元空间大小 - -XX:+PrintGCDetails:输出详细GC收集日志信息,如[名称:GC前内存占用->GC后内存占用(该区内存总大小)] - -XX:SurvivorRatio:设置新生代中Eden和S0/S1空间的比例,默认-XX:SurvivorRatio=8,Eden:S0:S1=8:1:1 - -XX:NewRatio:设置年轻代与老年代在堆结构的占比,如:默认-XX:NewRatio=2 新生代在1,老年代2,年轻代占整个堆的1/3,NewRatio值几句诗设置老年代的占比,剩下的1给新生代 - -XX:MaxTenuringThreshold:设置垃圾的最大年龄,默认-XX:MaxTenuringThreshold=15 - -XX:+UseSerialGC:串行垃圾回收器 - -XX:+UseParallelGC:并行垃圾回收器 <file_sep>package books; /** * @program JavaBooks * @description: 二叉树的深度 * @author: mf * @create: 2019/10/08 09:38 */ /* 输入一颗二叉树的根节点,求该树的深度。从根节点到叶节点 依次经过的节点(含根、叶节点)形成树的一条路径,最长路径 的长度为树的深度。 */ public class T55 { public static void main(String[] args) { int[] pre = {1, 2, 4, 5, 7, 3, 6}; int[] in = {4, 2, 7, 5, 1, 3, 6}; TreeNode pNode = TreeNode.setBinaryTree(pre, in); System.out.println(treeDepth(pNode)); } // 递归 private static int treeDepth(TreeNode pNode) { if (pNode == null) return 0; int pLeft = treeDepth(pNode.left); int pRight = treeDepth(pNode.right); return pLeft > pRight ? (pLeft + 1) : (pRight + 1); } } <file_sep>package web; /** * @program LeetNiu * @description: 矩形覆盖 * @author: mf * @create: 2020/01/09 13:36 */ /** * 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法? */ public class T10 { public int RectCover(int target) { // 条件 if (target <= 2) return target; int pre2 = 1, pre1 = 2; int sum = 0; for (int i = 3; i <= target; i++) { sum = pre2 + pre1; pre2 = pre1; pre1 = sum; } return sum; } } <file_sep>package normal; /** * @program JavaBooks * @description: 14. 最长公共前缀 * @author: mf * @create: 2019/11/10 16:09 */ public class LongestCommonPrefix { public static void main(String[] args) { String[] strs = {"flower","flow","flight"}; System.out.println(longestCommonPrefix(strs)); } public static String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String str = strs[0]; for (int i = 1; i < strs.length; i++) { while(strs[i].indexOf(str) != 0) { str = str.substring(0, str.length() - 1); } } return str; } } <file_sep>package web; /** * @program LeetNiu * @description: 旋转数组的最小数组 * @author: mf * @create: 2020/01/09 12:06 */ /** * 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 * 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 * 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 * NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 */ public class T6 { public int minNumberInRotateArray(int [] array) { // 判断条件 if (array.length == 0) return 0; if (array.length == 1) return array[0]; int a = array[0]; // 根据数组的特征 for (int i = 1; i < array.length; i++) { if (a > array[i]) { return array[i]; } else { a = array[i]; } } return 0; } } <file_sep>package com.basic; /** * @program JavaBooks * @description: 不要以字符串常量作为锁定对象 * @author: mf * @create: 2019/12/29 00:34 */ public class T10 { private String s1 = "hello"; private String s2 = "hello"; void m1() { synchronized (s1) { } } void m2() { synchronized (s2) { } } // m1和m2锁的同一个字符串常量对象。 } <file_sep>package books; import java.util.PriorityQueue; import java.util.Stack; /** * @program JavaBooks * @description: 用两个栈实现队列 * @author: mf * @create: 2019/08/21 14:18 */ /* 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail和deleteHead,分别完成在队列尾部插入节点和队列 头部删除节点的功能。 */ public class T9 { // 定义两个栈 Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { // 倒入stack2 while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } // 取stack2栈顶 int first = stack2.pop(); // 从stack2倒回去 while (!stack2.isEmpty()) { stack1.push(stack2.pop()); } return first; } public int pop2() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); // 返回输出栈的栈顶 } } /* 用两个队列实现一个栈 */ class T9_1 { PriorityQueue<Integer> queue1 = new PriorityQueue<>(); PriorityQueue<Integer> queue2 = new PriorityQueue<>(); public void add(int node) { queue1.add(node); } public int poll() { int first = 0; while (!queue1.isEmpty()) { first = queue1.poll(); queue2.add(first); } queue2.remove(first); while(!queue2.isEmpty()) { queue1.add(queue2.poll()); } return first; } }<file_sep>## 引言 **线性表-哈希表** ## 相关题目 哈希表使用 O(N) 空间复杂度存储数据,并且以 O(1) 时间复杂度求解问题。 <!-- more --> - Java 中的 **HashSet** 用于存储一个集合,可以查找元素是否在集合中。如果元素有穷,并且范围不大,那么可以用一个布尔数组来存储一个元素是否存在。例如对于只有小写字符的元素,就可以用一个长度为 26 的布尔数组来存储一个字符集合,使得空间复杂度降低为 O(1)。 - Java 中的 **HashMap** 主要用于映射关系,从而把两个元素联系起来。HashMap 也可以用来对元素进行计数统计,此时键为元素,值为计数。和 HashSet 类似,如果元素有穷并且范围不大,可以用整型数组来进行统计。在对一个内容进行压缩或者其它转换时,利用 HashMap 可以把原始内容和转换后的内容联系起来。 ### [1. 两数之和](https://leetcode-cn.com/problems/two-sum/) ```bash 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ``` 分析:哈希 ```java class Solution { public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length == 0) return null; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int error = target - nums[i]; if (map.containsKey(error)) { return new int[] {map.get(error), i}; } else { map.put(nums[i], i); } } return new int[0]; } } ``` ### [136. 只出现一次的数字](https://leetcode-cn.com/problems/single-number/) ```bash 输入: [2,2,1] 输出: 1 输入: [4,1,2,1,2] 输出: 4 ``` 分析:哈希或者异或 ```java /** * 哈希 * @param nums * @return */ class Solution { public int singleNumber(int[] nums) { if(nums.length == 1) return nums[0]; HashMap<Integer,Integer> map = new HashMap<>(); for(int num : nums) { if(map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } for(Integer key : map.keySet()) { if(map.get(key) == 1) { return key; } } return 0; } } ``` ```java /** * 异或 * @param nums * @return */ class Solution { public int singleNumber(int[] nums) { if(nums.length == 1) return nums[0]; int ans = nums[0]; for(int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } } ``` ### [202. 快乐数](https://leetcode-cn.com/problems/happy-number/) ```bash 输入: 19 输出: true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 ``` 分析:递归,哈希 ```java // 递归 class Solution { public boolean isHappy(int n) { if (n == 1) return true; if (n != 4) { int sum = 0, k = n; while (k > 0) { sum += (k % 10) * (k % 10); k /= 10; } return isHappy(sum); } return false; } } ``` ```java // 哈希 只要sum有重复的,必然是不快乐了。 public boolean isHappy(int n) { if(n == 1) return true; HashSet<Integer> set = new HashSet<>(); while(2 > 1) { int sum = 0; while (n > 0) { sum += (n % 10) *(n % 10); n /= 10; } if(sum == 1) return true; if(!set.add(sum)) return false; n = sum; } } ``` ### [217. 存在重复元素](https://leetcode-cn.com/problems/contains-duplicate/) ```bash 输入: [1,2,3,1] 输出: true 输入: [1,2,3,4] 输出: false 输入: [1,1,1,3,3,4,3,2,4,2] 输出: true ``` 分析:哈希 ```java class Solution { public boolean containsDuplicate(int[] nums) { HashSet<Integer> set = new HashSet<>(); for (int num : nums) { if (!set.add(num)) { return true; } } return false; } } ``` ### [242. 有效的字母异位词](https://leetcode-cn.com/problems/valid-anagram/) ```bash 输入: s = "anagram", t = "nagaram" 输出: true 输入: s = "rat", t = "car" 输出: false ``` 分析:字符串或者哈希 ```java // 哈希 class Solution { public boolean isAnagram(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for(char c : t.toCharArray()) { Integer count = map.get(c); if(count == null) { return false; } else if (count > 1) { map.put(c, count - 1); } else { map.remove(c); } } return map.isEmpty(); } } ``` ```java // 字符串 class Solution { public boolean isAnagram(String s, String t) { int[] sCount = new int[26]; int[] tCount = new int[26]; for(char c : s.toCharArray()) { sCount[c - 'a']++; } for(char c : t.toCharArray()) { tCount[c - 'a']++; } for(int i = 0; i < 26; i++) { if(sCount[i] != tCount[i]) { return false; } } return true; } } ``` ### [350. 两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/) ```bash 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] ``` 分析:哈希 ```java class Solution { public int[] intersect(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>(); for(int num : nums1) { map.put(num, map.getOrDefault(num, 0) + 1); } ArrayList<Integer> list = new ArrayList<>(); for(int num : nums2) { Integer count = map.get(num); if(count != null && count != 0) { list.add(num); map.put(num, --count); } } int ans[] = new int[list.size()]; for(int i = 0; i < list.size(); i++) { ans[i] = list.get(i); } return ans; } } ``` ### [387. 字符串中的第一个唯一字符](https://leetcode-cn.com/problems/first-unique-character-in-a-string/) ```bash s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. ``` 分:哈希 ```java class Solution { public int firstUniqChar(String s) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()){ map.put(c, map.getOrDefault(c, 0) + 1); } for (int i = 0; i < s.length(); i++) { if(map.get(s.charAt(i)) == 1) { return i; } } return -1; } } ``` <file_sep>## 引言 > Java常见的几种锁,比如: > > - 公平锁/非公平锁 > - 可重入锁 > - 独享锁/共享锁 > - 互斥锁/读写锁 > - 乐观锁/悲观锁 > - 分段锁 > - 偏向锁/轻量级锁/重量级锁 > - 自旋锁 <!-- more --> ## 公平锁/非公平锁 **公平锁指多个线程按照申请锁的顺序来获取锁。非公平锁指多个线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取锁。有可能,会造成优先级反转或者饥饿现象(很长时间都没获取到锁-非洲人...),ReentrantLock,了解一下。** ## 可重入锁 **可重入锁又名递归锁,是指在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁,典型的synchronized,了解一下** ```java synchronized void setA() throws Exception { Thread.sleep(1000); setB(); // 因为获取了setA()的锁,此时调用setB()将会自动获取setB()的锁,如果不自动获取的话方法B将不会执行 } synchronized void setB() throws Exception { Thread.sleep(1000); } ``` ## 独享锁/共享锁 - 独享锁:是指该锁一次只能被一个线程所持有。 - 共享锁:是该锁可被多个线程所持有。 ## 互斥锁/读写锁 **上面讲的独享锁/共享锁就是一种广义的说法,互斥锁/读写锁就是其具体的实现** ## 乐观锁/悲观锁 1. **乐观锁与悲观锁不是指具体的什么类型的锁,而是指看待兵法同步的角度。** 2. **悲观锁认为对于同一个人数据的并发操作,一定是会发生修改的,哪怕没有修改,也会认为修改。因此对于同一个数据的并发操作,悲观锁采取加锁的形式。悲观的认为,不加锁的并发操作一定会出现问题。** 3. **乐观锁则认为对于同一个数据的并发操作,是不会发生修改的。在更新数据的时候,会采用尝试更新,不断重新的方式更新数据。乐观的认为,不加锁的并发操作时没有事情的。** 4. **悲观锁适合写操作非常多的场景,乐观锁适合读操作非常多的场景,不加锁带来大量的性能提升。** 5. **悲观锁在Java中的使用,就是利用各种锁。乐观锁在Java中的使用,是无锁编程,常常采用的是CAS算法,典型的例子就是原子类,通过CAS自旋实现原子类操作的更新。重量级锁是悲观锁的一种,自旋锁、轻量级锁与偏向锁属于乐观锁** ## 分段锁 1. **分段锁其实是一种锁的设计,并不是具体的一种锁,对于ConcurrentHashMap而言,其并发的实现就是通过分段锁的形式来哦实现高效的并发操作。** 2. ** 以ConcurrentHashMap来说一下分段锁的含义以及设计思想,ConcurrentHashMap中的分段锁称为Segment,它即类似于HashMap(JDK7与JDK8中HashMap的实现)的结构,即内部拥有一个Entry数组,数组中的每个元素又是一个链表;同时又是ReentrantLock(Segment继承了ReentrantLock)** 3. **当需要put元素的时候,并不是对整个hashmap进行加锁,而是先通过hashcode来知道他要放在那一个分段中,然后对这个分段进行加锁,所以当多线程put的时候,只要不是放在一个分段中,就实现了真正的并行的插入。但是,在统计size的时候,可就是获取hashmap全局信息的时候,就需要获取所有的分段锁才能统计。** 4. **分段锁的设计目的是细化锁的粒度,当操作不需要更新整个数组的时候,就仅仅针对数组中的一项进行加锁操作。** ## 偏向锁/轻量级锁/重量级锁 1. **这三种锁是锁的状态,并且是针对Synchronized。在Java5通过引入锁升级的机制来实现高效Synchronized。这三种锁的状态是通过对象监视器在对象头中的字段来表明的。偏向锁是指一段同步代码一直被一个线程所访问,那么该线程会自动获取锁。降低获取锁的代价。** 2. **偏向锁的适用场景:始终只有一个线程在执行代码块,在它没有执行完释放锁之前,没有其它线程去执行同步快,在锁无竞争的情况下使用,一旦有了竞争就升级为轻量级锁,升级为轻量级锁的时候需要撤销偏向锁,撤销偏向锁的时候会导致stop the word操作;在有锁竞争时,偏向锁会多做很多额外操作,尤其是撤销偏向锁的时候会导致进入安全点,安全点会导致stw,导致性能下降,这种情况下应当禁用。** 3. **轻量级锁是指当锁是偏向锁的时候,被另一个线程锁访问,偏向锁就会升级为轻量级锁,其他线程会通过自选的形式尝试获取锁,不会阻塞,提高性能。** 4. **重量级锁是指当锁为轻量级锁的时候,另一个线程虽然是自旋,但自旋不会一直持续下去,当自旋一定次数的时候,还没有获取到锁,就会进入阻塞,该锁膨胀为重量级锁。重量级锁会让其他申请的线程进入阻塞,性能降低。** ## 自旋锁 1. **在Java中,自旋锁是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。** 2. **自旋锁原理非常简单,如果持有锁的线程能在很短时间内释放锁资源,那么那些等待竞争锁的线程就不需要做内核态和用户态之间的切换进入阻塞挂起状态,它们只需要等一等(自旋),等持有锁的线程释放锁后即可立即获取锁,这样就避免用户线程和内核的切换的消耗。** 3. **自旋锁尽可能的减少线程的阻塞,适用于锁的竞争不激烈,且占用锁时间非常短的代码来说性能能大幅度的提升,因为自旋的消耗会小于线程阻塞挂起再唤醒的操作的消耗。** 4. **但是如果锁的竞争激烈,或者持有锁的线程需要长时间占用锁执行同步块,这时候就不适用使用自旋锁了,因为自旋锁在获取锁前一直都是占用cpu做无用功,同时有大量线程在竞争一个锁,会导致获取锁的时间很长,线程自旋的消耗大于线程阻塞挂起操作的消耗,其它需要cpu的线程又不能获取到cpu,造成cpu的浪费。** ## Java锁总结 **Java锁机制可归为Sychornized锁和Lock锁两类。Synchronized是基于JVM来保证数据同步的,而Lock则是硬件层面,依赖特殊的CPU指令来实现数据同步的。** - Synchronized是一个非公平、悲观、独享、互斥、可重入的重量级锁。 - ReentrantLock是一个默认非公平但可实现公平的、悲观、独享、互斥、可重入、重量级锁。 - ReentrantReadWriteLock是一个默认非公平但可实现公平的、悲观、写独享、读共享、读写、可重入、重量级锁。 <file_sep>package books; /** * @program JavaBooks * @description: 序列化二叉树 * @author: mf * @create: 2019/09/18 10:02 */ /* 请实现两个函数,分别用来序列化和反序列化二叉树。 */ public class T37 { public static void main(String[] args) { int[] pre = {1, 2, 4, 3, 5, 6}; int[] in = {4, 2, 1, 5, 3, 6}; TreeNode root = TreeNode.setBinaryTree(pre, in); serialize(root); } private static void serialize(TreeNode root) { if (root == null) { System.out.print("$,"); return; } System.out.print(root.val + ","); serialize(root.left); serialize(root.right); } } <file_sep>package web; /** * @program LeetNiu * @description: 斐波那契数列 * @author: mf * @create: 2020/01/09 13:28 */ /** *大家都知道斐波那契数列,现在要求输入一个整数n, * 请你输出斐波那契数列的第n项(从0开始,第0项为0)。 * n<=39 * 思路: * 递归,重复项太多,自底向上 */ public class T7 { public int Fibonacci(int n) { // 条件 if (n <= 1) return n; int pre2 = 0, pre1 = 1; int f = 0; for (int i = 2; i <= n; i++) { f = pre2 + pre1; pre2 = pre1; pre1 = f; } return f; } } <file_sep>package normal; /** * @program JavaBooks * @description: 217.存在重复元素 * @author: mf * @create: 2019/11/04 16:24 */ import java.util.HashMap; /** * 题目:https://leetcode-cn.com/problems/contains-duplicate/ * 难度:easy * 类型:数组 */ /* 输入: [1,2,3,1] 输出: true 输入: [1,2,3,4] 输出: false */ public class ContainsDuplicate { public static void main(String[] args) { int[] nums = {1,2,3,1}; int[] nums1 = {1,2,3,4}; int[] nums2 = {0,4,5,0,3,6}; int[] nums3 = {2,14,18,22,22}; System.out.println(containsDuplicate(nums1)); } public static boolean containsDuplicate(int[] nums) { HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { if (map.containsKey(num)) { return true; } else { map.put(num, 1); } } return false; } } <file_sep>## 引言 **线性表-栈和队列** ## 栈-LIFO 实现 - 使用数组实现的叫`静态栈` - 使用链表实现的叫`动态栈` ## 队列-FIFO 实现 - 使用链表实现的叫`动态栈` - 使用链表实现的叫`动态队列` ## 相关题目 <!-- more --> ### [20. 有效的括号](https://leetcode-cn.com/problems/valid-parentheses/) ```bash 输入: "()" 输出: true 输入: "()[]{}" 输出: true 输入: "(]" 输出: false ``` 分析:栈 ```java class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(char c : s.toCharArray()) { if(stack.size() == 0) { stack.push(c); } else if(isSym(stack.peek(), c)) { stack.pop(); } else { stack.push(c); } } return stack.size() == 0; } public boolean isSym(char c1, char c2) { return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}'); } } ``` ### [155. 最小栈](https://leetcode-cn.com/problems/min-stack/) ```bash MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2. ``` 分析:当前值比min小,一次性入两次栈,相当于记录了上次的最小值,每次弹出去的时候,也将当前最小值弹出去,且重新找回上次记录的最小值 也可以用辅助栈 ```java class MinStack { private int min = Integer.MAX_VALUE; private Stack<Integer> stack; /** initialize your data structure here. */ public MinStack() { stack = new Stack<>(); } public void push(int x) { if(x <= min) { stack.push(min); min = x; } stack.push(x); } public void pop() { if(stack.pop() == min) { min = stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return min; } } ``` ```java class MinStack { private Stack<Integer> dataStack; private Stack<Integer> minStack; private int min; public MinStack() { dataStack = new Stack<>(); minStack = new Stack<>(); min = Integer.MAX_VALUE; } public void push(int x) { dataStack.add(x); min = Math.min(min, x); minStack.add(min); } public void pop() { dataStack.pop(); minStack.pop(); min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek(); } public int top() { return dataStack.peek(); } public int getMin() { return minStack.peek(); } } ``` ### [232. 用栈实现队列](https://leetcode-cn.com/problems/implement-queue-using-stacks/) ```bash MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false ``` 分析:两个栈 ```java class MyQueue { private Stack<Integer> in; private Stack<Integer> out; /** Initialize your data structure here. */ public MyQueue() { in = new Stack<>(); out = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { in.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if(out.isEmpty()) { while(! in.isEmpty()) { out.push(in.pop()); } } return out.pop(); } /** Get the front element. */ public int peek() { if(out.isEmpty()) { while(! in.isEmpty()) { out.push(in.pop()); } } return out.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return in.isEmpty() && out.isEmpty(); } } ``` ### [225. 用队列实现栈](https://leetcode-cn.com/problems/implement-stack-using-queues/) 分析:在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。 ```java class MyStack { private Queue<Integer> queue; /** Initialize your data structure here. */ public MyStack() { queue = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { queue.add(x); int cnt = queue.size(); while(cnt-- > 1) { queue.add(queue.poll()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return queue.remove(); } /** Get the top element. */ public int top() { return queue.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue.isEmpty(); } } ``` 用两个队列实现栈,比如加入的顺序是1,2,3; ```java private Queue<Integer> q1 = new LinkedList<>(); private Queue<Integer> q2 = new LinkedList<>(); private int top; public void push(int x) { // 添加顺序1, 2 q2.add(x); // 2 top = x; while (!q1.isEmpty()) { q2.add(q1.remove()); //2, 1 } Queue<Integer> temp = q1; // q1 null q1 = q2; q2 = temp; } public int pop() { int res = top; q1.remove(); if (!q1.isEmpty()) { top = q1.peek(); } return res; } ``` <file_sep>package books; /** * @program JavaBooks * @description: 复杂链表的复制 * @author: mf * @create: 2019/09/16 12:06 */ /* 见书 */ /* 思路: 1. 复制每个节点,如复制节点A得到A1,将节点A1插到节点A后面 2. 重新遍历链表,复制老结点的随机指针给新节点,如 A1.random = A.random.next; 3. 拆分链表,将链表拆分为原链表和复制后的链表 */ public class T35 { public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node1.random = node3; node2.random = node5; node4.random = node2; ListNode resNode = Clone(node1); } private static ListNode Clone(ListNode pHead) { if (pHead == null) return null; ListNode node = pHead; // 1. 复制每个节点,如复制节点A得到A1,将节点A1插到节点A后面 while (node != null) { ListNode copyNode = new ListNode(node.value); copyNode.next = node.next; node.next = copyNode; node = copyNode.next; } node = pHead; // 2. 重新遍历链表,复制老结点的随机指针给新节点,如 A1.random = A.random.next; while (node != null) { node.next.random = node.random == null ? null : node.random.next; node = node.next.next; } // 3. 拆分链表,将链表拆分为原链表和复制后的链表 node = pHead; ListNode pCloneHead = pHead.next; while (node != null) { ListNode copyNode = node.next; node.next = copyNode.next; copyNode.next = copyNode.next == null ? null : copyNode.next.next; node = node.next; } return pCloneHead; } } <file_sep>## 引言 **linux-基础** ## 常用操作以及概念 ### 快捷键 - Tab: 命令和文件名补全; - Ctrl+C: 中断正在运行的程序; - Ctrl+D: 结束键盘输入(End Of File,EOF) ### 求助 <!-- more --> #### --help 指令的基本用法与选项介绍。 #### man man 是 manual 的缩写,将指令的具体信息显示出来。 #### info info 与 man 类似,但是 info 将文档分成一个个页面,每个页面可以进行跳转。 #### doc /usr/share/doc 存放着软件的一整套说明文件。 ### 关机 #### who 在关机前需要先使用 who 命令查看有没有其它用户在线。 #### sync 为了加快对磁盘文件的读写速度,位于内存中的文件数据不会立即同步到磁盘上,因此关机之前需要先进行 sync 同步操作。 #### shutdown ```bash ## shutdown [-krhc] 时间 [信息] -k : 不会关机,只是发送警告信息,通知所有在线的用户 -r : 将系统的服务停掉后就重新启动 -h : 将系统的服务停掉后就立即关机 -c : 取消已经在进行的 shutdown 指令内容 ``` ### PATH 可以在环境变量 PATH 中声明可执行文件的路径,路径之间用 : 分隔。 `/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/dmtsai/.local/bin:/home/dmtsai/bin` ### sudo sudo 允许一般用户使用 root 可执行的命令,不过只有在 /etc/sudoers 配置文件中添加的用户才能使用该指令. ### 包管理工具 RPM 和 DPKG 为最常见的两类软件包管理工具: - RPM 全称为 Redhat Package Manager,最早由 Red Hat 公司制定实施,随后被 GNU 开源操作系统接受并成为很多 Linux 系统 (RHEL) 的既定软件标准。 - 与 RPM 进行竞争的是基于 Debian 操作系统 (Ubuntu) 的 DEB 软件包管理工具 DPKG,全称为 Debian Package,功能方面与 RPM 相似。 YUM 基于 RPM,具有依赖管理功能,并具有软件升级的功能。 ### 发行版 Linux 发行版是 Linux 内核及各种应用软件的集成版本。 | 基于的包管理工具 | 商业发行版 | 社区发行版 | | :--------------: | :--------: | :-------------: | | RPM | Red Hat | Fedora / CentOS | | DPKG | Ubuntu | Debian | ### VIM - 一般指令模式(Command mode): VIM 的默认模式,可以用于移动游标查看内容; - 编辑模式(Insert mode): 按下 "i" 等按键之后进入,可以对文本进行编辑; - 指令列模式(Bottom-line mode): 按下 ":" 按键之后进入,用于保存退出等操作。 在指令列模式下,有以下命令用于离开或者保存文件。 | 命令 | 作用 | | :--: | :----------------------------------------------------------: | | :w | 写入磁盘 | | :w! | 当文件为只读时,强制写入磁盘。到底能不能写入,与用户对该文件的权限有关 | | :q | 离开 | | :q! | 强制离开不保存 | | :wq | 写入磁盘后离开 | | :wq! | 强制写入磁盘后离开 | ## 磁盘 ### 磁盘接口 #### IDE IDE(ATA)全称 Advanced Technology Attachment,接口速度最大为 133MB/s,因为并口线的抗干扰性太差,且排线占用空间较大,不利电脑内部散热,已逐渐被 SATA 所取代。 #### SATA SATA 全称 Serial ATA,也就是使用串口的 ATA 接口,抗干扰性强,且对数据线的长度要求比 ATA 低很多,支持热插拔等功能。SATA-II 的接口速度为 300MiB/s,而新的 SATA-III 标准可达到 600MiB/s 的传输速度。SATA 的数据线也比 ATA 的细得多,有利于机箱内的空气流通,整理线材也比较方便。 #### SCSI SCSI 全称是 Small Computer System Interface(小型机系统接口),经历多代的发展,从早期的 SCSI-II 到目前的 Ultra320 SCSI 以及 Fiber-Channel(光纤通道),接口型式也多种多样。SCSI 硬盘广为工作站级个人电脑以及服务器所使用,因此会使用较为先进的技术,如碟片转速 15000rpm 的高转速,且传输时 CPU 占用率较低,但是单价也比相同容量的 ATA 及 SATA 硬盘更加昂贵。 #### SAS SAS(Serial Attached SCSI)是新一代的 SCSI 技术,和 SATA 硬盘相同,都是采取序列式技术以获得更高的传输速度,可达到 6Gb/s。此外也透过缩小连接线改善系统内部空间等。 ## 分区 ### 分区表 磁盘分区表主要有两种格式,一种是限制较多的 MBR 分区表,一种是较新且限制较少的 GPT 分区表。 #### MBR MBR 中,第一个扇区最重要,里面有主要开机记录(Master boot record, MBR)及分区表(partition table),其中主要开机记录占 446 bytes,分区表占 64 bytes。 分区表只有 64 bytes,最多只能存储 4 个分区,这 4 个分区为主分区(Primary)和扩展分区(Extended)。其中扩展分区只有一个,它使用其它扇区用记录额外的分区表,因此通过扩展分区可以分出更多分区,这些分区称为逻辑分区。 Linux 也把分区当成文件,分区文件的命名方式为: 磁盘文件名 + 编号,例如 /dev/sda1。注意,逻辑分区的编号从 5 开始。 #### GPT 不同的磁盘有不同的扇区大小,例如 512 bytes 和最新磁盘的 4 k。GPT 为了兼容所有磁盘,在定义扇区上使用逻辑区块地址(Logical Block Address, LBA),LBA 默认大小为 512 bytes。 GPT 第 1 个区块记录了主要开机记录(MBR),紧接着是 33 个区块记录分区信息,并把最后的 33 个区块用于对分区信息进行备份。这 33 个区块第一个为 GPT 表头纪录,这个部份纪录了分区表本身的位置与大小和备份分区的位置,同时放置了分区表的校验码 (CRC32),操作系统可以根据这个校验码来判断 GPT 是否正确。若有错误,可以使用备份分区进行恢复。 GPT 没有扩展分区概念,都是主分区,每个 LAB 可以分 4 个分区,因此总共可以分 4 * 32 = 128 个分区。 MBR 不支持 2.2 TB 以上的硬盘,GPT 则最多支持到 233 TB = 8 ZB。 ### 开机检测程序 #### BIOS BIOS(Basic Input/Output System,基本输入输出系统),它是一个固件(嵌入在硬件中的软件),BIOS 程序存放在断电后内容不会丢失的只读内存中。 BIOS 是开机的时候计算机执行的第一个程序,这个程序知道可以开机的磁盘,并读取磁盘第一个扇区的主要开机记录(MBR),由主要开机记录(MBR)执行其中的开机管理程序,这个开机管理程序会加载操作系统的核心文件。 主要开机记录(MBR)中的开机管理程序提供以下功能: 选单、载入核心文件以及转交其它开机管理程序。转交这个功能可以用来实现了多重引导,只需要将另一个操作系统的开机管理程序安装在其它分区的启动扇区上,在启动开机管理程序时,就可以通过选单选择启动当前的操作系统或者转交给其它开机管理程序从而启动另一个操作系统。 下图中,第一扇区的主要开机记录(MBR)中的开机管理程序提供了两个选单: M1、M2,M1 指向了 Windows 操作系统,而 M2 指向其它分区的启动扇区,里面包含了另外一个开机管理程序,提供了一个指向 Linux 的选单。 安装多重引导,最好先安装 Windows 再安装 Linux。因为安装 Windows 时会覆盖掉主要开机记录(MBR),而 Linux 可以选择将开机管理程序安装在主要开机记录(MBR)或者其它分区的启动扇区,并且可以设置开机管理程序的选单。 #### UEFI BIOS 不可以读取 GPT 分区表,而 UEFI 可以。 ## 文件系统 ### 分区与文件系统 对分区进行格式化是为了在分区上建立文件系统。一个分区通常只能格式化为一个文件系统,但是磁盘阵列等技术可以将一个分区格式化为多个文件系统。 ### 组成 最主要的几个组成部分如下: - inode: 一个文件占用一个 inode,记录文件的属性,同时记录此文件的内容所在的 block 编号; - block: 记录文件的内容,文件太大时,会占用多个 block。 - superblock: 记录文件系统的整体信息,包括 inode 和 block 的总量、使用量、剩余量,以及文件系统的格式与相关信息等; - block bitmap: 记录 block 是否被使用的位域。 ### 文件读取 对于 Ext2 文件系统,当要读取一个文件的内容时,先在 inode 中去查找文件内容所在的所有 block,然后把所有 block 的内容读出来。 ### 磁盘碎片 指一个文件内容所在的 block 过于分散。 ### Block 在 Ext2 文件系统中所支持的 block 大小有 1K,2K 及 4K 三种,不同的大小限制了单个文件和文件系统的最大大小。 一个 block 只能被一个文件所使用,未使用的部分直接浪费了。因此如果需要存储大量的小文件,那么最好选用比较小的 block。 ### inode inode 具体包含以下信息: - 权限 (read/write/excute); - 拥有者与群组 (owner/group); - 容量; - 建立或状态改变的时间 (ctime); - 最近一次的读取时间 (atime); - 最近修改的时间 (mtime); - 定义文件特性的旗标 (flag),如 SetUID...; - 该文件真正内容的指向 (pointer)。 inode 具有以下特点: - 每个 inode 大小均固定为 128 bytes (新的 ext4 与 xfs 可设定到 256 bytes); - 每个文件都仅会占用一个 inode。 inode 中记录了文件内容所在的 block 编号,但是每个 block 非常小,一个大文件随便都需要几十万的 block。而一个 inode 大小有限,无法直接引用这么多 block 编号。因此引入了间接、双间接、三间接引用。间接引用是指,让 inode 记录的引用 block 块记录引用信息。 ### 目录 建立一个目录时,会分配一个 inode 与至少一个 block。block 记录的内容是目录下所有文件的 inode 编号以及文件名。 可以看出文件的 inode 本身不记录文件名,文件名记录在目录中,因此新增文件、删除文件、更改文件名这些操作与目录的 w 权限有关。 ### 日志 如果突然断电,那么文件系统会发生错误,例如断电前只修改了 block bitmap,而还没有将数据真正写入 block 中。 ext3/ext4 文件系统引入了日志功能,可以利用日志来修复文件系统。 ### 挂载 挂载利用目录作为文件系统的进入点,也就是说,进入目录之后就可以读取文件系统的数据。 ### 目录配置 为了使不同 Linux 发行版本的目录结构保持一致性,Filesystem Hierarchy Standard (FHS) 规定了 Linux 的目录结构。最基础的三个目录如下: - / (root, 根目录) - /usr (unix software resource): 所有系统默认软件都会安装到这个目录; - /var (variable): 存放系统或程序运行过程中的数据文件。 ## 文件 ### 文件属性 用户分为三种: 文件拥有者、群组以及其它人,对不同的用户有不同的文件权限。 使用 ls 查看一个文件时,会显示一个文件的信息,例如 `drwxr-xr-x. 3 root root 17 May 6 00:14 .config`,对这个信息的解释如下: - drwxr-xr-x: 文件类型以及权限,第 1 位为文件类型字段,后 9 位为文件权限字段 - 3: 链接数 - root: 文件拥有者 - root: 所属群组 - 17: 文件大小 - May 6 00:14: 文件最后被修改的时间 - .config: 文件名 常见的文件类型及其含义有: - d: 目录 - -: 文件 - l: 链接文件 9 位的文件权限字段中,每 3 个为一组,共 3 组,每一组分别代表对文件拥有者、所属群组以及其它人的文件权限。一组权限中的 3 位分别为 r、w、x 权限,表示可读、可写、可执行。 文件时间有以下三种: - modification time (mtime): 文件的内容更新就会更新; - status time (ctime): 文件的状态(权限、属性)更新就会更新; - access time (atime): 读取文件时就会更新。 ### 文件与目录的基本操作 #### ls 列出文件或者目录的信息,目录的信息就是其中包含的文件。 ```bash ## ls [-aAdfFhilnrRSt] file|dir -a : 列出全部的文件 -d : 仅列出目录本身 -l : 以长数据串行列出,包含文件的属性与权限等等数据 ``` #### cd 更新当前目录 `cd [相对路径或者绝对路径]` #### mkdir 创建目录 ```bash ## mkdir [-mp] 目录名称 -m : 配置目录权限 -p : 递归创建目录 ``` #### rmdir 删除目录,目录必须为空 ```bash rmdir [-p] 目录名称 -p : 递归删除目录 ``` #### touch 更新文件时间或者建立新文件 ```bash ## touch [-acdmt] filename -a : 更新 atime -c : 更新 ctime,若该文件不存在则不建立新文件 -m : 更新 mtime -d : 后面可以接更新日期而不使用当前日期,也可以使用 --date="日期或时间" -t : 后面可以接更新时间而不使用当前时间,格式为[YYYYMMDDhhmm] ``` #### cp 复制文件 如果源文件有两个以上,则目的文件一定要是目录才行。 ```bash cp [-adfilprsu] source destination -a : 相当于 -dr --preserve=all 的意思,至于 dr 请参考下列说明 -d : 若来源文件为链接文件,则复制链接文件属性而非文件本身 -i : 若目标文件已经存在时,在覆盖前会先询问 -p : 连同文件的属性一起复制过去 -r : 递归持续复制 -u : destination 比 source 旧才更新 destination,或 destination 不存在的情况下才复制 --preserve=all : 除了 -p 的权限相关参数外,还加入 SELinux 的属性, links, xattr 等也复制了 ``` #### rm 删除文件 ```bash ## rm [-fir] 文件或目录 -r : 递归删除 ``` #### mv 移动文件 ```bash ## mv [-fiu] source destination ## mv [options] source1 source2 source3 .... directory -f : force 强制的意思,如果目标文件已经存在,不会询问而直接覆盖 ``` ### 修改权限 可以将一组权限用数字来表示,此时一组权限的 3 个位当做二进制数字的位,从左到右每个位的权值为 4、2、1,即每个权限对应的数字权值为 r : 4、w : 2、x : 1。 `## chmod [-R] xyz dirname/filename` 示例: 将 .bashrc 文件的权限修改为 -rwxr-xr--。 `## chmod 754 .bashrc` 也可以使用符号来设定权限。 ```bash ## chmod [ugoa] [+-=] [rwx] dirname/filename - u: 拥有者 - g: 所属群组 - o: 其他人 - a: 所有人 - +: 添加权限 - -: 移除权限 - =: 设定权限 ``` 示例: 为 .bashrc 文件的所有用户添加写权限。 `## chmod a+w .bashrc` ### 文件默认权限 - 文件默认权限: 文件默认没有可执行权限,因此为 666,也就是 -rw-rw-rw- 。 - 目录默认权限: 目录必须要能够进入,也就是必须拥有可执行权限,因此为 777 ,也就是 drwxrwxrwx。 可以通过 umask 设置或者查看文件的默认权限,通常以掩码的形式来表示,例如 002 表示其它用户的权限去除了一个 2 的权限,也就是写权限,因此建立新文件时默认的权限为 -rw-rw-r--。 ### 目录的权限 文件名不是存储在一个文件的内容中,而是存储在一个文件所在的目录中。因此,拥有文件的 w 权限并不能对文件名进行修改。 目录存储文件列表,一个目录的权限也就是对其文件列表的权限。因此,目录的 r 权限表示可以读取文件列表;w 权限表示可以修改文件列表,具体来说,就是添加删除文件,对文件名进行修改;x 权限可以让该目录成为工作目录,x 权限是 r 和 w 权限的基础,如果不能使一个目录成为工作目录,也就没办法读取文件列表以及对文件列表进行修改了。 ### 链接 ```bash ## ln [-sf] source_filename dist_filename -s : 默认是 hard link,加 -s 为 symbolic link -f : 如果目标文件存在时,先删除目标文件 ``` ### 实体链接 在目录下创建一个条目,记录着文件名与 inode 编号,这个 inode 就是源文件的 inode。 删除任意一个条目,文件还是存在,只要引用数量不为 0。 有以下限制: 不能跨越文件系统、不能对目录进行链接。 ```bash ## ln /etc/crontab . ## ll -i /etc/crontab crontab 34474855 -rw-r--r--. 2 root root 451 Jun 10 2014 crontab 34474855 -rw-r--r--. 2 root root 451 Jun 10 2014 /etc/crontab ``` ### 符号链接 符号链接文件保存着源文件所在的绝对路径,在读取时会定位到源文件上,可以理解为 Windows 的快捷方式。 当源文件被删除了,链接文件就打不开了。 可以为目录建立链接。 ```bash ## ll -i /etc/crontab /root/crontab2 34474855 -rw-r--r--. 2 root root 451 Jun 10 2014 /etc/crontab 53745909 lrwxrwxrwx. 1 root root 12 Jun 23 22:31 /root/crontab2 -> /etc/crontab ``` ### 获取文件内容 #### cat 取得文件内容。 ```bash ## cat [-AbEnTv] filename -n : 打印出行号,连同空白行也会有行号,-b 不会 ``` #### tac 是 cat 的反向操作,从最后一行开始打印。 #### more 和 cat 不同的是它可以一页一页查看文件内容,比较适合大文件的查看。 #### less 和 more 类似,但是多了一个向前翻页的功能。 #### head 取得文件前几行。 ```bash ## head [-n number] filename -n : 后面接数字,代表显示几行的意思 ``` #### tail 是head的反向操作,之水取得是后几行 #### od 以字符或者十六进制的形式显示二进制文件。 ### 指令与文件搜索 #### which 指令搜索 ```bash ## which [-a] command -a : 将所有指令列出,而不是只列第一个 ``` #### whereis 文件搜索。速度比较快,因为它只搜索几个特定的目录。 ```bash ## whereis [-bmsu] dirname/filename ``` #### locate 文件搜索。可以用关键字或者正则表达式进行搜索。 locate 使用 /var/lib/mlocate/ 这个数据库来进行搜索,它存储在内存中,并且每天更新一次,所以无法用 locate 搜索新建的文件。可以使用 updatedb 来立即更新数据库。 ```bash ## locate [-ir] keyword -r: 正则表达式 ``` #### find 文件搜索。可以使用文件的属性和权限进行搜索。 ```bash ## find [basedir] [option] example: find . -name "shadow*" ``` ## 压缩与打包 ### 压缩文件名 #### gzip gzip 是 Linux 使用最广的压缩指令,可以解开 compress、zip 与 gzip 所压缩的文件。 经过 gzip 压缩过,源文件就不存在了。 有 9 个不同的压缩等级可以使用。 可以使用 zcat、zmore、zless 来读取压缩文件的内容。 ```bash $ gzip [-cdtv#] filename -c : 将压缩的数据输出到屏幕上 -d : 解压缩 -t : 检验压缩文件是否出错 -v : 显示压缩比等信息 -## : ## 为数字的意思,代表压缩等级,数字越大压缩比越高,默认为 6 ``` #### bzip2 提供比 gzip 更高的压缩比。 查看命令: bzcat、bzmore、bzless、bzgrep。 #### xz 提供比 bzip2 更佳的压缩比。 可以看到,gzip、bzip2、xz 的压缩比不断优化。不过要注意的是,压缩比越高,压缩的时间也越长。 查看命令: xzcat、xzmore、xzless、xzgrep。 ### 打包 压缩指令只能对一个文件进行压缩,而打包能够将多个文件打包成一个大文件。tar 不仅可以用于打包,也可以使用 gip、bzip2、xz 将打包文件进行压缩。 ```bash $ tar [-z|-j|-J] [cv] [-f 新建的 tar 文件] filename... ==打包压缩 $ tar [-z|-j|-J] [tv] [-f 已有的 tar 文件] ==查看 $ tar [-z|-j|-J] [xv] [-f 已有的 tar 文件] [-C 目录] ==解压缩 -z : 使用 zip; -j : 使用 bzip2; -J : 使用 xz; -c : 新建打包文件; -t : 查看打包文件里面有哪些文件; -x : 解打包或解压缩的功能; -v : 在压缩/解压缩的过程中,显示正在处理的文件名; -f : filename: 要处理的文件; -C 目录 : 在特定目录解压缩。 ``` | 使用方式 | 命令 | | :------: | ----------------------------------------------------- | | 打包压缩 | tar -jcv -f filename.tar.bz2 要被压缩的文件或目录名称 | | 查 看 | tar -jtv -f filename.tar.bz2 | | 解压缩 | tar -jxv -f filename.tar.bz2 -C 要解压缩的目录 | ## bash 可以通过 Shell 请求内核提供服务,Bash 正是 Shell 的一种。 ### 特性 - 命令历史:记录使用过的命令 - 命令与文件补全:快捷键:tab - shell scripts - 通配符: 例如 ls -l /usr/bin/X* 列出 /usr/bin 下面所有以 X 开头的文件 ### 变量操作 对一个变量赋值直接使用 =。 对变量取用需要在变量前加上 $ ,也可以用 ${} 的形式; 输出变量使用 echo 命令。 ```bash $ x=abc $ echo $x $ echo ${x} ``` 变量内容如果有空格,必须使用双引号或者单引号。 - 双引号内的特殊字符可以保留原本特性,例如 x="lang is $LANG",则 x 的值为 lang is zh_TW.UTF-8; - 单引号内的特殊字符就是特殊字符本身,例如 x='lang is $LANG',则 x 的值为 lang is $LANG。 可以使用 `指令` 或者 $(指令) 的方式将指令的执行结果赋值给变量。例如 version=$(uname -r),则 version 的值为 4.15.0-22-generic。 可以使用 `指令` 或者 $(指令) 的方式将指令的执行结果赋值给变量。例如 version=$(uname -r),则 version 的值为 4.15.0-22-generic。 Bash 的变量可以声明为数组和整数数字。注意数字类型没有浮点数。如果不进行声明,默认是字符串类型。变量的声明使用 declare 命令: ```bash $ declare [-aixr] variable -a : 定义为数组类型 -i : 定义为整数类型 -x : 定义为环境变量 -r : 定义为 readonly 类型 ``` 对数组操作 ```bash $ array[1]=a $ array[2]=b $ echo ${array[1]} ``` ## 正则 g/re/p(globally search a regular expression and print),使用正则表示式进行全局查找并打印。 ```bash $ grep [-acinv] [--color=auto] 搜寻字符串 filename -c : 统计个数 -i : 忽略大小写 -n : 输出行号 -v : 反向选择,也就是显示出没有 搜寻字符串 内容的那一行 --color=auto : 找到的关键字加颜色显示 ``` 示例: 把含有 the 字符串的行提取出来(注意默认会有 --color=auto 选项,因此以下内容在 Linux 中有颜色显示 the 字符串) ```bash $ grep -n 'the' regular_express.txt 8:I can't finish the test. 12:the symbol '*' is represented as start. 15:You are the best is mean you are the no. 1. 16:The world Happy is the same with "glad". 18:google is the best tools for search keyword ``` ## 进程管理 ### 查看进程 #### ps 查看某个时间点的进程信息 示例一: 查看自己的进程`ps -l` 示例二: 查看系统所有进程`ps aux` 示例三: 查看特定的进程`ps aux | grep python` #### top 实时显示进程信息 示例: 两秒钟刷新一次`top -d 2` #### pstree 查看进程树 示例: 查看所有进程树`pstree -A` #### netstat 查看占用端口的进程 示例: 查看特定端口的进程`netstat -anp | grep port` ### 孤儿进程 一个父进程退出,而它的一个或多个子进程还在运行,那么这些子进程将成为孤儿进程。 孤儿进程将被init进程(进程号为1)所收养,并有init进程对它们完成状态收集工作。 由于孤儿进程会被init进程收养,所以孤儿进程不会对系统造成危害。 ### 僵尸进程 一个子进程的进程描述符在子进程退出时不会释放,只有当父进程通过wait()或者waitpid()获取了子进程信息后才会释放。如果子进程退出,而父进程并没有调用wait()或waitpid(),那么子进程的进程描述符仍然保存在系统中,这种进程称之为僵尸进程。 僵尸进程通过 ps 命令显示出来的状态为 Z(zombie)。 系统所能使用的进程号是有限的,如果产生大量僵尸进程,将因为没有可用的进程号而导致系统不能产生新的进程。 要消灭系统中大量的僵尸进程,只需要将其父进程杀死,此时僵尸进程就会变成孤儿进程,从而被 init 所收养,这样 init 就会释放所有的僵尸进程所占有的资源,从而结束僵尸进程。<file_sep>package web; /** * @program LeetNiu * @description: 整数中1出现的次数 * @author: mf * @create: 2020/01/14 00:27 */ /** * 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数? * 为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。 * ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。 */ public class T31 { public int NumberOf1Between1AndN_Solution(int n) { int count = 0; for (int i = 1; i <= n; i++) { int num = i; while(num != 0) { if (num % 10 == 1) { count++; } num /= 10; } } return count; } } <file_sep>## 引言 **线性表-链表** ## 概念 n个节点离散分配,彼此通过指针相连,每个节点只有一个前驱节点,每个节点只有一个后续节点,首节点没有前驱节点,尾节点没有后续节点。 确定一个链表我们只需要头指针,通过头指针就可以把整个链表都能推出来。 <!-- more --> ## 优缺点 ### 优点 - 空间没有限制 - 插入删除元素特别快 ### 缺点 - 查找非常慢 ## 分类 - 单向链表 一个节点指向下一个节点。 - 双向链表 一个节点有两个指针域。 - 循环链表 能通过任何一个节点找到其他所有的节点,将两种(双向/单向)链表的最后一个结点指向第一个结点从而实现循环。 ## 典型题目 ### [nkw-从尾到头打印链表](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035) ``` 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。 ``` 分析:递归 ```java /** * 递归 * @param listNode * @return */ public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList(); if (listNode != null) { this.printListFromTailToHead(listNode.next); list.add(listNode.val); } return list; } ``` 分析:栈 ```java /** * 栈试试 * @param listNode * @return */ public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) { ArrayList<Integer> list = new ArrayList(); Stack<Integer> stack = new Stack<>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.empty()) { list.add(stack.pop()); } return list; } ``` ### [面试题22-链表中倒数第k个结点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) ``` 给定一个链表: 1->2->3->4->5, 和 k = 2. 返回链表 4->5. ``` 分析:栈 ```java /** * 栈,比较容易想得的到 * @param head * @param k * @return */ public ListNode getKthFromEnd(ListNode head, int k) { Stack<ListNode> stack = new Stack<>(); while (head != null) { stack.push(head); head = head.next; } ListNode listNode= new ListNode(0); for (int i = 0; i < k; i++) { listNode = stack.pop(); } return listNode; } ``` 分析:双指针 ```java /** * 双指针 * @param head * @param k * @return */ public ListNode getKthFromEnd2(ListNode head, int k) { ListNode pNode = head; ListNode kNode = head; int p1 = 0; while (pNode != null) { if (p1 >= k) { kNode = kNode.next; } pNode = pNode.next; p1++; } return kNode; } ``` ### [206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/) ``` 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL ``` 分析:递归或者迭代 ```java /** * 迭代 * 流程: * 核心还是双指针... * pre和cur一直移动 * 接着相互指向 * @param head * @return */ public ListNode reverseList(ListNode head) { ListNode pre = null; // 当前节点之前的节点 null ListNode cur = head; while (cur != null) { ListNode nextTemp = cur.next; // 获取当前节点的下一个节点 cur.next = pre; // 当前节点的下个节点指向前一个节点 // 尾递归其实省了下面这两步 pre = cur; // 将前一个节点指针移动到当前指针 cur = nextTemp; // 当当前节点移动到下一个节点 } return pre; } ``` 分析:递归 ```java /** * 递归:尾递归 * @param head * @return */ public ListNode reverseList2(ListNode head) { return reverse(null, head); } public ListNode reverse(ListNode pre, ListNode cur) { if (cur == null) return pre; // 如果当前节点为null,直接返回 ListNode next = cur.next; // next节点指向当前节点的下一个节点 cur.next = pre; // 将当前节点指向 当前节点的前一个节点 return reverse(cur, next); } ``` ### [21.合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/) ```bash 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 ``` 分析:递归 ```java /** * 递归 * 比较大小,谁小,谁的下一个节点指向递归的结果 * @param l1 * @param l2 * @return */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } ``` ### [面试题35. 复杂链表的复制](https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/) ``` 输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]] ``` 分析:迭代,分三次 1. 目的是复制next,例如1->1^->2->2^ 2. 分配random 3. 双指针切断,例如1->2, 1^->2^ ```java /** * 迭代三次 * @param head * @return */ public Node copyRandomList(Node head) { if (head == null) return null; Node node = head; // 一般这样的操作其实就是好比是指针了,链表定义个指针, 走你 // 第一次迭代的目的是复制next while (node != null) { // 接下来的三步操作 复制节点 Node temp = new Node(node.val); // new一个和node值相同的当前节点 temp 比如1` temp.next = node.next; // temp 的下个节点指向 node的下个节点, 比如1`>2 node.next = temp; // node 的下个节点 指向temp 比如 1 > 1` > 2 // 一般迭代, 都会有这一步操作, 移动指针 node = temp.next; // 将node 指针 指向 temp的下个节点, 比如2 } // 这次的目的让复制的节点的random 和 原先的random各个指向的一致 // 将指针移动首部 node = head; while (node != null) { // 2 2` // ^_^ ^_^ // 1 > 1` > 2 > 2` > 3 > 3` node.next.random = node.random == null ? null : node.random.next; // 迭代,移动指针 node = node.next.next; } // 第三次目的是切断 返回复制的链表 // 双指针, 重新指向 node = head; Node pCloneHead = head.next; while (node != null) { Node temp = node.next; // 其实就是当前的复制节点 node.next = temp.next; // 其实就是 1 > 2 temp.next = temp.next == null ? null : temp.next.next; // 其实就是 1` > 2` // 迭代, 移动指针 node = node.next; } return pCloneHead; } ``` ### [面试题52. 两个链表的第一个公共节点](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/) ``` A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 ``` 分析:最容易想的是哈希,其次是双指针 ```java /** * 最容易想的是哈希 * headA走完一圈 * 开始走headB,判断哪个节点和A相等,即可 * @param headA * @param headB * @return */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; HashSet<ListNode> set = new HashSet<>(); while (headA != null) { set.add(headA); headA = headA.next; } while (headB != null) { if (set.contains(headB)) { return headB; } headB = headB.next; } return null; ``` ```java /** * 双指针 * @param headA * @param headB * @return */ public ListNode getIntersectionNode2(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; // 一男一女 ListNode node1 = headA; ListNode node2 = headB; // 我走你,你走我,直到相爱 while (node1 != node2) { node1 = node1 == null ? headB : node1.next; node2 = node2 == null ? headA : node2.next; } return node1; } ``` ### [141. 环形链表](https://leetcode-cn.com/problems/linked-list-cycle/) ```bash 输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。 ``` 分析:哈希 || 快慢指针 ```java /** * 哈希 * @param head * @return */ public class Solution { public boolean hasCycle(ListNode head) { HashSet<ListNode> set = new HashSet<>(); while(head != null) { if(set.contains(head)) { return true; } else { set.add(head); } head = head.next; } return false; } } ``` ```java /** * 快慢指针 * @param head * @return */ public class Solution { public boolean hasCycle(ListNode head) { if(head != null && head.next != null) { ListNode quick = head; ListNode slow = head; while(2 > 1) { quick = quick.next; if(quick == null) return false; quick = quick.next; if(quick == null) return false; slow = slow.next; if(slow == quick) return true; } } else { return false; } } } ``` ### [237. 删除链表中的节点](https://leetcode-cn.com/problems/delete-node-in-a-linked-list/) ``` 输入: head = [4,5,1,9], node = 5 输出: [4,1,9] ``` ```java public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } ``` ### [234. 回文链表](https://leetcode-cn.com/problems/palindrome-linked-list/) ```bash 输入: 1->2 输出: false 输入: 1->2->2->1 输出: true ``` 分析:切成两半,把后半段反转,然后比较两半是否相等。 ```java public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } if (fast != null) slow = slow.next; // 偶数节点,让 slow 指向下一个节点 cut(head, slow); // 切成两个链表 return isEqual(head, reverse(slow)); } private void cut(ListNode head, ListNode cutNode) { while (head.next != cutNode) { head = head.next; } head.next = null; } private ListNode reverse(ListNode head) { ListNode newHead = null; while (head != null) { ListNode nextNode = head.next; head.next = newHead; newHead = head; head = nextNode; } return newHead; } private boolean isEqual(ListNode l1, ListNode l2) { while (l1 != null && l2 != null) { if (l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } ``` <file_sep>/** * @program JavaBooks * @description: 翻转二叉树 * @author: mf * @create: 2020/03/10 14:30 */ package subject.tree; public class T8 { /** * 还是递归 * @param root * @return */ public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode left = invertTree(root.left); TreeNode right = invertTree(root.right); root.left = right; root.right = left; return root; } } <file_sep>- [synchronized底层原理](/Multithread/Java多线程-synchronized.md) **以下答案可在多线程系列中能找到** - **说一说自己对于 synchronized 关键字的了解** - **说说自己是怎么使用 synchronized 关键字,在项目中用到了吗** - **synchronized关键字最主要的三种使用方式:** - **双重校验锁实现对象单例(线程安全)** - **讲一下 synchronized 关键字的底层原理** - **说说 JDK1.6 之后的synchronized 关键字底层做了哪些优化,可以详细介绍一下这些优化吗** - **谈谈 synchronized和ReentrantLock 的区别** - **说说 synchronized 关键字和 volatile 关键字的区别** - [volatile](/Multithread/深刻理解volatile的一切.md) - [volatile的可见性](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/%E6%B7%B1%E5%88%BB%E7%90%86%E8%A7%A3volatile%E7%9A%84%E4%B8%80%E5%88%87.md#%E5%8F%AF%E8%A7%81%E6%80%A7) - [volatile的可序性](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/%E6%B7%B1%E5%88%BB%E7%90%86%E8%A7%A3volatile%E7%9A%84%E4%B8%80%E5%88%87.md#%E6%9C%89%E5%BA%8F%E6%80%A7) [单例模式](/Multithread/src/com/juc/volatiletest/VolatileVisibleDemo.java) - [volatile不能保证原子性](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/%E6%B7%B1%E5%88%BB%E7%90%86%E8%A7%A3volatile%E7%9A%84%E4%B8%80%E5%88%87.md#%E4%B8%8D%E8%83%BD%E4%BF%9D%E8%AF%81%E5%8E%9F%E5%AD%90%E6%80%A7) - [重排和内存屏障](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/%E6%B7%B1%E5%88%BB%E7%90%86%E8%A7%A3volatile%E7%9A%84%E4%B8%80%E5%88%87.md#%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9C) - [ThreadLocal底层原理](/Multithread/Java多线程-ThreadLocal.md) - **介绍一下ThreadLocal是什么** - **介绍一下底层原理** - **说一下ThreadLocal内存泄漏问题** - [CAS](/Multithread/CAS底层解析.md) - [CAS-Atomic](/Multithread/src/com/juc/cas/CASDemo.java) - [CAS-Unsafe类底层原理](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/CAS%E5%BA%95%E5%B1%82%E8%A7%A3%E6%9E%90.md#%E4%BE%8B%E5%AD%90) - [ABA问题及解决方法](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/CAS%E5%BA%95%E5%B1%82%E8%A7%A3%E6%9E%90.md#cas%E7%9A%84%E9%97%AE%E9%A2%98) - [Java锁机制](/Multithread/Java锁机制.md) - [公平锁/非公平锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E5%85%AC%E5%B9%B3%E9%94%81%E9%9D%9E%E5%85%AC%E5%B9%B3%E9%94%81) - [可重入锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E5%8F%AF%E9%87%8D%E5%85%A5%E9%94%81) - [独享锁/共享锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E7%8B%AC%E4%BA%AB%E9%94%81%E5%85%B1%E4%BA%AB%E9%94%81) - [互斥锁/读写锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E4%BA%92%E6%96%A5%E9%94%81%E8%AF%BB%E5%86%99%E9%94%81) - [乐观锁/悲观锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E4%B9%90%E8%A7%82%E9%94%81%E6%82%B2%E8%A7%82%E9%94%81) - [分段锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E5%88%86%E6%AE%B5%E9%94%81) - [偏向锁/轻量级锁/重量级锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E5%81%8F%E5%90%91%E9%94%81%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81%E9%87%8D%E9%87%8F%E7%BA%A7%E9%94%81) - [自旋锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E9%94%81%E6%9C%BA%E5%88%B6.md#%E8%87%AA%E6%97%8B%E9%94%81) - [手写自旋锁](/Multithread/src/com/juc/lock/SpinLock.java) - [手写读写锁](/Multithread/src/com/juc/lock/ReadWriteLockDemo.java) - [死锁](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%B9%B6%E5%8F%91%E5%9F%BA%E7%A1%80%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98%E6%80%BB%E7%BB%93.md#%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%BF%E7%A8%8B%E6%AD%BB%E9%94%81%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E6%AD%BB%E9%94%81) - [死锁条件](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%B9%B6%E5%8F%91%E5%9F%BA%E7%A1%80%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98%E6%80%BB%E7%BB%93.md#%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E7%BA%BF%E7%A8%8B%E6%AD%BB%E9%94%81) - [死锁代码例子](/Multithread/src/com/juc/pool/DeadLockDemo.java) - [如何找到死锁?]()**通过jdk常用的命令jsp和jstack,jsp查看java程序的id,jstack查看方法的栈信息等。** - [并发集合]() - [为什么ArrayList是线程不安全的?](/Multithread/为什么说ArrayList是线程不安全.md) - [ArrayList->Vector->SynchronizedList->CopyOnWriteArrayList](/Multithread/src/com/juc/collectiontest/ContainerNotSafeDemo.java) - [ArraySet->SynchronizedSet->CopyOnWriteArraySet](/Multithread/src/com/juc/collectiontest/HashSetTest.java) - [HashMap->SynchronizedMap->ConcurrentHashMap](/Multithread/src/com/juc/collectiontest/MapSafe.java) - [AQS](/Multithread/Java多线程-AQS.md) - [CountdownLatch-例子](/Multithread/src/com/juc/aqs/CountDownLatchDemo.java) - [CyclicBarrier-例子](/Multithread/src/com/juc/aqs/CyclicBarrierDemo.java) - [Semaphore-例子](/Multithread/src/com/juc/aqs/SemaphoreDemo.java) - [阻塞队列]() - [BlockingQueue](/Multithread/src/com/juc/queue/BlockingQueueDemo.java) - [传统版生产者消费者模式-synchronized](/Multithread/src/com/juc/queue/ProdConsumerSynchronized.java) - [传统版生产者消费者模式-ReentrantLock](/Multithread/src/com/juc/queue/ProdConsumerReentrantLock.java) - [阻塞队列版本生产者消费者模式](/Multithread/src/com/juc/queue/ProdConsumerBlockingQueue.java) - [线程池](/Multithread/Java多线程-线程池.md) - [线程池的好处?](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#%E4%BD%BF%E7%94%A8%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%A5%BD%E5%A4%84) - [FixedThreadPool详解](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#fixedthreadpool) - [SingleThreadExecutor详解](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#singlethreadexecutor-%E8%AF%A6%E8%A7%A3) - [CachedThreadPool详解](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#cachedthreadpool%E8%AF%A6%E8%A7%A3) - [ScheduledThreadPoolExecutor详解](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#scheduledthreadpoolexecutor-%E8%AF%A6%E8%A7%A3) - [线程池原理-ThreadPoolExecutor](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#%E9%87%8D%E8%A6%81threadpoolexecutor-%E7%B1%BB%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D) - [ThreadPoolExecutor使用示例](/Multithread/src/com/juc/pool/ThreadPoolExecutorDemo.java) - [线程池大小确定](https://github.com/DreamCats/JavaBooks/blob/master/Multithread/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E6%B1%A0.md#%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%A4%A7%E5%B0%8F%E7%A1%AE%E5%AE%9A) <file_sep>import java.util.Arrays; /** * @program JavaBooks * @description: 冒泡排序 * @author: mf * @create: 2019/08/10 19:14 */ /* - 比较相邻的两个元素,如果第一个比第二个大,就交换他们两个。 - 对每一对相邻的元素作同样的工作,从开始第一到结尾的最后一对。这步结束后,最后的元素会是最大的数 */ public class BubbleSort { public static void main(String[] args) { int[] arr = {5, 2, 3, 1, 4}; System.out.println("Bubble sort ..."); System.out.println(Arrays.toString(arr)); int[] resArr = bubbleSort(arr); System.out.println(Arrays.toString(resArr)); } public static int[] bubbleSort(int[] sourceArray) { int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); for (int i = 1; i < arr.length; i++) { // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 for (int j = 0; j < arr.length - i; j++) { // 如果前面的数比后面的数大,则交换 if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } return arr; } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } <file_sep>## 引言 > 咱们这个这样一个面试问题:**"从输入url到页面展示到底发生了什么?**" > > 回答的话,的确很简单!但是其中涉及到的细节非常多,估计能讲半个小时。 > > 大概的过程分为这8步(俗称天龙八部) > > 1. 根据域名,进行DNS域名解析; > 2. 拿到解析的IP地址,建立TCP连接; > 3. 向IP地址,发送HTTP请求; > 4. 服务器处理请求; > 5. 返回响应结果; > 6. 关闭TCP连接; > 7. 浏览器解析HTML; > 8. 浏览器布局渲染; > > 咱们目前这细讲dns,关于这个问题,每一步后续都会有文章讲解。 <!-- more --> ## 解析过程 先看图 ![解析图](https://raw.githubusercontent.com/DreamCats/PicBed/master/20191121165025.png) - 请求一旦发起,若是chrome浏览器,先在浏览器找之前有没有缓存过的域名所对应的ip地址,有的话,直接跳过dns解析了,若是没有,就会找硬盘的hosts文件,看看有没有,有的话,直接找到hosts文件里面的ip - 如果本地的hosts文件没有能的到对应的ip地址,浏览器会发出一个dns请求到本地dns服务器,本地dns服务器一般都是你的网络接入服务器商提供,比如中国电信,中国移动等。 - 查询你输入的网址的DNS请求到达本地DNS服务器之后,本地DNS服务器会首先查询它的缓存记录,如果缓存中有此条记录,就可以直接返回结果,此过程是递归的方式进行查询。如果没有,本地DNS服务器还要向DNS根服务器进行查询。 - 本地DNS服务器继续向域服务器发出请求,在这个例子中,请求的对象是.com域服务器。.com域服务器收到请求之后,也不会直接返回域名和IP地址的对应关系,而是告诉本地DNS服务器,你的域名的解析服务器的地址。 - 最后,本地DNS服务器向域名的解析服务器发出请求,这时就能收到一个域名和IP地址对应关系,本地DNS服务器不仅要把IP地址返回给用户电脑,还要把这个对应关系保存在缓存中,以备下次别的用户查询时,可以直接返回结果,加快网络访问。 ## DNS是? DNS(Domain Name System,域名系统),因特网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的IP数串。通过主机名,最终得到该主机名对应的IP地址的过程叫做域名解析(或主机名解析)。 通俗的讲,我们更习惯于记住一个网站的名字,比如www.baidu.com,而不是记住它的ip地址,比如:172.16.31.10。而计算机更擅长记住网站的ip地址,而不是像www.baidu.com等链接。因为,DNS就相当于一个电话本,比如你要找www.baidu.com这个域名,那我翻一翻我的电话本,我就知道,哦,它的电话(ip)是172.16.31.10。 ## 查询方式 ### 递归解析 当局部DNS服务器自己不能回答客户机的DNS查询时,它就需要向其他DNS服务器进行查询。此时有两种方式。局部DNS服务器自己负责向其他DNS服务器进行查询,一般是先向该域名的根域服务器查询,再由根域名服务器一级级向下查询。最后得到的查询结果返回给局部DNS服务器,再由局部DNS服务器返回给客户端。 ### 迭代解析 当局部DNS服务器自己不能回答客户机的DNS查询时,也可以通过迭代查询的方式进行解析。局部DNS服务器不是自己向其他DNS服务器进行查询,而是把能解析该域名的其他DNS服务器的IP地址返回给客户端DNS程序,客户端DNS程序再继续向这些DNS服务器进行查询,直到得到查询结果为止。也就是说,迭代解析只是帮你找到相关的服务器而已,而不会帮你去查。比如说:baidu.com的服务器ip地址在192.168.4.5这里,你自己去查吧,本人比较忙,只能帮你到这里了。 ## dns域名城空间组织方式 我们在前面有说到根DNS服务器,域DNS服务器,这些都是DNS域名称空间的组织方式。按其功能命名空间中用来描述 DNS 域名称的五个类别的介绍详见下表中,以及与每个名称类型的示例 | 名称类型 | 说明 | 示例 | | :------: | :----------------------------------------------------------: | :-----------------------------: | | 根域 | DNS域名中使用时,规定由尾部句点(.)来指定名称位于根或更高级的域名层次结构 | 单个句点(.)或句点用于末尾的名称 | | 顶级域 | 用来指定某个国家/地区或组织使用的名称的类型名称 | .com | | 第二层域 | 个人或组织Internet上使用的注册名称 | qq.com | | 子域 | 已注册的二级域名派生的域名,通俗的讲就是网站名 | www.qq.com | | 主机名 | 通常情况下,DNS域名的最左侧的标签标示网络上的特定计算机,如h1 | h1.www.qq.com | ## DNS负载均衡 当一个网站有足够多的用户的时候,假如每次请求的资源都位于同一台机器上面,那么这台机器随时可能会蹦掉。处理办法就是用DNS负载均衡技术,它的原理是在DNS服务器中为同一个主机名配置多个IP地址,在应答DNS查询时,DNS服务器对每个查询将以DNS文件中主机记录的IP地址按顺序返回不同的解析结果,将客户端的访问引导到不同的机器上去,使得不同的客户端访问不同的服务器,从而达到负载均衡的目的。例如可以根据每台机器的负载量,该机器离用户地理位置的距离等等。 ## DNS几个问题 ### 为什么域名解析用UDP协议? 因为UDP快啊!UDP的DNS协议只要一个请求、一个应答就好了。而使用基于TCP的DNS协议要三次握手、发送数据以及应答、四次挥手。但是UDP协议传输内容不能超过512字节。不过客户端向DNS服务器查询域名,一般返回的内容都不超过512字节,用UDP传输即可。 ### 为什么区域传送用TCP协议? 因为TCP协议可靠性好啊!你要从主DNS上复制内容啊,你用不可靠的UDP? 因为TCP协议传输的内容大啊,你用最大只能传512字节的UDP协议?万一同步的数据大于512字节,你怎么办?<file_sep>package web; /** * @program LeetNiu * @description: 变态跳台阶 * @author: mf * @create: 2020/01/09 13:34 */ /** * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 */ public class T9 { public int JumpFloorII(int target) { return 1 << (target - 1); } } <file_sep>## 引言 > 大家都知道,在Java并发种,我们最初接触的应该就是`synchronized`关键字了,但是`synchronized`属于重量级锁,很多时候会引起性能问题,`volatile`也是个不错的选择,但是`volatile`不能保证原子性,只能在某些场合下使用。像`synchronized`这种独占锁属于**悲观锁**,乐观锁最常见的就是`CAS`。 <!-- more --> ## 例子 **我们在读Concurrent包下的类的源码时,发现无论是**ReenterLock内部的AQS,还是各种Atomic开头的原子类**,内部都应用到了`CAS`,最常见的就是我们在并发编程时遇到的`i++`这种情况。传统的方法肯定是在方法上加上`synchronized`关键字:** ```java public class Test { public volatile int i; public synchronized void add() { i++; } } ``` **但是这种方法在性能上可能会差一点,我们还可以使用`AtomicInteger`,就可以保证`i`原子的`++`了。** ```java public class Test { public AtomicInteger i; public void add() { i.getAndIncrement(); } } ``` **我们来看`getAndIncrement`的内部:** ```java public final int getAndIncrement() { return unsafe.getAndAddInt(this, valueOffset, 1); } ``` **再深入到`getAndAddInt`():** ```java public final int getAndAddInt(Object var1, long var2, int var4) { int var5; do { var5 = this.getIntVolatile(var1, var2); } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4)); return var5; } ``` **现在重点来了,`compareAndSwapInt(var1, var2, var5, var5 + var4)`其实换成`compareAndSwapInt(obj, offset, expect, update)`比较清楚,意思就是如果`obj`内的`value`和`expect`相等,就证明没有其他线程改变过这个变量,那么就更新它为`update`,如果这一步的`CAS`没有成功,那就采用自旋的方式继续进行`CAS`操作,取出乍一看这也是两个步骤了啊,其实在`JNI`里是借助于一个`CPU`指令完成的。所以还是原子操作。** ## CAS底层原理 **我们可以看到compareAndSwapInt实现是在`Unsafe_CompareAndSwapInt`里面,再深入到`Unsafe_CompareAndSwapInt`:** ```c++ UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) UnsafeWrapper("Unsafe_CompareAndSwapInt"); oop p = JNIHandles::resolve(obj); jint* addr = (jint *) index_oop_from_field_offset_long(p, offset); return (jint)(Atomic::cmpxchg(x, addr, e)) == e; UNSAFE_END ``` **p是取出的对象,addr是p中offset处的地址,最后调用了`Atomic::cmpxchg(x, addr, e)`, 其中参数x是即将更新的值,参数e是原内存的值。代码中能看到cmpxchg有基于各个平台的实现。** ## CAS的问题 ### ABA问题 **CAS需要在操作值的时候检查下值有没有发生变化,如果没有发生变化则更新,但是如果一个值原来是A,变成了B,又变成了A,那么使用CAS进行检查时会发现它的值没有发生变化,但是实际上却变化了。这就是CAS的ABA问题。 常见的解决思路是使用版本号。在变量前面追加上版本号,每次变量更新的时候把版本号加一,那么`A-B-A` 就会变成`1A-2B-3A`。 目前在JDK的atomic包里提供了一个类`AtomicStampedReference`来解决ABA问题。这个类的compareAndSet方法作用是首先检查当前引用是否等于预期引用,并且当前标志是否等于预期标志,如果全部相等,则以原子方式将该引用和该标志的值设置为给定的更新值。** ```java public class ABADemo { static AtomicInteger atomicInteger = new AtomicInteger(100); static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1); public static void main(String[] args) { System.out.println("=====ABA的问题产生====="); new Thread(() -> { atomicInteger.compareAndSet(100, 101); atomicInteger.compareAndSet(101, 100); }, "t1").start(); new Thread(() -> { // 保证线程1完成一次ABA问题 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(atomicInteger.compareAndSet(100, 2020) + " " + atomicInteger.get()); }, "t2").start(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("=====解决ABA的问题====="); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); // 第一次获取版本号 System.out.println(Thread.currentThread().getName() + " 第1次版本号" + stamp); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t第2次版本号" + atomicStampedReference.getStamp()); atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1); System.out.println(Thread.currentThread().getName() + "\t第3次版本号" + atomicStampedReference.getStamp()); }, "t3").start(); new Thread(() -> { int stamp = atomicStampedReference.getStamp(); System.out.println(Thread.currentThread().getName() + "\t第1次版本号" + stamp); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } boolean result = atomicStampedReference.compareAndSet(100, 2020, stamp, stamp + 1); System.out.println(Thread.currentThread().getName() + "\t修改是否成功" + result + "\t当前最新实际版本号:" + atomicStampedReference.getStamp()); System.out.println(Thread.currentThread().getName() + "\t当前最新实际值:" + atomicStampedReference.getReference()); }, "t4").start(); } } ``` ### **循环时间长开销大** **上面我们说过如果CAS不成功,则会原地自旋,如果长时间自旋会给CPU带来非常大的执行开销。** [参考文章](https://juejin.im/post/5a73cbbff265da4e807783f5)<file_sep>package books; /** * @program JavaBooks * @description: 矩阵中的路径 * @author: mf * @create: 2019/08/24 15:02 */ /* 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某 字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步 可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵 的某一格,那么该路径不能再次进入该格子。例如,在下面的3x4的矩阵中包含一条 字符串"afce"的路径(路径中的字母用下画线标出。)但矩阵中不包含字符串"abfb"的 路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次 进入这个格子 */ public class T12 { public static void main(String[] args) { char[][] arr = { {'a', 'b', 't', 'g'}, {'c', 'f', 'c', 's'}, {'j', 'd', 'e', 'h'}}; char[] s = {'b', 'f', 'c', 'e', '\0'}; System.out.println(hasPath(arr, s)); } public static boolean hasPath(char[][] arr, char[] s) { if (arr == null || arr.length < 1 || arr[0].length < 1) return false; int rowNum = arr.length; int colNum = arr[0].length; int pathNum = 0; boolean[][] visited = new boolean[rowNum][colNum]; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < colNum; j++) { if (hasPathCore(arr, rowNum, colNum, i, j, s, pathNum, visited)) { return true; } } } return false; } public static boolean hasPathCore(char[][] arr, int rowNum, int colNum, int i, int j, char[] s, int pathNum, boolean[][] visited) { if (s[pathNum] == '\0') { return true; } boolean hasPath = false; if (i >= 0 && i < rowNum && j >= 0 && j < colNum && arr[i][j] == s[pathNum] && !visited[i][j]){ pathNum++; visited[i][j] = true; hasPath = hasPathCore(arr, rowNum, colNum, i, j -1, s, pathNum, visited) ||hasPathCore(arr, rowNum, colNum, i - 1, j, s, pathNum, visited) ||hasPathCore(arr, rowNum, colNum, i, j + 1, s, pathNum, visited) ||hasPathCore(arr, rowNum, colNum, i + 1, j, s, pathNum, visited); if (!hasPath){ pathNum--; visited[i][j] = false; } } return hasPath; } } <file_sep>## 引言 **Java的集合框架,包括常见的面试源码解析等...** <!-- more --> ## Collection类关系图 ![类关系图](https://www.pdai.tech/_images/java_collections_overview.png) ### 介绍 容器,就是可以容纳其他Java对象的对象。其始于JDK 1.2。 优点: - 降低编程难度 - 提高程序性能 - 提高API间的互操作性 - 降低学习难度 - 降低设计和实现相关API的难度 - 增加程序的重用性 ### Collection 容器主要包括 Collection 和 Map 两种,Collection 存储着对象的集合,而 Map 存储着键值对(两个对象)的映射表。 #### Set ##### TreeSet 基于红黑树实现,支持有序性操作,例如根据一个范围查找元素的操作。但是查找效率不如HashSet,HashSet查找的时间复杂为O(1),TreeSet则为O(logN)。 ##### HashSet 基于哈希表实现,支持快速查找,但不支持有序性操作。并且失去了元素的插入顺序信息,也就是说使用Iterator遍历HashSet得到结果是不确定的。 ##### LinkedHashSet 具有HashSet的查找效率,且内部使用双向链表维护元素的插入顺序。 #### List ##### ArrayList 基于动态数组实现,支持随机访问。 ##### Vector 和ArrayList类似,但它是线程安全的。 ##### LinkedList 基于双向链表实现,只能顺序访问,但是可以快速地在链表中间插入和删除元素。不仅如此,LinkedList还可以用作栈、队列和双向队列。 #### Queue ##### LinkedList 可以用来实现双向队列。 ##### PriorityQueue 基于堆结构实现,可以用它实现优先队列。 #### Map ##### TreeMap 基于红黑树实现 ##### HashMap 基于哈希表实现 ##### HashTable - 和 HashMap 类似,但它是线程安全的,这意味着同一时刻多个线程可以同时写入 HashTable 并且不会导致数据不一致。 - 它是遗留类,不应该去使用它。 - 现在可以使用 ConcurrentHashMap 来支持线程安全,并且 ConcurrentHashMap 的效率会更高,因为 ConcurrentHashMap 引入了分段锁。 ##### LinkedHashMap 使用双向链表来维护元素的顺序,顺序为插入顺序或者最近最少使用(LRU)顺序。<file_sep>## 引言 **HashMap 和 ConcurrentHashMap面试常问,务必理解和掌握** ## HashMap 众所周知,HashMap的底层结构是**数组和链表**组成的,不过在jdk1.7和jdk1.8中具体实现略有不同。 <!-- more --> ### jdk1.7 先看图![](https://i.loli.net/2019/05/08/5cd1d2be77958.jpg) 再看看1.7的实现![](https://i.loli.net/2019/05/08/5cd1d2bfd6aba.jpg) 介绍成员变量: - 初始化桶大小,因为底层是数组,所以这是数组默认的大小。 - 桶最大值。 - 默认的负载因子(0.75) - table真正存放数据的数组。 - map存放数量的大小 - 桶大小,可在构造函数时显式指定。 - 负载因子,可在构造函数时显式指定。 #### 负载因子 源代码 ```java public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); // 桶和负载因子 } public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); } ``` - 给定的默认容量为16,负载因子为0.75. - Map在使用过程中不断的往里面存放数据,当数量达到了`16 * 0.75 = 12`就需要将当前16的容量进行扩容,而扩容这个过程涉及到rehash(重新哈希)、复制数据等操作,所有非常消耗性能。 - 因此通常建议能提前预估HashMap的大小最好,尽量的减少扩容带来的额外性能损耗。 #### Entry `transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;` 如何定义呢?![](https://i.loli.net/2019/05/08/5cd1d2c08e693.jpg) Entry是Hashmap中的一个内部类,从他的成员变量很容易看出: - key就是写入时的键 - value自然就是值 - 开始的时候就提到HashMap是由数组和链表组成,所以这个next就是用于实现链表结构 - hash存放的是当前key的hashcode #### put ```java public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); // 判断数组是否需要初始化 } if (key == null) return putForNullKey(value); // 判断key是否为空 int hash = hash(key); // 计算hashcode int i = indexFor(hash, table.length); // 计算桶 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { // 遍历判断链表中的key和hashcode是否相等,等就替换 V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); // 没有就添加新的呗 return null; } ``` - 判断当前数组是否需要初始化 - 如果key为空,则put一个空值进去 - 根据key计算hashcode - 根据计算的hashcode定位index的桶 - 如果桶是一个链表,则需要遍历判断里面的hashcode、key是否和传入的key相等,如果相等则进行覆盖,并返回原来的值 - 如果桶是空的,说明当前位置没有数据存入,此时新增一个Entry对象写入当前位置。 ```java void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) {// 是否扩容 resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; } ``` - 当调用addEntry写入Entry时需要判断是否需要扩容 - 如果需要就进行两倍扩充,并将当前的key重新hash并定位。 - 而在createEntry中会将当前位置的桶传入到新建的桶中,如果当前桶油值就会在位置形成链表。 #### get ```java public V get(Object key) { if (key == null) // 判断key是否为空 return getForNullKey(); // 为空,就返回空值 Entry<K,V> entry = getEntry(key); // get entry return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); //根据key和hashcode for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; } ``` - 首先根据key计算hashcode,然后定位具体的桶 - 判断该位置是否为链表 - 不是链接就根据key和hashcode是否相等来返回值 - 为链表则需要遍历直到key和hashcode相等就返回值 - 啥都没得,就返回null ### jdk1.8 不知道 1.7 的实现大家看出需要优化的点没有? 其实一个很明显的地方就是链表 **当 Hash 冲突严重时,在桶上形成的链表会变的越来越长,这样在查询时的效率就会越来越低;时间复杂度为 `O(N)`。** ![](https://i.loli.net/2019/05/08/5cd1d2c1c1cd7.jpg) 看看成员变量 ```java static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; static final int TREEIFY_THRESHOLD = 8; transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; ``` - `TREEIFY_THRESHOLD` 用于判断是否需要将链表转换为红黑树的阈值。 - HashEntry 修改为 Node。 - Node 的核心组成其实也是和 1.7 中的 HashEntry 一样,存放的都是 `key value hashcode next` 等数据。 #### put ![](https://i.loli.net/2019/05/08/5cd1d2c378090.jpg) - 判断当前桶是否为空,空的就需要初始化(resize中会判断是否进行初始化) - 根据当前key的hashcode定位到具体的桶中并判断是否为空,为空则表明没有Hash冲突,就直接在当前位置创建一个新桶 - 如果当前桶油值(Hash冲突),那么就要比较当前桶中的key、key的hashcode与写入的key是否相等,相等就赋值给e,在第8步的时候会统一进行赋值及返回 - 如果当前桶为红黑树,那就要按照红黑树的方式写入数据 - 如果是个链表,就需要将当前的key、value封装称一个新节点写入到当前桶的后面形成链表。 - 接着判断当前链表的大小是否大于预设的阈值,大于就要转换成为红黑树 - 如果在遍历过程中找到key相同时直接退出遍历。 - 如果`e != null`就相当于存在相同的key,那就需要将值覆盖。 - 最后判断是否需要进行扩容。 #### get ```java public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } ``` - 首先将key hash之后取得所定位的桶 - 如果桶为空,则直接返回null - 否则判断桶的第一个位置(有可能是链表、红黑树)的key是否为查询的key,是就直接返回value - 如果第一个不匹配,则判断它的下一个是红黑树还是链表 - 红黑树就按照树的查找方式返回值 - 不然就按照链表的方式遍历匹配返回值 **从这两个核心方法(get/put)可以看出 1.8 中对大链表做了优化,修改为红黑树之后查询效率直接提高到了 `O(logn)`。** ## 问题 但是 HashMap 原有的问题也都存在,比如在并发场景下使用时容易出现死循环。 ```java final HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { @Override public void run() { map.put(UUID.randomUUID().toString(), ""); } }).start(); } ``` - HashMap扩容的时候会调用resize()方法,就是这里的并发操作容易在一个桶上形成环形链表 - 这样当获取一个不存在的key时,计算出的index正好是环形链表的下标就会出现死循环。 - 但是1.7的头插法造成的问题,1.8改变了插入顺序,就解决了这个问题,但是为了内存可见性等安全性,还是需要ConCurrentHashMap ![](https://i.loli.net/2019/05/08/5cd1d2c4ede54.jpg) ## 遍历方式 还有一个值得注意的是 HashMap 的遍历方式,通常有以下几种: ```java Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, Integer> next = entryIterator.next(); System.out.println("key=" + next.getKey() + " value=" + next.getValue()); } Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()){ String key = iterator.next(); System.out.println("key=" + key + " value=" + map.get(key)); } ``` - 建议使用第一种,同时可以把key value取出。 - 第二种还需要通过key取一次key,效率较低。 ## ConCurrentHashMap ### jdk1.7 ![](https://i.loli.net/2019/05/08/5cd1d2c5ce95c.jpg) - Segment数组 - HashEntry组成 - 和HashMap一样,仍然是数组加链表 ```java /** * Segment 数组,存放数据时首先需要定位到具体的 Segment 中。 */ final Segment<K,V>[] segments; transient Set<K> keySet; transient Set<Map.Entry<K,V>> entrySet; ``` Segment 是 ConcurrentHashMap 的一个内部类,主要的组成如下: ```java static final class Segment<K,V> extends ReentrantLock implements Serializable { private static final long serialVersionUID = 2249069246763182397L; // 和 HashMap 中的 HashEntry 作用一样,真正存放数据的桶 transient volatile HashEntry<K,V>[] table; transient int count; transient int modCount; transient int threshold; final float loadFactor; } ``` ![](https://i.loli.net/2019/05/08/5cd1d2c635c69.jpg) - 唯一的区别就是其中的核心数据如 value ,以及链表都是 volatile 修饰的,保证了获取时的可见性。 - ConcurrentHashMap 采用了分段锁技术,其中 Segment 继承于 ReentrantLock。 - 不会像HashTable那样不管是put还是get操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。 - 每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment。 #### put ```java public V put(K key, V value) { Segment<K,V> s; if (value == null) throw new NullPointerException(); int hash = hash(key); int j = (hash >>> segmentShift) & segmentMask; if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment s = ensureSegment(j); return s.put(key, hash, value, false); } ``` - 通过key定位到Segment,之后在对应的Segment中进行具体的put ```java final V put(K key, int hash, V value, boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { HashEntry<K,V>[] tab = table; int index = (tab.length - 1) & hash; HashEntry<K,V> first = entryAt(tab, index); for (HashEntry<K,V> e = first;;) { if (e != null) { K k; if ((k = e.key) == key || (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { if (node != null) node.setNext(first); else node = new HashEntry<K,V>(hash, key, value, first); int c = count + 1; if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); } return oldValue; } ``` - 虽然HashEntry中的value是用volatile关键字修饰的,但是并不能保证并发的原子性,所以put操作仍然需要加锁处理。 - 首先第一步的时候会尝试获取锁,如果获取失败肯定就是其他线程存在竞争,则利用 `scanAndLockForPut()` 自旋获取锁。 ![](https://i.loli.net/2019/05/08/5cd1d2cc3c982.jpg) - 尝试获取自旋锁 - 如果重试的次数达到了`MAX_SCAN_RETRIES` 则改为阻塞锁获取,保证能获取成功。 ![](https://i.loli.net/2019/05/08/5cd1d2cd25c37.jpg) - 将当前的Segment中的table通过key的hashcode定位到HashEntry - 遍历该HashEntry,如果不为空则判断传入的key和当前遍历的key是否相等,相等则覆盖旧的value - 不为空则需要新建一个HashEntry并加入到Segment中,同时会先判断是否需要扩容 - 最后会解除在1中所获取当前Segment的所。 #### get方法 ```java public V get(Object key) { Segment<K,V> s; // manually integrate access methods to reduce overhead HashEntry<K,V>[] tab; int h = hash(key); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE); e != null; e = e.next) { K k; if ((k = e.key) == key || (e.hash == h && key.equals(k))) return e.value; } } return null; } ``` - 只需要将 Key 通过 Hash 之后定位到具体的 Segment ,再通过一次 Hash 定位到具体的元素上。 - 由于 HashEntry 中的 value 属性是用 volatile 关键词修饰的,保证了内存可见性,所以每次获取时都是最新值。 - ConcurrentHashMap 的 get 方法是非常高效的,**因为整个过程都不需要加锁**。 ### jdk1.8 **那就是查询遍历链表效率太低。** ![](https://i.loli.net/2019/05/08/5cd1d2ce33795.jpg) **其中抛弃了原有的 Segment 分段锁,而采用了 `CAS + synchronized` 来保证并发安全性** ![](https://i.loli.net/2019/05/08/5cd1d2ceebe02.jpg) - 也将 1.7 中存放数据的 HashEntry 改为 Node,但作用都是相同的。 - 其中的 `val next` 都用了 volatile 修饰,保证了可见性。 #### put ![](https://i.loli.net/2019/05/08/5cd1d2cfc3293.jpg) - 根据key计算出hashcode - 判断是否需要进行初始化 - f即为当前key定位出的Node,如果为空表示当前位置可以写入数据,利用CAS尝试写入,失败则自旋保证成功。 - 如果当前位置的`hashcode == MOVED == -1`,则需要进行扩容 - 如果都不满足,则利用synchronized锁写入数据 - 如果数量大于`TREEIFY_THRESHOLD` 则要转换为红黑树。 #### get ![](https://i.loli.net/2019/05/08/5cd1d2d22c6cb.jpg) - 根据计算出来的 hashcode 寻址,如果就在桶上那么直接返回值。 - 如果是红黑树那就按照树的方式获取值。 - 就不满足那就按照链表的方式遍历获取值。 1.8 在 1.7 的数据结构上做了大的改动,采用红黑树之后可以保证查询效率(`O(logn)`),甚至取消了 ReentrantLock 改为了 synchronized,这样可以看出在新版的 JDK 中对 synchronized 优化是很到位的。 ## 总结 套路: - 谈谈你理解的 HashMap,讲讲其中的 get put 过程。 - 1.8 做了什么优化? - 是线程安全的嘛? - 不安全会导致哪些问题? - 如何解决?有没有线程安全的并发容器? - ConcurrentHashMap 是如何实现的? 1.7、1.8 实现有何不同?为什么这么做?<file_sep>package web; /** * @program LeetNiu * @description: 和为S的连续正数序列 * @author: mf * @create: 2020/01/15 10:37 */ import java.util.ArrayList; /** * 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。 * 但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。 * 没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。 * 现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck! */ public class T41 { public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>(); int phigh = 2; int plow = 1; while(phigh > plow) { int cur = (phigh + plow) * (phigh - plow + 1) / 2; if (cur < sum) { phigh++; } if (cur == sum) { ArrayList<Integer> arrayList = new ArrayList<>(); for (int i = plow; i <= phigh; i++) { arrayList.add(i); } arrayLists.add(arrayList); plow++; } if (cur > sum) { plow++; } } return arrayLists; } } <file_sep>package books; /** * @program JavaBooks * @description: 翻转字符串 * @author: mf * @create: 2019/10/08 15:39 */ /* 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变, 为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student." 则输出"student. a am I" */ public class T58 { public static void main(String[] args) { String s = "I am a student."; System.out.println(reverseSentence(s)); } private static String reverseSentence(String s) { if (s == null) return null; if (s.trim().equals("")) return s; String[] strs = s.split(" "); StringBuffer sb = new StringBuffer(); for (int i = strs.length - 1; i >= 0; i--) { sb.append(strs[i]).append(" "); } return sb.substring(0, sb.length() - 1); } } <file_sep>## 引言 > 面试时相信面试官首先就会问到关于它的知识。一个经常被问到的问题就是:ArrayList是否是线程安全的?那么它为什么是线程不安全的呢?它线程不安全的具体体现又是怎样的呢?我们从源码的角度来看下。 <!-- more --> ## 源码分析 **首先看看该类的属性字段**: ```java /** * 列表元素集合数组 * 如果新建ArrayList对象时没有指定大小,那么会将EMPTY_ELEMENTDATA赋值给elementData, * 并在第一次添加元素时,将列表容量设置为DEFAULT_CAPACITY */ transient Object[] elementData; /** * 列表大小,elementData中存储的元素个数 */ private int size; ``` **ArrayList的实现主要就是用了一个Object的数组,用来保存所有的元素,以及一个size变量用来保存当前数组中已经添加了多少元素。** **再次看add方法的源码** ```java public boolean add(E e) { /** * 添加一个元素时,做了如下两步操作 * 1.判断列表的capacity容量是否足够,是否需要扩容 * 2.真正将元素放在列表的元素数组里面 */ ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } ``` **由此看到add元素时,实际做了两个大的步骤:** 1. 判断elementData数组容量是否满足需求 2. 在elementData对应位置上设置值 ## 数组越界 1. 列表大小为9,即size=9 2. 线程A开始进入add方法,这时它获取到size的值为9,调用ensureCapacityInternal方法进行容量判断。 3. 线程B此时也进入add方法,它获取到size的值也为9,也开始调用ensureCapacityInternal方法。 4. 线程A发现需求大小为10,而elementData的大小就为10,可以容纳。于是它不再扩容,返回。 5. 线程B也发现需求大小为10,也可以容纳,返回。 6. 线程A开始进行设置值操作, elementData[size++] = e 操作。此时size变为10。 7. 线程B也开始进行设置值操作,它尝试设置elementData[10] = e,而elementData没有进行过扩容,它的下标最大为9。于是此时会报出一个数组越界的异常ArrayIndexOutOfBoundsException. ## null值的情况 **elementData[size++] = e不是一个原子操作**: - elementData[size] = e; - size = size + 1; **逻辑:** 1. 列表大小为0,即size=0 2. 线程A开始添加一个元素,值为A。此时它执行第一条操作,将A放在了elementData下标为0的位置上。 3. 接着线程B刚好也要开始添加一个值为B的元素,且走到了第一步操作。此时线程B获取到size的值依然为0,于是它将B也放在了elementData下标为0的位置上。 4. 线程A开始将size的值增加为1 5. 线程B开始将size的值增加为2 **这样线程AB执行完毕后,理想中情况为size为2,elementData下标0的位置为A,下标1的位置为B。而实际情况变成了size为2,elementData下标为0的位置变成了B,下标1的位置上什么都没有。并且后续除非使用set方法修改此位置的值,否则将一直为null,因为size为2,添加元素时会从下标为2的位置上开始。** ## 案例 ```java /** * 故障现象 * java.util.ConcurrentModificationException */ public static void notSafe() { List<String> list = new ArrayList<>(); for (int i = 1; i <= 3; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 8)); System.out.println(list); }, "Thread " + i).start(); } } ``` <file_sep># JavaBooks ## 引言 > 总结的知识点包括: > > - Java基础 > - Java集合 > - Java多线程 > - JVM虚拟机 > - Spring系列(SpringIOC、SpringAOP、SpringMVC及SpringBoot) > - ORM(Mybatis) > - 数据库(Mysql和Redis) > - 微服务(Dubbo) > - 消息队列(RocketMQ) > - 计算机网络 > - 操作系统(Linux系统) > - 微服务项目(SpringBoot+Mybatis+Dubbo+Mysql+Redis+RocketMQ) > - 数据结构与算法(Leetcode/剑指Offer) > - 设计模式 > - 常用工具 > > **如果观看不流畅,可以去我的博客浏览面试知识点** > - [dreamcat.ink](http://dreamcat.ink/) > - [在线阅读](https://dreamcater.gitee.io/javabooks/) ## 常用网站 - [:bookmark:开源项目总结](/Tools/network/开源的github项目总结.md) - [:fire:常用的在线网站](/Tools/network/收集常用的网站(持续更新...).md) - [:sparkles:emoji集合](/Tools/network/github表情图标.md) - [:smiling_imp:Linux命令行的奇淫技巧](/Tools/network/Linux命令行的奇淫技巧.md) - [📖今日热榜](https://tophub.today/):一款新闻聚合的产品,个人感觉还不错,闲时可以看一下新闻,可选择订阅哦 ## Java面试思维导图(包括分布式架构) - [总体架构](https://www.processon.com/view/link/5e170217e4b0bcfb733ce553) **这边就不放图了,放图的字体小,放大可能模糊。该图还在持续总结中...** - [Java常见基础问题](https://www.processon.com/view/link/5e457c32e4b05d0fd4e94cad) **常见的基础问题,这是必须要掌握。** - [Java常见集合问题]() **还没总结,后续总结...** - [Java常见多线程问题](https://www.processon.com/view/link/5e4ab92de4b0996b2ba505bf) **常见的多线程问题,也是必须掌握...** - [JVM常见问题](https://www.processon.com/view/link/5e4c0704e4b00aefb7e74f44) **常见的JVM要掌握的点...** - [Spring常见问题](https://www.processon.com/view/link/5e846de9e4b07b16dcdb63f0) **常见的Spring面试的问题...** - [Mybatis常见问题](https://www.processon.com/view/link/5e4e3b7ae4b0369b916b2e71) **常见的Mybatis面试的问题...** - [MySQL常见问题](https://www.processon.com/view/link/5e9b0cb15653bb1a686e17ea) **常见的MySQL面试的问题...** - [Redis常见问题](https://www.processon.com/view/link/5ea2da5907912948b0d89a0a) **常见的Redis面试的问题...** ## 微服务班车在线预约系统 - [微服务班车在线预约系统](https://github.com/DreamCats/SchoolBus) 个人撸的项目是基于微服务架构的班车预约系统,采用**springboot+mybatis+dubbo+rocketmq+mysql+redis等**。当然,该项目也是前后端分离,前端采用比较流行的vue框架。 ## 个人事迹 **本来是不想贴的,之前做了图,见丑了...** - [本科事迹](https://www.processon.com/view/link/5e45532fe4b06b291a6e0d7c) **不是科班出身,专业是就不说啦...** - [研究生事迹](https://www.processon.com/view/link/5e455cbae4b06b291a6e1af0) **还未结束,后续继续补充...** - [个人博客](http://www.dreamcat.ink) **这是我个人博客,该项目的文章都在博客上有体现,github上若是阅读不佳,可以去博客上观看,时间紧迫,有些地方还没有细细的优化** ## 吐血系列 - **个人吐血系列-总结Java基础**: [本地阅读](/Interview/crazy/个人吐血系列-总结Java基础.md)->[博客阅读](http://dreamcat.ink/2020/03/27/ge-ren-tu-xie-xi-lie-zong-jie-java-ji-chu/)->[掘金阅读](https://juejin.im/post/5e7e0615f265da795568754b) - **个人吐血系列-总结Java集合**: [本地阅读](/Interview/crazy/个人吐血系列-总结Java集合.md)->[博客阅读](http://dreamcat.ink/2020/03/28/ge-ren-tu-xie-xi-lie-zong-jie-java-ji-he/)->[掘金阅读](https://juejin.im/post/5e801e29e51d45470b4fce1c) - **个人吐血系列-总结Java多线程**: [本地阅读](/Interview/crazy/个人吐血系列-总结Java多线程.md)->[博客阅读](http://dreamcat.ink/2020/03/25/ge-ren-tu-xie-xi-lie-zong-jie-java-duo-xian-cheng/)->[掘金阅读-1](https://juejin.im/post/5e7e0e4ce51d4546cd2fcc7c) [掘金阅读-2](https://juejin.im/post/5e7e10b5518825739b2d1fb1) - **个人吐血系列-总结JVM**: [本地阅读](/Interview/crazy/个人吐血系列-总结JVM.md)->[博客阅读](http://dreamcat.ink/2020/03/28/ge-ren-tu-xie-xi-lie-zong-jie-jvm/)->[掘金阅读](https://juejin.im/post/5e8344486fb9a03c786ef885) - **个人吐血系列-总结Spring**: [本地阅读](/Interview/crazy/个人吐血系列-总结Spring.md)->[博客阅读](http://dreamcat.ink/2020/03/29/ge-ren-tu-xie-xi-lie-zong-jie-spring/)->[掘金阅读](https://juejin.im/post/5e846a4a6fb9a03c42378bc1) - **个人吐血系列-总结Mybatis**: [本地阅读](/Interview/crazy/个人吐血系列-总结Mybatis.md)->[博客阅读](http://dreamcat.ink/2020/03/29/ge-ren-tu-xie-xi-lie-zong-jie-mybatis/)->[掘金阅读](https://juejin.im/post/5e889b196fb9a03c875c8f50) - **个人吐血系列-总结MySQL**: [本地阅读](/Interview/crazy/个人吐血系列-总结MySQL.md)->[博客阅读](http://dreamcat.ink/2020/03/30/ge-ren-tu-xie-xi-lie-zong-jie-mysql/)->[掘金阅读](https://juejin.im/post/5e94116551882573b86f970f) - **个人吐血系列-总结Redis**: [本地阅读](/Interview/crazy/个人吐血系列-总结Redis.md)->[博客阅读](http://dreamcat.ink/2020/03/31/ge-ren-tu-xie-xi-lie-zong-jie-redis/)->[掘金阅读](https://juejin.im/post/5e9d6a9ff265da47e34c0e8a) - **个人吐血系列-总结计算机网络**: [本地阅读](/Interview/crazy/个人吐血系列-总结计算机网络.md)->[博客阅读](http://dreamcat.ink/2020/04/02/ge-ren-tu-xie-xi-lie-zong-jie-ji-suan-ji-wang-luo/)->[掘金阅读](https://juejin.im/post/5ea383c251882573716ab496) ## 面经 ### 美团 - [美团小象二面实习面经](/Interview/mianjing/meituan/meituan01.md) - [美团到店一、二面](/Interview/mianjing/meituan/meituan02.md) - [美团广告一、二面](/Interview/mianjing/meituan/meituan03.md) - [美团北京一、二、三面](/Interview/mianjing/meituan/meituan04.md) - [美团面经一、二、三面](/Interview/mianjing/meituan/meituan05.md) ## 微信公众号推荐 - **JavaGuide**:大家都懂的,帮这位老哥宣传一下-->"开源项目—JavaGuide (56k+Star)作者运营维护。专注Java后端学习!内容涵盖Java面试指南、Spring Boot、Dubbo、Zookeeper、Redis、Nginx、消息队列、系统设计、架构、编程规范等内容。" - **程序员乔戈里**:我也经常浏览,大佬也非常勤奋,也宣传一下-->"开源项目—JavaGuide (56k+Star)作者运营维护。专注Java后端学习!内容涵盖Java面试指南、Spring Boot、Dubbo、Zookeeper、Redis、Nginx、消息队列、系统设计、架构、编程规范等内容。" - **帅地玩编程**:少不了**帅地呀**,hhh-->"本号专注于讲解数据结构与算法、计算机基础(如计算机网络+操作系统+数据库+Linux)等编程知识,期待你的关注。" - **GitHubDaily**:经常分享Github一些项目-->"专注于分享 Python、Java、Web、AI、数据分析等多个领域的优质学习资源、开源项目及开发者工具。" - **方志朋**:号主为BAT一线架构师,CSDN博客专家,博客访问量突破一千万,著有畅销书《深入理解SpringCloud与微服务构建》。主要分享Java、Python等技术,用大厂程序员的视角来探讨技术进阶、面试指南、职业规划等。15W技术人的选择! - **好好学java**:学习Java必备公众号,关注于Java、算法,公众号每日与您分享Java知识,定期的分享面试题,关注我们吧,和小海一起学习进步! - **小鹿动画学编程**:和小鹿同学一起用动画的方式从基础学编程,将 Web前端领域、数据结构与算法、网络原理等通俗易懂的呈献给小伙伴。先定个小目标,原创 1000 篇的动画技术文章,和各位小伙伴一起学习! - **Java3y**:看人家说的:”只有光头才能变强“,头像也是个光头呢。 - **本来作者也有微信公众号的...**:可惜时间由于学业问题,很少维护,等后期有空重新整理,目前我就不贴自己微信公众号了 ## 刷题系列 - [SwordOffer-书的顺序](/SwordOffer/README.md) - [SwordOffer-牛客网的顺序](https://github.com/DreamCats/LeetNiu#%E5%89%91%E6%8C%87offer-%E7%BD%91%E7%AB%99) - [LeetCode-正常顺序](/LeetCode/README.md) - [链表-专题](/LeetCode/数据结构-链表.md) - [树-专题](/LeetCode/数据结构-树-基础.md) - [栈和队列-专题](/LeetCode/数据结构-栈和队列.md) - [双指针-专题](/LeetCode/数据结构-双指针.md) - [哈希表-专题](/LeetCode/数据结构-哈希表.md) - [位运算-专题](/LeetCode/数据结构-位运算.md) - [动态规划-专题](/LeetCode/数据结构-动态规划.md) ## 基础 - [Java面试基础一些常见问题-思维导图](https://www.processon.com/view/link/5e457c32e4b05d0fd4e94cad) - [Java面试基础知识](/Basics/Java面试基础知识.md) - [Java面试基础知识](/Basics/Java面试基础常见问题.md) ### 基础图解 - [异常分类图解](https://www.processon.com/view/link/5e404235e4b021dc289fbf72) ## 集合源码 - [Java面经-Java集合框架](/Collections/Java面经-Java集合框架.md) - [Java面经-ArrayList源码解析](/Collections/Java面经-ArrayList源码解析.md) - [Java面经-LinkedList源码解析](/Collections/Java面经-LinkedList源码解析.md) - [Java面经-HashSet-HashMap源码解析](/Collections/Java面经-HashSet-HashMap源码解析.md) - [Java面经-LinkedHashSet-Map源码解析](/Collections/Java面经-LinkedHashSet-Map源码解析.md) - [Java面经-TreeSet-TreeMap源码解析](/Collections/Java面经-TreeSet-TreeMap源码解析.md) - [Java面经-PriorityQueue源码解析](/Collections/Java面经-PriorityQueue源码解析.md) - [Java面经-Stack-Queue源码解析](/Collections/Java面经-Stack-Queue源码解析.md) - [HashMap-ConcurrentHashMap面试必问](/Collections/HashMap-ConcurrentHashMap面试必问.md) ### 集合图解 - [ArrayList源码分析](https://www.processon.com/view/link/5e13ddf5e4b07ae2d01c7369) - [LinkedList源码分析](https://www.processon.com/view/link/5e13e641e4b0c090e0b88a59) - [HashMap源码分析](https://www.processon.com/view/link/5e159150e4b07db4cfb0f418) ## 多线程系列 - [多线程思维导图](https://www.processon.com/view/link/5e4ab92de4b0996b2ba505bf) - [Java多线程-并发基础常见面试题总结](/Multithread/Java多线程-并发基础常见面试题总结.md) - [Java多线程-Synchronized](/Multithread/Java多线程-synchronized.md) - [Java多线程-volatile](/Multithread/深刻理解volatile的一切.md) - [Java多线程-CAS](/Multithread/CAS底层解析.md) - [Java多线程-ThreadLocal](/Multithread/Java多线程-ThreadLocal.md) - [Java多线程-Atomic原子类](/Multithread/Java多线程-Atomic原子类.md) - [Java多线程-AQS](/Multithread/Java多线程-AQS.md) - [Java多线程-线程池](/Multithread/Java多线程-线程池.md) - [Java多线程-并发进阶常见面试题总结](/Multithread/Java多线程-并发进阶常见面试题总结.md) - [多线程一些例子](/Multithread/README.md) - [Java多线程常见问题](/Multithread/Java多线程常见问题.md) ### 多线程图解 - [谈谈Java内存模型](https://www.processon.com/view/link/5e129d57e4b0da16bb11d127) - [有个成员变量int a = 1,那么a和1分别在jvm哪里](https://www.processon.com/view/link/5e13500de4b009af4a5fc40b) - [线程的状态周期图](https://www.processon.com/view/link/5e16a379e4b0f5a7ed06d2fb) - [volatile保证内存可见性和避免重排](https://www.processon.com/view/link/5e12e591e4b061a80c683639) - [volatile不能保证原子性操作](https://www.processon.com/view/link/5e130e51e4b07db4cfac9d2c) - [无锁-偏向锁-轻量级锁-重量级锁](https://www.processon.com/view/link/5e1744a7e4b0f5a7ed086f4a) - [内存屏障](https://www.processon.com/view/link/5e4420bde4b06b291a6c463b) ## JVM - [JVM面试思维导图](https://www.processon.com/view/link/5e4c0704e4b00aefb7e74f44) - [JVM-类文件结构](/Jvm/JVM-类文件结构.md) - [JVM-类加载过程](/Jvm/JVM-类加载过程.md) - [JVM-类加载机制](/Jvm/Java面经-类加载机制.md) - [JVM-类加载器](/Jvm/JVM-类加载器.md) - [JVM-内存模型](/Jvm/Java面经-内存模型.md) - [JVM-对象创建](/Jvm/JVM-对象创建.md) - [JVM-垃圾回收](/Jvm/JVM-垃圾回收.md) - [JVM-调优参数](/Jvm/Java面经-JVM调优参数.md) - [JVM面试常见问题](/Jvm/JVM面试常见问题.md) ### JVM例子 - [引用计数的循环引用问题](/Jvm/src/T2.java) ### JVM图解 - [JVM整个流程](https://www.processon.com/view/link/5e1182afe4b009af4a5cc54d) ## Spring系列 ### 参考笔记 - [b站视频入口](https://www.bilibili.com/video/av32102436?p=1) - [代码资料](https://gitee.com/adanzzz/spring_source_parsing_data) ### 思维导图 - [Spring注解驱动开发](https://www.processon.com/view/link/5e30213ae4b096de64c8e9bf) ### 源码总结 - [Spring和SpringAOP](/Spring和SpringAOP源码总结.md) - [参考这位大佬的MVC原理](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringMVC-Principle) **这位大佬总结的不错,可参考** - [SpringMVC开发文档](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html) **这里就不贴视频中的SpringMVC工程** ### 手写简单的IOC和AOP - [手写简单的IOC](/spring-ioc) 非常简单,每行都有注释 - [手写简单的AOP](/spring-aop2) 非常简单,每行都有注 ### SpringBoot **[参考这位大佬](https://snailclimb.gitee.io/springboot-guide/#/)** **项目结构过于具体简单的文件解释就不说了,主要是看细节和原理** - [SpringBoot启动流程分析](/SpringBoot启动流程分析.md) ### 常见问题 - [Spring面试常见问题](/Interview/spring/Spring面试常见问题.md) ## MyBatis系列 - [MyBatis常见问题的思维导图](https://www.processon.com/view/link/5e4e3b7ae4b0369b916b2e71) - [MyBatis面试相关系列](https://github.com/DreamCats/SpringBooks#mybatis) - [MyBatis源码](https://juejin.im/entry/5b9886735188255c960c1bec) - [MyBatis面试常见问题](/Interview/mybatis/MyBatis面试常见问题.md) ## 计算机网络 - [计算机网络原理-DNS是干什么的?](/Interview/network/计算机网络原理-DNS是干什么的.md) - [计算机网络原理-http那些事儿](/Interview/network/计算机网络原理-http那些事儿.md) - [动画:用动画给面试官解释 TCP 三次握手过程](https://blog.csdn.net/qq_36903042/article/details/102513465) - [动画:用动画给女朋友讲解 TCP 四次分手过程](https://blog.csdn.net/qq_36903042/article/details/102656641) - [计算机网络面试常见问题](Interview/network/计算机网络面试常见问题.md) ## MySQL - [SQL-数据库系统原理](/Interview/mysql/sql-数据库系统原理.md) - [MySQL中ACID的原理](/Interview/mysql/Mysql中ACID的原理.md) - [SQL-存储引擎](/Interview/mysql/sql-存储引擎.md) - [SQL-索引(B+树)](/Interview/mysql/sql-索引-B-树.md) - [MySQL面试常见问题](Interview/mysql/MySQL面试常见问题.md) ## Redis - [Redis-面试常见的问题](/Interview/redis/Redis-面试常见的问题.md) ## Dubbo - [Dubbo-面试常见问题](/Interview/crazy/个人吐血系列-总结Dubbo.md) ## RocketMQ - [消息队列-RocketMQ面试常见问题](Interview/crazy/个人吐血系列-总结RocketMQ.md) ## Linux - [linux-基础](/Interview/linux/linux-基础.md) ## Interview - [设计一个LRU](/Interview/src/LRUDemo.md) - [二叉树的深度搜索遍历](/Interview/src/DFSDemo.java) ## Sorts(排序) - [冒泡排序](/Sorts/src/BubbleSort.java) - [选择排序](/Sorts/src/SelectSort.java) - [插入排序](/Sorts/src/InsertSort.java) - [归并排序](/Sorts/src/MergeSort.java) - [快速排序](/Sorts/src/QuickSort.java) - [堆排序](/Sorts/src/HeapSort.java) ## Searchs(查找) - [二分查找](/Searchs/src/BinarySearch.java) ## DesignPattern(设计模式) - [单例模式](/SwordOffer/src/T2.java) - [工厂模式](/DesignPattern/src/FactoryMode.java) - [代理模式](/DesignPattern/src/ProxyMode.java) - [模版方法模式](/DesignPattern/src/TemplateMode.java) - [观察者模式](/DesignPattern/src/ObserverMode.java) - [装饰器模式](/DesignPattern/src/DecoratorMode.java) ## 工具篇 - [IDEA开发的26个常用的配置](https://juejin.im/post/5e4d33abe51d4526f76eb2d3) - [全网最全frp内网穿透(ssh及web)](/Tools/frp/全网最全frp内网穿透(ssh及web).md) - [centos7安装dubbo环境](/Tools/dubbo/centos7安装dubbo环境.md) - [centos7安装rocketmq环境及配置](/Tools/rocketmq/centos7安装rocketmq及配置.md) <file_sep>## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## 面向对象和面向过程的区别 - **面向过程** :**面向过程性能比面向对象高。** 因为类调用时需要实例化,开销比较大,比较消耗资源,所以当性能是最重要的考量因素的时候,比如单片机、嵌入式开发、Linux/Unix等一般采用面向过程开发。但是,**面向过程没有面向对象易维护、易复用、易扩展。** - **面向对象** :**面向对象易维护、易复用、易扩展。** 因为面向对象有封装、继承、多态性的特性,所以可以设计出低耦合的系统,使系统更加灵活、更加易于维护。但是,**面向对象性能比面向过程低**。 > 这个并不是根本原因,面向过程也需要分配内存,计算内存偏移量,Java性能差的主要原因并不是因为它是面向对象语言,而是Java是半编译语言,最终的执行代码并不是可以直接被CPU执行的二进制机械码。 > > 而面向过程语言大多都是直接编译成机械码在电脑上执行,并且其它一些面向过程的脚本语言性能也并不一定比Java好。 ## Java 语言有哪些特点? 1. 简单易学; 2. 面向对象(封装,继承,多态); 3. 平台无关性( Java 虚拟机实现平台无关性); 4. 可靠性; 5. 安全性; 6. 支持多线程( C++ 语言没有内置的多线程机制,因此必须调用操作系统的多线程功能来进行多线程程序设计,而 Java 语言却提供了多线程支持); 7. 支持网络编程并且很方便( Java 语言诞生本身就是为简化网络编程设计的,因此 Java 语言不仅支持网络编程而且很方便); 8. 编译与解释并存; ## 关于 JVM JDK 和 JRE 最详细通俗的解答 ### JVM Java虚拟机(JVM)是运行 Java 字节码的虚拟机。JVM有针对不同系统的特定实现(Windows,Linux,macOS),目的是使用相同的字节码,它们都会给出相同的结果。 **什么是字节码?采用字节码的好处是什么?** > 在 Java 中,JVM可以理解的代码就叫做`字节码`(即扩展名为 `.class` 的文件),它不面向任何特定的处理器,只面向虚拟机。Java 语言通过字节码的方式,在一定程度上解决了传统解释型语言执行效率低的问题,同时又保留了解释型语言可移植的特点。所以 Java 程序运行时比较高效,而且,由于字节码并不针对一种特定的机器,因此,Java程序无须重新编译便可在多种不同操作系统的计算机上运行。 **Java 程序从源代码到运行一般有下面3步:** ![Java程序运行过程](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/Java%20%E7%A8%8B%E5%BA%8F%E8%BF%90%E8%A1%8C%E8%BF%87%E7%A8%8B.png) 我们需要格外注意的是 .class->机器码 这一步。在这一步 JVM 类加载器首先加载字节码文件,然后通过解释器逐行解释执行,这种方式的执行速度会相对比较慢。而且,有些方法和代码块是经常需要被调用的(也就是所谓的热点代码),所以后面引进了 JIT 编译器,而JIT 属于运行时编译。当 JIT 编译器完成第一次编译后,其会将字节码对应的机器码保存下来,下次可以直接使用。而我们知道,机器码的运行效率肯定是高于 Java 解释器的。这也解释了我们为什么经常会说 Java 是编译与解释共存的语言。 > HotSpot采用了惰性评估(Lazy Evaluation)的做法,根据二八定律,消耗大部分系统资源的只有那一小部分的代码(热点代码),而这也就是JIT所需要编译的部分。JVM会根据代码每次被执行的情况收集信息并相应地做出一些优化,因此执行的次数越多,它的速度就越快。JDK 9引入了一种新的编译模式AOT(Ahead of Time Compilation),它是直接将字节码编译成机器码,这样就避免了JIT预热等各方面的开销。JDK支持分层编译和AOT协作使用。但是 ,AOT 编译器的编译质量是肯定比不上 JIT 编译器的。 **总结:** Java虚拟机(JVM)是运行 Java 字节码的虚拟机。JVM有针对不同系统的特定实现(Windows,Linux,macOS),目的是使用相同的字节码,它们都会给出相同的结果。字节码和不同系统的 JVM 实现是 Java 语言“一次编译,随处可以运行”的关键所在。 ### JDK 和 JRE JDK是Java Development Kit,它是功能齐全的Java SDK。它拥有JRE所拥有的一切,还有编译器(javac)和工具(如javadoc和jdb)。它能够创建和编译程序。 JRE 是 Java运行时环境。它是运行已编译 Java 程序所需的所有内容的集合,包括 Java虚拟机(JVM),Java类库,java命令和其他的一些基础构件。但是,它不能用于创建新程序。 如果你只是为了运行一下 Java 程序的话,那么你只需要安装 JRE 就可以了。如果你需要进行一些 Java 编程方面的工作,那么你就需要安装JDK了。但是,这不是绝对的。有时,即使您不打算在计算机上进行任何Java开发,仍然需要安装JDK。例如,如果要使用JSP部署Web应用程序,那么从技术上讲,您只是在应用程序服务器中运行Java程序。那你为什么需要JDK呢?因为应用程序服务器会将 JSP 转换为 Java servlet,并且需要使用 JDK 来编译 servlet。 ## Java和C++的区别? 我知道很多人没学过 C++,但是面试官就是没事喜欢拿咱们 Java 和 C++ 比呀!没办法!!!就算没学过C++,也要记下来! - 都是面向对象的语言,都支持封装、继承和多态 - Java 不提供指针来直接访问内存,程序内存更加安全 - Java 的类是单继承的,C++ 支持多重继承;虽然 Java 的类不可以多继承,但是接口可以多继承。 - Java 有自动内存管理机制,不需要程序员手动释放无用内存 ## 什么是 Java 程序的主类 应用程序和小程序的主类有何不同? 一个程序中可以有多个类,但只能有一个类是主类。在 Java 应用程序中,这个主类是指包含 main()方法的类。而在 Java 小程序中,这个主类是一个继承自系统类 JApplet 或 Applet 的子类。应用程序的主类不一定要求是 public 类,但小程序的主类要求必须是 public 类。主类是 Java 程序执行的入口点。 ## Java 应用程序与小程序之间有哪些差别? 简单说应用程序是从主线程启动(也就是 `main()` 方法)。applet 小程序没有 `main()` 方法,主要是嵌在浏览器页面上运行(调用`init()`或者`run()`来启动),嵌入浏览器这点跟 flash 的小游戏类似。 ## 字符型常量和字符串常量的区别? 1. 形式上: 字符常量是单引号引起的一个字符; 字符串常量是双引号引起的若干个字符 2. 含义上: 字符常量相当于一个整型值( ASCII 值),可以参加表达式运算; 字符串常量代表一个地址值(该字符串在内存中存放位置) 3. 占内存大小 字符常量只占2个字节; 字符串常量占若干个字节(至少一个字符结束标志) (**注意: char在Java中占两个字节**) ![参考-JavaGuide](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-15/86735519.jpg) ## 构造器 Constructor 是否可被 override? 在讲继承的时候我们就知道父类的私有属性和构造方法并不能被继承,所以 Constructor 也就不能被 override(重写),但是可以 overload(重载),所以你可以看到一个类中有多个构造函数的情况。 ## 重载和重写的区别 ### 重载 发生在同一个类中,方法名必须相同,参数类型不同、个数不同、顺序不同,方法返回值和访问修饰符可以不同。 ### 重写 重写是子类对父类的允许访问的方法的实现过程进行重新编写,发生在子类中,方法名、参数列表必须相同,返回值范围小于等于父类,抛出的异常范围小于等于父类,访问修饰符范围大于等于父类。另外,如果父类方法访问修饰符为 private 则子类就不能重写该方法。**也就是说方法提供的行为改变,而方法的外貌并没有改变。** ## Java 面向对象编程三大特性: 封装 继承 多态 ### 封装 封装把一个对象的属性私有化,同时提供一些可以被外界访问的属性的方法,如果属性不想被外界访问,我们大可不必提供方法给外界访问。但是如果一个类没有提供给外界访问的方法,那么这个类也没有什么意义了。 ### 继承 继承是使用已存在的类的定义作为基础建立新类的技术,新类的定义可以增加新的数据或新的功能,也可以用父类的功能,但不能选择性地继承父类。通过使用继承我们能够非常方便地复用以前的代码。 **关于继承如下 3 点请记住:** 1. 子类拥有父类对象所有的属性和方法(包括私有属性和私有方法),但是父类中的私有属性和方法子类是无法访问,**只是拥有**。 2. 子类可以拥有自己属性和方法,即子类可以对父类进行扩展。 3. 子类可以用自己的方式实现父类的方法。(以后介绍)。 ### 多态 所谓多态就是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,即一个引用变量到底会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定。 在Java中有两种形式可以实现多态:继承(多个子类对同一方法的重写)和接口(实现接口并覆盖接口中同一方法)。 ## String StringBuffer 和 StringBuilder 的区别是什么? String 为什么是不可变的? **可变性** 简单的来说:String 类中使用 final 关键字修饰字符数组来保存字符串,`private final char value[]`,所以 String 对象是不可变的。而StringBuilder 与 StringBuffer 都继承自 AbstractStringBuilder 类,在 AbstractStringBuilder 中也是使用字符数组保存字符串`char[]value` 但是没有用 final 关键字修饰,所以这两种对象都是可变的。 **线程安全性** String 中的对象是不可变的,也就可以理解为常量,线程安全。AbstractStringBuilder 是 StringBuilder 与 StringBuffer 的公共父类,定义了一些字符串的基本操作,如 expandCapacity、append、insert、indexOf 等公共方法。StringBuffer 对方法加了同步锁或者对调用的方法加了同步锁,所以是线程安全的。StringBuilder 并没有对方法进行加同步锁,所以是非线程安全的。  **性能** 每次对 String 类型进行改变的时候,都会生成一个新的 String 对象,然后将指针指向新的 String 对象。StringBuffer 每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象并改变对象引用。相同情况下使用 StringBuilder 相比使用 StringBuffer 仅能获得 10%~15% 左右的性能提升,但却要冒多线程不安全的风险。 **对于三者使用的总结:** 1. 操作少量的数据: 适用String 2. 单线程操作字符串缓冲区下操作大量数据: 适用StringBuilder 3. 多线程操作字符串缓冲区下操作大量数据: 适用StringBuffer ## 自动装箱与拆箱 - **装箱**:将基本类型用它们对应的引用类型包装起来; - **拆箱**:将包装类型转换为基本数据类型; ## 在一个静态方法内调用一个非静态成员为什么是非法的? 由于静态方法可以不通过对象进行调用,因此在静态方法里,不能调用其他非静态变量,也不可以访问非静态变量成员。 ## 在 Java 中定义一个不做事且没有参数的构造方法的作用 Java 程序在执行子类的构造方法之前,如果没有用 `super() `来调用父类特定的构造方法,则会调用父类中“没有参数的构造方法”。因此,如果父类中只定义了有参数的构造方法,而在子类的构造方法中又没有用 `super() `来调用父类中特定的构造方法,则编译时将发生错误,因为 Java 程序在父类中找不到没有参数的构造方法可供执行。解决办法是在父类里加上一个不做事且没有参数的构造方法。 ## import java和javax有什么区别? 刚开始的时候 JavaAPI 所必需的包是 java 开头的包,javax 当时只是扩展 API 包来使用。然而随着时间的推移,javax 逐渐地扩展成为 Java API 的组成部分。但是,将扩展从 javax 包移动到 java 包确实太麻烦了,最终会破坏一堆现有的代码。因此,最终决定 javax 包将成为标准API的一部分。 ## 接口和抽象类的区别是什么? 1. 接口的方法默认是 public,所有方法在接口中不能有实现(Java 8 开始接口方法可以有默认实现),而抽象类可以有非抽象的方法。 2. 接口中除了static、final变量,不能有其他变量,而抽象类中则不一定。 3. 一个类可以实现多个接口,但只能实现一个抽象类。接口自己本身可以通过extends关键字扩展多个接口。 4. 接口方法默认修饰符是public,抽象方法可以有public、protected和default这些修饰符(抽象方法就是为了被重写所以不能使用private关键字修饰!)。 5. 从设计层面来说,抽象是对类的抽象,是一种模板设计,而接口是对行为的抽象,是一种行为的规范。 备注:在JDK8中,接口也可以定义静态方法,可以直接用接口名调用。实现类和实现是不可以调用的。如果同时实现两个接口,接口中定义了一样的默认方法,则必须重写,不然会报错。 ## 成员变量与局部变量的区别有哪些? 1. 从语法形式上看:成员变量是属于类的,而局部变量是在方法中定义的变量或是方法的参数;成员变量可以被 public,private,static 等修饰符所修饰,而局部变量不能被访问控制修饰符及 static 所修饰;但是,成员变量和局部变量都能被 final 所修饰。 2. 从变量在内存中的存储方式来看:如果成员变量是使用`static`修饰的,那么这个成员变量是属于类的,如果没有使用`static`修饰,这个成员变量是属于实例的。而对象存在于堆内存,局部变量则存在于栈内存。 3. 从变量在内存中的生存时间上看:成员变量是对象的一部分,它随着对象的创建而存在,而局部变量随着方法的调用而自动消失。 4. 成员变量如果没有被赋初值:则会自动以类型的默认值而赋值(一种情况例外:被 final 修饰的成员变量也必须显式地赋值),而局部变量则不会自动赋值。 ## 创建一个对象用什么运算符?对象实体与对象引用有何不同? new运算符,new创建对象实例(对象实例在堆内存中),对象引用指向对象实例(对象引用存放在栈内存中)。一个对象引用可以指向0个或1个对象(一根绳子可以不系气球,也可以系一个气球);一个对象可以有n个引用指向它(可以用n条绳子系住一个气球)。 ## 什么是方法的返回值?返回值在类的方法里的作用是什么? 方法的返回值是指我们获取到的某个方法体中的代码执行后产生的结果!(前提是该方法可能产生结果)。返回值的作用:接收出结果,使得它可以用于其他的操作! ## 一个类的构造方法的作用是什么? 若一个类没有声明构造方法,该程序能正确执行吗? 为什么? 主要作用是完成对类对象的初始化工作。可以执行。因为一个类即使没有声明构造方法也会有默认的不带参数的构造方法。 ## 构造方法有哪些特性? 1. 名字与类名相同。 2. 没有返回值,但不能用void声明构造函数。 3. 生成类的对象时自动执行,无需调用。 ## 静态方法和实例方法有何不同 1. 在外部调用静态方法时,可以使用"类名.方法名"的方式,也可以使用"对象名.方法名"的方式。而实例方法只有后面这种方式。也就是说,调用静态方法可以无需创建对象。 2. 静态方法在访问本类的成员时,只允许访问静态成员(即静态成员变量和静态方法),而不允许访问实例成员变量和实例方法;实例方法则无此限制。 ## 对象的相等与指向他们的引用相等,两者有什么不同? 对象的相等,比的是内存中存放的内容是否相等。而引用相等,比较的是他们指向的内存地址是否相等。 ## 在调用子类构造方法之前会先调用父类没有参数的构造方法,其目的是? 帮助子类做初始化工作。 ## == 与 equals(重要) **==** : 它的作用是判断两个对象的地址是不是相等。即,判断两个对象是不是同一个对象(基本数据类型==比较的是值,引用数据类型==比较的是内存地址)。 **equals()** : 它的作用也是判断两个对象是否相等。但它一般有两种使用情况: - 情况1:类没有覆盖 equals() 方法。则通过 equals() 比较该类的两个对象时,等价于通过“==”比较这两个对象。 - 情况2:类覆盖了 equals() 方法。一般,我们都覆盖 equals() 方法来比较两个对象的内容是否相等;若它们的内容相等,则返回 true (即,认为这两个对象相等)。 **举个例子:** ```java public class test1 { public static void main(String[] args) { String a = new String("ab"); // a 为一个引用 String b = new String("ab"); // b为另一个引用,对象的内容一样 String aa = "ab"; // 放在常量池中 String bb = "ab"; // 从常量池中查找 if (aa == bb) // true System.out.println("aa==bb"); if (a == b) // false,非同一对象 System.out.println("a==b"); if (a.equals(b)) // true System.out.println("aEQb"); if (42 == 42.0) { // true System.out.println("true"); } } } ``` **说明:** - String 中的 equals 方法是被重写过的,因为 object 的 equals 方法是比较的对象的内存地址,而 String 的 equals 方法比较的是对象的值。 - 当创建 String 类型的对象时,虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象,如果有就把它赋给当前引用。如果没有就在常量池中重新创建一个 String 对象。 ## hashCode 与 equals (重要) 面试官可能会问你:“你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?” ### hashCode()介绍 hashCode() 的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。hashCode() 定义在JDK的Object.java中,这就意味着Java中的任何类都包含有hashCode() 函数。 散列表存储的是键值对(key-value),它的特点是:能根据“键”快速的检索出对应的“值”。这其中就利用到了散列码!(可以快速找到所需要的对象) ### 为什么要有 hashCode **我们先以“HashSet 如何检查重复”为例子来说明为什么要有 hashCode:** 当你把对象加入 HashSet 时,HashSet 会先计算对象的 hashcode 值来判断对象加入的位置,同时也会与其他已经加入的对象的 hashcode 值作比较,如果没有相符的hashcode,HashSet会假设对象没有重复出现。但是如果发现有相同 hashcode 值的对象,这时会调用 `equals()`方法来检查 hashcode 相等的对象是否真的相同。如果两者相同,HashSet 就不会让其加入操作成功。如果不同的话,就会重新散列到其他位置。(摘自我的Java启蒙书《Head first java》第二版)。这样我们就大大减少了 equals 的次数,相应就大大提高了执行速度。 通过我们可以看出:`hashCode()` 的作用就是**获取哈希码**,也称为散列码;它实际上是返回一个int整数。这个**哈希码的作用**是确定该对象在哈希表中的索引位置。**`hashCode() `在散列表中才有用,在其它情况下没用**。在散列表中hashCode() 的作用是获取对象的散列码,进而确定该对象在散列表中的位置。 ### hashCode()与equals()的相关规定 1. 如果两个对象相等,则hashcode一定也是相同的 2. 两个对象相等,对两个对象分别调用equals方法都返回true 3. 两个对象有相同的hashcode值,它们也不一定是相等的 4. **因此,equals 方法被覆盖过,则 hashCode 方法也必须被覆盖** 5. hashCode() 的默认行为是对堆上的对象产生独特值。如果没有重写 hashCode(),则该 class 的两个对象无论如何都不会相等(即使这两个对象指向相同的数据) ## 为什么Java中只有值传递? - 一个方法不能修改一个基本数据类型的参数(即数值型或布尔型)。 - 一个方法可以改变一个对象参数的状态。 - 一个方法不能让对象参数引用一个新的对象。 ## 简述线程、程序、进程的基本概念。以及他们之间关系是什么? **线程**与进程相似,但线程是一个比进程更小的执行单位。一个进程在其执行的过程中可以产生多个线程。与进程不同的是同类的多个线程共享同一块内存空间和一组系统资源,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程。 **程序**是含有指令和数据的文件,被存储在磁盘或其他的数据存储设备中,也就是说程序是静态的代码。 **进程**是程序的一次执行过程,是系统运行程序的基本单位,因此进程是动态的。系统运行一个程序即是一个进程从创建,运行到消亡的过程。简单来说,一个进程就是一个执行中的程序,它在计算机中一个指令接着一个指令地执行着,同时,每个进程还占有某些系统资源如CPU时间,内存空间,文件,输入输出设备的使用权等等。换句话说,当程序在执行时,将会被操作系统载入内存中。 线程是进程划分成的更小的运行单位。线程和进程最大的不同在于基本上各进程是独立的,而各线程则不一定,因为同一进程中的线程极有可能会相互影响。从另一角度来说,进程属于操作系统的范畴,主要是同一段时间内,可以同时执行一个以上的程序,而线程则是在同一程序内几乎同时执行一个以上的程序段。 ## 关于 final 关键字的一些总结 final关键字主要用在三个地方:变量、方法、类。 1. 对于一个final变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改;如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。 2. 当用final修饰一个类时,表明这个类不能被继承。final类中的所有成员方法都会被隐式地指定为final方法。 3. 使用final方法的原因有两个。第一个原因是把方法锁定,以防任何继承类修改它的含义;第二个原因是效率。在早期的Java实现版本中,会将final方法转为内嵌调用。但是如果方法过于庞大,可能看不到内嵌调用带来的任何性能提升(现在的Java版本已经不需要使用final方法进行这些优化了)。类中所有的private方法都隐式地指定为final。 **Final修饰有啥好处** - final的关键字提高了性能,JVM和java应用会缓存final变量; - final变量可以在多线程环境下保持线程安全; - 使用final的关键字提高了性能,JVM会对方法变量类进行优化; ## Java 中的异常处理 在 Java 中,所有的异常都有一个共同的祖先java.lang包中的 **Throwable类**。Throwable: 有两个重要的子类:**Exception(异常)** 和 **Error(错误)** ,二者都是 Java 异常处理的重要子类,各自都包含大量子类。 **Error(错误):是程序无法处理的错误**,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。例如,Java虚拟机运行错误(Virtual MachineError),当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError。这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。 这些错误表示故障发生于虚拟机自身、或者发生在虚拟机试图执行应用时,如Java虚拟机运行错误(Virtual MachineError)、类定义错误(NoClassDefFoundError)等。这些错误是不可查的,因为它们在应用程序的控制和处理能力之 外,而且绝大多数是程序运行时不允许出现的状况。对于设计合理的应用程序来说,即使确实发生了错误,本质上也不应该试图去处理它所引起的异常状况。在 Java中,错误通过Error的子类描述。 **Exception(异常):是程序本身可以处理的异常**。</font>Exception 类有一个重要的子类 **RuntimeException**。RuntimeException 异常由Java虚拟机抛出。**NullPointerException**(要访问的变量没有引用任何对象时,抛出该异常)、**ArithmeticException**(算术运算异常,一个整数除以0时,抛出该异常)和 **ArrayIndexOutOfBoundsException** (下标越界异常)。 **注意:异常和错误的区别:异常能被程序本身处理,错误是无法处理。** ### Throwable类常用方法 - **public string getMessage()**:返回异常发生时的简要描述 - **public string toString()**:返回异常发生时的详细信息 - **public string getLocalizedMessage()**:返回异常对象的本地化信息。使用Throwable的子类覆盖这个方法,可以生成本地化信息。如果子类没有覆盖该方法,则该方法返回的信息与getMessage()返回的结果相同 - **public void printStackTrace()**:在控制台上打印Throwable对象封装的异常信息 ### 异常处理总结 - **try 块:** 用于捕获异常。其后可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。 - **catch 块:** 用于处理try捕获到的异常。 - **finally 块:** 无论是否捕获或处理异常,finally块里的语句都会被执行。当在try块或catch块中遇到return 语句时,finally语句块将在方法返回之前被执行。 **在以下4种特殊情况下,finally块不会被执行:** 1. 在finally语句块第一行发生了异常。 因为在其他行,finally块还是会得到执行 2. 在前面的代码中用了System.exit(int)已退出程序。 exit是带参函数 ;若该语句在异常语句之后,finally会执行 3. 程序所在的线程死亡。 4. 关闭CPU。 **注意:** 当try语句和finally语句中都有return语句时,在方法返回之前,finally语句的内容将被执行,并且finally语句的返回值将会覆盖原始的返回值。如下: ```java public static int f(int value) { try { return value * value; } finally { if (value == 2) { return 0; } } } ``` 如果调用 `f(2)`,返回值将是0,因为finally语句的返回值覆盖了try语句块的返回值。 ## Java序列化中如果有些字段不想进行序列化,怎么办? 对于不想进行序列化的变量,使用transient关键字修饰。 transient关键字的作用是:阻止实例中那些用此关键字修饰的的变量序列化;当对象被反序列化时,被transient修饰的变量值不会被持久化和恢复。transient只能修饰变量,不能修饰类和方法。 ## 获取用键盘输入常用的两种方法 方法1:通过 Scanner ```java Scanner input = new Scanner(System.in); String s = input.nextLine(); input.close(); ``` 方法2:通过 BufferedReader ```java BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s = input.readLine(); ``` ## Java 中 IO 流 ### Java 中 IO 流分为几种? - 按照流的流向分,可以分为输入流和输出流; - 按照操作单元划分,可以划分为字节流和字符流; - 按照流的角色划分为节点流和处理流。 Java Io流共涉及40多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧密的联系, Java I0流的40多个类都是从如下4个抽象类基类中派生出来的。 - InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。 - OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。 ### 既然有了字节流,为什么还要有字符流? 问题本质想问:**不管是文件读写还是网络发送接收,信息的最小存储单元都是字节,那为什么 I/O 流操作要分为字节流操作和字符流操作呢?** 回答:字符流是由 Java 虚拟机将字节转换得到的,问题就出在这个过程还算是非常耗时,并且,如果我们不知道编码类型就很容易出现乱码问题。所以, I/O 流就干脆提供了一个直接操作字符的接口,方便我们平时对字符进行流操作。如果音频文件、图片等媒体文件用字节流比较好,如果涉及到字符的话使用字符流比较好。 ### BIO,NIO,AIO 有什么区别? - **BIO (Blocking I/O):** 同步阻塞I/O模式,数据的读取写入必须阻塞在一个线程内等待其完成。在活动连接数不是特别高(小于单机1000)的情况下,这种模型是比较不错的,可以让每一个连接专注于自己的 I/O 并且编程模型简单,也不用过多考虑系统的过载、限流等问题。线程池本身就是一个天然的漏斗,可以缓冲一些系统处理不了的连接或请求。但是,当面对十万甚至百万级连接的时候,传统的 BIO 模型是无能为力的。因此,我们需要一种更高效的 I/O 处理模型来应对更高的并发量。 - **NIO (New I/O):** NIO是一种同步非阻塞的I/O模型,在Java 1.4 中引入了NIO框架,对应 java.nio 包,提供了 Channel , Selector,Buffer等抽象。NIO中的N可以理解为Non-blocking,不单纯是New。它支持面向缓冲的,基于通道的I/O操作方法。 NIO提供了与传统BIO模型中的 `Socket` 和 `ServerSocket` 相对应的 `SocketChannel` 和 `ServerSocketChannel` 两种不同的套接字通道实现,两种通道都支持阻塞和非阻塞两种模式。阻塞模式使用就像传统中的支持一样,比较简单,但是性能和可靠性都不好;非阻塞模式正好与之相反。对于低负载、低并发的应用程序,可以使用同步阻塞I/O来提升开发速率和更好的维护性;对于高负载、高并发的(网络)应用,应使用 NIO 的非阻塞模式来开发 - **AIO (Asynchronous I/O):** AIO 也就是 NIO 2。在 Java 7 中引入了 NIO 的改进版 NIO 2,它是异步非阻塞的IO模型。异步 IO 是基于事件和回调机制实现的,也就是应用操作之后会直接返回,不会堵塞在那里,当后台处理完成,操作系统会通知相应的线程进行后续的操作。AIO 是异步IO的缩写,虽然 NIO 在网络操作中,提供了非阻塞的方法,但是 NIO 的 IO 行为还是同步的。对于 NIO 来说,我们的业务线程是在 IO 操作准备好时,得到通知,接着就由这个线程自行进行 IO 操作,IO操作本身是同步的。查阅网上相关资料,我发现就目前来说 AIO 的应用还不是很广泛,Netty 之前也尝试使用过 AIO,不过又放弃了。 ## static 关键字 **static 关键字主要有以下四种使用场景:** 1. **修饰成员变量和成员方法:** 被 static 修饰的成员属于类,不属于单个这个类的某个对象,被类中所有对象共享,可以并且建议通过类名调用。被static 声明的成员变量属于静态成员变量,静态变量 存放在 Java 内存区域的方法区。调用格式:`类名.静态变量名` `类名.静态方法名()` 2. **静态代码块:** 静态代码块定义在类中方法外, 静态代码块在非静态代码块之前执行(静态代码块—>非静态代码块—>构造方法)。 该类不管创建多少对象,静态代码块只执行一次. 3. **静态内部类(static修饰类的话只能修饰内部类):** 静态内部类与非静态内部类之间存在一个最大的区别: 非静态内部类在编译完成之后会隐含地保存着一个引用,该引用是指向创建它的外围类,但是静态内部类却没有。没有这个引用就意味着:1. 它的创建是不需要依赖外围类的创建。2. 它不能使用任何外围类的非static成员变量和方法。 4. **静态导包(用来导入类中的静态资源,1.5之后的新特性):** 格式为:`import static` 这两个关键字连用可以指定导入某个类中的指定静态资源,并且不需要使用类名调用类中静态成员,可以直接使用类中静态成员变量和成员方法。 ## this 关键字 ```java class Manager { Employees[] employees; void manageEmployees() { int totalEmp = this.employees.length; System.out.println("Total employees: " + totalEmp); this.report(); } void report() { } } ``` 在上面的示例中,this关键字用于两个地方: - this.employees.length:访问类Manager的当前实例的变量。 - this.report():调用类Manager的当前实例的方法。 此关键字是可选的,这意味着如果上面的示例在不使用此关键字的情况下表现相同。 但是,使用此关键字可能会使代码更易读或易懂。 ## super 关键字 super关键字用于从子类访问父类的变量和方法。 例如: ```java public class Super { protected int number; protected showNumber() { System.out.println("number = " + number); } } public class Sub extends Super { void bar() { super.number = 10; super.showNumber(); } } ``` 在上面的例子中,Sub 类访问父类成员变量 number 并调用其其父类 Super 的 `showNumber()` 方法。 **使用 this 和 super 要注意的问题:** - 在构造器中使用 `super()` 调用父类中的其他构造方法时,该语句必须处于构造器的首行,否则编译器会报错。另外,this 调用本类中的其他构造方法时,也要放在首行。 - this、super不能用在static方法中。 **简单解释一下:** 被 static 修饰的成员属于类,不属于单个这个类的某个对象,被类中所有对象共享。而 this 代表对本类对象的引用,指向本类对象;而 super 代表对父类对象的引用,指向父类对象;所以, **this和super是属于对象范畴的东西,而静态方法是属于类范畴的东西**。 ## 深拷贝 vs 浅拷贝 1. **浅拷贝**:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝。 2. **深拷贝**:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。 ![deep and shallow copy](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/java-deep-and-shallow-copy.jpg) ## String A = "123"; String B = new String("123");生成几个对象? 我说如果常量池中,原来没有“123”那么就是生成了2个对象,如果常量池中有“123”那么只要1个对象生成 ## hashTable吗,和hashmap有啥区别? - Hashtable的方法是安全的有synchronized修饰,Hashmap是不安全的; - hashtable不可以有null值;HashMap则可以有空值; - Hashtable中数组默认大小是11,而Hashmap默认大小是16,;扩容的时候hashtable是乘以2加1,而hashmap是乘以2. ## ArrayList和LinkedList的区别? - ArrayList底层是数组,ArrayLIst查找数据快 - LinkedList底层是链表,LinkedList插入删除快; ## linkedList可以用for循环遍历吗? - 能不用尽量不要用,linkedList底层是链表,它使用for进行遍历,访问每一个元素都是从头开始访问然后直到找到这个元素, - 比如说找第三个节点,需要先找到第一个节点然后找到第二个节点; - 继续找第4个节点,不是从第三个节点开始找的,还是从第一个节点开始,所以非常的慢,不推荐,可以用迭代器进行遍历。 ## 说说&和&&的区别 - &和&&都可以用作逻辑与的运算符,表示逻辑与(and) - 当运算符两边的表达式的结果都为 true 时, 整个运算结果才为 true,否则,只要有一方为 false,则结果为 false。 - &&还具有短路的功能,即如果第一个表达式为 false,则不再计算第二个表达式 - &还可以用作位运算符,当&操作符两边的表达式不是 boolean 类型时,&表示按位与操作,我们通常 使用 0x0f 来与一个整数进行&运算,来获取该整数的最低 4 个 bit 位 ## switch语句能否作用在byte上,能否作用在long上,能否作用在String上? - switch的condition只能是一个整数表达式或者枚举常量 - 整数表达式则是int或者integet包装类型,由于,byte,short,char都可以隐式转换为int,则作用。 - long 和 String 类型都不符合 switch 的语法规定,并且不能被隐式转 换成 int 类型,所以,它们不能作用于 swtich 语句中。 ## short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1; 有什么错? - 对于 short s1 = 1; s1 = s1 + 1; 由于 s1+1 运算时会自动提升表达式的类型,所以结果是 int 型,再赋值 给 short 类型 s1 时,**编译器将报告需要强制转换类型的错误。** - 对于 short s1 = 1; s1 += 1;由于 **+= 是 java 语言规定的运算符,java 编译器会对它进行特殊处理**,因此 可以正确编译。 ## char 型变量中能不能存贮一个中文汉字?为什么? - char 型变量是用来存储 Unicode 编码的字符的,unicode 编码字符集中包含了汉字,所以,char 型变量 中当然可以存储汉字啦。 - 如果某个特殊的汉字没有被包含在 unicode 编码字符集中,那么,这个 char 型变量中就不能存储这个特殊汉字。 - unicode 编码占用两个字节,所以,char 类型的变量也是占 用两个字节。 ## 请说出作用域 public,private,protected,以及不写时 的区别 | 作用域 | 当前类 | 同package | 子孙类 | 其他package | | :-------: | :----: | :-------: | :----: | :---------: | | public | √ | √ | √ | √ | | protected | √ | √ | √ | × | | friednly | √ | √ | × | × | | private | √ | × | × | × | ## final, finally, finalize 的区别。 - final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。 内部类要访问局部变量,局部变量必须定义成 final 类型 - finally 是异常处理语句结构的一部分,表示总是执行。 - finalize 是 Object 类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法, 可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。JVM 不保证此方法总被调用 ## 请写出你最常见到的 5 个 runtime exception。 - RuntimeException 的子类 - NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException。 ## 反射 ### 反射机制介绍 **Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能成为java语言的反射机制。** ### 静态编译和动态编译 - 静态编译:在编译时确定类型,绑定对象 - 动态编译:运行时确定类型,绑定对象 ### 反射机制优缺点 - 优点:运行期间类型的判断,动态加载类,提高代码的灵活度。 - 缺点:性能瓶颈:反射相当于一系列解释操作,通知JVM要做的事情,性能比直接的java代码要慢很多。 ### 反射的应用场景 **反射是框架设计的灵魂** 在我们平时的项目开发过程中,基本上很少会直接使用的反射机制,但这不能说明反射机制没有用,实际上有很多设计、开发都与反射机制有关,例如**模块化**的开发,通过反射去调用对应的字节码;动态代理设计模型也采用了反射机制,还有我们日常使用的**Spring / Hibernate**等框架也大量使用到了反射机制。 - 我们在使用JDBC连接数据库时使用`Class.forName()`通过反射加载数据看的驱动程序; - Spring框架也用到很多反射机制,最经典的就是xml的配置模式。Spring通过XML配置模式装载Bean的过程; - 将程序内所有XML或Properties配置文件加载入内存中; - Java类里面解析xml或properties里面的内容,得到对应实体类的字节码字符串以及相关的属性信息; - 使用反射机制,根据这个字符串获得某个类的Class实例 - 动态配置实例的属性 - [反射参考(重要)](https://blog.csdn.net/sinat_38259539/article/details/71799078)<file_sep>package normal; /** * @program JavaBooks * @description: 26.删除排序数组中的重复项 * @author: mf * @create: 2019/11/03 17:10 */ /** * 题目:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ * 难度:easy * 类型:数组 */ import java.util.Arrays; /** * 题目: * 给定数组 nums = [1,1,2], * 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 * 你不需要考虑数组中超出新长度后面的元素。 */ public class RemoveDuplicates { public static void main(String[] args) { int[] arr = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; System.out.println(removeDuplicates(arr)); System.out.println(Arrays.toString(arr)); } private static int removeDuplicates(int[] arr) { int p = 0; // 符合条件指针 for (int i = 1; i < arr.length; i++) { if (arr[p] != arr[i]) { arr[++p] = arr[i]; } } return p + 1; } } <file_sep>package web; /** * @program LeetNiu * @description: 二叉搜索树的后序遍历序列 * @author: mf * @create: 2020/01/13 10:31 */ /** * 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。 * 假设输入的数组的任意两个数字都互不相同。 */ public class T23 { public boolean VerifySquenceOfBST(int [] sequence) { if (sequence == null || sequence.length == 0) return false; return isBST(sequence, 0, sequence.length - 1); } private boolean isBST(int[] seq, int start, int end) { if (start >= end) { return true; } int inx = seq[end]; int m = start; // 找到分界点 for (int i = end - 1; i >= start; i--) { if (seq[i] < inx) { m = i; break; } if (i == start) { m = -1; } } // 分界点前的数据都小于根节点 for (int i = start; i <= m; i++) { if (seq[i] > inx) return false; } // 递归 return isBST(seq, start, m) && isBST(seq, m + 1, end - 1); } } <file_sep>/** * @program JavaBooks * @description: 对称二叉树 * @author: mf * @create: 2020/03/09 13:28 */ package subject.tree; /** * 1 * / \ * 2 2 * / \ / \ * 3 4 4 3 */ public class T2 { /** * 还是前序递归 * @param root * @return */ public boolean isSymmetric(TreeNode root) { return isSym(root, root); } public boolean isSym(TreeNode root, TreeNode root1) { if (root == null && root1 == null) return true; if (root == null || root1 == null) return false; if (root.val != root1.val) return false; return isSym(root.left, root1. right) && isSym(root.right, root1.left); } } <file_sep>## 引言 > 不得不说,如果谈到volatile只会它的作用:可见性,可序性和不能保证原子性,就太Low了些,因此还得熟悉其中的奥妙才行呀... <!-- more --> ## 可见性 **volatile的可见性是指当一个变量被volatile修饰后,这个变量就对所有线程均可见。白话点就是说当一个线程修改了一个volatile修饰的变量后,其他线程可以立刻得知这个变量的修改,拿到最这个变量最新的值。** ```java public class VolatileVisibleDemo { // private boolean isReady = true; private volatile boolean isReady = true; void m() { System.out.println(Thread.currentThread().getName() + " m start..."); while (isReady) { } System.out.println(Thread.currentThread().getName() + " m end..."); } public static void main(String[] args) { VolatileVisibleDemo demo = new VolatileVisibleDemo(); new Thread(() -> demo.m(), "t1").start(); try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();} demo.isReady = false; // 刚才一秒过后开始执行 } } ``` **分析:一开始isReady为true,m方法中的while会一直循环,而主线程开启开线程之后会延迟1s将isReady赋值为false,若不加volatile修饰,则程序一直在运行,若加了volatile修饰,则程序最后会输出t1 m end...** ## 有序性 **有序性是指程序代码的执行是按照代码的实现顺序来按序执行的;volatile的有序性特性则是指禁止JVM指令重排优化。** ```java public class Singleton { private static Singleton instance = null; //private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { //第一次判断 if(instance == null) { synchronized (Singleton.class) { if(instance == null) { //初始化,并非原子操作 instance = new Singleton(); } } } return instance; } } ``` **上面的代码是一个很常见的单例模式实现方式,但是上述代码在多线程环境下是有问题的。为什么呢,问题出在instance对象的初始化上,因为`instance = new Singleton();`这个初始化操作并不是原子的,在JVM上会对应下面的几条指令:** ```java memory =allocate(); //1. 分配对象的内存空间 ctorInstance(memory); //2. 初始化对象 instance =memory; //3. 设置instance指向刚分配的内存地址 ``` **上面三个指令中,步骤2依赖步骤1,但是步骤3不依赖步骤2,所以JVM可能针对他们进行指令重拍序优化,重排后的指令如下:** ```java memory =allocate(); //1. 分配对象的内存空间 instance =memory; //3. 设置instance指向刚分配的内存地址 ctorInstance(memory); //2. 初始化对象 ``` **这样优化之后,内存的初始化被放到了instance分配内存地址的后面,这样的话当线程1执行步骤3这段赋值指令后,刚好有另外一个线程2进入getInstance方法判断instance不为null,这个时候线程2拿到的instance对应的内存其实还未初始化,这个时候拿去使用就会导致出错。** **所以我们在用这种方式实现单例模式时,会使用volatile关键字修饰instance变量,这是因为volatile关键字除了可以保证变量可见性之外,还具有防止指令重排序的作用。当用volatile修饰instance之后,JVM执行时就不会对上面提到的初始化指令进行重排序优化,这样也就不会出现多线程安全问题了。** ## 不能保证原子性 **volatile关键字能保证变量的可见性和代码的有序性,但是不能保证变量的原子性,下面我再举一个volatile与原子性的例子:** ```java public class VolatileAtomicDemo { public static volatile int count = 0; public static void increase() { count++; } public static void main(String[] args) { Thread[] threads = new Thread[20]; for(int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { for(int j = 0; j < 1000; j++) { increase(); } }); threads[i].start(); } //等待所有累加线程结束 while (Thread.activeCount() > 1) { Thread.yield(); } System.out.println(count); } } ``` **上面这段代码创建了20个线程,每个线程对变量count进行1000次自增操作,如果这段代码并发正常的话,结果应该是20000,但实际运行过程中经常会出现小于20000的结果,因为count++这个自增操作不是原子操作。**[可参照这张图](https://www.processon.com/diagraming/5e130e50e4b0c090e0b7c183) ## 内存屏障 **Java的Volatile的特征是任何读都能读到最新值,本质上是JVM通过内存屏障来实现的;为了实现volatile内存语义,JMM会分别限制重排序类型。下面是JMM针对编译器制定的volatile重排序规则表:** | 是否能重排序 | 第二个操作 | | | | :----------: | :--------: | :--------: | :--------: | | 第一个操作 | 普通读/写 | volatile读 | volatile写 | | 普通读/写 | | | no | | volatile读 | no | no | no | | volatile写 | | no | no | **从上表我们可以看出:** - 当第二个操作是volatile写时,不管第一个操作是什么,都不能重排序。这个规则确保volatile写之前的操作不会被编译器重排序到volatile写之后。 - 当第一个操作是volatile读时,不管第二个操作是什么,都不能重排序。这个规则确保volatile读之后的操作不会被编译器重排序到volatile读之前。 - 当第一个操作是volatile写,第二个操作是volatile读时,不能重排序。 **为了实现volatile的内存语义,编译器在生成字节码时,会在指令序列中插入内存屏障来禁止特定类型的处理器重排序。对于编译器来说,发现一个最优布置来最小化插入屏障的总数几乎不可能,为此,JMM采取保守策略。下面是基于保守策略的JMM内存屏障插入策略:** - 在每个volatile写操作的前面插入一个StoreStore屏障。 - 在每个volatile写操作的后面插入一个StoreLoad屏障。 - 在每个volatile读操作的后面插入一个LoadLoad屏障。 - 在每个volatile读操作的后面插入一个LoadStore屏障。 **volatile写插入内存指令图:** ![volatile](https://segmentfault.com/img/bV7PaN?w=485&h=313) **上图中的StoreStore屏障可以保证在volatile写之前,其前面的所有普通写操作已经对任意处理器可见了。这是因为StoreStore屏障将保障上面所有的普通写在volatile写之前刷新到主内存。** **这里比较有意思的是volatile写后面的StoreLoad屏障。这个屏障的作用是避免volatile写与后面可能有的volatile读/写操作重排序。因为编译器常常无法准确判断在一个volatile写的后面,是否需要插入一个StoreLoad屏障(比如,一个volatile写之后方法立即return)。为了保证能正确实现volatile的内存语义,JMM在这里采取了保守策略:在每个volatile写的后面或在每个volatile读的前面插入一个StoreLoad屏障。从整体执行效率的角度考虑,JMM选择了在每个volatile写的后面插入一个StoreLoad屏障。因为volatile写-读内存语义的常见使用模式是:一个写线程写volatile变量,多个读线程读同一个volatile变量。当读线程的数量大大超过写线程时,选择在volatile写之后插入StoreLoad屏障将带来可观的执行效率的提升。从这里我们可以看到JMM在实现上的一个特点:首先确保正确性,然后再去追求执行效率。** **volatile读插入内存指令图:** ![volatile读](https://segmentfault.com/img/bV7Pbg?w=500&h=306) **上图中的LoadLoad屏障用来禁止处理器把上面的volatile读与下面的普通读重排序。LoadStore屏障用来禁止处理器把上面的volatile读与下面的普通写重排序。** **上述volatile写和volatile读的内存屏障插入策略非常保守。在实际执行时,只要不改变volatile写-读的内存语义,编译器可以根据具体情况省略不必要的屏障。下面我们通过具体的示例代码来说明:** ```java class VolatileBarrierExample { int a; volatile int v1 = 1; volatile int v2 = 2; void readAndWrite() { int i = v1; //第一个volatile读 int j = v2; // 第二个volatile读 a = i + j; //普通写 v1 = i + 1; // 第一个volatile写 v2 = j * 2; //第二个 volatile写 } } ``` **针对readAndWrite()方法,编译器在生成字节码时可以做如下的优化:** ![readAndWrite](https://segmentfault.com/img/bV7Pbl?w=491&h=465) **注意,最后的StoreLoad屏障不能省略。因为第二个volatile写之后,方法立即return。此时编译器可能无法准确断定后面是否会有volatile读或写,为了安全起见,编译器常常会在这里插入一个StoreLoad屏障。** ### volatile汇编: ```java 0x000000011214bb49: mov %rdi,%rax 0x000000011214bb4c: dec %eax 0x000000011214bb4e: mov %eax,0x10(%rsi) 0x000000011214bb51: lock addl $0x0,(%rsp) ;*putfield v1 ; - com.earnfish.VolatileBarrierExample::readAndWrite@21 (line 35) 0x000000011214bb56: imul %edi,%ebx 0x000000011214bb59: mov %ebx,0x14(%rsi) 0x000000011214bb5c: lock addl $0x0,(%rsp) ;*putfield v2 ; - com.earnfish.VolatileBarrierExample::readAndWrite@28 (line 36) ``` **对应的Java:** ```java v1 = i - 1; // 第一个volatile写 v2 = j * i; // 第二个volatile写 ``` **可见其本质是通过一个lock指令来实现的。那么lock是什么意思呢?** **它的作用是使得本CPU的Cache写入了内存,该写入动作也会引起别的CPU invalidate其Cache。所以通过这样一个空操作,可让前面volatile变量的修改对其他CPU立即可见。** - 锁住内存 - 任何读必须在写完成之后再执行 - 使其它线程这个值的栈缓存失效 [参考volatile内存屏障](https://segmentfault.com/a/1190000014315651?utm_source=tag-newest)<file_sep>/** * @program JavaBooks * @description: String.Intern * @author: mf * @create: 2020/02/12 01:35 */ package com.strings; /** * 使用 String.intern() 可以保证相同内容的字符串变量引用同一的内存对象。 */ public class SIntern { public static void main(String[] args) { // 采用new String创建对象 String s1 = new String("aaa"); String s2 = new String("aaa"); System.out.println(s1 == s2); // false // 将s1的对象通过intern放到String Pool中 String s3 = s1.intern(); System.out.println(s1.intern() == s3); // true System.out.println(s1.intern() == s2.intern()); // true System.out.println(s3 == "aaa"); // true // 如果是采用 "bbb" 这种使用双引号的形式创建字符串实例,会自动地将新建的对象放入 String Pool 中。 String s4 = "bbb"; String s5 = "bbb"; System.out.println(s4 == s5); // true } } <file_sep>package normal; import java.util.Stack; /** * @program JavaBooks * @description: 155.最小栈 * @author: mf * @create: 2019/11/07 12:01 */ /* 题目:https://leetcode-cn.com/problems/min-stack/ 类型:栈 难度:easy */ /* MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2. */ public class MinStack { private int min = Integer.MAX_VALUE; private Stack<Integer> stack; public static void main(String[] args) { MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); System.out.println(minStack.getMin()); minStack.pop(); System.out.println(minStack.getMin()); } public MinStack() { stack = new Stack<>(); } public void push(int x) { if (min >= x) { stack.push(min); min = x; } stack.push(x); } public void pop() { if (stack.pop() == min) { min = stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return min; } } <file_sep>/** * @program JavaBooks * @description: 实现strStr() * @author: mf * @create: 2020/03/22 14:56 */ package subject.dpointer; public class T3 { public int strStr(String haystack, String needle) { int l = haystack.length(), n = needle.length(); for (int i = 0; i < l - n + 1; i++) { if (haystack.substring(i, i + n).equals(needle)) { return i; } } return -1; } } <file_sep>/** * @program JavaBooks * @description: 两个链表的第一个公共节点 * @author: mf * @create: 2020/03/08 20:41 */ package subject.linked; import java.util.HashSet; /** * */ public class T6 { /** * 最容易想的是哈希 * headA走完一圈 * 开始走headB,判断哪个节点和A相等,即可 * @param headA * @param headB * @return */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; HashSet<ListNode> set = new HashSet<>(); while (headA != null) { set.add(headA); headA = headA.next; } while (headB != null) { if (set.contains(headB)) { return headB; } headB = headB.next; } return null; } /** * 双指针 * @param headA * @param headB * @return */ public ListNode getIntersectionNode2(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; // 一男一女 ListNode node1 = headA; ListNode node2 = headB; // 我走你,你走我,直到相爱 while (node1 != node2) { node1 = node1 == null ? headB : node1.next; node2 = node2 == null ? headA : node2.next; } return node1; } } <file_sep>package normal; /** * @program JavaBooks * @description: 171. Excel表列序号 * @author: mf * @create: 2019/11/10 19:27 */ /* 题目:https://leetcode-cn.com/problems/excel-sheet-column-number/ 难度:easy */ /* A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... */ // for (int i = 0; i < n; i++) { // int value = s.charAt(i) - 'A' + 1; // value = (int) (Math.pow(26, n - i - 1)) * value; // ans += value; // } public class TitleToNumber { public static void main(String[] args) { String s = "AAB"; System.out.println(titleToNumber(s)); } public static int titleToNumber(String s) { int ans = 0; int n = s.length(); int m = 26; for (int i = 0; i < n; i++) { int value = s.charAt(i) - 'A' + 1; int k = n - i - 1; int temp = 1; while (k > 0) { temp = temp * m; k--; } ans = ans + temp * value; } return ans; } } <file_sep>## 大纲图 ![基础面试](http://media.dreamcat.ink/uPic/基础面试.png) ### 简述线程、程序、进程的基本概念。以及他们之间关系是什么? **线程**与进程相似,但线程是一个比进程更小的执行单位。一个进程在其执行的过程中可以产生多个线程。与进程不同的是同类的多个线程共享同一块内存空间和一组系统资源,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程。 **程序**是含有指令和数据的文件,被存储在磁盘或其他的数据存储设备中,也就是说程序是静态的代码。 **进程**是程序的一次执行过程,是系统运行程序的基本单位,因此进程是动态的。系统运行一个程序即是一个进程从创建,运行到消亡的过程。简单来说,一个进程就是一个执行中的程序,它在计算机中一个指令接着一个指令地执行着,同时,每个进程还占有某些系统资源如CPU时间,内存空间,文件,输入输出设备的使用权等等。换句话说,当程序在执行时,将会被操作系统载入内存中。 线程是进程划分成的更小的运行单位。线程和进程最大的不同在于基本上各进程是独立的,而各线程则不一定,因为同一进程中的线程极有可能会相互影响。从另一角度来说,进程属于操作系统的范畴,主要是同一段时间内,可以同时执行一个以上的程序,而线程则是在同一程序内几乎同时执行一个以上的程序段。 ### Java 语言有哪些特点? 1. 简单易学; 2. 面向对象(封装,继承,多态); 3. 平台无关性( Java 虚拟机实现平台无关性); 4. 可靠性; 5. 安全性; 6. 支持多线程( C++ 语言没有内置的多线程机制,因此必须调用操作系统的多线程功能来进行多线程程序设计,而 Java 语言却提供了多线程支持); 7. 支持网络编程并且很方便( Java 语言诞生本身就是为简化网络编程设计的,因此 Java 语言不仅支持网络编程而且很方便); 8. 编译与解释并存; ### 面向对象和面向过程的区别 - **面向过程** :**面向过程性能比面向对象高。** 因为类调用时需要实例化,开销比较大,比较消耗资源,所以当性能是最重要的考量因素的时候,比如单片机、嵌入式开发、Linux/Unix等一般采用面向过程开发。但是,**面向过程没有面向对象易维护、易复用、易扩展。** - **面向对象** :**面向对象易维护、易复用、易扩展。** 因为面向对象有封装、继承、多态性的特性,所以可以设计出低耦合的系统,使系统更加灵活、更加易于维护。但是,**面向对象性能比面向过程低**。 > 这个并不是根本原因,面向过程也需要分配内存,计算内存偏移量,Java性能差的主要原因并不是因为它是面向对象语言,而是Java是半编译语言,最终的执行代码并不是可以直接被CPU执行的二进制机械码。 > > 而面向过程语言大多都是直接编译成机械码在电脑上执行,并且其它一些面向过程的脚本语言性能也并不一定比Java好。 ### ==、hashcode和equals #### **==** 它的作用是判断两个对象的地址是不是相等。即,判断两个对象是不是同一个对象(基本数据类型==比较的是值,引用数据类型==比较的是内存地址)。 #### **equals()** 它的作用也是判断两个对象是否相等。但它一般有两种使用情况: - 情况1:类没有覆盖 equals() 方法。则通过 equals() 比较该类的两个对象时,等价于通过“==”比较这两个对象。 - 情况2:类覆盖了 equals() 方法。一般,我们都覆盖 equals() 方法来比较两个对象的内容是否相等;若它们的内容相等,则返回 true (即,认为这两个对象相等)。 ```java public class test1 { public static void main(String[] args) { String a = new String("ab"); // a 为一个引用 String b = new String("ab"); // b为另一个引用,对象的内容一样 String aa = "ab"; // 放在常量池中 String bb = "ab"; // 从常量池中查找 if (aa == bb) // true System.out.println("aa==bb"); if (a == b) // false,非同一对象 System.out.println("a==b"); if (a.equals(b)) // true System.out.println("aEQb"); if (42 == 42.0) { // true System.out.println("true"); } } } ``` - String 中的 equals 方法是被重写过的,因为 object 的 equals 方法是比较的对象的内存地址,而 String 的 equals 方法比较的是对象的值。 - 当创建 String 类型的对象时,虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象,如果有就把它赋给当前引用。如果没有就在常量池中重新创建一个 String 对象。 #### hashcode **hashcode:**hashCode() 的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。hashCode() 定义在JDK的Object.java中,这就意味着Java中的任何类都包含有hashCode() 函数。 散列表存储的是键值对(key-value),它的特点是:能根据“键”快速的检索出对应的“值”。这其中就利用到了散列码!(可以快速找到所需要的对象) #### 为什么要有hashcode **我们先以“HashSet 如何检查重复”为例子来说明为什么要有 hashCode:** 当你把对象加入 HashSet 时,HashSet 会先计算对象的 hashcode 值来判断对象加入的位置,同时也会与其他已经加入的对象的 hashcode 值作比较,如果没有相符的hashcode,HashSet会假设对象没有重复出现。但是如果发现有相同 hashcode 值的对象,这时会调用 `equals()`方法来检查 hashcode 相等的对象是否真的相同。如果两者相同,HashSet 就不会让其加入操作成功。如果不同的话,就会重新散列到其他位置。(摘自我的Java启蒙书《Head first java》第二版)。这样我们就大大减少了 equals 的次数,相应就大大提高了执行速度。 通过我们可以看出:`hashCode()` 的作用就是**获取哈希码**,也称为散列码;它实际上是返回一个int整数。这个**哈希码的作用**是确定该对象在哈希表中的索引位置。**`hashCode() `在散列表中才有用,在其它情况下没用**。在散列表中hashCode() 的作用是获取对象的散列码,进而确定该对象在散列表中的位置。 #### hashcode和equals的相关规定 1. 如果两个对象相等,则hashcode一定也是相同的 2. 两个对象相等,对两个对象分别调用equals方法都返回true 3. 两个对象有相同的hashcode值,它们也不一定是相等的 4. **因此,equals 方法被覆盖过,则 hashCode 方法也必须被覆盖** 5. hashCode() 的默认行为是对堆上的对象产生独特值。如果没有重写 hashCode(),则该 class 的两个对象无论如何都不会相等(即使这两个对象指向相同的数据) ### JVM JDK 和 JRE 最详细通俗的解答 #### JVM Java虚拟机(JVM)是运行 Java 字节码的虚拟机。JVM有针对不同系统的特定实现(Windows,Linux,macOS),目的是使用相同的字节码,它们都会给出相同的结果。 > 在 Java 中,JVM可以理解的代码就叫做`字节码`(即扩展名为 `.class` 的文件),它不面向任何特定的处理器,只面向虚拟机。Java 语言通过字节码的方式,在一定程度上解决了传统解释型语言执行效率低的问题,同时又保留了解释型语言可移植的特点。所以 Java 程序运行时比较高效,而且,由于字节码并不针对一种特定的机器,因此,Java程序无须重新编译便可在多种不同操作系统的计算机上运行。 #### JDK和JRE **JDK**是Java Development Kit,它是功能齐全的Java SDK。它拥有JRE所拥有的一切,还有编译器(javac)和工具(如javadoc和jdb)。它能够创建和编译程序。 **JRE** 是 Java运行时环境。它是运行已编译 Java 程序所需的所有内容的集合,包括 Java虚拟机(JVM),Java类库,java命令和其他的一些基础构件。但是,它不能用于创建新程序。 如果你只是为了运行一下 Java 程序的话,那么你只需要安装 JRE 就可以了。如果你需要进行一些 Java 编程方面的工作,那么你就需要安装JDK了。但是,这不是绝对的。有时,即使您不打算在计算机上进行任何Java开发,仍然需要安装JDK。例如,如果要使用JSP部署Web应用程序,那么从技术上讲,您只是在应用程序服务器中运行Java程序。那你为什么需要JDK呢?因为应用程序服务器会将 JSP 转换为 Java servlet,并且需要使用 JDK 来编译 servlet。 ### Java和C++的区别? - 都是面向对象的语言,都支持封装、继承和多态 - Java 不提供指针来直接访问内存,程序内存更加安全 - Java 的类是单继承的,C++ 支持多重继承;虽然 Java 的类不可以多继承,但是接口可以多继承。 - Java 有自动内存管理机制,不需要程序员手动释放无用内存 ### 基本类型 #### 字符型常量和字符串常量的区别? 1. 形式上: 字符常量是单引号引起的一个字符; 字符串常量是双引号引起的若干个字符 2. 含义上: 字符常量相当于一个整型值( ASCII 值),可以参加表达式运算; 字符串常量代表一个地址值(该字符串在内存中存放位置) 3. 占内存大小 字符常量只占2个字节; 字符串常量占若干个字节(至少一个字符结束标志) (**注意: char在Java中占两个字节**) ![](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-15/86735519.jpg) #### 自动装箱与拆箱 - **装箱**:将基本类型用它们对应的引用类型包装起来; - **拆箱**:将包装类型转换为基本数据类型; #### 说说&和&&的区别 - &和&&都可以用作逻辑与的运算符,表示逻辑与(and) - 当运算符两边的表达式的结果都为 true 时, 整个运算结果才为 true,否则,只要有一方为 false,则结果为 false。 - &&还具有短路的功能,即如果第一个表达式为 false,则不再计算第二个表达式 - &还可以用作位运算符,当&操作符两边的表达式不是 boolean 类型时,&表示按位与操作,我们通常 使用 0x0f 来与一个整数进行&运算,来获取该整数的最低 4 个 bit 位 #### short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1; 有什么错? - 对于 short s1 = 1; s1 = s1 + 1; 由于 s1+1 运算时会自动提升表达式的类型,所以结果是 int 型,再赋值 给 short 类型 s1 时,**编译器将报告需要强制转换类型的错误。** - 对于 short s1 = 1; s1 += 1;由于 **+= 是 java 语言规定的运算符,java 编译器会对它进行特殊处理**,因此 可以正确编译。 - ```java public class TypeConvert { public static void main(String[] args) { // 字面量属于 double 类型 // 不能直接将 1.1 直接赋值给 float 变量,因为这是向下转型 // Java 不能隐式执行向下转型,因为这会使得精度降低。 // float f = 1.1; float f = 1.1f; // 因为字面量 1 是 int 类型,它比 short 类型精度要高,因此不能隐式地将 int 类型下转型为 short 类型。 short s1 = 1; // s1 = s1 + 1; // 但是使用 += 运算符可以执行隐式类型转换。 s1 += 1; // 上面的语句相当于将 s1 + 1 的计算结果进行了向下转型: s1 = (short) (s1 + 1); } } ``` #### char 型变量中能不能存贮一个中文汉字?为什么? - char 型变量是用来存储 Unicode 编码的字符的,unicode 编码字符集中包含了汉字,所以,char 型变量 中当然可以存储汉字啦。 - 如果某个特殊的汉字没有被包含在 unicode 编码字符集中,那么,这个 char 型变量中就不能存储这个特殊汉字。 - unicode 编码占用两个字节,所以,char 类型的变量也是占 用两个字节。 #### 整形包装类缓存池 ```java public class IntegerPackDemo { public static void main(String[] args) { Integer x = 3; // 装箱 int z = x; // 拆箱 Integer y = 3; System.out.println(x == y); // true // ------------------------- Integer a = new Integer(3); Integer b = new Integer(3); System.out.println(a == b); // false 老生常谈了,就不说为什么了 System.out.println(a.equals.(b)); // true // 这里是用重写了equals方法,比较的是值,而不是对象的地址 // ------------------------ // 缓存池 Integer aa = Integer.valueOf(123); Integer bb = Integer.valueOf(123); System.out.println(aa == bb); // true /** * valueOf的源码 * public static Integer valueOf(int i) { * // 判断是否在Integer的范围内 * if (i >= IntegerCache.low && i <= IntegerCache.high) * return IntegerCache.cache[i + (-IntegerCache.low)]; * return new Integer(i); * } */ } } ``` **当使用自动装箱方式创建一个Integer对象时,当数值在-128 ~127时,会将创建的 Integer 对象缓存起来,当下次再出现该数值时,直接从缓存中取出对应的Integer对象。所以上述代码中,x和y引用的是相同的Integer对象。** ### 面向对象 #### Java 面向对象编程三大特性: 封装 继承 多态 ##### 封装 封装把一个对象的**属性私有化**,同时提供一些可以**被外界访问的属性的方法**,如果属性不想被外界访问,我们大可不必提供方法给外界访问。但是如果一个类没有提供给外界访问的方法,那么这个类也没有什么意义了。 ##### 继承 继承是使用**已存在的类**的定义作为基础建立新类的技术,新类的定义可以增加**新的数据**或**新的功能**,也可以用**父类的功能**,但不**能选择性地继承父类**。通过使用继承我们能够非常方便地复用以前的代码。 **关于继承如下 3 点请记住:** 1. 子类拥有父类对象所有的属性和方法(包括私有属性和私有方法),但是父类中的私有属性和方法子类是无法访问,**只是拥有**。 2. 子类可以拥有自己属性和方法,即子类可以对父类进行扩展。 3. 子类可以用自己的方式实现父类的方法。(以后介绍)。 ##### 多态 所谓多态就是指程序中定义的**引用变量所指向的具体类型**和**通过该引用变量发出的方法**调用在编程时**并不确定**,而是在程序**运行期间才确定**,即一个引用变量到底会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定。 在Java中有两种形式可以实现多态:继承(多个子类对同一方法的重写)和接口(实现接口并覆盖接口中同一方法)。 #### 构造器 Constructor 是否可被 override? 在讲继承的时候我们就知道父类的私有属性和构造方法并不能被继承,所以 Constructor 也就不能被 override(重写),但是可以 overload(重载),所以你可以看到一个类中有多个构造函数的情况。 #### 构造方法有哪些特性 1. 名字与类名相同。 2. 没有返回值,但不能用void声明构造函数。 3. 生成类的对象时自动执行,无需调用。 #### 接口和抽象类的区别是什么? 1. 接口的方法默认是 public,所有方法在接口中不能有实现(Java 8 开始接口方法可以有默认实现),而抽象类可以有非抽象的方法。 2. 接口中除了static、final变量,不能有其他变量,而抽象类中则不一定。 3. 一个类可以实现多个接口,但只能实现一个抽象类。接口自己本身可以通过implement关键字扩展多个接口。 4. 接口方法默认修饰符是public,抽象方法可以有public、protected和default这些修饰符(抽象方法就是为了被重写所以不能使用private关键字修饰!)。 5. 从设计层面来说,抽象是对类的抽象,是一种模板设计,而接口是对行为的抽象,是一种行为的规范。 备注:在JDK8中,接口也可以定义静态方法,可以直接用接口名调用。实现类和实现是不可以调用的。如果同时实现两个接口,接口中定义了一样的默认方法,则必须重写,不然会报错。 #### 成员变量与局部变量的区别有哪些? 1. 从语法形式上看:成员变量是属于类的,而局部变量是在方法中定义的变量或是方法的参数;成员变量可以被 public,private,static 等修饰符所修饰,而局部变量不能被访问控制修饰符及 static 所修饰;但是,成员变量和局部变量都能被 final 所修饰。 2. 从变量在内存中的存储方式来看:如果成员变量是使用`static`修饰的,那么这个成员变量是属于类的,如果没有使用`static`修饰,这个成员变量是属于实例的。而对象存在于堆内存,局部变量则存在于栈内存。 3. 从变量在内存中的生存时间上看:成员变量是对象的一部分,它随着对象的创建而存在,而局部变量随着方法的调用而自动消失。 4. 成员变量如果没有被赋初值:则会自动以类型的默认值而赋值(一种情况例外:被 final 修饰的成员变量也必须显式地赋值),而局部变量则不会自动赋值。 #### 重载和重写的区别 ##### 重载 发生在同一个类中,方法名必须相同,参数类型不同、个数不同、顺序不同,方法返回值和访问修饰符可以不同。 ##### 重写 重写是子类对父类的允许访问的方法的实现过程进行重新编写,发生在子类中,方法名、参数列表必须相同,返回值范围小于等于父类,抛出的异常范围小于等于父类,访问修饰符范围大于等于父类。另外,如果父类方法访问修饰符为 private 则子类就不能重写该方法。**也就是说方法提供的行为改变,而方法的外貌并没有改变。** #### 创建一个对象用什么运算符?对象实体与对象引用有何不同? new运算符,new创建对象实例(对象实例在堆内存中),对象引用指向对象实例(对象引用存放在栈内存中)。一个对象引用可以指向0个或1个对象(一根绳子可以不系气球,也可以系一个气球);一个对象可以有n个引用指向它(可以用n条绳子系住一个气球)。 #### 对象的相等与指向他们的引用相等,两者有什么不同? 对象的相等,比的是内存中存放的内容是否相等。而引用相等,比较的是他们指向的内存地址是否相等。 ### Java值传递 **按值调用(call by value)表示方法接收的是调用者提供的值,而按引用调用(call by reference)表示方法接收的是调用者提供的变量地址。一个方法可以修改传递引用所对应的变量值,而不能修改传递值调用所对应的变量值。** 接下来三个例子瞧一瞧: 基本类型传递 ```java public static void main(String[] args) { int num1 = 10; int num2 = 20; swap(num1, num2); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; System.out.println("a = " + a); System.out.println("b = " + b); } // a = 20 // b = 10 // num1 = 10 // num2 = 20 ``` ![基本类型传递](http://media.dreamcat.ink/uPic/基本类型传递%20.png) 在 swap 方法中,a、b 的值进行交换,并不会影响到 num1、num2。因为,a、b 中的值,只是从 num1、num2 的复制过来的。也就是说,a、b 相当于 num1、num2 的副本,副本的内容无论怎么修改,都不会影响到原件本身。 接下来看数组: ```java public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; System.out.println(arr[0]); change(arr); System.out.println(arr[0]); // 法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象。 } private static void change(int[] array) { // 修改数组中的一个元素 array[0] = 0; } // 1 // 0 ``` ![数组类型传递](http://media.dreamcat.ink/uPic/数组类型传递.png) array 被初始化 arr 的拷贝也就是一个对象的引用,也就是说 array 和 arr 指向的是同一个数组对象。 因此,外部对引用对象的改变会反映到所对应的对象上。 **通过 example2 我们已经看到,实现一个改变对象参数状态的方法并不是一件难事。理由很简单,方法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象。** 再看对象引用例子: ```java public static void main(String[] args) { // 有些程序员(甚至本书的作者)认为 Java 程序设计语言对对象采用的是引用调用,实际上,这种理解是不对的。 Student s1 = new Student("Mai"); Student s2 = new Student("Feng"); swap2(s1, s2); System.out.println("s1:" + s1.getName()); System.out.println("s2:" + s2.getName()); // 方法并没有改变存储在变量 s1 和 s2 中的对象引用。 // swap 方法的参数 x 和 y 被初始化为两个对象引用的拷贝,这个方法交换的是这两个拷贝 } private static void swap2(Student x, Student y) { Student temp = x; x = y; y = temp; System.out.println("x:" + x.getName()); System.out.println("y:" + y.getName()); } // x:Feng // y:Mai // s1:Mai // s2:Feng ``` ![对象引用传递](http://media.dreamcat.ink/uPic/对象引用传递.png) **方法并没有改变存储在变量 s1 和 s2 中的对象引用。swap 方法的参数 x 和 y 被初始化为两个对象引用的拷贝,这个方法交换的是这两个拷贝** 下面再总结一下 Java 中方法参数的使用情况: - 一个方法不能修改一个基本数据类型的参数(即数值型或布尔型)。 - 一个方法可以改变一个对象参数的状态。 - 一个方法不能让对象参数引用一个新的对象。 ### String #### String StringBuffer 和 StringBuilder 的区别是什么? String 为什么是不可变的? ##### **可变性** 简单的来说:String 类中使用 final 关键字修饰字符数组来保存字符串,`private final char value[]`,所以 String 对象是不可变的。而StringBuilder 与 StringBuffer 都继承自 AbstractStringBuilder 类,在 AbstractStringBuilder 中也是使用字符数组保存字符串`char[]value` 但是没有用 final 关键字修饰,所以这两种对象都是可变的。 ##### **线程安全性** String 中的对象是不可变的,也就可以理解为常量,线程安全。AbstractStringBuilder 是 StringBuilder 与 StringBuffer 的公共父类,定义了一些字符串的基本操作,如 expandCapacity、append、insert、indexOf 等公共方法。StringBuffer 对方法加了同步锁或者对调用的方法加了同步锁,所以是线程安全的。StringBuilder 并没有对方法进行加同步锁,所以是非线程安全的。 ##### **性能** 每次对 String 类型进行改变的时候,都会生成一个新的 String 对象,然后将指针指向新的 String 对象。StringBuffer 每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象并改变对象引用。相同情况下使用 StringBuilder 相比使用 StringBuffer 仅能获得 10%~15% 左右的性能提升,但却要冒多线程不安全的风险。 ##### **对于三者使用的总结:** 1. 操作少量的数据: 适用String 2. 单线程操作字符串缓冲区下操作大量数据: 适用StringBuilder 3. 多线程操作字符串缓冲区下操作大量数据: 适用StringBuffer ##### 代码例子 ```java public static void main(String[] args) { // String String str = "hello"; long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { str += i; // 创建多少个对象,, } System.out.println("String: " + (System.currentTimeMillis() - start)); // StringBuffer StringBuffer sb = new StringBuffer("hello"); long start1 = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { sb.append(i); } System.out.println("StringBuffer: " + (System.currentTimeMillis() - start1)); // StringBuilder StringBuilder stringBuilder = new StringBuilder("hello"); long start2 = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { stringBuilder.append(i); } System.out.println("StringBuilder: " + (System.currentTimeMillis() - start2)); } ``` #### String A = "123"; String B = new String("123");生成几个对象? 如果常量池中,原来没有“123”那么就是生成了2个对象,如果常量池中有“123”那么只要1个对象生成 #### 聊一聊String.intern()这个方法 ```java public class StringTest { public static void main(String[] args) { String str1 = "todo"; String str2 = "todo"; String str3 = "to"; String str4 = "do"; String str5 = str3 + str4; String str6 = new String(str1); System.out.println("------普通String测试结果------"); System.out.print("str1 == str2 ? "); System.out.println( str1 == str2); System.out.print("str1 == str5 ? "); System.out.println(str1 == str5); System.out.print("str1 == str6 ? "); System.out.print(str1 == str6); System.out.println(); System.out.println("---------intern测试结果---------"); System.out.print("str1.intern() == str2.intern() ? "); System.out.println(str1.intern() == str2.intern()); System.out.print("str1.intern() == str5.intern() ? "); System.out.println(str1.intern() == str5.intern()); System.out.print("str1.intern() == str6.intern() ? "); System.out.println(str1.intern() == str6.intern()); System.out.print("str1 == str6.intern() ? "); System.out.println(str1 == str6.intern()); } } ``` 运行结果: ```java ------普通String测试结果------ str1 == str2 ? true str1 == str5 ? false str1 == str6 ? false ---------intern测试结果--------- str1.intern() == str2.intern() ? true str1.intern() == str5.intern() ? true str1.intern() == str6.intern() ? true str1 == str6.intern() ? true ``` 普通String代码结果分析: Java语言会使用常量池保存那些在编译期就已确定的已编译的class文件中的一份数据。主要有类、接口、方法中的常量,以及一些以文本形式出现的符号引用,如类和接口的全限定名、字段的名称和描述符、方法和名称和描述符等。因此在编译完Intern类后,生成的class文件中会在常量池中**保存“todo”、“to”和“do”三个String常量**。**变量str1和str2均保存的是常量池中“todo”的引用,所以str1==str2成立**;在执行 str5 = str3 + str4这句时,JVM会先创建一个**StringBuilder对象**,通过StringBuilder.append()方法将str3与str4的值拼接,然后通过StringBuilder.toString()返回一个**堆中的String对象的引用**,赋值给str5,因此str1和str5指向的不是同一个String对象,str1 == str5不成立;String str6 = new String(str1)一句显式创建了一个新的String对象,因此str1 == str6不成立便是显而易见的事了。 intern代码结果分析: String.intern()是一个Native方法,底层调用C++的 StringTable::intern方法实现。当通过语句str.intern()调用intern()方法后,JVM 就会在当前类的常量池中查找是否存在与str等值的String,**若存在则直接返回常量池中相应Strnig的引用**;**若不存在,则会在常量池中创建一个等值的String,然后返回这个String在常量池中的引用**。因此,只要是等值的String对象,使用intern()方法返回的都是常量池中同一个String引用,所以,这些等值的String对象通过intern()后使用==是可以匹配的。由此就可以理解上面代码中------intern------部分的结果了。因为str1、str5和str6是三个等值的String,所以通过intern()方法,他们均会指向常量池中的同一个String引用,因此str1.intern() == str5.intern() == str6.intern()均为true。 ##### jdk6 Jdk6中常量池位于PermGen(永久代)中,PermGen是一块主要用于存放已加载的类信息和字符串池的大小固定的区域。执行intern()方法时,**若常量池中不存在等值的字符串,JVM就会在常量池中创建一个等值的字符串,然后返回该字符串的引用**。除此以外,JVM 会自动在常量池中保存一份之前已使用过的字符串集合。Jdk6中使用intern()方法的主要问题就在于常量池被保存在PermGen中:首先,PermGen是一块大小固定的区域,一般不同的平台PermGen的默认大小也不相同,大致在32M到96M之间。所以不能对不受控制的运行时字符串(如用户输入信息等)使用intern()方法,否则很有可能会引发PermGen内存溢出;其次String对象保存在Java堆区,Java堆区与PermGen是物理隔离的,因此如果对多个不等值的字符串对象执行intern操作,则会导致内存中存在许多重复的字符串,会造成性能损失。 ##### jdk7 Jdk7**将常量池从PermGen区移到了Java堆区**,执行intern操作时,**如果常量池已经存在该字符串,则直接返回字符串引用**,否则**复制该字符串对象的引用**到常量池中并返回。堆区的大小一般不受限,所以将常量池从PremGen区移到堆区使得常量池的使用不再受限于固定大小。除此之外,位于堆区的常量池中的对象可以被垃圾回收。当常量池中的字符串不再存在指向它的引用时,JVM就会回收该字符串。可以使用 -XX:StringTableSize 虚拟机参数设置字符串池的map大小。字符串池内部实现为一个HashMap,所以当能够确定程序中需要intern的字符串数目时,可以将该map的size设置为所需数目*2(减少hash冲突),这样就可以使得String.intern()每次都只需要常量时间和相当小的内存就能够将一个String存入字符串池中。 ##### 适用场景 Jdk6中常量池位于PermGen区,大小受限,所以不建议适用intern()方法,当需要字符串池时,需要自己使用HashMap实现。Jdk7、8中,常量池由PermGen区移到了堆区,还可以通过-XX:StringTableSize参数设置StringTable的大小,常量池的使用不再受限,由此可以重新考虑使用intern()方法。intern()方法优点:执行速度非常快,直接使用==进行比较要比使用equals()方法快很多;内存占用少。虽然intern()方法的优点看上去很诱人,但若不是在恰当的场合中使用该方法的话,便非但不能获得如此好处,反而还可能会有性能损失。 ### 关键字 #### final final关键字主要用在三个地方:变量、方法、类。 1. 对于一个final变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改;如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。 2. 当用final修饰一个类时,表明这个类不能被继承。final类中的所有成员方法都会被隐式地指定为final方法。 3. 使用final方法的原因有两个。第一个原因是把方法锁定,以防任何继承类修改它的含义;第二个原因是效率。在早期的Java实现版本中,会将final方法转为内嵌调用。但是如果方法过于庞大,可能看不到内嵌调用带来的任何性能提升(现在的Java版本已经不需要使用final方法进行这些优化了)。类中所有的private方法都隐式地指定为final。 final修饰有啥好处 - final的关键字提高了性能,JVM和java应用会缓存final变量; - final变量可以在多线程环境下保持线程安全; - 使用final的关键字提高了性能,JVM会对方法变量类进行优化; #### static 1. **修饰成员变量和成员方法:** 被 static 修饰的成员属于类,不属于单个这个类的某个对象,被类中所有对象共享,可以并且建议通过类名调用。被static 声明的成员变量属于静态成员变量,静态变量 存放在 Java 内存区域的方法区。调用格式:`类名.静态变量名` `类名.静态方法名()` 2. **静态代码块:** 静态代码块定义在类中方法外, 静态代码块在非静态代码块之前执行(静态代码块—>非静态代码块—>构造方法)。 该类不管创建多少对象,静态代码块只执行一次. 3. **静态内部类(static修饰类的话只能修饰内部类):** 静态内部类与非静态内部类之间存在一个最大的区别: 非静态内部类在编译完成之后会隐含地保存着一个引用,该引用是指向创建它的外围类,但是静态内部类却没有。没有这个引用就意味着:1. 它的创建是不需要依赖外围类的创建。2. 它不能使用任何外围类的非static成员变量和方法。 4. **静态导包(用来导入类中的静态资源,1.5之后的新特性):** 格式为:`import static` 这两个关键字连用可以指定导入某个类中的指定静态资源,并且不需要使用类名调用类中静态成员,可以直接使用类中静态成员变量和成员方法。 #### this ```java class Manager { Employees[] employees; void manageEmployees() { int totalEmp = this.employees.length; System.out.println("Total employees: " + totalEmp); this.report(); } void report() { } } ``` 在上面的示例中,this关键字用于两个地方: - this.employees.length:访问类Manager的当前实例的变量。 - this.report():调用类Manager的当前实例的方法。 此关键字是可选的,这意味着如果上面的示例在不使用此关键字的情况下表现相同。 但是,使用此关键字可能会使代码更易读或易懂。 #### super ```java public class Super { protected int number; protected showNumber() { System.out.println("number = " + number); } } public class Sub extends Super { void bar() { super.number = 10; super.showNumber(); } } ``` 在上面的例子中,Sub 类访问父类成员变量 number 并调用其其父类 Super 的 `showNumber()` 方法。 **使用 this 和 super 要注意的问题:** - 在构造器中使用 `super()` 调用父类中的其他构造方法时,该语句必须处于构造器的首行,否则编译器会报错。另外,this 调用本类中的其他构造方法时,也要放在首行。 - this、super不能用在static方法中。 **简单解释一下:** 被 static 修饰的成员属于类,不属于单个这个类的某个对象,被类中所有对象共享。而 this 代表对本类对象的引用,指向本类对象;而 super 代表对父类对象的引用,指向父类对象;所以, **this和super是属于对象范畴的东西,而静态方法是属于类范畴的东西**。 #### final, finally, finalize 的区别 - final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。 内部类要访问局部变量,局部变量必须定义成 final 类型 - finally 是异常处理语句结构的一部分,表示总是执行。 - finalize 是 Object 类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法, 可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。JVM 不保证此方法总被调用 #### 请说出作用域 public,private,protected | 作用域 | 当前类 | 同package | 子孙类 | 其他package | | :-------: | :----: | :-------: | :----: | :---------: | | public | √ | √ | √ | √ | | protected | √ | √ | √ | × | | friednly | √ | √ | × | × | | private | √ | × | × | × | ### 异常处理 在 Java 中,所有的异常都有一个共同的祖先java.lang包中的 **Throwable类**。Throwable: 有两个重要的子类:**Exception(异常)** 和 **Error(错误)** ,二者都是 Java 异常处理的重要子类,各自都包含大量子类。 #### Error **是程序无法处理的错误**,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。例如,Java虚拟机运行错误(Virtual MachineError),当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError。这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。 这些错误表示故障发生于虚拟机自身、或者发生在虚拟机试图执行应用时,如Java虚拟机运行错误(Virtual MachineError)、类定义错误(NoClassDefFoundError)等。这些错误是不可查的,因为它们在应用程序的控制和处理能力之 外,而且绝大多数是程序运行时不允许出现的状况。对于设计合理的应用程序来说,即使确实发生了错误,本质上也不应该试图去处理它所引起的异常状况。在 Java中,错误通过Error的子类描述。 #### Exception **是程序本身可以处理的异常**。Exception 类有一个重要的子类 **RuntimeException**。RuntimeException 异常由Java虚拟机抛出。**NullPointerException**(要访问的变量没有引用任何对象时,抛出该异常)、**ArithmeticException**(算术运算异常,一个整数除以0时,抛出该异常)和 **ArrayIndexOutOfBoundsException** (下标越界异常)。 #### 处理 - **try 块:** 用于捕获异常。其后可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。 - **catch 块:** 用于处理try捕获到的异常。 - **finally 块:** 无论是否捕获或处理异常,finally块里的语句都会被执行。当在try块或catch块中遇到return 语句时,finally语句块将在方法返回之前被执行。 **在以下4种特殊情况下,finally块不会被执行:** 1. 在finally语句块第一行发生了异常。 因为在其他行,finally块还是会得到执行 2. 在前面的代码中用了System.exit(int)已退出程序。 exit是带参函数 ;若该语句在异常语句之后,finally会执行 3. 程序所在的线程死亡。 4. 关闭CPU。 **注意:** 当try语句和finally语句中都有return语句时,在方法返回之前,finally语句的内容将被执行,并且finally语句的返回值将会覆盖原始的返回值。如下: ```java public static int f(int value) { try { return value * value; } finally { if (value == 2) { return 0; } } } ``` 如果调用 `f(2)`,返回值将是0,因为finally语句的返回值覆盖了try语句块的返回值。 #### 最常见到的 5 个 runtime exception - RuntimeException - NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException。 #### Throwable图解 ![异常分类](http://media.dreamcat.ink/uPic/异常分类.png) ### IO #### 获取用键盘输入常用的两种方法 方法1:通过 Scanner ```java Scanner input = new Scanner(System.in); String s = input.nextLine(); input.close(); ``` 方法2:通过 BufferedReader ```java BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s = input.readLine(); ``` #### Java 中 IO 流分为几种? - 按照流的流向分,可以分为输入流和输出流; - 按照操作单元划分,可以划分为字节流和字符流; - 按照流的角色划分为节点流和处理流。 Java Io流共涉及40多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧密的联系, Java I0流的40多个类都是从如下4个抽象类基类中派生出来的。 - InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。 - OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。 #### 既然有了字节流,为什么还要有字符流? 问题本质想问:**不管是文件读写还是网络发送接收,信息的最小存储单元都是字节,那为什么 I/O 流操作要分为字节流操作和字符流操作呢?** 回答:字符流是由 Java 虚拟机将字节转换得到的,问题就出在这个过程还算是非常耗时,并且,如果我们不知道编码类型就很容易出现乱码问题。所以, I/O 流就干脆提供了一个直接操作字符的接口,方便我们平时对字符进行流操作。如果音频文件、图片等媒体文件用字节流比较好,如果涉及到字符的话使用字符流比较好。 #### BIO,NIO,AIO 有什么区别? - **BIO (Blocking I/O):** 同步阻塞I/O模式,数据的读取写入必须阻塞在一个线程内等待其完成。在活动连接数不是特别高(小于单机1000)的情况下,这种模型是比较不错的,可以让每一个连接专注于自己的 I/O 并且编程模型简单,也不用过多考虑系统的过载、限流等问题。线程池本身就是一个天然的漏斗,可以缓冲一些系统处理不了的连接或请求。但是,当面对十万甚至百万级连接的时候,传统的 BIO 模型是无能为力的。因此,我们需要一种更高效的 I/O 处理模型来应对更高的并发量。 - **NIO (New I/O):** NIO是一种同步非阻塞的I/O模型,在Java 1.4 中引入了NIO框架,对应 java.nio 包,提供了 Channel , Selector,Buffer等抽象。NIO中的N可以理解为Non-blocking,不单纯是New。它支持面向缓冲的,基于通道的I/O操作方法。 NIO提供了与传统BIO模型中的 `Socket` 和 `ServerSocket` 相对应的 `SocketChannel` 和 `ServerSocketChannel` 两种不同的套接字通道实现,两种通道都支持阻塞和非阻塞两种模式。阻塞模式使用就像传统中的支持一样,比较简单,但是性能和可靠性都不好;非阻塞模式正好与之相反。对于低负载、低并发的应用程序,可以使用同步阻塞I/O来提升开发速率和更好的维护性;对于高负载、高并发的(网络)应用,应使用 NIO 的非阻塞模式来开发 - **AIO (Asynchronous I/O):** AIO 也就是 NIO 2。在 Java 7 中引入了 NIO 的改进版 NIO 2,它是异步非阻塞的IO模型。异步 IO 是基于事件和回调机制实现的,也就是应用操作之后会直接返回,不会堵塞在那里,当后台处理完成,操作系统会通知相应的线程进行后续的操作。AIO 是异步IO的缩写,虽然 NIO 在网络操作中,提供了非阻塞的方法,但是 NIO 的 IO 行为还是同步的。对于 NIO 来说,我们的业务线程是在 IO 操作准备好时,得到通知,接着就由这个线程自行进行 IO 操作,IO操作本身是同步的。查阅网上相关资料,我发现就目前来说 AIO 的应用还不是很广泛,Netty 之前也尝试使用过 AIO,不过又放弃了。 ### 反射 #### 反射式什么? **Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能成为java语言的反射机制。** #### 静态编译和动态编译 - 静态编译:在编译时确定类型,绑定对象 - 动态编译:运行时确定类型,绑定对象 #### 反射机制优缺点 - 优点:运行期间类型的判断,动态加载类,提高代码的灵活度。 - 缺点:性能瓶颈:反射相当于一系列解释操作,通知JVM要做的事情,性能比直接的java代码要慢很多。 #### 反射的应用场景 在我们平时的项目开发过程中,基本上很少会直接使用的反射机制,但这不能说明反射机制没有用,实际上有很多设计、开发都与反射机制有关,例如**模块化**的开发,通过反射去调用对应的字节码;动态代理设计模型也采用了反射机制,还有我们日常使用的**Spring / Hibernate**等框架也大量使用到了反射机制。 - 我们在使用JDBC连接数据库时使用`Class.forName()`通过反射加载数据看的驱动程序; - Spring框架也用到很多反射机制,最经典的就是xml的配置模式。Spring通过XML配置模式装载Bean的过程; - 将程序内所有XML或Properties配置文件加载入内存中; - Java类里面解析xml或properties里面的内容,得到对应实体类的字节码字符串以及相关的属性信息; - 使用反射机制,根据这个字符串获得某个类的Class实例 - 动态配置实例的属性 #### 反射得到的Class对象的三种方式 ```java public class ReflectDemo { public static void main(String[] args) throws ClassNotFoundException { // 第一种方式获取Class对象 Student student = new Student(); // 这一new 产生一个Student对象,一个Class对象。 Class studentClass = student.getClass(); System.out.println(studentClass.getName()); // com.reflect.Student // 第二种方式获取Class对象 Class studentClass2 = Student.class; System.out.println(studentClass == studentClass2); //判断第一种方式获取的Class对象和第二种方式获取的是否是同一个 //第三种方式获取Class对象 Class studentClass3 = Class.forName("com.reflect.Student"); //注意此字符串必须是真实路径,就是带包名的类路径,包名.类名 System.out.println(studentClass3 == studentClass2); // //判断三种方式是否获取的是同一个Class对象 // 三种方式常用第三种,第一种对象都有了还要反射干什么。 // 第二种需要导入类的包,依赖太强,不导包就抛编译错误。 // 一般都第三种,一个字符串可以传入也可写在配置文件中等多种方法。 } } ``` #### 反射访问并调用构造方法 ```java public class ConstructorsDemo { public static void main(String[] args) throws Exception { // 1. 加载Class对象 Class clazz = Class.forName("com.reflect.Student"); // 2. 获取所有公有构造方法 System.out.println("**********************所有公有构造方法*********************************"); Constructor[] constructors = clazz.getConstructors(); for (Constructor constructor : constructors) { System.out.println(constructor); } // 3. System.out.println("************所有的构造方法(包括:私有、受保护、默认、公有)***************"); Constructor[] declaredConstructors = clazz.getDeclaredConstructors(); for (Constructor declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); } // 4. System.out.println("*****************获取公有、无参的构造方法*******************************"); Constructor constructor = clazz.getConstructor(); System.out.println(constructor); // 调用构造方法 Object object = constructor.newInstance(); System.out.println(object); // System.out.println("******************获取私有构造方法,并调用*******************************"); Constructor constructor1 = clazz.getDeclaredConstructor(char.class); System.out.println(constructor1); // 调用构造方法 constructor1.setAccessible(true); // 暴力访问 Object object2 = constructor1.newInstance('买'); System.out.println(object2); } } ``` #### 反射访问并调用成员变量 ```java public class FieldDemo { public static void main(String[] args) throws Exception { // 1. 获取class对象 Class clazz = Class.forName("com.reflect.Student"); // 2. 获取所有字段 System.out.println("************获取所有公有的字段********************"); Field[] fields = clazz.getFields(); for (Field field : fields) { System.out.println(field); } // System.out.println("************获取所有的字段(包括私有、受保护、默认的)********************"); Field[] fields1 = clazz.getDeclaredFields(); for (Field field : fields1) { System.out.println(field); } // System.out.println("*************获取公有字段**并调用***********************************"); Field gender = clazz.getField("gender"); System.out.println(gender); // 获取一个对象 Object o = clazz.getConstructor().newInstance(); gender.set(o, "男"); Student stu = (Student) o; System.out.println("验证性别:" + stu.getGender()); // System.out.println("*************获取公有字段**并调用***********************************"); Field name = clazz.getDeclaredField("name"); System.out.println(name); name.setAccessible(true); //暴力反射,解除私有限定 name.set(o, "买"); System.out.println("验证姓名:" + stu); } } ``` #### 反射访问并调用成员方法 ```java public class MethodDemo { public static void main(String[] args) throws Exception { // 1. 获取对象 Class clazz = Class.forName("com.reflect.Student"); // 2. 获取所有公有方法 System.out.println("***************获取所有的”公有“方法*******************"); Method[] methods = clazz.getMethods(); for (Method method : methods) { System.out.println(method); } System.out.println("***************获取所有的方法,包括私有的*******************"); Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { System.out.println(declaredMethod); } System.out.println("***************获取公有的show1()方法*******************"); Method m = clazz.getMethod("show1", String.class); System.out.println(m); // 实例化对象 Object o = clazz.getConstructor().newInstance(); m.invoke(o, "买"); System.out.println("***************获取私有的show4()方法******************"); m = clazz.getDeclaredMethod("show4", int.class); System.out.println(m); m.setAccessible(true); // 暴力解除 私有 Object result = m.invoke(o, 20);//需要两个参数,一个是要调用的对象(获取有反射),一个是实参 System.out.println("返回值:" + result); } } ``` ### 深拷贝VS浅拷贝 1. **浅拷贝**:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝。 2. **深拷贝**:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。 ![deep and shallow copy](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/java-deep-and-shallow-copy.jpg) #### 浅拷贝例子 ```java public class ShallowCopyDemo { public static void main(String[] args) throws CloneNotSupportedException { // 原始对象 Student student = new Student(new Subject("买"), "峰"); System.out.println("原始对象: " + student.getName() + " - " + student.getSubject().getName()); // 拷贝对象 Student cloneStu = (Student) student.clone(); System.out.println("拷贝对象: " + cloneStu.getName() + " - " + cloneStu.getSubject().getName()); // 原始对象和拷贝对象是否一样: System.out.println("原始对象和拷贝对象是否一样: " + (student == cloneStu)); // 原始对象和拷贝对象的name属性是否一样 System.out.println("原始对象和拷贝对象的name属性是否一样: " + (student.getName() == cloneStu.getName())); // 原始对象和拷贝对象的subj属性是否一样 System.out.println("原始对象和拷贝对象的subj属性是否一样: " + (student.getSubject() == cloneStu.getSubject())); student.setName("小"); student.getSubject().setName("疯"); System.out.println("更新后的原始对象: " + student.getName() + " - " + student.getSubject().getName()); System.out.println("更新原始对象后的克隆对象: " + cloneStu.getName() + " - " + cloneStu.getSubject().getName()); // 在这个例子中,让要拷贝的类Student实现了Clonable接口并重写Object类的clone()方法,然后在方法内部调用super.clone()方法。 // 从输出结果中我们可以看到,对原始对象stud的"name"属性所做的改变并没有影响到拷贝对象clonedStud; // 但是对引用对象subj的"name"属性所做的改变影响到了拷贝对象clonedStud。 } } ``` 结果如下: ``` 原始对象: 峰 - 买 拷贝对象: 峰 - 买 原始对象和拷贝对象是否一样: false 原始对象和拷贝对象的name属性是否一样: true 原始对象和拷贝对象的subj属性是否一样: true 更新后的原始对象: 小 - 疯 更新原始对象后的克隆对象: 峰 - 疯 ``` **可以看到,浅拷贝中的引用类型并没有拷贝一份,都指向同一个对象**。 深拷贝例子 ```java // 重写 student的clone方法,例子还是如上。 @Override protected Object clone() throws CloneNotSupportedException { // 浅拷贝 // return super.clone(); // 深拷贝 Student student = new Student(new Subject(subject.getName()), name); return student; // 因为它是深拷贝,所以你需要创建拷贝类的一个对象。 // 因为在Student类中有对象引用,所以需要在Student类中实现Cloneable接口并且重写clone方法。 } ``` 结果如下: ``` 原始对象: 峰 - 买 拷贝对象: 峰 - 买 原始对象和拷贝对象是否一样: false 原始对象和拷贝对象的name属性是否一样: true 原始对象和拷贝对象的subj属性是否一样: false 更新后的原始对象: 小 - 疯 更新原始对象后的克隆对象: 峰 - 买 ``` **可以看到,浅拷贝中的引用类型创建一份新对象**。 > 创作不易哇,觉得有帮助的话,给个小小的star呗。[github地址](https://github.com/DreamCats/JavaBooks)😁😁😁<file_sep>/** * @program JavaBooks * @description: compare and swap * @author: mf * @create: 2020/02/13 14:48 */ package com.juc.cas; import java.util.concurrent.atomic.AtomicInteger; public class CASDemo { public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(5); System.out.println(atomicInteger.compareAndSet(5, 2020) + " current value: " + atomicInteger.get()); System.out.println(atomicInteger.compareAndSet(5, 1024) + " current value: " + atomicInteger.get()); } } <file_sep>/** * @program JavaBooks * @description: 汉明距离 * @author: mf * @create: 2020/04/11 18:02 */ package subject.bit; public class T1 { public int hammingDistance(int x, int y) { int xor = x ^ y; int distance = 0; while (xor != 0) { if (xor % 2 == 1) { distance += 1; } xor = xor >> 1; } return distance; } } <file_sep>package books; /** * @program JavaBooks * @description: 礼物的最大价值 * @author: mf * @create: 2019/09/30 09:36 */ /* 在一个m×n的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0)。 你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格直到到达棋盘的右下角。 给定一个棋盘及其上面的礼物,请计算你最多能拿到多少价值的礼物? */ /* 思路: 使用动态规划,f(i,j)表示到达坐标[i,j]时能拿到的最大礼物总和。 则当前格子f(i,j)可由左边格子f(i-1,j)或f(i,j-1)上面格子到达。因此,递归式子为: f(i,j)=max(f(i−1,j),f(i,j−1))+gift[i,j], 其中,gift[i,j]=坐标[i,j]格子里的礼物 */ public class T47 { public static void main(String[] args) { int[][] values = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(getMaxPath(values)); } private static int getMaxPath(int[][] values) { if (values == null) return 0; int rows = values.length; if (rows == 0) return 0; int cols = values[0].length; if (cols == 0) return 0; int[][] maxValues = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int fromUp = 0; // 上面 int fromLeft = 0; // 左边 if (i > 0) fromUp = maxValues[i - 1][j]; if (j > 0) fromLeft = maxValues[i][j - 1]; maxValues[i][j] = Math.max(fromLeft, fromUp) + values[i][j]; } } return maxValues[rows - 1][cols - 1]; } } <file_sep>/** * @program JavaBooks * @description: 环形链表 * @author: mf * @create: 2020/04/09 17:24 */ package subject.dpointer; public class T6 { public boolean hasCycle(ListNode head) { if (head != null && head.next != null) { // 快慢指针 ListNode quick = head; ListNode slow = head; while (2 > 1) { quick = quick.next; if (quick == null) return false; quick = quick.next; if (quick == null) return false; slow = slow.next; if (slow == quick) return true; } } else { return false; } } } <file_sep>/** * @program JavaBooks * @description: 最长上升子序列 * @author: mf * @create: 2020/04/17 22:14 */ package subject.dp; /** * 输入: [10,9,2,5,3,7,101,18] * 输出: 4 * 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 */ public class T6 { public int lengthOfLIS(int[] nums) { if (nums.length == 0) return 0; int[] dp = new int[nums.length]; dp[0] = 1; int lis = 1; for (int i = 1; i < dp.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j] && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; } } lis = Math.max(lis, dp[i]); } return lis; } } <file_sep>package com.basic; import java.util.concurrent.*; /** * @program JavaBooks * @description: future * @author: mf * @create: 2020/01/01 14:18 */ public class T23 { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> task = new FutureTask<>(() -> { TimeUnit.MILLISECONDS.sleep(500); return 1000; }); new Thread(task).start(); System.out.println(task.get()); // 阻塞 ExecutorService service = Executors.newFixedThreadPool(5); Future<Integer> f = service.submit(() -> { try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return 1; }); // System.out.println(f.get()); System.out.println(f.isDone()); System.out.println(f.get()); System.out.println(f.isDone()); service.shutdown(); } } <file_sep>## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## 回顾一下类加载过程 类加载过程:**加载->连接->初始化**。连接过程又可分为三步:**验证->准备->解析**。 ![参考-JavaGuide-类加载过程](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/类加载过程.png) 一个非数组类的加载阶段(加载阶段获取类的二进制字节流的动作)是可控性最强的阶段,这一步我们可以去完成还可以自定义类加载器去控制字节流的获取方式(重写一个类加载器的 `loadClass()` 方法)。数组类型不通过类加载器创建,它由 Java 虚拟机直接创建。 所有的类都由类加载器加载,加载的作用就是将 .class文件加载到内存。 ## 类加载器总结 JVM 中内置了三个重要的 ClassLoader,除了 BootstrapClassLoader 其他类加载器均由 Java 实现且全部继承自`java.lang.ClassLoader`: 1. **BootstrapClassLoader(启动类加载器)** :最顶层的加载类,由C++实现,负责加载 `%JAVA_HOME%/lib`目录下的jar包和类或者或被 `-Xbootclasspath`参数指定的路径中的所有类。 2. **ExtensionClassLoader(扩展类加载器)** :主要负责加载目录 `%JRE_HOME%/lib/ext` 目录下的jar包和类,或被 `java.ext.dirs` 系统变量所指定的路径下的jar包。 3. **AppClassLoader(应用程序类加载器)** :面向我们用户的加载器,负责加载当前应用classpath下的所有jar包和类。 ## 双亲委派模型 ### 双亲委派模型介绍 每一个类都有一个对应它的类加载器。系统中的 ClassLoder 在协同工作的时候会默认使用 **双亲委派模型** 。即在类加载的时候,系统会首先判断当前类是否被加载过。已经被加载的类会直接返回,否则才会尝试加载。加载的时候,首先会把该请求委派该父类加载器的 `loadClass()` 处理,因此所有的请求最终都应该传送到顶层的启动类加载器 `BootstrapClassLoader` 中。当父类加载器无法处理时,才由自己来处理。当父类加载器为null时,会使用启动类加载器 `BootstrapClassLoader` 作为父类加载器。 ![参考-JavaGuide-ClassLoader](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/classloader_WPS图片.png) ```java public class ClassLoaderDemo { public static void main(String[] args) { System.out.println("ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader()); System.out.println("The Parent of ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader().getParent()); System.out.println("The GrandParent of ClassLodarDemo's ClassLoader is " + ClassLoaderDemo.class.getClassLoader().getParent().getParent()); } } ClassLodarDemo's ClassLoader is sun.misc.Launcher$AppClassLoader@18b4aac2 The Parent of ClassLodarDemo's ClassLoader is sun.misc.Launcher$ExtClassLoader@1b6d3586 The GrandParent of ClassLodarDemo's ClassLoader is null ``` `AppClassLoader`的父类加载器为`ExtClassLoader` `ExtClassLoader`的父类加载器为null,**null并不代表`ExtClassLoader`没有父类加载器,而是 `BootstrapClassLoader`** 。 其实这个双亲翻译的容易让别人误解,我们一般理解的双亲都是父母,这里的双亲更多地表达的是“父母这一辈”的人而已,并不是说真的有一个 Mother ClassLoader 和一个 Father ClassLoader 。另外,类加载器之间的“父子”关系也不是通过继承来体现的,是由“优先级”来决定。 ### 双亲委派模型的好处 双亲委派模型保证了Java程序的稳定运行,可以避免类的重复加载(JVM 区分不同类的方式不仅仅根据类名,相同的类文件被不同的类加载器加载产生的是两个不同的类),也保证了 Java 的核心 API 不被篡改。如果没有使用双亲委派模型,而是每个类加载器加载自己的话就会出现一些问题,比如我们编写一个称为 `java.lang.Object` 类的话,那么程序运行的时候,系统就会出现多个不同的 `Object` 类。 ### 如果我们不想用双亲委派模型怎么办? 为了避免双亲委托机制,我们可以自己定义一个类加载器,然后重写 `loadClass()` 即可。 ## 自定义类加载器 除了 `BootstrapClassLoader` 其他类加载器均由 Java 实现且全部继承自`java.lang.ClassLoader`。如果我们要自定义自己的类加载器,很明显需要继承 `ClassLoader`。<file_sep>package web; /** * @program LeetNiu * @description: 不用加减乘除做加法 * @author: mf * @create: 2020/01/15 13:47 */ /** *写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。 */ public class T48 { public int Add(int num1,int num2) { while (num2 != 0) { int temp = num1 ^ num2; num2 = (num1 & num2) << 1; num1 = temp; } return num1; } } <file_sep>/** * @program JavaBooks * @description: TreeNode * @author: mf * @create: 2020/03/09 13:13 */ package subject.tree; public class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } } <file_sep>## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## Atomic 原子类介绍 Atomic 翻译成中文是原子的意思。在化学上,我们知道原子是构成一般物质的最小单位,在化学反应中是不可分割的。在我们这里 Atomic 是指一个操作是不可中断的。即使是在多个线程一起执行的时候,一个操作一旦开始,就不会被其他线程干扰。 所以,所谓原子类说简单点就是具有原子/原子操作特征的类。 JUC包中的原子类分为4类 **基本类型** 使用原子的方式更新基本类型 - AtomicInteger:整型原子类 - AtomicLong:长整型原子类 - AtomicBoolean :布尔型原子类 **数组类型** 使用原子的方式更新数组里的某个元素 - AtomicIntegerArray:整型数组原子类 - AtomicLongArray:长整型数组原子类 - AtomicReferenceArray :引用类型数组原子类 **引用类型** - AtomicReference:引用类型原子类 - AtomicReferenceFieldUpdater:原子更新引用类型里的字段 - AtomicMarkableReference :原子更新带有标记位的引用类型 **对象的属性修改类型** - AtomicIntegerFieldUpdater:原子更新整型字段的更新器 - AtomicLongFieldUpdater:原子更新长整型字段的更新器 - AtomicStampedReference :原子更新带有版本号的引用类型。该类将整数值与引用关联起来,可用于解决原子的更新数据和数据的版本号,可以解决使用 CAS 进行原子更新时可能出现的 ABA 问题。 - AtomicMarkableReference:原子更新带有标记的引用类型。该类将 boolean 标记与引用关联起来,也可以解决使用 CAS 进行原子更新时可能出现的 ABA 问题。 **CAS ABA 问题** - 描述: 第一个线程取到了变量 x 的值 A,然后巴拉巴拉干别的事,总之就是只拿到了变量 x 的值 A。这段时间内第二个线程也取到了变量 x 的值 A,然后把变量 x 的值改为 B,然后巴拉巴拉干别的事,最后又把变量 x 的值变为 A (相当于还原了)。在这之后第一个线程终于进行了变量 x 的操作,但是此时变量 x 的值还是 A,所以 compareAndSet 操作是成功。 - 例子描述(可能不太合适,但好理解): 年初,现金为零,然后通过正常劳动赚了三百万,之后正常消费了(比如买房子)三百万。年末,虽然现金零收入(可能变成其他形式了),但是赚了钱是事实,还是得交税的! - 代码例子(以``` AtomicInteger ```为例) ```java import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerDefectDemo { public static void main(String[] args) { defectOfABA(); } static void defectOfABA() { final AtomicInteger atomicInteger = new AtomicInteger(1); Thread coreThread = new Thread( () -> { final int currentValue = atomicInteger.get(); System.out.println(Thread.currentThread().getName() + " ------ currentValue=" + currentValue); // 这段目的:模拟处理其他业务花费的时间 try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } boolean casResult = atomicInteger.compareAndSet(1, 2); System.out.println(Thread.currentThread().getName() + " ------ currentValue=" + currentValue + ", finalValue=" + atomicInteger.get() + ", compareAndSet Result=" + casResult); } ); coreThread.start(); // 这段目的:为了让 coreThread 线程先跑起来 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } Thread amateurThread = new Thread( () -> { int currentValue = atomicInteger.get(); boolean casResult = atomicInteger.compareAndSet(1, 2); System.out.println(Thread.currentThread().getName() + " ------ currentValue=" + currentValue + ", finalValue=" + atomicInteger.get() + ", compareAndSet Result=" + casResult); currentValue = atomicInteger.get(); casResult = atomicInteger.compareAndSet(2, 1); System.out.println(Thread.currentThread().getName() + " ------ currentValue=" + currentValue + ", finalValue=" + atomicInteger.get() + ", compareAndSet Result=" + casResult); } ); amateurThread.start(); } } ``` 输出内容如下: ``` Thread-0 ------ currentValue=1 Thread-1 ------ currentValue=1, finalValue=2, compareAndSet Result=true Thread-1 ------ currentValue=2, finalValue=1, compareAndSet Result=true Thread-0 ------ currentValue=1, finalValue=2, compareAndSet Result=true ``` 下面我们来详细介绍一下这些原子类。 ## 基本类型原子类 ### 基本类型原子类介绍 使用原子的方式更新基本类型 - AtomicInteger:整型原子类 - AtomicLong:长整型原子类 - AtomicBoolean :布尔型原子类 上面三个类提供的方法几乎相同,所以我们这里以 AtomicInteger 为例子来介绍。 **AtomicInteger 类常用方法** ```java public final int get() //获取当前的值 public final int getAndSet(int newValue)//获取当前的值,并设置新的值 public final int getAndIncrement()//获取当前的值,并自增 public final int getAndDecrement() //获取当前的值,并自减 public final int getAndAdd(int delta) //获取当前的值,并加上预期的值 boolean compareAndSet(int expect, int update) //如果输入的数值等于预期值,则以原子方式将该值设置为输入值(update) public final void lazySet(int newValue)//最终设置为newValue,使用 lazySet 设置之后可能导致其他线程在之后的一小段时间内还是可以读到旧的值。 ``` ### 基本数据类型原子类的优势 **①多线程环境不使用原子类保证线程安全(基本数据类型)** ```java class Test { private volatile int count = 0; //若要线程安全执行执行count++,需要加锁 public synchronized void increment() { count++; } public int getCount() { return count; } } ``` **②多线程环境使用原子类保证线程安全(基本数据类型)** ```java class Test2 { private AtomicInteger count = new AtomicInteger(); public void increment() { count.incrementAndGet(); } //使用AtomicInteger之后,不需要加锁,也可以实现线程安全。 public int getCount() { return count.get(); } } ``` ### AtomicInteger 线程安全原理简单分析 AtomicInteger 类的部分源码: ```java // setup to use Unsafe.compareAndSwapInt for updates(更新操作时提供“比较并替换”的作用) private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value; ``` AtomicInteger 类主要利用 CAS (compare and swap) + volatile 和 native 方法来保证原子操作,从而避免 synchronized 的高开销,执行效率大为提升。 CAS的原理是拿期望的值和原本的一个值作比较,如果相同则更新成新的值。UnSafe 类的 objectFieldOffset() 方法是一个本地方法,这个方法是用来拿到“原来的值”的内存地址。另外 value 是一个volatile变量,在内存中可见,因此 JVM 可以保证任何时刻任何线程总能拿到该变量的最新值。 ### 其他 数组类型原子类、引用类型原子类和对象的属性修改类型原子类就不介绍了<file_sep>package web; /** * @program LeetNiu * @description: 和为S的两个数字 * @author: mf * @create: 2020/01/15 10:48 */ import java.util.ArrayList; /** * 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。 */ public class T42 { public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) { int start = 0, end = array.length - 1; ArrayList<Integer> list = new ArrayList<>(); while (start < end) { int count = array[start] + array[end]; if (count < sum) { start++; } if (count == sum) { list.add(array[start]); list.add(array[end]); return list; } if (count > sum) { end--; } } return list; } } <file_sep>package com.basic; import java.util.concurrent.TimeUnit; /** * @program JavaBooks * @description: 锁对象变了,锁就被释放了 * @author: mf * @create: 2019/12/29 00:28 */ public class T9 { Object o = new Object(); void m() { synchronized (o) { while (true) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); // 打印自己的名字 } } } public static void main(String[] args) { T9 t9 = new T9(); new Thread(t9::m, "t9").start(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } t9.o = new Object(); // 注释掉这句话的话, t9二代是不会启动的,因为还在上锁呢。 new Thread(t9::m, "t9二代").start(); } } <file_sep>/** * @program JavaBooks * @description: 路径总和 * @author: mf * @create: 2020/03/10 14:14 */ package subject.tree; /** * 5 * / \ * 4 8 * / / \ * 11 13 4 * / \ \ * 7 2 1 * sum = 22 */ public class T7 { /** * 递归 * @param root * @param sum * @return */ public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; // 总和减去路径上节点的值 sum -= root.val; // 如果节的左右节点都为空,说明那个路径上走完了,可以开始比较sum是否为0 if (root.left == null && root.right == null) return sum == 0; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } <file_sep>package books; import java.util.ArrayList; /** * @program JavaBooks * @description: 二叉树中和为某一值的路径 * @author: mf * @create: 2019/09/15 13:56 */ /* 输入一颗二叉树和一个整数,打印出二叉树中节点值的和 为输入整数的所有路径。从树的根节点开始往下一直到叶节点 所经过的节点形成一条路径。 */ /* 思路: 准备两个容器 一个存放走过来的路径 一个存放和为target的路径 递归的过程,前序遍历 用第一个容器去记录节点值, 每当路径走完计算和是否为target, 不管等不等,都需要减掉最后节点 */ public class T34 { private static ArrayList<ArrayList<Integer>> listall = new ArrayList<>(); private static ArrayList<Integer> lists = new ArrayList<>(); public static void main(String[] args) { int[] pre = {10, 5, 4, 7, 12}; int[] in = {4, 5, 7, 10, 12}; TreeNode node = TreeNode.setBinaryTree(pre, in); ArrayList<ArrayList<Integer>> resList = findPath(node, 22); System.out.println(resList); } private static ArrayList<ArrayList<Integer>> findPath(TreeNode node, int target) { if (node == null) return listall; lists.add(node.val); target -= node.val; if (target == 0 && node.left == null && node.right == null) { listall.add(new ArrayList<>(lists)); } findPath(node.left, target); findPath(node.right, target); lists.remove(lists.size() - 1); return listall; } } <file_sep>package normal; import java.util.HashMap; /** * @program JavaBooks * @description: 387.字符串中的第一个唯一字符 * @author: mf * @create: 2019/11/06 16:59 */ /* 题目:https://leetcode-cn.com/problems/first-unique-character-in-a-string/ 类型: 难度:easy */ /* s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. */ public class FirstUniqChar { public static void main(String[] args) { String s = "leetcode"; String s1 = "loveleetcode"; System.out.println(firstUniqChar(s1)); } private static int firstUniqChar(String s) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (int i = 0; i < s.length(); i++) { if (map.get(s.charAt(i)) == 1) { return i; } } return -1; } } <file_sep>package web; /** * @program LeetNiu * @description: 用两个栈实现队列 * @author: mf * @create: 2020/01/09 12:01 */ import java.util.Stack; /** * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 */ public class T5 { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); public void push (int node) { stack1.push(node); } public int pop() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } } <file_sep>## 引言 **线性表-树-基础** <!-- more --> ![](https://www.pdai.tech/_images/alg/alg-tree-0.png) ## 树 树是一种数据结构,它是n(n>=0)个节点的有限集。n=0时称为空树。n>0时,有限集的元素构成一个具有层次感的数据结构。 ![](https://www.pdai.tech/_images/alg/alg-tree-1.png) 区别于线性表一对一的元素关系,树中的节点是一对多的关系。树具有以下特点: - n>0时,根节点是唯一的,不可能存在多个根节点。 - 每个节点有零个至多个子节点;除了根节点外,每个节点有且仅有一个父节点。根节点没有父节点。 ## 树的相关概念 - `子树`: 除了根节点外,每个子节点都可以分为多个不相交的子树。 - `孩子与双亲`: 若一个结点有子树,那么该结点称为子树根的"双亲",子树的根是该结点的"孩子"。在图一中,B、H是A的孩子,A是B、H的双亲。 - `兄弟`: 具有相同双亲的节点互为兄弟,例如B与H互为兄弟。 - `节点的度`: 一个节点拥有子树的数目。例如A的度为2,B的度为1,C的度为3. - `叶子`: 没有子树,也即是度为0的节点。 - `分支节点`: 除了叶子节点之外的节点,也即是度不为0的节点。 - `内部节点`: 除了根节点之外的分支节点。 - `层次`: 根节点为第一层,其余节点的层次等于其双亲节点的层次加1. - `树的高度`: 也称为树的深度,树中节点的最大层次。 - `有序树`: 树中节点各子树之间的次序是重要的,不可以随意交换位置。 - `无序树`: 树种节点各子树之间的次序是不重要的。可以随意交换位置。 - `森林`: 0或多棵互不相交的树的集合。 ## 二叉树、完全二叉树、满二叉树 - 二叉树: 最多有两棵子树的树被称为二叉树 ![](https://www.pdai.tech/_images/alg/alg-tree-3.png) - 斜树: 所有节点都只有左子树的二叉树叫做左斜树,所有节点都只有右子树的二叉树叫做右斜树。(本质就是链表) ![](https://www.pdai.tech/_images/alg/alg-tree-4.png) - 满二叉树: 二叉树中所有非叶子结点的度都是2,且叶子结点都在同一层次上 ![](https://www.pdai.tech/_images/alg/alg-tree-5.png) - 完全二叉树: 如果一个二叉树与满二叉树前m个节点的结构相同,这样的二叉树被称为完全二叉树 ![](https://www.pdai.tech/_images/alg/alg-tree-6.png) ## 二叉查找树-BST 二叉查找树(Binary Search Tree)是指一棵空树或者具有下列性质的二叉树: - 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值; - 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值; - 任意节点的左、右子树也分别为二叉查找树; - 没有键值相等的节点。 二叉查找树相比于其他数据结构的优势在于查找、插入的时间复杂度较低为 O ( log ⁡ n ) 。二叉查找树是基础性数据结构,用于构建更为抽象的数据结构,如集合、多重集、关联数组等。 ![](https://www.pdai.tech/_images/alg/alg-tree-binary-search-1.svg) ## 平衡二叉树-AVL 含有相同节点的二叉查找树可以有不同的形态,而二叉查找树的平均查找长度与树的深度有关,所以需要找出一个查找平均长度最小的一棵,那就是平衡二叉树,具有以下性质: - 要么是棵空树,要么其根节点左右子树的深度之差的绝对值不超过1; - 其左右子树也都是平衡二叉树; - 二叉树节点的平衡因子定义为该节点的左子树的深度减去右子树的深度。则平衡二叉树的所有节点的平衡因子只可能是-1,0,1。 ![](https://www.pdai.tech/_images/alg/alg-tree-balance-tree-1.jpg) ## 红黑树 红黑树也是一种自平衡的二叉查找树。 - 每个结点要么是红的要么是黑的。(红或黑) - 根结点是黑的。 (根黑) - 每个叶结点(叶结点即指树尾端NIL指针或NULL结点)都是黑的。 (叶黑) - 如果一个结点是红的,那么它的两个儿子都是黑的。 (红子黑) - 对于任意结点而言,其到叶结点树尾端NIL指针的每条路径都包含相同数目的黑结点。(路径下黑相同) ![](https://www.pdai.tech/_images/alg/alg-tree-14.png) 应用场景: - Java ConcurrentHashMap & TreeMap - C++ STL: map & set - linux进程调度Completely Fair Scheduler,用红黑树管理进程控制块 - epoll在内核中的实现,用红黑树管理事件块 - nginx中,用红黑树管理timer等 ## B-树 B树(英语: B-tree)是一种自平衡的树,能够保持数据有序。这种数据结构能够让查找数据、顺序访问、插入数据及删除的动作,都在对数时间内完成。B树,概括来说是一个一般化的二叉查找树(binary search tree),可以拥有最多2个子节点。与自平衡二叉查找树不同,B树适用于读写相对大的数据块的存储系统,例如磁盘。 ## B+树 B+ 树是一种树数据结构,通常用于关系型数据库(如Mysql)和操作系统的文件系统中。B+ 树的特点是能够保持数据稳定有序,其插入与修改拥有较稳定的对数时间复杂度。B+ 树元素自底向上插入,这与二叉树恰好相反。 在B树基础上,为叶子结点增加链表指针(B树+叶子有序链表),所有关键字都在叶子结点 中出现,非叶子结点作为叶子结点的索引;B+树总是到叶子结点才命中。 b+树的非叶子节点不保存数据,只保存子树的临界值(最大或者最小),所以同样大小的节点,b+树相对于b树能够有更多的分支,使得这棵树更加矮胖,查询时做的IO操作次数也更少。 将上一节中的B-Tree优化,由于B+Tree的非叶子节点只存储键值信息,假设每个磁盘块能存储4个键值及指针信息,则变成B+Tree后其结构如下图所示: ![](https://www.pdai.tech/_images/alg/alg-tree-16.png) ## 总结 我们知道,实际应用当中,我们经常使用的是`查找`和`排序`操作,这在我们的各种管理系统、数据库系统、操作系统等当中,十分常用。 `数组`的下标寻址十分迅速,但计算机的内存是有限的,故数组的长度也是有限的,实际应用当中的数据往往十分庞大;而且无序数组的查找最坏情况需要遍历整个数组;后来人们提出了二分查找,二分查找要求数组的构造一定有序,二分法查找解决了普通数组查找复杂度过高的问题。任和一种数组无法解决的问题就是插入、删除操作比较复杂,因此,在一个增删查改比较频繁的数据结构中,数组不会被优先考虑 `普通链表`由于它的结构特点被证明根本不适合进行查找 `哈希表`是数组和链表的折中,同时它的设计依赖散列函数的设计,数组不能无限长、链表也不适合查找,所以也适合大规模的查找 `二叉查找树`因为可能退化成链表,同样不适合进行查找 `AVL树`是为了解决可能退化成链表问题,但是AVL树的旋转过程非常麻烦,因此插入和删除很慢,也就是构建AVL树比较麻烦 `红黑树`是平衡二叉树和AVL树的折中,因此是比较合适的。集合类中的Map、关联数组具有较高的查询效率,它们的底层实现就是红黑树。 `多路查找树` 是大规模数据存储中,实现索引查询这样一个实际背景下,树节点存储的元素数量是有限的(如果元素数量非常多的话,查找就退化成节点内部的线性查找了),这样导致二叉查找树结构由于树的深度过大而造成磁盘I/O读写过于频繁,进而导致查询效率低下。 `B树`与自平衡二叉查找树不同,B树适用于读写相对大的数据块的存储系统,例如磁盘。它的应用是文件系统及部分非关系型数据库索引。 `B+树`在B树基础上,为叶子结点增加链表指针(B树+叶子有序链表),所有关键字都在叶子结点 中出现,非叶子结点作为叶子结点的索引;B+树总是到叶子结点才命中。通常用于关系型数据库(如Mysql)和操作系统的文件系统中。 针对大量数据,如果在内存中作业优先考虑红黑树(map,set之类多为RB-tree实现),如果在硬盘中作业优先考虑B系列树(B+, B, B*) ## 相关题目 ### 前序遍历 - 访问根结点; - 先序遍历左子树; - 先序遍历右子树。 ```java private void preOrder(TreeNode<T> tree) { if(tree != null) { System.out.print(tree.key+" "); preOrder(tree.left); preOrder(tree.right); } } public void preOrder() { preOrder(mRoot); } ``` ### 中序遍历 - 中序遍历左子树; - 访问根结点; - 中序遍历右子树。 ```java private void inOrder(TreeNode<T> tree) { if(tree != null) { inOrder(tree.left); System.out.print(tree.key+" "); inOrder(tree.right); } } public void inOrder() { inOrder(mRoot); } ``` ### 后序遍历 - 后序遍历左子树; - 后序遍历右子树; - 访问根结点。 ```java private void postOrder(TreeNode<T> tree) { if(tree != null) { postOrder(tree.left); postOrder(tree.right); System.out.print(tree.key+" "); } } public void postOrder() { postOrder(mRoot); } ``` ### [100. 相同的树](https://leetcode-cn.com/problems/same-tree/) ``` 输入: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] 输出: true 输入: 1 1 / \ 2 2 [1,2], [1,null,2] 输出: false ``` 分析:递归判断 ```java /** * 递归判断(实际上前行遍历) * @param p * @param q * @return */ public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; // 递归到最后二者都是null 说明相同 if (p == null || q == null) return false; // 递归到其中有一方为空,则不相同 if (p.val != q.val) return false; // 值不相等 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } ``` ### [101. 对称二叉树](https://leetcode-cn.com/problems/symmetric-tree/) ```bash 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 ``` 分析:对称的前序遍历的值是一样的 ```java class Solution { public boolean isSymmetric(TreeNode root) { return isSym(root, root); } private boolean isSym(TreeNode root, TreeNode root1) { if(root == null && root1 == null) return true; if(root == null || root1 == null) return false; if(root.val != root1.val) return false; return isSym(root.left, root1.right) && isSym(root.right, root1.left); } } ``` ### [104. 二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) ```bash 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 ``` 分析:递归 ```java class Solution { public int maxDepth(TreeNode root) { return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } } ``` ### [108. 将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/) ```bash 给定有序数组: [-10,-3,0,5,9], 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5 ``` 分析:中序遍历的逆过程 左右等分建立左右子树,中间节点作为子树根节点,递归该过程 ```java class Solution { public TreeNode sortedArrayToBST(int[] nums) { return nums == null ? null : buildTree(nums, 0, nums.length - 1); } private TreeNode buildTree(int[] nums, int l, int r) { if(l > r) return null; int m = l + (r - l) / 2; TreeNode root = new TreeNode(nums[m]); root.left = buildTree(nums, l, m - 1); root.right = buildTree(nums, m + 1, r); return root; } } ``` ### [110. 平衡二叉树](https://leetcode-cn.com/problems/balanced-binary-tree/) ``` 3 / \ 9 20 / \ 15 7 true ``` ```java /** * 自顶向下递归 * @param root * @return */ public boolean isBalanced(TreeNode root) { if (root == null) return true; return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right); } public int maxDepth(TreeNode root) { if (root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } ``` #### [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) ``` 3 / \ 9 20 / \ 15 7 2 ``` ```java /** * 注意仔细读题,一开始没想到根左和根右任意为空的情况 * @param root * @return */ public int minDepth(TreeNode root) { if(root == null) return 0; int m1 = minDepth(root.left); int m2 = minDepth(root.right); return root.left == null || root.right == null ? m1 + m2 + 1 : Math.min(m1, m2) + 1; } ``` #### [112. 路径总和](https://leetcode-cn.com/problems/path-sum/) ``` 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 sum = 22 ``` ```java /** * 递归 * @param root * @param sum * @return */ public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; // 总和减去路径上节点的值 sum -= root.val; // 如果节的左右节点都为空,说明那个路径上走完了,可以开始比较sum是否为0 if (root.left == null && root.right == null) return sum == 0; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } ``` #### [226. 翻转二叉树](https://leetcode-cn.com/problems/invert-binary-tree/) ``` 4 / \ 2 7 / \ / \ 1 3 6 9 输出: 4 / \ 7 2 / \ / \ 9 6 3 1 ``` ```java /** * 还是递归 * @param root * @return */ public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode left = invertTree(root.left); // 递归到最后的坐 TreeNode right = invertTree(root.right); // 递归到最后的右 // 你给我,我给你 root.left = right; root.right = left; return root; } ``` <file_sep>> 微服务和分布式算是一种潮流和趋势,项目中要到了微服务还是准备准备面试的问题吧... ## 大纲图 ![Dubbo常见面试](http://media.dreamcat.ink/uPic/Dubbo常见面试.png) ### Dubbo和SpringCloud的区别 - **底层**:`Dubbo`底层是使用Netty的NIO框架,基于TCP协议传输,使用Hession序列化完成RPC通信;`SpringCloud`是基于HTTP协议+REST接口调用远程过程的通信,HTTP请求会有更大的报文,占的带宽也会更多。但是REST相比RPC更为灵活,不存在代码级别的强依赖。 - **集成**:springcloud相关组件多,有自己得注册中心网关等,集成方便,Dubbo需要自己额外去集成。 - **定位**:Dubbo是SOA时代的产物,它的关注点主要在于**服务的调用,流量分发、流量监控和熔断**。而SpringCloud诞生于微服务架构时代,考虑的是微服务治理的方方面面,另外由于依托了Spirng、SpirngBoot 的优势之上,两个框架在开始目标就不一致,Dubbo定位服务治理、SpirngCloud是一个生态。因此可以大胆地判断,Dubbo未来会在服务治理方面更为出色,而Spring Cloud在微服务治理上面无人能敌。 ### 什么是Dubbo? Dubbo是一款**高性能**、**轻量级**的开源Java RPC 框架,它提供了三大核心能力:**面向接口的远程方法调用**,**智能容错和负载均衡**,以及**服务自动注册和发现**。简单来说 Dubbo 是一个**分布式服务框架**,致力于提供**高性能和透明化的RPC远程服务调用方案**,以及**SOA服务治理方案。** ### 什么是RPC?原理是什么? #### RPC RPC(Remote Procedure Call)—远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。比如两个不同的服务 A、B 部署在两台不同的机器上,那么服务 A 如果想要调用服务 B 中的某个方法该怎么办呢?使用 HTTP请求 当然可以,但是可能会比较慢而且一些优化做的并不好。 RPC 的出现就是为了解决这个问题。 #### RPC原理 ![RPC原理](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-12-6/37345851.jpg) 1. 服务消费方(client)调用以本地调用方式调用服务; 2. client stub接收到调用后负责将方法、参数等组装成能够进行网络传输的消息体; 3. client stub找到服务地址,并将消息发送到服务端; 4. server stub收到消息后进行解码; 5. server stub根据解码结果调用本地的服务; 6. 本地服务执行并将结果返回给server stub; 7. server stub将返回结果打包成消息并发送至消费方; 8. client stub接收到消息,并进行解码; 9. 服务消费方得到最终结果。 ![RPC时序图](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-12-6/32527396.jpg) ### 为什么要用Dubbo? Dubbo 的诞生和 **SOA 分布式架构**的流行有着莫大的关系。**SOA 面向服务的架构**(Service Oriented Architecture),也就是把工程按照业务逻辑拆分成**服务层、表现层**两个工程。**服务层中包含业务逻辑,只需要对外提供服务即可**。**表现层只需要处理和页面的交互**,业务逻辑都是调用服务层的服务来实现。SOA架构中有两个主要角色:**服务提供者**(Provider)**和服务使用者**(Consumer)。 我觉得主要可以从 Dubbo 提供的下面四点特性来说为什么要用 Dubbo: 1. **负载均衡**——同一个服务部署在不同的机器时该调用那一台机器上的服务。 2. **服务调用链路生成**——随着系统的发展,服务越来越多,服务间依赖关系变得错踪复杂,甚至分不清哪个应用要在哪个应用之前启动,架构师都不能完整的描述应用的架构关系。Dubbo 可以为我们解决服务之间互相是如何调用的。 3. **服务访问压力以及时长统计、资源调度和治理**——基于访问压力实时管理集群容量,提高集群利用率。 4. **服务降级**——某个服务挂掉之后调用备用服务。 另外,Dubbo 除了能够应用在分布式系统中,也可以应用在现在比较火的微服务系统中。不过,由于 Spring Cloud 在微服务中应用更加广泛,所以,我觉得一般我们提 Dubbo 的话,大部分是分布式系统的情况。 ### 什么是分布式? 分布式或者说 SOA 分布式重要的就是**面向服务**,说简单的分布式就是我们把**整个系统拆分成不同的服务然后将这些服务放在不同的服务器上减轻单体服务的压力提高并发量和性能**。比如电商系统可以简单地拆分成订单系统、商品系统、登录系统等等,拆分之后的每个服务可以**部署在不同的机器上**,如果某一个服务的访问量比较大的话也可以将这个服务同时部署在多台机器上。 ### 为什么要分布式? - 从开发角度来讲**单体应用的代码都集中在一起**,而**分布式系统的代码根据业务被拆分**。所以,每个团队可以负责一个服务的开发,这样提升了开发效率。另外,代码根据业务拆分之后更加便于维护和扩展。 - 系统拆分成分布式之后不光便于系统扩展和维护,更能提高整个系统的性能。把整个系统拆分成不同的服务/系统,然后每个服务/系统 单独部署在一台服务器上,是不是很大程度上提高了系统性能呢? ### Dubbo的架构图解 ![dubbo架构图解](http://media.dreamcat.ink/uPic/dubbo架构图解.png) - **Provider:** 暴露服务的服务提供方 - **Consumer:** 调用远程服务的服务消费方 - **Registry:** 服务注册与发现的注册中心 - **Monitor:** 统计服务的调用次数和调用时间的监控中心 - **Container:** 服务运行容器 **调用关系说明**: 1. 服务容器负责启动,加载,运行服务提供者。 2. 服务提供者在启动时,向注册中心注册自己提供的服务。 3. 服务消费者在启动时,向注册中心订阅自己所需的服务。 4. 注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者。 5. 服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失败,再选另一台调用。 6. 服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心。 **各个组件总结**: - **注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小** - **监控中心负责统计各服务调用次数,调用时间等,统计先在内存汇总后每分钟一次发送到监控中心服务器,并以报表展示** - **注册中心,服务提供者,服务消费者三者之间均为长连接,监控中心除外** - **注册中心通过长连接感知服务提供者的存在,服务提供者宕机,注册中心将立即推送事件通知消费者** - **注册中心和监控中心全部宕机,不影响已运行的提供者和消费者,消费者在本地缓存了提供者列表** - **注册中心和监控中心都是可选的,服务消费者可以直连服务提供者** - **服务提供者无状态,任意一台宕掉后,不影响使用** - **服务提供者全部宕掉后,服务消费者应用将无法使用,并无限次重连等待服务提供者恢复** ### Dubbo工作原理 ![参考-JavaGuide-工作原理](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-26/64702923.jpg) 图中从下至上分为十层,各层均为**单向依赖**,右边的黑色箭头代表层之间的依赖关系,每一层都可以剥离上层被复用,其中,Service 和 Config 层为 API,其它各层均为 SPI。 - 第一层:**service层**,接口层,给服务提供者和消费者来实现的 - 第二层:**config层**,配置层,主要是对dubbo进行各种配置的 - 第三层:**proxy层**,服务接口透明代理,生成服务的客户端 Stub 和服务器端 Skeleton - 第四层:**registry层**,服务注册层,负责服务的注册与发现 - 第五层:**cluster层**,集群层,封装多个服务提供者的路由以及负载均衡,将多个实例组合成一个服务 - 第六层:**monitor层**,监控层,对rpc接口的调用次数和调用时间进行监控 - 第七层:**protocol层**,远程调用层,封装rpc调用 - 第八层:**exchange层**,信息交换层,封装请求响应模式,同步转异步 - 第九层:**transport层**,网络传输层,抽象mina和netty为统一接口 - 第十层:**serialize层**,数据序列化层,网络传输需要 ### Dubbo的负载均衡 #### 什么是负载均衡 > 负载均衡改善了跨多个计算资源(例如计算机,计算机集群,网络链接,中央处理单元或磁盘驱动的的工作负载分布。负载平衡旨在优化资源使用,最大化吞吐量,最小化响应时间,并避免任何单个资源的过载。使用具有负载平衡而不是单个组件的多个组件可以通过冗余提高可靠性和可用性。负载平衡通常涉及专用软件或硬件。------ 够强硬 比如我们的系统中的某个服务的**访问量特别大**,我们将这个服务部署在了**多台服务器**上,当客户端发起请求的时候,**多台服务器都可以处理这个请求**。那么,如何正确选择处理该请求的服务器就很关键。假如,你就要一台服务器来处理该服务的请求,那该服务部署在多台服务器的意义就不复存在了。负载均衡就是为了避免单个服务器响应同一请求,容易造成服务器宕机、崩溃等问题,我们从负载均衡的这四个字就能明显感受到它的意义。 #### Dubbo的负载均衡 在集群负载均衡时,Dubbo 提供了多种均衡策略,默认为 `random` 随机调用。可以自行扩展负载均衡策略 ##### Random LoadBalance(默认,基于权重的随机负载均衡机制) - **随机,按权重设置随机概率。** - 在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。 ![参考-JavaGuide-Random LoadBalance](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-12-7/77722327.jpg) ##### RoundRobin LoadBalance(不推荐,基于权重的轮询负载均衡机制) - 轮循,按公约后的权重设置轮循比率。 - 存在慢的提供者累积请求的问题,比如:第二台机器很慢,但没挂,当请求调到第二台时就卡在那,久而久之,所有请求都卡在调到第二台上。 ![参考-JavaGuide-RoundRobin](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-12-7/97933247.jpg) ##### LeastAcive LoadBalace - 最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差。 - 使慢的提供者收到更少请求,因为越慢的提供者的调用前后计数差会越大。 ##### ConsistentHash LodaBalance - **一致性 Hash,相同参数的请求总是发到同一提供者。(如果你需要的不是随机负载均衡,是要一类请求都到一个节点,那就走这个一致性hash策略。)** - 当某一台提供者挂时,原本发往该提供者的请求,基于虚拟节点,平摊到其它提供者,不会引起剧烈变动。 ### Dubbo配置方式 #### xml配置方式 **服务端服务级别**: ```xml <dubbo:service interface="..." loadbalance="roundrobin" /> ``` **客户端服务级别**: ```xml <dubbo:reference interface="..." loadbalance="roundrobin" /> ``` **服务端方法级别**: ```xml <dubbo:service interface="..."> <dubbo:method name="..." loadbalance="roundrobin"/> </dubbo:service> ``` **客户端方法级别**: ```xml <dubbo:reference interface="..."> <dubbo:method name="..." loadbalance="roundrobin"/> </dubbo:reference> ``` #### 注解配置方式: 服务级别配置: ```java @Service .... ``` 消费注解配置: ```java @Reference(loadbalance = "roundrobin") ``` ### zookeeper宕机与dubbo直连的情况 在实际生产中,假如zookeeper注册中心宕掉,一段时间内服务消费方还是能够调用提供方的服务的,实际上它使用的本地缓存进行通讯,这只是dubbo健壮性的一种体现。 **dubbo的健壮性表现:** 1. 监控中心宕掉不影响使用,只是丢失部分采样数据 2. 数据库宕掉后,注册中心仍能通过缓存提供服务列表查询,但不能注册新服务 3. 注册中心对等集群,任意一台宕掉后,将自动切换到另一台 4. 注册中心全部宕掉后,服务提供者和服务消费者仍能通过本地缓存通讯 5. 服务提供者无状态,任意一台宕掉后,不影响使用 6. 服务提供者全部宕掉后,服务消费者应用将无法使用,并无限次重连等待服务提供者恢复 我们前面提到过:注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小。所以,我们可以完全可以绕过注册中心——采用 **dubbo 直连** ,即在服务消费方配置服务提供方的位置信息。<file_sep>/** * @program JavaBooks * @description: String StringBuffer StringBuilder * @author: mf * @create: 2020/02/07 19:13 */ package com.strings; public class SbDemo { public static void main(String[] args) { // String String str = "hello"; long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { str += i; // 创建多少个对象,, } System.out.println("String: " + (System.currentTimeMillis() - start)); // StringBuffer StringBuffer sb = new StringBuffer("hello"); long start1 = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { sb.append(i); } System.out.println("StringBuffer: " + (System.currentTimeMillis() - start1)); // StringBuilder StringBuilder stringBuilder = new StringBuilder("hello"); long start2 = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { stringBuilder.append(i); } System.out.println("StringBuilder: " + (System.currentTimeMillis() - start2)); } } <file_sep>> 个人感觉,这部分源码的重要基础之一就是反射,不过这里就不贴源码,好好学习Java的反射吧。 ## 大纲图 ![MyBatis面试常见问题](http://media.dreamcat.ink/uPic/MyBatis面试常见问题.png) ### 什么是数据持久化? 数据持久化是将**内存**中的**数据**模型转换为**存储**模型,以及将存储模型转换为内存中的数据模型的统称。例如,文件的存储、数据的读取等都是数据持久化操作。数据模型可以是任何**数据结构或对象的模型、XML、二进制流**等。 当我们编写应用程序操作数据库,对表数据进行**增删改查**的操作的时候就是数据持久化的操作。 ### Mybatis框架简介 - **MyBatis框架是一个开源的数据持久层框架。** - **它的内部封装了通过JDBC访问数据库的操作,支持普通的SQL查询、存储过程和高级映射,几乎消除了所有的JDBC代码和参数的手工设置以及结果集的检索。** - **MyBatis作为持久层框架,其主要思想是将程序中的大量SQL语句剥离出来,配置在配置文件当中,实现SQL的灵活配置。** - **这样做的好处是将SQL与程序代码分离,可以在不修改代码的情况下,直接在配置文件当中修改SQL。** ### 什么是ORM? ORM(Object/Relational Mapping)即**对象关系映射**,是一种数据持久化技术。它在**对象模型和关系型数据库直接建立起对应关系**,并且提供一种机制,**通过JavaBean对象去操作数据库表的数据**。 MyBatis通过简单的**XML**或者**注解**的方式进行配置和原始映射,将实体类和SQL语句之间建立映射关系,是一种**半自动**(之所以说是半自动,因为我们要自己写SQL)的ORM实现。 ### MyBatis框架的优缺点及其适用的场合 #### 优点 1. 与JDBC相比,减少了50%以上的代码量。 2. MyBatis是易学的持久层框架,小巧并且简单易学。 3. MyBatis相当灵活,不会对应用程序或者数据库的现有设计强加任何影响,SQL写在XML文件里,从程序代码中彻底分离,降低耦合度,便于统一的管理和优化,并可重用。 4. 提供XML标签,支持编写动态的SQL,满足不同的业务需求。 5. 提供映射标签,支持对象与数据库的ORM字段关系映射。 #### 缺点 1. SQL语句的编写工作量较大,对开发人员编写SQL的能力有一定的要求。 2. SQL语句依赖于数据库,导致数据库不具有好的移植性,不可以随便更换数据库。 #### 适用场景 MyBatis专注于SQL自身,是一个足够灵活的DAO层解决方案。对性能的要求很高,或者需求变化较多的项目,例如Web项目,那么MyBatis是不二的选择。 ### MyBatis与Hibernate有哪些不同? 1. Mybatis和hibernate不同,它不完全是一个ORM框架,因为MyBatis需要程序员自己编写Sql语句。 2. Mybatis直接编写原生态sql,可以严格控制sql执行性能,灵活度高,非常适合对关系数据模型要求不高的软件开发,因为这类软件需求变化频繁,一但需求变化要求迅速输出成果。但是灵活的前提是mybatis无法做到数据库无关性,如果需要实现支持多种数据库的软件,则需要自定义多套sql映射文件,工作量大。 3. Hibernate对象/关系映射能力强,数据库无关性好,对于关系模型要求高的软件,如果用hibernate开发可以节省很多代码,提高效率。 ### #{}和${}的区别是什么? 1. `#{}` 是预编译处理,`${}`是字符串替换。 2. Mybatis在处理`#{}`时,会将sql中的`#{}`替换为?号,调用PreparedStatement的set方法来赋值; 3. Mybatis在处理`${}`时,就是把`${}`替换成变量的值。 4. 使用`#{}`可以有效的防止SQL注入,提高系统安全性。 ### 当实体类中的属性名和表中的字段名不一样,怎么办? 1. 第1种: 通过在查询的sql语句中定义字段名的别名,让字段名的别名和实体类的属性名一致。 2. 第2种: 通过 `<resultMap` 来映射字段名和实体类属性名的一一对应的关系。 ### 模糊查询like语句该怎么写? 1. 第1种:在Java代码中添加sql通配符。 2. 第2种:在sql语句中拼接通配符,会引起sql注入 ### Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗? Dao接口即**Mapper接口**。接口的**全限名**,就是映射文件中的**namespace的值**;接口的**方法名**,就是映射文件中**Mapper的Statement的id值**;接口方法内的参数,就是传递给sql的参数。 Mapper接口是没有实现类的,当调用接口方法时,**接口全限名+方法名拼接字符串作为key值**,**可唯一定位一个MapperStatement**。在Mybatis中每`<select、<insert、<update、<delete `标签,都会被解析为一个MapperStatement对象。 Mapper接口里的方法,是**不能重载**的,因为是使用 全限名+方法名 的保存和寻找策略。**Mapper 接口的工作原理是JDK动态代理**,Mybatis运行时会使用JDK动态代理为Mapper接口生成代理对象proxy,代理对象会拦截接口方法,转而执行MapperStatement所代表的sql,然后将sql执行结果返回。 ### Mybatis是如何进行分页的?分页插件的原理是什么? Mybatis使用**RowBounds**对象进行分页,它是针对ResultSet结果集执行的内存分页,而非物理分页。可以在sql内直接书写带有物理分页的参数来完成物理分页功能,也可以使用分页插件来完成物理分页。 分页插件的基本原理是使用**Mybatis提供的插件接口**,实现自定义插件,在插件的**拦截方法内拦截待执行的sql**,然后重写sql,根据**dialect**方言,添加对应的**物理分页语句和物理分页**参数。 ### Mybatis是如何将sql执行结果封装为目标对象并返回的?都有哪些映射形式? 1. 第一种是使用` <resultMap `标签,逐一定义数据库列名和对象属性名之间的映射关系。 2. 第二种是使用sql列的别名功能,将列的别名书写为对象属性名。 有了列名与属性名的映射关系后,Mybatis通过**反射创建对象**,同时使用**反射给对象的属性逐一赋值并返回**,那些找不到映射关系的属性,是无法完成赋值的。 ### Mybatis动态sql有什么用?执行原理?有哪些动态sql? Mybatis动态sql可以在Xml映射文件内,以标签的形式编写动态sql,执行原理是**根据表达式的值完成逻辑判断并动态拼接sql**的功能。 ### Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复? 不同的Xml映射文件,如果配置了namespace,那么id可以重复;如果没有配置namespace,那么id不能重复; 原因就是namespace+id是作为Map <String,MapperStatement 的key使用的,如果没有namespace,就剩下id,那么,id重复会导致数据互相覆盖。有了namespace,自然id就可以重复,namespace不同,namespace+id自然也就不同。 ### 为什么说Mybatis是半自动ORM映射工具?它与全自动的区别在哪里? Hibernate属于**全自动ORM映射工具**,使用Hibernate查询关联对象或者关联集合对象时,可以根据对象关系模型直接获取,所以它是全自动的。而Mybatis在查询关联对象或关联集合对象时,需要**手动编写sql来完成**,所以,称之为**半自动ORM映射工具**。 ### MyBatis实现一对一有几种方式?具体怎么操作的? 有联合查询和嵌套查询,联合查询是几个表联合查询,只查询一次, 通过在resultMap里面配置association节点配置一对一的类就可以完成; 嵌套查询是先查一个表,根据这个表里面的结果的 外键id,去再另外一个表里面查询数据,也是通过association配置,但另外一个表的查询通过select属性配置。 ### MyBatis实现一对多有几种方式,怎么操作的? 有联合查询和嵌套查询。联合查询是几个表联合查询,只查询一次,通过在resultMap里面的collection节点配置一对多的类就可以完成;嵌套查询是先查一个表,根据这个表里面的 结果的外键id,去再另外一个表里面查询数据,也是通过配置collection,但另外一个表的查询通过select节点配置。 ### Mybatis是否支持延迟加载?如果支持,它的实现原理是什么? Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载lazyLoadingEnabled=true|false。 它的原理是,使用**CGLIB创建目标对象的代理对象**,当调用目标方法时,进入拦截器方法,比如调用a.getB().getName(),拦截器invoke()方法发现a.getB()是null值,那么就会**单独发送事先保存好的查询关联B对象的sql**,**把B查询上来**,**然后调用a.setB(b)**,于是a的对象b属性就有值了,接着完成a.getB().getName()方法的调用。 ### Mybatis的一级、二级缓存 - 一级缓存: 基于 PerpetualCache 的 HashMap 本地缓存,其存储作用域为 Session,当 Session flush 或 close 之后,该 Session 中的所有 Cache 就将清空,默认打开一级缓存。 - 二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap 存储,不同在于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache。默认不打开二级缓存,要开启二级缓存,使用二级缓存属性类需要实现Serializable序列化接口(可用来保存对象的状态),可在它的映射文件中配置 <cache/ ; - 对于缓存数据更新机制,当某一个作用域(一级缓存 Session/二级缓存Namespaces)的进行了C/U/D 操作后,默认该作用域下所有 select 中的缓存将被 clear。 ### 什么是MyBatis的接口绑定?有哪些实现方式? 接口绑定,就是在MyBatis中任意定义接口,然后把接口里面的方法和SQL语句绑定, 我们直接调用接口方法就可以,这样比起原来了SqlSession提供的方法我们可以有更加灵活的选择和设置。 接口绑定有两种实现方式: - 注解绑定,就是在接口的方法上面加上 @Select、@Update等注解,里面包含Sql语句来绑定; - 外一种就是通过xml里面写SQL来绑定, 在这种情况下,要指定xml映射文件里面的namespace必须为接口的全路径名。当Sql语句比较简单时候,用注解绑定, 当SQL语句比较复杂时候,用xml绑定,一般用xml绑定的比较多。 ### 使用MyBatis的mapper接口调用时有哪些要求? - Mapper接口方法名和mapper.xml中定义的每个sql的id相同; - Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同; - Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同; - Mapper.xml文件中的namespace即是mapper接口的类路径。 ### mybatis是如何防止SQL注入的? **首先看一下下面两个sql语句的区别:** ```xml <select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap" select id, username, password, role from user where username = #{username,jdbcType=VARCHAR} and password = #{<PASSWORD>,jdbcType=VARCHAR} </select ``` ```xml <select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap" select id, username, password, role from user where username = ${username,jdbcType=VARCHAR} and password = ${<PASSWORD>,jdbcType=VARCHAR} </select ``` **mybatis中的#和$的区别:** - `#`将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。 如:`where username=#{username}`,如果传入的值是111,那么解析成sql时的值为`where username="111"`, 如果传入的值是id,则解析成的sql为`where username="id"`.  - `$`将传入的数据直接显示生成在sql中。如:`where username=${username}`,如果传入的值是111,那么解析成sql时的值为`where username=111`;如果传入的值是:`drop table user;`,则解析成的sql为:`select id, username, password, role from user where username=;drop table user`; - `#`方式能够很大程度防止sql注入,`$`方式无法防止Sql注入。 - `$`方式一般用于传入数据库对象,例如传入表名. - 一般能用`#`的就别用`$`,若不得不使用`“${xxx}”`这样的参数,要手工地做好过滤工作,来防止sql注入攻击。 - 在MyBatis中,`“${xxx}”`这样格式的参数会直接参与SQL编译,从而不能避免注入攻击。但涉及到动态表名和列名时,只能使用`“${xxx}”`这样的参数格式。所以,这样的参数需要我们在代码中手工进行处理来防止注入。 **sql注入**: **SQL注入**,大家都不陌生,是一种常见的攻击方式。**攻击者**在界面的表单信息或URL上输入一些奇怪的SQL片段(例如“or ‘1’=’1’”这样的语句),有可能入侵**参数检验不足**的应用程序。所以,在我们的应用中需要做一些工作,来防备这样的攻击方式。在一些安全性要求很高的应用中(比如银行软件),经常使用将**SQL语句**全部替换为**存储过程**这样的方式,来防止SQL注入。这当然是**一种很安全的方式**,但我们平时开发中,可能不需要这种死板的方式。 **mybatis是如何做到防止sql注入的** MyBatis框架作为一款半自动化的持久层框架,其SQL语句都要我们自己手动编写,这个时候当然需要防止SQL注入。其实,MyBatis的SQL是一个具有“**输入+输出**”的功能,类似于函数的结构,参考上面的两个例子。其中,parameterType表示了输入的参数类型,resultType表示了输出的参数类型。回应上文,如果我们想防止SQL注入,理所当然地要在输入参数上下功夫。上面代码中使用#的即输入参数在SQL中拼接的部分,传入参数后,打印出执行的SQL语句,会看到SQL是这样的: ```sql select id, username, password, role from user where username=? and password=? ``` 不管输入什么参数,打印出的SQL都是这样的。这是因为MyBatis启用了预编译功能,在SQL执行前,会先将上面的SQL发送给数据库进行编译;执行时,直接使用编译好的SQL,替换占位符“?”就可以了。因为SQL注入只能对编译过程起作用,所以这样的方式就很好地避免了SQL注入的问题。 [底层实现原理]MyBatis是如何做到SQL预编译的呢?其实在框架底层,是JDBC中的PreparedStatement类在起作用,PreparedStatement是我们很熟悉的Statement的子类,它的对象包含了编译好的SQL语句。这种“准备好”的方式不仅能提高安全性,而且在多次执行同一个SQL时,能够提高效率。原因是SQL已编译好,再次执行时无需再编译。 ```java //安全的,预编译了的 Connection conn = getConn();//获得连接 String sql = "select id, username, password, role from user where id=?"; //执行sql前会预编译号该条语句 PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); ResultSet rs=pstmt.executeUpdate(); ...... ``` ```java //不安全的,没进行预编译 private String getNameByUserId(String userId) { Connection conn = getConn();//获得连接 String sql = "select id,username,password,role from user where id=" + id; //当id参数为"3;drop table user;"时,执行的sql语句如下: //select id,username,password,role from user where id=3; drop table user; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs=pstmt.executeUpdate(); ...... } ``` **结论**: **\#{}**:相当于JDBC中的PreparedStatement **${}**:是输出变量的值 简单说,#{}是经过预编译的,是安全的;${}是未经过预编译的,仅仅是取变量的值,是非安全的,存在SQL注入。 > 创作不易哇,觉得有帮助的话,给个小小的star呗。[github地址](https://github.com/DreamCats/JavaBooks)😁😁😁<file_sep>package web; /** * @program LeetNiu * @description: 正则表达式匹配 * @author: mf * @create: 2020/01/16 14:03 */ /** * 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。 * 例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配 */ public class T52 { public boolean match(char[] str, char[] pattern) { if (str == null || pattern == null) { return false; } int strIndex = 0; int patternIndex = 0; return matchCore(str, strIndex, pattern, patternIndex); } public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) { // 有效性校验:str到尾, pattern到尾,匹配成功 if (strIndex == str.length && patternIndex == pattern.length) { return true; } // pattern 先到尾,匹配失败 if (strIndex != str.length && patternIndex == pattern.length) { return false; } // 模式第二个是*,且字符串第一个根模式第一个匹配,分三种匹配模式; // 如果不匹配,模式后移两 if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') { if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) { return matchCore(str, strIndex, pattern, patternIndex + 2) || matchCore(str, strIndex + 1, pattern, patternIndex + 2) || matchCore(str, strIndex + 1, pattern, patternIndex); } else { return matchCore(str, strIndex, pattern, patternIndex + 2); } } // 模式第二个不是*,且字符串第一个根模式第一个匹配,则都后移一位,否则直接返回false if ((strIndex != str.length && pattern[patternIndex] == str[strIndex])|| (pattern[patternIndex] == '.' && strIndex != str.length)) { return matchCore(str, strIndex + 1, pattern, patternIndex + 1); } return false; } } <file_sep>## 引言 > **一些有趣的github项目总结,其中包括终端、Python、Java、笔试&面试、效率软件等。** ## 终端 - [The Art of Command Line](<https://github.com/jlevy/the-art-of-command-line>) :系统的学习命令行的用法。**star:57509** - [oh-my-zsh](<https://github.com/robbyrussell/oh-my-zsh>): 这玩意不用我简单介绍了吧?**star:90516** - [git-tips](https://github.com/521xueweihan/git-tips) Git的奇技淫巧 **star:11400** - [powerline-fonts](<https://github.com/supermarin/powerline-fonts>) : mac挺好用的一款终端字体。**star:169** - [powerlevel9k](<https://github.com/bhilburn/powerlevel9k>) : oh-my-zsh的一款皮肤。**star:9952** - [zsh-syntax-highlighting](<https://github.com/zsh-users/zsh-syntax-highlighting>) : 终端输入的命令有语法高亮效果。**star:7326** - [zsh-autosuggestions](<https://github.com/zsh-users/zsh-autosuggestions>) : 终端代码补全插件。**star:6662** <!-- more --> ## Python - [awesome-python-login-model](<https://github.com/CriseLYJ/awesome-python-login-model>) : 模拟登陆一些大型网站的demo,个人觉得不错,值得学习。**star:8403** - [pyppeteer](<https://github.com/miyakogi/pyppeteer>) : 模拟动态加载js,比selenium稍微好用一些。**star:1924** - [requests](<https://github.com/psf/requests>) :Python HTTP Requests for Humans™ ✨🍰✨ **star:39860** - [requests-html](<https://github.com/psf/requests-html>) : Pythonic HTML Parsing for Humans™ **star:10111** - [httpx](<https://github.com/encode/httpx>) A next generation HTTP client for Python. 🦋 <https://www.encode.io/httpx> **star:1900** - [PySimpleGUI](<https://github.com/PySimpleGUI/PySimpleGUI>) : 做一些简单的GUI,可以用这个,简单应用。**star:1608** - [bokeh](<https://github.com/bokeh/bokeh>) Interactive Web Plotting for Python。 **star:10701** - [wxpy](<https://github.com/youfou/wxpy>) 微信机器人 / 可能是最优雅的微信个人号 API ✨✨ [http://wxpy.readthedocs.io](http://wxpy.readthedocs.io/) **star:10700** ## Java - [Awesome Java](<https://github.com/akullpp/awesome-java>) A curated list of awesome frameworks, libraries and software for the Java programming language. **star:21651** ### 1. 后端 - [spring-boot-examples](<https://github.com/ityouknow/spring-boot-examples>) : 对于初学者学习Spring-boot,是个非常不错的例子。**star:16408** - [SpringAll](<https://github.com/wuyouzhuguli/SpringAll>)循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Cloud、Spring Security & Spring Security OAuth2,博客Spring系列源码。**star:6181** - [interest](<https://github.com/Big-Chinese-Cabbage/interest>) : Vue+Spring boot前后端分离博客项目。**star:494** - [litemall](<https://github.com/linlinjava/litemall>) : 一个小商城。litemall = Spring Boot后端 + Vue管理员前端 + 微信小程序用户前端 + Vue用户移动端。**star:7586** - [vhr](<https://github.com/lenve/vhr>)微人事是一个前后端分离的人力资源管理系统,项目采用SpringBoot+Vue开发。**star:4705** - [mybatis](<https://github.com/mybatis/mybatis-3>) MyBatis SQL mapper framework for Java **star:11335** - [miaosha](<https://github.com/qiurunze123/miaosha>) ⭐⭐⭐⭐秒杀系统设计与实现.互联网工程师进阶与分析🙋🐓 **star:9400** - [spring-boot-plus](<https://github.com/geekidea/spring-boot-plus>)🔥spring-boot-plus集成Spring Boot 2.1.6,Mybatis,Mybatis Plus,Druid,FastJson,Redis,Rabbit MQ,Kafka等,可使用代码生成器快速开发项目. **star:551** - [hope-boot](<https://github.com/hope-for/hope-boot>) 🌱🚀一款现代化的脚手架项目。🍻整合Springboot2 **star:1543** - [spring-boot-demo](<https://github.com/xkcoding/spring-boot-demo>) spring boot demo 是一个用来学习 spring boot 的项目,总共包含 57 个集成demo,已经完成 47 个。**star:2149** - [spring-boot-api-project-seed](<https://github.com/lihengming/spring-boot-api-project-seed>) 🌱🚀一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目~ **star:1543** - [White-Jotter](<https://github.com/Antabot/White-Jotter>): 白卷是一款使用 Vue+Spring Boot 开发的前后端分离的图书管理项目 **star:115** - [eladmin](<https://github.com/elunez/eladmin>) 项目基于 Spring Boot 2.1.0 、 Jpa、 Spring Security、redis、Vue的前后端分离的后台管理系统,项目采用分模块开发方式, 权限控制采用 RBAC,支持数据字典与数据权限管理,支持一键生成前后端代码,支持动态路由 **start:3163** - [dbblog](<https://github.com/llldddbbb/dbblog>) 基于SpringBoot2.x+Vue2.x+ElementUI+Iview+Elasticsearch+RabbitMQ+Redis+Shiro的多模块前后端分离的博客项目 **star:375** - [spring-analysis](<https://github.com/seaswalker/spring-analysis>) Spring源码阅读 **star:4045** - [mall](<https://github.com/macrozheng/mall>) mall项目是一套电商系统,包括前台商城系统及后台管理系统,基于SpringBoot+MyBatis实现。**star:21926** - [后端架构师技术图谱](https://github.com/xingshaocheng/architect-awesome) **star:42900** - [mall-swarm](https://github.com/macrozheng/mall-swarm)mall-swarm是一套微服务商城系统,采用了 Spring Cloud Greenwich、Spring Boot 2、MyBatis、Docker、Elasticsearch等核心技术,同时提供了基于Vue的管理后台方便快速搭建系统。**star:1400** - [jeecg-boot](https://github.com/zhangdaiscott/jeecg-boot)一款基于代码生成器的JAVA快速开发平台,开源界“小普元”超越传统商业企业级开发平台!**star:9600** - [dbblog](https://github.com/llldddbbb/dbblog) 基于SpringBoot2.x+Vue2.x+ElementUI+Iview+Elasticsearch+RabbitMQ+Redis+Shiro的多模块前后端分离的博客项目 [http://www.dblearn.cn](http://www.dblearn.cn/) **star:643** - [ springboot-seckill](https://github.com/zaiyunduan123/springboot-seckill) 基于SpringBoot + MySQL + Redis + RabbitMQ + Guava开发的高并发商品限时秒杀系统 **star:943** - [MeetingFilm](https://github.com/daydreamdev/MeetingFilm)基于微服务架构的在线电影购票平台 **star:111** - [guava](https://github.com/google/guava) Google core libraries for Java **star:36400** - [hutool](https://github.com/looly/hutool) A set of tools that keep Java sweet. [http://www.hutool.cn](http://www.hutool.cn/) **star:10800** ### 2. 笔试&&面试 - [JavaGuide](<https://github.com/Snailclimb/JavaGuide>) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159** - [advanced-java](<https://github.com/doocs/advanced-java>) :互联网 Java 工程师进阶知识完全扫盲:涵盖高并发、分布式、高可用、微服务等领域知识,后端同学必看,前端同学也可学习。**star:22747** - [LeetCodeAnimation](<https://github.com/MisterBooo/LeetCodeAnimation>) : LeetCode用动画的形式的呈现。**star:32650** - [technology-talk](<https://github.com/aalansehaiyang/technology-talk>) 汇总java生态圈常用技术框架等。**star:6229** - [interview_internal_reference](<https://github.com/0voice/interview_internal_reference>) 2019年最新总结,阿里,腾讯,百度,美团,头条等技术面试题目,以及答案,专家出题人分析汇总。 **star:14335** - [interviews](<https://github.com/kdn251/interviews>) Everything you need to know to get the job. **star:37598** - [interview_internal_reference](<https://github.com/0voice/interview_internal_reference>)2019年最新总结,阿里,腾讯,百度,美团,头条等技术面试题目,以及答案,专家出题人分析汇总。 **star:15570** - [leetcode](<https://github.com/azl397985856/leetcode>) LeetCode Solutions: A Record of My Problem Solving Journey.( leetcode题解,记录自己的leetcode解题之路。) - [reverse-interview-zh](<https://github.com/yifeikong/reverse-interview-zh>) 技术面试最后反问面试官的话 **star:4500** - [algo](https://github.com/wangzheng0822/algo) 数据结构和算法必知必会的50个代码实现 **star:10700** - [fucking-algorithm](https://github.com/labuladong/fucking-algorithm) 手把手撕LeetCode题目,扒各种算法套路的裤子,not only how,but also why. English version supported! https://labuladong.gitbook.io/algo/ **star:4700** - [JavaFamily](https://github.com/AobingJava/JavaFamily)【互联网一线大厂面试+学习指南】进阶知识完全扫盲:涵盖高并发、分布式、高可用、微服务等领域知识,作者风格幽默,看起来津津有味,把学习当做一种乐趣,何乐而不为,后端同学必看,前端同学我保证你也看得懂,看不懂你加我微信骂我渣男就好了。 **star:7100** - [Java-Interview](https://github.com/gzc426/Java-Interview) Java 面试必会 直通BAT **star:3500** ## Vue&&前端 - [awesome-vue](<https://github.com/vuejs/awesome-vue>) awesome things related to Vue.js **star:46634** - [vue-form-making](<https://github.com/GavinZhuLei/vue-form-making>)基于Vue的表单设计器,让表单开发简单而高效。 **star:1347** - [fe-interview](<https://github.com/haizlin/fe-interview>) 前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家)**star:6667** - [vue2-elm](<https://github.com/bailicangdu/vue2-elm>) 基于 vue2 + vuex 构建一个具有 45 个页面的大型单页面应用 **star:30300** - [Web](<https://github.com/qianguyihao/Web>) 前端入门和进阶学习笔记,超详细的Web前端学习图文教程。从零开始学前端,做一名精致的前端工程师。持续更新… **star:55300** - [javascript-algorithms](<https://github.com/trekhleb/javascript-algorithms>) Algorithms and data structures implemented in JavaScript with explanations and links to further readings **star:55277** - [nodebestpractices](<https://github.com/goldbergyoni/nodebestpractices>) ✅ The largest Node.js best practices list (September 2019) <https://twitter.com/nodepractices/> **star:35000** - [gods-pen](https://github.com/ymm-tech/gods-pen) 基于vue的高扩展在线网页制作平台,可自定义组件,可添加脚本,可数据统计。A mobile page builder/editor, similar with amolink. [https://godspen.ymm56.com](https://godspen.ymm56.com/) **star:1200** - [Daily-Interview-Question](https://github.com/Advanced-Frontend/Daily-Interview-Question) 我是木易杨,公众号「高级前端进阶」作者,每天搞定一道前端大厂面试题,祝大家天天进步,一年后会看到不一样的自己。**star:17000** ## 面试 - [CS-Notes](<https://github.com/CyC2018/CS-Notes>) : 技术面试必备基础知识、Leetcode 题解、Java、C++、Python、后端面试、操作系统、计算机网络、系统设计。**star:67433** ## Flutter - [Flutter_YYeTs](<https://github.com/popeyelau/Flutter_YYeTs>) : 基于Flutter的人人影视移动端。**star:233** - [Flutter-Notebook](<https://github.com/OpenFlutter/Flutter-Notebook>) 日更的FlutterDemo合集,今天你fu了吗 **star:3879** - [Best-Flutter-UI-Templates](<https://github.com/mitesh77/Best-Flutter-UI-Templates>) completely free for everyone. Its build-in Flutter Dart. **star:1261** ## 效率软件 - [frp](<https://github.com/fatedier/frp>) : 内网穿透,你懂的。**star:24539** - [musicbox](<https://github.com/darknessomi/musicbox>) : 网易云音乐命令行版本。**star:7601** - [motrix](<https://github.com/agalwood/Motrix>) : 配合百度云有着奇淫技巧。 **star:11098** - [Electronic WeChat](<https://github.com/geeeeeeeeek/electronic-wechat>) : 该项目虽然不再维护,但挺好用的(linux)。**star:12622** - [hexo](<https://github.com/hexojs/hexo>) : 搭建博客系统框架,挺好用。**star:26868** - [awesome-mac](<https://github.com/jaywcjlove/awesome-mac>)推荐的非常给力且实用。 **star:29814** - [蓝灯](<https://github.com/getlantern/download>) 免费的vpn。 **star:9520** - [LazyDocker](<https://github.com/jesseduffield/lazydocker>) The lazier way to manage everything docker. **star:10906** - [postwoman](<https://github.com/liyasthomas/postwoman>) 👽 API request builder - Helps you create your requests faster, saving you precious time on your development. **star:2190** - [x64dbg](<https://github.com/x64dbg/x64dbg>)An open-source x64/x32 debugger for windows. **star:34260** - [google-access-helper](<https://github.com/haotian-wang/google-access-helper>) 谷歌访问助手破解版 **star:3887** - [v2ray-core](<https://github.com/v2ray/v2ray-core>) A platform for building proxies to bypass network restrictions. **star:21444** - [v2rayN](<https://github.com/2dust/v2rayN>) vpn **star:1249** - [Alfred-collection](<https://github.com/msoedov/Alfred-collection>) A collection of all known Alfred3 workflows **star:411** - [RevokeMsgPatcher](https://github.com/huiyadanli/RevokeMsgPatcher) editor for WeChat/QQ/TIM - PC版微信/QQ/TIM防撤回补丁(我已经看到了,撤回也没用了) **star:1500** - [lx-music-desktop](https://github.com/lyswhut/lx-music-desktop) 一个基于 electron 的音乐软件 **star:1300** - [UnblockNeteaseMusic](https://github.com/nondanee/UnblockNeteaseMusic) Revive unavailable songs for Netease Cloud Music **star:7900** - [CodeVar](https://github.com/xudaolong/CodeVar) 生成可用的代码变量 (CodeVar that return u a better variable from Chinese to English . ) **star:684** ## 有趣 - [ChineseBQB](ChineseBQB)🇨🇳Chinese sticker pack,More joy / 中国表情包大集合,更欢乐 **star:2319** - [free-programming-books-zh_CN](<https://github.com/justjavac/free-programming-books-zh_CN>)📚 免费的计算机编程类中文书籍,欢迎投稿 **star:55296** - [freeCodeCamp](<https://github.com/freeCodeCamp/freeCodeCamp>) The [https://www.freeCodeCamp.org](https://www.freecodecamp.org/) open source codebase and curriculum. Learn to code for free together with millions of people. **star:304920** - [hosts](<https://github.com/googlehosts/hosts>) 镜像 **star:15582** - [free-api](<https://github.com/fangzesheng/free-api>) 收集免费的接口服务,做一个api的搬运工 **star:6000** - [fanhaodaquan](https://github.com/imfht/fanhaodaquan) 番号大全。 **star:1200* - [BullshitGenerator](https://github.com/menzi11/BullshitGenerator) Needs to generate some texts to test if my GUI rendering codes good or not. so I made this. **star:3700** - [howto-make-more-money](https://github.com/easychen/howto-make-more-money): 程序员如何优雅的挣零花钱 **star:8200** - [marktext](https://github.com/marktext/marktext) A simple and elegant markdown editor, available for Linux, macOS and Windows. [https://marktext.app](https://marktext.app/) **star:14800** - [FreePAC](https://github.com/xiaoming2028/FreePAC) 科学上网/梯子/自由上网/翻墙 SS/SSR/V2Ray/Brook 搭建教程 **star:2146** ## 持续更新...<file_sep>/** * @program JavaBooks * @description: ListNode * @author: mf * @create: 2020/03/06 18:39 */ package subject.linked; public class ListNode { int val; ListNode next = null; public ListNode(int val) { this.val = val; } } <file_sep>package web; /** * @program LeetNiu * @description: 序列化二叉树 * @author: mf * @create: 2020/01/17 21:13 */ /** * 请实现两个函数,分别用来序列化和反序列化二叉树 * 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。 * 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。 * 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。 */ public class T61 { String Serialize(TreeNode root) { if (null == root) { return ""; } StringBuffer sb = new StringBuffer(); Serialize2(root, sb); return sb.toString(); } void Serialize2(TreeNode root, StringBuffer sb) { if (null == root) { sb.append("#,"); return; } sb.append(root.val); sb.append(","); Serialize2(root.left, sb); Serialize2(root.right, sb); } int index = -1; TreeNode Deserialize(String str) { if (str.length() == 0) { return null; } String[] strings = str.split(","); return Deserialize2(strings); } TreeNode Deserialize2(String[] strings) { index++; if (!strings[index].equals("#")) { TreeNode root = new TreeNode(0); root.val = Integer.parseInt(strings[index]); root.left = Deserialize2(strings); root.right = Deserialize2(strings); return root; } return null; } } <file_sep>package books; /** * @program JavaBooks * @description: 替换空格 * @author: mf * @create: 2019/08/18 18:27 */ /* 请实现一个函数,把字符串中的每个空格替换成"%20",例如 输入"We are happy.",则输出"We%20are%20happy." */ public class T5 { public static void main(String[] args) { StringBuffer s = new StringBuffer("We are happy."); // String s1 = replaceSpace(s); String s1 = replaceSpace2(s); System.out.println(s1); } /** * 双指针,从后往前遍历即可 * @param str * @return */ public static String replaceSpace(StringBuffer str) { int spaceNum = 0; // 检测空格数目 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') spaceNum++; } char[] s1 = new char[str.length() + 2 * spaceNum]; // 新数组的长度 int p2 = s1.length - 1; // 定义新数组的指针 for (int i = str.length() - 1; i>= 0; i--) { // 从后往前遍历 if (str.charAt(i) == ' ') { s1[p2--] = '0'; s1[p2--] = '2'; s1[p2--] = '%'; } else { s1[p2--] = str.charAt(i); } } return new String(s1); } // 第二种方法,Stringbuffer的特性 public static String replaceSpace2(StringBuffer str) { StringBuffer s1 = new StringBuffer(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { s1.append("%20"); } else { s1.append(str.charAt(i)); } } return new String(s1); } } <file_sep>package com.basic; import java.util.Queue; import java.util.Random; import java.util.concurrent.*; /** * @program JavaBooks * @description: 利用容器LinkedBlockingQueue生产者消费者 * @author: mf * @create: 2019/12/31 22:26 */ public class T21 { // private static Queue<String> strs = new ConcurrentLinkedDeque<>(); // private static BlockingQueue<String> strs = new ArrayBlockingQueue<>(10); // 有界队列 // private static LinkedTransferQueue<String> strs = new LinkedTransferQueue<>(); // 更高的高并发,先找消费者 private static BlockingQueue<String> strs = new LinkedBlockingDeque<>(); // 无界队列 private static Random r = new Random(); public static void main(String[] args) { new Thread(() -> { for (int i = 0; i < 100; i++) { try { strs.put("a" + i); TimeUnit.MILLISECONDS.sleep(r.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }, "p1").start(); for (int i = 0; i < 5; i++) { new Thread(() -> { for (;;) { try { System.out.println(Thread.currentThread().getName() + " take -" + strs.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }, "c" + i).start(); } } } <file_sep>/** * @program JavaBooks * @description: 移动零 * @author: mf * @create: 2020/04/09 17:40 */ package subject.dpointer; /** * 输入: [0,1,0,3,12] * 输出: [1,3,12,0,0] */ public class T8 { public void moveZeroes(int[] nums) { // index记录什么开始填充0 int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) nums[index++] = nums[i]; } for (int i = index; i < nums.length; i++) { nums[i] = 0; } } } <file_sep>/** * @program JavaBooks * @description: 手写自旋锁 * 通过CAS操作完成自旋锁,A线程先进来调用mylock方法自己持有锁5秒钟,B随后进来发现当前有线程持有锁,不是null, * 所以只能通过自旋等待,知道A释放锁后B随后抢到 * @author: mf * @create: 2020/02/15 12:20 */ package com.juc.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class SpinLock { // 原子引用线程 AtomicReference<Thread> atomicReference = new AtomicReference<>(); public void mylock() { Thread thread = Thread.currentThread(); System.out.println(Thread.currentThread().getName() + " como in..."); while (!atomicReference.compareAndSet(null, thread)) { // System.out.println("不爽,重新获取一次值瞧瞧..."); } } public void myUnlock() { Thread thread = Thread.currentThread(); atomicReference.compareAndSet(thread, null); System.out.println(Thread.currentThread().getName() + " invoke myUnLock..."); } public static void main(String[] args) { SpinLock spinLock = new SpinLock(); new Thread(() -> { spinLock.mylock(); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } spinLock.myUnlock(); }, "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { spinLock.mylock(); spinLock.myUnlock(); }, "t2").start(); } } <file_sep>> 毕竟Redis还是挺热门的缓存中间件,得好好学习一下子,在高并发的场景当中,也用的比较多,面试也是常问的点。 ## 大纲图 ![Redis常见面试](http://media.dreamcat.ink/uPic/Redis常见面试.png) ### Redis是什么 简单来说redis就是一个**数据库**,不过与传统数据库不同的是redis的数据库是存在**内存**中,所以**读写速度非常快**,因此redis被广泛应用于**缓存**方向。另外,redis也经常用来做**分布式锁**,redis提供了多种数据类型来支持不同的业务场景。除此之外,**redis 支持事务** 、**持久化**、**LUA脚本**、**LRU驱动事件**、**多种集群**方案。 ### 为什么要用Redis 1. **高性能**:假如用户第一次访问数据库中的某些数据。这个过程会比较慢,因为是从**硬盘上读取**的。将该用户访问的**数据存在缓存**中,这样下一次再访问这些数据的时候就可以直接从缓存中获取了。操**作缓存就是直接操作内存,所以速度相当快**。如果数据库中的对应数据改变的之后,同步改变缓存中相应的数据即可! 2. **高并发**:**直接操作缓存能够承受的请求是远远大于直接访问数据库的**,所以我们可以考虑把数据库中的部分数据转移到缓存中去,这样用户的一部分请求会直接到缓存这里而不用经过数据库。 ### 使用Redis有哪些好处 1. **速度快**,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1) 2. 支持丰富数据类型,支持**string,list,set,sorted set,hash** 3. **支持事务**,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行 4. 丰富的特性:**可用于缓存,消息,按key设置过期时间,过期后将会自动删除** 5. 等等... ### 为什么要用Redis而不用map/guava做缓存 缓存分为**本地缓存**和**分布式缓存**。以 Java 为例,使用自带的 **map 或者 guava 实现的是本地缓存**,最主要的特点是**轻量以及快速,生命周期随着 jvm 的销毁而结束,并且在多实例的情况下,每个实例都需要各自保存一份缓存,缓 存不具有一致性。** 使用 **redis 或 memcached 之类的称为分布式缓存**,在多实例的情况下,各实例共用一份缓存数据,**缓存具有一致 性**。缺点是需要保持 **redis 或 memcached服务的高可用**,整个程序架构上较为复杂。 ### Redis相比Memcached有哪些优势 1. memcached所有的值**均是简单的字符串**,redis作为其替代者,支持更为**丰富的数据类型** 2. redis的速度比memcached**快**很多 3. redis可以**持久化**其数据 ### Redis的线程模型 redis 内部使用文件事件处理器 `file event handler`,这个文件事件处理器是**单线程**的,所以 redis 才叫做**单线程的模型**。它采用 **IO 多路复用机制**同时监听多个 socket,根据 socket 上的事件来**选择对应的事件处理器**进行处理。 文件事件处理器的结构包含 4 个部分: - 多个 socket - IO多路复用程序 - 文件事件分派器 - 事件处理器(连接应答处理器、命令请求处理器、命令回复处理器) 多个 socket 可能会**并发产生不同的操作**,每个操作对应不同的文件事件,但是 IO 多路复用程序会监听多个 socket,会将 socket 产生的**事件放入队列中排队**,事件分派器每次从队列中取出一个事件,把该事件交给对应的**事件处理器**进行处理。 ### Redis常见性能问题和解决方案 1. Master最好不要做任何持久化工作,如RDB内存快照和AOF日志文件 2. 如果数据比较重要,某个Slave开启AOF备份数据,策略设置为每秒同步一次 3. 为了主从复制的速度和连接的稳定性,Master和Slave最好在同一个局域网内 4. 尽量避免在压力很大的主库上增加从库 5. 主从复制不要用图状结构,用单向链表结构更为稳定,即:Master <- Slave1 <- Slave2 <- Slave3... ### Redis常见数据结构以及使用场景分析 #### String > 常用命令: set,get,decr,incr,mget 等。 String数据结构是简单的key-value类型,value其实不仅可以是String,也可以是数字。 常规key-value缓存应用; 常规计数:微博数,粉丝数等。 #### Hash > 常用命令: hget,hset,hgetall 等。 Hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象,后续操作的时候,你可以直接仅 仅修改这个对象中的某个字段的值。 比如我们可以Hash数据结构来存储用户信息,商品信息等等。 #### List > 常用命令: lpush,rpush,lpop,rpop,lrange等 list 就是链表,Redis list 的应用场景非常多,也是Redis最重要的数据结构之一,比如微博的关注列表,粉丝列表, 消息列表等功能都可以用Redis的 list 结构来实现。 Redis list 的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销。 另外可以通过 lrange 命令,就是从某个元素开始读取多少个元素,可以基于 list 实现分页查询,这个很棒的一个功 能,基于 redis 实现简单的高性能分页,可以做类似微博那种下拉不断分页的东西(一页一页的往下走),性能高。 #### Set > 常用命令: sadd,spop,smembers,sunion 等 set 对外提供的功能与list类似是一个列表的功能,特殊之处在于 set 是可以自动排重的。 当你需要存储一个列表数据,又不希望出现重复数据时,set是一个很好的选择,并且set提供了判断某个成员是否在 一个set集合内的重要接口,这个也是list所不能提供的。可以基于 set 轻易实现交集、并集、差集的操作。 比如:在微博应用中,可以将一个用户所有的关注人存在一个集合中,将其所有粉丝存在一个集合。Redis可以非常 方便的实现如共同关注、共同粉丝、共同喜好等功能。这个过程也就是求交集的过程,具体命令如下:`sinterstore key1 key2 key3`将交集存在key1内 #### Sorted Set > 常用命令: zadd,zrange,zrem,zcard等 和set相比,sorted set增加了一个权重参数score,使得集合中的元素能够按score进行有序排列。 举例: 在直播系统中,实时排行信息包含直播间在线用户列表,各种礼物排行榜,弹幕消息(可以理解为按消息维 度的消息排行榜)等信息,适合使用 Redis 中的 SortedSet 结构进行存储。 ### Redis设置过期时间 Redis中有个设置时间过期的功能,即对存储在 redis 数据库中的值可以设置一个过期时间。作为一个缓存数据库, 这是非常实用的。如我们一般项目中的 token 或者一些登录信息,尤其是短信验证码都是有时间限制的,按照传统 的数据库处理方式,一般都是自己判断过期,这样无疑会严重影响项目性能。 我们 set key 的时候,都可以给一个 expire time,就是过期时间,通过过期时间我们可以指定这个 key 可以存活的 时间。 #### 定期删除+惰性删除 - 定期删除:redis默认是每隔 100ms 就随机抽取一些设置了过期时间的key,检查其是否过期,如果过期就删 除。注意这里是随机抽取的。为什么要随机呢?你想一想假如 redis 存了几十万个 key ,每隔100ms就遍历所 有的设置过期时间的 key 的话,就会给 CPU 带来很大的负载! - 惰性删除 :定期删除可能会导致很多过期 key 到了时间并没有被删除掉。所以就有了惰性删除。假如你的过期 key,靠定期删除没有被删除掉,还停留在内存里,除非你的系统去查一下那个 key,才会被redis给删除掉。这 就是所谓的惰性删除,也是够懒的哈! 如果定期删除漏掉了很多过期 key,然后你也没及时去查, 也就没走惰性删除,此时会怎么样?如果大量过期key堆积在内存里,导致redis内存块耗尽了。怎么解决这个问题 呢? **redis 内存淘汰机制。** ### Mysql有2000万数据,redis只存20万,如何保证redis中的数据都是热点数据 redis 内存数据集大小上升到一定大小的时候,就会施行数据淘汰策略。redis 提供 6种数据淘汰策略: - voltile-lru:从已设置过期时间的数据集(server.db[i].expires)中挑选最近最少使用的数据淘汰 - volatile-ttl:从已设置过期时间的数据集(server.db[i].expires)中挑选将要过期的数据淘汰 - volatile-random:从已设置过期时间的数据集(server.db[i].expires)中任意选择数据淘汰 - allkeys-lru:从数据集(server.db[i].dict)中挑选最近最少使用的数据淘汰 - allkeys-random:从数据集(server.db[i].dict)中任意选择数据淘汰 - no-enviction(驱逐):禁止驱逐数据 ### Memcache与Redis的区别都有哪些 1. 存储方式 1. Memecache把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小。 2. Redis有部份存在硬盘上,这样能保证数据的持久性。 2. 数据支持类型 1. Memcache对数据类型支持相对简单。String 2. Redis有复杂的数据类型。Redis不仅仅支持简单的k/v类型的数据,同时还提供 list,set,zset,hash等数据结构的存储。 3. 使用底层模型不同 1. 它们之间底层实现方式 以及与客户端之间通信的应用协议不一样。 2. Redis直接自己构建了VM 机制 ,因为一般的系统调用系统函数的话,会浪费一定的时间去移动和请求。 4. 集群模式 memcached没有原生的集群模式,需要依靠客户端来实现往集群中分片写入数据;但是 redis 目前 是原生支持 cluster 模式的. 5. Memcached是多线程,非阻塞IO复用的网络模型;Redis使用单线程的多路 IO 复用模型。 ### Redis持久化机制 很多时候我们需要持久化数据也就是将内存中的数据写入到硬盘里面,大部分原因是为了之后重用数据(比如重启机 器、机器故障之后回复数据),或者是为了防止系统故障而将数据备份到一个远程位置。 Redis不同于Memcached的很重一点就是,**Redis支持持久化**,而且支持两种不同的持久化操作。Redis的一种持久化方式叫**快照(snapshotting,RDB)**,另一种方式是**只追加文件(append-only file,AOF)**.这两种方法各有千 秋,下面我会详细这两种持久化方法是什么,怎么用,如何选择适合自己的持久化方。 #### 快照(snapshotting)持久化(RDB) Redis可以通过创建快照来获得存储在内存里面的数据在某个时间点上的副本。Redis创建快照之后,可以对快照进行 备份,可以将快照复制到其他服务器从而创建具有相同数据的服务器副本(Redis主从结构,主要用来提高Redis性 能),还可以将快照留在原地以便重启服务器的时候使用。 快照持久化是Redis默认采用的持久化方式,在redis.conf配置文件中默认有此下配置: ```shell save 900 1 #在900秒(15分钟)之后,如果至少有1个key发生变化,Redis就会自动触发BGSAVE命令 创建快照。 save 300 10 #在300秒(5分钟)之后,如果至少有10个key发生变化,Redis就会自动触发BGSAVE命令创建快照。 save 60 10000 #在60秒(1分钟)之后,如果至少有10000个key发生变化,Redis就会自动触发BGSAVE命令创建快照。 ``` #### AOF(append-only file)持久化 与快照持久化相比,AOF**持久化的实时性更好**,因此已成为主流的持久化方案。默认情况下Redis没有开启 AOF(append only file)方式的持久化,可以通过appendonly参数开启:`appendonly yes` 开启AOF持久化后每执行一条会更改Redis中的数据的命令,Redis就会将该命令写入硬盘中的AOF文件。AOF文件的 保存位置和RDB文件的位置相同,都是通过dir参数设置的,默认的文件名是appendonly.aof。 在Redis的配置文件中存在三种不同的 AOF 持久化方式,它们分别是: ```shell appendfsync always #每次有数据修改发生时都会写入AOF文件,这样会严重降低Redis的速度 appendfsync everysec #每秒钟同步一次,显示地将多个写命令同步到硬盘 appendfsync no #让操作系统决定何时进行同步 ``` 为了兼顾数据和写入性能,用户可以考虑 appendfsync everysec选项 ,让Redis每秒同步一次AOF文件,Redis性能 几乎没受到任何影响。而且这样即使出现系统崩溃,用户最多只会丢失一秒之内产生的数据。当硬盘忙于执行写入操 作的时候,Redis还会优雅的放慢自己的速度以便适应硬盘的最大写入速度。 **Redis 4.0 对于持久化机制的优化** Redis 4.0 开始支持 RDB 和 AOF 的混合持久化(默认关闭,可以通过配置项 aof-use-rdb-preamble 开启)。 如果把混合持久化打开,AOF 重写的时候就直接把 RDB 的内容写到 AOF 文件开头。这样做的好处是可以结合 RDB 和 AOF 的优点, 快速加载同时避免丢失过多的数据。当然缺点也是有的, AOF 里面的 RDB 部分是压缩格式不再是 AOF 格式,可读性较差。 ### AOF重写 AOF重写可以产生一个新的AOF文件,这个新的AOF文件和原有的AOF文件所保存的数据库状态一样,**但体积更小**。 AOF重写是一个有歧义的名字,该功能是通过读取数据库中的**键值**对来实现的,程序无须对现有AOF文件进行任伺读 入、分析或者写入操作。 在执行 BGREWRITEAOF 命令时,Redis 服务器会维护一个 AOF **重写缓冲区**,该缓冲区会在子进程创建新AOF文件期 间,记录服务器执行的所有写命令。**当子进程完成创建新AOF文件的工作之后,服务器会将重写缓冲区中的所有内容 追加到新AOF文件的末尾,使得新旧两个AOF文件所保存的数据库状态一致**。最后,服务器用新的AOF文件替换旧的 AOF文件,以此来完成AOF文件重写操作。 ### Redis事务 Redis 通过 MULTI、EXEC、WATCH 等命令来实现事务(transaction)功能。事务提供了一种**将多个命令请求打包,然 后一次性、按顺序地执行多个命令的机制,并且在事务执行期间,服务器不会中断事务而改去执行其他客户端的命令 请求,它会将事务中的所有命令都执行完毕**,然后才去处理其他客户端的命令请求。 在传统的关系式数据库中,常常用 ACID 性质来检验事务功能的可靠性和安全性。在 Redis 中,事务**总是**具有原子性 (Atomicity)、一致性(Consistency)和隔离性(Isolation),并且当 Redis 运行在某种特定的持久化模式下时,事务 也具有持久性(Durability)。 ### Redis常见的性能问题都有哪些?如何解决? 1. Master写内存快照,save命令调度rdbSave函数,会阻塞主线程的工作,当快照比较大时对性能影响是非常大的,会间断性暂停服务,所以Master最好不要写内存快照。 2. Master AOF持久化,如果不重写AOF文件,这个持久化方式对性能的影响是最小的,但是AOF文件会不断增大,AOF文件过大会影响Master重启的恢复速度。Master最好不要做任何持久化工作,包括内存快照和AOF日志文件,特别是不要启用内存快照做持久化,如果数据比较关键,某个Slave开启AOF备份数据,策略为每秒同步一次。 3. Master调用BGREWRITEAOF重写AOF文件,AOF在重写的时候会占大量的CPU和内存资源,导致服务load过高,出现短暂服务暂停现象。 4. Redis主从复制的性能问题,为了主从复制的速度和连接的稳定性,Slave和Master最好在同一个局域网内 ### Redis的同步机制了解吗? 主从同步。第一次同步时,**主节点做一次bgsave**,并同时将后续修改操作记录到**内存buffer**,待完成后**将rdb文件全量同步到复制节点**,复制节点接受完成后**将rdb镜像加载到内存**。加载完成后,再通知主节点**将期间修改的操作记录同步到复制节点进行重放**就完成了同步过程。 ### 是否使用Redis集群,集群的原理是什么 Redis Sentinel着眼于高可用,在master宕机时会自动将slave提升为master,继续提供服务。 Redis Cluster着眼于扩展性,在单个redis内存不足时,使用Cluster进行分片存储。 ### 缓存雪崩和缓存问题解决方案 #### 缓存雪崩 缓存同一时间大面积的失效,所以,后面的请求都会落到数据库上,造成数据库短时间内承受大量请求而崩 掉。 - 事前:尽量保证整个 redis 集群的高可用性,发现机器宕机尽快补上。选择合适的内存淘汰策略。 - 事中:本地ehcache缓存 + hystrix限流&降级,避免MySQL崩掉 - 事后:利用 redis 持久化机制保存的数据尽快恢复缓存 #### 缓存穿透 一般是黑客故意去请求缓存中不存在的数据,导致所有的请求都落到数据库上,造成数据库短时间内承受大量 请求而崩掉。 解决办法: 有很多种方法可以有效地解决缓存穿透问题,最常见的则是采用布隆过滤器,将所有可能存在的数据哈 希到一个足够大的**bitmap**中,一个一定不存在的数据会被 这个bitmap拦截掉,从而避免了对底层存储系统的查询压 力。另外也有一个更为简单粗暴的方法(我们采用的就是这种),如果一个**查询返回的数据为空**(不管是数据不存 在,还是系统故障),我们仍然把这个空结果进行缓存,但它的**过期时间会很短**,最长不超过五分钟。 ### 如何解决Redis的并发竞争Key问题 所谓 Redis 的并发竞争 Key 的问题也就是多个系统同时对一个 key 进行操作,但是最后执行的顺序和我们期望的顺 序不同,这样也就导致了结果的不同! 推荐一种方案:分布式锁(zookeeper 和 redis 都可以实现分布式锁)。(如果不存在 Redis 的并发竞争 Key 问 题,不要使用分布式锁,这样会影响性能) 基于zookeeper临时有序节点可以实现的分布式锁。大致思想为:每个客户端对某个方法加锁时,在zookeeper上的 与该方法对应的指定节点的目录下,生成一个唯一的瞬时有序节点。 判断是否获取锁的方式很简单,只需要判断有 序节点中序号最小的一个。 当释放锁的时候,只需将这个瞬时节点删除即可。同时,其可以避免服务宕机导致的锁 无法释放,而产生的死锁问题。完成业务流程后,删除对应的子节点释放锁。 在实践中,当然是从以可靠性为主。所以首推Zookeeper。 ### 如何保证缓存与数据库双写时的数据一致性 你只要用缓存,就可能会涉及到缓存与数据库双存储双写,你只要是双写,就一定会有数据一致性的问题,那么你如 何解决一致性问题? 一般来说,就是如果你的系统不是严格要求缓存+数据库必须一致性的话,缓存可以稍微的跟数据库偶尔有不一致的 情况,最好不要做这个方案,读请求和写请求串行化,串到一个内存队列里去,这样就可以保证一定不会出现不一致 的情况 串行化之后,就会导致系统的吞吐量会大幅度的降低,用比正常情况下多几倍的机器去支撑线上的一个请求。<file_sep>## 1. 准备工作 - vps(云服务器一台) - 访问目标设备(就是你最终要访问的设备) - 简单的Linux基础(会用cp等几个简单命令即可) <!-- more --> ## 2. 下载frp - [frp-github](<https://github.com/fatedier/frp>) - 选择release中对应的版本 - 比如linux:[frp_0.27.0_linux_amd64.tar.gz](https://github.com/fatedier/frp/releases/download/v0.27.0/frp_0.27.0_linux_amd64.tar.gz) ## 3. 配置frp ### 1. 简单介绍 - frps(服务端启动) - frps.ini(服务器启动配置文件) - frpc(客户端启动) - frpc.ini(客户端启动配置文件) - 配置前先备份哦`cp` ### 2. 服务端 1. `vim frps.ini` 2. 有以下内容 ```shell [common] bind_port = 7000 dashboard_port = 7500 token = <PASSWORD> dashboard_user = admin dashboard_pwd = <PASSWORD> ``` - “bind_port”表示用于客户端和服务端连接的端口,这个端口号我们之后在配置客户端的时候要用到。 - “dashboard_port”是服务端仪表板的端口,若使用7500端口,在配置完成服务启动后可以通过浏览器访问 x.x.x.x:7500 (其中x.x.x.x为VPS的IP)查看frp服务运行信息。 - “token”是用于客户端和服务端连接的口令,请自行设置并记录,稍后会用到。 - “dashboard_user”和“dashboard_pwd”表示打开仪表板页面登录的用户名和密码,自行设置即可。 3. `./frps -c frps.ini` 4. 若出现以下内容 ```shell 2019/01/12 15:22:39 [I] [service.go:130] frps tcp listen on 0.0.0.0:7000 2019/01/12 15:22:39 [I] [service.go:172] http service listen on 0.0.0.0:10080 2019/01/12 15:22:39 [I] [service.go:193] https service listen on 0.0.0.0:10443 2019/01/12 15:22:39 [I] [service.go:216] Dashboard listen on 0.0.0.0:7500 2019/01/12 15:22:39 [I] [root.go:210] Start frps success ``` - 此时访问 x.x.x.x:7500 并使用自己设置的用户名密码登录,即可看到仪表板界面 5. 后台运行`nohup ./frps -c frps.ini &` ### 3. 客户端 1. `vim frpc.ini` 2. 有以下内容 ```shell [common] server_addr = x.x.x.x # 服务器地址 server_port = 7000 # 和服务器端口对应 token = <PASSWORD> # 和服务器token对应 [ssh] type = tcp local_ip = 127.0.0.1 local_port = 22 remote_port = 2222 ``` - “server_addr”为服务端IP地址,填入即可。 - “server_port”为服务器端口,填入你设置的端口号即可,如果未改变就是7000 - “token”是你在服务器上设置的连接口令,原样填入即可。 3. `./frpc -c frpc.ini` 4. 后台运行如服务器同上 ## 映射web项目的端口 ### 服务端 `vim frps.ini` ```shell [common] bind_port = 6000 token = mai vhost_http_port = 2020 # 这里很重要哈 ``` `./frps -c frps.ini` ### 客户端 `vim frpc.ini` ```shell [common] server_addr = 39.108.xx.xxx server_port = 6000 token = mai #[ssh] #type = tcp #local_ip = 127.0.0.1 #local_port = 22 #remote_port = 6000 # 举例第一个 [web-flask] type = http local_port = 5000 custom_domains = flask.dreamcat.ink # 举例第二个 [web-flask2] type = http local_port = 5001 custom_domains = flask2.dreamcat.ink ``` `./frpc -c frpc.ini` **注意:custom_domains的域名需要去域名系统解析上述外网地址** **访问:flask.dreamcat.ink** **访问:flas2.dreamcat.ink** ## 4. 开机自启 ### 1. 第一种 最简单粗暴的方式直接在脚本`/etc/rc.d/rc.local`(和`/etc/rc.local`是同一个文件,软链)末尾添加自己的**脚本** 然后,增加脚本执行权限。 ```shell nohup /home/dsp/config/frp/frpc -c /home/dsp/config/frp/frpc.ini & ``` ```shell chmod +x /etc/rc.d/rc.local ``` ### 2. 第二种 ```shell crontab -e @reboot /home/user/test.sh ``` ### 每次登陆自动执行 也可以设置每次登录自动执行脚本,在`/etc/profile.d/`目录下新建sh脚本, `/etc/profile`会遍历`/etc/profile.d/*.sh` ### 第三种 **压缩包中有systemd,可利用这个服务开机自启** **比如,将frps.server复制到`etc/systemd/system/`** ```shell [Unit] Description=Frp Server Service After=network.target [Service] Type=simple User=nobody Restart=on-failure RestartSec=5s ExecStart=/usr/bin/frps -c /etc/frp/frps.ini ##这里记得对应的路径 [Install] WantedBy=multi-user.target ``` **接着可以利用systemd命令,比如** ```shell systemctl start frps #启动 systemctl stop frps #停止 systemctl restart frps #重启 systemctl status frps #查看状态 systemctl enable frps #开机启动frp systemctl disable frps # 禁止启动 ``` <file_sep>## 引言 **线性表-双指针** ### [26. 删除排序数组中的重复项](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/) <!-- more --> ``` 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 ``` ```java class Solution { public int removeDuplicates(int[] nums) { int p = 0; for(int i = 1; i < nums.length; i++) { if(nums[p] != nums[i]) { nums[++p] = nums[i]; } } return p+1; } } ``` ### [28. 实现 strStr()](https://leetcode-cn.com/problems/implement-strstr/) ```bash 输入: haystack = "hello", needle = "ll" 输出: 2 输入: haystack = "aaaaa", needle = "bba" 输出: -1 ``` ```java class Solution { public int strStr(String haystack, String needle) { if (needle.equals("")) return 0; char[] sChar = haystack.toCharArray(); char[] nChar = needle.toCharArray(); int s1 = 0, s2 = 0; int e1 = sChar.length - 1, e2 = nChar.length - 1; while (s1 <= e1) { if (sChar[s1] == nChar[s2]) { int k = s1; while (k <= e1 && s2 <= e2) { if (sChar[k] == nChar[s2]) { k++; s2++; } else { s2 = 0; break; } } if (k >= e1 && s2 <= e2) return -1; if (s2 > e2) return s1; } s1++; } return -1; } } ``` ### [88. 合并两个有序数组](https://leetcode-cn.com/problems/merge-sorted-array/) ```bash 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] ``` ```java class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { if(m == 0) { for(int i = 0; i < n; i++){ nums1[i] = nums2[i]; } return; } int p = nums1.length - 1; int a1 = m - 1; for(int i = n - 1; i >= 0; i--) { while(a1 >= 0 && nums1[a1] > nums2[i]) { nums1[p--] = nums1[a1--]; } nums1[p--] = nums2[i]; } } } ``` ### [125. 验证回文串](https://leetcode-cn.com/problems/valid-palindrome/) ```bash 输入: "A man, a plan, a canal: Panama" 输出: true 输入: "race a car" 输出: false ``` ```java class Solution { public boolean isPalindrome(String s) { if (s.equals("")) return true; s = s.toLowerCase(); char[] sChar = s.toCharArray(); int l = 0, r = sChar.length - 1; while (l <= r) { if (sChar[l] == sChar[r]) { l++; r--; } else if (!((sChar[l] >= 'a' && sChar[l] <= 'z') || (sChar[l] >= '0' && sChar[l] <= '9'))) { l++; } else if (!((sChar[r] >= 'a' && sChar[r] <= 'z') || (sChar[r] >= '0' && sChar[r] <= '9'))) { r--; } else { return false; } } return true; } } ``` ### [141. 环形链表](https://leetcode-cn.com/problems/linked-list-cycle/) ```java public class Solution { public boolean hasCycle(ListNode head) { if(head != null && head.next != null) { ListNode quick = head; ListNode slow = head; while(2 > 1) { quick = quick.next; if(quick == null) return false; quick = quick.next; if(quick == null) return false; slow = slow.next; if(slow == quick) return true; } } else { return false; } } } ``` ### [234. 回文链表](https://leetcode-cn.com/problems/palindrome-linked-list/) ```java class Solution { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) return true; // 找中点 ListNode slow = head, fast = head.next; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } if(fast != null) slow = slow.next; // cut cut(head, slow); // 比较 return isEqual(head, reverse(slow)); } public void cut (ListNode head, ListNode cutNode) { ListNode node = head; while(node.next != cutNode) { node = node.next; } node.next = null; } public ListNode reverse(ListNode head) { ListNode pre = null; ListNode cur = head; while(cur != null) { ListNode nextNode = cur.next; cur.next = pre; pre = cur; cur = nextNode; } return pre; } public boolean isEqual(ListNode l1, ListNode l2) { while(l1 != null && l2 != null) { if(l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } } ``` ### [283. 移动零](https://leetcode-cn.com/problems/move-zeroes/) ```java class Solution { public void moveZeroes(int[] nums) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { nums[index++] = nums[i]; } } for(int i = index; i < nums.length; i++) { nums[i] = 0; } } } ``` ### [344. 反转字符串](https://leetcode-cn.com/problems/reverse-string/) ```bash 输入:["h","e","l","l","o"] 输出:["o","l","l","e","h"] ``` ```java class Solution { public void reverseString(char[] s) { int p1 = 0, p2 = s.length - 1; while(p1 < p2 ){ swap(s, p1++, p2--); } } public void swap(char[] s, int i, int j) { char temp = s[i]; s[i] = s[j]; s[j] = temp; } } ``` <file_sep>/** * @program JavaBooks * @description: 反转链表 * @author: mf * @create: 2020/03/07 12:04 */ package subject.linked; /** * 1->2->3->4->5->NULL * NULL<-1<-2<-3<-4<-5 */ public class T3 { /** * 迭代 * 流程: * 核心还是双指针... * pre和cur一直移动 * 接着相互指向 * @param head * @return */ public ListNode reverseList(ListNode head) { ListNode pre = null; // 当前节点之前的节点 null ListNode cur = head; while (cur != null) { ListNode nextTemp = cur.next; // 获取当前节点的下一个节点 cur.next = pre; // 当前节点的下个节点指向前一个节点 // 尾递归其实省了下面这两步 pre = cur; // 将前一个节点指针移动到当前指针 cur = nextTemp; // 当当前节点移动到下一个节点 } return pre; } /** * 递归:尾递归 * @param head * @return */ public ListNode reverseList2(ListNode head) { return reverse(null, head); } public ListNode reverse(ListNode pre, ListNode cur) { if (cur == null) return pre; // 如果当前节点为null,直接返回 ListNode next = cur.next; // next节点指向当前节点的下一个节点 cur.next = pre; // 将当前节点指向 当前节点的前一个节点 return reverse(cur, next); } } <file_sep>package books; import java.util.ArrayList; import java.util.HashMap; /** * @program JavaBooks * @description: 数组中重复的数字 * @author: mf * @create: 2019/08/16 19:22 */ /* 在一个长度为n的数组中里的所有数字都在0~n-1的范围中。数组中某些数字是重复的, 但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复 的数字。例如,如果输入长度为7的数组{2, 3, 1, 0, 2, 5, 3},那么对应的输出 重复的数字2或者3 */ public class T3 { public static void main(String[] args) { int[] arr = {2, 3, 1, 0, 2, 5, 3}; // 第一种 可修改数组 ArrayList<Integer> helpList = duplication(arr); System.out.println(helpList); int[] arr1 = {2, 3, 1, 0, 2, 5, 3}; // 第二种,哈希表 -- 不可修改数组 ArrayList<Integer> helpList1 = duplication2(arr1); System.out.println(helpList1); // 刚才的第一种,可以添加辅助数组来解决不可修改数组的方案 // 或者用二分查找...以时间换空间... } /** * 可修改数组 * @param arr * @return */ public static ArrayList<Integer> duplication(int[] arr) { ArrayList<Integer> helpList = new ArrayList<>(); // 提高鲁棒性 for (int i : arr) { if (i < 0 || i > arr.length - 1) { System.out.println("arr is not true..."); break; } } // 核心步骤 for (int i = 0; i < arr.length; i++) { while (arr[i] != i) { if (arr[i] == arr[arr[i]]) { helpList.add(arr[i]); arr[i] = i; break; } swap(arr, arr[i], arr[arr[i]]); } } return helpList; } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /** * 哈希 * @param arr * @return */ public static ArrayList<Integer> duplication2(int[] arr) { HashMap<Integer, Integer> hashMap = new HashMap<>(); ArrayList<Integer> helpList = new ArrayList<>(); for (int i : arr) { if (hashMap.containsKey(i)) { helpList.add(i); } hashMap.put(i,i); } return helpList; } } <file_sep>package normal; /** * @program JavaBooks * @description: 7. 整数反转 * @author: mf * @create: 2019/11/10 14:49 */ /* 题目:https://leetcode-cn.com/problems/reverse-integer/ 难度:easy */ /* 输入: -123 输出: -321 */ public class Reverse { public static void main(String[] args) { System.out.println(reverse(-123)); } public static int reverse(int x) { long ans = 0; while (x != 0) { ans = ans * 10 + x % 10; x /= 10; } if (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) { return 0; } return (int) ans; } } <file_sep>## 美团到店一面 - [原文链接](https://www.nowcoder.com/discuss/411346) ### SpringBoot 对Spring的优化原理 - [参考博客](https://blog.csdn.net/qq_41855420/article/details/104207300) ### redis的五种数据类型 - String > 常用命令: set,get,decr,incr,mget 等。 String数据结构是简单的key-value类型,value其实不仅可以是String,也可以是数字。 常规key-value缓存应用; 常规计数:微博数,粉丝数等。 - Hash > 常用命令: hget,hset,hgetall 等。 Hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象,后续操作的时候,你可以直接仅 仅修改这个对象中的某个字段的值。 比如我们可以Hash数据结构来存储用户信息,商品信息等等。 - List > 常用命令: lpush,rpush,lpop,rpop,lrange等 list 就是链表,Redis list 的应用场景非常多,也是Redis最重要的数据结构之一,比如微博的关注列表,粉丝列表, 消息列表等功能都可以用Redis的 list 结构来实现。 Redis list 的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销。 另外可以通过 lrange 命令,就是从某个元素开始读取多少个元素,可以基于 list 实现分页查询,这个很棒的一个功 能,基于 redis 实现简单的高性能分页,可以做类似微博那种下拉不断分页的东西(一页一页的往下走),性能高。 - Set > 常用命令: sadd,spop,smembers,sunion 等 set 对外提供的功能与list类似是一个列表的功能,特殊之处在于 set 是可以自动排重的。 当你需要存储一个列表数据,又不希望出现重复数据时,set是一个很好的选择,并且set提供了判断某个成员是否在 一个set集合内的重要接口,这个也是list所不能提供的。可以基于 set 轻易实现交集、并集、差集的操作。 比如:在微博应用中,可以将一个用户所有的关注人存在一个集合中,将其所有粉丝存在一个集合。Redis可以非常 方便的实现如共同关注、共同粉丝、共同喜好等功能。这个过程也就是求交集的过程,具体命令如下:`sinterstore key1 key2 key3`将交集存在key1内 - Sorted Set > 常用命令: zadd,zrange,zrem,zcard等 和set相比,sorted set增加了一个权重参数score,使得集合中的元素能够按score进行有序排列。 举例: 在直播系统中,实时排行信息包含直播间在线用户列表,各种礼物排行榜,弹幕消息(可以理解为按消息维 度的消息排行榜)等信息,适合使用 Redis 中的 SortedSet 结构进行存储。 ### redis集群 > Redis集群是一个可以在多个 Redis 节点之间进行数据共享的设施(installation)。 Redis 集群不支持那些需要同时处理多个键的 Redis 命令, 因为执行这些命令需要在多个 Redis 节点之间移动数据, 并且在高负载的情况下, 这些命令将降低 Redis 集群的性能, 并导致不可预测的错误。 Redis 集群通过分区(partition)来提供一定程度的可用性(availability): 即使集群中有一部分节点失效或者无法进行通讯, 集群也可以继续处理命令请求。 Redis 集群提供了以下两个好处: - 将数据自动切分(split)到多个节点的能力。 - 当集群中的一部分节点失效或者无法进行通讯时, 仍然可以继续处理命令请求的能力。 ### redis持久化 Redis不同于Memcached的很重一点就是,Redis支持持久化,而且支持两种不同的持久化操作。Redis的一种持久化方式叫快照(snapshotting,RDB),另一种方式是只追加文件(append-only file,AOF).这两种方法各有千秋,下面我会详细这两种持久化方法是什么,怎么用,如何选择适合自己的持久化。 #### 快照 Redis可以通过创建快照来获得存储在内存里面的数据在某个时间点上的副本。Redis创建快照之后,可以对快照进行 备份,可以将快照复制到其他服务器从而创建具有相同数据的服务器副本(Redis主从结构,主要用来提高Redis性 能),还可以将快照留在原地以便重启服务器的时候使用。 #### AOF 与快照持久化相比,AOF持久化的实时性更好,因此已成为主流的持久化方案。 #### 4.0 Redis 4.0 开始支持 RDB 和 AOF 的混合持久化,如果把混合持久化打开,AOF 重写的时候就直接把 RDB 的内容写到 AOF 文件开头。这样做的好处是可以结合 RDB 和 AOF 的优点, 快速加载同时避免丢失过多的数据。当然缺点也是有的, AOF 里面的 RDB 部分是压缩格式不再是 AOF 格式,可读性较差。 ### B+树、红黑树 #### 红黑树 > 红黑树也是一种自平衡的二叉查找树。 - 每个结点要么是红的要么是黑的。(红或黑) - 根结点是黑的。 (根黑) - 每个叶结点(叶结点即指树尾端NIL指针或NULL结点)都是黑的。 (叶黑) - 如果一个结点是红的,那么它的两个儿子都是黑的。 (红子黑) - 对于任意结点而言,其到叶结点树尾端NIL指针的每条路径都包含相同数目的黑结点。(路径下黑相同) 应用场景: - Java ConcurrentHashMap & TreeMap - C++ STL: map & set - linux进程调度Completely Fair Scheduler,用红黑树管理进程控制块 - epoll在内核中的实现,用红黑树管理事件块 - nginx中,用红黑树管理timer等 #### B+树 B+ 树是一种树数据结构,通常用于关系型数据库(如Mysql)和操作系统的文件系统中。B+ 树的特点是能够保持数据稳定有序,其插入与修改拥有较稳定的对数时间复杂度。B+ 树元素自底向上插入,这与二叉树恰好相反。 在B树基础上,为叶子结点增加链表指针(B树+叶子有序链表),所有关键字都在叶子结点 中出现,非叶子结点作为叶子结点的索引;B+树总是到叶子结点才命中。 b+树的非叶子节点不保存数据,只保存子树的临界值(最大或者最小),所以同样大小的节点,b+树相对于b树能够有更多的分支,使得这棵树更加矮胖,查询时做的IO操作次数也更少。 ### 进程线程的区别 #### 进程 进程是程序的一次执行过程,是系统运行程序的基本单位,因此进程是动态的。系统运行一个程序即是一个进程从创建,运行到消亡的过程。 #### 线程 - 线程是一个比进程更小的执行单位 - 一个进程在其执行的过程中可以产生多个线程 - 与进程不同的是同类的多个线程共享进程的堆和方法区资源,但每个线程有自己的程序计数器、虚拟机栈和本地方法栈,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程 #### 线程切换为什么比进程切换开销小 多线程编程中一般线程的个数都大于 CPU 核心的个数,而一个 CPU 核心在任意时刻只能被一个线程使用,为了让这些线程都能得到有效执行,CPU 采取的策略是为每个线程分配时间片并轮转的形式。当一个线程的时间片用完的时候就会重新处于就绪状态让给其他线程使用,这个过程就属于一次上下文切换。 实际上就是任务从保存到再加载的过程就是一次上下文切换。 线程可以比作是轻量级的进程,是程序执行的最小单位,线程间的切换和调度的成本远远小于进程。另外,多核 CPU 时代意味着多个线程可以同时运行,这减少了线程上下文切换的开销。 ### 虚拟地址作用 有时如果程序量过大,存储器内存无法满足程序运行,而内存里某些物理地址是可以被一些不同的程序指令共用,因此为提高内存的利用,采用虚拟内存地址的思想 ### 地址栏输入URL会发生什么 - 根据域名,进行DNS域名解析; - 拿到解析的IP地址,建立TCP连接; - 向IP地址,发送HTTP请求; - 服务器处理请求; - 返回响应结果; - 关闭TCP连接; - 浏览器解析HTML; - 浏览器布局渲染; ### 数据从应用层到物理层过程 以HTTP数据为例 MAC头+IP头+TCP头+HTTP头+HTTP数据 - 一个数据从物理层发送到数据链路层,就是一个解密的过程。是由bit为单位发送的,也就是0001010100001这种数据。 - 到了数据链路层以后,把bit组合成字节,MAC地址就是一种,然后拆掉头部包尾部包,解校验序列。 - 到了网络层以后,再拆掉IP的头部包。 - 到了传输层后,再拆掉TCP包,数据就成功的到达了上层。 - 上层数据发送到下层就是反过来。 ## 二面 ### Spring里bean的线程安全问题 单例 bean 存在线程问题,主要是因为当多个线程操作同一个对象的时候,对这个对象的非静态成员变量的写操作会存在线程安全问题。 - 在Bean对象中尽量避免定义可变的成员变量(不太现实)。 - 在类中定义一个ThreadLocal成员变量,将需要的可变成员变量保存在 ThreadLocal 中(推荐的一种方式)。 ### java基本类型 8大类型:byte short int long char boolean float double ### 拆箱装箱 - 装箱:将基本类型用它们对应的引用类型包装起来; - 拆箱:将包装类型转换为基本数据类型; ### java运行原理 Java编译器 -> JVM虚拟机 -> 解释器(翻译) -> 机器码 ### 垃圾回收算法 - 标记-清除 该算法分为“标记”和“清除”阶段:首先标记出所有需要回收的对象,在标记完成后统一回收所有被标记的对象。它是最基础的收集算法,后续的算法都是对其不足进行改进得到。这种垃圾收集算法会带来两个明显的问题: - 效率问题 - 空间问题(标记清除后会产生大量不连续的碎片) - 标记-整理 根据老年代的特点提出的一种标记算法,标记过程仍然与“标记-清除”算法一样,但后续步骤不是直接对可回收对象回收,而是让所有存活的对象向一端移动,然后直接清理掉端边界以外的内存。 - 复制 为了解决效率问题,“复制”收集算法出现了。它可以将内存分为大小相同的两块,每次使用其中的一块。当这一块的内存使用完后,就将还存活的对象复制到另一块去,然后再把使用的空间一次清理掉。这样就使每次的内存回收都是对内存区间的一半进行回收。 - 分代收集 比如在新生代中,每次收集都会有大量对象死去,所以可以选择复制算法,只需要付出少量对象的复制成本就可以完成每次垃圾收集。而老年代的对象存活几率是比较高的,而且没有额外的空间对它进行分配担保,所以我们必须选择“标记-清除”或“标记-整理”算法进行垃圾收集。 ### G1,CMS收集器 #### CMS > CMS(Concurrent Mark Sweep)收集器是一种以获取最短回收停顿时间为目标的收集器。它非常符合在注重用户体验的应用上使用。 > CMS(Concurrent Mark Sweep)收集器是 HotSpot 虚拟机第一款真正意义上的并发收集器,它第一次实现了让垃圾收集线程与用户线程(基本上)同时工作。 CMS 收集器是一种 “标记-清除”算法实现的,它的运作过程相比于前面几种垃圾收集器来说更加复杂一些。整个过程分为四个步骤: - 初始标记: 暂停所有的其他线程,并记录下直接与 root 相连的对象,速度很快 ; - 并发标记: 同时开启 GC 和用户线程,用一个闭包结构去记录可达对象。但在这个阶段结束,这个闭包结构并不能保证包含当前所有的可达对象。因为用户线程可能会不断的更新引用域,所以 GC 线程无法保证可达性分析的实时性。所以这个算法里会跟踪记录这些发生引用更新的地方。 - 重新标记: 重新标记阶段就是为了修正并发标记期间因为用户程序继续运行而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段的时间稍长,远远比并发标记阶段时间短。 - 并发清除: 开启用户线程,同时 GC 线程开始对为标记的区域做清扫。 从它的名字就可以看出它是一款优秀的垃圾收集器,主要优点:并发收集、低停顿。但是它有下面三个明显的缺点: - 对 CPU 资源敏感; - 无法处理浮动垃圾; - 它使用的回收算法-“标记-清除”算法会导致收集结束时会有大量空间碎片产生。 G1收集器 #### G1 > G1 (Garbage-First) 是一款面向服务器的垃圾收集器,主要针对配备多颗处理器及大容量内存的机器. 以极高概率满足 GC 停顿时间要求的同时,还具备高吞吐量性能特征. - G1 (Garbage-First) 是一款面向服务器的垃圾收集器,主要针对配备多颗处理器及大容量内存的机器. 以极高概率满足 GC 停顿时间要求的同时,还具备高吞吐量性能特征. - 分代收集:虽然 G1 可以不需要其他收集器配合就能独立管理整个 GC 堆,但是还是保留了分代的概念。 - 空间整合:与 CMS 的“标记–清理”算法不同,G1 从整体来看是基于“标记整理”算法实现的收集器;从局部上来看是基于“复制”算法实现的。 - 可预测的停顿:这是 G1 相对于 CMS 的另一个大优势,降低停顿时间是 G1 和 CMS 共同的关注点,但 G1 除了追求低停顿外,还能建立可预测的停顿时间模型,能让使用者明确指定在一个长度为 M 毫秒的时间片段内。 G1 收集器的运作大致分为以下几个步骤: - 初始标记 - 并发标记 - 最终标记 - 筛选回收 > G1 收集器在后台维护了一个优先列表,每次根据允许的收集时间,优先选择回收价值最大的 Region(这也就是它的名字 Garbage-First 的由来)。这种使用 Region 划分内存空间以及有优先级的区域回收方式,保证了 GF 收集器在有限时间内可以尽可能高的收集效率(把内存化整为零)。 ### jvm内存模型,volatile关键字 - [jvm内存模型](https://juejin.im/post/5e8344486fb9a03c786ef885#heading-21) - [volatile](https://juejin.im/post/5e7e0e4ce51d4546cd2fcc7c#heading-18) ### Mysql Innodb 特点介绍 - [Innodb](https://juejin.im/post/5e94116551882573b86f970f#heading-1) ### 四种隔离级别 - [四种隔离级别](https://juejin.im/post/5e94116551882573b86f970f#heading-20) ### 单例模式写一下代码 ```java public class Singleton { // private static Singleton instance = null; // valotile private static volatile Singleton instance = null; private Singleton() { } // 私有 public static Singleton getInstance() { // 双重校验 //第一次判断 if(instance == null) { synchronized (Singleton.class) { // 加锁 if(instance == null) { //初始化,并非原子操作 instance = new Singleton(); // 这一行代码展开其实分三步走 } } } return instance; } } ``` <file_sep>package web; /** * @program LeetNiu * @description: 二维数组中的查找 * @author: mf * @create: 2020/01/06 14:57 */ /** * 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, * 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数, * 判断数组中是否含有该整数。 * * 思路: * 注意数组值的规律,可适当举个例子 */ public class T1 { public boolean Find(int target, int [][] array) { int col = 0; for (int i = array.length - 1; i >= 0; i--) { while (col < array[0].length && array[i][col] < target) col++; if (col == array[0].length) return false; if (array[i][col] == target) return true; } return false; } } <file_sep>package normal; import java.util.HashMap; /** * @program JavaBooks * @description: 242.有效的字母异位词 * @author: mf * @create: 2019/11/06 15:19 */ /* 题目:https://leetcode-cn.com/problems/valid-anagram/ 类型:哈希等 难度:easy */ /* 输入: s = "anagram", t = "nagaram" 输出: true 输入: s = "rat", t = "car" 输出: false */ public class IsAnagram { public static void main(String[] args) { String s = "anagram"; String t = "nagaram"; System.out.println(isAnagram(s, t)); System.out.println(isAnagram2(s, t)); } /** * 普通字符串方法 * @param s * @param t * @return */ private static boolean isAnagram(String s, String t) { int[] sCount = new int[26]; int[] tCount = new int[26]; for (char ch : s.toCharArray()) { sCount[ch - 'a']++; } for (char c : t.toCharArray()) { tCount[c - 'a']++; } for (int i = 0; i < 26; i++) { if (sCount[i] != tCount[i]) { return false; } } return true; } /** * 哈希 * @param s * @param t * @return */ private static boolean isAnagram2(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : t.toCharArray()) { Integer count = map.get(c); if (count == null){ return false; } else if (count > 1) { map.put(c, count - 1); } else { map.remove(c); } } return map.isEmpty(); } } <file_sep>## 引言 **常用的命令行技巧...** ## 前言 - 主要针对常用的一些命令行的使用 - 主要是unix的操作系统 <!-- more --> ## 常用 - `cd`:这个就不需要多讲了 - `clear`:这个也不需要多讲了 - `mkdir`:当前目录创建文件夹 - `touch`:当前目录下创建文件 - `ls`:查看目录下的文件 - `ls -a`:查看文件,包括隐藏文件 - `ls -l`:详细查看文件 - `top`:查看cpu和内存等 - `df -h`:查看各个磁盘使用的状态 - `du -hd1`:查看当前目录下文件的大小 - `du -h`:查看当前目录下文件的大小,包括子目录 - `nautilus ./`:打开当前文件管理器 - `pwd`:查看当前路径 - `w`:查看机器运行的时间 - `lsof -i:8000`:查看端口占用情况 - `ps -aux | grep python`: 查看某个进程 - `ps -ef | grep python`: 查看某个进程 ## 统计文件数目 ### ls `ls -l | wc -l`计数当前目录的文件和文件夹。 它会计算所有的文件和目录。 `ls -la | wc -l`统计当前目录包含隐藏文件和目录在内的文件和文件夹。 ### find `find . -type f | wc -l`递归计算当前目录的文件,包括隐藏文件。 `find . type d | wc -l`递归计算包含隐藏目录在内的目录数。 `find . -name '*.txt' | wc -l`根据文件扩展名计数文件数量。 这里我们要计算 `.txt` 文件。 ## 日常使用 - 可以通过**Tab**键实现自动补全参数 - 使用**ctrl-r**搜索命令行的历史记录 - 按下**ctrl-w**删除键入的最后的一个单词 - 按下**ctrl-u**可以删除行内光标所在位置之前的内容,**alt-b**和**alt-f**可以在以单词为单位移动光标,**ctrl-a**可以将光标移至行首,**ctrl-e**可以将光标移至行尾 - 回到前一个工作路径:`cd -` - `pstree -p`以一种优雅的方式展示进程树 - `kill -STOP[pid]`停止一个进程 - 使用`nohup`或`disown`使一个后台进程持续运行 - eg:`nohup python -u demo.py > ./logs/demo.log 2>&1 &` - 使用`netstat -lntp`检查哪些进程在监听端口 - 使用`uptime`或`w`查看系统已经运行对长时间 - 使用`alias`来常见常用命令的快捷形式,例如:`alias ll='ls -latr'`创建了一个新的命令别名,可以把别名放在`~./bashrc` ## 文件及数据处理 - 在当前目录下通过文件名查找一个文件,使用类似于这样的命令:`find . -name '*something'` - 使用`wc`去计算新行数`-l`,字符数`-m`,单词数`-w`以及字节数`-c`,例如`ls | wc -l` 、`ls -lR | grep "^-" | wc -l` - `du -sh *`查看某个文件的大小 - `du -h --max-depth=1`查看当前目下文件的大小 - `du -hd1`查看当前目录下文件的大小--mac - `df -hl` 查看磁盘情况 ## 和服务器交互 - 下载文件`scp username@servername:/path/filename /var/www/local_dir(本地目录)` - 上传文件`scp /path/filename username@servername:/path` - 下载文件夹`scp -r username@servername:/path/filename /var/www/local_dir(本地目录)` - 下载文件夹`scp -r /path/filename username@servername:/path` - 若是更改端口, 则前面 加上-p ## bash互换 - zsh切bash`chsh -s /bin/bash` - bash切zsh`chsh -s /bin/zsh` ## 有一些挺有用 - `bc`计算器 - `cal`漂亮的日历 - `tree`以树的形式显示路径和文件 - `watch`重复运行同一个命令,展示结果有更改的部分 ## 持续补充... <file_sep>package web; /** * @program LeetNiu * @description: 数字在排序数组中出现的次数 * @author: mf * @create: 2020/01/15 09:57 */ /** * 统计一个数字在排序数组中出现的次数。 */ public class T37 { public int GetNumberOfK(int [] array , int k) { int count = 0; for (int i : array) { if (i == k) count++; } return count; } } <file_sep>## 美团广告 一面 ### 代码中的异常的处理过程 - try 块: 用于捕获异常。其后可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。 - catch 块: 用于处理try捕获到的异常。 - finally 块: 无论是否捕获或处理异常,finally块里的语句都会被执行。当在try块或catch块中遇到return 语句时,finally语句块将在方法返回之前被执行。 ### Spring 里autowired注解和resource注解 - @Autowire 默认按照类型装配,默认情况下它要求依赖对象必须存在如果允许为null,可以设置它required属性为false,如果我们想使用按照名称装配,可 以结合@Qualifier注解一起使用; - @Resource默认按照名称装配,当找不到与名称匹配的bean才会按照类型装配,可以通过name属性指定,如果没有指定name属 性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找 依赖对象. ### String和StringBuffer区别,存储位置是否相同 - [String和StringBuffer区别](https://juejin.im/post/5e7e0615f265da795568754b#heading-37) ### cookie和session区别 #### cookie Cookie 是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器之后向同一服务器再次发起请求时被携带上,用于告知服务端两个请求是否来自同一浏览器。由于之后每次请求都会需要携带 Cookie 数据,因此会带来额外的性能开销(尤其是在移动环境下)。 - 会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息) - 个性化设置(如用户自定义设置、主题等) - 浏览器行为跟踪(如跟踪分析用户行为等) #### session Session 可以存储在服务器上的文件、数据库或者内存中。也可以将 Session 存储在 Redis 这种内存型数据库中,效率会更高。 - 用户进行登录时,用户提交包含用户名和密码的表单,放入 HTTP 请求报文中; - 服务器验证该用户名和密码,如果正确则把用户信息存储到 Redis 中,它在 Redis 中的 Key 称为 Session ID; - 服务器返回的响应报文的 Set-Cookie 首部字段包含了这个 Session ID,客户端收到响应报文之后将该 Cookie 值存入浏览器中; - 客户端之后对同一个服务器进行请求时会包含该 Cookie 值,服务器收到之后提取出 Session ID,从 Redis 中取出用户信息,继续之前的业务操作。 注意:Session ID 的安全性问题,不能让它被恶意攻击者轻易获取,那么就不能产生一个容易被猜到的 Session ID 值。此外,还需要经常重新生成 Session ID。在对安全性要求极高的场景下,例如转账等操作,除了使用 Session 管理用户状态之外,还需要对用户进行重新验证,比如重新输入密码,或者使用短信验证码等方式 Cookie和Session的选择 ### 二进制中1的个数 ```java public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; while (n != 0) { count++; n = (n - 1) & n; } return count; } } ``` ### 最长不含重复字符的子字符串 ```java class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; HashMap<Character, Integer> map = new HashMap<>(); for (int i = 0, j = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } } ``` ## 美团广告 二面 ### hashmap,hashtable的实现 - [HashMap-1.7和1.8](https://juejin.im/post/5e801e29e51d45470b4fce1c#heading-21) - [ConcurrentHashMap-1.7和1.8](https://juejin.im/post/5e801e29e51d45470b4fce1c#heading-33) - HashMap和Hashtable的对比 > HashTable 基于 Dictionary 类,而 HashMap 是基于 AbstractMap。Dictionary 是任何可将键映射到相应值的类的抽象父类,而 AbstractMap 是基于 Map 接口的实现,它以最大限度地减少实现此接口所需的工作。 > HashMap 的 key 和 value 都允许为 null,而 Hashtable 的 key 和 value 都不允许为 null。HashMap 遇到 key 为 null 的时候,调用 putForNullKey 方法进行处理,而对 value 没有处理;Hashtable遇到 null,直接返回 NullPointerException。 > Hashtable 方法是同步,而HashMap则不是。我们可以看一下源码,Hashtable 中的几乎所有的 public 的方法都是 synchronized 的,而有些方法也是在内部通过 synchronized 代码块来实现。所以有人一般都建议如果是涉及到多线程同步时采用 HashTable,没有涉及就采用 HashMap,但是在 Collections 类中存在一个静态方法:synchronizedMap(),该方法创建了一个线程安全的 Map 对象,并把它作为一个封装的对象来返回。 ### 公平锁和非公平锁如何实现 > ReentrantLock的公平锁和非公平锁 > 学习AQS的时候,了解到AQS依赖于内部的FIFO同步队列来完成同步状态的管理,当前线程获取同步状态失败时,同步器会将当前线程以及等待状态等信息构造成一个Node对象并将其加入到同步队列,同时会阻塞当前线程,当同步状态释放时,会把首节点中的线程唤醒,使其再次尝试获取同步状态。 - ReentrantLock 默认采用非公平锁,除非在构造方法中传入参数 true 。 ```java //默认 public ReentrantLock() { sync = new NonfairSync(); } //传入true or false public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } ``` #### 公平锁的lock方法 ```java static final class FairSync extends Sync { final void lock() { acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { // 1. 和非公平锁相比,这里多了一个判断:是否有线程在等待 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } ``` > 我们可以看到,在注释1的位置,有个!hasQueuedPredecessors()条件,意思是说当前同步队列没有前驱节点(也就是没有线程在等待)时才会去compareAndSetState(0, acquires)使用CAS修改同步状态变量。所以就实现了公平锁,根据线程发出请求的顺序获取锁。 #### 非公平锁的lock方法 ```java static final class NonfairSync extends Sync { final void lock() { // 2. 和公平锁相比,这里会直接先进行一次CAS,成功就返回了 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } /** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //3.这里也是直接CAS,没有判断前面是否还有节点。 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } ``` > 非公平锁的实现在刚进入lock方法时会直接使用一次CAS去尝试获取锁,不成功才会到acquire方法中,如注释2。而在nonfairTryAcquire方法中并没有判断是否有前驱节点在等待,直接CAS尝试获取锁,如注释3。由此实现了非公平锁。 #### 总结 > 非公平锁和公平锁的两处不同: 1. 非公平锁在调用 lock 后,首先就会调用 CAS 进行一次抢锁,如果这个时候恰巧锁没有被占用,那么直接就获取到锁返回了。 ### 操作系统里进程状态及转换 - [操作系统之进程的状态和转换详解](https://blog.csdn.net/qwe6112071/article/details/70473905) ### yield sleep结合状态转换讲一下 - sleep:不会释放锁 让当前正在执行的线程先暂停一定的时间,并进入阻塞状态。 在其睡眠的时间段内,该线程由于不是处于就绪状态,因此不会得到执行的机会。 即使此时系统中没有任何其他可执行的线程,处于sleep()中的线程也不会执行。 因此sleep()方法常用来暂停线程的执行。当sleep()结束后,然后转入到 Runnable(就绪状态),这样才能够得到执行的机会。 - yield:线程让步,不会释放锁 让一个线程执行了yield()方法后,就会进入Runnable(就绪状态),不同于sleep()和join()方法,因为这两个方法是使线程进入阻塞状态】。 除此之外,yield()方法还与线程优先级有关,当某个线程调用yield()方法时,就会从运行状态转换到就绪状态后,CPU从就绪状态线程队列中只会选择与该线程优先级相同或者更高优先级的线程去执行。 ### 常用的排序算法哪些,最优时间复杂度,最差时间复杂度,平均时间复杂度,空间复杂度 - [常用的排序算法](http://dreamcat.ink/2019/07/09/shi-da-jing-dian-pai-xu-suan-fa/) ### 最长不含重复字符的子字符串 ```java class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; HashMap<Character, Integer> map = new HashMap<>(); for (int i = 0, j = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } } ``` ### 4G内存读取10G日志,统计其中出现频次最高的十个word,如何实现,如何使得速度更快 - [教你如何迅速秒杀掉99%的海量数据处理面试题](https://juejin.im/entry/5a27cb796fb9a045104a5e8c) ### 数据库范式 - [数据库范式](https://juejin.im/post/5e94116551882573b86f970f#heading-31)<file_sep>package normal; /** * @program JavaBooks * @description: 69. x 的平方根 * @author: mf * @create: 2019/11/09 09:38 */ /* 题目:https://leetcode-cn.com/problems/sqrtx/ 难度:easy */ /* 输入: 4 输出: 2 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 */ public class MySqrt { public static void main(String[] args) { System.out.println(mySqrt(8)); } public static int mySqrt(int x) { if (x <= 1) return x; int l = 1, h = x; while (l <= h) { int mid = l + (h - l) / 2; int sqrt = x / mid; if (sqrt == mid ) return sqrt; else if (mid > sqrt) h = mid - 1; else l = mid + 1; } return h; } } <file_sep>package com.basic; import java.util.concurrent.TimeUnit; /** * @program JavaBooks * @description: ThreadLocal * @author: mf * @create: 2019/12/30 23:55 */ public class T17 { private static ThreadLocal<person> tl = new ThreadLocal<>(); public static void main(String[] args) { new Thread(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(tl.get()); // 无法得到线程二的new的person }).start(); new Thread(() -> { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } tl.set(new person()); }).start(); } } class person { String name = "zhangsan"; } <file_sep>package com.basic; /** * @program JavaBooks * @description: 通信 * @author: mf * @create: 2019/12/30 15:54 */ import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * 实现一个容器,提供两个方法add size * 写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5个时,线程2给出提示并结束 */ public class T11 { // List lists = new ArrayList(); // 解决方法1, 添加volatile,使t2能够得到通知 volatile List lists = new ArrayList(); public void add(Object o) { lists.add(o); } public int size() { return lists.size(); } public static void main(String[] args) { T11 t11 = new T11(); new Thread(() -> { for (int i = 0; i < 10; i++) { t11.add(new Object()); System.out.println("add " + i); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1").start(); new Thread(() -> { while (true) { if (t11.size() == 5) { break; } } System.out.println("t2结束"); }, "t2").start(); } } /** * 使用wait和notify优化 * wait释放锁,但是notify不释放 */ class T11_1 { List lists = new ArrayList(); public void add(Object o) { lists.add(o); } public int size() { return lists.size(); } public static void main(String[] args) { T11_1 t11_1 = new T11_1(); final Object lock = new Object(); new Thread(() -> { synchronized (lock) { System.out.println("t2 启动"); if (t11_1.size() != 5) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("t2 结束"); lock.notify(); } }, "t2").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { System.out.println("t1 启动"); synchronized (lock) { for (int i = 0; i < 10; i++) { t11_1.add(new Object()); System.out.println("add " + i); if (t11_1.size() == 5) { lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "t1").start(); } } /** * 使用CountDownLatch CyclicBarrier semaphore */ class T11_2 { List lists = new ArrayList(); public void add (Object o) { lists.add(o); } public int size() { return lists.size(); } public static void main(String[] args) { T11_2 t11_2 = new T11_2(); CountDownLatch countDownLatch = new CountDownLatch(1); new Thread(() -> { System.out.println("t2启动"); if (t11_2.size() != 5) { try { countDownLatch.await(); // 上个门闩 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("t2结束"); }, "t2").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { System.out.println("t1启动"); for (int i = 0; i < 10; i++) { t11_2.add(new Object()); System.out.println("add " + i); if (t11_2.size() == 5) { // 打开门闩,让t2得以执行 countDownLatch.countDown(); } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1").start(); } }<file_sep>/** * @program JavaBooks * @description: 三角形最小路径和 * @author: mf * @create: 2020/04/15 19:04 */ package subject.dp; import java.util.List; /** * [ * [2], * [3,4], * [6,5,7], * [4,1,8,3] * ] */ public class T5 { public int minimumTotal(List<List<Integer>> triangle){ if (triangle.size() == 0) return 0; int row = triangle.size(); int[][] dp = new int[row][triangle.get(row - 1).size()]; for (int i = 0; i < row; i++) { for (int j = 0; j < triangle.get(i).size(); j++) { dp[i][j] = 0; } } for (int i = 0; i < triangle.get(row - 1).size(); i++) { dp[row - 1][i] = triangle.get(row - 1).get(i); } for (int i = row - 2; i >= 0; i--) { for (int j = 0; j < triangle.get(i).size(); j++) { dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1]) + triangle.get(i).get(j); } } return dp[0][0]; } } <file_sep>package books; /** * @program JavaBooks * @description: 树的子结构 * @author: mf * @create: 2019/09/06 10:07 */ /* 输入两颗二叉树A和B,判断B是不是A的子结构。 */ /* 思路 两个递归, 第一个大递归的功能是遍历A的node和B树root是否相等,终止条件就是是否为空,如果都不相等,最后肯定是false 当相等的时候,那第二个递归的功能就是同时遍历A树和B树的对应的左右子节点是否相等,终止条件就是 */ public class T26 { public static void main(String[] args) { int[] preA = {8, 8, 9, 2, 4, 7, 7}; int[] inA = {9, 8, 4, 2, 7, 8, 7}; int[] preB = {8, 9 , 2}; int[] inB = {9, 8, 2}; // 根据笔试题T7, 前序列和中序,重建二叉树 TreeNode nodeA = TreeNode.setBinaryTree(preA, inA); TreeNode nodeB = TreeNode.setBinaryTree(preB, inB); // System.out.println("前序A:"); // TreeNode.preOrderRe(nodeA); // System.out.println("前序B:"); // TreeNode.preOrderRe(nodeB); boolean isSubTree = hasSubTree(nodeA, nodeB); System.out.println(isSubTree); } private static boolean hasSubTree(TreeNode nodeA, TreeNode nodeB) { boolean result = false; // 注意条件 if (nodeA != null && nodeB != null) { if (nodeA.val == nodeB.val) { // root's val equal , so 开始遍历子节点 result = goOnFind(nodeA, nodeB); } // 递归找左 if (!result) { result = hasSubTree(nodeA.left, nodeB); } // 递归找右 if (!result) { result = hasSubTree(nodeA.right, nodeB); } } return result; } private static boolean goOnFind(TreeNode nodeA, TreeNode nodeB) { if (nodeB == null) return true; // 说明b提前遍历完成 if (nodeA == null) return false; // 说明B还有节点,A没有子节点等 if (nodeA.val != nodeB.val) return false; // 说明值不相等 // 递归子节点 return goOnFind(nodeA.left, nodeB.left) && goOnFind(nodeA.right, nodeB.right); } } <file_sep>## 引言 > 项目中用到消息队列RocketMQ,因此在Centos7安装及配置。。。 <!-- more --> ## 下载 - [rocketmq](https://mirrors.tuna.tsinghua.edu.cn/apache/rocketmq/) - 选择**rocketmq-all-4.6.1-bin-release.zip** - 因为RocketMQ依赖maven打包,因此需要安装maven - 注意:下面所添加的环境统统是.zshrc ## Maven安装 - [maven地址](http://mirrors.hust.edu.cn/apache/maven/maven-3/) - 在本文章中采用最新**3.6.3** - 解压`tar -zxf apache-maven-3.6.3-bin.tar.gz` - 修改仓库地址为阿里云,因为默认下载依赖总超时,找到conf中的setting.xml文件 - ```xml <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> ``` - 配置环境变量`vim .zshrc` - ```shell export M2_HOME=/home/pch/Documents/mf/web/maven3 export PATH=$PATH:$Java_HOME/bin:$M2_HOME/bin ``` - 刷新环境变量`source .zshrc` ## Rocketmq安装 - 解压`unzip rocketmq-all-4.6.1-bin-release.zip -d ./` - 注意在bin目录中:`runserver.sh和runbroker.sh` **个人情况修改JAVA_OPT="${JAVA_OPT} -server一行参数** - 将nameserver地址添加到环境变量中 - `export NAMESRV_ADDR=127.0.0.1:9876` - **刷新配置文件`source .zshrh`** - 创建logs文件夹,存放启动日志,方便查看 - 后台运行nameserver`nohup sh mqnamesrv > ../logs/nameser.log 2>&1&` - 后台运行broker`nohup sh mqbroker > ../logs/broker.log 2>&1&` ## 控制台安装 **这个控制台属于springboot的项目...** - 项目链接`git clone https://github.com/apache/rocketmq-externals` - rocketmq-externals里面有所有Apache RocketMq外部项目,有的还在孵化中,我主要是使用rocketmq-console,进入到console项目中,修改resources文件夹下面的配置文件 - 在`rocketmq-externals/rocketmq-console/src/main/resources`目录下打开配置文件`vim application.properties` - 修改以下配置 - ```properties server.port=8090 rocketmq.config.namesrvAddr=127.0.0.1:9876 rocketmq.config.dataPath=/home/pch/Documents/mf/web/rocket-data ``` - 开始maven打包`mvn clean install -Dmaven.test.skip=true` - 完成之后在target找到`rocketmq-console-ng-1.0.1.jar`,后台运行它 - `nohup java -jar rocketmq-console-ng-1.0.1.jar > rocket-data/console.out 2>&1&` - `localhost:8090`即可看到效果 - ![](http://media.dreamcat.ink/20200222002600.png) <file_sep>package normal; import java.util.LinkedList; import java.util.Queue; /** * @program JavaBooks * @description: 225.用队列实现栈 * @author: mf * @create: 2019/11/07 15:10 */ /* 题目:https://leetcode-cn.com/problems/implement-stack-using-queues/ 类型:队列 难度:easy */ public class MyStack { public static void main(String[] args) { MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); System.out.println(myStack.pop()); } private Queue<Integer> queue; // private LinkedList<Integer> queue; public MyStack() { queue = new LinkedList<>(); } public void push(int x) { queue.add(x); int cnt = queue.size(); while (cnt-- > 1) { queue.add(queue.poll()); } // queue.addFirst(x); } public int pop() { return queue.remove(); } public int top() { return queue.peek(); } public boolean empty() { return queue.isEmpty(); } } <file_sep>package web; /** * @program LeetNiu * @description: 求1+2+3+...+n * @author: mf * @create: 2020/01/15 13:42 */ /** * 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 */ public class T47 { public int Sum_Solution(int n) { int res = n; boolean t = ((res != 0) && ((res += Sum_Solution(n - 1)) != 0)); return res; } } <file_sep>package normal; import java.util.Arrays; import java.util.HashSet; /** * @program JavaBooks * @description: 204.计算质数 * @author: mf * @create: 2019/11/06 10:44 */ /* 题目:https://leetcode-cn.com/problems/count-primes/ 类型:筛选 难度:easy */ /* 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。s */ public class CountPrimes { public static void main(String[] args) { System.out.println(countPrimes(10)); } private static int countPrimes(int n) { if (n == 0 || n == 1) return 0; boolean[] num = new boolean[n + 1]; int count = 0; for (int i = 2; i < n; i++) { if (num[i] == false) { count++; for (int j = 2 * i; j < n + 1; j += i) { num[j] = true; } } } return count; } } <file_sep>package books; /** * @program JavaBooks * @description: 重建二叉树 * @author: mf * @create: 2019/08/20 14:38 */ /* 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 例如,输入前序遍历序列{1, 2, 4, 7, 3, 5, 6, 8}和 中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则如下二叉树并 输出它的头节点。 1 2 3 4 5 6 7 8 */ public class T7 { // 递归 public TreeNode reConstructBinaryTree(int[] pre, int[] in) { TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1); return root; } //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6} private TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { if (startPre > endPre || startIn > endIn) { return null; } TreeNode root = new TreeNode(pre[startPre]); for (int i = startIn; i <= endIn; i++) { if (in[i] == pre[startPre]) { //注意边界,递归可看成重复的子问题。 root.left = reConstructBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1); root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn); } } return root; } } class TestT7 { public static void main(String[] args) { int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; T7 t7 = new T7(); TreeNode root = t7.reConstructBinaryTree(pre, in); System.out.println(root.val); } }<file_sep>package normal; import com.sun.org.apache.bcel.internal.generic.RET; /** * @program JavaBooks * @description: 198. 打家劫舍 * @author: mf * @create: 2019/11/10 13:27 */ /* 题目:https://leetcode-cn.com/problems/house-robber/ 类型:动态规划 难度:easy */ /* 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。   偷窃到的最高金额 = 1 + 3 = 4 。 */ public class Rob { public static void main(String[] args) { int[] nums = {1,2,3,1}; System.out.println(rob(nums)); } public static int rob(int[] nums) { if (nums.length == 0) return 0; if (nums.length == 1) return nums[0]; int pre3 = 0, pre2 = 0, pre1 = 0; for (int i = 0; i < nums.length; i++) { int cur = Math.max(pre2, pre3) + nums[i]; pre3 = pre2; pre2 = pre1; pre1 = cur; } return Math.max(pre1, pre2); } } <file_sep>> 一般面试问消息队列,都是结合自己的项目进行回答的...最好有个项目有消息队列的中间件.本项目使用了RocketMQ ### 什么是消息队列?消息队列的主要作用是什么? 我们可以把消息队列比作是一个**存放消息的容器**,当我们需要使用消息的时候可以取出消息供自己使用。消息队列是分布式系统中重要的组件,使用消息队列主要是为了通过**异步处理提高系统性能和削峰、降低系统耦合性**。 - **异步处理**:非核心流程异步化,提高系统响应性能 - **应用解耦**: - 系统不是强耦合,消息接受者可以随意增加,而不需要修改消息发送者的代码。消息发送者的成功不依赖消息接受者(比如有些银行接口不稳定,但调用方并不需要依赖这些接口) - 消息发送者的成功不依赖消息接受者(比如有些银行接口不稳定,但调用方并不需要依赖这些接口) - **最终一致性**:最终一致性不是消息队列的必备特性,但确实可以依靠消息队列来做最终一致性的事情。 - 先写消息再操作,确保操作完成后再修改消息状态。定时任务补偿机制实现消息可靠发送接收、业务操作的可靠执行,要注意消息重复与幂等设计 - 所有不保证100%不丢消息的消息队列,理论上无法实现最终一致性。 - **广播**:只需要关心消息是否送达了队列,至于谁希望订阅,是下游的事情 - **流量削峰与监控**:当上下游系统处理能力存在差距的时候,利用消息队列做一个通用的“漏斗”。在下游有能力处理的时候,再进行分发。 - **日志处理**:将消息队列用在日志处理中,比如Kafka的应用,解决大量日志传输的问题 - **消息通讯**:消息队列一般都内置了高效的通信机制,因此也可以用于单纯的消息通讯,如实现点对点消息队列或者聊天室等。 **推荐浅显易懂的讲解**: - [《吊打面试官》系列-消息队列基础](https://mp.weixin.qq.com/s/qGzMRvWwworit4lWp0EL3w) - [面试官问你什么是消息队列?把这篇甩给他!](https://mp.weixin.qq.com/s/wHaaipxYx0CUwpYVRJnV1A) ### kafka、activemq、rabbitmq、rocketmq都有什么区别? - ActiveMQ 的社区算是比较成熟,但是较目前来说,ActiveMQ 的性能比较差,而且版本迭代很慢,不推荐使用。 - RabbitMQ 在吞吐量方面虽然稍逊于 Kafka 和 RocketMQ ,但是由于它基于 erlang 开发,所以并发能力很强,性能极其好,延时很低,达到微秒级。但是也因为 RabbitMQ 基于 erlang 开发,所以国内很少有公司有实力做erlang源码级别的研究和定制。如果业务场景对并发量要求不是太高(十万级、百万级),那这四种消息队列中,RabbitMQ 一定是你的首选。如果是大数据领域的实时计算、日志采集等场景,用 Kafka 是业内标准的,绝对没问题,社区活跃度很高,绝对不会黄,何况几乎是全世界这个领域的事实性规范。 - RocketMQ 阿里出品,Java 系开源项目,源代码我们可以直接阅读,然后可以定制自己公司的MQ,并且 RocketMQ 有阿里巴巴的实际业务场景的实战考验。RocketMQ 社区活跃度相对较为一般,不过也还可以,文档相对来说简单一些,然后接口这块不是按照标准 JMS 规范走的有些系统要迁移需要修改大量代码。还有就是阿里出台的技术,你得做好这个技术万一被抛弃,社区黄掉的风险,那如果你们公司有技术实力我觉得用RocketMQ 挺好的 - kafka 的特点其实很明显,就是仅仅提供较少的核心功能,但是提供超高的吞吐量,ms 级的延迟,极高的可用性以及可靠性,而且分布式可以任意扩展。同时 kafka 最好是支撑较少的 topic 数量即可,保证其超高吞吐量。kafka 唯一的一点劣势是有可能消息重复消费,那么对数据准确性会造成极其轻微的影响,在大数据领域中以及日志采集中,这点轻微影响可以忽略这个特性天然适合大数据实时计算以及日志收集。 ### MQ在高并发情况下,假设队列满了如何防止消息丢失? ![](https://bbsmax.ikafan.com/static/L3Byb3h5L2h0dHBzL2ltZzIwMTguY25ibG9ncy5jb20vYmxvZy85OTgzNDIvMjAxOTAyLzk5ODM0Mi0yMDE5MDIxNjEyMTEzNzM1Mi04MzE0MzYzMDkucG5n.jpg) 1. 生产者可以采用重试机制。因为消费者会不停的消费消息,可以重试将消息放入队列。 2. 死信队列,可以理解为备胎(推荐) - 即在消息过期,队列满了,消息被拒绝的时候,都可以扔给死信队列。 - 如果出现死信队列和普通队列都满的情况,此时考虑消费者消费能力不足,可以对消费者开多线程进行处理。 ### 谈谈死信队列 **死信队列用于处理无法被正常消费的消息,即死信消息**。 当一条消息初次消费失败,**消息队列 RocketMQ 版会自动进行消息重试**;达到最大重试次数后,若消费依然失败,则表明消费者在正常情况下无法正确地消费该消息,此时,消息队列 RocketMQ 版不会立刻将消息丢弃,而是将其发送到该**消费者对应的特殊队列中**,该特殊队列称为**死信队列**。 **死信消息的特点**: - 不会再被消费者正常消费。 - 有效期与正常消息相同,均为 3 天,3 天后会被自动删除。因此,请在死信消息产生后的 3 天内及时处理。 **死信队列的特点**: - 一个死信队列对应一个 Group ID, 而不是对应单个消费者实例。 - 如果一个 Group ID 未产生死信消息,消息队列 RocketMQ 版不会为其创建相应的死信队列。 - 一个死信队列包含了对应 Group ID 产生的所有死信消息,不论该消息属于哪个 Topic。 消息队列 RocketMQ 版控制台提供对死信消息的查询、导出和重发的功能。 ### 消费者消费消息,如何保证MQ幂等性? #### 幂等性 消费者在消费mq中的消息时,mq已把消息发送给消费者,消费者在给mq返回ack时网络中断,故mq未收到确认信息,该条消息会重新发给其他的消费者,或者在网络重连后再次发送给该消费者,但实际上该消费者已成功消费了该条消息,造成消费者消费了重复的消息; #### 解决方案 - MQ消费者的幂等行的解决一般使用全局ID 或者写个唯一标识比如时间戳 或者UUID 或者订单 - 也可利用mq的该id来判断,或者可按自己的规则生成一个全局唯一id,每次消费消息时用该id先判断该消息是否已消费过。 - 给消息分配一个全局id,只要消费过该消息,将 < id,message>以K-V形式写入redis。那消费者开始消费前,先去redis中查询有没消费记录即可。 ### 使用异步消息时如何保证数据的一致性 1. **借助数据库的事务**:使用异步消息怎么还能借助到数据库事务?这需要在数据库中创建一个**本地消息表**,这样可以通过**一个事务来控制本地业务逻辑更新**和本**地消息表的写入在同一个事务中**,一旦消息落库失败,则直接全部回滚。如果消息落库成功,后续就可以根据情况基于本地数据库中的消息数据对消息进行重投了。关于本地消息表和消息队列中状态如何保持一致,可以采用 2PC 的方式。在发消息之前落库,然后发消息,在得到同步结果或者消息回调的时候更新本地数据库表中消息状态。然后只需要通过**定时轮询**的方式对状态未已记录但是未发送的消息重新投递就行了。但是这种方案有个前提,就是要求消息的消费者**做好幂等控制**,这个其实异步消息的消费者一般都需要考虑的。 2. 除了使用数据库以外,还可以使用 **Redis** 等缓存。这样就是无法利用关系型数据库自带的事务回滚了。 ### RockMQ不适用Zookeeper作为注册中心的原因,以及自制的NameServer优缺点? 1. ZooKeeper 作为支持**顺序一致性**的中间件,在某些情况下,它为了满足一致性,会丢失一定时间内的**可用性**,RocketMQ 需要注册中心只是为了**发现组件地址**,在某些情况下,RocketMQ 的注册中心可以出现数据不一致性,这同时也是 **NameServer 的缺点,因为 NameServer 集群间互不通信,它们之间的注册信息可能会不一致**。 2. 另外,当有新的服务器加入时,**NameServer 并不会立马通知到 Produer**,而是由 **Produer 定时去请求 NameServer 获取最新的 Broker/Consumer 信息**(这种情况是通过 Producer 发送消息时,负载均衡解决) 3. 包括组件通信间使用 Netty 的自定义协议 4. 消息重试负载均衡策略(具体参考 Dubbo 负载均衡策略) 5. 消息过滤器(Producer 发送消息到 Broker,Broker 存储消息信息,Consumer 消费时请求 Broker 端从磁盘文件查询消息文件时,在 Broker 端就使用过滤服务器进行过滤) 6. Broker 同步双写和异步双写中 Master 和 Slave 的交互<file_sep>package books; import java.util.Arrays; /** * @program JavaBooks * @description: 扑克牌中的顺子 * @author: mf * @create: 2019/10/08 21:53 */ /* 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的 2~10为数字本身,A为1,J为11,Q为12,k为13,而大、小王可以 看成任意数字。 */ public class T61 { public static void main(String[] args) { int[] arr = {2, 3, 4, 6, 6}; System.out.println(isContinuous(arr)); } private static boolean isContinuous(int[] arr) { int numberOfZero = 0; int numOfInterval = 0; int length = arr.length; if (length == 0) return false; Arrays.sort(arr); for (int i = 0; i < length - 1; i++) { // 大小王 if (arr[i] == 0) { numberOfZero++; continue; } // 对子直接返回 if (arr[i] == arr[i + 1]) { return false; } numOfInterval += arr[i + 1] - arr[i] - 1; } if (numberOfZero >= numOfInterval) { return true; } return false; } } <file_sep>## LeetCode ### easy - [1、两数之和](/LeetCode/src/normal/TwoSum.java) - [7、整数反转](/LeetCode/src/normal/Reverse.java) - [13、罗马数字转整数](/LeetCode/src/normal/RomanToInt.java) - [13、最长公共前缀](/LeetCode/src/normal/LongestCommonPrefix.java) - [20、有效的括号](/LeetCode/src/normal/IsValid.java) - [21、合并两个有序链表](/LeetCode/src/normal/MergeTwoLists.java) - [26、删除排序数组中的重复项](/LeetCode/src/normal/RemoveDuplicates.java) - [28、strStr](/LeetCode/src/normal/StrStr.java) - [53、最大子序和](/LeetCode/src/normal/MaxSubArray.java) - [66、加一](/LeetCode/src/normal/PlusOne.java) - [69、x的平方根](/LeetCode/src/normal/MySqrt.java) - [70、爬楼梯](/LeetCode/src/normal/ClimbStairs.java) - [88、合并两个排序的数组](/LeetCode/src/normal/Merge.java) - [101、对称二叉树](/LeetCode/src/normal/IsSymmetric.java) - [104、二叉树的最大深度](/LeetCode/src/normal/MaxDepth.java) - [108、将有序数组转换为二叉搜索树](/LeetCode/src/normal/SortedArrayToBST.java) - [111、二叉树的最小深度](/LeetCode/src/normal/MinDepth.java) - [118、杨辉三角](/LeetCode/src/normal/Generate.java) - [121、买卖股票的最佳时机](/LeetCode/src/normal/MaxProfit.java) - [122、买卖股票的最佳时机2](/LeetCode/src/normal/MaxProfi2t.java) - [125、验证回文串](/LeetCode/src/normal/IsPalindromeStr.java) - [136、只出现一次的数字](/LeetCode/src/normal/SingleNumber.java) - [141、环形链表](/LeetCode/src/normal/HasCycle.java) - [155、最小栈](/LeetCode/src/normal/MinStack.java) - [160、相交链表](/LeetCode/src/normal/GetIntersectionNode.java) - [169、求众数](/LeetCode/src/normal/MajorityElement.java) - [171、Excel表列序号](/LeetCode/src/normal/TitleToNumber.java) - [172、阶乘后的零](/LeetCode/src/normal/TrailingZeroes.java) - [189、旋转数组](/LeetCode/src/normal/Rotate.java) - [190、颠倒二进制位](/LeetCode/src/normal/ReverseBits.java) - [191、位1的个数](/LeetCode/src/normal/HammingWeight.java) - [198、打家劫舍](/LeetCode/src/normal/Rob.java) - [202、快乐数](/LeetCode/src/normal/IsHappy.java) - [204、计算质数](/LeetCode/src/normal/CountPrimes.java) - [206、反转链表](/LeetCode/src/normal/ReverseList.java) - [217、存在重复元素](/LeetCode/src/normal/ContainsDuplicate.java) - [225、用队列实现栈](/LeetCode/src/normal/MyStack.java) - [232、用栈实现队列](/LeetCode/src/normal/MyQueue.java) - [234、回文链表](/LeetCode/src/normal/isPalindromeNode.java) - [242、有效的字母异位词](/LeetCode/src/normal/IsAnagram.java) - [268、缺失数字](/LeetCode/src/normal/MissingNumber.java) - [283、移动零](/LeetCode/src/normal/MoveZeroes.java) - [326、3的幂](/LeetCode/src/normal/IsPowerOfThree.java) - [344、反转字符串](/LeetCode/src/normal/ReverseString.java) - [350、两个数组的交集 II](/LeetCode/src/normal/Intersect.java) - [371、两整数之和](/LeetCode/src/normal/GetSum.java) - [387、字符串中的第一个唯一字符](/LeetCode/src/normal/FirstUniqChar.java) - [412、Fizz Buzz](/LeetCode/src/normal/FizzBuzz.java) - [744、寻找比目标字母大的最小字母](/LeetCode/src/normal/NextGreatestLetter.java) ### Medium - [2、两个链表相加](/LeetCode/src/normal/AddTwoNumbers.java) - [3、无重复字符的最长子串](/LeetCode/src/normal/LengthOfLongestSubstring.java)<file_sep>package books; /** * @program JavaBooks * @description: 旋转数组的最小数字 * @author: mf * @create: 2019/08/23 10:18 */ /* 把一个数组最开始的若干个元素搬到数组的末尾,我们称之 为数组的旋转。输入一个递增排序的数组是的一个旋转,输出旋转 数组的最小元素。例如{3, 4, 5, 1, 2}为{1, 2, 3, 4, 5}的 一个旋转,该数组的最小值为1。 {0, 1, 1, 1, 1, ,1, 1} */ public class T11 { public static void main(String[] args) { int[] arr = {3, 4, 5, 1, 2}; System.out.println(findMin2(arr)); } /** * * @param arr * @return 坐标 */ public static int findMin(int[] arr) { int p1 = 0; int p2 = arr.length - 1; int mid = p1; while (arr[p1] >= arr[p2]) { if (p2 - p1 == 1) { mid = p2; break; } mid = p1 + ((p2 - p1) >> 1); // 提高代码健壮性,若是出现arr[p1] arr[p2] mid三者相等 if (arr[p1] == arr[p2] && arr[p1] == mid) { return ergodic(arr, p1, p2); } if (arr[p1] < arr[mid]) { p1 = mid; } else { p2 = mid; } } return mid; } public static int ergodic(int[] arr, int p1, int p2) { int res = 0; for (int i = p1; i <= p2; i++) { if (res > arr[i]) { res = arr[i]; } } return res; } /** * 分析数组规律,单指针即可 * @param arr * @return */ public static int findMin2(int[] arr) { if (arr.length == 0) return 0; if (arr.length == 1) return arr[0]; int a = arr[0]; for (int i = 1; i < arr.length; i++) { if (a > arr[i]) { return arr[i]; } else { a = arr[i]; } } return 0; } } <file_sep>## 美团北京 一面 3月24日 - [原链接](https://www.nowcoder.com/discuss/411183) ### LinkedList和ArrayList - [ArrayList](http://dreamcat.ink/2019/10/29/java-ji-he-arraylist-yuan-ma-jie-xi/) - [LinkedList](http://dreamcat.ink/2019/10/30/java-ji-he-linkedlist-yuan-ma-jie-xi/) ### Set的一些种类的不同 - TreeSet > 基于红黑树实现,支持有序性操作,例如根据一个范围查找元素的操作。但是查找效率不如HashSet,HashSet查找的时间复杂为O(1),TreeSet则为O(logN)。 - HashSet > 基于哈希表实现,支持快速查找,但不支持有序性操作。并且失去了元素的插入顺序信息,也就是说使用Iterator遍历HashSet得到结果是不确定的。 - LinkedHashSet > 具有HashSet的查找效率,且内部使用双向链表维护元素的插入顺序。 ### Hashmap的特点和扩容 - [一个 HashMap 跟面试官扯了半个小时](https://gitbook.cn/books/5e8cb23a0e53912fafc48fd9/index.html) ### ConcurrentHashMap - [ConcurrentHashMap](https://juejin.im/post/5e801e29e51d45470b4fce1c#heading-33) ### ==和equals的区别 - [==和equals的区别](https://juejin.im/post/5e7e0615f265da795568754b#heading-4) ### 线程池的三个主要参数的意思 - corePoolSize: 核心线程数线程数定义了最小可以同时运行的线程数量。 - maximumPoolSize: 当队列中存放的任务达到队列容量的时候,当前可以同时运行的线程数量变为最大线程数。 - workQueue: 当新任务来的时候会先判断当前运行的线程数量是否达到核心线程数,如果达到的话,信任就会被存放在队列中。 ### Synchronize的底层实现和优化 - [Synchronize的底层实现和优化](https://juejin.im/post/5e7e0e4ce51d4546cd2fcc7c#heading-12) ### 可重入锁是如何实现的 > 可重入锁又名递归锁,是指在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁,典型的synchronized,了解一下 - [参考文章](https://blog.csdn.net/xzp_12345/article/details/79431404) ### AQS和synchronize的区别 - [Synchronized 和 ReenTrantLock 的对比](https://juejin.im/post/5e7e0e4ce51d4546cd2fcc7c#heading-15) ### Threadlocal - [Threadlocal](https://juejin.im/post/5e7e0e4ce51d4546cd2fcc7c#heading-25) ### 介绍GC的各个收集器,以及如何选择 - [GC各个收集器](https://juejin.im/post/5e8344486fb9a03c786ef885#heading-52) ### 数据库组合索引 - 超过3个列的联合索引不合适,否则虽然减少了回表动作,但索引块过多,查询时就要遍历更多的索引块了; - 建索引动作应谨慎,因为建索引的过程会产生锁,不是行级锁,而是锁住整个表,任何该表的DML操作都将被阻止,在生产环境中的繁忙时段建索引是一件非常危险的事情; - 对于某段时间内,海量数据表有频繁的更新,这时可以先删除索引,插入数据,再重新建立索引来达到高效的目的。 ### 数据库事务 - [事务](https://juejin.im/post/5e94116551882573b86f970f#heading-14) ### Spring Ioc和AOP的动态代理 > IOC负责将对象动态的注入到容器,从而达到一种需要谁就注入谁,什么时候需要就什么时候注入的效果,可谓是招之则来,挥之则去。 > Spring两大核心,IOC和AOP,其中AOP用到了动态代理,常用于日志记录,性能统计,安全控制,事物处理,异常处理等,主要将与业务无关的逻辑从代码中抽离出来复用,实现解耦。 > 动态代理是在静态代理的基础上产生的, 态代理模式对弊端是被代理对象需要实现其公共接口以及接口的所有方法。试想若在一个系统中要给所有对象的所有方法都加上日志记录,让所有代理对象都去实现其接口是不妥的,不能体现其复用性,耦合度也较高。 > 动态代理通过反射技术,在调用被代理的对象的方法时,动态增加一些操作。 ### Redis有什么基本类型,你的项目用到了什么基本类型 - String > 常用命令: set,get,decr,incr,mget 等。 String数据结构是简单的key-value类型,value其实不仅可以是String,也可以是数字。 常规key-value缓存应用; 常规计数:微博数,粉丝数等。 - Hash > 常用命令: hget,hset,hgetall 等。 Hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象,后续操作的时候,你可以直接仅 仅修改这个对象中的某个字段的值。 比如我们可以Hash数据结构来存储用户信息,商品信息等等。 - List > 常用命令: lpush,rpush,lpop,rpop,lrange等 list 就是链表,Redis list 的应用场景非常多,也是Redis最重要的数据结构之一,比如微博的关注列表,粉丝列表, 消息列表等功能都可以用Redis的 list 结构来实现。 Redis list 的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销。 另外可以通过 lrange 命令,就是从某个元素开始读取多少个元素,可以基于 list 实现分页查询,这个很棒的一个功 能,基于 redis 实现简单的高性能分页,可以做类似微博那种下拉不断分页的东西(一页一页的往下走),性能高。 - Set > 常用命令: sadd,spop,smembers,sunion 等 set 对外提供的功能与list类似是一个列表的功能,特殊之处在于 set 是可以自动排重的。 当你需要存储一个列表数据,又不希望出现重复数据时,set是一个很好的选择,并且set提供了判断某个成员是否在 一个set集合内的重要接口,这个也是list所不能提供的。可以基于 set 轻易实现交集、并集、差集的操作。 比如:在微博应用中,可以将一个用户所有的关注人存在一个集合中,将其所有粉丝存在一个集合。Redis可以非常 方便的实现如共同关注、共同粉丝、共同喜好等功能。这个过程也就是求交集的过程,具体命令如下:`sinterstore key1 key2 key3`将交集存在key1内 - Sorted Set > 常用命令: zadd,zrange,zrem,zcard等 和set相比,sorted set增加了一个权重参数score,使得集合中的元素能够按score进行有序排列。 举例: 在直播系统中,实时排行信息包含直播间在线用户列表,各种礼物排行榜,弹幕消息(可以理解为按消息维 度的消息排行榜)等信息,适合使用 Redis 中的 SortedSet 结构进行存储。 ### 只出现一次的数字 ```java class Solution { public int singleNumber(int[] nums) { if(nums.length == 1) return nums[0]; int ans = nums[0]; for(int i = 1; i < nums.length; i++) { ans ^= nums[i]; } return ans; } } ``` ## 美团成都一面 ### 自我介绍 > 准备个模板 ### 数据库如何优化 #### 索引优化 - 通过创建**唯一性索引**,可以保证数据库表中每一行数据的唯一性。 - 可以大大**加快数据的检索速度**,这也是创建索引的最主要的原因。 - 帮助服务器**避免排序和临时表**。 - 将**随机IO变为顺序IO**。 - 可以加速**表和表之间的连接**,特别是在实现数据的参考完整性方面特别有意义。 #### 数据库结构优化 - **范式优化**: 比如消除冗余(节省空间。。) - **反范式优化**:比如适当加冗余等(减少join) - **限定数据的范围**: 务必禁止不带任何限制数据范围条件的查询语句。比如:我们当用户在查询订单历史的时候,我们可以控制在一个月的范围内。 - **读/写分离**: 经典的数据库拆分方案,主库负责写,从库负责读; - **拆分表**:分区将数据在物理上分隔开,不同分区的数据可以制定保存在处于不同磁盘上的数据文件里。这样,当对这个表进行查询时,只需要在表分区中进行扫描,而不必进行全表扫描,明显缩短了查询时间,另外处于不同磁盘的分区也将对这个表的数据传输分散在不同的磁盘I/O,一个精心设置的分区可以将数据传输对磁盘I/O竞争均匀地分散开。对数据量大的时时表可采取此方法。可按月自动建表分区。 ### 数据库有什么存储引擎 - MyISAM - Memory - InnoDB - Archive #### InnoDB - 是 MySQL 默认的**事务型**存储引擎,只有在需要它不支持的特性时,才考虑使用其它存储引擎。 - 实现了四个标准的隔离级别,默认级别是**可重复读**(REPEATABLE READ)。在可重复读隔离级别下,**通过多版本并发控制(MVCC)+ 间隙锁(Next-Key Locking)防止幻影读。** - 主索引是**聚簇索引**,在索引中保存了数据,从而避免直接读取磁盘,因此对查询性能有很大的提升。 - 内部做了很多优化,包括从磁盘读取数据时采用的**可预测性读**、能够加快读操作并且自动创建的**自适应哈希索引**、能够加速插入操作的插入缓冲区等。 - 支持真正的**在线热备份**。其它存储引擎不支持在线热备份,要获取一致性视图需要停止对所有表的写入,而在读写混合场景中,停止写入可能也意味着停止读取。 #### MyISAM - 设计简单,数据以**紧密格式存储**。对于只读数据,或者表比较小、可以容忍修复操作,则依然可以使用它。 - 提供了大量的特性,包括**压缩表**、**空间数据索引**等。 - 不支持事务 - 不支持行级锁 - 可以**手工或者自动执行检查和修复操作**,但是和事务恢复以及崩溃恢复不同,**可能导致一些数据丢失,而且修复操作是非常慢的**。 ### innodb是索引和数据一体的放在一个文件,那么如果我新建一个索引,那么会放在哪个文件呢 - [参考-掘金](https://juejin.im/post/5a6873fbf265da3e393a97fa) - [参考-知乎](https://zhuanlan.zhihu.com/p/85553838) - [参考](https://database.51cto.com/art/202002/610953.htm) ### 数据库的MVCC的缺点 > MVCC在大多数情况下代替了行锁,实现了对读的非阻塞,读不加锁,读写不冲突。缺点是每行记录都需要额外的存储空间,需要做更多的行维护和检查工作。 > 要知道的,MVCC机制下,会在更新前建立undo log,根据各种策略读取时非阻塞就是MVCC,undo log中的行就是MVCC中的多版本。 而undo log这个关键的东西,记载的内容是串行化的结果,记录了多个事务的过程,不属于多版本共存。 > 这么一看,似乎mysql的mvcc也并没有所谓的多版本共存 InnoDB的实现方式是: 1. 事务以排他锁的形式修改原始数据 2. 把修改前的数据存放于undo log,通过回滚指针与主数据关联 3. 修改成功(commit),数据放到redo log中,失败则恢复undo log中的数据(rollback) ### 事务的四大特性 - 原子性 > 根据定义,原子性是指一个事务是一个不可分割的工作单位,其中的操作要么都做,要么都不做。即要么转账成功,要么转账失败,是不存在中间的状态! - 隔离性 > 根据定义,隔离性是指多个事务并发执行的时候,事务内部的操作与其他事务是隔离的,并发执行的各个事务之间不能互相干扰。 - 持久性 > 根据定义,持久性是指事务一旦提交,它对数据库的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。 - 一致性 > 根据定义,一致性是指事务执行前后,数据处于一种合法的状态,这种状态是语义上的而不是语法上的。 那什么是合法的数据状态呢? oK,这个状态是满足预定的约束就叫做合法的状态,再通俗一点,这状态是由你自己来定义的。满足这个状态,数据就是一致的,不满足这个状态,数据就是不一致的! ### (a,b,c)是一个组合索引,问where b=10 and a=10是否用了索引,那么where a=10 and b>3 and b<10呢 > 以下参考文章介绍了联合索引的最左原则 - [参考-掘金](https://juejin.im/post/5a6873fbf265da3e393a97fa) - [参考-知乎](https://zhuanlan.zhihu.com/p/85553838) - [参考](https://database.51cto.com/art/202002/610953.htm) ### 解释线程池的三个主要参数 - corePoolSize: 核心线程数线程数定义了最小可以同时运行的线程数量。 - maximumPoolSize: 当队列中存放的任务达到队列容量的时候,当前可以同时运行的线程数量变为最大线程数。 - workQueue: 当新任务来的时候会先判断当前运行的线程数量是否达到核心线程数,如果达到的话,信任就会被存放在队列中。 ### 线程池都有哪几种工作队列 - ArrayBlockingQueue > 是一个基于数组结构的有界阻塞队列,此队列按 FIFO(先进先出)原则对元素进行排序。 - LinkedBlockingQueue > 一个基于链表结构的阻塞队列,此队列按FIFO (先进先出) 排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法Executors.newFixedThreadPool()使用了这个队列 - SynchronousQueue > 一个不存储元素的阻塞队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于LinkedBlockingQueue,静态工厂方法Executors.newCachedThreadPool(5)使用了这个队列。 - PriorityBlockingQueue > 一个具有优先级的无限阻塞队列。 ### Synchronize和ReentrantLock的区别 - 两者都是可重入锁:两者都是可重入锁。“可重入锁”概念是:自己可以再次获取自己的内部锁。比如一个线程获得了某个对象的锁,此时这个对象锁还没有释放,当其再次想要获取这个对象的锁的时候还是可以获取的,如果不可锁重入的话,就会造成死锁。同一个线程每次获取锁,锁的计数器都自增1,所以要等到锁的计数器下降为0时才能释放锁。 - Synchronized 依赖于 JVM 而 ReenTrantLock 依赖于 API」:synchronized 是依赖于 JVM 实现的,前面我们也讲到了 虚拟机团队在 JDK1.6 为 synchronized 关键字进行了很多优化,但是这些优化都是在虚拟机层面实现的,并没有直接暴露给我们。ReenTrantLock 是 JDK 层面实现的(也就是 API 层面,需要 lock() 和 unlock 方法配合 try/finally 语句块来完成),所以我们可以通过查看它的源代码,来看它是如何实现的。 - ReenTrantLock 比 Synchronized 增加了一些高级功能 - 等待可中断:过lock.lockInterruptibly()来实现这个机制。也就是说正在等待的线程可以选择放弃等待,改为处理其他事情。 - 可实现公平锁 - 可实现选择性通知(锁可以绑定多个条件):线程对象可以注册在指定的Condition中,从而可以有选择性的进行线程通知,在调度线程上更加灵活。 在使用notify/notifyAll()方法进行通知时,被通知的线程是由 JVM 选择的,用ReentrantLock类结合Condition实例可以实现“选择性通知” - 性能已不是选择标准:在jdk1.6之前synchronized 关键字吞吐量随线程数的增加,下降得非常严重。1.6之后,synchronized 和 ReenTrantLock 的性能基本是持平了。 ### 公平锁和非公平锁是如何实现的 > ReentrantLock的公平锁和非公平锁 > 学习AQS的时候,了解到AQS依赖于内部的FIFO同步队列来完成同步状态的管理,当前线程获取同步状态失败时,同步器会将当前线程以及等待状态等信息构造成一个Node对象并将其加入到同步队列,同时会阻塞当前线程,当同步状态释放时,会把首节点中的线程唤醒,使其再次尝试获取同步状态。 - ReentrantLock 默认采用非公平锁,除非在构造方法中传入参数 true 。 ```java //默认 public ReentrantLock() { sync = new NonfairSync(); } //传入true or false public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } ``` #### 公平锁的lock方法 ```java static final class FairSync extends Sync { final void lock() { acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { // 1. 和非公平锁相比,这里多了一个判断:是否有线程在等待 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } } ``` > 我们可以看到,在注释1的位置,有个!hasQueuedPredecessors()条件,意思是说当前同步队列没有前驱节点(也就是没有线程在等待)时才会去compareAndSetState(0, acquires)使用CAS修改同步状态变量。所以就实现了公平锁,根据线程发出请求的顺序获取锁。 #### 非公平锁的lock方法 ```java static final class NonfairSync extends Sync { final void lock() { // 2. 和公平锁相比,这里会直接先进行一次CAS,成功就返回了 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } // AbstractQueuedSynchronizer.acquire(int arg) public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } /** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //3.这里也是直接CAS,没有判断前面是否还有节点。 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } ``` > 非公平锁的实现在刚进入lock方法时会直接使用一次CAS去尝试获取锁,不成功才会到acquire方法中,如注释2。而在nonfairTryAcquire方法中并没有判断是否有前驱节点在等待,直接CAS尝试获取锁,如注释3。由此实现了非公平锁。 #### 总结 > 非公平锁和公平锁的两处不同: 1. 非公平锁在调用 lock 后,首先就会调用 CAS 进行一次抢锁,如果这个时候恰巧锁没有被占用,那么直接就获取到锁返回了。 ### AQS都有什么公共方法 - isHeldExclusively()//该线程是否正在独占资源。只有用到condition才需要去实现它。 - tryAcquire(int)//独占方式。尝试获取资源,成功则返回true,失败则返回false。 - tryRelease(int)//独占方式。尝试释放资源,成功则返回true,失败则返回false。 - tryAcquireShared(int)//共享方式。尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。 - tryReleaseShared(int)//共享方式。尝试释放资源,成功则返回true,失败则返回false。 ### Spring框架Bean的生命周期 - ![bean的生命周期](https://user-gold-cdn.xitu.io/2020/4/1/171353f25c01690b?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) ### 那单例模式和prototype模式,spring都是怎么实现的 - Spring为实现单例类可继承,使用的是单例注册表的方式 - 使用map实现注册表; - 使用protect修饰构造方法; - Spring中,如果一个类被标记为”prototype”,每一次请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)都会产生一个新的bean实例。 > 但是,Spring不能对一个prototype Bean的整个生命周期负责,容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法,而对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype作用域的对象并释放任何prototype bean所持有的昂贵资源,都是客户端代码的职责。 ### session和cookie的区别 #### cookie Cookie 是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器之后向同一服务器再次发起请求时被携带上,用于告知服务端两个请求是否来自同一浏览器。由于之后每次请求都会需要携带 Cookie 数据,因此会带来额外的性能开销(尤其是在移动环境下)。 - 会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息) - 个性化设置(如用户自定义设置、主题等) - 浏览器行为跟踪(如跟踪分析用户行为等) #### session Session 可以存储在服务器上的文件、数据库或者内存中。也可以将 Session 存储在 Redis 这种内存型数据库中,效率会更高。 - 用户进行登录时,用户提交包含用户名和密码的表单,放入 HTTP 请求报文中; - 服务器验证该用户名和密码,如果正确则把用户信息存储到 Redis 中,它在 Redis 中的 Key 称为 Session ID; - 服务器返回的响应报文的 Set-Cookie 首部字段包含了这个 Session ID,客户端收到响应报文之后将该 Cookie 值存入浏览器中; - 客户端之后对同一个服务器进行请求时会包含该 Cookie 值,服务器收到之后提取出 Session ID,从 Redis 中取出用户信息,继续之前的业务操作。 注意:Session ID 的安全性问题,不能让它被恶意攻击者轻易获取,那么就不能产生一个容易被猜到的 Session ID 值。此外,还需要经常重新生成 Session ID。在对安全性要求极高的场景下,例如转账等操作,除了使用 Session 管理用户状态之外,还需要对用户进行重新验证,比如重新输入密码,或者使用短信验证码等方式 Cookie和Session的选择 ### get请求和post请求的区别 1. GET使用URL或Cookie传参,而POST将数据放在BODY中 2. GET方式提交的数据有长度限制,则POST的数据则可以非常大 3. POST比GET安全,因为数据在地址栏上不可见,没毛病 4. **本质区别**:GET请求是幂等性的,POST请求不是。 > 这里的幂等性:幂等性是指一次和多次请求某一个资源应该具有同样的副作用。简单来说意味着对同一URL的多个请求应该返回同样的结果。 ### 线程和进程 #### 进程 - **进程**是**程序的一次执行过程**,是**系统运行程序的基本单位**,因此进程是动态的。 - 系统运行一个程序即是一个进程从创建,运行到消亡的过程。简单来说,**一个进程就是一个执行中的程序**, - 它在计算机中一个指令接着一个指令地执行着,同时,每个进程还占有某些系统资源如CPU时间,内存空间,文件,输入输出设备的使用权等等。 - 换句话说,当程序在执行时,将会被操作系统载入内存中。 - **线程是进程划分成的更小的运行单位**。 - 线程和进程最大的不同在于基本上各进程是独立的,而各线程则不一定,因为同一进程中的线程极有可能会相互影响。 - 从另一角度来说,进程属于操作系统的范畴,主要是同一段时间内,可以同时执行一个以上的程序,而线程则是在同一程序内几乎同时执行一个以上的程序段。 #### 线程 - **线程**与进程相似,但**线程是一个比进程更小的执行单位**。 - 一个进程在其执行的过程中可以产生**多个线程**。 - 与进程不同的是同类的**多个线程共享同一块内存空间和一组系统资源**,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,**线程也被称为轻量级进程**。 ### 搜索关键字在日志文件中哪一行是什么命令,看最后1000行数据的命令 - 搜索关键字 > cat 文件名 | grep "关键词" > grep -i "关键词" 文件名 - 查看前、后n行的数据的命令 > `head -n 10 /etc/profile` > `tail -n 5 /etc/profile` ### 计算机网络应用层都有什么协议 ![协议端口号](http://media.dreamcat.ink/uPic/EuHz2s.png) ### tcp的滑动窗口是怎么工作的 > TCP滑动窗口技术通过动态改变窗口大小来调节两台主机间数据传输 > TCP 中采用滑动窗口来进行传输控制,滑动窗口的大小意味着接收方还有多大的缓冲区可以用于接收数据。 > 发送方可以通过滑动窗口的大小来确定应该发送多少字节的数据。当滑动窗口为 0 时,发送方一般不能再发送数据报,但有两种情况除外,一种情况是可以发送紧急数据, > 例如,允许用户终止在远端机上的运行进程。另一种情况是发送方可以发送一个 1 字节的数据报来通知接收方重新声明它希望接收的下一字节及发送方的滑动窗口大小。 ### GC的CMS回收器的步骤 - 初始标记:暂停所有的其他线程,并记录下直接与 root 相连的对象,速度很快 ; - 并发标记: 同时开启 GC 和用户线程,用一个闭包结构去记录可达对象。但在这个阶段结束,这个闭包结构并不能保证包含当前所有的可达对象。因为用户线程可能会不断的更新引用域,所以 GC 线程无法保证可达性分析的实时性。所以这个算法里会跟踪记录这些发生引用更新的地方。 - 重新标记: 重新标记阶段就是为了修正并发标记期间因为用户程序继续运行而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段的时间稍长,远远比并发标记阶段时间短 - 并发清除:开启用户线程,同时 GC 线程开始对为标记的区域做清扫。 ## 美团成都二面 ### 数据库索引的实现方式(hash,B+) #### 哈希索引 哈希索引就是采用一定的哈希算法,把键值换算成新的哈希值,检索时不需要类似B+树那样从根节点到叶子节点逐级查找,只需一次哈希算法即可立刻定位到相应的位置,速度非常快。 #### B+ - MyISAM MyISAM,**B+Tree叶节点的data域存放的是数据记录的地址**,在索引检索的时候,首先按照B+Tree搜索算法搜索索引,如果指定的key存在,则取出其data域的值,然后以data域的值为地址读区相应的数据记录,这被称为“非聚簇索引” - InnoDB InnoDB,其数据文件本身就是索引文件,相比MyISAM,**索引文件和数据文件是分离的**,**其表数据文件本身就是按B+Tree组织的一个索引结构,树的节点data域保存了完整的数据记录**,这个索引的key是数据表的主键,因此InnoDB表数据文件本身就是主索引。 这被称为“聚簇索引”或者聚集索引,而其余的索引都作为辅助索引,辅助索引的data域存储相应记录主键的值而不是地址,这也是和MyISAM不同的地方,在根据主索引搜索时,直接找到key所在的节点即可取出数据;在根据辅助索引查找时,则需要先取出主键的值,在走一遍主索引。 因此,在设计表的时候,不建议使用过长的字段为主键,也不建议使用非单调的字段作为主键,这样会造成主索引频繁分裂。 #### 二者区别 - 如果是等值查询,那么哈希索引明显有绝对优势,因为只需要经过一次算法即可找到相应的键值;当然了,这个前提是,键值都是唯一的。如果键值不是唯一的,就需要先找到该键所在位置,然后再根据链表往后扫描,直到找到相应的数据; - 如果是范围查询检索,这时候哈希索引就毫无用武之地了,因为原先是有序的键值,经过哈希算法后,有可能变成不连续的了,就没办法再利用索引完成范围查询检索; - 同理,哈希索引也没办法利用索引完成排序,以及like ‘xxx%’ 这样的部分模糊查询(这种部分模糊查询,其实本质上也是范围查询); - 哈希索引也不支持多列联合索引的最左匹配规则; - B+树索引的关键字检索效率比较平均,不像B树那样波动幅度大,在有大量重复键值情况下,哈希索引的效率也是极低的,因为存在所谓的哈希碰撞问题。 ### MySQL的的默认隔离级别、防止了什么读? **脏读和可重复读** ### 可重复读级别下的MySQL可以防止幻读吗,如何实现的? 用next-key lock可以防止,快照读不可以 ### 为什么数据库用B+树而不用B树 > B树(英语: B-tree)是一种自平衡的树,能够保持数据有序。这种数据结构能够让查找数据、顺序访问、插入数据及删除的动作,都在对数时间内完成。B树,概括来说是一个一般化的二叉查找树(binary search tree),可以拥有最多2个子节点。与自平衡二叉查找树不同,B树适用于读写相对大的数据块的存储系统,例如磁盘。 > B+ 树是一种树数据结构,通常用于关系型数据库(如Mysql)和操作系统的文件系统中。B+ 树的特点是能够保持数据稳定有序,其插入与修改拥有较稳定的对数时间复杂度。B+ 树元素自底向上插入,这与二叉树恰好相反。 > 在B树基础上,为叶子结点增加链表指针(B树+叶子有序链表),所有关键字都在叶子结点 中出现,非叶子结点作为叶子结点的索引;B+树总是到叶子结点才命中。 > b+树的非叶子节点不保存数据,只保存子树的临界值(最大或者最小),所以同样大小的节点,b+树相对于b树能够有更多的分支,使得这棵树更加矮胖,查询时做的IO操作次数也更少。 ### Object类里面有什么方法 - clone方法 > 保护方法,实现对象的浅复制,只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedException异常。 - getClass方法 > final方法,获得运行时类型。 - toString方法 > 该方法用得比较多,一般子类都有覆盖。 - finalize方法 > 该方法用于释放资源。因为无法确定该方法什么时候被调用,很少使用。 - equals方法 > 该方法是非常重要的一个方法。一般equals和==是不一样的,但是在Object中两者是一样的。子类一般都要重写这个方法。 - hashCode方法 > 该方法用于哈希查找,重写了equals方法一般都要重写hashCode方法。这个方法在一些具有哈希功能的Collection中用到。 - wait方法 > wait方法就是使当前线程等待该对象的锁,当前线程必须是该对象的拥有者,也就是具有该对象的锁。wait()方法一直等待,直到获得锁或者被中断。wait(long timeout)设定一个超时间隔,如果在规定时间内没有获得锁就返回。 > 调用该方法后当前线程进入睡眠状态,直到以下事件发生。 > - 其他线程调用了该对象的notify方法。 > - 其他线程调用了该对象的notifyAll方法。 > - 其他线程调用了interrupt中断该线程。 > - 时间间隔到了。 - notify方法 > 该方法唤醒在该对象上等待的某个线程。 - notifyAll方法 > 该方法唤醒在该对象上等待的所有线程。 ### 四次挥手的过程 - 客户端-发送一个 FIN,用来关闭客户端到服务器的数据传送 - 服务器-收到这个 FIN,它发回一 个 ACK,确认序号为收到的序号加1 。和 SYN 一样,一个 FIN 将占用一个序号 - 服务器-关闭与客户端的连接,发送一个FIN给客户端 - 客户端-发回 ACK 报文确认,并将确认序号设置为收到序号加1 > 任何一方都可以在数据传送结束后发出连接释放的通知,待对方确认后进入半关闭状态。当另一方也没有数据再发送的时候,则发出连接释放通知,对方确认后就完全关闭了TCP连接。举个例子:A 和 B 打电话,通话即将结束后,A 说“我没啥要说的了”,B回答“我知道了”,但是 B 可能还会有要说的话,A 不能要求 B 跟着自己的节奏结束通话,于是 B 可能又巴拉巴拉说了一通,最后 B 说“我说完了”,A 回答“知道了”,这样通话才算结束。 ### Linux命令,如何查看所有端口信息 - lsof > lsof -i:端口号 - netstat > netstat -tunlp | grep 端口号 > netstat -ntlp //查看当前所有tcp端口 ### 跳台阶的那道经典dp题目,口述如何解决 ```java class Solution { public int climbStairs(int n) { if(n <= 2) return n; int[] dp = new int[n + 1]; dp[1] = 1; dp[2] = 2; for (int i = 3; i <= n; i++) { dp[i] = dp[i-1] + dp[i-2]; } return dp[n]; } } ``` ### 写代码:写双重验证的单例模式 ```java public class Singleton { private volatile static Singleton uniqueInstance; // 第一步 private Singleton() { // 第二步,私有 } public static Singleton getUniqueInstance() { //先判断对象是否已经实例过,没有实例化过才进入加锁代码 if (uniqueInstance == null) { // 双重校验 //类对象加锁 synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } } ``` ### 单链表反转 ```java class Solution { public ListNode reverseList(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } } ``` ## 美团成都三面 ### redis如何保持和mysql的数据一致性 一般来说,就是如果你的系统不是严格要求缓存+数据库必须一致性的话,缓存可以稍微的跟数据库偶尔有不一致的情况,最好不要做这个方案,**读请求和写请求串行化,串到一个内存队列里去**,这样就可以保证一定不会出现不一致的情况 ### 说一下都有什么类型二叉树 - 二叉查找树-BST - 平衡二叉树-AVL - 红黑树 - B-树 - B+树 ### 构建一个二叉树,做前序的非递归遍历 ```java public static ArrayList preOrder1(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList alist = new ArrayList(); TreeNode p = root; while(p != null || !stack.empty()){ while(p != null){ alist.add(p.val); stack.push(p); p = p.left; } if(!stack.empty()){ TreeNode temp = stack.pop(); p = temp.right; } } return alist; } ``` <file_sep>package normal; import java.util.Stack; /** * @program JavaBooks * @description: 232.用栈实现队列 * @author: mf * @create: 2019/11/07 14:55 */ /* 题目:https://leetcode-cn.com/problems/implement-queue-using-stacks/ 类型:栈 难度:easy */ /* MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false */ public class MyQueue { private Stack<Integer> in; private Stack<Integer> out; public static void main(String[] args) { MyQueue myQueue = new MyQueue(); myQueue.push(1); myQueue.push(2); System.out.println(myQueue.peek()); System.out.println(myQueue.pop()); System.out.println(myQueue.empty()); } public MyQueue() { in = new Stack<>(); out = new Stack<>(); } public void push (int x) { in.push(x); } public int pop () { if (out.isEmpty()) { while (! in.isEmpty()) { out.push(in.pop()); } } return out.pop(); } public int peek () { if (out.isEmpty()) { while (! in.empty()) { out.push(in.pop()); } } return out.peek(); } public boolean empty() { return in.isEmpty() && out.isEmpty(); } } <file_sep>package books; /** * @program JavaBooks * @description: 二叉搜索树的后序遍历序列 * @author: mf * @create: 2019/09/14 21:15 */ /* 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果 如果是则返回true,否则返回false。假设输入的数组的任意两个数字 都互不相同。例如,输入数组{5, 7, 6, 9, 11, 10, 8}, 则返回true 因为这个整数序列是书上图4.9二叉搜索树的后序遍历结果。如果输入的数组是 {7,4,6,5} */ public class T33 { public static void main(String[] args) { int[] sequence = {5, 7, 6, 9, 11, 10, 8}; boolean res = VerifySquenceOfBST(sequence); System.out.println(res); } private static boolean VerifySquenceOfBST(int[] sequence) { if (sequence == null || sequence.length == 0) return false; return isBST(sequence, 0, sequence.length - 1); } private static boolean isBST(int[] sequence, int start, int end) { if (start >= end) { return true; } int inx = sequence[end]; int m = start; // 找到分界点 for (int i = end - 1; i >= start; i--) { if (sequence[i] < inx) { m = i; break; } if (i == start) { m = -1; } } // 分界点前的数据都小于根节点 for (int i = start; i <= m; i++) { if (sequence[i] > inx) { return false; } } // 递归判断根节点的左右子树 return isBST(sequence, start, m) && isBST(sequence, m + 1, end - 1); } } <file_sep>## 引言 > 最近看了看分布式架构,尝试了一下dubbo,注册中心是hiZookeeper,所以先在centos下配置环境吧。 <!-- more --> ## 前提 - 系统:Centos7 - 安装[Java](http://dreamcat.ink/2019/07/08/windows-mac-he-linux-an-zhuang-java/)环境 - [下载地址](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) - 选择Linux 64位tar.gz - 我一般将它放进`/usr/local/myapps`,myapps是存放自己的软件等。 - 解压`tar -xzvf xxx`,xxx指的刚才下载的jdk - 添加java的环境变量,打开`vim /etc/profile` - 在蓝色字体下面添加 - ```bash JAVA_HOME=/usr/local/myapps/jdk1.8.0_221 # 这是我的java存放的地址 PATH=$JAVA_HOME/bin:$PATH export JAVA_HOME PATH ``` - 更新`source /etc/profile` - 查看是否添加成功`javac `即可 ## 安装Zookeeper - [下载地址](https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/) - 选择3.4.14版本下载即可,放进和刚才的myapps下。 - 解压:`tar -zxf zookeeper-3.4.14.tar.gz` - 将配置文件`cp -r zoo_sample.cfg zoo.cfg` - 启动zookeeper`./zkServer.sh start` ## 安装Dubbo Dubbo的源码[github](https://github.com/apache/dubbo/tree/2.5.x) 我提前编译好的[dubbo.war](https://www.lanzous.com/i7xn2di). [dubbo-monitor-simple](https://www.lanzous.com/i7xn1ih) - 下载2.5.x版本的zip - 前提是系统装了maven环境,可以编译生成war。 - 解压分别进入dubbo-admin和Dubbo-simple->Dubbo-monitor-simple,执行`mvn package` - 分别在target文件下找到了对应的一个war包和tar.gz包 - 解压 `tar -zxf dubbo-monitor-simple-2.0.0-assembly.tar.gz` - 进入配置文件修改`vim dubbo.properties` - 将注册中心#去掉,`dubbo.registry.address=zookeeper://127.0.0.1:2181` - 将multicast注册中心加# - 如果是低配置云服务器,记得修改`vim start.sh`的内存大小,512m,原来2g - 然后启动dubbo`./start.sh start` - 记得防火墙设置,可以加端口,也可以直接关掉防火墙 - 加端口:如果在`/etc/sysconfig/iptables`,那默认是firewall防火墙,所以卸载 - `systemctl stop firewalld ` - `systemctl mask firewalld` - `yum install -y iptables` - `yum install iptables-services` - 开启服务`systemctl start iptables.service` - 设置防火墙启动`systemctl enable iptables.service` - 然后执行`vim /etc/sysconfig/iptables`模仿22端口添加即可 - 记得添加2181,8080 ## 安装tomcat 由于dubbo.war在tomcat容器中运行,所以先下载tomcat,其实tomcat不用安装,下载解压即可。 - [下载地址](http://tomcat.apache.org/) - 选择左边栏中的**tomcat8** - 选择core中的**tar.gz**下载 - 然后放在`myapps`路径下:`/usr/local/myapps`下 - 解压:`tar -zxf apache-tomcat-8.5.47` - 修改端口`cd conf` - `vim server.xml`将8080改为8088,因为不改的话会和dubbo冲突 - 将webapps下的ROOT目录下的文件全部删除`rm -rf ./*`即可 - 将dubbo.war存放在刚才的ROOT目录下 - 解压:`unzip dubbo.war -d apache-tomcat-8.5.47/webapps/ROOT/` - 如果提示没有unzip的话,安装`yum install -y unzip zip` - 去bin目录下启动`./startup.sh` - 记得添加防火墙 - 访问对应的ip加端口:8088之后,guest账户和密码guest,root账户和密码是root<file_sep>package web; /** * @program LeetNiu * @description: * @author: mf * @create: 2020/01/16 14:23 */ public class TreeLinkNode { int val; TreeLinkNode left = null; TreeLinkNode right = null; TreeLinkNode next = null; public TreeLinkNode(int val) { this.val = val; } } <file_sep>- [idea配置class反编译工具](https://www.itread01.com/content/1549811589.html)<file_sep>package books; import javax.naming.RefAddr; /** * @program JavaBooks * @description: 表示数值的字符串 * @author: mf * @create: 2019/09/01 10:16 */ /* 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如 字符串"+100"、"5e2"、"-123"、"3。1416"及"-1E-16"都表示数值。 但"12e"、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是 */ /* 数字的格式可以用A[.[B]][e|EC]表示,其中A和C都是 整数(可以有正负号,也可以没有),而B是一个无符号整数 */ public class T20 { public static void main(String[] args) { char[] str = {'1', '2', '3', '.', '4', '5', 'e', '+', '6'}; boolean res = isNumeric(str); System.out.println(res); } private static boolean isNumeric(char[] str) { int index = 0; if (str == null || str.length == 0) return false; if (str.length == 1 && (str[0] == '+' || str[0] == '-')) return false; // 说明只有一个字符,要不+要不- if (str[0] == '+' || str[0] == '-') index++; // 跳过+ 或者- index = judgeDigits(str, index); // 跳过整数的数字部分 if (index == str.length) return true; // 正好满足 if (str[index] == '.') { // 跳过整数, 就是小数点了 //跳过小数点 index++; if (index == str.length) return false; // 不满足 index = judgeDigits(str, index); // 跳过小数点后的整数部分 if (index == str.length) return true; // 正好满足就返回 if (str[index] == 'e' || str[index] == 'E') { index++; // 吧e和E跳过去 return judgeE(str, index); } return false; } else if(str[index] == 'e' || str[index] == 'E') { index++; // 吧e和E跳过去 return judgeE(str, index); } return false; } private static boolean judgeE(char[] str, int index) { if (index >= str.length) return false; if (str[index] == '+' || str[index] == '-') index++; // 跳过+ 或者- if (index >= str.length) return false;//如果刚跳过e就到了字符串末尾 是12e就是不规范的 index = judgeDigits(str, index); // 跳过数字部分部分 if (index == str.length) return true; return false; } private static int judgeDigits(char[] str, int index) { while (index < str.length) { // 判断是不是0-9之间,不是的话就break返回index下标 int number = str[index] - '0'; if (number <= 9 && number >= 0) index++; else break; } return index; } } <file_sep>package web; /** * @program LeetNiu * @description: 树的子结构 * @author: mf * @create: 2020/01/10 16:07 */ /** * 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) */ public class T17 { public boolean HasSubtree(TreeNode root1,TreeNode root2) { // 判断 if (root1 == null || root2 == null) return false; boolean result = false; if (root1.val == root2.val) { result = goOnFind(root1, root2); } if (!result) { result = HasSubtree(root1.left, root2); } if (!result) { result = HasSubtree(root1.right, root2); } return result; } /** * 递归找 * @param root1 * @param root2 * @return */ private boolean goOnFind(TreeNode root1, TreeNode root2) { if (root2 == null) return true; if (root1 == null) return false; if (root1.val != root2.val) return false; return goOnFind(root1.left, root2.left) && goOnFind(root1.right, root2.right); } } <file_sep>> 个人感觉掌握常用的集合类,看其中的源码即可,有很多其实都差不多的,把个别不同的源码多看看,其实就是增删查 > > 比如,常见的ArrayList、LinkedList、HashMap和ConcurrentHashMap经常被问到的多准备准备。 > > 这一块就是看源码分析,没别的 ### ArrayList #### 概述 - *ArrayList*实现了*List*接口,是顺序容器,即元素存放的数据与放进去的顺序相同,允许放入`null`元素,底层通过**数组实现**。 - 除该类未实现同步外,其余跟*Vector*大致相同。 - 每个*ArrayList*都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多于当前容量。 - 当向容器中添加元素时,如果容量不足,**容器会自动增大底层数组的大小**。 - 前面已经提过,Java泛型只是编译器提供的语法糖,所以这里的数组是一个Object数组,以便能够容纳任何类型的对象。 ![](https://www.pdai.tech/_images/collection/ArrayList_base.png) - size(), isEmpty(), get(), set()方法均能在**常数时间**内完成,add()方法的时间开销跟插入位置有关,addAll()方法的时间开销跟添加元素的个数成正比。其余方法大都是线性时间。 - 为追求效率,ArrayList没有实现同步(**synchronized**),如果需要多个线程并发访问,用户可以手动同步,也可使用Vector替代。 #### 实现 ##### 底层数据结构 ```java transient Object[] elementData; // Object 数组 private int size; // 大小 ``` ##### 构造函数 ```java // 参数为容量的构造参数 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; // 默认 } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } // 无参的构造参数 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; // 默认容量 } public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } } ``` ##### 自动扩容 ```java public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } ``` - 每当向数组中添加元素时,都要去检查添加后**元素的个数是否会超出当前数组的长度**,如果超出,**数组将会进行扩容**,以满足添加数据的需求。 - 数组扩容通过一个公开的方法`ensureCapacity(int minCapacity)`来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。 - 数组进行扩容时,会将老数组中的元素重新**拷贝**一份到新的数组中,每次数组容量的增长大约是其原容量的**1.5倍**。 - 这种操作的代价是很高的,因此在实际使用时,我们应该**尽量避免数组容量的扩张**。 - 当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就**指定其容量**,以避免数组扩容的发生。 - 或者根据实际需求,通过调用ensureCapacity方法来手动增加ArrayList实例的容量。 ![扩容](https://www.pdai.tech/_images/collection/ArrayList_grow.png) ##### add() 是向容器中添加新元素,这可能会导致*capacity*不足,因此在添加元素之前,都需要进行剩余空间检查,如果需要则自动扩容。扩容操作最终是通过`grow()`方法完成的。 ```java public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! // 多线程容易出问题 elementData[size++] = e; // 这里也是 return true; } public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } ``` ##### get() `get()`方法同样很简单,唯一要注意的是由于底层数组是Object[],得到元素后需要进行类型转换。 ```java public E get(int index) { rangeCheck(index); return (E) elementData[index];//注意类型转换 } ``` ##### remove() `remove()`方法也有两个版本,一个是`remove(int index)`删除指定位置的元素,另一个是`remove(Object o)`删除第一个满足`o.equals(elementData[index])`的元素。删除操作是`add()`操作的逆过程,需要将删除点之后的元素向前移动一个位置。需要注意的是为了让**GC**起作用,必须显式的为最后一个位置赋`null`值。 ```java public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; //清除该位置的引用,让GC起作用 return oldValue; } ``` ##### indexOf() **循环遍历用equals** ```java public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } ``` ##### Fail-Fast机制 ArrayList也采用了**快速失败的机制**,**通过记录modCount参数来实现**。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。 ##### 多线程问题 [请参考->个人吐血系列-总结java多线程](http://dreamcat.ink/2020/03/25/ge-ren-tu-xie-xi-lie-zong-jie-java-duo-xian-cheng/#toc-heading-14) ### LinkedList #### 概述 **LinkedList**同时实现了**list**接口和**Deque**接口,也就是说它既可以看作一个**顺序容器**,又可以看作**一个队列(Queue)**,同时又可以看作**一个栈(Stack)**。这样看来,LinkedList简直就是个全能冠军。当你需要使用栈或者队列时,可以考虑使用LinkedList,一方面是因为Java官方已经声明不建议使用Stack类,更遗憾的是,Java里根本没有一个叫做Queue的类(它是个接口名字)。**关于栈或队列,现在的首选是ArrayDeque,它有着比LinkedList(当作栈或队列使用时)有着更好的性能**。 ![LinkedList](https://www.pdai.tech/_images/collection/LinkedList_base.png) LinkedList的实现方式决定了所有跟**下标相关的操作都是线性时间**,而在**首段或者末尾删除元素只需要常数时间**。为追求效率LinkedList没有实现同步(synchronized),如果需要多个线程并发访问,可以先采用`Collections.synchronizedList()`方法对其进行包装。 #### 实现 ##### 底层数据接口 ```java transient int size = 0; transient Node<E> first; // 经常用到 transient Node<E> last; // 也经常用到 // Node是私有的内部类 private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } } ``` LinkedList底层**通过双向链表实现**,本节将着重讲解插入和删除元素时双向链表的维护过程,也即是之间解跟List接口相关的函数。双向链表的每个节点用内部类Node表示。LinkedList通过`first`和`last`引用分别指向链表的第一个和最后一个元素。注意这里没有所谓的哑元,当链表为空的时候`first`和`last`都指向`null`。 ##### 构造函数 ```java public LinkedList() { } public LinkedList(Collection<? extends E> c) { this(); addAll(c); } ``` ##### getFirst(),getLast() **本身在数据结构中,维护了first和last的变量,因此其实挺简单的**。 ```java public E getFirst() { final Node<E> f = first; // 获取第一个元素 if (f == null) throw new NoSuchElementException(); return f.item; } public E getLast() { final Node<E> l = last; // 获取最后一个元素 if (l == null) throw new NoSuchElementException(); return l.item; } ``` ##### removeFirst(),removeLast(),remove(e),remove(index) ![remove](https://www.pdai.tech/_images/collection/LinkedList_remove.png) **删除元素** - 指的是删除第一次出现的这个元素, 如果没有这个元素,则返回false;判读的依据是`equals`方法, 如果equals,则直接unlink这个node;由于LinkedList可存放null元素,故也可以删除第一次出现null的元素; ```java public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { // 循环遍历 用equals判断 unlink(x); return true; } } } return false; } E unlink(Node<E> x) { // assert x != null; final E element = x.item; // 当前元素 final Node<E> next = x.next; // 指向下一个节点 final Node<E> prev = x.prev; // 上一个节点 if (prev == null) {// 第一个元素,如果该节点的上节点为空,那么就把该节点的下个节点放在第一个位置 first = next; } else { prev.next = next; // 不为空,则把上个节点指向该节点的下个节点 x.prev = null; } if (next == null) {// 最后一个元素 last = prev; } else { next.prev = prev; x.next = null; } x.item = null; // GC size--; modCount++; return element; } ``` `remove(int index)`使用的是下标计数, 只需要判断该index是否有元素即可,如果有则直接unlink这个node。 ```java public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } ``` `removeFirst()`其实挺简单的 ```java public E removeFirst() { final Node<E> f = first; // 拿到firs直接unlink if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } private E unlinkFirst(Node<E> f) { // assert f == first && f != null; final E element = f.item; // first e final Node<E> next = f.next; // first 没有 pre , 只有next f.item = null; f.next = null; // help GC first = next; // 让first指向next if (next == null) // 如果next为空,则当前元素已经是最后一个元素了,那么last自然为空 last = null; else next.prev = null; // 如果不为空,next的上个节点指向为空 size--; modCount++; return element; } ``` `removLast()`其实挺简单的,和上面差不多 ```java public E removeLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } private E unlinkLast(Node<E> l) { // assert l == last && l != null; final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; } ``` ##### add() ```java public boolean add(E e) { linkLast(e); // 在链表末尾插入元素,所以常数时间 return true; } void linkLast(E e) { // 其实就是最后面修改引用 final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } ``` `add(int index, E element)`, 当index==size时,等同于add(E e); 如果不是,则分两步:1.先根据index找到要插入的位置,即node(index)方法;2.修改引用,完成插入操作,其实想就是遍历插入。 ##### indexOf() 循环遍历equals,找到对应的下标 ```java public int indexOf(Object o) { int index = 0; // 维护index if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) // 用equals return index; index++; } } return -1; } ``` ### HashMap(面试常问) 众所周知,HashMap的底层结构是**数组和链表**组成的,不过在jdk1.7和jdk1.8中具体实现略有不同。 ![底层结构](https://i.loli.net/2019/05/08/5cd1d2be77958.jpg) #### 1.7的实现 ##### 成员变量 这里,就不贴1.7版本的源码了,因此贴图。 ![](https://i.loli.net/2019/05/08/5cd1d2bfd6aba.jpg) 介绍成员变量: 1. **初始化桶大小**,因为底层是数组,所以这是数组默认的大小。 2. **桶最大值**。 3. 默认的**负载因子**(0.75) 4. table真正存放数据的数组。 5. map存放数量的大小 6. 桶大小,可在构造函数时显式指定。 7. 负载因子,可在构造函数时显式指定。 ##### 负载因子 ```java public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); // 桶和负载因子 } public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; // 只能获取默认的最大值 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; in ``` - **给定的默认容量为16,负载因子为0.75**. - Map在使用过程中不断的往里面存放数据,当数量达到了`16 * 0.75 = 12`就需要将当前16的容量进行扩容,而扩容这个过程涉及到`rehash`(重新哈希)、复制数据等操作,所有非常消耗性能。 - 因此通常建议能提前预估HashMap的大小最好,尽量的减少扩容带来的额外性能损耗。 - 关于这部分后期专门出一篇文章进行讲解。 ##### Entry ![Entry](https://i.loli.net/2019/05/08/5cd1d2c08e693.jpg) Entry是**Hashmap中的一个内部类**,从他的成员变量很容易看出: - key就是写入时的键 - value自然就是值 - 开始的时候就提到HashMap是由数组和链表组成,所以这个next就是用于实现链表结构 - hash存放的是当前key的hashcode ##### put(重点来了) ```java public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); // 判断数组是否需要初始化 } if (key == null) return putForNullKey(value); // 判断key是否为空 int hash = hash(key); // 计算hashcode int i = indexFor(hash, table.length); // 计算桶 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { // 遍历判断链表中的key和hashcode是否相等,等就替换 V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); // 没有就添加新的呗 return null; } ``` - 判断当前数组是否需要初始化 - 如果key为空,则put一个空值进去 - 根据key计算hashcode - 根据计算的hashcode定位index的桶 - 如果桶是一个链表,则需要遍历判断里面的hashcode、key是否和传入的key相等,如果相等则进行覆盖,并返回原来的值 - 如果桶是空的,说明当前位置没有数据存入,此时新增一个Entry对象写入当前位置。 ```java void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) {// 是否扩容 resize(2 * table.length); // 两倍扩容 重新哈希 hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; } ``` - 当调用addEntry写入Entry时需要判断是否需要扩容 - 如果需要就进行**两倍扩充**,并将当前的key重新hash并定位。 - 而在createEntry中会将当前位置的桶传入到新建的桶中,如果当前桶有值就会在位置形成链表。 ##### get ```java public V get(Object key) { if (key == null) // 判断key是否为空 return getForNullKey(); // 为空,就返回空值 Entry<K,V> entry = getEntry(key); // get entry return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); //根据key和hashcode for (Entry<K,V> e = table[indexFor(hash, table.length)]; //循环遍历equals key拿值 e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; } ``` - 首先根据key计算hashcode,然后定位具体的桶 - 判断该位置是否为链表 - 不是链接就根据key和hashcode是否相等来返回值 - 为链表则需要遍历直到key和hashcode相等就返回值 - 啥都没得,就返回null #### 1.8的实现 不知道 1.7 的实现大家看出需要优化的点没有? 其实一个很明显的地方就是链表 **当 Hash 冲突严重时,在桶上形成的链表会变的越来越长,这样在查询时的效率就会越来越低;时间复杂度为 `O(N)`。** ![](https://i.loli.net/2019/05/08/5cd1d2c1c1cd7.jpg) ##### 成员变量 ```java static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; static final int TREEIFY_THRESHOLD = 8; transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; ``` - `TREEIFY_THRESHOLD` 用于判断是否需要将链表转换为红黑树的阈值。 - HashEntry 修改为 Node。 - Node 的核心组成其实也是和 1.7 中的 HashEntry 一样,存放的都是 `key value hashcode next` 等数据。 ##### put ```java /** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) // 1. 判断当前桶是否为空,空的就需要初始化(resize中会判断是否进行初始化) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) // 2. 根据当前key的hashcode定位到具体的桶中并判断是否为空,为空则表明没有Hash冲突,就直接在当前位置创建一个新桶 tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && // 3. 如果当前桶有值(Hash冲突),那么就要比较当前桶中的key、key的hashcode与写入的key是否相等,相等就赋值给e,在第8步的时候会统一进行赋值及返回 ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) // 4. 如果当前桶为红黑树,那就要按照红黑树的方式写入数据 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { // 5. 如果是个链表,就需要将当前的key、value封装称一个新节点写入到当前桶的后面形成链表。 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st // 6. 接着判断当前链表的大小是否大于预设的阈值,大于就要转换成为红黑树 - treeifyBin(tab, hash); break; } if (e.hash == hash && // 7. 如果在遍历过程中找到key相同时直接退出遍历。 ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key 8. 如果`e != null`就相当于存在相同的key,那就需要将值覆盖。 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) // 9. 最后判断是否需要进行扩容。 resize(); afterNodeInsertion(evict); return null; } ``` - 判断当前桶是否为空,空的就需要初始化(resize中会判断是否进行初始化) - 根据当前key的hashcode定位到具体的桶中并判断是否为空,为空则表明没有Hash冲突,就直接在当前位置创建一个新桶 - 如果当前桶有值(Hash冲突),那么就要比较当前桶中的key、key的hashcode与写入的key是否相等,相等就赋值给e,在第8步的时候会统一进行赋值及返回 - 如果当前桶为**红黑树**,那就要按照红黑树的方式写入数据 - 如果是个链表,就需要将当前的key、value封装称一个新节点写入到当前桶的后面形成链表。 - 接着判断当前链表的大小是否**大于预设的阈值**,大于就要转换成为**红黑树** - 如果在遍历过程中找到key相同时直接退出遍历。 - 如果`e != null`就相当于存在相同的key,那就需要将值覆盖。 - 最后判断是否需要进行扩容。 ##### get ```java public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } ``` - 首先将key hash之后取得所定位的桶 - 如果桶为空,则直接返回null - 否则判断桶的第一个位置(有可能是链表、红黑树)的key是否为查询的key,是就直接返回value - 如果第一个不匹配,则判断它的下一个是红黑树还是链表 - 红黑树就按照树的查找方式返回值 - 不然就按照链表的方式遍历匹配返回值 **从这两个核心方法(get/put)可以看出 1.8 中对大链表做了优化,修改为红黑树之后查询效率直接提高到了 `O(logn)`。** #### 问题 但是 HashMap 原有的问题也都存在,比如在并发场景下使用时容易出现**死循环**。 ```java final HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { @Override public void run() { map.put(UUID.randomUUID().toString(), ""); } }).start(); } ``` - HashMap扩容的时候会调用resize()方法,就是这里的并发操作容易在一个桶上形成环形链表 - 这样当获取一个不存在的key时,计算出的index正好是环形链表的下标就会出现死循环。 - **但是1.7的头插法造成的问题,1.8改变了插入顺序,就解决了这个问题,但是为了内存可见性等安全性,还是需要ConCurrentHashMap** > 参考:hashMap死循环分析 > > [hashMap死循环分析](https://zhuanlan.zhihu.com/p/67915754) 还有一个值得注意的是 HashMap 的遍历方式,通常有以下几种: ```java Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, Integer> next = entryIterator.next(); System.out.println("key=" + next.getKey() + " value=" + next.getValue()); } Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()){ String key = iterator.next(); System.out.println("key=" + key + " value=" + map.get(key)); } ``` - **建议使用第一种,同时可以把key value取出**。 - 第二种还需要通过key取一次key,效率较低。 ### ConcurrentHashMap #### 1.7 ![](https://i.loli.net/2019/05/08/5cd1d2c5ce95c.jpg) - Segment数组 - HashEntry组成 - 和HashMap一样,仍然是数组加链表 ```java /** * Segment 数组,存放数据时首先需要定位到具体的 Segment 中。 */ final Segment<K,V>[] segments; transient Set<K> keySet; transient Set<Map.Entry<K,V>> entrySet; ``` Segment 是 ConcurrentHashMap 的一个内部类,主要的组成如下: ```java static final class Segment<K,V> extends ReentrantLock implements Serializable { private static final long serialVersionUID = 2249069246763182397L; // 和 HashMap 中的 HashEntry 作用一样,真正存放数据的桶 transient volatile HashEntry<K,V>[] table; transient int count; transient int modCount; transient int threshold; final float loadFactor; } ``` ![](https://i.loli.net/2019/05/08/5cd1d2c635c69.jpg) - 唯一的区别就是其中的核心数据如 value ,以及链表都是 `volatile` 修饰的,保证了获取时的可见性。 - ConcurrentHashMap 采用了**分段锁**技术,其中 Segment 继承于 `ReentrantLock`。 - 不会像HashTable那样不管是put还是get操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。 - **每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment**。 ##### put ```java public V put(K key, V value) { Segment<K,V> s; if (value == null) throw new NullPointerException(); int hash = hash(key); int j = (hash >>> segmentShift) & segmentMask; if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment s = ensureSegment(j); return s.put(key, hash, value, false); } ``` 通过key定位到Segment,之后在对应的Segment中进行具体的put ```java final V put(K key, int hash, V value, boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); // 1. 加锁处理 V oldValue; try { HashEntry<K,V>[] tab = table; int index = (tab.length - 1) & hash; HashEntry<K,V> first = entryAt(tab, index); for (HashEntry<K,V> e = first;;) { if (e != null) { K k; if ((k = e.key) == key || // 2. 遍历该HashEntry,如果不为空则判断传入的key和当前遍历的key是否相等,相等则覆盖旧的value (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { // 3. 不为空则需要新建一个HashEntry并加入到Segment中,同时会先判断是否需要扩容 if (node != null) node.setNext(first); else node = new HashEntry<K,V>(hash, key, value, first); int c = count + 1; if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); // 4. 解锁 } return oldValue; } ``` - **虽然HashEntry中的value是用volatile关键字修饰的,但是并不能保证并发的原子性,所以put操作仍然需要加锁处理**。 - **首先第一步的时候会尝试获取锁,如果获取失败肯定就是其他线程存在竞争,则利用 `scanAndLockForPut()` 自旋获取锁**。 1. 尝试获取自旋锁 2. 如果重试的次数达到了`MAX_SCAN_RETRIES` 则改为**阻塞锁获取**,保证能获取成功。 总的来说: - 将当前的Segment中的table通过key的hashcode定位到HashEntry - 遍历该HashEntry,如果不为空则判断传入的key和当前遍历的key是否相等,相等则覆盖旧的value - 不为空则需要新建一个HashEntry并加入到Segment中,同时会先判断是否需要扩容 - 最后会解除在1中所获取当前Segment的锁。 ##### get ```java public V get(Object key) { Segment<K,V> s; // manually integrate access methods to reduce overhead HashEntry<K,V>[] tab; int h = hash(key); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE); e != null; e = e.next) { K k; if ((k = e.key) == key || (e.hash == h && key.equals(k))) return e.value; } } return null; } ``` - 只需要将 Key 通过 Hash 之后定位到具体的 Segment ,再通过一次 Hash 定位到具体的元素上。 - 由于 HashEntry 中的 value 属性是用 volatile 关键词修饰的,保证了内存可见性,所以每次获取时都是最新值。 - ConcurrentHashMap 的 get 方法是非常高效的,**因为整个过程都不需要加锁**。 #### 1.8 **那就是查询遍历链表效率太低。** ![](https://i.loli.net/2019/05/08/5cd1d2ce33795.jpg) **其中抛弃了原有的 Segment 分段锁,而采用了 `CAS + synchronized` 来保证并发安全性** ##### put ```java final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { // 1. 根据key计算出hashcode Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) // 2. 判断是否需要进行初始化 tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // 3. f即为当前key定位出的Node,如果为空表示当前位置可以写入数据,利用CAS尝试写入,失败则自旋保证成功。 if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) // 4. 如果当前位置的`hashcode == MOVED == -1`,则需要进行扩容 tab = helpTransfer(tab, f); else { V oldVal = null; synchronized (f) { // 5. 如果都不满足,则利用synchronized锁写入数据 if (tabAt(tab, i) == f) { if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) // 6. 如果数量大于`TREEIFY_THRESHOLD` 则要转换为红黑树。 treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; } ``` - 根据key计算出hashcode - 判断是否需要进行初始化 - f即为当前key定位出的Node,如果为空表示当前位置可以写入数据,**利用CAS尝试写入,失败则自旋保证成功**。 - 如果当前位置的`hashcode == MOVED == -1`,则需要进行扩容 - **如果都不满足,则利用synchronized锁写入数据** - 如果数量大于`TREEIFY_THRESHOLD` 则要转换为**红黑树**。 ##### get ```java public V get(Object key) { Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; int h = spread(key.hashCode()); if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) { if ((ek = e.key) == key || (ek != null && key.equals(ek))) return e.val; } else if (eh < 0) return (p = e.find(h, key)) != null ? p.val : null; while ((e = e.next) != null) { if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) return e.val; } } return null; } ``` - 根据计算出来的 hashcode 寻址,如果就在桶上那么直接返回值。 - 如果是红黑树那就按照树的方式获取值。 - 就不满足那就按照链表的方式遍历获取值。 1.8 在 1.7 的数据结构上做了大的改动,采用红黑树之后可以保证查询效率(`O(logn)`),甚至取消了 ReentrantLock 改为了 synchronized,这样可以看出在新版的 JDK 中对 synchronized 优化是很到位的。 ### 总结 套路: - 谈谈你理解的 HashMap,讲讲其中的 get put 过程。 - 1.8 做了什么优化? - 是线程安全的嘛? - 不安全会导致哪些问题? - 如何解决?有没有线程安全的并发容器? - ConcurrentHashMap 是如何实现的? 1.7、1.8 实现有何不同?为什么这么做? > 创作不易哇,觉得有帮助的话,给个小小的star呗。github地址😁😁😁<file_sep>package web; /** * @program LeetNiu * @description: 连续子数组的最大和 * @author: mf * @create: 2020/01/14 00:25 */ /** * HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。 * 今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。 * 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢? * 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 * 给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1) */ public class T30 { public int FindGreatestSumOfSubArray(int[] array) { // 动态规划完事 if (array == null || array.length == 0) return 0; int res = array[0]; // 记录当前所有子数组的和的最大值 int max = array[0]; // 记录包含arr[i]的连续子数组的最大值 for (int i = 1; i < array.length; i++) { max = Math.max(max + array[i], array[i]); res = Math.max(max, res); } return res; } } <file_sep>package com.basic; /** * @program JavaBooks * @description: 加锁和不加锁输出 * @author: mf * @create: 2019/12/26 21:19 */ public class T2 implements Runnable{ private int count = 10; @Override public /*synchronized*/ void run() { count--; System.out.println(Thread.currentThread().getName() + " count = " + count); } public static void main(String[] args) { T2 t2 = new T2(); for (int i = 0; i < 5; i++) { // 5个线程共同访问T2这个对象 new Thread(t2, "thread" + i).start(); } } } <file_sep>package com.basic; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @program JavaBooks * @description: CountDownLatch例子 * @author: mf * @create: 2020/01/09 16:52 */ public class T33 { // 请求的数量 private static final int threadCount= 30; public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(10); CountDownLatch countDownLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { final int threadNum = i; service.execute(() -> { try { Thread.sleep(500); System.out.println("threadNum: " + threadNum); } catch (InterruptedException e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } }); } countDownLatch.await(); service.shutdown(); System.out.println("finish..."); } } <file_sep>## 多线程总结 ## 容器 ### Map/Set 1. 不需要同步的时候可以选择 HashMap 2. 不需要同步,需要排序可以选择 TreeMap 3. 不需要同步,且需要双向队列或者栈的可选择 LinkedHashMap 4. 同步,并发量小可以选择 HashTable Collections.sychronizedXXX 5. 并发量大,可选择 ConcurrentHashMap 6. 在5的前提下,需要排序 ConcurrentSkipListMap ### 队列 1. 不需要同步,可以选择 ArrayList LinkedList 2. 并发量小,可选择 Collections.synchroizedXXX CopyOnWriteList(适合大量读,少量写) 3. 并发量大,可选择 ConcurrentLinkedQueue BlockingQueue(无界阻塞式队列) ArrayBQ(有界) TransferBQ(直接转给消费者) DelayQueue(执行定时任务) ## 线程池 1. Executor 2. ExecutorService 3. Callable 4. Future 5. 6种线程池 - newFixedThreadPool(固定线程池) - newCachedThreadPool(带有缓存线程池,默认空闲线程60s) - newSingleThreadExecutor(单个线程) - newScheduledThreadPoold(定时线程池) - newWorkStealingPool(空闲线程去抢占其他线程的任务队列的任务) - ForkJoinPool(适合大规模计算) ## 索引 ### 基础 - [synchronized加锁](./src/com/basic/T1.java) - [加锁与不加锁的区别](./src/com/basic/T2.java) - [产生脏读问题](./src/com/basic/Account.java) - [同步和非同步方法是否可以同时使用](./src/com/basic/T3.java) - [synchronized是可重入锁](./src/com/basic/T4.java) - [异常释放锁](./src/com/basic/T5.java) - [volatile](./src/com/basic/T6.java) - [volatile并不能保证的多线程的一致性](./src/com/basic/T7.java) - [锁粒度](./src/com/basic/T8.java) - [锁对象变了,锁就被释放了](./src/com/basic/T9.java) - [不要以字符串常量作为锁定对象](./src/com/basic/T10.java) - [线程通信](./src/com/basic/T11.java) - [ReentrantLock](./src/com/basic/T12.java) - [trylock](./src/com/basic/T13.java) - [ReentrantLock的公平锁](./src/com/basic/T14.java) - [生产者消费者](./src/com/basic/T15.java) - [用lock和condition进行生产者和消费者](./src/com/basic/T16.java) - [ThreadLocal](./src/com/basic/T17.java) - [单例,内部类方式,不需要加锁](./src/com/basic/T18.java) - [售票程序](./src/com/basic/T19.java) - [ConcurrentMap](./src/com/basic/T20.java) - [利用容器LinkedBlockingQueue生产者消费者](./src/com/basic/T21.java) - [线程池-newFixedThreadPool](./src/com/basic/T22.java) - [future](./src/com/basic/T23.java) - [并行计算的小例子](./src/com/basic/T24.java) - [newCachedThreadPool](./src/com/basic/T25.java) - [newSingleThreadExecutor](./src/com/basic/T26.java) - [newScheduledThreadPool](./src/com/basic/T27.java) - [WorkStealingPool](./src/com/basic/T28.java) - [ForkJoinPool](./src/com/basic/T29.java) - [parallel的小例子](./src/com/basic/T30.java) - [死锁的模拟](./src/com/basic/T31.java) - [Semaphore例子](./src/com/basic/T32.java) - [CountDownLatch例子](./src/com/basic/T33.java) - [CyclicBarrier的使用示例](./src/com/basic/T34.java)<file_sep>package books; import java.util.Stack; /** * @program JavaBooks * @description: 包含min函数的栈 * @author: mf * @create: 2019/09/11 10:12 */ /* 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素 的min函数。在干栈中,调用min、push及pop的时间复杂度都是o(1) */ /* 思路 一般来个辅助栈 好多题, 都需要辅助空间的 辅助栈的话,就很简单了。思路也很明了了。 */ public class T30 { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); Stack<Integer> helpStack = new Stack<>(); dataPush(stack, helpStack, 3); dataPush(stack, helpStack, 2); dataPush(stack, helpStack, 1); dataPush(stack, helpStack, 5); dataPush(stack, helpStack, 0); // dataPop(stack, helpStack); Integer value = dataMin(stack, helpStack); System.out.println(value); } private static Integer dataMin(Stack<Integer> stack, Stack<Integer> helpStack) { if (stack.isEmpty() || helpStack.isEmpty()) return null; return helpStack.peek(); } private static void dataPop(Stack<Integer> stack, Stack<Integer> helpStack) { if (stack.empty() || helpStack.empty()) return; stack.pop(); helpStack.pop(); } private static void dataPush(Stack<Integer> stack, Stack<Integer> helpStack, int value) { stack.push(value); if (helpStack.empty() || value < helpStack.peek()) { helpStack.push(value); } else { helpStack.push(helpStack.peek()); } } } <file_sep>## 引言 > Mysql,那可是老生常谈了,对于后端同学,那是必须要掌握的呀。 ## 常见问题 ### 数据库引擎innodb与myisam的区别? [InnoDB和MyISAM比较](http://dreamcat.ink/2019/11/15/sql-notes/1/) ### 4大特性 [Mysql的ACID原理](http://dreamcat.ink/2019/11/20/sql-notes/1/) ### 并发事务带来的问题 #### 脏读 ![](https://www.pdai.tech/_images/pics/dd782132-d830-4c55-9884-cfac0a541b8e.png) #### 丢弃修改 T1 和 T2 两个事务都对一个数据进行修改,T1 先修改,T2 随后修改,T2 的修改覆盖了 T1 的修改。例如:事务1读取某表中的数据A=20,事务2也读取A=20,事务1修改A=A-1,事务2也修改A=A-1,最 终结果A=19,事务1的修改被丢失。 ![](https://www.pdai.tech/_images/pics/88ff46b3-028a-4dbb-a572-1f062b8b96d3.png) ### 不可重复读 T2 读取一个数据,T1 对该数据做了修改。如果 T2 再次读取这个数据,此时读取的结果和第一次读取的结果不同。 ![](https://www.pdai.tech/_images/pics/c8d18ca9-0b09-441a-9a0c-fb063630d708.png) #### 幻读 T1 读取某个范围的数据,T2 在这个范围内插入新的数据,T1 再次读取这个范围的数据,此时读取的结果和和第一次读取的结果不同。 ![](https://www.pdai.tech/_images/pics/72fe492e-f1cb-4cfc-92f8-412fb3ae6fec.png) #### 不可重复度和幻读区别: 不可重复读的重点是修改,幻读的重点在于新增或者删除。 例1(同样的条件, 你读取过的数据, 再次读取出来发现值不一样了 ):事务1中的A先生读取自己的工资为 1000的操 作还没完成,事务2中的B先生就修改了A的工资为2000,导 致A再读自己的工资时工资变为 2000;这就是不可重复读。 例2(同样的条件, 第1次和第2次读出来的记录数不一样 ):假某工资单表中工资大于3000的有4人,事务1读取了所 有工资大于3000的人,共查到4条记录,这时事务2 又插入了一条工资大于3000的记录,事务1再次读取时查到的记 录就变为了5条,这样就导致了幻读。 ### 数据库的隔离级别 1. 未提交读,事务中发生了修改,即使没有提交,其他事务也是可见的,比如对于一个数A原来50修改为100,但是我还没有提交修改,另一个事务看到这个修改,而这个时候原事务发生了回滚,这时候A还是50,但是另一个事务看到的A是100.**可能会导致脏读、幻读或不可重复读** 2. 提交读,对于一个事务从开始直到提交之前,所做的任何修改是其他事务不可见的,举例就是对于一个数A原来是50,然后提交修改成100,这个时候另一个事务在A提交修改之前,读取的A是50,刚读取完,A就被修改成100,这个时候另一个事务再进行读取发现A就突然变成100了;**可以阻止脏读,但是幻读或不可重复读仍有可能发生** 3. 可重复读,就是对一个记录读取多次的记录是相同的,比如对于一个数A读取的话一直是A,前后两次读取的A是一致的;**可以阻止脏读和不可重复读,但幻读仍有可能发生。** 4. 可串行化读,在并发情况下,和串行化的读取的结果是一致的,没有什么不同,比如不会发生脏读和幻读;**该级别可以防止脏读、不可重复读以及幻读。** | 隔离级别 | 脏读 | 不可重复读 | 幻影读 | | ---------------- | ---- | ---------- | ------ | | READ-UNCOMMITTED | √ | √ | √ | | READ-COMMITTED | × | √ | √ | | REPEATABLE-READ | × | × | √ | | SERIALIZABLE | × | × | × | MySQL InnoDB 存储引擎的默认支持的隔离级别是 REPEATABLE-READ(可重读)。我们可以通过 命令来查看。我们可以通过`SELECT@@tx_isolation;` 这里需要注意的是:与 SQL 标准不同的地方在于InnoDB 存储引擎在 REPEATABLE-READ(可重读)事务隔离级别 下使用的是Next-Key Lock 锁算法,因此可以避免幻读的产生,这与其他数据库系统(如 SQL Server)是不同的。所以 说InnoDB 存储引擎的默认支持的隔离级别是 REPEATABLE-READ(可重读) 已经可以完全保证事务的隔离性要 求,即达到了 SQL标准的SERIALIZABLE(可串行化)隔离级别。 因为隔离级别越低,事务请求的锁越少,所以大部分数据库系统的隔离级别都是READ-COMMITTED(读取提交内 容):,但是你要知道的是InnoDB 存储引擎默认使用 REPEATABLE-READ(可重读)并不会有任何性能损失。 InnoDB 存储引擎在 分布式事务 的情况下一般会用到SERIALIZABLE(可串行化)隔离级别。 ### 为什么使用索引? - 通过创建唯一性索引,可以保证数据库表中每一行数据的唯一性。 - 可以大大加快数据的检索速度,这也是创建索引的最主要的原因。 - 帮助服务器避免排序和临时表 - 将随机IO变为顺序IO - 可以加速表和表之间的连接,特别是在实现数据的参考完整性方面特别有意义。 ### 索引这么多优点,为什么不对表中的每一个列创建一个索引呢? - 当对表中的数据进行增加、删除和修改的时候,索引也要动态的维护,这样就降低了数据的维护速度。 - 索引需要占物理空间,除了数据表占数据空间之外,每一个索引还要占一定的物理空间,如果要建立簇索引,那么需要的空间就会更大。 - 创建索引和维护索引要耗费时间,这种时间随着数据量的增加而增加 ### 索引如如何提高查询速度的? - 将无序的数据变成相对有序的数据(就像查目一样) ### 使用索引的注意事项? - 在经常需要搜索的列上,可以加快搜索的速度; - 在经常使用在where子句中的列上面创建索引,加快条件的判断速度。 - 在经常需要排序的列上创建索引,因为索引已经排序,这样查询可以利用索引的排序,加快排序查询时间 - 在中到大型表索引都是非常有效的,但是特大型表的维护开销会很大,不适合建索引 - 在经常用到连续的列上,这些列主要是由一些外键,可以加快连接的速度 - 避免where子句中对字段施加函数,这会造成无法命中索引 - 在使用InnoDB时使用与业务无关的自增主键作为主键,即使用逻辑主键,而不要使用业务主键。 - **将打算加索引的列设置为NOT NULL,否则将导致引擎放弃使用索引而进行全表扫描** - 删除长期未使用的索引,不用的索引的存在会造成不必要的性能损耗 - 在使用limit offset查询缓存时,可以借助索引来提高性能。 ### Mysql索引主要使用的两种数据结构 - 哈希索引,对于哈希索引来说,底层的数据结构肯定是哈希表,因此在绝大多数需求为单条记录查询的时候,可以选择哈希索引,查询性能最快;其余大部分场景,建议选择BTree索引 - BTree索引,Mysql的BTree索引使用的是B树中的B+Tree但对于主要的两种存储引擎(MyISAM和InnoDB)的实现方式是不同的。 ### MyISAM和InnoDB实现BTree索引方式的区别 - MyISAM,B+Tree叶节点的data域存放的是数据记录的地址,在索引检索的时候,首先按照B+Tree搜索算法搜索索引,如果指定的key存在,则取出其data域的值,然后以data域的值为地址读区相应的数据记录,这被称为“非聚簇索引” - InnoDB,其数据文件本身就是索引文件,相比MyISAM,索引文件和数据文件是分离的,其表数据文件本身就是按B+Tree组织的一个索引结构,树的节点data域保存了完整的数据记录,这个索引的key是数据表的主键,因此InnoDB表数据文件本身就是主索引。这被称为“聚簇索引”或者聚集索引,而其余的索引都作为辅助索引,辅助索引的data域存储相应记录主键的值而不是地址,这也是和MyISAM不同的地方,在根据主索引搜索时,直接找到key所在的节点即可取出数据;在根据辅助索引查找时,则需要先取出主键的值,在走一遍主索引。因此,在设计表的时候,不建议使用过长的字段为主键,也不建议使用非单调的字段作为主键,这样会造成主索引频繁分裂。 ### 数据库结构优化 - 范式优化: 比如消除冗余(节省空间。。) - 反范式优化:比如适当加冗余等(减少join) - 限定数据的范围: 务必禁止不带任何限制数据范围条件的查询语句。比如:我们当用户在查询订单历史的时 候,我们可以控制在一个月的范围内。 - 读/写分离: 经典的数据库拆分方案,主库负责写,从库负责读; - 拆分表:分区将数据在物理上分隔开,不同分区的数据可以制定保存在处于不同磁盘上的数据文件里。这样,当对这个表进行查询时,只需要在表分区中进行扫描,而不必进行全表扫描,明显缩短了查询时间,另外处于不同磁盘的分区也将对这个表的数据传输分散在不同的磁盘I/O,一个精心设置的分区可以将数据传输对磁盘I/O竞争均匀地分散开。对数据量大的时时表可采取此方法。可按月自动建表分区。 - 拆分其实又分垂直拆分和水平拆分: - 案例: 简单购物系统暂设涉及如下表: - 1.产品表(数据量10w,稳定) - 2.订单表(数据量200w,且有增长趋势) - 3.用户表 (数据量100w,且有增长趋势) - 以mysql为例讲述下水平拆分和垂直拆分,mysql能容忍的数量级在百万静态数据可以到千万 - **垂直拆分:** - 解决问题:表与表之间的io竞争 - 不解决问题:单表中数据量增长出现的压力 - 方案: 把产品表和用户表放到一个server上 订单表单独放到一个server上 - **水平拆分:** - 解决问题:单表中数据量增长出现的压力 - 不解决问题:表与表之间的io争夺 - 方案:**用户表** 通过性别拆分为男用户表和女用户表,**订单表** 通过已完成和完成中拆分为已完成订单和未完成订单,**产品表** 未完成订单放一个server上,已完成订单表盒男用户表放一个server上,女用户表放一个server上(女的爱购物 哈哈)。 ### 主键 超键 候选键 外键是什么 #### 定义 超键:在关系中能唯一标识元组的属性集称为关系模式的超键 候选键:不含有多余属性的超键称为候选键。也就是在候选键中,若再删除属性,就不是键了! 主键:用户选作元组标识的一个候选键程序主键 外键:如果关系模式R中属性K是其它模式的主键,那么k在模式R中称为外键。 #### 举例 | 学号 | 姓名 | 性别 | 年龄 | 系别 | 专业 | | -------- | ------ | ---- | ---- | ------ | -------- | | 20020612 | 李辉 | 男 | 20 | 计算机 | 软件开发 | | 20060613 | 张明 | 男 | 18 | 计算机 | 软件开发 | | 20060614 | 王小玉 | 女 | 19 | 物理 | 力学 | | 20060615 | 李淑华 | 女 | 17 | 生物 | 动物学 | | 20060616 | 赵静 | 男 | 21 | 化学 | 食品化学 | | 20060617 | 赵静 | 女 | 20 | 生物 | 植物学 | 1. 超键:于是我们从例子中可以发现 学号是标识学生实体的唯一标识。那么该元组的超键就为学号。除此之外我们还可以把它跟其他属性组合起来,比如:(`学号`,`性别`),(`学号`,`年龄`) 2. 候选键:根据例子可知,学号是一个可以唯一标识元组的唯一标识,因此学号是一个候选键,实际上,候选键是超键的子集,比如 (学号,年龄)是超键,但是它不是候选键。因为它还有了额外的属性。 3. 主键:简单的说,例子中的元组的候选键为学号,但是我们选定他作为该元组的唯一标识,那么学号就为主键。 4. 外键是相对于主键的,比如在学生记录里,主键为学号,在成绩单表中也有学号字段,因此学号为成绩单表的外键,为学生表的主键。 #### 总结 **主键为候选键的子集,候选键为超键的子集,而外键的确定是相对于主键的。** ### drop,delete与truncate的区别 drop直接删掉表;truncate删除表中数据,再插入时自增长id又从1开始 ;delete删除表中数据,可以加where字句。 1. DELETE语句执行删除的过程是每次从表中删除一行,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作。TRUNCATE TABLE 则一次性地从表中删除所有的数据并不把单独的删除操作记录记入日志保存,删除行是不能恢复的。并且在删除的过程中不会激活与表有关的删除触发器。执行速度快。 2. 表和索引所占空间。当表被TRUNCATE 后,这个表和索引所占用的空间会恢复到初始大小,而DELETE操作不会减少表或索引所占用的空间。drop语句将表所占用的空间全释放掉。 3. 一般而言,drop > truncate > delete 4. 应用范围。TRUNCATE 只能对TABLE;DELETE可以是table和view 5. TRUNCATE 和DELETE只删除数据,而DROP则删除整个表(结构和数据)。 6. truncate与不带where的delete :只删除数据,而不删除表的结构(定义)drop语句将删除表的结构被依赖的约束(constrain),触发器(trigger)索引(index);依赖于该表的存储过程/函数将被保留,但其状态会变为:invalid。 7. delete语句为DML(Data Manipulation Language),这个操作会被放到 rollback segment中,事务提交后才生效。如果有相应的 tigger,执行的时候将被触发。 8. truncate、drop是DDL(Data Define Language),操作立即生效,原数据不放到 rollback segment中,不能回滚 9. 在没有备份情况下,谨慎使用 drop 与 truncate。要删除部分数据行采用delete且注意结合where来约束影响范围。回滚段要足够大。要删除表用drop;若想保留表而将表中数据删除,如果于事务无关,用truncate即可实现。如果和事务有关,或老是想触发trigger,还是用delete。 10. Truncate table 表名 速度快,而且效率高,因为: truncate table 在功能上与不带 WHERE 子句的 DELETE 语句相同:二者均删除表中的全部行。但 TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少。DELETE 语句每次删除一行,并在事务日志中为所删除的每行记录一项。TRUNCATE TABLE 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放。 11. TRUNCATE TABLE 删除表中的所有行,但表结构及其列、约束、索引等保持不变。新行标识所用的计数值重置为该列的种子。如果想保留标识计数值,请改用 DELETE。如果要删除表定义及其数据,请使用 DROP TABLE 语句。 12. 对于由 FOREIGN KEY 约束引用的表,不能使用 TRUNCATE TABLE,而应使用不带 WHERE 子句的 DELETE 语句。由于 TRUNCATE TABLE 不记录在日志中,所以它不能激活触发器。 ### 视图的作用,视图可以更改么? 视图是虚拟的表,与包含数据的表不一样,视图只包含使用时动态检索数据的查询;不包含任何列或数据。使用视图可以简化复杂的sql操作,隐藏具体的细节,保护数据;视图创建后,可以使用与表相同的方式利用它们。 视图不能被索引,也不能有关联的触发器或默认值,如果视图本身内有order by 则对视图再次order by将被覆盖。 创建视图:`create view xxx as xxxx` 对于某些视图比如未使用联结子查询分组聚集函数Distinct Union等,是可以对其更新的,对视图的更新将对基表进行更新;但是视图主要用于简化检索,保护数据,并不用于更新,而且大部分视图都不可以更新。 ### 数据库范式 #### 第一范式 在任何一个关系数据库中,第一范式(1NF)是对关系模式的基本要求,不满足第一范式(1NF)的数据库就不是关系数据库。 所谓第一范式(1NF)是指数据库表的每一列都是不可分割的基本数据项,同一列中不能有多个值,即实体中的某个属性不能有多个值或者不能有重复的属性。如果出现重复的属性,就可能需要定义一个新的实体,新的实体由重复的属性构成,新实体与原实体之间为一对多关系。在第一范式(1NF)中表的每一行只包含一个实例的信息。简而言之,**第一范式就是无重复的列**。 #### 第二范式 第二范式(2NF)是在第一范式(1NF)的基础上建立起来的,即满足第二范式(2NF)必须先满足第一范式(1NF)。第二范式(2NF)要求数据库表中的每个实例或行必须可以被惟一地区分。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。这个惟一属性列被称为主关键字或主键、主码。 第二范式(2NF)要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体,新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,**第二范式就是非主属性非部分依赖于主关键字**。 #### 第三范式 满足第三范式(3NF)必须先满足第二范式(2NF)。简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主关键字信息。例如,存在一个部门信息表,其中每个部门有部门编号(dept_id)、部门名称、部门简介等信息。那么在员工信息表中列出部门编号后就不能再将部门名称、部门简介等与部门有关的信息再加入员工信息表中。如果不存在部门信息表,则根据第三范式(3NF)也应该构建它,否则就会有大量的数据冗余。简而言之,第三范式就是属性不依赖于其它非主属性。(我的理解是消除冗余) ### 什么是覆盖索引? 如果一个索引包含(或者说覆盖)所有需要查询的字段的值,我们就称 之为“覆盖索引”。我们知道在InnoDB存储引 擎中,如果不是主键索引,叶子节点存储的是主键+列值。最终还是要“回表”,也就是要通过主键再查找一次,这样就 会比较慢。覆盖索引就是把要查询出的列和索引是对应的,不做回表操作!<file_sep>- [参考这位大佬总结的,挺好的](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions) 其实专注一个参考资料,认真备面就完全ok - [什么是Spring框架](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_1-%e4%bb%80%e4%b9%88%e6%98%af-spring-%e6%a1%86%e6%9e%b6) - [列举一些重要的Spring模块](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_2-%e5%88%97%e4%b8%be%e4%b8%80%e4%ba%9b%e9%87%8d%e8%a6%81%e7%9a%84spring%e6%a8%a1%e5%9d%97%ef%bc%9f) - [@RestController vs @Controller](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_3-restcontroller-vs-controller) - **@ResponseBody的作用**:**注解的作用是将 Controller 的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到HTTP 响应(Response)对象的 body 中,通常用来返回 JSON 或者 XML 数据,返回 JSON 数据的情况比较多。** - [谈谈自己对于Spring IoC和AOP的理解](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_41-%e8%b0%88%e8%b0%88%e8%87%aa%e5%b7%b1%e5%af%b9%e4%ba%8e-spring-ioc-%e5%92%8c-aop-%e7%9a%84%e7%90%86%e8%a7%a3) - [SpringAOP和AspectAOP有什么区别](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_41-%e8%b0%88%e8%b0%88%e8%87%aa%e5%b7%b1%e5%af%b9%e4%ba%8e-spring-ioc-%e5%92%8c-aop-%e7%9a%84%e7%90%86%e8%a7%a3) - [Spring中的bean的作用域有哪些](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_51-spring-%e4%b8%ad%e7%9a%84-bean-%e7%9a%84%e4%bd%9c%e7%94%a8%e5%9f%9f%e6%9c%89%e5%93%aa%e4%ba%9b) - [Spring中的单例bean的线程安全问题了解吗](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_52-spring-%e4%b8%ad%e7%9a%84%e5%8d%95%e4%be%8b-bean-%e7%9a%84%e7%ba%bf%e7%a8%8b%e5%ae%89%e5%85%a8%e9%97%ae%e9%a2%98%e4%ba%86%e8%a7%a3%e5%90%97%ef%bc%9f) - [@Component和@bean的区别是什么](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_53-component-%e5%92%8c-bean-%e7%9a%84%e5%8c%ba%e5%88%ab%e6%98%af%e4%bb%80%e4%b9%88%ef%bc%9f) - [将一个类声明为Spring的bean的注解有哪些](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_54-%e5%b0%86%e4%b8%80%e4%b8%aa%e7%b1%bb%e5%a3%b0%e6%98%8e%e4%b8%baspring%e7%9a%84-bean-%e7%9a%84%e6%b3%a8%e8%a7%a3%e6%9c%89%e5%93%aa%e4%ba%9b) - [Spring中的bean生命周期-一](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_55-spring-%e4%b8%ad%e7%9a%84-bean-%e7%94%9f%e5%91%bd%e5%91%a8%e6%9c%9f) - [Spring中的bean生命周期-二](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringBean) - [说说自己对于SpringMVC了解](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_61-%e8%af%b4%e8%af%b4%e8%87%aa%e5%b7%b1%e5%af%b9%e4%ba%8e-spring-mvc-%e4%ba%86%e8%a7%a3) - [SpringMVC工作原理了解吗](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_62-springmvc-%e5%b7%a5%e4%bd%9c%e5%8e%9f%e7%90%86%e4%ba%86%e8%a7%a3%e5%90%97) - [Spring框架中用到了哪些设计模型-一](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/SpringInterviewQuestions?id=_7-spring-%e6%a1%86%e6%9e%b6%e4%b8%ad%e7%94%a8%e5%88%b0%e4%ba%86%e5%93%aa%e4%ba%9b%e8%ae%be%e8%ae%a1%e6%a8%a1%e5%bc%8f%ef%bc%9f) - [Spring框架中用到了哪些设计模型-二](https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/Spring-Design-Patterns) <file_sep>package books; import java.util.ArrayList; /** * @program JavaBooks * @description: 圆圈中最后剩下的数字 * @author: mf * @create: 2019/10/09 16:05 */ /* 0,1,...,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里 删除第m个数字。求出这个圆圈里剩下的最后一个数字。 */ public class T62 { public static void main(String[] args) { System.out.println(lastRemaining(5, 3)); } private static int lastRemaining(int n, int m) { if (n == 0 || m == 0) return -1; ArrayList<Integer> data = new ArrayList<>(); for (int i = 0; i < n; i++) { data.add(i); } int index = -1; while (data.size() > 1) { index = (index + m) % data.size(); data.remove(index); index--; } return data.get(0); } } <file_sep>## 引言 **JVM - 内存模型** <!-- more --> ![](https://www.pdai.tech/_images/pics/c9ad2bf4-5580-4018-bce4-1b9a71804d9c.png) ## 程序计数器 记录正在执行的虚拟机字节码指令的地址(如果正在执行的是本地方法则为空)。 ## Java虚拟机栈 每个 Java 方法在执行的同时会创建一个栈帧用于存储局部变量表、操作数栈、常量池引用等信息,从调用直至执行完成的过程,就对应着一个栈帧在 Java 虚拟机栈中入栈和出栈的过程。 ![](https://www.pdai.tech/_images/pics/926c7438-c5e1-4b94-840a-dcb24ff1dafe.png) 可以通过 -Xss 这个虚拟机参数来指定每个线程的 Java 虚拟机栈内存大小:java -Xss512M HackTheJava 该区域可能抛出以下异常: - 当线程请求的栈深度超过最大值,会抛出 StackOverflowError 异常; - 栈进行动态扩展时如果无法申请到足够内存,会抛出 OutOfMemoryError 异常。 ## 本地方法栈 本地方法一般是用其它语言(C、C++ 或汇编语言等)编写的,并且被编译为基于本机硬件和操作系统的程序,对待这些方法需要特别处理。 本地方法栈与 Java 虚拟机栈类似,它们之间的区别只不过是本地方法栈为本地方法服务。 ## 堆 所有对象都在这里分配内存,是垃圾收集的主要区域("GC 堆")。 现代的垃圾收集器基本都是采用分代收集算法,针对不同类型的对象采取不同的垃圾回收算法,可以将堆分成两块: - 新生代(Young Generation) - 老年代(Old Generation) 新生代可以继续划分成以下三个空间: - Eden(伊甸园) - From Survivor(幸存者) - To Survivor 堆不需要连续内存,并且可以动态增加其内存,增加失败会抛出 OutOfMemoryError 异常。 可以通过 -Xms 和 -Xmx 两个虚拟机参数来指定一个程序的堆内存大小,第一个参数设置初始值,第二个参数设置最大值。java -Xms1M -Xmx2M HackTheJava ## 方法区 用于存放已被加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。 和堆一样不需要连续的内存,并且可以动态扩展,动态扩展失败一样会抛出 OutOfMemoryError 异常。 对这块区域进行垃圾回收的主要目标是对常量池的回收和对类的卸载,但是一般比较难实现。 JDK 1.7 之前,HotSpot 虚拟机把它当成永久代来进行垃圾回收。但是从 JDK 1.7 开始,已经把原本放在永久代的字符串常量池移到 Native Method 中。 ## 运行时常量池 运行时常量池是方法区的一部分。 Class 文件中的常量池(编译器生成的各种字面量和符号引用)会在类加载后被放入这个区域。 除了在编译期生成的常量,还允许动态生成,例如 String 类的 intern()。 ## 直接内存 在 JDK 1.4 中新加入了 NIO 类,它可以使用 Native 函数库直接分配堆外内存,然后通过一个存储在 Java 堆里的 DirectByteBuffer 对象作为这块内存的引用进行操作。 这样能在一些场景中显著提高性能,因为避免了在 Java 堆和 Native 堆中来回复制数据。 ## 请你谈谈对OOM的认识 - `java.lang.StackOverflowError`:栈空间溢出 ,递归调用卡死 - `java.lang.OutOfMemoryError:Java heap space`:堆内存溢出 , 对象过大 - `java.lang.OutOfMemoryError:GC overhead limit exceeded`:GC回收时间过长 - `java.lang.OutOfMemoryError:Direct buffer memory`执行内存挂了,比如:NIO - `java.lang.OutOfMemoryError:unable to create new native thread` - 应用创建了太多线程,一个应用进程创建了多个线程,超过系统承载极限 - 你的服务器并不允许你的应用程序创建这么多线程,linux系统默认允许单个进程可以创建的线程数是1024,超过这个数量,就会报错 - 解决办法:降低应用程序创建线程的数量,分析应用给是否针对需要这么多线程,如果不是,减到最低修改linux服务器配置 - `java.lang.OutOfMemoryError:Metaspace`:元空间主要存放了虚拟机加载的类的信息、常量池、静态变量、即时编译后的代码<file_sep>/** * @program JavaBooks * @description: 链表中倒数第k个节点 * @author: mf * @create: 2020/03/06 20:55 */ package subject.linked; import java.util.Stack; /** * 1->2->3->4->5 k = 2 * 返回: * 4->5 */ public class T2 { /** * 栈,比较容易想得的到 * @param head * @param k * @return */ public ListNode getKthFromEnd(ListNode head, int k) { Stack<ListNode> stack = new Stack<>(); while (head != null) { stack.push(head); head = head.next; } ListNode listNode= new ListNode(0); for (int i = 0; i < k; i++) { listNode = stack.pop(); } return listNode; } /** * 双指针 * @param head * @param k * @return */ public ListNode getKthFromEnd2(ListNode head, int k) { ListNode pNode = head; ListNode kNode = head; int p1 = 0; while (pNode != null) { if (p1 >= k) { kNode = kNode.next; } pNode = pNode.next; p1++; } return kNode; } } <file_sep>## 引言 > **收集一些常用的在线网站,包括在线工具、第三方视频、文章博客、磁力和软件等...** ## 在线工具 - [在线JSON校验格式工具](<http://www.bejson.com/>) - [正则表达式在线测试](<http://tool.chinaz.com/regex/>) - [RGB颜色查询对照表](<https://www.114la.com/other/rgb.htm>) - [在线正则表达式测试](<http://tool.oschina.net/regex/>) - [UrlEncode编码解码](<http://tool.chinaz.com/tools/urlencode.aspx>) - [时间戳在线转换](<http://tool.chinaz.com/Tools/unixtime.aspx>) - [草料二维码生成器](<https://cli.im/>) - [在线Java编辑器](<https://www.jdoodle.com/online-java-compiler>) - [MarkDown转HTML](<https://www.it399.com/code/markdown2html>) - [在线图标下载](<https://www.easyicon.net/>) - [Greasy Fork 油猴脚本](<https://greasyfork.org/zh-CN>) - [科技小c](<http://www.kejixiaoc.com/>) - [高清壁纸wall](<https://wall.alphacoders.com/?lang=Chinese>) - [在线图片尺寸大小修改](<https://www.gaitubao.com/>) - [Unicode转中文](http://tool.chinaz.com/tools/unicode.aspx) - [ppt模版下载](http://www.ypppt.com/) - [CSDN自助下载](http://kuaitu888.com/) - [4k壁纸](http://pic.netbian.com/) - [xclient-mac软件下载](<https://xclient.info/?t=57388619b991a74c710f1fec5d84a7e8101efb2b>) - [iterm2主题](https://sspai.com/post/53008) - [常用的workflow](https://hufangyun.com/2018/alfred-workflow-recommend/) - [mac软件下载-1](https://www.macenjoy.co/) - [mac软件下载-2](https://xclient.info/) ## 第三方视频 - [免费影视网站](https://hao.su/531/) - [动漫](https://www.agefans.tv/) ## BT磁力 - [磁力导航](<http://hao.su/909>) - [网盘搜索](<https://www.xiaobaipan.com/>) - [DogeDoge搜索](<https://www.dogedoge.com/>) - [云盘精灵](https://www.yunpanjingling.com/) - [盘天才](https://www.pantianxia.com/) ## 其他 - [chromium-575458](https://npm.taobao.org/mirrors/chromium-browser-snapshots/) <file_sep>## 引言 > 想必大家都用过浏览器吧? > > 在浏览器上输入url,居然能渲染出这么多信息,是不是感觉好6呀? > > 本文简单聊一下http,当然面试的时候也会经常问这种类型相关的题。 <!-- more --> ## 概念 - URI:Uniform Resource Identifier:统一资源标识符 - URL:Uniform Resource Locator:统一资源定位符,eg:https://www.baidu.com - URN:Uniform Resource Name:统一资源名称 ### 请求和响应报文 #### 请求报文 简单来说: - 请求行:Request Line - 请求头:Request Headers - 请求体:Request Body #### 响应报文 简单来说: - 状态行:Status Line - 响应头:Response Headers - 响应体:Response Body ## HTTP方法 客户端发送的 **请求报文** 第一行为请求行,包含了方法字段。 ### GET > 获取资源 当前网络请求中,绝大部分使用的是 GET 方法。 ### HEAD > 获取报文头部 和 GET 方法类似,但是不返回报文实体主体部分。 主要用于确认 URL 的有效性以及资源更新的日期时间等。 ### POST > 传输实体主体 POST 主要用来传输数据,而 GET 主要用来获取资源。 更多 POST 与 GET 的比较见后 ### PUT > 上传文件 由于自身不带验证机制,任何人都可以上传文件,因此存在安全性问题,一般不使用该方法。 ### PATCH > 对资源进行部分修改 PUT 也可以用于修改资源,但是只能完全替代原始资源,PATCH 允许部分修改。 ### DELETE > 删除文件 与 PUT 功能相反,并且同样不带验证机制。 ### OPTIONS > 查询支持的方法 查询指定的 URL 能够支持的方法。 会返回 `Allow: GET, POST, HEAD, OPTIONS` 这样的内容。 ### CONNECT > 要求在与代理服务器通信时建立隧道 使用 SSL(Secure Sockets Layer,安全套接层)和 TLS(Transport Layer Security,传输层安全)协议把通信内容加密后经网络隧道传输。 ## HTTP状态码 服务器返回的 **响应报文** 中第一行为状态行,包含了状态码以及原因短语,用来告知客户端请求的结果。 | 状态码 | 类别 | 含义 | | :----: | :------------------------------: | :------------------------: | | 1XX | Informational(信息性状态码) | 接收的请求正在处理 | | 2XX | Success(成功状态码) | 请求正常处理完毕 | | 3XX | Redirection(重定向状态码) | 需要进行附加操作以完成请求 | | 4XX | Client Error(客户端错误状态码) | 服务器无法处理请求 | | 5XX | Server Error(服务器错误状态码) | 服务器处理请求出错 | ### 1XX 信息 - **100 Continue** :表明到目前为止都很正常,客户端可以继续发送请求或者忽略这个响应。 ### 2XX 成功 - **200 OK** - **204 No Content** :请求已经成功处理,但是返回的响应报文不包含实体的主体部分。一般在只需要从客户端往服务器发送信息,而不需要返回数据时使用。 - **206 Partial Content** :表示客户端进行了范围请求,响应报文包含由 Content-Range 指定范围的实体内容。 ### 3XX 重定向 - **301 Moved Permanently** :永久性重定向 - **302 Found** :临时性重定向 - **303 See Other** :和 302 有着相同的功能,但是 303 明确要求客户端应该采用 GET 方法获取资源。 - **304 Not Modified** :如果请求报文首部包含一些条件,例如:If-Match,If-Modified-Since,If-None-Match,If-Range,If-Unmodified-Since,如果不满足条件,则服务器会返回 304 状态码。 - **307 Temporary Redirect** :临时重定向,与 302 的含义类似,但是 307 要求浏览器不会把重定向请求的 POST 方法改成 GET 方法。 ### 4XX 客户端错误 - **400 Bad Request** :请求报文中存在语法错误。 - **401 Unauthorized** :该状态码表示发送的请求需要有认证信息(BASIC 认证、DIGEST 认证)。如果之前已进行过一次请求,则表示用户认证失败。 - **403 Forbidden** :请求被拒绝。 - **404 Not Found** ### 5XX 服务器错误 - **500 Internal Server Error** :服务器正在执行请求时发生错误。 - **503 Service Unavailable** :服务器暂时处于超负载或正在进行停机维护,现在无法处理请求。 ## HTTP首部 有 4 种类型的首部字段:通用首部字段、请求首部字段、响应首部字段和实体首部字段。 各种首部字段及其含义如下(**不需要全记,仅供查阅):** ### 通用首部字段 | 首部字段名 | 说明 | | :---------------: | :----------------------------------------: | | Cache-Control | 控制缓存的行为 | | Connection | 控制不再转发给代理的首部字段、管理持久连接 | | Date | 创建报文的日期时间 | | Pragma | 报文指令 | | Trailer | 报文末端的首部一览 | | Transfer-Encoding | 指定报文主体的传输编码方式 | | Upgrade | 升级为其他协议 | | Via | 代理服务器的相关信息 | | Warning | 错误通知 | ### 请求首部字段 | 首部字段名 | 说明 | | :-----------------: | :---------------------------------------------: | | Accept | 用户代理可处理的媒体类型 | | Accept-Charset | 优先的字符集 | | Accept-Encoding | 优先的内容编码 | | Accept-Language | 优先的语言(自然语言) | | Authorization | Web 认证信息 | | Expect | 期待服务器的特定行为 | | From | 用户的电子邮箱地址 | | Host | 请求资源所在服务器 | | If-Match | 比较实体标记(ETag) | | If-Modified-Since | 比较资源的更新时间 | | If-None-Match | 比较实体标记(与 If-Match 相反) | | If-Range | 资源未更新时发送实体 Byte 的范围请求 | | If-Unmodified-Since | 比较资源的更新时间(与 If-Modified-Since 相反) | | Max-Forwards | 最大传输逐跳数 | | Proxy-Authorization | 代理服务器要求客户端的认证信息 | | Range | 实体的字节范围请求 | | Referer | 对请求中 URI 的原始获取方 | | TE | 传输编码的优先级 | | User-Agent | HTTP 客户端程序的信息 | ### 响应首部字段 | 首部字段名 | 说明 | | :----------------: | :--------------------------: | | Accept-Ranges | 是否接受字节范围请求 | | Age | 推算资源创建经过时间 | | ETag | 资源的匹配信息 | | Location | 令客户端重定向至指定 URI | | Proxy-Authenticate | 代理服务器对客户端的认证信息 | | Retry-After | 对再次发起请求的时机要求 | | Server | HTTP 服务器的安装信息 | | Vary | 代理服务器缓存的管理信息 | | WWW-Authenticate | 服务器对客户端的认证信息 | ### 实体首部字段 | 首部字段名 | 说明 | | :--------------: | :--------------------: | | Allow | 资源可支持的 HTTP 方法 | | Content-Encoding | 实体主体适用的编码方式 | | Content-Language | 实体主体的自然语言 | | Content-Length | 实体主体的大小 | | Content-Location | 替代对应资源的 URI | | Content-MD5 | 实体主体的报文摘要 | | Content-Range | 实体主体的位置范围 | | Content-Type | 实体主体的媒体类型 | | Expires | 实体主体过期的日期时间 | | Last-Modified | 资源的最后修改日期时间 | ## 具体应用 举一点例子即可 ### Cookies HTTP 协议是无状态的,主要是为了让 HTTP 协议尽可能简单,使得它能够处理大量事务。HTTP/1.1 引入 Cookie 来保存状态信息。 Cookie 是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器之后向同一服务器再次发起请求时被携带上,用于告知服务端两个请求是否来自同一浏览器。由于之后每次请求都会需要携带 Cookie 数据,因此会带来额外的性能开销(尤其是在移动环境下)。 Cookie 曾一度用于客户端数据的存储,因为当时并没有其它合适的存储办法而作为唯一的存储手段,但现在随着现代浏览器开始支持各种各样的存储方式,Cookie 渐渐被淘汰。新的浏览器 API 已经允许开发者直接将数据存储到本地,如使用 Web storage API(本地存储和会话存储)或 IndexedDB。 **用途** - 会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息) - 个性化设置(如用户自定义设置、主题等) - 浏览器行为跟踪(如跟踪分析用户行为等) ### Session 除了可以将用户信息通过 Cookie 存储在用户浏览器中,也可以利用 Session 存储在服务器端,存储在服务器端的信息更加安全。 Session 可以存储在服务器上的文件、数据库或者内存中。也可以将 Session 存储在 Redis 这种内存型数据库中,效率会更高。 使用 Session 维护用户登录状态的过程如下: - 用户进行登录时,用户提交包含用户名和密码的表单,放入 HTTP 请求报文中; - 服务器验证该用户名和密码,如果正确则把用户信息存储到 Redis 中,它在 Redis 中的 Key 称为 Session ID; - 服务器返回的响应报文的 Set-Cookie 首部字段包含了这个 Session ID,客户端收到响应报文之后将该 Cookie 值存入浏览器中; - 客户端之后对同一个服务器进行请求时会包含该 Cookie 值,服务器收到之后提取出 Session ID,从 Redis 中取出用户信息,继续之前的业务操作。 应该注意 Session ID 的安全性问题,不能让它被恶意攻击者轻易获取,那么就不能产生一个容易被猜到的 Session ID 值。此外,还需要经常重新生成 Session ID。在对安全性要求极高的场景下,例如转账等操作,除了使用 Session 管理用户状态之外,还需要对用户进行重新验证,比如重新输入密码,或者使用短信验证码等方式。 ### Cookie与Session选择 - Cookie 只能存储 ASCII 码字符串,而 Session 则可以存储任何类型的数据,因此在考虑数据复杂性时首选 Session; - Cookie 存储在浏览器中,容易被恶意查看。如果非要将一些隐私数据存在 Cookie 中,可以将 Cookie 值进行加密,然后在服务器进行解密; - 对于大型网站,如果用户所有的信息都存储在 Session 中,那么开销是非常大的,因此不建议将所有的用户信息都存储到 Session 中。 ## HTTPS HTTP 有以下安全性问题: - 使用明文进行通信,内容可能会被窃听; - 不验证通信方的身份,通信方的身份有可能遭遇伪装; - 无法证明报文的完整性,报文有可能遭篡改。 HTTPS 并不是新协议,而是让 HTTP 先和 SSL(Secure Sockets Layer)通信,再由 SSL 和 TCP 通信,也就是说 HTTPS 使用了隧道进行通信。 通过使用 SSL,HTTPS 具有了加密(防窃听)、认证(防伪装)和完整性保护(防篡改)。 ### 加密 #### 对称密钥加密 对称密钥加密(Symmetric-Key Encryption),加密和解密使用同一密钥。 - 优点:运算速度快 - 缺点:无法安全地将密钥传输给通信方 #### 非对称密钥加密 非对称密钥加密,又称公开密钥加密(Public-Key Encryption),加密和解密使用不同的密钥。 公开密钥所有人都可以获得,通信发送方获得接收方的公开密钥之后,就可以使用公开密钥进行加密,接收方收到通信内容后使用私有密钥解密。 非对称密钥除了用来加密,还可以用来进行签名。因为私有密钥无法被其他人获取,因此通信发送方使用其私有密钥进行签名,通信接收方使用发送方的公开密钥对签名进行解密,就能判断这个签名是否正确。 - 优点:可以更安全地将公开密钥传输给通信发送方; - 缺点:运算速度慢。 ### HTTPS采用的加密方式 HTTPS 采用混合的加密机制,使用非对称密钥加密用于传输对称密钥来保证传输过程的安全性,之后使用对称密钥加密进行通信来保证通信过程的效率。 确保传输安全过程(其实就是rsa原理): 1. Client给出协议版本号、一个客户端生成的随机数(Client random),以及客户端支持的加密方法。 2. Server确认双方使用的加密方法,并给出数字证书、以及一个服务器生成的随机数(Server random)。 3. Client确认数字证书有效,然后生成呀一个新的随机数(Premaster secret),并使用数字证书中的公钥,加密这个随机数,发给Server。 4. Server使用自己的私钥,获取Client发来的随机数(Premaster secret)。 5. Client和Server根据约定的加密方法,使用前面的三个随机数,生成”对话密钥”(session key),用来加密接下来的整个对话过程。 ![](https://raw.githubusercontent.com/DreamCats/PicBed/master/20191121192634.png) ### 认证 通过使用 **证书** 来对通信方进行认证。 数字证书认证机构(CA,Certificate Authority)是客户端与服务器双方都可信赖的第三方机构。 服务器的运营人员向 CA 提出公开密钥的申请,CA 在判明提出申请者的身份之后,会对已申请的公开密钥做数字签名,然后分配这个已签名的公开密钥,并将该公开密钥放入公开密钥证书后绑定在一起。 进行 HTTPS 通信时,服务器会把证书发送给客户端。客户端取得其中的公开密钥之后,先使用数字签名进行验证,如果验证通过,就可以开始通信了。 ### HTTPS的缺点 - 因为需要进行加密解密等过程,因此速度会更慢; - 需要支付证书授权的高额费用。 ## HTTP几个问题 ### **代浏览器在与服务器建立了一个 TCP 连接后是否会在一个 HTTP 请求完成后断开?什么情况下会断开?** 在 HTTP/1.0 中,一个服务器在发送完一个 HTTP 响应后,会断开 TCP 链接。但是这样每次请求都会重新建立和断开 TCP 连接,代价过大。所以虽然标准中没有设定,某些服务器对 Connection: keep-alive 的 Header 进行了支持。意思是说,完成这个 HTTP 请求之后,不要断开 HTTP 请求使用的 TCP 连接。这样的好处是连接可以被重新使用,之后发送 HTTP 请求的时候不需要重新建立 TCP 连接,以及如果维持连接,那么 SSL 的开销也可以避免。 持久连接:既然维持 TCP 连接好处这么多,HTTP/1.1 就把 Connection 头写进标准,并且默认开启持久连接,除非请求中写明 Connection: close,那么浏览器和服务器之间是会维持一段时间的 TCP 连接,不会一个请求结束就断掉。 默认情况下建立 TCP 连接不会断开,只有在请求报头中声明 Connection: close 才会在请求完成后关闭连接。 ### 一个 TCP 连接可以对应几个 HTTP 请求? 如果维持连接,一个 TCP 连接是可以发送多个 HTTP 请求的。 ### 一个 TCP 连接中 HTTP 请求发送可以一起发送么(比如一起发三个请求,再三个响应一起接收)? HTTP/1.1 存在一个问题,单个 TCP 连接在同一时刻只能处理一个请求,意思是说:两个请求的生命周期不能重叠,任意两个 HTTP 请求从开始到结束的时间在同一个 TCP 连接里不能重叠。 在 HTTP/1.1 存在 Pipelining 技术可以完成这个多个请求同时发送,但是由于浏览器默认关闭,所以可以认为这是不可行的。在 HTTP2 中由于 Multiplexing 特点的存在,多个 HTTP 请求可以在同一个 TCP 连接中并行进行。 那么在 HTTP/1.1 时代,浏览器是如何提高页面加载效率的呢?主要有下面两点: - 维持和服务器已经建立的 TCP 连接,在同一连接上顺序处理多个请求。 - 和服务器建立多个 TCP 连接。 ### 为什么有的时候刷新页面不需要重新建立 SSL 连接? TCP 连接有的时候会被浏览器和服务端维持一段时间。TCP 不需要重新建立,SSL 自然也会用之前的。 ### 浏览器对同一 Host 建立 TCP 连接到数量有没有限制? 假设我们还处在 HTTP/1.1 时代,那个时候没有多路传输,当浏览器拿到一个有几十张图片的网页该怎么办呢?肯定不能只开一个 TCP 连接顺序下载,那样用户肯定等的很难受,但是如果每个图片都开一个 TCP 连接发 HTTP 请求,那电脑或者服务器都可能受不了,要是有 1000 张图片的话总不能开 1000 个TCP 连接吧,你的电脑同意 NAT 也不一定会同意。 有。Chrome 最多允许对同一个 Host 建立六个 TCP 连接。不同的浏览器有一些区别。 如果图片都是 HTTPS 连接并且在同一个域名下,那么浏览器在 SSL 握手之后会和服务器商量能不能用 HTTP2,如果能的话就使用 Multiplexing 功能在这个连接上进行多路传输。不过也未必会所有挂在这个域名的资源都会使用一个 TCP 连接去获取,但是可以确定的是 Multiplexing 很可能会被用到。 如果发现用不了 HTTP2 呢?或者用不了 HTTPS(现实中的 HTTP2 都是在 HTTPS 上实现的,所以也就是只能使用 HTTP/1.1)。那浏览器就会在一个 HOST 上建立多个 TCP 连接,连接数量的最大限制取决于浏览器设置,这些连接会在空闲的时候被浏览器用来发送新的请求,如果所有的连接都正在发送请求呢?那其他的请求就只能等等了。<file_sep>package com.basic; import java.util.concurrent.TimeUnit; /** * @program JavaBooks * @description: 一个同步方法可以调用另外一个同步方法,synchronized是可重入锁 子类同步也可以调用父类的同步方法 * @author: mf * @create: 2019/12/26 22:00 */ public class T4 { synchronized void m1() { System.out.println("m1 start"); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } m2(); } synchronized void m2() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("m2"); } } <file_sep>package com.basic; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @program JavaBooks * @description: ReentrantLock * @author: mf * @create: 2019/12/30 19:51 */ public class T12 { Lock lock = new ReentrantLock(); void m1() { try { lock.lock(); // 加锁 for (int i = 0; i < 10; i++) { System.out.println(i); TimeUnit.SECONDS.sleep(1); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } void m2() { lock.lock(); System.out.println("m2..."); } public static void main(String[] args) { T12 t12 = new T12(); new Thread(t12::m1, "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(t12::m2, "t2").start(); } } <file_sep>/** * @program JavaBooks * @description: 模拟变量在内存的布局 * @author: mf * @create: 2020/03/20 13:30 */ package com.type; public class IntegerTest { int value = 1; String s = "买"; int a = 257; } <file_sep>package com.basic; import java.util.concurrent.TimeUnit; /** * @program JavaBooks * @description: 锁粒度 * @author: mf * @create: 2019/12/29 00:23 */ public class T8 { private int count = 0; synchronized void m1() { // 锁粒度较粗,锁的东西较多 try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } count++; try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } void m2() { // 锁粒度较细, 锁的东西较少, 运行时间比上面快 try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { count++; // } } } <file_sep>/** * @program JavaBooks * @description: ProdConsumerSynchronized * synchronized版本的生产者和消费者,比较繁琐 * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * @author: mf * @create: 2020/02/16 13:01 */ package com.juc.queue; import java.util.LinkedList; public class ProdConsumerSynchronized { private final LinkedList<String> lists = new LinkedList<>(); public synchronized void put(String s) { while (lists.size() != 0) { // 用while怕有存在虚拟唤醒线程 // 满了, 不生产了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(s); System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst()); this.notifyAll(); // 这里可是通知所有被挂起的线程,包括其他的生产者线程 } public synchronized void get() { while (lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst()); this.notifyAll(); // 通知所有被wait挂起的线程 用notify可能就死锁了。 } public static void main(String[] args) { ProdConsumerSynchronized prodConsumerSynchronized = new ProdConsumerSynchronized(); // 启动消费者线程 for (int i = 0; i < 5; i++) { new Thread(prodConsumerSynchronized::get, "ConsA" + i).start(); } // 启动生产者线程 for (int i = 0; i < 5; i++) { int tempI = i; new Thread(() -> { prodConsumerSynchronized.put("" + tempI); }, "ProdA" + i).start(); } } } <file_sep>package books; /** * @program JavaBooks * @description: n个骰子的点数 * @author: mf * @create: 2019/10/08 20:30 */ /* 把n个骰子仍在地上,所有骰子朝上一面的点数之和为s。 输入n,打印出s的所有可能的值出现的概率。 */ public class T60 { public static void main(String[] args) { // 基于循环 PrintProbability(2); } private static void PrintProbability(int number) { if (number < 1) return; int[][] pProbabilities = new int[2][6 * number + 1]; // 初始化数组 for (int i = 0; i < 6; i++) { pProbabilities[0][i] = 0; pProbabilities[1][i] = 0; } int flag = 0; for (int i = 1; i <= 6; i++) { pProbabilities[flag][i] = 1; //当第一次抛掷骰子时,有6种可能,每种可能出现一次 } //从第二次开始掷骰子,假设第一个数组中的第n个数字表示骰子和为n出现的次数, //在下一循环中,我们加上一个新骰子,此时和为n的骰子出现次数应该等于上一次循环中骰子点数和为n-1,n-2,n-3,n-4,n-5, //n-6的次数总和,所以我们把另一个数组的第n个数字设为前一个数组对应的n-1,n-2,n-3,n-4,n-5,n-6之和 for (int k = 2; k <= number; k++) { for (int i = 0; i < k; i++) { //第k次掷骰子,和最小为k,小于k的情况是不可能发生的!所以另不可能发生的次数设置为0! pProbabilities[1-flag][i] = 0; } for(int i = k;i <= 6 * k; i++) { pProbabilities[1-flag][i] = 0;//初始化,因为这个数组要重复使用,上一次的值要清0 for(int j = 1;j <= i && j <= 6; j++) { pProbabilities[1-flag][i] += pProbabilities[flag][i-j]; } } flag = 1-flag; } double total = Math.pow(6, number); for(int i = number; i <= 6 * number; i++) { double ratio = pProbabilities[flag][i]/total; System.out.println("sum: "+i+" ratio: "+ratio); } } } <file_sep>package web; /** * @program LeetNiu * @description: 丑数 * @author: mf * @create: 2020/01/14 14:03 */ /** * 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 * 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 */ public class T33 { public int GetUglyNumber_Solution(int index) { if (index <= 0) return 0; int[] ans = new int[index]; int count = 0; int i2 = 0, i3 = 0, i5 = 0; ans[0] = 1; int temp = 0; while (count < index - 1) { temp = min(ans[i2] * 2, min(ans[i3] * 3, ans[i5] * 5)); if (temp == ans[i2] * 2) i2++; if (temp == ans[i3] * 3) i3++; if (temp == ans[i5] * 5) i5++; ans[++count] = temp; } return ans[index - 1]; } /** * 求最小值 * @param a * @param b * @return */ private int min(int a, int b) { return (a > b) ? b : a; } } <file_sep>## 引言 **sql-索引(B+树)** ## B+Tree原理 ### 数据结构 B Tree 指的是 Balance Tree,也就是平衡树。平衡树是一颗查找树,并且所有叶子节点位于同一层。 B+ Tree 是基于 B Tree 和叶子节点顺序访问指针进行实现,它具有 B Tree 的平衡性,并且通过顺序访问指针来提高区间查询的性能。 在 B+ Tree 中,一个节点中的 key 从左到右非递减排列,如果某个指针的左右相邻 key 分别是 keyi 和 keyi+1,且不为 null,则该指针指向节点的所有 key 大于等于 keyi 且小于等于 keyi+1。 <!-- more --> ### 操作 进行查找操作时,首先在根节点进行二分查找,找到一个key所在的指针,然后递归地指针指向的节点进行查找。直到查找到叶子结点,然后在叶子节点上进行二分查找,找出key所对应的data。 插入删除操作记录会破坏平衡树的平衡性,因此在插入删除操作之后,需要对树进行一个分裂、合并、旋转等操作来维护平衡性。 ### 与红黑树的比较 红黑树等平衡树可以用实现索引,但是文件系统及数据库系统普遍采用B+Tree作为索引结构,主要有以下两个原因: (1)更少的查找次数 平衡树查找操作的时间复杂度等于树高h,而树高大致为 O(h)=O(logdN),其中 d 为每个节点的出度。 红黑树的出度为2,而B+Tree的出度一般非常大,所以红黑树的树高h很明显比B+ Tree 大非常多,检索的次数也就更多。 (2)利用计算机预读特性 为了减少磁盘 I/O,磁盘往往不是严格按需读取,而是每次都会预读。预读过程中,磁盘进行顺序读取,顺序读取不需要进行磁盘寻道,并且只需要很短的旋转时间,因此速度会非常快。 操作系统一般将内存和磁盘分割成固态大小的块,每一块称为一页,内存与磁盘以页为单位交换数据。数据库系统将索引的一个节点的大小设置为页的大小,使得一次 I/O 就能完全载入一个节点,并且可以利用预读特性,相邻的节点也能够被预先载入。 ## MySQL 索引 索引是在存储引擎层实现的,而不是在服务器层实现的,所以不同存储引擎具有不同的索引类型和实现。 ### B+Tree索引 是大多数MySQL存储引擎的默认索引类型。 因为不再需要进行全表扫描,只需要对树进行搜索即可,因此查找速度快很多。除了用于查找,还可以用于排序和分组。 可以指定多个列作为索引列,多个索引列共同组成键。 适用于全键值、键值范围和键前缀查找,其中键前缀查找只适用于最左前缀查找。如果不是按照索引列的顺序进行查找,则无法使用索引。 InnoDB 的 B+Tree 索引分为主索引和辅助索引。 主索引的叶子节点 data 域记录着完整的数据记录,这种索引方式被称为聚簇索引。因为无法把数据行存放在两个不同的地方,所以一个表只能有一个聚簇索引。 辅助索引的叶子节点的 data 域记录着主键的值,因此在使用辅助索引进行查找时,需要先查找到主键值,然后再到主索引中进行查找。 ### 哈希索引 哈希索引能以 O(1) 时间进行查找,但是失去了有序性,它具有以下限制: - 无法用于排序与分组; - 只支持精确查找,无法用于部分查找和范围查找。 InnoDB 存储引擎有一个特殊的功能叫“自适应哈希索引”,当某个索引值被使用的非常频繁时,会在 B+Tree 索引之上再创建一个哈希索引,这样就让 B+Tree 索引具有哈希索引的一些优点,比如快速的哈希查找。 ### 全文索引 MyISAM 存储引擎支持全文索引,用于查找文本中的关键词,而不是直接比较是否相等。查找条件使用 MATCH AGAINST,而不是普通的 WHERE。 全文索引一般使用倒排索引实现,它记录着关键词到其所在文档的映射。 InnoDB 存储引擎在 MySQL 5.6.4 版本中也开始支持全文索引。 ### 空间数据索引 MyISAM 存储引擎支持空间数据索引(R-Tree),可以用于地理数据存储。空间数据索引会从所有维度来索引数据,可以有效地使用任意维度来进行组合查询。 必须使用 GIS 相关的函数来维护数据。 ## 索引优化 ### 独立的列 在进行查询时,索引列不能是表达式的一部分,也不能是函数的参数,否则无法使用索引。 `SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5;` ### 多列索引 在需要使用多个列作为条件进行查询时,使用多列索引比使用多个单列索引性能更好。例如下面的语句中,最好把 actor_id 和 film_id 设置为多列索引。 `SELECT film_id, actor_ id FROM sakila.film_actor WHERE actor_id = 1 AND film_id = 1;` ### 索引列的顺序 让选择性最强的索引列放在前面,索引的选择性是指: 不重复的索引值和记录总数的比值。最大值为 1,此时每个记录都有唯一的索引与其对应。选择性越高,查询效率也越高。 例如下面显示的结果中 customer_id 的选择性比 staff_id 更高,因此最好把 customer_id 列放在多列索引的前面。 ·`SELECT COUNT(DISTINCT staff_id)/COUNT(*) AS staff_id_selectivity, COUNT(DISTINCT customer_id)/COUNT(*) AS customer_id_selectivity, COUNT(*) FROM payment;` ### 前缀索引 对于 BLOB、TEXT 和 VARCHAR 类型的列,必须使用前缀索引,只索引开始的部分字符。 对于前缀长度的选取需要根据索引选择性来确定。 ### 覆盖索引 索引包含所有需要查询的字段的值。 具有以下优点: - 索引通常远小于数据行的大小,只读取索引能大大减少数据访问量。 - 一些存储引擎(例如 MyISAM)在内存中只缓存索引,而数据依赖于操作系统来缓存。因此,只访问索引可以不使用系统调用(通常比较费时)。 - 对于 InnoDB 引擎,若辅助索引能够覆盖查询,则无需访问主索引。 ## 索引的优点 - 大大减少了服务器需要扫描的数据行数。 - 帮助服务器避免进行排序和分组,也就不需要创建临时表(B+Tree 索引是有序的,可以用于 ORDER BY 和 GROUP BY 操作。临时表主要是在排序和分组过程中创建,因为不需要排序和分组,也就不需要创建临时表)。 - 将随机 I/O 变为顺序 I/O(B+Tree 索引是有序的,也就将相邻的数据都存储在一起)。 ### 索引的使用场景 - 对于非常小的表、大部分情况下简单的全表扫描比建立索引更高效。 - 对于中到大型的表,索引就非常有效。 - 但是对于特大型的表,建立和维护索引的代价将会随之增长。这种情况下,需要用到一种技术可以直接区分出需要查询的一组数据,而不是一条记录一条记录地匹配,例如可以使用分区技术。<file_sep>package web; /** * @program LeetNiu * @description: 随机链表 * @author: mf * @create: 2020/01/13 13:11 */ public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; public RandomListNode(int label) { this.label = label; } } <file_sep>package web; /** * @program LeetNiu * @description: 替换空格 * @author: mf * @create: 2020/01/07 20:11 */ /** * 请实现一个函数,将一个字符串中的每个空格替换成“%20”。 * 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 * 思路: * 1。 检测空格数目 * 2。 创建新数组 * 3。 遍历检测' ',则替换相应字符 */ public class T2 { public String replaceSpace(StringBuffer str) { // 检测空格数目 int spaceNum = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') spaceNum++; } // 创建新数组 char[] ans = new char[str.length() + 2 * spaceNum]; int p1 = ans.length - 1; for (int i = str.length() - 1; i >= 0; i++) { if (str.charAt(i) == ' ') { ans[p1--] = '0'; ans[p1--] = '2'; ans[p1--] = '%'; } else { ans[p1--] = str.charAt(i); } } return new String(ans); } } <file_sep>--- title: 个人吐血系列-总结Mysql date: 2020-03-30 15:13:08 tags: db categories: java-interview --- > MySQL这一块的知识还是挺多的,问深度的话, 一般都是如何调优的,当然少不了MySQL的基础等知识。 ![MySQL面试常见问题](http://media.dreamcat.ink/uPic/Mysql面试常见问题.png) ### 数据库引擎innodb与myisam的区别 #### InnoDB 是 MySQL 默认的**事务型**存储引擎,只有在需要它不支持的特性时,才考虑使用其它存储引擎。 实现了四个标准的隔离级别,默认级别是**可重复读**(REPEATABLE READ)。在可重复读隔离级别下,**通过多版本并发控制(MVCC)+ 间隙锁(Next-Key Locking)防止幻影读。** 主索引是**聚簇索引**,在索引中保存了数据,从而避免直接读取磁盘,因此对查询性能有很大的提升。 内部做了很多优化,包括从磁盘读取数据时采用的**可预测性读**、能够加快读操作并且自动创建的**自适应哈希索引**、能够加速插入操作的插入缓冲区等。 支持真正的**在线热备份**。其它存储引擎不支持在线热备份,要获取一致性视图需要停止对所有表的写入,而在读写混合场景中,停止写入可能也意味着停止读取。 #### MyISAM 设计简单,数据以**紧密格式存储**。对于只读数据,或者表比较小、可以容忍修复操作,则依然可以使用它。 提供了大量的特性,包括**压缩表**、**空间数据索引**等。 **不支持事务**。 **不支持行级锁**,只能对整张表加锁,读取时会对需要读到的所有表加共享锁,写入时则对表加排它锁。但在表有读取操作的同时,也可以往表中插入新的记录,这被称为并发插入(CONCURRENT INSERT)。 可以手工或者自动执行检查和修复操作,但是和事务恢复以及崩溃恢复不同,可能导致一些数据丢失,而且修复操作是非常慢的。 如果指定了 DELAY_KEY_WRITE 选项,在每次修改执行完成时,不会立即将修改的索引数据写入磁盘,而是会写到内存中的键缓冲区,只有在清理键缓冲区或者关闭表的时候才会将对应的索引块写入磁盘。这种方式可以极大的提升写入性能,但是在数据库或者主机崩溃时会造成索引损坏,需要执行修复操作。 #### 比较 - **事务**: InnoDB 是事务型的,可以使用 Commit 和 Rollback 语句。 - **并发**: MyISAM 只支持表级锁,而 InnoDB 还支持行级锁。 - **外键**: InnoDB 支持外键。 - **备份**: InnoDB 支持在线热备份。 - **崩溃恢复**: MyISAM 崩溃后发生损坏的概率比 InnoDB 高很多,而且恢复的速度也更慢。 - **其它特性**: MyISAM 支持压缩表和空间数据索引。 ### MySQL是如何执行一条SQL的 ![SQL执行的全部过程](http://media.dreamcat.ink/uPic/SQL执行的全部过程.png) **MySQL内部可以分为服务层和存储引擎层两部分:** 1. **服务层包括连接器、查询缓存、分析器、优化器、执行器等**,涵盖MySQL的大多数核心服务功能,以及所有的内置函数(如日期、时间、数学和加密函数等),所有跨存储引擎的功能都在这一层实现,比如存储过程、触发器、视图等。 2. **存储引擎层负责数据的存储和提取。**其架构模式是插件式的,支持InnoDB、MyISAM、Memory等多个存储引擎。现在最常用的存储引擎是InnoDB,它从MySQL 5.5.5版本开始成为了默认的存储引擎。 **Server层按顺序执行sql的步骤为:** 客户端请求->连接器(验证用户身份,给予权限) -> 查询缓存(存在缓存则直接返回,不存在则执行后续操作)->分析器(对SQL进行词法分析和语法分析操作) -> 优化器(主要对执行的sql优化选择最优的执行方案方法) -> 执行器(执行时会先看用户是否有执行权限,有才去使用这个引擎提供的接口)->去引擎层获取数据返回(如果开启查询缓存则会缓存查询结果) **简单概括**: - **连接器**:管理连接、权限验证; - **查询缓存**:命中缓存则直接返回结果; - **分析器**:对SQL进行词法分析、语法分析;(判断查询的SQL字段是否存在也是在这步) - **优化器**:执行计划生成、选择索引; - **执行器**:操作引擎、返回结果; - **存储引擎**:存储数据、提供读写接口。 ### mysql的acid原理 **ACID嘛,原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)!** 我们以从A账户转账50元到B账户为例进行说明一下ACID,四大特性。 #### 原子性 根据定义,原子性是指一个事务是一个不可分割的工作单位,其中的操作要么都做,要么都不做。即要么转账成功,要么转账失败,是不存在中间的状态! **如果无法保证原子性会怎么样?** OK,就会出现**数据不一致**的情形,A账户减去50元,而B账户增加50元操作失败。系统将无故丢失50元~ #### 隔离性 根据定义,隔离性是指多个事务并发执行的时候,**事务内部的操作与其他事务是隔离的**,并发执行的各个事务之间不能互相干扰。 **如果无法保证隔离性会怎么样?** OK,假设A账户有200元,B账户0元。A账户往B账户转账两次,金额为50元,分别在两个事务中执行。如果无法保证隔离性,会出现下面的情形 ![事务隔离性](http://media.dreamcat.ink/uPic/事务隔离性.png) 如图所示,如果不保证隔离性,A扣款两次,而B只加款一次,凭空消失了50元,依然出现了**数据不一致**的情形! #### 持久性 根据定义,**持久性是指事务一旦提交,它对数据库的改变就应该是永久性的**。接下来的其他操作或故障不应该对其有任何影响。 **如果无法保证持久性会怎么样?** 在MySQL中,为了解决CPU和磁盘速度不一致问题,MySQL是将磁盘上的数据加载到内存,对内存进行操作,然后再回写磁盘。好,假设此时宕机了,在内存中修改的数据全部丢失了,持久性就无法保证。 设想一下,系统提示你转账成功。但是你发现金额没有发生任何改变,此时数据出现了不合法的数据状态,我们将这种状态认为是**数据不一致**的情形。 #### 一致性 根据定义,一致性是指事务执行前后,数据处于一种合法的状态,这种状态是语义上的而不是语法上的。 那什么是合法的数据状态呢? oK,这个状态是满足预定的约束就叫做合法的状态,再通俗一点,这状态是由你自己来定义的。**满足这个状态,数据就是一致的,不满足这个状态,数据就是不一致的**! **如果无法保证一致性会怎么样?** - 例一:A账户有200元,转账300元出去,此时A账户余额为-100元。你自然就发现了此时数据是不一致的,为什么呢?因为你定义了一个状态,余额这列必须大于0。 - 例二:A账户200元,转账50元给B账户,A账户的钱扣了,但是B账户因为各种意外,余额并没有增加。你也知道此时数据是不一致的,为什么呢?因为你定义了一个状态,要求A+B的余额必须不变。 #### mysql怎么保证一致性? OK,这个问题分为两个层面来说。 **从数据库层面**,数据库通过原子性、隔离性、持久性来保证一致性。也就是说ACID四大特性之中,C(一致性)是目的,A(原子性)、I(隔离性)、D(持久性)是手段,是为了保证一致性,数据库提供的手段。数据库必须要实现AID三大特性,才有可能实现一致性。例如,原子性无法保证,显然一致性也无法保证。 但是,如果你在事务里故意写出违反约束的代码,一致性还是无法保证的。例如,你在转账的例子中,你的代码里故意不给B账户加钱,那一致性还是无法保证。因此,还必须从应用层角度考虑。 **从应用层面**,通过代码判断数据库数据是否有效,然后决定回滚还是提交数据! #### mysql怎么保证原子性 OK,是利用Innodb的`undo log`。 `undo log`名为回滚日志,是实现原子性的关键,当事务回滚时能够**撤销所有已经成功执行的sql语句**,他需要记录你要回滚的相应日志信息。 例如 - (1)当你delete一条数据的时候,就需要记录这条数据的信息,回滚的时候,insert这条旧数据 - (2)当你update一条数据的时候,就需要记录之前的旧值,回滚的时候,根据旧值执行update操作 - (3)当年insert一条数据的时候,就需要这条记录的主键,回滚的时候,根据主键执行delete操作 `undo log`记录了这些回滚需要的信息,当事务执行失败或调用了rollback,导致事务需要回滚,便可以利用undo log中的信息将数据回滚到修改之前的样子。 #### mysql怎么保证持久性的 OK,是利用Innodb的`redo log`。 正如之前说的,Mysql是先把磁盘上的数据加载到内存中,在内存中对数据进行修改,再刷回磁盘上。如果此时突然宕机,内存中的数据就会丢失。 *怎么解决这个问题?* 简单啊,事务提交前直接把数据写入磁盘就行啊。 *这么做有什么问题?* - 只修改一个页面里的一个字节,就要将整个页面刷入磁盘,太浪费资源了。毕竟一个页面16kb大小,你只改其中一点点东西,就要将16kb的内容刷入磁盘,听着也不合理。 - 毕竟一个事务里的SQL可能牵涉到多个数据页的修改,而这些数据页可能不是相邻的,也就是属于随机IO。显然操作随机IO,速度会比较慢。 于是,决定采用`redo log`解决上面的问题。当做数据修改的时候,不仅在内存中操作,还会在`redo log`中记录这次操作。当事务提交的时候,会将`redo log`日志进行刷盘(`redo log`一部分在内存中,一部分在磁盘上)。当数据库宕机重启的时候,会将`redo log`中的内容恢复到数据库中,再根据`undo log`和`binlog`内容决定回滚数据还是提交数据。 **采用redo log的好处?** 其实好处就是将`redo log`进行刷盘比对数据页刷盘效率高,具体表现如下 - `redo log`体积小,毕竟只记录了哪一页修改了啥,因此体积小,刷盘快。 - `redo log`是一直往末尾进行追加,属于顺序IO。效率显然比随机IO来的快。 #### mysql怎么保证隔离性 利用的是锁和MVCC机制。 ### 并发事务带来的问题 #### 脏读 ![脏读](https://www.pdai.tech/_images/pics/dd782132-d830-4c55-9884-cfac0a541b8e.png) #### 丢弃修改 T1 和 T2 两个事务都对一个数据进行修改,**T1 先修改,T2 随后修改,T2 的修改覆盖了 T1 的修改**。例如:事务1读取某表中的数据A=20,事务2也读取A=20,事务1修改A=A-1,事务2也修改A=A-1,最终结果A=19,事务1的修改被丢失。 ![丢弃修改](https://www.pdai.tech/_images/pics/88ff46b3-028a-4dbb-a572-1f062b8b96d3.png) #### 不可重复读 **T2 读取一个数据,T1 对该数据做了修改。如果 T2 再次读取这个数据,此时读取的结果和第一次读取的结果不同**。 ![不可重复读](https://www.pdai.tech/_images/pics/c8d18ca9-0b09-441a-9a0c-fb063630d708.png) #### 幻读 **T1 读取某个范围的数据,T2 在这个范围内插入新的数据,T1 再次读取这个范围的数据,此时读取的结果和和第一次读取的结果不同**。 ![幻读](https://www.pdai.tech/_images/pics/72fe492e-f1cb-4cfc-92f8-412fb3ae6fec.png) #### 不可重复读和幻读区别 **不可重复读的重点是修改,幻读的重点在于新增或者删除**。 例1(同样的条件, 你读取过的数据, 再次读取出来发现值不一样了 ):事务1中的A先生读取自己的工资为 1000的操 作还没完成,事务2中的B先生就修改了A的工资为2000,导 致A再读自己的工资时工资变为 2000;这就是不可重复读。 例2(同样的条件, 第1次和第2次读出来的记录数不一样 ):假某工资单表中工资大于3000的有4人,事务1读取了所 有工资大于3000的人,共查到4条记录,这时事务2 又插入了一条工资大于3000的记录,事务1再次读取时查到的记 录就变为了5条,这样就导致了幻读。 ### 数据库的隔离级别 1. 未提交读,事务中发生了修改,即使没有提交,其他事务也是可见的,比如对于一个数A原来50修改为100,但是我还没有提交修改,另一个事务看到这个修改,而这个时候原事务发生了回滚,这时候A还是50,但是另一个事务看到的A是100.**可能会导致脏读、幻读或不可重复读** 2. 提交读,对于一个事务从开始直到提交之前,所做的任何修改是其他事务不可见的,举例就是对于一个数A原来是50,然后提交修改成100,这个时候另一个事务在A提交修改之前,读取的A是50,刚读取完,A就被修改成100,这个时候另一个事务再进行读取发现A就突然变成100了;**可以阻止脏读,但是幻读或不可重复读仍有可能发生** 3. 可重复读,就是对一个记录读取多次的记录是相同的,比如对于一个数A读取的话一直是A,前后两次读取的A是一致的;**可以阻止脏读和不可重复读,但幻读仍有可能发生。** 4. 可串行化读,在并发情况下,和串行化的读取的结果是一致的,没有什么不同,比如不会发生脏读和幻读;**该级别可以防止脏读、不可重复读以及幻读。** | 隔离级别 | 脏读 | 不可重复读 | 幻影读 | | ---------------- | ---- | ---------- | ------ | | READ-UNCOMMITTED | √ | √ | √ | | READ-COMMITTED | × | √ | √ | | REPEATABLE-READ | × | × | √ | | SERIALIZABLE | × | × | × | MySQL InnoDB 存储引擎的默认支持的隔离级别是 REPEATABLE-READ(可重读)。 **这里需要注意的是**:与 SQL 标准不同的地方在于InnoDB 存储引擎在 REPEATABLE-READ(可重读)事务隔离级别 下使用的是**Next-Key Lock 锁**算法,因此可以避免幻读的产生,这与其他数据库系统(如 SQL Server)是不同的。所以 说InnoDB 存储引擎的默认支持的隔离级别是 REPEATABLE-READ(可重读) 已经可以完全保证事务的隔离性要 求,即达到了 SQL标准的SERIALIZABLE(可串行化)隔离级别。 因为隔离级别越低,事务请求的锁越少,所以大部分数据库系统的隔离级别都是READ-COMMITTED(读取提交内 容):,但是你要知道的是InnoDB 存储引擎默认使用 **REPEATABLE-READ(可重读)并不会有任何性能损失**。 InnoDB 存储引擎在分布式事务 的情况下一般会用到SERIALIZABLE(可串行化)隔离级别。 ### 为什么使用索引 - 通过创建**唯一性索引**,可以保证数据库表中每一行数据的唯一性。 - 可以大大**加快数据的检索速度**,这也是创建索引的最主要的原因。 - 帮助服务器**避免排序和临时表** - 将**随机IO变为顺序IO**。 - 可以加速**表和表之间的连接**,特别是在实现数据的参考完整性方面特别有意义。 ### 索引这么多优点,为什么不对表总的每一列创建一个索引 - 当对表中的数据进行增加、删除和修改的时候,**索引也要动态的维护**,这样就降低了数据的维护速度。 - **索引需要占物理空间**,除了数据表占数据空间之外,每一个索引还要占一定的物理空间,如果要建立簇索引,那么需要的空间就会更大。 - **创建索引和维护索引要耗费时间**,这种时间随着数据量的增加而增加 ### 索引如何提高查询速度的 将无序的数据变成相对有序的数据(就像查有目的一样) ### 使用索引的注意事项 - 在经常需要搜索的列上,可以加快搜索的速度; - 在经常使用在where子句中的列上面创建索引,加快条件的判断速度。 - 在经常需要排序的列上创建索引,因为索引已经排序,这样查询可以利用索引的排序,加快排序查询时间 - 在中到大型表索引都是非常有效的,但是特大型表的维护开销会很大,不适合建索引 - 在经常用到连续的列上,这些列主要是由一些外键,可以加快连接的速度 - 避免where子句中对字段施加函数,这会造成无法命中索引 - 在使用InnoDB时使用与业务无关的自增主键作为主键,即使用逻辑主键,而不要使用业务主键。 - **将打算加索引的列设置为NOT NULL,否则将导致引擎放弃使用索引而进行全表扫描** - 删除长期未使用的索引,不用的索引的存在会造成不必要的性能损耗 - 在使用limit offset查询缓存时,可以借助索引来提高性能。 ### MySQL索引主要使用的两种数据结构 - **哈希索引**,对于哈希索引来说,底层的数据结构肯定是哈希表,因此在绝大多数需求为单条记录查询的时候,可以选择哈希索引,查询性能最快;其余大部分场景,建议选择BTree索引 - **BTree索引**,Mysql的BTree索引使用的是B树中的B+Tree但对于主要的两种存储引擎(MyISAM和InnoDB)的实现方式是不同的。 ### myisam和innodb实现btree索引方式的区别 - MyISAM,**B+Tree叶节点的data域存放的是数据记录的地址**,在索引检索的时候,首先按照B+Tree搜索算法搜索索引,如果指定的key存在,则取出其data域的值,然后以data域的值为地址读区相应的数据记录,这被称为“非聚簇索引” - InnoDB,其数据文件本身就是索引文件,相比MyISAM,**索引文件和数据文件是分离的**,**其表数据文件本身就是按B+Tree组织的一个索引结构,树的节点data域保存了完整的数据记录**,这个索引的key是数据表的主键,因此InnoDB表数据文件本身就是主索引。这被称为“聚簇索引”或者聚集索引,而其余的索引都作为辅助索引,辅助索引的data域存储相应记录主键的值而不是地址,这也是和MyISAM不同的地方,在根据主索引搜索时,直接找到key所在的节点即可取出数据;在根据辅助索引查找时,则需要先取出主键的值,在走一遍主索引。因此,在设计表的时候,不建议使用过长的字段为主键,也不建议使用非单调的字段作为主键,这样会造成主索引频繁分裂。 ### 数据库结构优化 - **范式优化**: 比如消除冗余(节省空间。。) - **反范式优化**:比如适当加冗余等(减少join) - **限定数据的范围**: 务必禁止不带任何限制数据范围条件的查询语句。比如:我们当用户在查询订单历史的时候,我们可以控制在一个月的范围内。 - **读/写分离**: 经典的数据库拆分方案,主库负责写,从库负责读; - **拆分表**:分区将数据在物理上分隔开,不同分区的数据可以制定保存在处于不同磁盘上的数据文件里。这样,当对这个表进行查询时,只需要在表分区中进行扫描,而不必进行全表扫描,明显缩短了查询时间,另外处于不同磁盘的分区也将对这个表的数据传输分散在不同的磁盘I/O,一个精心设置的分区可以将数据传输对磁盘I/O竞争均匀地分散开。对数据量大的时时表可采取此方法。可按月自动建表分区。 **拆分其实又分垂直拆分和水平拆分:** - 案例: 简单购物系统暂设涉及如下表: - 1.产品表(数据量10w,稳定) - 2.订单表(数据量200w,且有增长趋势) - 3.用户表 (数据量100w,且有增长趋势) - 以mysql为例讲述下水平拆分和垂直拆分,mysql能容忍的数量级在百万静态数据可以到千万 - **垂直拆分:** - 解决问题:表与表之间的io竞争 - 不解决问题:单表中数据量增长出现的压力 - 方案: 把产品表和用户表放到一个server上 订单表单独放到一个server上 - **水平拆分:** - 解决问题:单表中数据量增长出现的压力 - 不解决问题:表与表之间的io争夺 - 方案:**用户表** 通过性别拆分为男用户表和女用户表,**订单表** 通过已完成和完成中拆分为已完成订单和未完成订单,**产品表** 未完成订单放一个server上,已完成订单表盒男用户表放一个server上,女用户表放一个server上(女的爱购物 哈哈)。 ### 主键超键候选键外键是什么 - **超键**:在关系中能唯一标识**元组的属性集**称为关系模式的超键 - **候选键**:不含有**多余属性的超键**称为候选键。也就是在候选键中,若再删除属性,就不是键了! - **主键**:**用户选作元组标识的一个候选键程序主键** - **外键**:如果关系模式**R中属性K是其它模式的主键**,那么**k在模式R中称为外键**。 **举例**: | 学号 | 姓名 | 性别 | 年龄 | 系别 | 专业 | | -------- | ------ | ---- | ---- | ------ | -------- | | 20020612 | 李辉 | 男 | 20 | 计算机 | 软件开发 | | 20060613 | 张明 | 男 | 18 | 计算机 | 软件开发 | | 20060614 | 王小玉 | 女 | 19 | 物理 | 力学 | | 20060615 | 李淑华 | 女 | 17 | 生物 | 动物学 | | 20060616 | 赵静 | 男 | 21 | 化学 | 食品化学 | | 20060617 | 赵静 | 女 | 20 | 生物 | 植物学 | 1. 超键:于是我们从例子中可以发现 学号是标识学生实体的唯一标识。那么该元组的超键就为学号。除此之外我们还可以把它跟其他属性组合起来,比如:(`学号`,`性别`),(`学号`,`年龄`) 2. 候选键:根据例子可知,学号是一个可以唯一标识元组的唯一标识,因此学号是一个候选键,实际上,候选键是超键的子集,比如 (学号,年龄)是超键,但是它不是候选键。因为它还有了额外的属性。 3. 主键:简单的说,例子中的元组的候选键为学号,但是我们选定他作为该元组的唯一标识,那么学号就为主键。 4. 外键是相对于主键的,比如在学生记录里,主键为学号,在成绩单表中也有学号字段,因此学号为成绩单表的外键,为学生表的主键。 **主键为候选键的子集,候选键为超键的子集,而外键的确定是相对于主键的。** ### drop,delete与truncate的区别 - drop直接删掉表; - truncate删除表中数据,再插入时自增长id又从1开始 ; - delete删除表中数据,可以加where字句。 1. DELETE语句执行删除的过程是每次从表中删除一行,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作。TRUNCATE TABLE 则一次性地从表中删除所有的数据并不把单独的删除操作记录记入日志保存,删除行是不能恢复的。并且在删除的过程中不会激活与表有关的删除触发器。执行速度快。 2. 表和索引所占空间。当表被TRUNCATE 后,这个表和索引所占用的空间会恢复到初始大小,而DELETE操作不会减少表或索引所占用的空间。drop语句将表所占用的空间全释放掉。 3. 一般而言,drop > truncate > delete 4. 应用范围。TRUNCATE 只能对TABLE;DELETE可以是table和view 5. TRUNCATE 和DELETE只删除数据,而DROP则删除整个表(结构和数据)。 6. truncate与不带where的delete :只删除数据,而不删除表的结构(定义)drop语句将删除表的结构被依赖的约束(constrain),触发器(trigger)索引(index);依赖于该表的存储过程/函数将被保留,但其状态会变为:invalid。 7. delete语句为DML(Data Manipulation Language),这个操作会被放到 rollback segment中,事务提交后才生效。如果有相应的 tigger,执行的时候将被触发。 8. truncate、drop是DDL(Data Define Language),操作立即生效,原数据不放到 rollback segment中,不能回滚 9. 在没有备份情况下,谨慎使用 drop 与 truncate。要删除部分数据行采用delete且注意结合where来约束影响范围。回滚段要足够大。要删除表用drop;若想保留表而将表中数据删除,如果于事务无关,用truncate即可实现。如果和事务有关,或老是想触发trigger,还是用delete。 10. Truncate table 表名 速度快,而且效率高,因为: truncate table 在功能上与不带 WHERE 子句的 DELETE 语句相同:二者均删除表中的全部行。但 TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少。DELETE 语句每次删除一行,并在事务日志中为所删除的每行记录一项。TRUNCATE TABLE 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放。 11. TRUNCATE TABLE 删除表中的所有行,但表结构及其列、约束、索引等保持不变。新行标识所用的计数值重置为该列的种子。如果想保留标识计数值,请改用 DELETE。如果要删除表定义及其数据,请使用 DROP TABLE 语句。 12. 对于由 FOREIGN KEY 约束引用的表,不能使用 TRUNCATE TABLE,而应使用不带 WHERE 子句的 DELETE 语句。由于 TRUNCATE TABLE 不记录在日志中,所以它不能激活触发器。 ### 视图的作用,视图可以更改吗 视图是虚拟的表,与包含数据的表不一样,视图只包含使用时动态检索数据的查询;不包含任何列或数据。使用视图可以简化复杂的sql操作,隐藏具体的细节,保护数据;视图创建后,可以使用与表相同的方式利用它们。 视图不能被索引,也不能有关联的触发器或默认值,如果视图本身内有order by 则对视图再次order by将被覆盖。 创建视图:`create view xxx as xxxx` 对于某些视图比如未使用联结子查询分组聚集函数Distinct Union等,是可以对其更新的,对视图的更新将对基表进行更新;但是视图主要用于简化检索,保护数据,并不用于更新,而且大部分视图都不可以更新。 ### 数据库范式 #### 第一范式 在任何一个关系数据库中,第一范式(1NF)是对关系模式的基本要求,不满足第一范式(1NF)的数据库就不是关系数据库。 所谓第一范式(1NF)是指数据库表的每一列都是不可分割的基本数据项,同一列中不能有多个值,即实体中的某个属性不能有多个值或者不能有重复的属性。如果出现重复的属性,就可能需要定义一个新的实体,新的实体由重复的属性构成,新实体与原实体之间为一对多关系。在第一范式(1NF)中表的每一行只包含一个实例的信息。简而言之,**第一范式就是无重复的列**。 #### 第二范式 第二范式(2NF)是在第一范式(1NF)的基础上建立起来的,即满足第二范式(2NF)必须先满足第一范式(1NF)。第二范式(2NF)要求数据库表中的每个实例或行必须可以被惟一地区分。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。这个惟一属性列被称为主关键字或主键、主码。 第二范式(2NF)要求实体的属性完全依赖于主关键字。所谓完全依赖是指不能存在仅依赖主关键字一部分的属性,如果存在,那么这个属性和主关键字的这一部分应该分离出来形成一个新的实体,新实体与原实体之间是一对多的关系。为实现区分通常需要为表加上一个列,以存储各个实例的惟一标识。简而言之,**第二范式就是非主属性非部分依赖于主关键字**。 #### 第三范式 满足第三范式(3NF)必须先满足第二范式(2NF)。简而言之,第三范式(3NF)要求一个数据库表中不包含已在其它表中已包含的非主关键字信息。例如,**存在一个部门信息表,其中每个部门有部门编号(dept_id)、部门名称、部门简介等信息。那么在员工信息表中列出部门编号后就不能再将部门名称、部门简介等与部门有关的信息再加入员工信息表中。如果不存在部门信息表,则根据第三范式(3NF)也应该构建它,否则就会有大量的数据冗余。**简而言之,第三范式就是属性不依赖于其它非主属性。(我的理解是消除冗余) ### 什么是覆盖索引 如果一个索引包含(或者说覆盖)所有需要查询的字段的值,我们就称 之为“覆盖索引”。我们知道在InnoDB存储引 擎中,如果不是主键索引,叶子节点存储的是主键+列值。最终还是要“回表”,也就是要通过主键再查找一次,这样就 会比较慢。覆盖索引就是把要查询出的列和索引是对应的,不做回表操作! ### 各种树 > 这里就不多介绍了,有兴趣可以在这里看[各种树](http://dreamcat.ink/2019/11/08/shu-ju-jie-gou-shu-ji-chu/) > 创作不易哇,觉得有帮助的话,给个小小的star呗。github地址😁😁😁 <file_sep>package normal; import java.util.HashSet; /** * @program JavaBooks * @description: 141.环形链表 * @author: mf * @create: 2019/11/05 10:19 */ /* 题目: 难度:easy 类型:链表 */ public class HasCycle { public static void main(String[] args) { } /** * 哈希 * @param head * @return */ public static boolean hasCycle(ListNode head) { HashSet<ListNode> set = new HashSet<>(); while (head != null) { if (set.contains(head)) { return true; } else { set.add(head); } head = head.next; } return false; } /** * 快慢指针 * @param head * @return */ public static boolean hasCycle2(ListNode head) { if (head != null && head.next != null) { ListNode quick = head; ListNode slow = head; while (2 > 1) { quick = quick.next; if (quick == null) return false; quick = quick.next; if (quick == null) return false; slow = slow.next; if (slow == quick) return true; } } else { return false; } } } <file_sep>package books; /** * @program JavaBooks * @description: 合并两个排序的链表 * @author: mf * @create: 2019/09/06 09:19 */ /* 输入两个递增排序的链表,合并这两个链表并使新链表中的节点 仍然使递增排序的。例如,。。。 1 3 5 2 4 6 1 2 3 4 5 6 */ /* 思路还是类似于准备两个指针一样,但是这次不同 比较两个值,谁小,谁让出来, 比如, p1 < p2 那么,node = p1 那么node.next 继续和p2比较, 如果还小, 继续上面的过程,所以递归(因为p1 p2已经排好序) 如果p1 >= p2,那就将node = p2, node.next 和p1剩下的比较, 继续上面的过程 */ public class T25 { public static void main(String[] args) { ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); ListNode listNode4 = new ListNode(4); ListNode listNode5 = new ListNode(5); ListNode listNode6 = new ListNode(6); listNode1.next = listNode3; listNode3.next = listNode5; listNode2.next = listNode4; listNode4.next = listNode6; ListNode node = merge(listNode1, listNode2); while (node != null) { System.out.println(node.value); node = node.next; } } // 递归 private static ListNode merge(ListNode headNode1, ListNode headNode2) { if (headNode1 == null) return headNode2; if (headNode2 == null) return headNode1; ListNode node = null; if (headNode1.value < headNode2.value) { node = headNode1; node.next = merge(node.next, headNode2); } else { node = headNode2; node.next = merge(node.next, headNode1); } return node; } } <file_sep>- [什么是数据持久化](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E6%95%B0%E6%8D%AE%E6%8C%81%E4%B9%85%E5%8C%96) - [Mybatis框架简介](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E6%A1%86%E6%9E%B6%E7%AE%80%E4%BB%8B) - [什么是ORM](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#orm) - [MyBatis框架的优缺点及其适用的场合](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E6%A1%86%E6%9E%B6%E7%9A%84%E4%BC%98%E7%BC%BA%E7%82%B9%E5%8F%8A%E5%85%B6%E9%80%82%E7%94%A8%E7%9A%84%E5%9C%BA%E5%90%88) - [MyBatis与Hibernate有哪些不同?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E4%B8%8Ehibernate%E6%9C%89%E5%93%AA%E4%BA%9B%E4%B8%8D%E5%90%8C) - [#{}和${}的区别是什么?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E5%92%8C%E7%9A%84%E5%8C%BA%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88) - [当实体类中的属性名和表中的字段名不一样,怎么办](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E5%BD%93%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%AD%E7%9A%84%E5%B1%9E%E6%80%A7%E5%90%8D%E5%92%8C%E8%A1%A8%E4%B8%AD%E7%9A%84%E5%AD%97%E6%AE%B5%E5%90%8D%E4%B8%8D%E4%B8%80%E6%A0%B7-%E6%80%8E%E4%B9%88%E5%8A%9E-) - [模糊查询like语句该怎么写?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E6%A8%A1%E7%B3%8A%E6%9F%A5%E8%AF%A2like%E8%AF%AD%E5%8F%A5%E8%AF%A5%E6%80%8E%E4%B9%88%E5%86%99) - [这个Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E9%80%9A%E5%B8%B8%E4%B8%80%E4%B8%AAxml%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6%E9%83%BD%E4%BC%9A%E5%86%99%E4%B8%80%E4%B8%AAdao%E6%8E%A5%E5%8F%A3%E4%B8%8E%E4%B9%8B%E5%AF%B9%E5%BA%94%E8%AF%B7%E9%97%AE%E8%BF%99%E4%B8%AAdao%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86%E6%98%AF%E4%BB%80%E4%B9%88dao%E6%8E%A5%E5%8F%A3%E9%87%8C%E7%9A%84%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E4%B8%8D%E5%90%8C%E6%97%B6%E6%96%B9%E6%B3%95%E8%83%BD%E9%87%8D%E8%BD%BD%E5%90%97) - [Mybatis是如何进行分页的?分页插件的原理是什么?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E6%98%AF%E5%A6%82%E4%BD%95%E8%BF%9B%E8%A1%8C%E5%88%86%E9%A1%B5%E7%9A%84%E5%88%86%E9%A1%B5%E6%8F%92%E4%BB%B6%E7%9A%84%E5%8E%9F%E7%90%86%E6%98%AF%E4%BB%80%E4%B9%88) - [Mybatis是如何将sql执行结果封装为目标对象并返回的?都有哪些映射形式?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E6%98%AF%E5%A6%82%E4%BD%95%E5%B0%86sql%E6%89%A7%E8%A1%8C%E7%BB%93%E6%9E%9C%E5%B0%81%E8%A3%85%E4%B8%BA%E7%9B%AE%E6%A0%87%E5%AF%B9%E8%B1%A1%E5%B9%B6%E8%BF%94%E5%9B%9E%E7%9A%84%E9%83%BD%E6%9C%89%E5%93%AA%E4%BA%9B%E6%98%A0%E5%B0%84%E5%BD%A2%E5%BC%8F) - [Mybatis动态sql有什么用?执行原理?有哪些动态sql?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E5%8A%A8%E6%80%81sql%E6%9C%89%E4%BB%80%E4%B9%88%E7%94%A8%E6%89%A7%E8%A1%8C%E5%8E%9F%E7%90%86%E6%9C%89%E5%93%AA%E4%BA%9B%E5%8A%A8%E6%80%81sql) - [Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E7%9A%84xml%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6%E4%B8%AD%E4%B8%8D%E5%90%8C%E7%9A%84xml%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6id%E6%98%AF%E5%90%A6%E5%8F%AF%E4%BB%A5%E9%87%8D%E5%A4%8D) - [为什么说Mybatis是半自动ORM映射工具?它与全自动的区别在哪里?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%AF%B4mybatis%E6%98%AF%E5%8D%8A%E8%87%AA%E5%8A%A8orm%E6%98%A0%E5%B0%84%E5%B7%A5%E5%85%B7%E5%AE%83%E4%B8%8E%E5%85%A8%E8%87%AA%E5%8A%A8%E7%9A%84%E5%8C%BA%E5%88%AB%E5%9C%A8%E5%93%AA%E9%87%8C) - [MyBatis实现一对一有几种方式?具体怎么操作的?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E5%AE%9E%E7%8E%B0%E4%B8%80%E5%AF%B9%E4%B8%80%E6%9C%89%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F%E5%85%B7%E4%BD%93%E6%80%8E%E4%B9%88%E6%93%8D%E4%BD%9C%E7%9A%84) - [MyBatis实现一对多有几种方式,怎么操作的?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E5%AE%9E%E7%8E%B0%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%9C%89%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F%E6%80%8E%E4%B9%88%E6%93%8D%E4%BD%9C%E7%9A%84) - [Mybatis是否支持延迟加载?如果支持,它的实现原理是什么?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E6%98%AF%E5%90%A6%E6%94%AF%E6%8C%81%E5%BB%B6%E8%BF%9F%E5%8A%A0%E8%BD%BD%E5%A6%82%E6%9E%9C%E6%94%AF%E6%8C%81%E5%AE%83%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E6%98%AF%E4%BB%80%E4%B9%88) - [Mybatis的一级、二级缓存](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#mybatis%E7%9A%84%E4%B8%80%E7%BA%A7%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98) - [什么是MyBatis的接口绑定?有哪些实现方式?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E4%BB%80%E4%B9%88%E6%98%AFmybatis%E7%9A%84%E6%8E%A5%E5%8F%A3%E7%BB%91%E5%AE%9A%E6%9C%89%E5%93%AA%E4%BA%9B%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F) - [使用MyBatis的mapper接口调用时有哪些要求?](https://github.com/DreamCats/SpringBooks/blob/master/MyBatis%E6%A1%86%E6%9E%B6%E9%9D%A2%E8%AF%95%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98.md#%E4%BD%BF%E7%94%A8mybatis%E7%9A%84mapper%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8%E6%97%B6%E6%9C%89%E5%93%AA%E4%BA%9B%E8%A6%81%E6%B1%82) - [mybatis是如何防止SQL注入的](https://zhuanlan.zhihu.com/p/39408398) <file_sep>## 引言 > **JVM - 参数调优** ## 如何盘点查看JVM系统默认值 **如何查看运行中程序的JVM信息** - jps查看进程信息 - jinfo -flag 配置项 晋城号 - jinfo -flags 进程号(查看所有配置) #### JVM参数类型 1. 标配参 1. `-version -help` 2. 各个版本之间稳定,很少有很大的变化 2. x参数 1. `-Xint -Xcomp -Xmixed` 2. -Xint:解释执行 3. -Xcomp:第一次使用就编译成本地代码 4. -Xmixed:混合模式 3. **XX参数(重要)** 1. Boolean类型 1. 公式:`-XX+或者-某个属性`---> +表示开启,-表示关闭 2. 比如:**是否打印GC收集细节 -XX:+PrintGCDetails -XX:-PrintGCDetails** 3. 比如:**是否使用串行垃圾回收器:-XX:-UserSerialGC** 2. KV设值类型 1. 公式:`-XX:key=value` 2. 比如:`-XX:MetaspaceSize=128m` `-XX:MaxTenuringThreshold=15` `-Xms----> -XX:InitialHeapSize` `-Xmx----> -XX:MaxHeapSize` #### 查看参数 - `-XX:+PrintFlagsInitial`:查看初始默认,eg:`java -XX:+PrintFlagsInitial -version` - `-XX:+PrintFlagsFinal`:查看修改后的 `:=`说明是修改过的 - `-XX:+PrintCommandLineFlags`:查看使用的垃圾回收器 ## JVM参数 - -Xms 堆最小值 - -Xmx 堆最大堆。-Xms与-Xmx 的单位默认字节都是以k、m做单位的。 通常这两个配置参数相等,避免每次空间不足,动态扩容带来的影响。 <!-- more --> - -Xmn 新生代大小 - -Xss 每个线程池的堆栈大小。在jdk5以上的版本,每个线程堆栈大小为1m,jdk5以前的版本是每个线程池大小为256k。一般在相同物理内存下,如果减少-xss值会产生更大的线程数,但不同的操作系统对进程内线程数是有限制的,是不能无限生成。 - -XX:NewRatio 设置新生代与老年代比值,-XX:NewRatio=4 表示新生代与老年代所占比例为1:4 ,新生代占比整个堆的五分之一。如果设置了-Xmn的情况下,该参数是不需要在设置的。 - -XX:PermSize 设置持久代初始值,默认是物理内存的六十四分之一 - -XX:MaxPermSize 设置持久代最大值,默认是物理内存的四分之一 - -XX:MaxTenuringThreshold 新生代中对象存活次数,默认15。(若对象在eden区,经历一次MinorGC后还活着,则被移动到Survior区,年龄加1。以后,对象每次经历MinorGC,年龄都加1。达到阀值,则移入老年代) - -XX:SurvivorRatio Eden区与Subrvivor区大小的比值,如果设置为8,两个Subrvivor区与一个Eden区的比值为2:8,一个Survivor区占整个新生代的十分之一 - -XX:+UseFastAccessorMethods 原始类型快速优化 - -XX:+AggressiveOpts 编译速度加快 - -XX:PretenureSizeThreshold 对象超过多大值时直接在老年代中分配 ```text 说明: 整个堆大小的计算公式:JVM 堆大小 = 年轻代大小+年老代大小+持久代大小。 增大新生代大小就会减少对应的年老代大小,设置-Xmn值对系统性能影响较大,所以如果设置新生代大小的调整,则需要严格的测试调整。而新生代是用来存放新创建的对象,大小是随着堆大小增大和减少而有相应的变化,默认值是保持堆大小的十五分之一,-Xmn参数就是设置新生代的大小,也可以通过-XX:NewRatio来设置新生代与年老代的比例,java 官方推荐配置为3:8。 新生代的特点就是内存中的对象更新速度快,在短时间内容易产生大量的无用对象,如果在这个参数时就需要考虑垃圾回收器设置参数也需要调整。推荐使用:复制清除算法和并行收集器进行垃圾回收,而新生代的垃圾回收叫做初级回收。 StackOverflowError和OutOfMemoryException。当线程中的请求的栈的深度大于最大可用深度,就会抛出前者;若内存空间不够,无法创建新的线程,则会抛出后者。栈的大小直接决定了函数的调用最大深度,栈越大,函数嵌套可调用次数就越多。 ``` ## 经验 1. Xmn用于设置新生代的大小。过小会增加Minor GC频率,过大会减小老年代的大小。一般设为整个堆空间的1/4或1/3. 2. XX:SurvivorRatio用于设置新生代中survivor空间(from/to)和eden空间的大小比例; XX:TargetSurvivorRatio表示,当经历Minor GC后,survivor空间占有量(百分比)超过它的时候,就会压缩进入老年代(当然,如果survivor空间不够,则直接进入老年代)。默认值为50%。 3. 为了性能考虑,一开始尽量将新生代对象留在新生代,避免新生的大对象直接进入老年代。因为新生对象大部分都是短期的,这就造成了老年代的内存浪费,并且回收代价也高(Full GC发生在老年代和方法区Perm). 4. 当Xms=Xmx,可以使得堆相对稳定,避免不停震荡 5. 一般来说,MaxPermSize设为64MB可以满足绝大多数的应用了。若依然出现方法区溢出,则可以设为128MB。若128MB还不能满足需求,那么就应该考虑程序优化了,减少**动态类**的产生。 ## 垃圾回收 ### 垃圾回收算法 - 引用计数法:会有循环引用的问题,古老的方法; - Mark-Sweep:标记清除。根可达判断,最大的问题是空间碎片(清除垃圾之后剩下不连续的内存空间); - Copying:复制算法。对于短命对象来说有用,否则需要复制大量的对象,效率低。**如Java的新生代堆空间中就是使用了它(survivor空间的from和to区);** - Mark-Compact:标记整理。对于老年对象来说有用,无需复制,不会产生内存碎片 ### GC考虑的指标 - 吞吐量:应用耗时和实际耗时的比值; - 停顿时间:垃圾回收的时候,由于Stop the World,应用程序的所有线程会挂起,造成应用停顿。 ```text 吞吐量和停顿时间是互斥的。 对于后端服务(比如后台计算任务),吞吐量优先考虑(并行垃圾回收); 对于前端应用,RT响应时间优先考虑,减少垃圾收集时的停顿时间,适用场景是Web系统(并发垃圾回收) ``` ### 回收器的JVM参数 - -XX:+UseSerialGC 串行垃圾回收,现在基本很少使用。 - -XX:+UseParNewGC 新生代使用并行,老年代使用串行; - -XX:+UseConcMarkSweepGC 新生代使用并行,老年代使用CMS(一般都是使用这种方式),CMS是Concurrent Mark Sweep的缩写,并发标记清除,一看就是老年代的算法,所以,它可以作为老年代的垃圾回收器。CMS不是独占式的,它关注停顿时间 - -XX:ParallelGCThreads 指定并行的垃圾回收线程的数量,最好等于CPU数量 - -XX:+DisableExplicitGC 禁用System.gc(),因为它会触发Full GC,这是很浪费性能的,JVM会在需要GC的时候自己触发GC。 - -XX:CMSFullGCsBeforeCompaction 在多少次GC后进行内存压缩,这个是因为并行收集器不对内存空间进行压缩的,所以运行一段时间后会产生很多碎片,使得运行效率降低。 - -XX:+CMSParallelRemarkEnabled 降低标记停顿 - -XX:+UseCMSCompactAtFullCollection 在每一次Full GC时对老年代区域碎片整理,因为CMS是不会移动内存的,因此会非常容易出现碎片导致内存不够用的 - -XX:+UseCmsInitiatingOccupancyOnly 使用手动触发或者自定义触发cms 收集,同时也会禁止hostspot 自行触发CMS GC - -XX:CMSInitiatingOccupancyFraction 使用CMS作为垃圾回收,使用70%后开始CMS收集 - -XX:CMSInitiatingPermOccupancyFraction 设置perm gen使用达到多少%比时触发垃圾回收,默认是92% - -XX:+CMSIncrementalMode 设置为增量模式 - -XX:+CmsClassUnloadingEnabled CMS是不会默认对永久代进行垃圾回收的,设置此参数则是开启 - -XX:+PrintGCDetails 开启详细GC日志模式,日志的格式是和所使用的算法有关 - -XX:+PrintGCDateStamps 将时间和日期也加入到GC日志中 ## 你平时工作用过的JVM常用基本配置参数有哪些 `-Xms` `-Xmx` `-Xmn` ```shell -Xms128m -Xmx4096m -Xss1024K -XX:MetaspaceSize=512m -XX:+PrintCommandLineFlags -XX:+PrintGCDetails -XX:+UseSerialGC ``` - -Xms:初始大小内存,默认为物理内存1/64,等价于-XX:InitialHeapSize - -Xmx:最大分配内存,默认物理内存1/4,等价于-XX:MaxHeapSize - -Xss:设置单个线程栈的大小,默认542K~1024K ,等价于-XX:ThreadStackSize - -Xmn:设置年轻代的大小 - -XX:MetaspaceSize:设置元空间大小 - -XX:+PrintGCDetails:输出详细GC收集日志信息,如[名称:GC前内存占用->GC后内存占用(该区内存总大小)] - -XX:SurvivorRatio:设置新生代中Eden和S0/S1空间的比例,默认-XX:SurvivorRatio=8,Eden:S0:S1=8:1:1 - -XX:NewRatio:设置年轻代与老年代在堆结构的占比,如:默认-XX:NewRatio=2 新生代在1,老年代2,年轻代占整个堆的1/3,NewRatio值几句诗设置老年代的占比,剩下的1给新生代 - -XX:MaxTenuringThreshold:设置垃圾的最大年龄,默认-XX:MaxTenuringThreshold=15 - -XX:+UseSerialGC:串行垃圾回收器 - -XX:+UseParallelGC:并行垃圾回收器<file_sep>package normal; import java.util.HashMap; /** * @program JavaBooks * @description: 13. 罗马数字转整数 * @author: mf * @create: 2019/11/10 15:18 */ /* 题目:https://leetcode-cn.com/problems/roman-to-integer/ 难度:easy */ /* 输入: "IV" 输出: 4 输入: "IX" 输出: 9 输入: "MCMXCIV" 输出: 1994 解释: M = 1000, CM = 900, XC = 90, IV = 4. */ public class RomanToInt { public static void main(String[] args) { String s = "MCMXCIV"; System.out.println(romanToInt(s)); } public static int romanToInt(String s) { HashMap<Character, Integer> map = new HashMap<>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int ans = 0, lastValue = 0; for (int i = s.length() - 1; i >= 0; i--) { int value = map.get(s.charAt(i)); if (value < lastValue) { ans -= value; } else { ans += value; } lastValue = value; } return ans; } } <file_sep>package books; /** * @program JavaBooks * @description: 构建乘积数组 * @author: mf * @create: 2019/10/09 20:09 */ import java.util.Arrays; /** * 给定一个数组A[0,1,...,n-1], * 请构建一个数组B[0,1,...,n-1], * 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。 * 不能使用除法。 */ public class T66 { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int[] res = multiply(arr); System.out.println(Arrays.toString(res)); } private static int[] multiply(int[] arr) { int length = arr.length; int[] temp = new int[length]; if (length != 0) { temp[0] = 1; // 计算下三角 for (int i = 1; i < length; i++) { temp[i] = temp[i - 1] * arr[i - 1]; } int t = 1; // 计算上三角 for (int i = length - 2; i >= 0; i--) { t *= arr[i + 1]; temp[i] *= t; } } return temp; } } <file_sep>## 引言 > Redis在大型项目中也是经常用到的非关系型数据库,面试官也挺喜欢问的。 <!-- more --> ## 常见问题 ### redis是什么玩意? 简单来说redis就是一个数据库,不过与传统数据库不同的是redis的数据库是存在内存中,所以读写速度非常快,因此redis被广泛应用于缓存方向。另外,redis也经常用来做分布式锁,redis提供了多种数据类型来支持不同的业务场景。除此之外,redis 支持事务 、持久化、LUA脚本、LRU驱动事件、多种集群方案。 ### 为什么要用redis/为什么要用缓存? 1. **高性能**:假如用户第一次访问数据库中的某些数据。这个过程会比较慢,因为是从硬盘上读取的。将该用户访问的数据存在缓存中,这样下一次再访问这些数据的时候就可以直接从缓存中获取了。操作缓存就是直接操作内存,所以速度相当快。如果数据库中的对应数据改变的之后,同步改变缓存中相应的数据即可! 2. **高并发**:直接操作缓存能够承受的请求是远远大于直接访问数据库的,所以我们可以考虑把数据库中的部分数据转移到缓存中去,这样用户的一部分请求会直接到缓存这里而不用经过数据库。 ### 使用Redis有哪些好处? 1. 速度快,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1) 2. 支持丰富数据类型,支持string,list,set,sorted set,hash 3. 支持事务,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行 4. 丰富的特性:可用于缓存,消息,按key设置过期时间,过期后将会自动删除 5. 等等... ### 为什么要用 redis 而不用 map/guava 做缓存? 缓存分为本地缓存和分布式缓存。以 Java 为例,使用自带的 map 或者 guava 实现的是本地缓存,最主要的特点是 轻量以及快速,生命周期随着 jvm 的销毁而结束,并且在多实例的情况下,每个实例都需要各自保存一份缓存,缓 存不具有一致性。 使用 redis 或 memcached 之类的称为分布式缓存,在多实例的情况下,各实例共用一份缓存数据,缓存具有一致 性。缺点是需要保持 redis 或 memcached服务的高可用,整个程序架构上较为复杂。 ### redis相比memcached有哪些优势? 1. memcached所有的值均是简单的字符串,redis作为其替代者,支持更为丰富的数据类型 2. redis的速度比memcached快很多 3. redis可以持久化其数据 ### redis的线程模型? redis 内部使用文件事件处理器 `file event handler`,这个文件事件处理器是单线程的,所以 redis 才叫做单线程的模型。它采用 IO 多路复用机制同时监听多个 socket,根据 socket 上的事件来选择对应的事件处理器进行处理。 文件事件处理器的结构包含 4 个部分: - 多个 socket - IO多路复用程序 - 文件事件分派器 - 事件处理器(连接应答处理器、命令请求处理器、命令回复处理器) 多个 socket 可能会并发产生不同的操作,每个操作对应不同的文件事件,但是 IO 多路复用程序会监听多个 socket,会将 socket 产生的事件放入队列中排队,事件分派器每次从队列中取出一个事件,把该事件交给对应的事件处理器进行处理。 ### redis常见性能问题和解决方案 1. Master最好不要做任何持久化工作,如RDB内存快照和AOF日志文件 2. 如果数据比较重要,某个Slave开启AOF备份数据,策略设置为每秒同步一次 3. 为了主从复制的速度和连接的稳定性,Master和Slave最好在同一个局域网内 4. 尽量避免在压力很大的主库上增加从库 5. 主从复制不要用图状结构,用单向链表结构更为稳定,即:Master <- Slave1 <- Slave2 <- Slave3... ### redis 常见数据结构以及使用场景分析 #### String > 常用命令: set,get,decr,incr,mget 等。 String数据结构是简单的key-value类型,value其实不仅可以是String,也可以是数字。 常规key-value缓存应用; 常规计数:微博数,粉丝数等。 #### Hash > 常用命令: hget,hset,hgetall 等。 Hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象,后续操作的时候,你可以直接仅 仅修改这个对象中的某个字段的值。 比如我们可以Hash数据结构来存储用户信息,商品信息等等。比如下面我就用 hash 类型存放了我本人的一些信息: ```json key=JavaUser293847 value={ “id”: 1, “name”: “SnailClimb”, “age”: 22, “location”: “Wuhan, Hubei” } ``` #### List > 常用命令: lpush,rpush,lpop,rpop,lrange等 list 就是链表,Redis list 的应用场景非常多,也是Redis最重要的数据结构之一,比如微博的关注列表,粉丝列表, 消息列表等功能都可以用Redis的 list 结构来实现。 Redis list 的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销。 另外可以通过 lrange 命令,就是从某个元素开始读取多少个元素,可以基于 list 实现分页查询,这个很棒的一个功 能,基于 redis 实现简单的高性能分页,可以做类似微博那种下拉不断分页的东西(一页一页的往下走),性能高。 #### Set > 常用命令: sadd,spop,smembers,sunion 等 set 对外提供的功能与list类似是一个列表的功能,特殊之处在于 set 是可以自动排重的。 当你需要存储一个列表数据,又不希望出现重复数据时,set是一个很好的选择,并且set提供了判断某个成员是否在 一个set集合内的重要接口,这个也是list所不能提供的。可以基于 set 轻易实现交集、并集、差集的操作。 比如:在微博应用中,可以将一个用户所有的关注人存在一个集合中,将其所有粉丝存在一个集合。Redis可以非常 方便的实现如共同关注、共同粉丝、共同喜好等功能。这个过程也就是求交集的过程,具体命令如下:`sinterstore key1 key2 key3`将交集存在key1内 #### Sorted Set > 常用命令: zadd,zrange,zrem,zcard等 和set相比,sorted set增加了一个权重参数score,使得集合中的元素能够按score进行有序排列。 举例: 在直播系统中,实时排行信息包含直播间在线用户列表,各种礼物排行榜,弹幕消息(可以理解为按消息维 度的消息排行榜)等信息,适合使用 Redis 中的 SortedSet 结构进行存储。 ### redis 设置过期时间 Redis中有个设置时间过期的功能,即对存储在 redis 数据库中的值可以设置一个过期时间。作为一个缓存数据库, 这是非常实用的。如我们一般项目中的 token 或者一些登录信息,尤其是短信验证码都是有时间限制的,按照传统 的数据库处理方式,一般都是自己判断过期,这样无疑会严重影响项目性能。 我们 set key 的时候,都可以给一个 expire time,就是过期时间,通过过期时间我们可以指定这个 key 可以存活的 时间。 **定期删除+惰性删除。** - 定期删除:redis默认是每隔 100ms 就随机抽取一些设置了过期时间的key,检查其是否过期,如果过期就删 除。注意这里是随机抽取的。为什么要随机呢?你想一想假如 redis 存了几十万个 key ,每隔100ms就遍历所 有的设置过期时间的 key 的话,就会给 CPU 带来很大的负载! - 惰性删除 :定期删除可能会导致很多过期 key 到了时间并没有被删除掉。所以就有了惰性删除。假如你的过期 key,靠定期删除没有被删除掉,还停留在内存里,除非你的系统去查一下那个 key,才会被redis给删除掉。这 就是所谓的惰性删除,也是够懒的哈! 如果定期删除漏掉了很多过期 key,然后你也没及时去查, 也就没走惰性删除,此时会怎么样?如果大量过期key堆积在内存里,导致redis内存块耗尽了。怎么解决这个问题 呢? **redis 内存淘汰机制。** ### MySQL里有2000w数据,redis中只存20w的数据,如何保证redis中的数据都是热点数据 redis 内存数据集大小上升到一定大小的时候,就会施行数据淘汰策略。redis 提供 6种数据淘汰策略: - voltile-lru:从已设置过期时间的数据集(server.db[i].expires)中挑选最近最少使用的数据淘汰 - volatile-ttl:从已设置过期时间的数据集(server.db[i].expires)中挑选将要过期的数据淘汰 - volatile-random:从已设置过期时间的数据集(server.db[i].expires)中任意选择数据淘汰 - allkeys-lru:从数据集(server.db[i].dict)中挑选最近最少使用的数据淘汰 - allkeys-random:从数据集(server.db[i].dict)中任意选择数据淘汰 - no-enviction(驱逐):禁止驱逐数据 ### Memcache与Redis的区别都有哪些? 1. 存储方式 1. Memecache把数据全部存在内存之中,断电后会挂掉,数据不能超过内存大小。 2. Redis有部份存在硬盘上,这样能保证数据的持久性。 2. 数据支持类型 1. Memcache对数据类型支持相对简单。String 2. Redis有复杂的数据类型。Redis不仅仅支持简单的k/v类型的数据,同时还提供 list,set,zset,hash等数据结构的存储。 3. 使用底层模型不同 1. 它们之间底层实现方式 以及与客户端之间通信的应用协议不一样。 2. Redis直接自己构建了VM 机制 ,因为一般的系统调用系统函数的话,会浪费一定的时间去移动和请求。 4. 集群模式 memcached没有原生的集群模式,需要依靠客户端来实现往集群中分片写入数据;但是 redis 目前 是原生支持 cluster 模式的. 5. Memcached是多线程,非阻塞IO复用的网络模型;Redis使用单线程的多路 IO 复用模型。 ### redis 持久化机制(怎么保证 redis 挂掉之后再重启数据可以 进行恢复) 很多时候我们需要持久化数据也就是将内存中的数据写入到硬盘里面,大部分原因是为了之后重用数据(比如重启机 器、机器故障之后回复数据),或者是为了防止系统故障而将数据备份到一个远程位置。 Redis不同于Memcached的很重一点就是,**Redis支持持久化**,而且支持两种不同的持久化操作。Redis的一种持久化方式叫**快照(snapshotting,RDB)**,另一种方式是**只追加文件(append-only file,AOF)**.这两种方法各有千 秋,下面我会详细这两种持久化方法是什么,怎么用,如何选择适合自己的持久化方法。 **快照(snapshotting)持久化(RDB)** Redis可以通过创建快照来获得存储在内存里面的数据在某个时间点上的副本。Redis创建快照之后,可以对快照进行 备份,可以将快照复制到其他服务器从而创建具有相同数据的服务器副本(Redis主从结构,主要用来提高Redis性 能),还可以将快照留在原地以便重启服务器的时候使用。 快照持久化是Redis默认采用的持久化方式,在redis.conf配置文件中默认有此下配置: ```yaml save 900 1 #在900秒(15分钟)之后,如果至少有1个key发生变化,Redis就会自动触发BGSAVE命令 创建快照。 save 300 10 #在300秒(5分钟)之后,如果至少有10个key发生变化,Redis就会自动触发BGSAVE命令创建快照。 save 60 10000 #在60秒(1分钟)之后,如果至少有10000个key发生变化,Redis就会自动触发BGSAVE命令创建快照。 ``` **AOF(append-only file)持久化** 与快照持久化相比,AOF持久化 的实时性更好,因此已成为主流的持久化方案。默认情况下Redis没有开启 AOF(append only file)方式的持久化,可以通过appendonly参数开启:`appendonly yes` 开启AOF持久化后每执行一条会更改Redis中的数据的命令,Redis就会将该命令写入硬盘中的AOF文件。AOF文件的 保存位置和RDB文件的位置相同,都是通过dir参数设置的,默认的文件名是appendonly.aof。 在Redis的配置文件中存在三种不同的 AOF 持久化方式,它们分别是: ```yaml appendfsync always #每次有数据修改发生时都会写入AOF文件,这样会严重降低Redis的速度 appendfsync everysec #每秒钟同步一次,显示地将多个写命令同步到硬盘 appendfsync no #让操作系统决定何时进行同步 ``` 为了兼顾数据和写入性能,用户可以考虑 appendfsync everysec选项 ,让Redis每秒同步一次AOF文件,Redis性能 几乎没受到任何影响。而且这样即使出现系统崩溃,用户最多只会丢失一秒之内产生的数据。当硬盘忙于执行写入操 作的时候,Redis还会优雅的放慢自己的速度以便适应硬盘的最大写入速度。 **Redis 4.0 对于持久化机制的优化** Redis 4.0 开始支持 RDB 和 AOF 的混合持久化(默认关闭,可以通过配置项 aof-use-rdb-preamble 开启)。 如果把混合持久化打开,AOF 重写的时候就直接把 RDB 的内容写到 AOF 文件开头。这样做的好处是可以结合 RDB 和 AOF 的优点, 快速加载同时避免丢失过多的数据。当然缺点也是有的, AOF 里面的 RDB 部分是压缩格式不再是 AOF 格式,可读性较差。 ### **AOF 重写** AOF重写可以产生一个新的AOF文件,这个新的AOF文件和原有的AOF文件所保存的数据库状态一样,但体积更小。 AOF重写是一个有歧义的名字,该功能是通过读取数据库中的键值对来实现的,程序无须对现有AOF文件进行任伺读 入、分析或者写入操作。 在执行 BGREWRITEAOF 命令时,Redis 服务器会维护一个 AOF 重写缓冲区,该缓冲区会在子进程创建新AOF文件期 间,记录服务器执行的所有写命令。当子进程完成创建新AOF文件的工作之后,服务器会将重写缓冲区中的所有内容 追加到新AOF文件的末尾,使得新旧两个AOF文件所保存的数据库状态一致。最后,服务器用新的AOF文件替换旧的 AOF文件,以此来完成AOF文件重写操作 ### Redis 事务 Redis 通过 MULTI、EXEC、WATCH 等命令来实现事务(transaction)功能。事务提供了一种将多个命令请求打包,然 后一次性、按顺序地执行多个命令的机制,并且在事务执行期间,服务器不会中断事务而改去执行其他客户端的命令 请求,它会将事务中的所有命令都执行完毕,然后才去处理其他客户端的命令请求。 在传统的关系式数据库中,常常用 ACID 性质来检验事务功能的可靠性和安全性。在 Redis 中,事务总是具有原子性 (Atomicity)、一致性(Consistency)和隔离性(Isolation),并且当 Redis 运行在某种特定的持久化模式下时,事务 也具有持久性(Durability)。 ### Redis 常见的性能问题都有哪些?如何解决? 1. Master写内存快照,save命令调度rdbSave函数,会阻塞主线程的工作,当快照比较大时对性能影响是非常大的,会间断性暂停服务,所以Master最好不要写内存快照。 2. Master AOF持久化,如果不重写AOF文件,这个持久化方式对性能的影响是最小的,但是AOF文件会不断增大,AOF文件过大会影响Master重启的恢复速度。Master最好不要做任何持久化工作,包括内存快照和AOF日志文件,特别是不要启用内存快照做持久化,如果数据比较关键,某个Slave开启AOF备份数据,策略为每秒同步一次。 3. Master调用BGREWRITEAOF重写AOF文件,AOF在重写的时候会占大量的CPU和内存资源,导致服务load过高,出现短暂服务暂停现象。 4. Redis主从复制的性能问题,为了主从复制的速度和连接的稳定性,Slave和Master最好在同一个局域网内 ### Redis的同步机制了解么? 主从同步。第一次同步时,主节点做一次bgsave,并同时将后续修改操作记录到内存buffer,待完成后将rdb文件全量同步到复制节点,复制节点接受完成后将rdb镜像加载到内存。加载完成后,再通知主节点将期间修改的操作记录同步到复制节点进行重放就完成了同步过程。 ### 是否使用过Redis集群,集群的原理是什么? Redis Sentinel着眼于高可用,在master宕机时会自动将slave提升为master,继续提供服务。 Redis Cluster着眼于扩展性,在单个redis内存不足时,使用Cluster进行分片存储。 ### 缓存雪崩和缓存穿透问题解决方案 #### 缓存雪崩 缓存同一时间大面积的失效,所以,后面的请求都会落到数据库上,造成数据库短时间内承受大量请求而崩 掉。 - 事前:尽量保证整个 redis 集群的高可用性,发现机器宕机尽快补上。选择合适的内存淘汰策略。 - 事中:本地ehcache缓存 + hystrix限流&降级,避免MySQL崩掉 - 事后:利用 redis 持久化机制保存的数据尽快恢复缓存 #### 缓存穿透 一般是黑客故意去请求缓存中不存在的数据,导致所有的请求都落到数据库上,造成数据库短时间内承受大量 请求而崩掉。 解决办法: 有很多种方法可以有效地解决缓存穿透问题,最常见的则是采用布隆过滤器,将所有可能存在的数据哈 希到一个足够大的bitmap中,一个一定不存在的数据会被 这个bitmap拦截掉,从而避免了对底层存储系统的查询压 力。另外也有一个更为简单粗暴的方法(我们采用的就是这种),如果一个查询返回的数据为空(不管是数 据不存 在,还是系统故障),我们仍然把这个空结果进行缓存,但它的过期时间会很短,最长不超过五分钟。 ### 如何解决 Redis 的并发竞争 Key 问题 所谓 Redis 的并发竞争 Key 的问题也就是多个系统同时对一个 key 进行操作,但是最后执行的顺序和我们期望的顺 序不同,这样也就导致了结果的不同! 推荐一种方案:分布式锁(zookeeper 和 redis 都可以实现分布式锁)。(如果不存在 Redis 的并发竞争 Key 问 题,不要使用分布式锁,这样会影响性能) 基于zookeeper临时有序节点可以实现的分布式锁。大致思想为:每个客户端对某个方法加锁时,在zookeeper上的 与该方法对应的指定节点的目录下,生成一个唯一的瞬时有序节点。 判断是否获取锁的方式很简单,只需要判断有 序节点中序号最小的一个。 当释放锁的时候,只需将这个瞬时节点删除即可。同时,其可以避免服务宕机导致的锁 无法释放,而产生的死锁问题。完成业务流程后,删除对应的子节点释放锁。 在实践中,当然是从以可靠性为主。所以首推Zookeeper。 ### 如何保证缓存与数据库双写时的数据一致性? 你只要用缓存,就可能会涉及到缓存与数据库双存储双写,你只要是双写,就一定会有数据一致性的问题,那么你如 何解决一致性问题? 一般来说,就是如果你的系统不是严格要求缓存+数据库必须一致性的话,缓存可以稍微的跟数据库偶尔有不一致的 情况,最好不要做这个方案,读请求和写请求串行化,串到一个内存队列里去,这样就可以保证一定不会出现不一致 的情况 串行化之后,就会导致系统的吞吐量会大幅度的降低,用比正常情况下多几倍的机器去支撑线上的一个请求。<file_sep>## 美团小象二面实习面经 - [原文链接](https://www.nowcoder.com/discuss/411053) ### 最小生成树prim和kruskal算法 > 最小生成树是一副连通加权无向图中一棵权值最小的生成树。 #### Prim算法原理: >1)以某一个点开始,寻找当前该点可以访问的所有的边; >2)在已经寻找的边中发现最小边,这个边必须有一个点还没有访问过,将还没有访问的点加入我们的集合,记录添加的边; >3)寻找当前集合可以访问的所有边,重复2的过程,直到没有新的点可以加入; >4)此时由所有边构成的树即为最小生成树。 #### Kruskal算法原理: >现在我们假设一个图有m个节点,n条边。 >首先,我们需要把m个节点看成m个独立的生成树,并且把n条边按照从小到大的数据进行排列。 >在n条边中,我们依次取出其中的每一条边,如果发现边的两个节点分别位于两棵树上,那么把两棵树合并成为一颗树; >如果树的两个节点位于同一棵树上,那么忽略这条边,继续运行。 >等到所有的边都遍历结束之后,如果所有的生成树可以合并成一条生成树,那么它就是我们需要寻找的最小生成树,反之则没有最小生成树。 #### 总结 总的来说,Prim算法是以点为对象,挑选与点相连的最短边来构成最小生成树。 而Kruskal算法是以边为对象,不断地加入新的不构成环路的最短边来构成最小生成树。 ### Hash冲突哪几种解决方式 - 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列) - 再哈希法 - 链地址法(Java hashmap就是这么做的) - 建立一个公共溢出区 #### 拉链法的优点 - 拉链法处理冲突简单,且无堆积现象,即非同义词决不会发生冲突,因此平均查找长度较短; - 由于拉链法中各链表上的结点空间是动态申请的,故它更适合于造表前无法确定表长的情况; - 开放定址法为减少冲突,要求装填因子α较小,故当结点规模较大时会浪费很多空间。而拉链法中可取α≥1,且结点较大时,拉链法中增加的指针域可忽略不计,因此节省空间; - 在用拉链法构造的散列表中,删除结点的操作易于实现。 #### 拉链法的缺点 指针需要额外的空间,故当结点规模较小时,开放定址法较为节省空间,而若将节省的指针空间用来扩大散列表的规模,可使装填因子变小,这又减少了开放定址法中的冲突,从而提高平均查找速度。 ### HashSet怎么实现 > 对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了,那么学习 HashSet 也是很轻松的。 对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层使用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,相关 HashSet 的操作,基本上都是直接调用底层 HashMap 的相关方法来完成,我们应该为保存到 HashSet 中的对象覆盖 hashCode() 和 equals() > 主要是add方法 ```java /** * @param e 将添加到此set中的元素。 * @return 如果此set尚未包含指定元素,则返回true。 */ public boolean add(E e) { return map.put(e, PRESENT)==null; } ``` > 由于HashMap的put()方法添加 key-value 对时, > 当新放入HashMap的Entry中key 与集合中原有 Entry 的 key 相同(hashCode()返回值相等, > 通过 equals 比较也返回 true),新添加的 Entry 的 value 会将覆盖原来 Entry 的 value(HashSet 中的 value 都是PRESENT), > 但 key 不会有任何改变,因此如果向 HashSet 中添加一个已经存在的元素时,新添加的集合元素将不会被放入 HashMap中, > 原来的元素也不会有任何改变,这也就满足了 Set 中元素不重复的特性。 ### MySQL数据库有哪几种索引 #### 索引类型 - FULLTEXT 即为全文索引,目前只有MyISAM引擎支持。其可以在CREATE TABLE ,ALTER TABLE ,CREATE INDEX 使用,不过目前只有 CHAR、VARCHAR ,TEXT 列上可以创建全文索引。 - HASH 由于HASH的唯一(几乎100%的唯一)及类似键值对的形式,很适合作为索引。 HASH索引可以一次定位,不需要像树形索引那样逐层查找,因此具有极高的效率。但是,这种高效是有条件的,即只在“=”和“in”条件下高效,对于范围查询、排序及组合索引仍然效率不高。 - BTREE BTREE索引就是一种将索引值按一定的算法,存入一个树形的数据结构中(二叉树),每次查询都是从树的入口root开始,依次遍历node,获取leaf。这是MySQL里默认和最常用的索引类型。 - RTREE RTREE在MySQL很少使用,仅支持geometry数据类型,支持该类型的存储引擎只有MyISAM、BDb、InnoDb、NDb、Archive几种。 相对于BTREE,RTREE的优势在于范围查找。 #### 索引种类 - 普通索引:仅加速查询 - 唯一索引:加速查询 + 列值唯一(可以有null) - 主键索引:加速查询 + 列值唯一(不可以有null)+ 表中只有一个 - 组合索引:多列值组成一个索引,专门用于组合搜索,其效率大于索引合并 - 全文索引:对文本的内容进行分词,进行搜索 - 索引合并:使用多个单列索引组合搜索 - 覆盖索引:select的数据列只用从索引中就能够取得,不必读取数据行,换句话说查询列要被所建的索引覆盖 ### 三次握手和四次挥手 - [动画:用动画给面试官解释 TCP 三次握手过程](https://blog.csdn.net/qq_36903042/article/details/102513465) - [动画:用动画给女朋友讲解 TCP 四次分手过程](https://blog.csdn.net/qq_36903042/article/details/102656641) ### Linux查看当前文件路径命令 - `pwd` ### 找出数组中的两个出现次数是奇数的数字(其他都是偶数)(剑指offer) ```java public class SingleNumbers { public int[] singleNumbers(int[] nums) { int xorNumber = nums[0]; for (int i = 1; i < nums.length; i++) { xorNumber ^= nums[i]; } int onePosition = xorNumber & (-xorNumber); int ans1 = 0, ans2 = 0; for (int i = 0; i < nums.length; i++) { if ((nums[i] & onePosition) == onePosition) { ans1 ^= nums[i]; } else { ans2 ^= nums[i]; } } return new int[] {ans1^0, ans2^0}; } } ``` ### 无重复最长子串(HashMap) ```java public class LongestSubstring { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; HashMap<Character, Integer> map = new HashMap<>(); // abcabc for (int i = 0, j = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } } ```<file_sep>package web; /** * @program LeetNiu * @description: 机器人的运动范围 * @author: mf * @create: 2020/01/17 23:46 */ public class T66 { public int movingCount(int threshold, int rows, int cols) { boolean[][] visited = new boolean[rows][cols]; return countingStep(threshold,rows,cols,0,0,visited); } public int countingStep(int limit, int rows, int cols, int r, int c, boolean[][] visited) { if (r < 0 || r >= rows || c < 0 || c >= cols || visited[r][c] || bitSum(r) + bitSum(c) > limit) { return 0; } visited[r][c] = true; return countingStep(limit,rows,cols,r - 1,c,visited) + countingStep(limit,rows,cols,r,c - 1,visited)+countingStep(limit,rows,cols,r+1,c,visited)+countingStep(limit,rows,cols,r,c+1,visited) + 1; } public int bitSum(int t) { int count = 0; while (t != 0) { count += t % 10; t /= 10; } return count; } } <file_sep>package com.basic; import java.util.concurrent.TimeUnit; /** * @program JavaBooks * @description: volatile关键字 * @author: mf * @create: 2019/12/28 22:54 */ public class T6 { /*volatile*/ boolean running = true; // 对比一下有无valotile的情况下,整个程序运行结果的区别 void m() { System.out.println("m start"); while (running) { // 啥都没得 // try { // TimeUnit.SECONDS.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } System.out.println("m end ..."); } public static void main(String[] args) { T6 t6 = new T6(); new Thread(() -> t6.m(), "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } t6.running = false; } } <file_sep>package books; import java.util.ArrayList; import java.util.Stack; /** * @program JavaBooks * @description: 从尾到头打印链表 * @author: mf * @create: 2019/08/19 13:19 */ /* 输入一个链表的头节点,从尾到头反过来打印出每个节点的值。 链表定义如ListNote */ public class T6 { ArrayList<Integer> arrayList = new ArrayList<>(); public static void main(String[] args) { // 递归方法中的arraylist ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); listNode1.next = listNode2; listNode2.next = listNode3; // 栈方法 ArrayList<Integer> list = printListFromTailToHead1(listNode1); list.forEach(System.out::println); // 递归方法 } /** * 栈方法 * @param listNote * @return */ public static ArrayList<Integer> printListFromTailToHead1(ListNode listNote) { Stack<Integer> stack = new Stack<>(); // 压栈 while (listNote != null) { stack.push(listNote.value); listNote = listNote.next; } // 弹栈 ArrayList<Integer> arrayList = new ArrayList<>(); while (!stack.isEmpty()) { arrayList.add(stack.pop()); } return arrayList; } /** * 递归方法 * @param listNote * @return */ public ArrayList<Integer> printListFromTailToHead2(ListNode listNote) { if (listNote != null) { this.printListFromTailToHead2(listNote.next); // 层层递归到最后链表最后一位,从最后一位add arrayList.add(listNote.value); } return arrayList; } } class TestMethod2 { public static void main(String[] args) { ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); listNode1.next = listNode2; listNode2.next = listNode3; T6 t6 = new T6(); ArrayList<Integer> list = t6.printListFromTailToHead2(listNode1); list.forEach(System.out::println); } }<file_sep>/** * @program JavaBooks * @description: 同构字符串 * @author: mf * @create: 2020/04/10 19:59 */ package subject.hash; import java.util.HashMap; /** * 输入: s = "egg", t = "add" * 输出: true * 输入: s = "foo", t = "bar" * 输出: false * 输入: s = "paper", t = "title" * 输出: true */ public class T0 { public boolean isIsomorphic(String s, String t) { return isomerphic(s, t) && isomerphic(t, s); } private boolean isomerphic(String s, String t) { int n = s.length(); HashMap<Character, Character> map = new HashMap<>(); for (int i = 0; i < n; i++) { Character c1 = s.charAt(i); Character c2 = t.charAt(i); if (map.containsKey(c1)) { if (map.get(c1) != c2) { return false; } } else { map.put(c1, c2); } } return true; } } <file_sep>package web; /** * @program LeetNiu * @description: 扑克牌顺序 * @author: mf * @create: 2020/01/15 13:19 */ import java.util.Arrays; /** * LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)... * 他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!! * “红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。 * 上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 * 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。 * 为了方便起见,你可以认为大小王是0。 */ public class T45 { public boolean isContinuous(int [] numbers) { int numOfZero = 0; int numOfInterval = 0; int length = numbers.length; if (length == 0) return false; Arrays.sort(numbers); for (int i = 0; i < length - 1; i++) { // 计算癞子数量 if (numbers[i] == 0) { numOfZero++; continue; } // 对子直接返回 if (numbers[i] == numbers[i + 1]) return false; numOfInterval += numbers[i + 1] - numbers[i] - 1; } if (numOfZero >= numOfInterval) return true; return false; } } <file_sep>--- title: 个人吐血系列-总结Spring date: 2020-03-29 15:45:57 tags: spring categories: java-interview --- > 个人感觉,Spring这一块,不仅会用,还得知道底层的源码或者是说初始化加载等过程吧,这篇就不介绍如何配置以及各个注解的使用,在这里不是重点。 ## 大纲图 ![Spring常见问题](http://media.dreamcat.ink/uPic/Spring常见问题.png) ### 什么是Spring框架 我们一般说 Spring 框架指的都是 Spring Framework,它是很多模块的集合,使用这些模块可以很方便地协助我们进行开发。这些模块是:核心容器、数据访问/集成,、Web、AOP(面向切面编程)、工具、消息和测试模块。比如:Core Container 中的 Core 组件是Spring 所有组件的核心,Beans 组件和 Context 组件是实现IOC和依赖注入的基础,AOP组件用来实现面向切面编程。 Spring 官网列出的 Spring 的 6 个特征: - **核心技术** :依赖注入(DI),AOP,事件(events),资源,i18n,验证,数据绑定,类型转换,SpEL。 - **测试** :模拟对象,TestContext框架,Spring MVC 测试,WebTestClient。 - **数据访问** :事务,DAO支持,JDBC,ORM,编组XML。 - **Web支持** : Spring MVC和Spring WebFlux Web框架。 - **集成** :远程处理,JMS,JCA,JMX,电子邮件,任务,调度,缓存。 - **语言** :Kotlin,Groovy,动态语言。 ### 列举一些重要的Spring模块 - **Spring Core:** 基础,可以说 Spring 其他所有的功能都需要依赖于该类库。主要提供 IoC 依赖注入功能。 - **Spring Aspects** : 该模块为与AspectJ的集成提供支持。 - **Spring AOP** :提供了面向切面的编程实现。 - **Spring JDBC** : Java数据库连接。 - **Spring JMS** :Java消息服务。 - **Spring ORM** : 用于支持Hibernate等ORM工具。 - **Spring Web** : 为创建Web应用程序提供支持。 - **Spring Test** : 提供了对 JUnit 和 TestNG 测试的支持。 ### @RestController VS Controller #### Controller **`Controller` 返回一个页面** 单独使用 `@Controller` 不加 `@ResponseBody`的话一般使用在要返回一个视图的情况,这种情况属于比较传统的Spring MVC 的应用,对应于前后端不分离的情况。 #### RestController **`@RestController` 返回JSON 或 XML 形式数据** 但`@RestController`只返回对象,对象数据直接以 JSON 或 XML 形式写入 HTTP 响应(Response)中,这种情况属于 RESTful Web服务,这也是目前日常开发所接触的最常用的情况(前后端分离)。 **`@Controller +@ResponseBody` 返回JSON 或 XML 形式数据** 如果你需要在Spring4之前开发 RESTful Web服务的话,你需要使用`@Controller` 并结合`@ResponseBody`注解,也就是说`@Controller` +`@ResponseBody`= `@RestController`(Spring 4 之后新加的注解)。 ### 谈谈SpringIOC和AOP #### IOC IoC(Inverse of Control:控制反转)是一种**设计思想**,就是 **将原本在程序中手动创建对象的控制权,交由Spring框架来管理。** IoC 在其他语言中也有应用,并非 Spring 特有。 **IoC 容器是 Spring 用来实现 IoC 的载体, IoC 容器实际上就是个Map(key,value),Map 中存放的是各种对象。** 将对象之间的相互依赖关系交给 IoC 容器来管理,并由 IoC 容器完成对象的注入。这样可以很大程度上简化应用的开发,把应用从复杂的依赖关系中解放出来。 **IoC 容器就像是一个工厂一样,当我们需要创建一个对象的时候,只需要配置好配置文件/注解即可,完全不用考虑对象是如何被创建出来的。** 在实际项目中一个 Service 类可能有几百甚至上千个类作为它的底层,假如我们需要实例化这个 Service,你可能要每次都要搞清这个 Service 所有底层类的构造函数,这可能会把人逼疯。如果利用 IoC 的话,你只需要配置好,然后在需要的地方引用就行了,这大大增加了项目的可维护性且降低了开发难度。 Spring 时代我们一般通过 XML 文件来配置 Bean,后来开发人员觉得 XML 文件来配置不太好,于是 SpringBoot 注解配置就慢慢开始流行起来。 推荐阅读:https://www.zhihu.com/question/23277575/answer/169698662 ##### ioc容器初始化流程 **可以看到有很多PostProcessors的后置处理器** ```java @Override public void refresh() throws BeansException, IllegalStateException { // 来个锁,不然 refresh() 还没结束,你又来个启动或销毁容器的操作,那不就乱套了嘛 synchronized (this.startupShutdownMonitor) { // 准备工作,记录下容器的启动时间、标记“已启动”状态、处理配置文件中的占位符 prepareRefresh(); // 这步比较关键,这步完成后,配置文件就会解析成一个个 Bean 定义,注册到 BeanFactory 中, // 当然,这里说的 Bean 还没有初始化,只是配置信息都提取出来了, // 注册也只是将这些信息都保存到了注册中心(说到底核心是一个 beanName-> beanDefinition 的 map) ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean // 这块待会会展开说 prepareBeanFactory(beanFactory); try { // 【这里需要知道 BeanFactoryPostProcessor 这个知识点,Bean 如果实现了此接口, // 那么在容器初始化以后,Spring 会负责调用里面的 postProcessBeanFactory 方法。】 // 这里是提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化 // 具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事 postProcessBeanFactory(beanFactory); // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法 invokeBeanFactoryPostProcessors(beanFactory); // 注册 BeanPostProcessor 的实现类,注意看和 BeanFactoryPostProcessor 的区别 // 此接口两个方法: postProcessBeforeInitialization 和 postProcessAfterInitialization // 两个方法分别在 Bean 初始化之前和初始化之后得到执行。注意,到这里 Bean 还没初始化 registerBeanPostProcessors(beanFactory); // 初始化当前 ApplicationContext 的 MessageSource,国际化这里就不展开说了,不然没完没了了 initMessageSource(); // 初始化当前 ApplicationContext 的事件广播器,这里也不展开了 initApplicationEventMulticaster(); // 从方法名就可以知道,典型的模板方法(钩子方法), // 具体的子类可以在这里初始化一些特殊的 Bean(在初始化 singleton beans 之前) onRefresh(); // 注册事件监听器,监听器需要实现 ApplicationListener 接口。这也不是我们的重点,过 registerListeners(); // 重点,重点,重点 // 初始化所有的 singleton beans //(lazy-init 的除外) finishBeanFactoryInitialization(beanFactory); // 最后,广播事件,ApplicationContext 初始化完成 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. // 销毁已经初始化的 singleton 的 Beans,以免有些 bean 会一直占用资源 destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // 把异常往外抛 throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } } ``` ##### 大概总结一下 1. Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息; 1. xml注册bean;<bean> 2. 注解注册Bean;@Service、@Component、@Bean、xxx 2. Spring容器会合适的时机创建这些Bean 1. 用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中; 2. 统一创建剩下所有的bean的时候;finishBeanFactoryInitialization(); 3. 后置处理器;BeanPostProcessor 1. 每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;比如 1. AutowiredAnnotationBeanPostProcessor:处理自动注入 2. AnnotationAwareAspectJAutoProxyCreator:来做AOP功能; 3. xxx 4. 事件驱动模型; 1. ApplicationListener;事件监听; 2. ApplicationEventMulticaster;事件派发: 更详细的源码可看 1. [http://dreamcat.ink/2020/01/31/spring-springaop-yuan-ma-fen-xi/ ](http://dreamcat.ink/2020/01/31/spring-springaop-yuan-ma-fen-xi/ ) 2. [ https://javadoop.com/post/spring-ioc](https://javadoop.com/post/spring-ioc]) #### AOP AOP(Aspect-Oriented Programming:面向切面编程)能够将那些与业务无关,**却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来**,便于**减少系统的重复代码**,**降低模块间的耦合度**,并**有利于未来的可拓展性和可维护性**。 **Spring AOP就是基于动态代理的**,如果要代理的对象,实现了某个接口,那么Spring AOP会使用**JDK Proxy**,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用**Cglib** ,这时候Spring AOP会使用 **Cglib** 生成一个被代理对象的子类来作为代理。 当然你也可以使用 AspectJ ,Spring AOP 已经集成了AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。 使用 AOP 之后我们可以把一些通用功能抽象出来,在需要用到的地方直接使用即可,这样大大简化了代码量。我们需要增加新功能时也方便,这样也提高了系统扩展性。日志功能、事务管理等等场景都用到了 AOP 。 ##### Spring AOP 和 AspectJ AOP 有什么区别 **Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。** Spring AOP 基于代理(Proxying),而 AspectJ 基于字节码操作(Bytecode Manipulation) Spring AOP 已经集成了 AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。AspectJ 相比于 Spring AOP 功能更加强大,但是 Spring AOP 相对来说更简单, 如果我们的切面比较少,那么两者性能差异不大。但是,当切面太多的话,最好选择 AspectJ ,它比Spring AOP 快很多。 ##### 源码总结 ![AnnotationAwareAspectJAutoProxyCreator](http://media.dreamcat.ink//20200201150935.png) 1. @EnableAspectJAutoProxy 开启AOP功能 2. @EnableAspectJAutoProxy 会给容器中注册一个组件 AnnotationAwareAspectJAutoProxyCreator 3. AnnotationAwareAspectJAutoProxyCreator是一个后置处理器; 4. 容器的创建流程: 1. registerBeanPostProcessors()注册后置处理器;创建AnnotationAwareAspectJAutoProxyCreator对象(**Spring源码**) 2. finishBeanFactoryInitialization()初始化剩下的单实例bean(**Spring源码**) 1. 创建业务逻辑组件和切面组件 2. AnnotationAwareAspectJAutoProxyCreator拦截组件的创建过程 3. 组件创建完之后,判断组件是否需要增强;是->切面的通知方法,包装成增强器(Advisor);给业务逻辑组件创建一个代理对象(cglib); 5. 执行目标方法: 1. 代理对象执行目标方法 2. CglibAopProxy.intercept(); 1. 得到目标方法的拦截器链(增强器包装成拦截器MethodInterceptor) 2. 利用拦截器的链式机制,依次进入每一个拦截器进行执行; 3. 效果: 1. 正常执行:前置通知-》目标方法-》后置通知-》返回通知 2. 出现异常:前置通知-》目标方法-》后置通知-》异常通知 ### Spring Bean #### 作用域 - singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。 - prototype : 每次请求都会创建一个新的 bean 实例。 - request : 每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request内有效。 - session : 每一次HTTP请求都会产生一个新的 bean,该bean仅在当前 HTTP session 内有效。 - global-session: 全局session作用域,仅仅在基于portlet的web应用中才有意义,Spring5已经没有了。Portlet是能够生成语义代码(例如:HTML)片段的小型Java Web插件。它们基于portlet容器,可以像servlet一样处理HTTP请求。但是,与 servlet 不同,每个 portlet 都有不同的会话 #### Spring的单例有线程安全问题吗 大部分时候我们并没有在系统中使用多线程,所以很少有人会关注这个问题。单例 bean 存在线程问题,主要是因为当多个线程操作同一个对象的时候,对这个对象的非静态成员变量的写操作会存在线程安全问题。 常见的有两种解决办法: 1. 在Bean对象中尽量避免定义可变的成员变量(不太现实)。 2. 在类中定义一个ThreadLocal成员变量,将需要的可变成员变量保存在 ThreadLocal 中(推荐的一种方式)。 #### Component和Bean的区别 1. 作用对象不同: `@Component` 注解作用于类,而`@Bean`注解作用于方法。 2. `@Component`通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中(我们可以使用 `@ComponentScan` 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。`@Bean` 注解通常是我们在标有该注解的方法中定义产生这个 bean,`@Bean`告诉了Spring这是某个类的示例,当我需要用它的时候还给我。 3. `@Bean` 注解比 `Component` 注解的自定义性更强,而且很多地方我们只能通过 `@Bean` 注解来注册bean。比如当我们引用第三方库中的类需要装配到 `Spring`容器时,则只能通过 `@Bean`来实现。 #### 将类声明为bean有哪些 我们一般使用 `@Autowired` 注解自动装配 bean,要想把类标识成可用于 `@Autowired` 注解自动装配的 bean 的类,采用以下注解可实现: - `@Component` :通用的注解,可标注任意类为 `Spring` 组件。如果一个Bean不知道属于哪个层,可以使用`@Component` 注解标注。 - `@Repository` : 对应持久层即 Dao 层,主要用于数据库相关操作。 - `@Service` : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao层。 - `@Controller` : 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。 #### Bean的声明周期 ![bean周期](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-17/5496407.jpg) - Bean 容器找到配置文件中 Spring Bean 的定义。 - Bean 容器利用 Java Reflection API 创建一个Bean的实例。 - 如果涉及到一些属性值 利用 `set()`方法设置一些属性值。 - 如果 Bean 实现了 `BeanNameAware` 接口,调用 `setBeanName()`方法,传入Bean的名字。 - 如果 Bean 实现了 `BeanClassLoaderAware` 接口,调用 `setBeanClassLoader()`方法,传入 `ClassLoader`对象的实例。 - 与上面的类似,如果实现了其他 `*.Aware`接口,就调用相应的方法。 - 如果有和加载这个 Bean 的 Spring 容器相关的 `BeanPostProcessor` 对象,执行`postProcessBeforeInitialization()` 方法 - 如果Bean实现了`InitializingBean`接口,执行`afterPropertiesSet()`方法。 - 如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。 - 如果有和加载这个 Bean的 Spring 容器相关的 `BeanPostProcessor` 对象,执行`postProcessAfterInitialization()` 方法 - 当要销毁 Bean 的时候,如果 Bean 实现了 `DisposableBean` 接口,执行 `destroy()` 方法。 - 当要销毁 Bean 的时候,如果 Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。 ### SpringMVC MVC 是一种设计模式,Spring MVC 是一款很优秀的 MVC 框架。Spring MVC 可以帮助我们进行更简洁的Web层的开发,并且它天生与 Spring 框架集成。Spring MVC 下我们一般把后端项目分为 Service层(处理业务)、Dao层(数据库操作)、Entity层(实体类)、Controller层(控制层,返回数据给前台页面)。 ![springmvc](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-10-11/60679444.jpg) #### 工作原理 ![springmvc工作原理](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-10-11/49790288.jpg) **流程说明(重要):** 1. 客户端(浏览器)发送请求,直接请求到 `DispatcherServlet`。 2. `DispatcherServlet` 根据请求信息调用 `HandlerMapping`,解析请求对应的 `Handler`。 3. 解析到对应的 `Handler`(也就是我们平常说的 `Controller` 控制器)后,开始由 `HandlerAdapter` 适配器处理。 4. `HandlerAdapter` 会根据 `Handler`来调用真正的处理器开处理请求,并处理相应的业务逻辑。 5. 处理器处理完业务后,会返回一个 `ModelAndView` 对象,`Model` 是返回的数据对象,`View` 是个逻辑上的 `View`。 6. `ViewResolver` 会根据逻辑 `View` 查找实际的 `View`。 7. `DispaterServlet` 把返回的 `Model` 传给 `View`(视图渲染)。 8. 把 `View` 返回给请求者(浏览器) ### Spring都用到了哪些设计模式 - **工厂设计模式** : Spring使用工厂模式通过 `BeanFactory`、`ApplicationContext` 创建 bean 对象。 - **代理设计模式** : Spring AOP 功能的实现。 - **单例设计模式** : Spring 中的 Bean 默认都是单例的。 - **模板方法模式** : Spring 中 `jdbcTemplate`、`hibernateTemplate` 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。 - **包装器设计模式** : 我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。 - **观察者模式:** Spring 事件驱动模型就是观察者模式很经典的一个应用。 - **适配器模式** :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配`Controller`。 - ...... ### Spring事务 #### 管理事物有几种 - 编程式事务,在代码中硬编码。 - 声明式事务,在配置文件中配置 **声明式事务又分为两种**: 1. 基于XML的声明式事务 2. 基于注解的声明式事务 #### 隔离级别 **隔离级别就跟mysql几乎差不多** #### 源码分析 1. 开启@EnableTransactionManagement 2. 利用TransactionManagementConfigurationSelector给容器中会导入组件 1. AutoProxyRegistrar 2. ProxyTransactionManagementConfiguration 3. AutoProxyRegistrar: 1. 给容器中注册一个 InfrastructureAdvisorAutoProxyCreator 组件; 2. 利用后置处理器机制在对象创建以后,包装对象,返回一个代理对象(增强器),代理对象执行方法利用拦截器链进行调用; 4. ProxyTransactionManagementConfiguration 做了什么? 1. 给容器中注册事务增强器; 1. 事务增强器要用事务注解的信息,AnnotationTransactionAttributeSource解析事务注解 2. 事务拦截器: 1. TransactionInterceptor;保存了事务属性信息,事务管理器; 2. 他是一个 MethodInterceptor;在目标方法执行的时候; 1. 先获取事务相关的属性 2. 再获取PlatformTransactionManager,如果事先没有添加指定任何transactionmanger,最终会从容器中按照类型获取一个PlatformTransactionManager; 3. 执行目标方法 1. 如果异常,获取到事务管理器,利用事务管理回滚操作; 2. 如果正常,利用事务管理器,提交事务 ### Springboot启动流程 #### SpringApplication实例 ```java public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) { this.sources = new LinkedHashSet(); // 1. this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = new HashSet(); this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); this.webApplicationType = this.deduceWebApplicationType(); this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 3. this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); // 4. this.mainApplicationClass = this.deduceMainApplicationClass(); // 5. } ``` - `com.example.helloworld.HelloworldApplication`放入到Set的集合中 - 判断是否为Web环境:存在(javax.servlet.Servlet && org.springframework.web.context.ConfigurableWebApplicationContext )类 - 创建并初始化ApplicationInitializer列表 (spring.factories) - 创建并初始化ApplicationListener列表 (spring.factories) - 初始化主类mainApplicatioClass (DemoApplication) - **总结:上面就是SpringApplication初始化的代码,new SpringApplication()没做啥事情 ,主要加载了META-INF/spring.factories 下面定义的事件监听器接口实现类** #### ConfigurableApplicationContext的run方法 ```java public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); // 1. 创建计时器StopWatch stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); // 2. 获取SpringApplicationRunListeners并启动 listeners.starting(); // Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // 创建ApplicationArguments ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); // 创建并初始化ConfigurableEnvironment this.configureIgnoreBeanInfo(environment); // Banner printedBanner = this.printBanner(environment); // 打印Banner context = this.createApplicationContext(); // 创建ConfigurableApplicationContext exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);// 准备ConfigurableApplicationContext this.refreshContext(context); // 刷新ConfigurableApplicationContext,这个refreshContext()加载了bean,还启动了内置web容器,需要细细的去看看 this.afterRefresh(context, applicationArguments); // 容器刷新后动作,啥都没做 stopWatch.stop();// 计时器停止计时 if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } listeners.started(context); this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, exceptionReporters, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } } ``` - 创建计时器StopWatch - 获取SpringApplicationRunListeners并启动 - 创建ApplicationArguments - 创建并初始化ConfigurableEnvironment - 打印Banner - 创建ConfigurableApplicationContext - 准备ConfigurableApplicationContext - 刷新ConfigurableApplicationContext,**这个refreshContext()加载了bean,还启动了内置web容器,需要细细的去看看** - 容器刷新后动作,啥都没做 - 计时器停止计时 #### refreshContext() **该源码中其实就是Spring源码的refresh()的源码** - **不过这里的refresh()是在`AbstractApplicationContext`抽象类上** - **其他就不提了,关注点在onrefresh()方法上,但是个空方法,毕竟是抽象类,去找其子类继承的它** - **debug调试可以找到ServletWebServerApplicationContext** #### ServletWebServerApplicationContext ![](http://media.dreamcat.ink//20200203211202.png) - `onRefresh()`->`createWebServer()`->`getWebServerFactory()`,此时已经加载了个web容器 - 可以返回刚才的`createWebServer()`,然后看`factory.getWebServer` ```java public WebServer getWebServer(ServletContextInitializer... initializers) { //tomcat这位大哥出现了 Tomcat tomcat = new Tomcat(); File baseDir = (this.baseDirectory != null ? this.baseDirectory : createTempDir("tomcat")); tomcat.setBaseDir(baseDir.getAbsolutePath()); Connector connector = new Connector(this.protocol); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); } ``` - 内置的Tomcat就出现了 - **总结:run() 方法主要调用了spring容器启动方法扫描配置,加载bean到spring容器中;启动的内置Web容器** #### SpringBootApplication的注解 **主要是三个注解** - @SpringBootConfiguration:允许在上下文中注册额外的bean或导入其他配置类。 - @EnableAutoConfiguration:启用 SpringBoot 的自动配置机制 - @ComponentScan: 扫描常用的注解 <file_sep>package web; /** * @program LeetNiu * @description: 包含min函数的栈 * @author: mf * @create: 2020/01/12 23:33 */ import java.util.Stack; /** * 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。 * 用两个栈把 */ public class T20 { private Stack<Integer> stack = new Stack<>(); private Stack<Integer> stack2 = new Stack<>(); public void push(int node) { stack.push(node); if (stack2.isEmpty() || node < stack2.peek()) { stack2.push(node); } else { stack2.push(stack2.peek()); } } public void pop() { stack.pop(); stack2.pop(); } public int top() { return stack.peek(); } public int min() { return stack2.peek(); } } <file_sep>## 引言 > [JavaGuide](https://github.com/Snailclimb/JavaGuide) :一份涵盖大部分Java程序员所需要掌握的核心知识。**star:45159**,替他宣传一下子 > > 这位大佬,总结的真好!!!我引用这位大佬的文章,因为方便自己学习和打印... <!-- more --> ## AQS 简单介绍 AQS的全称为(AbstractQueuedSynchronizer),这个类在java.util.concurrent.locks包下面。 AQS是一个用来构建锁和同步器的框架,使用AQS能简单且高效地构造出应用广泛的大量的同步器,比如我们提到的ReentrantLock,Semaphore,其他的诸如ReentrantReadWriteLock,SynchronousQueue,FutureTask等等皆是基于AQS的。当然,我们自己也能利用AQS非常轻松容易地构造出符合我们自己需求的同步器。 ## AQS原理 ### 概述 **AQS核心思想是,如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资源设置为锁定状态。如果被请求的共享资源被占用,那么就需要一套线程阻塞等待以及被唤醒时锁分配的机制,这个机制AQS是用CLH队列锁实现的,即将暂时获取不到锁的线程加入到队列中。** > CLH(Craig,Landin,and Hagersten)队列是一个虚拟的双向队列(虚拟的双向队列即不存在队列实例,仅存在结点之间的关联关系)。AQS是将每条请求共享资源的线程封装成一个CLH锁队列的一个结点(Node)来实现锁的分配。 ![参考-JavaGuide-enter image description here](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/Java%20%E7%A8%8B%E5%BA%8F%E5%91%98%E5%BF%85%E5%A4%87%EF%BC%9A%E5%B9%B6%E5%8F%91%E7%9F%A5%E8%AF%86%E7%B3%BB%E7%BB%9F%E6%80%BB%E7%BB%93/CLH.png) AQS使用一个int成员变量来表示同步状态,通过内置的FIFO队列来完成获取资源线程的排队工作。AQS使用CAS对该同步状态进行原子操作实现对其值的修改。 ```java private volatile int state;//共享变量,使用volatile修饰保证线程可见性 ``` 状态信息通过protected类型的getState,setState,compareAndSetState进行操作 ```java //返回同步状态的当前值 protected final int getState() { return state; } // 设置同步状态的值 protected final void setState(int newState) { state = newState; } //原子地(CAS操作)将同步状态值设置为给定值update如果当前同步状态的值等于expect(期望值) protected final boolean compareAndSetState(int expect, int update) { return unsafe.compareAndSwapInt(this, stateOffset, expect, update); } ``` ### AQS对资源的共享方式 **AQS定义两种资源共享方式** - **Exclusive**(独占):只有一个线程能执行,如ReentrantLock。又可分为公平锁和非公平锁: - 公平锁:按照线程在队列中的排队顺序,先到者先拿到锁 - 非公平锁:当线程要获取锁时,无视队列顺序直接去抢锁,谁抢到就是谁的 - **Share**(共享):多个线程可同时执行,如Semaphore/CountDownLatch。Semaphore、CountDownLatCh、 CyclicBarrier、ReadWriteLock 我们都会在后面讲到。 ReentrantReadWriteLock 可以看成是组合式,因为ReentrantReadWriteLock也就是读写锁允许多个线程同时对某一资源进行读。 不同的自定义同步器争用共享资源的方式也不同。自定义同步器在实现时只需要实现共享资源 state 的获取与释放方式即可,至于具体线程等待队列的维护(如获取资源失败入队/唤醒出队等),AQS已经在上层已经帮我们实现好了。 ### AQS底层使用了模板方法模式 这和我们以往通过实现接口的方式有很大区别,这是模板方法模式很经典的一个运用,下面简单的给大家介绍一下模板方法模式,模板方法模式是一个很容易理解的设计模式之一。 > 模板方法模式是基于”继承“的,主要是为了在不改变模板结构的前提下在子类中重新定义模板中的内容以实现复用代码。举个很简单的例子假如我们要去一个地方的步骤是:购票`buyTicket()`->安检`securityCheck()`->乘坐某某工具回家`ride()`->到达目的地`arrive()`。我们可能乘坐不同的交通工具回家比如飞机或者火车,所以除了`ride()`方法,其他方法的实现几乎相同。我们可以定义一个包含了这些方法的抽象类,然后用户根据自己的需要继承该抽象类然后修改 `ride()`方法。 默认情况下,每个方法都抛出 `UnsupportedOperationException`。 这些方法的实现必须是内部线程安全的,并且通常应该简短而不是阻塞。AQS类中的其他方法都是final ,所以无法被其他类使用,只有这几个方法可以被其他类使用。 以ReentrantLock为例,state初始化为0,表示未锁定状态。A线程lock()时,会调用tryAcquire()独占该锁并将state+1。此后,其他线程再tryAcquire()时就会失败,直到A线程unlock()到state=0(即释放锁)为止,其它线程才有机会获取该锁。当然,释放锁之前,A线程自己是可以重复获取此锁的(state会累加),这就是可重入的概念。但要注意,获取多少次就要释放多么次,这样才能保证state是能回到零态的。 再以CountDownLatch以例,任务分为N个子线程去执行,state也初始化为N(注意N要与线程个数一致)。这N个子线程是并行执行的,每个子线程执行完后countDown()一次,state会CAS(Compare and Swap)减1。等到所有子线程都执行完后(即state=0),会unpark()主调用线程,然后主调用线程就会从await()函数返回,继续后余动作。 一般来说,自定义同步器要么是独占方法,要么是共享方式,他们也只需实现`tryAcquire-tryRelease`、`tryAcquireShared-tryReleaseShared`中的一种即可。但AQS也支持自定义同步器同时实现独占和共享两种方式,如`ReentrantReadWriteLock`。 ## Semaphore(信号量)-允许多个线程同时访问 **synchronized 和 ReentrantLock 都是一次只允许一个线程访问某个资源,Semaphore(信号量)可以指定多个线程同时访问某个资源。** 示例代码如下: ```java public class SemaphoreExample1 { // 请求的数量 private static final int threadCount = 550; public static void main(String[] args) throws InterruptedException { // 创建一个具有固定线程数量的线程池对象(如果这里线程池的线程数量给太少的话你会发现执行的很慢) ExecutorService threadPool = Executors.newFixedThreadPool(300); // 一次只能允许执行的线程数量。 final Semaphore semaphore = new Semaphore(20); for (int i = 0; i < threadCount; i++) { final int threadnum = i; threadPool.execute(() -> {// Lambda 表达式的运用 try { semaphore.acquire();// 获取一个许可,所以可运行线程数量为20/1=20 test(threadnum); semaphore.release();// 释放一个许可 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); } threadPool.shutdown(); System.out.println("finish"); } public static void test(int threadnum) throws InterruptedException { Thread.sleep(1000);// 模拟请求的耗时操作 System.out.println("threadnum:" + threadnum); Thread.sleep(1000);// 模拟请求的耗时操作 } } ``` 执行 `acquire` 方法阻塞,直到有一个许可证可以获得然后拿走一个许可证;每个 `release` 方法增加一个许可证,这可能会释放一个阻塞的acquire方法。然而,其实并没有实际的许可证这个对象,Semaphore只是维持了一个可获得许可证的数量。 Semaphore经常用于限制获取某种资源的线程数量。 除了 `acquire`方法之外,另一个比较常用的与之对应的方法是`tryAcquire`方法,该方法如果获取不到许可就立即返回false。 Semaphore 有两种模式,公平模式和非公平模式。 - **公平模式:** 调用acquire的顺序就是获取许可证的顺序,遵循FIFO; - **非公平模式:** 抢占式的。 **Semaphore 对应的两个构造方法如下:** ```java public Semaphore(int permits) { sync = new NonfairSync(permits); } public Semaphore(int permits, boolean fair) { sync = fair ? new FairSync(permits) : new NonfairSync(permits); } ``` **这两个构造方法,都必须提供许可的数量,第二个构造方法可以指定是公平模式还是非公平模式,默认非公平模式。** ## CountDownLatch (倒计时器) CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。在Java并发中,countdownlatch的概念是一个常见的面试题,所以一定要确保你很好的理解了它。 ### CountDownLatch 的三种典型用法 ①某一线程在开始运行前等待n个线程执行完毕。将 CountDownLatch 的计数器初始化为n :`new CountDownLatch(n) `,每当一个任务线程执行完毕,就将计数器减1 `countdownlatch.countDown()`,当计数器的值变为0时,在`CountDownLatch上 await()` 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。 ②实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。做法是初始化一个共享的 `CountDownLatch` 对象,将其计数器初始化为 1 :`new CountDownLatch(1) `,多个线程在开始执行任务前首先 `coundownlatch.await()`,当主线程调用 countDown() 时,计数器变为0,多个线程同时被唤醒。 ③死锁检测:一个非常方便的使用场景是,你可以使用n个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁。 ```java public class CountDownLatchExample1 { // 请求的数量 private static final int threadCount = 550; public static void main(String[] args) throws InterruptedException { // 创建一个具有固定线程数量的线程池对象(如果这里线程池的线程数量给太少的话你会发现执行的很慢) ExecutorService threadPool = Executors.newFixedThreadPool(300); final CountDownLatch countDownLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { final int threadnum = i; threadPool.execute(() -> {// Lambda 表达式的运用 try { test(threadnum); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { countDownLatch.countDown();// 表示一个请求已经被完成 } }); } countDownLatch.await(); threadPool.shutdown(); System.out.println("finish"); } public static void test(int threadnum) throws InterruptedException { Thread.sleep(1000);// 模拟请求的耗时操作 System.out.println("threadnum:" + threadnum); Thread.sleep(1000);// 模拟请求的耗时操作 } } ``` 上面的代码中,我们定义了请求的数量为550,当这550个请求被处理完成之后,才会执行`System.out.println("finish");`。 与CountDownLatch的第一次交互是主线程等待其他线程。主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。 其他N个线程必须引用闭锁对象,因为他们需要通知CountDownLatch对象,他们已经完成了各自的任务。这种通知机制是通过 CountDownLatch.countDown()方法来完成的;每调用一次这个方法,在构造函数中初始化的count值就减1。所以当N个线程都调 用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务。 ### CountDownLatch 的不足 CountDownLatch是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。 ### CountDownLatch相常见面试题: 解释一下CountDownLatch概念? CountDownLatch 和CyclicBarrier的不同之处? 给出一些CountDownLatch使用的例子? CountDownLatch 类中主要的方法? ## CyclicBarrier(循环栅栏) CyclicBarrier 和 CountDownLatch 非常类似,它也可以实现线程间的技术等待,但是它的功能比 CountDownLatch 更加复杂和强大。主要应用场景和 CountDownLatch 类似。 CyclicBarrier 的字面意思是可循环使用(Cyclic)的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活。CyclicBarrier默认的构造方法是 `CyclicBarrier(int parties)`,其参数表示屏障拦截的线程数量,每个线程调用`await`方法告诉 CyclicBarrier 我已经到达了屏障,然后当前线程被阻塞。 ### CyclicBarrier 的应用场景 CyclicBarrier 可以用于多线程计算数据,最后合并计算结果的应用场景。比如我们用一个Excel保存了用户所有银行流水,每个Sheet保存一个帐户近一年的每笔银行流水,现在需要统计用户的日均银行流水,先用多线程处理每个sheet里的银行流水,都执行完之后,得到每个sheet的日均银行流水,最后,再用barrierAction用这些线程的计算结果,计算出整个Excel的日均银行流水。 ```java public class CyclicBarrierExample2 { // 请求的数量 private static final int threadCount = 550; // 需要同步的线程数量 private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(5); public static void main(String[] args) throws InterruptedException { // 创建线程池 ExecutorService threadPool = Executors.newFixedThreadPool(10); for (int i = 0; i < threadCount; i++) { final int threadNum = i; Thread.sleep(1000); threadPool.execute(() -> { try { test(threadNum); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); } threadPool.shutdown(); } public static void test(int threadnum) throws InterruptedException, BrokenBarrierException { System.out.println("threadnum:" + threadnum + "is ready"); try { /**等待60秒,保证子线程完全执行结束*/ cyclicBarrier.await(60, TimeUnit.SECONDS); } catch (Exception e) { System.out.println("-----CyclicBarrierException------"); } System.out.println("threadnum:" + threadnum + "is finish"); } } ``` ``` threadnum:0is ready threadnum:1is ready threadnum:2is ready threadnum:3is ready threadnum:4is ready threadnum:4is finish threadnum:0is finish threadnum:1is finish threadnum:2is finish threadnum:3is finish threadnum:5is ready threadnum:6is ready threadnum:7is ready threadnum:8is ready threadnum:9is ready threadnum:9is finish threadnum:5is finish threadnum:8is finish threadnum:7is finish threadnum:6is finish ...... ``` 可以看到当线程数量也就是请求数量达到我们定义的 5 个的时候, `await`方法之后的方法才被执行。 另外,CyclicBarrier还提供一个更高级的构造函数`CyclicBarrier(int parties, Runnable barrierAction)`,用于在线程到达屏障时,优先执行`barrierAction`,方便处理更复杂的业务场景。示例代码如下: ```java public class CyclicBarrierExample3 { // 请求的数量 private static final int threadCount = 550; // 需要同步的线程数量 private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> { System.out.println("------当线程数达到之后,优先执行------"); }); public static void main(String[] args) throws InterruptedException { // 创建线程池 ExecutorService threadPool = Executors.newFixedThreadPool(10); for (int i = 0; i < threadCount; i++) { final int threadNum = i; Thread.sleep(1000); threadPool.execute(() -> { try { test(threadNum); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); } threadPool.shutdown(); } public static void test(int threadnum) throws InterruptedException, BrokenBarrierException { System.out.println("threadnum:" + threadnum + "is ready"); cyclicBarrier.await(); System.out.println("threadnum:" + threadnum + "is finish"); } } ``` ``` threadnum:0is ready threadnum:1is ready threadnum:2is ready threadnum:3is ready threadnum:4is ready ------当线程数达到之后,优先执行------ threadnum:4is finish threadnum:0is finish threadnum:2is finish threadnum:1is finish threadnum:3is finish threadnum:5is ready threadnum:6is ready threadnum:7is ready threadnum:8is ready threadnum:9is ready ------当线程数达到之后,优先执行------ threadnum:9is finish threadnum:5is finish threadnum:6is finish threadnum:8is finish threadnum:7is finish ...... ``` ### CyclicBarrier和CountDownLatch的区别 CountDownLatch是计数器,只能使用一次,而CyclicBarrier的计数器提供reset功能,可以多次使用。 对于CountDownLatch来说,重点是“一个线程(多个线程)等待”,而其他的N个线程在完成“某件事情”之后,可以终止,也可以等待。而对于CyclicBarrier,重点是多个线程,在任意一个线程没有完成,所有的线程都必须等待。 CountDownLatch是计数器,线程完成一个记录一个,只不过计数不是递增而是递减,而CyclicBarrier更像是一个阀门,需要所有线程都到达,阀门才能打开,然后继续执行。 ![参考-JavaGuide-CyclicBarrier和CountDownLatch的区别](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/Java%20%E7%A8%8B%E5%BA%8F%E5%91%98%E5%BF%85%E5%A4%87%EF%BC%9A%E5%B9%B6%E5%8F%91%E7%9F%A5%E8%AF%86%E7%B3%BB%E7%BB%9F%E6%80%BB%E7%BB%93/AQS333.png) <file_sep>package mianjing; import java.util.HashMap; /** * @program JavaBooks * @description: 无重复字符的最长子串 * @author: mf * @create: 2020/04/18 23:11 */ /** * 输入: "abcabcbb" * 输出: 3 * 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 * 输入: "bbbbb" * 输出: 1 * 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 * 输入: "pwwkew" * 输出: 3 * 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 *   请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 * */ public class LongestSubstring { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; HashMap<Character, Integer> map = new HashMap<>(); // abcabc for (int i = 0, j = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } public static void main(String[] args) { LongestSubstring longestSubstring = new LongestSubstring(); System.out.println(longestSubstring.lengthOfLongestSubstring("abcabcbb")); } } <file_sep>package web; /** * @program LeetNiu * @description: 调整数组顺序使奇数位于偶数前面 * @author: mf * @create: 2020/01/10 14:03 */ /** * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分, * 所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 */ public class T13 { public void reOrderArray(int [] array) { // 判断 if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length - 1; j++) { if ((array[j] & 0x1) == 0 && (array[j + 1] & 0x1) == 1) { swap(array, j, j + 1); } } } } /** * 数据交换 * @param arr * @param x * @param y */ private void swap(int[] arr, int x, int y) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } <file_sep>package normal; /** * @program JavaBooks * @description: 88、合并两个有序数组 * @author: mf * @create: 2019/11/04 09:46 */ /** * 题目:https://leetcode-cn.com/problems/merge-sorted-array/ * 难度:easy */ import java.util.Arrays; /** * 输入: * nums1 = [1,2,3,0,0,0], m = 3 * nums2 = [2,5,6], n = 3 * * 输出: [1,2,2,3,5,6] * */ public class Merge { public static void main(String[] args) { // int[] nums1 = {1,2,3,0,0,0}; // int[] nums2 = {2,5,6}; int[] nums1 = {2,0}; int[] nums2 = {1}; merge(nums1, 1, nums2, 1); System.out.println(Arrays.toString(nums1)); } // 可以双指针 public static void merge(int[] nums1, int m, int[] nums2, int n) { // 两种情况 // 第一种,nums1全是0,也就是m==0 if (m == 0) { for (int i = 0; i < n; i++) { nums1[i] = nums2[i]; } return; } // 第二种,m不是0的情况 int p = nums1.length - 1; int a1 = m - 1; for (int i = n - 1; i >= 0; i--) { while (a1 >= 0 && nums1[a1] > nums2[i]) { nums1[p--] = nums1[a1--]; } nums1[p--] = nums2[i]; } } } <file_sep>/** * @program JavaBooks * @description: 复杂链表的复制 * @author: mf * @create: 2020/03/08 02:19 */ package subject.linked; /** * 输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] * 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]] */ public class T5 { /** * 迭代三次 * @param head * @return */ public Node copyRandomList(Node head) { if (head == null) return null; Node node = head; // 一般这样的操作其实就是好比是指针了,链表定义个指针, 走你 // 第一次迭代的目的是复制next while (node != null) { // 接下来的三步操作 复制节点 Node temp = new Node(node.val); // new一个和node值相同的当前节点 temp 比如1` temp.next = node.next; // temp 的下个节点指向 node的下个节点, 比如1`>2 node.next = temp; // node 的下个节点 指向temp 比如 1 > 1` > 2 // 一般迭代, 都会有这一步操作, 移动指针 node = temp.next; // 将node 指针 指向 temp的下个节点, 比如2 } // 这次的目的让复制的节点的random 和 原先的random各个指向的一致 // 将指针移动首部 node = head; while (node != null) { // 2 2` // ^_^ ^_^ // 1 > 1` > 2 > 2` > 3 > 3` node.next.random = node.random == null ? null : node.random.next; // 迭代,移动指针 node = node.next.next; } // 第三次目的是切断 返回复制的链表 // 双指针, 重新指向 node = head; Node pCloneHead = head.next; while (node != null) { Node temp = node.next; // 其实就是当前的复制节点 node.next = temp.next; // 其实就是 1 > 2 temp.next = temp.next == null ? null : temp.next.next; // 其实就是 1` > 2` // 迭代, 移动指针 node = node.next; } return pCloneHead; } } <file_sep>## 问题描述 - 请设计一个LRU,伪代码... ## 思路 - 双向链表+Hashmap ## 伪代码 - 简单定义节点Node ```java class Node { int key; int value; Node pre; Node next; } ``` - 定义Hashmap ```java HashMap<Integer, Node> map = new HashMap<>(); ``` - get操作 ```java public int get(int key) { if (map.containsKey(key)) { Node n = map.get(key); remove(n); // 链表 setHead(n); // 链表 return n.value; } return -1; } ``` - 由于当一个节点通过key来访问到这个节点,那么这个节点就是刚被访问了, - 就把这个节点删除掉,然后放到队列头,这样队列的头部都是最近访问的, - 队列尾部是最近没有被访问的。 - set操作 ```java public void set(int key, int value) { if (map.containsKey(key)) { Node old = map.get(key); old.value = value; remove(old); setHead(old); } else { Node created = new Node(key, value); if (map.size() >= capacity) { map.remove(end.key); remove(end); setHead(created); } else { setHead(created); } map.put(key, created); } } ``` - 由于set操作是找到这个键值对,然后修改value的值,由于这个节点被访问了,所以删除他,把这个节点放到头部, - 如果这个节点不存在,那么就新建一个节点,把这个节点放到头部,同时map增加这个键值对。 - 上述中所有过程都是先访问map,由于hashmap是O(1)的时间复杂度,而且双向链表的所有操作的时间复杂度在本例中都是O(1), - 删除啦,插入头部都是O(1)时间复杂度,所以整个get和set的时间复杂度都是O(1)。<file_sep>- [简述线程、程序、进程的基本概念。以及他们之间关系是什么?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E7%AE%80%E8%BF%B0%E7%BA%BF%E7%A8%8B%E7%A8%8B%E5%BA%8F%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5%E4%BB%A5%E5%8F%8A%E4%BB%96%E4%BB%AC%E4%B9%8B%E9%97%B4%E5%85%B3%E7%B3%BB%E6%98%AF%E4%BB%80%E4%B9%88) - [Java 语言有哪些特点?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#java-%E8%AF%AD%E8%A8%80%E6%9C%89%E5%93%AA%E4%BA%9B%E7%89%B9%E7%82%B9) - [面向对象和面向过程的区别](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%92%8C%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E7%9A%84%E5%8C%BA%E5%88%AB) - **==、hashcode和equals** - [==与equals](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#-%E4%B8%8E-equals%E9%87%8D%E8%A6%81) - [hashcode和equlas](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#hashcode-%E4%B8%8E-equals-%E9%87%8D%E8%A6%81) - [hashcode和equlas代码小例子](/Basics/src/com/equal/Student.java) - **关于 JVM JDK 和 JRE 最详细通俗的解答** - [JVM](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#jvm) - [JDK 和 JRE](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#jdk-%E5%92%8C-jre) - [Java和C++的区别?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#java%E5%92%8Cc%E7%9A%84%E5%8C%BA%E5%88%AB) - **基本类型** - [自动装箱与拆箱](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E8%87%AA%E5%8A%A8%E8%A3%85%E7%AE%B1%E4%B8%8E%E6%8B%86%E7%AE%B1) - [字符型常量和字符串常量的区别?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%AD%97%E7%AC%A6%E5%9E%8B%E5%B8%B8%E9%87%8F%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E9%87%8F%E7%9A%84%E5%8C%BA%E5%88%AB) - [说说&和&&的区别](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E8%AF%B4%E8%AF%B4%E5%92%8C%E7%9A%84%E5%8C%BA%E5%88%AB) - [short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1; 有什么错?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#short-s1--1-s1--s1--1%E6%9C%89%E4%BB%80%E4%B9%88%E9%94%99-short-s1--1-s1--1-%E6%9C%89%E4%BB%80%E4%B9%88%E9%94%99) [demo](/Basics/src/com/type/TypeConvert.java) - [char 型变量中能不能存贮一个中文汉字?为什么?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#char-%E5%9E%8B%E5%8F%98%E9%87%8F%E4%B8%AD%E8%83%BD%E4%B8%8D%E8%83%BD%E5%AD%98%E8%B4%AE%E4%B8%80%E4%B8%AA%E4%B8%AD%E6%96%87%E6%B1%89%E5%AD%97%E4%B8%BA%E4%BB%80%E4%B9%88) - [整形包装缓存池例子vlaueof](/Basics/src/com/pack/IntegerPackDemo.java) - **构造器** - [构造器 Constructor 是否可被 override?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%9E%84%E9%80%A0%E5%99%A8-constructor-%E6%98%AF%E5%90%A6%E5%8F%AF%E8%A2%AB-override) - [构造方法有哪些特性?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95%E6%9C%89%E5%93%AA%E4%BA%9B%E7%89%B9%E6%80%A7) - **String** - [String StringBuffer 和 StringBuilder 的区别是什么? String 为什么是不可变的?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#string-stringbuffer-%E5%92%8C-stringbuilder-%E7%9A%84%E5%8C%BA%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88-string-%E4%B8%BA%E4%BB%80%E4%B9%88%E6%98%AF%E4%B8%8D%E5%8F%AF%E5%8F%98%E7%9A%84) - [String StringBuffer 和 StringBuilder的代码例子](/Basics/src/com/strings/SbDemo.java) - [String A = "123"; String B = new String("123");生成几个对象?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#string-a--123-string-b--new-string123%E7%94%9F%E6%88%90%E5%87%A0%E4%B8%AA%E5%AF%B9%E8%B1%A1) - [String.intern与缓存池](/Basics/src/com/strings/SIntern.java) - **对象** - [Java 面向对象编程三大特性: 封装 继承 多态](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E9%87%8D%E8%BD%BD%E5%92%8C%E9%87%8D%E5%86%99%E7%9A%84%E5%8C%BA%E5%88%AB) - [接口和抽象类的区别是什么?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%8E%A5%E5%8F%A3%E5%92%8C%E6%8A%BD%E8%B1%A1%E7%B1%BB%E7%9A%84%E5%8C%BA%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88) - [成员变量与局部变量的区别有哪些?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F%E4%B8%8E%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E7%9A%84%E5%8C%BA%E5%88%AB%E6%9C%89%E5%93%AA%E4%BA%9B) - [重载和重写的区别](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E9%87%8D%E8%BD%BD%E5%92%8C%E9%87%8D%E5%86%99%E7%9A%84%E5%8C%BA%E5%88%AB) - [创建一个对象用什么运算符?对象实体与对象引用有何不同?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E5%AF%B9%E8%B1%A1%E7%94%A8%E4%BB%80%E4%B9%88%E8%BF%90%E7%AE%97%E7%AC%A6%E5%AF%B9%E8%B1%A1%E5%AE%9E%E4%BD%93%E4%B8%8E%E5%AF%B9%E8%B1%A1%E5%BC%95%E7%94%A8%E6%9C%89%E4%BD%95%E4%B8%8D%E5%90%8C) - [对象的相等与指向他们的引用相等,两者有什么不同?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%9B%B8%E7%AD%89%E4%B8%8E%E6%8C%87%E5%90%91%E4%BB%96%E4%BB%AC%E7%9A%84%E5%BC%95%E7%94%A8%E7%9B%B8%E7%AD%89%E4%B8%A4%E8%80%85%E6%9C%89%E4%BB%80%E4%B9%88%E4%B8%8D%E5%90%8C) - [为什么Java中只有值传递?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E4%B8%BA%E4%BB%80%E4%B9%88java%E4%B8%AD%E5%8F%AA%E6%9C%89%E5%80%BC%E4%BC%A0%E9%80%92) - [参考这篇文章](https://github.com/Snailclimb/JavaGuide/blob/master/docs/essential-content-for-interview/PreparingForInterview/%E5%BA%94%E5%B1%8A%E7%94%9F%E9%9D%A2%E8%AF%95%E6%9C%80%E7%88%B1%E9%97%AE%E7%9A%84%E5%87%A0%E9%81%93Java%E5%9F%BA%E7%A1%80%E9%97%AE%E9%A2%98.md#%E4%B8%80-%E4%B8%BA%E4%BB%80%E4%B9%88-java-%E4%B8%AD%E5%8F%AA%E6%9C%89%E5%80%BC%E4%BC%A0%E9%80%92) - [基本类型传递代码例子](/Basics/src/com/transfer/TransferDemo.java) - [数组类型传递代码例子](/Basics/src/com/transfer/TransferDemo2.java) - [对象引用类型传递代码例子](/Basics/src/com/transfer/TransferDemo3.java) - **关键字** - [关于 final 关键字的一些总结](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%85%B3%E4%BA%8E-final-%E5%85%B3%E9%94%AE%E5%AD%97%E7%9A%84%E4%B8%80%E4%BA%9B%E6%80%BB%E7%BB%93) **一般关键字的面试,答的时候按照变量、方法和类去总结** - [static 关键字](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#static-%E5%85%B3%E9%94%AE%E5%AD%97) - [this 关键字](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#this-%E5%85%B3%E9%94%AE%E5%AD%97) - [super 关键字](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#super-%E5%85%B3%E9%94%AE%E5%AD%97) - [final, finally, finalize 的区别](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#final-finally-finalize-%E7%9A%84%E5%8C%BA%E5%88%AB) - [请说出作用域 public,private,protected,以及不写时的区别](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E8%AF%B7%E8%AF%B4%E5%87%BA%E4%BD%9C%E7%94%A8%E5%9F%9F-publicprivateprotected%E4%BB%A5%E5%8F%8A%E4%B8%8D%E5%86%99%E6%97%B6-%E7%9A%84%E5%8C%BA%E5%88%AB) - **异常** - [Java 中的异常处理](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#java-%E4%B8%AD%E7%9A%84%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86) - [请写出你最常见到的 5 个 runtime exception](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E8%AF%B7%E5%86%99%E5%87%BA%E4%BD%A0%E6%9C%80%E5%B8%B8%E8%A7%81%E5%88%B0%E7%9A%84-5-%E4%B8%AA-runtime-exception) - **IO** - [获取用键盘输入常用的两种方法](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E8%8E%B7%E5%8F%96%E7%94%A8%E9%94%AE%E7%9B%98%E8%BE%93%E5%85%A5%E5%B8%B8%E7%94%A8%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E6%B3%95) - [Java 中 IO 流分为几种?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#java-%E4%B8%AD-io-%E6%B5%81%E5%88%86%E4%B8%BA%E5%87%A0%E7%A7%8D) - [既然有了字节流,为什么还要有字符流?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%97%A2%E7%84%B6%E6%9C%89%E4%BA%86%E5%AD%97%E8%8A%82%E6%B5%81%E4%B8%BA%E4%BB%80%E4%B9%88%E8%BF%98%E8%A6%81%E6%9C%89%E5%AD%97%E7%AC%A6%E6%B5%81) - [BIO,NIO,AIO 有什么区别?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#bionioaio-%E6%9C%89%E4%BB%80%E4%B9%88%E5%8C%BA%E5%88%AB) - **反射** - [反射是什么?](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6%E4%BB%8B%E7%BB%8D) - [静态编译和动态编译](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E9%9D%99%E6%80%81%E7%BC%96%E8%AF%91%E5%92%8C%E5%8A%A8%E6%80%81%E7%BC%96%E8%AF%91) - [反射机制优缺点](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6%E4%BC%98%E7%BC%BA%E7%82%B9) - [反射的应用场景](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E5%8F%8D%E5%B0%84%E7%9A%84%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF) - [反射得到Class对象的三种方式代码例子](/Basics/src/com/reflect/ReflectDemo.java) - [反射访问并调用构造方法的代码例子](/Basics/src/com/reflect/ConstructorsDemo.java) - [反射访问并调用成员变量的代码例子](/Basics/src/com/reflect/FieldDemo.java) - [反射访问并调用成员方法的代码例子](/Basics/src/com/reflect/MethodDemo.java) - **拷贝** - [深拷贝 vs 浅拷贝](https://github.com/DreamCats/JavaBooks/blob/master/Basics/Java%E9%9D%A2%E8%AF%95%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86.md#%E6%B7%B1%E6%8B%B7%E8%B4%9D-vs-%E6%B5%85%E6%8B%B7%E8%B4%9D) - [深浅拷贝参考](https://juejin.im/post/5c988a7ef265da6116246d11) - [浅拷贝代码例子](/Basics/src/com/copy/ShallowCopyDemo.java) - [深拷贝代码例子](/Basics/src/com/copy/Student.java) <file_sep>package books; /** * @program JavaBooks * @description: 机器人的运动范围 * @author: mf * @create: 2019/08/25 09:45 */ /* 地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动 它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标 的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35, 37), 因为 3+5+3+7=18。但它不能进入方格(35, 38),因为3+5+3+8=19。请问? 该机器人能够到达多少个格子。 */ public class T13 { public static void main(String[] args) { int count = movingCount(18, 40, 40); System.out.println(count); } public static int movingCount(int threshold, int rows, int cols) { if (threshold < 0 || rows < 1 || cols < 0) return 0; boolean[][] visited = new boolean[rows][cols]; int count = movingCountCore(threshold, rows, cols, 0, 0, visited); return count; } public static int movingCountCore(int threshold, int rows, int cols, int i, int j, boolean[][] visited) { int count = 0; if (check(threshold, rows, cols, i, j, visited)) { visited[i][j] = true; // 核心之二 count = 1 + movingCountCore(threshold, rows, cols, i, j - 1, visited) + movingCountCore(threshold, rows, cols, i, j + 1, visited) + movingCountCore(threshold, rows, cols, i - 1, j, visited) + movingCountCore(threshold, rows, cols, i + 1, j, visited); } return count; } public static boolean check(int threshold, int rows, int cols, int i, int j, boolean[][] visited) { // 核心之一 if (i >=0 && j >= 0 && i < rows && j < cols && getDigiSum(i) + getDigiSum(j) <= threshold && !visited[i][j]) return true; return false; } // 常用方法,求一个数的总和 public static int getDigiSum(int i) { int sum = 0; while (i > 0 ) { sum += i % 10; i /= 10; } return sum; } }
66a455be4ca757eee7a7f7bd044809c5cb039c70
[ "Markdown", "Java" ]
188
Java
DreamCats/JavaBooks
2ad85514ea4367c075cb476dd5d6f1e40ecda9cf
65a7e7b1a1632fe500a0dc4f76727ce62b2f759e
refs/heads/master
<repo_name>binbsr/ExData_Plotting1<file_sep>/load_data.R library(httr) url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" dataFolder <- "data" if(!file.exists(dataFolder)){ dir.create(dataFolder) } dataFileArchive <- paste(getwd(), "/data/household_power_consumption.zip", sep = "") if(!file.exists(dataFileArchive)){ download.file(url, dataFileArchive) } unzip(dataFileArchive, list = FALSE, overwrite = TRUE, exdir = "data")
9157a4d37292e19251acf5bc99eff4165873a3ea
[ "R" ]
1
R
binbsr/ExData_Plotting1
92873a95f25e232252eac57145fd0445fd188e23
52a67865adce96a60af8b8da188e8b41a55e1de5
refs/heads/main
<repo_name>FA-MatSci/Who-wants-to-be-a-millionaire-<file_sep>/README.md # The game! After the popular TV quiz show, here it is written in Python. # Instructions The game consists of 10 questions with 4 possible answers. The complexity of questions (relatively speaking) is increasing from 1 being the easiest and 10 the hardest. Only one answer (a, b, c, or d) for every question is correct. There are 3 different lifelines available during the game that may be used when needed. Each of them can only be used once. If there is an attempt for using a particular lifeline more than once, the game will stop. Lifeline 1 eliminates two possible answers (50 : 50). Lifeline 2 seeks help from the audience (ask the audience). Lifeline 3 calls a person to ask him/her about the question (phone a friend). There are no second chances, and a wrong answer means that the game is over. # Breakdown of the script Questions 1- 5: **kwargs and @classmethod Questions 6-7: hasattr() Questions 8: composition Question 9: inheritance Question 10: magic methods <file_sep>/The_game.py #Copyrights <NAME> import sys import random import time #Lets do the first 5 questions via **kwargs class Question_class: def __init__(self, **kwargs): self.q1=kwargs['q1'] self.q2=kwargs['q2'] self.q3=kwargs['q3'] self.q4=kwargs['q4'] self.q5=kwargs['q5'] print('Hello, World!\n\n' + 'Who Wants to Be a Millionaire?\n\n' + 'Before you start, may I ask you for some information? - ' + 'We need that for lifelines!\n') name1 = input('What is your name? >>>:') name2 = input('What is the name of your mother? >>>:') name3 = input('What is the name of your father? >>>:') name4 = input('What is the name of your best friend? >>>:') def qu1(self): return str('\nQuestion 1 \n\n ') + self.q1 def qu2(self): return str('\nQuestion 2 \n\n') + self.q2 def qu3(self): return str('\nQuestion 3 \n\n') + self.q3 def qu4(self): return str('\nQuestion 4 \n\n') + self.q4 def qu5(self): return str('\nQuestion 5 \n\n') + self.q5 class Key_class: def qu1_keys(self): return str('a) Manchester \t\t\t\t') + str('b) London \n') + str('c) Liverpool \t\t\t\t') + str('d) Edinburgh \n') def qu2_keys(self): return str('a) 2 months \t\t\t\t') + str('b) 3 months \n') + str('c) 4 months \t\t\t\t') + str('d) 5 months \n') def qu3_keys(self): return str('a) vinum \t\t\t\t') + str('b) verba \n') + str('c) iuvat \t\t\t\t') + str('d) vici \n') def qu4_keys(self): return str('a) <NAME> \t\t\t\t\t') + str('\tb) <NAME> \n') + str('c) <NAME> \t\t\t\t') + str('d) <NAME> \n') def qu5_keys(self): return str('a) <NAME> \t\t\t\t') + str('b) <NAME> \n') + str('c) <NAME> \t\t\t') +str('d) <NAME> \n') class Input_class: def input_qu1(self): self._a = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>:') return self._a #this is internal attribute to the class Input_class def input_answer1(self): if self._a == 'London' or self._a == 'b' or self._a == 'b)' or self._a == 'london': return('\nLondon is the correct answer!!\n\n') + Correct_class.correct1() elif self._a == '1': return Lifeline1.q1lifeline1(self) elif self._a == '2': return Lifeline2.q1lifeline2(self) elif self._a == '3': return Lifeline3.q1lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 0 questions right (0/10 - miserable ' + 'performance) - Game Over!') def input_answer1lif(self): self._aa = input('Type your answer here >>>:') if self._aa == 'London' or self._aa == 'b' or self._aa == 'b)' or self._aa == 'london': return('\nLondon is the correct answer!!\n\n') + Correct_class.correct1() elif self._aa == '1': return Lifeline1.q1lifeline1(self) elif self._aa == '2': return Lifeline2.q1lifeline2(self) elif self._aa == '3': return Lifeline3.q1lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 0 questions right (0/10 - miserable ' + 'performance) - Game Over!') def input_qu2(self): self._b = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number - attention!' +' For lifeline 3 type "3+") here >>>:') return self._b def input_answer2(self): if self._b == '3 months' or self._b == '3' or self._b == 'b' or self._b == 'b)': return('\n3 months is the correct answer!!\n\n') + Correct_class.correct2() elif self._b == '1': return Lifeline1.q2lifeline1(self) elif self._b == '2': return Lifeline2.q2lifeline2(self) elif self._b == '3+': return Lifeline3.q2lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 1 question right (1/10 - poor performance)' + '- Game Over!') def input_answer2lif(self): self._bb = input('Type your answer here >>>:') if self._bb == '3 months' or self._bb == '3' or self._bb == 'b' or self._bb == 'b)': return ('\n3 months is the correct answer!!\n\n') + Correct_class.correct2() elif self._bb == '1': return Lifeline1.q2lifeline1(self) elif self._bb == '2': return Lifeline2.q2lifeline2(self) elif self._bb == '3+': return Lifeline3.q2lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 1 question right (1/10 - poor performance)' + '- Game Over!') def input_qu3(self): self._c = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>:') return self._c def input_answer3(self): if self._c == 'vici' or self._c == 'd' or self._c == 'd)': return('\nvici is the correct answer!!\n\n') + Correct_class.correct3() elif self._c == '1': return Lifeline1.q3lifeline1(self) elif self._c == '2': return Lifeline2.q3lifeline2(self) elif self._c == '3': return Lifeline3.q3lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 2 questions right (2/10 - meager performance)' + '- Game Over!') def input_answer3lif(self): self._cc = input('Type your answer here >>>:') if self._cc == 'vici' or self._cc == 'd' or self._cc == 'd)': return('\nvici is the correct answer!!\n\n') + Correct_class.correct3() elif self._cc == '1': return Lifeline1.q3lifeline1(self) elif self._cc == '2': return Lifeline2.q3lifeline2(self) elif self._cc == '3': return Lifeline3.q3lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 2 questions right (2/10 - meager performance)' + '- Game Over!') def input_qu4(self): self._d = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>:') return self._d def input_answer4(self): if self._d == '<NAME>' or self._d == 'Shakespeare' or self._d == 'c' or self._d == 'c)': return('\n<NAME> is the correct answer!!\n\n') + Correct_class.correct4() elif self._d == '1': return Lifeline1.q4lifeline1(self) elif self._d == '2': return Lifeline2.q4lifeline2(self) elif self._d == '3': return Lifeline3.q4lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 3 questions right (3/10 - inferior performance)' + '- Game Over!') def input_answer4lif(self): self._dd = input('Type your answer here >>>:') if self._dd == '<NAME>' or self._dd == 'Shakespeare' or self._dd == 'c' or self._dd == 'c)': return('\n<NAME> is the correct answer!!\n\n') + Correct_class.correct4() elif self._dd == '1': return Lifeline1.q4lifeline1(self) elif self._dd == '2': return Lifeline2.q4lifeline2(self) elif self._dd == '3': return Lifeline3.q4lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 3 questions right (3/10 - inferior performance)' + '- Game Over!') def input_qu5(self): self._e = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>:') return self._e def input_answer5(self): if self._e == '<NAME>' or self._e == 'von der Leyen' or self._e == 'der Leyen' or self._e == 'der leyen' or self._e =='c' or self._e == 'c)': return('\n<NAME> is the correct answer!!\n\n') + Correct_class.correct5() elif self._e == '1': return Lifeline1.q5lifeline1(self) elif self._e == '2': return Lifeline2.q5lifeline2(self) elif self._e == '3': return Lifeline3.q5lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 4 questions right (4/10 - insufficient performance)' + '- Game Over!') def input_answer5lif(self): self._ee = input('Type your answer here >>>:') if self._ee == '<NAME>' or self._ee == 'von der Leyen' or self._ee == 'der Leyen' or self._ee == 'der leyen' or self._ee =='c' or self._ee == 'c)': return('\n<NAME> is the correct answer!!\n\n') + Correct_class.correct5() elif self._ee == '1': return Lifeline1.q5lifeline1(self) elif self._ee == '2': return Lifeline2.q5lifeline2(self) elif self._ee == '3': return Lifeline3.q5lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You only answered 4 questions right (4/10 - insufficient performance)' + '- Game Over!') def input_next_question(self): self.next = input('Type your answer here >>>:') if self.next == 'Next' or self.next == 'next': pass else: exit('Sorry to see you go! I hope you had a good time!') class Correct_class: #for right answers @classmethod def correct1(cls): return str('Type "Next" to proceed to Question 2 or "Quit" to close the game.\n') @classmethod def correct2(cls): return str('Type "Next" to proceed to Question 3 or "Quit" to close the game.\n') @classmethod def correct3(cls): return str('Type "Next" to proceed to Question 4 or "Quit" to close the game.\n') @classmethod def correct4(cls): return str('Type "Next" to proceed to Question 5 or "Quit" to close the game.\n') @classmethod def correct5(cls): return str('Type "Next" to proceed to Question 6 or "Quit" to close the game.\n') #Lets do the next 2 questions on a different way class Questions: def __init__(self): self.quest6 = '\nQuestion 6\n' self.quest7 = '\nQuestion 7\n' def question6(self): return str('What is the name of a very popular fantasy drama series created by <NAME> and <NAME>?') def question7(self): return str('What year did the French Revolution begin?') def answer6(self): return str('a) Game of Thrones\t\t\t') + str('b) Lucifer\n') + str('c) Manifest\t\t\t\t\t') + str('d) The Witcher\n') def answer7(self): return str('a) 1786\t\t\t\t') + str('b) 1787\n') + str('c) 1788\t\t\t\t') + str('d) 1789\n') def input_q6(self): self._q6 = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>') if self._q6 == 'Game of Thrones' or self._q6 == 'a' or self._q6 == 'a)': self._answer6 = 'ok' elif self._q6 == '1': return Lifeline1.q6lifeline1(self) elif self._q6 == '2': return Lifeline2.q6lifeline2(self) elif self._q6 == '3': return Lifeline3.q6lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 5 questions right (5/10 - unsatisfactory ' + 'performance) ' + '- Game Over!') def input_q6lif(self): self._q6l = input('Type your answer here >>>') if self._q6l == 'Game of Thrones' or self._q6l == 'a' or self._q6l == 'a)': self._answer6 = 'ok' elif self._q6l == '1': return Lifeline1.q6lifeline1(self) elif self._q6l == '2': return Lifeline2.q6lifeline2(self) elif self._q6l == '3': return Lifeline3.q6lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 5 questions right (5/10 - unsatisfactory ' + 'performance) ' + '- Game Over!') def input_q7(self): self._q7 = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>') if self._q7 == '1789' or self._q7 == 'd' or self._q7 == 'd)': self._answer7 = 'ok' elif self._q7 == '1': return Lifeline1.q7lifeline1(self) elif self._q7 == '2': return Lifeline2.q7lifeline2(self) elif self._q7 == '3': return Lifeline3.q7lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 6 questions right (6/10 - inadequate ' + 'performance) ' + '- Game Over!') def input_q7lif(self): self._q7l = input('Type your answer here >>>') if self._q7l == '1789' or self._q7l == 'd' or self._q7l == 'd)': self._answer7 = 'ok' elif self._q7l == '1': return Lifeline1.q7lifeline1(self) elif self._q7l == '2': return Lifeline2.q7lifeline2(self) elif self._q7l == '3': return Lifeline3.q7lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 6 questions right (6/10 - inadequate ' + 'performance) ' + '- Game Over!') def correct6(self): if hasattr(self, '_answer6'): return str('\nGame of Thrones is the correct answer!!') + str('\n\nType "Next" to proceed to Question 7' + ' or "Quit" to close the game.\n') else: pass def correct7(self): if hasattr(self, '_answer7'): return str('\n1789 is the correct answer!!') + str('\n\nType "Next" to proceed to Question 7' + ' or "Quit" to close the game.\n') def next_one6(self): self.next6 = input('Type your answer here >>>') if self.next6 == 'Next' or self.next6 == 'next': return self.quest7 else: sys.exit('Sorry to see you go! I hope you had a good time!') def next_one7(self): self.next7 = input('Type your answer here >>>') if self.next7 == 'Next' or self.next7 == 'next': return str('') else: sys.exit('Sorry to see you go! I hope you had a good time!') #Lets do the next question via composition class Composite: def __init__(self, question, answers): self.question = question self.answers = answers class Question8: def __str__(self): return '\nQuestion 8\n' + '\nWho among the listed researchers is considered a pioneer in the field of perovskite solar cells?' class Answers: def __str__(self): return 'a) <NAME>\t\t\t\t\t' + 'b) <NAME>\n' + 'c) <NAME>\t\t\t\t' + 'd) <NAME>' def input(self): self.input8 = input('\nType your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>') if self.input8 == '<NAME>' or self.input8 == 'Snaith' or self.input8 == 'd' or self.input8 == 'd)': print('\n<NAME> is the correct answer!!' + '\n\nType "Next" to proceed to Question 7 ' + 'or "Quit" to close the game.\n') elif self.input8 == '1': return Lifeline1.q8lifeline1(self) elif self.input8 == '2': return Lifeline2.q8lifeline2(self) elif self.input8 == '3': return Lifeline3.q8lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 7 questions right (7/10 - acceptable performance)' + ' - Game Over!') def inputlif(self): self.input8l = input('\nType your answer here >>>') if self.input8l == '<NAME>' or self.input8l == 'Snaith' or self.input8l == 'd' or self.input8l == 'd)': print('\n<NAME> is the correct answer!!' + '\n\nType "Next" to proceed to Question 7 ' + 'or "Quit" to close the game.\n') elif self.input8l == '1': return Lifeline1.q8lifeline1(self) elif self.input8l == '2': return Lifeline2.q8lifeline2(self) elif self.input8l == '3': return Lifeline3.q8lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 7 questions right (7/10 - acceptable performance)' + ' - Game Over!') def proceed(self): self.proceed = input('Type your answer here >>>') if self.proceed == 'Next' or self.proceed == 'next': pass else: sys.exit('\nSorry to see you go! I hope you had a good time!') #Lets do the next question via inheritance class Question9: question = '\nQuestion 9\n' #class attribute def question9(self): return 'Which two software engineers created a cryptocurrency called Dogecoin?' def answer9(self): return 'a) <NAME> and <NAME>' + '\t\t\tb) <NAME> and <NAME>' + '\nc) <NAME> and <NAME>\t\t\t\t' + 'd) <NAME> and <NAME>\n' class Input9(Question9): def inp9(self): self.inp9 = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>:') if self.inp9 == '<NAME> and <NAME>' or self.inp9 == '<NAME>' or self.inp9 == 'a' or self.inp9 == 'a)': return '\<NAME> and <NAME> is the correct answer!!\n\n' + 'Type "Next" to proceed to the final Question' + ' or "Quit" to close the game.\n' elif self.inp9 == '1': return Lifeline1.q9lifeline1(self) elif self.inp9 == '2': return Lifeline2.q9lifeline2(self) elif self.inp9 == '3': return Lifeline3.q9lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 8 questions right (8/10 - excellent performance)' + ' - Game Over!') def inp9lif(self): self.inp9l = input('Type your answer here >>>:') if self.inp9l == '<NAME> <NAME>' or self.inp9l == '<NAME>' or self.inp9l == 'a' or self.inp9l == 'a)': return '\<NAME> and <NAME> is the correct answer!!\n\n' + 'Type "Next" to proceed to the final Question' + ' or "Quit" to close the game.\n' elif self.inp9l == '1': return Lifeline1.q9lifeline1(self) elif self.inp9l == '2': return Lifeline2.q9lifeline2(self) elif self.inp9l == '3': return Lifeline3.q9lifeline3(self) else: sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 8 questions right (8/10 - excellent performance)' + ' - Game Over!') def proceed9(self): self.proceed9 = input('Type your answer here >>>') if self.proceed9 == 'Next' or self.proceed9 == 'next': return ' ' else: sys.exit('Sorry to see you go! I hope you had a good time!') #Lets do the final question via magic methods class Attr: def __init__(self, name=None): self.name = name def __getattribute__(self, item): object.__getattribute__(self, item) return '\n<NAME> is the correct answer!!\n\n' + 'YOU JUST WON A MILLION $$$$$!!' + ' You answered 10 questions right (10/10 - outstanding performance)!!' + '\n\t\t\t\t\t\t\t\tWELL DONE AND CONGRATULATIONS!!' def __getattr__(self, item): return sys.exit('\nYour answer is wrong!!\n\n' + 'You answered 9 questions right (9/10 - phenomenal performance)' + ' - Game Over!') class Question10: #in attr class you can't have other methods def quest10(self): return 'Who was the first Byzantine emperor of the Justinian dynasty (518 - 602)?' def answ10(self): return 'a) Justinian I\t\t\t\t\t' + 'b) <NAME>\n' + 'c) Anastasius I\t\t\t\t\t' + 'd) <NAME>\n' def inp10lif(self): inpl = input('Type your answer here >>>') if inpl == 'b' or inpl == 'b)' or inpl == '<NAME>' or inpl == 'justin I': print('\n<NAME> is the correct answer!!\n\n' + 'YOU JUST WON A MILLION $$$$$!!' + ' You answered 10 questions right (10/10 - outstanding performance)!!' + '\n\t\t\t\t\t\t\t\tWELL DONE AND CONGRATULATIONS!!') elif inpl == '1': return Lifeline1.q10lifeline1(self) elif inpl == '2': return Lifeline2.q10lifeline2(self) elif inpl == '3': return Lifeline3.q10lifeline3(self) else: print('\nYour answer is wrong!!\n\n' + 'You answered 9 questions right (9/10 - phenomenal performance)' + ' - Game Over!') class Lifeline1: called = False def q1lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) / \t\t\t\t' + 'b) London \n' + 'c) / \t\t\t\t' + 'd) Edinburgh \n') time.sleep(1.5) return Input_class.input_answer1lif(self) def q2lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) / \t\t\t\t' + 'b) 3 months \n' + 'c) 4 months \t\t' + 'd) / \n') time.sleep(1.5) return Input_class.input_answer2lif(self) def q3lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) vinum \t\t\t' + 'b) / \n' + 'c) / \t\t\t\t' + 'd) vici \n') time.sleep(1.5) return Input_class.input_answer3lif(self) def q4lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) <NAME> \t\t\t\t\t' + '\tb) / \n' + 'c) <NAME> \t\t\t\t' + 'd) / \n') time.sleep(1.5) return Input_class.input_answer4lif(self) def q5lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) / \t\t\t\t\t\t\t\t' + 'b) <NAME> \n' + 'c) <NAME> \t\t\t' + 'd) / \n') time.sleep(1.5) return Input_class.input_answer5lif(self) def q6lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) Game of Thrones\t\t\t' + 'b) Lucifer\n' + 'c) /\t\t\t\t\t\t' + 'd) /\n') time.sleep(1.5) return Questions.input_q6lif(self) def q7lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) /\t\t\t\t' + 'b) 1787\n' + 'c) /\t\t\t\t' + 'd) 1789\n') time.sleep(1.5) return Questions.input_q7lif(self) def q8lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) /\t\t\t\t' + 'b) <NAME>\n' + 'c) /\t\t\t\t' + 'd) <NAME>') time.sleep(1.5) return Answers.inputlif(self) def q9lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) <NAME> and <NAME>' + '\t\t\tb) /' + '\nc) <NAME> and <NAME>\t\t\t\t' + 'd) /\n') time.sleep(1.5) return Input9.inp9lif(self) def q10lifeline1(self): if Lifeline1.called: raise Exception("Lifeline 1 may only be used once") Lifeline1.called = True print('\nLifeline 1 (50:50) called!\n\n' \ + 'a) <NAME>\t\t\t' + 'b) <NAME>\n' + 'c) /\t\t\t\t\t' + 'd) /\n') time.sleep(1.5) return Question10.inp10lif(self) class Lifeline2: called = False def q1lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True a = random.randrange(1,5,1) b = random.randrange(70,80,1) c = random.randrange(10,13,1) d = random.randrange(1,2,1) e = 100 f = e-a-b-c-d print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t\t'.format(a) + 'b) {}% \n'.format(b) + 'c) {}% \t\t\t\t'.format(d) + 'd) {}% \n'.format(c+f)) time.sleep(1.5) return Input_class.input_answer1lif(self) def q2lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(20,23,1) h = random.randrange(45,60,1) i = random.randrange(10,14,1) j = random.randrange(1,3,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t\t'.format(g) + 'b) {}% \n'.format(h) + 'c) {}% \t\t\t\t'.format(i+l) + 'd) {}% \n'.format(j)) time.sleep(1.5) return Input_class.input_answer2lif(self) def q3lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(10,20,1) h = random.randrange(8,10,1) i = random.randrange(2,5,1) j = random.randrange(55,65,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t\t'.format(g) + 'b) {}% \n'.format(h+l) + 'c) {}% \t\t\t\t'.format(i) + 'd) {}% \n'.format(j)) time.sleep(1.5) return Input_class.input_answer3lif(self) def q4lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(20,29,1) h = random.randrange(23,29,1) i = random.randrange(30,39,1) j = random.randrange(1,3,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t'.format(g) + '\tb) {}% \n'.format(h) + 'c) {}% \t\t\t\t'.format(i) + 'd) {}% \n'.format(j+l)) time.sleep(1.5) return Input_class.input_answer4lif(self) def q5lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(20,29,1) h = random.randrange(23,30,1) i = random.randrange(29,38,1) j = random.randrange(1,3,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t'.format(g) + 'b) {}% \n'.format(h) + 'c) {}% \t\t\t'.format(i) + 'd) {}% \n'.format(j+l)) time.sleep(1.5) return Input_class.input_answer5lif(self) def q6lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(30,35,1) h = random.randrange(23,30,1) i = random.randrange(20,25,1) j = random.randrange(5,10,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}%\t\t\t'.format(g+l) + 'b) {}%\n'.format(h) + 'c) {}%\t\t\t'.format(i) + 'd) {}%\n'.format(j)) time.sleep(1.5) return Questions.input_q6lif(self) def q7lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(5,10,1) h = random.randrange(23,30,1) i = random.randrange(20,30,1) j = random.randrange(25,30,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}%\t\t\t\t'.format(g+l) + 'b) {}%\n'.format(h) + 'c) {}%\t\t\t\t'.format(i) + 'd) {}%\n'.format(j)) time.sleep(1.5) return Questions.input_q7lif(self) def q8lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(5,10,1) h = random.randrange(23,25,1) i = random.randrange(20,30,1) j = random.randrange(25,35,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}%\t\t\t\t'.format(g+l) + 'b) {}%\n'.format(h) + 'c) {}%\t\t\t\t'.format(i) + 'd) {}%'.format(j)) time.sleep(1.5) return Answers.inputlif(self) def q9lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(20,25,1) h = random.randrange(20,25,1) i = random.randrange(20,25,1) j = random.randrange(20,25,1) k = 100 l = (k-g-h-i-j) print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}%'.format(g) + '\t\t\tb) {}%'.format(h+l) + '\nc) {}%\t\t\t'.format(i) + 'd) {}%\n'.format(j)) time.sleep(1.5) return Input9.inp9lif(self) def q10lifeline2(self): if Lifeline2.called: raise Exception("Lifeline 2 may only be used once") Lifeline2.called = True g = random.randrange(15,25,1) h = random.randrange(15,25,1) i = random.randrange(15,25,1) j = random.randrange(15,25,1) k = 100 l = k-g-h-i-j print('\nLifeline 2 - Ask The Audience - called!\n\n' \ + 'a) {}% \t\t\t\t\t'.format(g) + 'b) {}% \n'.format(h) + 'c) {}% \t\t\t\t\t'.format(i) + 'd) {}% \n'.format(j+l)) time.sleep(1.5) return Question10.inp10lif(self) class Lifeline3: called = False def q1lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') a = '{}: Hello Father, how are you?\n\n'.format(Question_class.name1) + '{}: Good afternoon! Who is calling?\n\n'.format(Question_class.name3)\ + "{}: It is me, {}! I need your help with the 1st question!\n\n".format(Question_class.name1, Question_class.name1) \ + '{}: With the first question?!?! You must be joking!\n\n'.format(Question_class.name3) \ + '{}: Unfortunately, I am not! What is the capital city of England?\n\n'.format(Question_class.name1) \ + '{}: Shameful that you must ask for that! It is London!!\n\n'.format(Question_class.name3) for q1l3 in a: sys.stdout.write(q1l3) sys.stdout.flush() time.sleep(0.2) return Input_class.input_answer1lif(self) def q2lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') b = '{}: Hi Mother, it is me {}!\n\n'.format(Question_class.name1, Question_class.name1) + '{}: {}! Where are you? Did you make it to the game?\n\n'.format(Question_class.name2, Question_class.name1) \ + '{}: Yes, I did! However, I am stuck at the second question!\n\n'.format(Question_class.name1) \ + '{}: You need my help at the second question?? That is pathetic!\n\n'.format(Question_class.name2) \ + '{}: How many months are in summer season?\n\n'.format(Question_class.name1) + "{}: Don't know whether I should laugh or cry! There are 3!!\n\n".format(Question_class.name2) for q2l3 in b: sys.stdout.write(q2l3) sys.stdout.flush() time.sleep(0.2) return Input_class.input_answer2lif(self) def q3lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') c = '{}: Hi {}! It is me, {}!\n\n'.format(Question_class.name1, Question_class.name4, Question_class.name1) \ + '{}: {}!! How is it going?\n\n'.format(Question_class.name4, Question_class.name1) + '{}: Not too bad! I need your help. I made it to the game!\n\n'.format(Question_class.name1) \ + '{}: Wow! Amazing! I will try to help!\n\n'.format(Question_class.name4) + '{}: veni, vidi, what is next?\n\n'.format(Question_class.name1) \ + '{}: As <NAME> used to say: veni, vidi, vici!\n\n'.format(Question_class.name4) for q3l3 in c: sys.stdout.write(q3l3) sys.stdout.flush() time.sleep(0.2) return Input_class.input_answer3lif(self) def q4lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') d = '{}: Hi Father! I am at the game and don\'t know an answer to the question!\n\n'.format(Question_class.name1) \ + '{}: How far have you come?\n\n'.format(Question_class.name3) + '{}: I am at the fourth question.\n\n'.format(Question_class.name1) \ + '{}: A bit early to use a lifeline!\n\n'.format(Question_class.name3) + '{}: Who wrote Hamlet and Macbeth?\n\n'.format(Question_class.name1) \ + '{}: I assume that you would have known that! It\'s Shakespeare!\n\n'.format(Question_class.name3) + '{}: Cheers!\n\n'.format(Question_class.name1) for q4l3 in d: sys.stdout.write(q4l3) sys.stdout.flush() time.sleep(0.2) return Input_class.input_answer4lif(self) def q5lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') e = '{}: Am I speaking to {}?\n\n'.format(Question_class.name1, Question_class.name4) + '{}: Yes {}, {} speaking!\n\n'.format(Question_class.name4, Question_class.name1, Question_class.name4) \ + '{}: I need help with the fifth question at Who Wants to be a Millionaire!\n\n'.format(Question_class.name1) \ + '{}: Sounds good! Let\'s see what I can do.\n\n'.format(Question_class.name4) \ + '{}: The current president of the European Commission? der Leyen or Michel?\n\n'.format(Question_class.name1) \ + '{}: Mhmmm, I think it is Ursula von der Leyen.\n\n'.format(Question_class.name4) for q5l3 in e: sys.stdout.write(q5l3) sys.stdout.flush() time.sleep(0.2) return Input_class.input_answer5lif(self) def q6lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') f = '{}: Hello {}, I think that you could know the question that I am struggling with.\n\n'.format(Question_class.name1, Question_class.name4) \ + '{}: Who is calling?\n\n'.format(Question_class.name4) + '{}: It is me, {}!\n\n'.format(Question_class.name1, Question_class.name1) \ + '{}: Hi {}! Sounds good! Let me know what you need!\n\n'.format(Question_class.name4, Question_class.name1) \ + '{}: Do you know about that famous series that was created by Weiss and Benioff?\n\n'.format(Question_class.name1) \ + '{}: Mhmm, do you mean Lucifer?\n\n'.format(Question_class.name4) \ + '{}: I think that is wrong. I believe it is the Game of Thrones?\n\n'.format(Question_class.name1) \ + '{}: Yes, it might be!\n\n'.format(Question_class.name4) for q6l3 in f: sys.stdout.write(q6l3) sys.stdout.flush() time.sleep(0.2) return Questions.input_q6lif(self) def q7lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') g = '{}: Mom, {} here!\n\n'.format(Question_class.name1, Question_class.name1) + '{}: {}! Nice to hear from you!\n\n'.format(Question_class.name2, Question_class.name1) \ + '{}: Since you know history, you might be helpful with this question!\n\n'.format(Question_class.name1) \ + '{}: Ok.\n\n'.format(Question_class.name2) + '{}: French Revolution! What year did it start?\n\n'.format(Question_class.name1) \ + '{}: That is a tough one! I think one of the two: 1787 or 1789!\n\n'.format(Question_class.name2) for q7l3 in g: sys.stdout.write(q7l3) sys.stdout.flush() time.sleep(0.2) return Questions.input_q7lif(self) def q8lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') h = '{}: Hey mate! It is me, {}!\n\n'.format(Question_class.name1, Question_class.name1) + '{}: {}!! Are you participating in the game?\n\n'.format(Question_class.name4, Question_class.name1) \ + '{}: That is correct! Who started with perovskite solar cells? I think it is one of Goodenough, Yaghi or Snaith?\n\n'.format(Question_class.name1) \ + '{}: Sorry, but I have no idea!! I know it has started in Oxford though!\n\n'.format(Question_class.name4) for q8l3 in h: sys.stdout.write(q8l3) sys.stdout.flush() time.sleep(0.2) return Answers.inputlif(self) def q9lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') j = '{}: Hi Father! I need your help! I am at the ninth question!\n\n'.format(Question_class.name1) \ + '{}: Amazing! You will be a millionaire!! I am proud of you!\n\n'.format(Question_class.name3) \ + '{}: Who created Dogecoin?\n\n'.format(Question_class.name1) + '{}: Dogecoin to the moon! Elon Musk\'s favourite crypto!\n\n'.format(Question_class.name3) \ + '{}: Was it Nakamoto?\n\n'.format(Question_class.name1) + '{}: Nah, that was Bitcoin!\n\n'.format(Question_class.name3) + '{}: Then who was it?\n\n'.format(Question_class.name1) \ + '{}: Mhm, I know there were two guys but don\'t know which ones! Sorry!\n\n'.format(Question_class.name3) for q9l3 in j: sys.stdout.write(q9l3) sys.stdout.flush() time.sleep(0.2) return Input9.inp9lif(self) def q10lifeline3(self): if Lifeline3.called: raise Exception("Lifeline 3 may only be used once") Lifeline3.called = True print('\nLifeline 3 (call) called!\n\n') k = '{}: Good evening mother! I am at the last question!!\n\n'.format(Question_class.name1) \ + '{}: That\'s insane! How did you manage to come that far?\n\n'.format(Question_class.name2) \ + '{}: I struggle with the last one! It\'s ridiculous!\n\n'.format(Question_class.name1) \ + '{}: I can imagine!\n\n'.format(Question_class.name2) + '{}: The first Byzantine emperor of the Justinian dynasty?\n\n'.format(Question_class.name1) \ + '{}: I have no idea! Good luck!\n\n'.format(Question_class.name2) for q10l3 in k: sys.stdout.write(q10l3) sys.stdout.flush() time.sleep(0.2) return Question10.inp10lif(self) def main(): object1 = Question_class(q1='What is the capital city of England?', q2='How many months are in summer ' + 'season (Northern Hemisphere)?', q3='Continue the following Latin phrase: veni, vidi,', q4='Who wrote the famous plays Hamlet and Macbeth?', q5='Who is the current President ' + 'of the European Commission?') object2 = Key_class() object3 = Input_class() object4 = Correct_class() object5 = Questions() object6 = Question8() object7 = Answers() object8 = Composite(object6, object7) object9 = Input9() object10 = Attr() object11 = Question10() object12 = Lifeline1() object13 = Lifeline2() object14 = Lifeline3() print(object1.qu1()) print(object2.qu1_keys()) object3.input_qu1() print(object3.input_answer1()) object3.input_next_question() print(object1.qu2()) #you can't call **kwargs (e.g. self.q2 in def qu2()) inside the method print(object2.qu2_keys()) object3.input_qu2() print(object3.input_answer2()) object3.input_next_question() print(object1.qu3()) print(object2.qu3_keys()) object3.input_qu3() print(object3.input_answer3()) object3.input_next_question() print(object1.qu4()) print(object2.qu4_keys()) object3.input_qu4() print(object3.input_answer4()) object3.input_next_question() print(object1.qu5()) print(object2.qu5_keys()) object3.input_qu5() print(object3.input_answer5()) object3.input_next_question() print(object5.quest6) print(object5.question6()) print(object5.answer6()) object5.input_q6() print(object5.correct6()) print(object5.next_one6()) print(object5.question7()) print(object5.answer7()) object5.input_q7() print(object5.correct7()) print(object5.next_one7()) print(object8.question) print(object8.answers) object7.input() object7.proceed() print(getattr(object9, 'question')) print(object9.question9()) print(object9.answer9()) print(object9.inp9()) print(object9.proceed9()) print('\nQuestion 10\n') print(object11.quest10()) print(object11.answ10()) inp = input('Type your answer (for lifelines 1 (50:50), 2 (ask the audience) or 3 (call) type the number) here >>>') if inp == 'b' or inp == 'b)' or inp == '<NAME>' or inp == '<NAME>': print(object10.name) elif inp == '1': return object12.q10lifeline1() elif inp == '2': return object13.q10lifeline2() elif inp == '3': return object14.q10lifeline3() else: print(object10.nothing) if __name__ == '__main__': main()
28d8b35dc23075e57a05bd053db6b206ebe143f8
[ "Markdown", "Python" ]
2
Markdown
FA-MatSci/Who-wants-to-be-a-millionaire-
089c1fdc39cb565f5fe770dd7b8ba5b4092aee01
aa503d8f86f4079c8ba7bc6d5879252141519ee4
refs/heads/master
<repo_name>tht/jeelib<file_sep>/examples/RF12/smaRelay/smaRelay.ino /// @dir smaRelay /// Read out SMA solar inverter via Bluetooth and relay readings using RFM12B. /// @see http://jeelabs.org/2012/11/06/accessing-the-sma-inverter-via-bluetooth/ /// @see http://jeelabs.org/2012/11/07/relaying-sma-data-as-rf12-packets/ // 2012-11-04 <<EMAIL>> http://opensource.org/licenses/mit-license.php #include <JeeLib.h> #define LED 9 // inverted logic // this is the main driver, it calls the getByte() and) emitFinal() functions #include "smaComms.h" struct { word yield, total, acw, dcv[2], dcw[2]; } payload; byte myAddrBT[] = { 0xCA,0xC2,0x46,0x66,0x06,0x00 }; // @TODO obtain from rn42 MilliTimer sendTimer; ISR(WDT_vect) { Sleepy::watchdogEvent(); } static byte getByte () { #if LED pinMode(LED, OUTPUT); digitalWrite(LED, 0); #endif while (!Serial.available()) ; #if LED digitalWrite(LED, 1); #endif return Serial.read(); } static void emitFinal () { // fill in packet length and prefix check packetBuf[1] = fill - packetBuf; packetBuf[3] = packetBuf[0] ^ packetBuf[1]; // send the packet out for (byte i = 0; i < fill - packetBuf; ++i) Serial.write(packetBuf[i]); } static void initBluetooth (word baud) { Serial.begin(baud); delay(1000); Serial.print("$$$"); // enter command mode delay(100); Serial.println("C"); // connect to saved remote address delay(100); Serial.println("F,1"); // leave command mode } static void getSmaData () { memset(&payload, 0, sizeof payload); payload.yield = dailyYield(); // Wh payload.total = totalPower() / 1000; // kWh payload.acw = acPowerNow(); // W dcVoltsNow(payload.dcv); // V * 100 dcPowerNow(payload.dcw); // W } void setup () { rf12_initialize(15, RF12_868MHZ, 5); initBluetooth(19200); smaInitAndLogin(myAddrBT); } void loop () { if (sendTimer.poll(10000)) { getSmaData(); rf12_sleep(RF12_WAKEUP); while (!rf12_canSend()) rf12_recvDone(); rf12_sendStart(0, &payload, sizeof payload); rf12_sendWait(2); rf12_sleep(RF12_SLEEP); } Sleepy::loseSomeTime(sendTimer.remaining()); }
e72f2834ca4b897162423b0f43f498563016311e
[ "C++" ]
1
C++
tht/jeelib
28808ab459ce89176626bc214f9b66a0294db754
f50ba908c695274f31c5eaeac291776ae1bd3b16
refs/heads/master
<repo_name>chainlinq/boatkeeper<file_sep>/src/boatkeeper.c /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Main source file for Boat Keeper. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://github.com/chainlinq/boatkeeper/blob/master/LICENSE * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations * under the License. */ /* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <limits.h> #include <string.h> #include "aws_iot_log.h" #include "aws_iot_version.h" #include "aws_iot_mqtt_client_interface.h" #include "ai_aws_iot.h" #include "ai_boatkeeper_pi.h" /** * This parameter will avoid infinite loop of publish and exit the program after certain number of publishes */ //TODO: find a way to pass this with argv and still set the argv's in ai_aws_iot.c uint32_t g_publish_count = 2; int main(int argc, char **argv) { bool infinite_publish_flag = true; int32_t i = 0; IoT_Error_t rc = FAILURE; IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); const char * p_serial_number = read_serial_number(); AWS_IoT_Client client; IoT_Client_Init_Params mqtt_init_params = iotClientInitParamsDefault; rc = init_mqtt(argc, argv, &client, &mqtt_init_params); if (SUCCESS != rc) { IOT_ERROR("init_mqtt returned error : %d ", rc); return rc; } IOT_INFO("Connecting..."); IoT_Client_Connect_Params connect_params = iotClientConnectParamsDefault; rc = mqtt_connect( &client, &connect_params, p_serial_number); if (SUCCESS != rc) { IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqtt_init_params.pHostURL, mqtt_init_params.port); return rc; } /* * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL */ rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); if (SUCCESS != rc) { IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); return rc; } /* IOT_INFO("Subscribing..."); rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, subscribe_callback_handler, NULL); if(SUCCESS != rc) { IOT_ERROR("Error subscribing : %d ", rc); return rc; } */ if (g_publish_count != 0) { infinite_publish_flag = false; } while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) && (g_publish_count > 0 || infinite_publish_flag)) { //Max time the yield function will wait for read messages rc = aws_iot_mqtt_yield(&client, 100); if(NETWORK_ATTEMPTING_RECONNECT == rc) { // If the client is attempting to reconnect we will skip the rest of the loop. continue; } IOT_INFO("-->sleep"); sleep(10); rc = publish_shore_power_status ( &client, QOS1); if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { IOT_WARN("QOS1 publish ack not received.\n"); rc = SUCCESS; } if(g_publish_count > 0) { g_publish_count--; } } if(SUCCESS != rc) { IOT_ERROR("An error occurred in the loop.\n"); } else { IOT_INFO("Publish done\n"); } return rc; } <file_sep>/src/ai_boatkeeper_pi.c /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Source file for Boat Keeper on a Raspberry Pi. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://github.com/chainlinq/boatkeeper/blob/master/LICENSE * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations * under the License. */ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include <time.h> #include "aws_iot_log.h" #include "aws_iot_mqtt_client_interface.h" #include "ai_aws_iot.h" #include "ai_boatkeeper_pi.h" char g_serial_number[SERIAL_NUMBER_LENGTH] = DUMMY_SERIAL_NUMBER; const char * read_serial_number () { FILE * p_file; p_file = fopen( RASPBERRYPI_SERIAL_NUMBER_FILENAME, "r"); if (p_file == NULL) // if did not open, alert and use the default number { IOT_ERROR("Failed to open serial number file - %s", RASPBERRYPI_SERIAL_NUMBER_FILENAME); } else { char line_buffer [1024]; char * number_line; size_t bytes_read; bool keep_reading = true; do { bytes_read = fread( line_buffer, 1, sizeof (line_buffer)-1, p_file); if (bytes_read == 0) { IOT_ERROR("Failed to read serial number file - %s", RASPBERRYPI_SERIAL_NUMBER_FILENAME); keep_reading = false; } else { number_line = strstr(line_buffer, "Serial"); if (number_line != NULL) { char * number; // Line is something like "Serial : 999999" // To get the number find ':' and work towards the number number = strchr( number_line, ':'); if (number == NULL) { IOT_ERROR("Failed to find serial number deliminater ':'"); keep_reading = false; } else { // move off ':' number++; //strip leading white space while ( isspace((unsigned char)*number)) number++; // replace CRLF (if any) with NULL number[strcspn(number, "\r\n")] = 0; // copy number into g_serial_number strcpy ( g_serial_number, number); keep_reading = false; } } } } while (keep_reading); } IOT_INFO("Serial Number - %s", g_serial_number); return g_serial_number; } IoT_Error_t publish_shore_power_status (AWS_IoT_Client *p_client, QoS qos) { IoT_Error_t result = FAILURE; char payload[100]; const char * p_shore_power_status_string = read_shore_power_status_string(); time_t raw_time; time(&raw_time); sprintf( payload, "{ \"serial_number\": \"%s\", \"shore_power\": \"%s\", \"timestamp\":\"%ld\" }", g_serial_number, p_shore_power_status_string, raw_time); result = mqtt_publish ( p_client, qos, payload, AI_BOATKEEPER_STATUS_TOPIC); return result; } <file_sep>/src/ai_boatkeeper_pi.h /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Include file for Boat Keeper on a Raspberry Pi. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://github.com/chainlinq/boatkeeper/blob/master/LICENSE * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations * under the License. */ #ifndef AI_BOATKEEPER_PI_H_ #define AI_BOATKEEPER_PI_H_ // Serial number on a Raspberry Pi is stored in the 'cpuinfo' file and // is 16 chars long #define RASPBERRYPI_SERIAL_NUMBER_FILENAME "/proc/cpuinfo" #define DUMMY_SERIAL_NUMBER "DUMMY_SERIAL_NUM" #define SERIAL_NUMBER_LENGTH 17 // 16 digit serial number plus NULL #define AI_BOATKEEPER_STATUS_TOPIC "boatkeeper/status" const char * read_serial_number(); IoT_Error_t publish_shore_power_status (AWS_IoT_Client *p_client, QoS qos); #endif /* AI_BOATKEEPER_PI_H */ <file_sep>/src/ai_aws_iot.h /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Main include file for communicationg with AWS IoT. * * Mostly taken from AWS example published by Amazon, modified as needed. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://github.com/chainlinq/boatkeeper/blob/master/LICENSE * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations * under the License. */ #ifndef AI_AWS_IOT_H_ #define AI_AWS_IOT_H_ void subscribe_callback_handler (AWS_IoT_Client * p_client, char * p_topic_name, uint16_t topic_name_len, IoT_Publish_Message_Params * p_params, void * p_data); void disconnect_callback_handler (AWS_IoT_Client * p_client, void * p_data); void parse_input_args_for_connect_params(int argc, char **argv); IoT_Error_t init_mqtt (int argc, char **argv, AWS_IoT_Client * p_client, IoT_Client_Init_Params * p_mqtt_init_params); IoT_Error_t mqtt_connect (AWS_IoT_Client * p_client, IoT_Client_Connect_Params * p_connect_params, const char * p_serial_number); IoT_Error_t mqtt_publish (AWS_IoT_Client *p_client, QoS qos, const char *p_payload, const char *p_topic_name); #endif /* AI_AWS_IOT_H_ */ <file_sep>/src/ai_power_sensor.h /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Header file for dummy holder power sensor. Used for testing the rest * of the system * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef AI_POWER_SENSOR_H_ #define AI_POWER_SENSOR_H_ typedef enum { power_undefined, power_off, power_on } Power_Status_t; const char * g_power_status_strings[] = {"Undefined", "Off", "On" }; // Forward method declarations void toggle_shore_power_status (); Power_Status_t read_shore_power_status (); const char * read_shore_power_status_string (); #endif /* AI_POWER_SENSOR_H_ */ <file_sep>/README.md # Boat Keeper Provide remote monitoring of a boat using a Raspberry Pi and AWS. Written in Embedded-C. ## Version 0.0.1 This version will connect to your AWS IoT account and publish 2 status messages for shore power. Shore power detection has not been implemented so shore power status is "undefined" ## Authors * **<NAME>** - *Initial work* - [chainlinq](https://github.com/chainlinq) ## License This project is licensed under the Apache 2 License - see the [LICENSE.md](LICENSE) file for details <file_sep>/src/ai_aws_iot.c /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Main source file for communicationg with AWS IoT. * * Mostly taking from AWS example published by Amazon, modified as needed. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://github.com/chainlinq/boatkeeper/blob/master/LICENSE * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations * under the License. */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <limits.h> #include <string.h> #include "aws_iot_config.h" #include "aws_iot_log.h" #include "aws_iot_version.h" #include "aws_iot_mqtt_client_interface.h" #include "ai_aws_iot.h" /** * @brief Default cert location */ char g_cert_directory[PATH_MAX + 1] = "/../../.aws"; /** * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h */ char g_host_address[255] = AWS_IOT_MQTT_HOST; /** * @brief Default MQTT port is pulled from the aws_iot_config.h */ uint32_t g_port = AWS_IOT_MQTT_PORT; void subscribe_callback_handler (AWS_IoT_Client *p_client, char *p_topic_name, uint16_t topic_name_len, IoT_Publish_Message_Params *p_params, void *p_data) { IOT_UNUSED(p_data); IOT_UNUSED(p_client); IOT_INFO("Subscribe callback"); IOT_INFO("%.*s\t%.*s", topic_name_len, p_topic_name, (int) p_params->payloadLen, (char*)(p_params->payload)); } void disconnect_callback_handler (AWS_IoT_Client *p_client, void *p_data) { IOT_WARN("MQTT Disconnect"); IoT_Error_t rc = FAILURE; if (NULL == p_client) { return; } IOT_UNUSED(p_data); if (aws_iot_is_autoreconnect_enabled(p_client)) { IOT_INFO("Auto Reconnect is enabled, Reconnecting attempt will start now"); } else { IOT_WARN("Auto Reconnect not enabled. Starting manual reconnect..."); rc = aws_iot_mqtt_attempt_reconnect(p_client); if (NETWORK_RECONNECTED == rc) { IOT_WARN("Manual Reconnect Successful"); } else { IOT_WARN("Manual Reconnect Failed - %d", rc); } } } //TODO: add ability to pass cert, root_CA and client ID names void parse_input_args_for_connect_params(int argc, char **argv) { int opt; while(-1 != (opt = getopt(argc, argv, "h:p:c:x:"))) { switch(opt) { case 'h': strcpy(g_host_address, optarg); IOT_DEBUG("Host %s", optarg); break; case 'p': g_port = atoi(optarg); IOT_DEBUG("arg %s", optarg); break; case 'c': strcpy(g_cert_directory, optarg); IOT_DEBUG("cert root directory %s", optarg); break; /* left here for example, needs to be added to calling main program case 'x': m_publish_count = atoi(optarg); IOT_DEBUG("publish %s times\n", optarg); break; */ case '?': if(optopt == 'c') { IOT_ERROR("Option -%c requires an argument.", optopt); } else if(isprint(optopt)) { IOT_WARN("Unknown option `-%c'.", optopt); } else { IOT_WARN("Unknown option character `\\x%x'.", optopt); } break; default: IOT_ERROR("Error in command line argument parsing"); break; } } } IoT_Error_t init_mqtt (int argc, char **argv, AWS_IoT_Client * p_client, IoT_Client_Init_Params * p_mqtt_init_params) { IoT_Error_t rc = FAILURE; char root_CA[PATH_MAX + 1]; char client_CRT[PATH_MAX + 1]; char client_key[PATH_MAX + 1]; char current_working_dir[PATH_MAX + 1]; parse_input_args_for_connect_params(argc, argv); getcwd(current_working_dir, sizeof(current_working_dir)); snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", current_working_dir, g_cert_directory, AWS_IOT_ROOT_CA_FILENAME); snprintf(client_CRT, PATH_MAX + 1, "%s/%s/%s", current_working_dir, g_cert_directory, AWS_IOT_CERTIFICATE_FILENAME); snprintf(client_key, PATH_MAX + 1, "%s/%s/%s", current_working_dir, g_cert_directory, AWS_IOT_PRIVATE_KEY_FILENAME); IOT_DEBUG("root_CA %s", root_CA); IOT_DEBUG("client_CRT %s", client_CRT); IOT_DEBUG("client_key %s", client_key); p_mqtt_init_params->enableAutoReconnect = false; // We enable this later below p_mqtt_init_params->pHostURL = g_host_address; p_mqtt_init_params->port = g_port; p_mqtt_init_params->pRootCALocation = root_CA; p_mqtt_init_params->pDeviceCertLocation = client_CRT; p_mqtt_init_params->pDevicePrivateKeyLocation = client_key; p_mqtt_init_params->mqttCommandTimeout_ms = 20000; p_mqtt_init_params->tlsHandshakeTimeout_ms = 5000; p_mqtt_init_params->isSSLHostnameVerify = true; p_mqtt_init_params->disconnectHandler = disconnect_callback_handler; p_mqtt_init_params->disconnectHandlerData = NULL; rc = aws_iot_mqtt_init( p_client, p_mqtt_init_params); return rc; } IoT_Error_t mqtt_connect (AWS_IoT_Client * p_client, IoT_Client_Connect_Params * p_connect_params, const char * p_client_id) { IoT_Error_t rc = FAILURE; p_connect_params->keepAliveIntervalInSec = 10; p_connect_params->isCleanSession = true; p_connect_params->MQTTVersion = MQTT_3_1_1; p_connect_params->pClientID = p_client_id; p_connect_params->clientIDLen = (uint16_t) strlen(p_client_id); p_connect_params->isWillMsgPresent = false; IOT_INFO("Connecting"); rc = aws_iot_mqtt_connect(p_client, p_connect_params); return rc; } IoT_Error_t mqtt_publish (AWS_IoT_Client *p_client, QoS qos, const char *p_payload, const char *p_topic_name) { IoT_Error_t rc = FAILURE; IoT_Publish_Message_Params params; params.qos = qos; params.payload = (void *) p_payload; params.isRetained = 0; params.payloadLen = strlen(p_payload); IOT_INFO("Publishing %s", p_topic_name); rc = aws_iot_mqtt_publish( p_client, p_topic_name, strlen(p_topic_name), &params); return rc; } <file_sep>/src/ai_power_sensor.c /* * Copyright © 2017 Astonish Inc. All Rights Reserved. * * Source file for dummy holder power sensor. Used for testing the rest * of the system * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "ai_power_sensor.h" Power_Status_t g_power_status = power_undefined; void toggle_shore_power_status () { if (g_power_status == power_on) { g_power_status = power_off; } // If power status is undefined or off, set it to on else { g_power_status = power_on; } } Power_Status_t read_shore_power_status () { return g_power_status; } const char * read_shore_power_status_string () { return g_power_status_strings[g_power_status]; }
ff5c918dd4c5b32dbed60fd749f709ef104aa08f
[ "Markdown", "C" ]
8
C
chainlinq/boatkeeper
802f788242166deefef94fb62aae098a70698e61
9ef5fc5ed32f48b0beade1037eb18349840c96c1
refs/heads/master
<file_sep># basic-color-classifier Basic color recognition based on KNN algorithm. It reads the very first pixel of the provided PNG image and predicts its color. ### How to use it? Before you can use this classifier you have to create the training data file. Once it's created it doesn't need to be regenerated unless the training dataset has changed. To create the training data file run: ```sbtshell $ node index.js --build ``` Once it's done, there should be created `training.data` file in the current working directory. Then, just put some images directly into the `./test-dataset/` directory and then run ```sbtshell $ node index.js ``` In the result you will see the list of your files followed by the predicted color. #### Notice: At the moment this classifier can predict only following colors: black, blue, green, pink, red and white. If you want to make it classify more colors simply create more samples and place them into the `./training-dataset/` similarly as they are placed now. After that, remember to regenerate the training data file as described above.<file_sep>'use strict'; const ColorClassifier = require('./utils/color-classifier'); const createTrainingData = require('./utils/create-training-data'); const [,, build] = process.argv; if (!!build && build === '--build') { createTrainingData(); } else { const cc = new ColorClassifier(); cc.predictColors(); } <file_sep>'use strict'; const fs = require('fs'); const PNG = require('png-js'); const config = require('../config'); function createTrainingData() { const dirs = getTrainingDirs(); dirs.forEach((dir) => { const images = getImages(dir); images.forEach((image) => { if (!image.endsWith('.png')) { console.log(`File ${image} doesn't seem to be PNG file. Skipping...`); return; } getRGB(dir, image, (inputVector) => { fs.appendFileSync(config.trainingDataFile, `${inputVector.join(',')},${dir}\n`); }); }); }); } function getTrainingDirs() { return fs.readdirSync(config.trainingDatasetDir, { encoding: 'utf8' }); } function getImages(dir) { return fs.readdirSync(`${config.trainingDatasetDir}/${dir}`, { encoding: 'utf8' }); } function getRGB(dir, image, callback) { PNG.decode(`${config.trainingDatasetDir}/${dir}/${image}`, (pixels) => { callback([pixels[0], pixels[1], pixels[2]]); }); } module.exports = createTrainingData; <file_sep>'use strict'; const fs = require('fs'); const PNG = require('png-js'); const config = require('../config'); class ColorClassifier { constructor () { this.inputs = []; this.outputs = []; this.loadFeatures(); } loadFeatures() { let features = ''; try { features = fs.readFileSync(config.trainingDataFile, 'utf8'); } catch (e) { console.log('Could not load training.data file. Run with `--build` first. Exiting...'); process.exit(1); } features = features.split('\n'); features.forEach((feature) => { const [r, g, b, output] = feature.split(','); this.inputs.push([r, g, b]); this.outputs.push(output); }); } predictColors() { const images = fs.readdirSync(config.testDatasetDir, { encoding: 'utf8' }); images.forEach((image) => { if (!image.endsWith('.png')) { console.log(`File ${image} doesn't seem to be PNG file. Skipping...`); return; } PNG.decode(`${config.testDatasetDir}/${image}`, (pixels) => { const [r, g, b] = pixels; const sample = [r, g, b]; console.log(`${image}:`, this.knn(config.K, sample)); }); }); } knn(k, sample) { const distances = []; this.inputs.forEach((input) => distances.push([this._euclideanDistance(sample, input), input])); const kNearest = distances.sort((a,b) => { if (a[0] < b[0]) return -1; else if (a[0] > b[0]) return 1; return 0; }).slice(0, k).map((nearest) => nearest[1]); const nearestLabels = []; kNearest.forEach((nearest) => { const index = this.inputs.findIndex((input) => this._vectorsEqual(input, nearest)); nearestLabels.push(this.outputs[index]); }); const predictionMap = nearestLabels.reduce((res, label) => { res[label] = res[label] || 0; res[label]++; return res; }, {}); return Object.entries(predictionMap).sort((a, b) => { if (a[1] < b[1]) return 1; else if (a[1] > b[1]) return -1; return 0; })[0][0]; } _euclideanDistance(vector1, vector2) { const squareDiffs = []; vector1.forEach((num, i) => squareDiffs.push(Math.pow(num - vector2[i], 2))); return Math.sqrt(this._sum(...squareDiffs)); } _sum(...numbers) { return numbers.reduce((res, num) => res + num, 0); } _vectorsEqual(vector1, vector2) { for (let i = 0; i < vector1.length; i++) { if (vector1[i] !== vector2[i]) return false; } return true; } } module.exports = ColorClassifier;
0c62754d5df4fb3e539a30d57cc95182b2aaee62
[ "Markdown", "JavaScript" ]
4
Markdown
catchmareck/basic-color-classifier
eddc4cf16b2a8eb6d7ea11055d10366bec8d2b78
da2fd81a587cc5f2c17f9c7471b16d0d520b99fb
refs/heads/master
<file_sep>DO $$ /* Copyright (c) 1999-2011 by OpenMFG LLC, d/b/a xTuple. See www.xm.ple.com/CPAL for the full text of the software license. */ var sql = "select dropifexists('VIEW', viewname, schemaname, true) " + "from pg_views " + "where schemaname = 'xm';", result; result = plv8.execute(sql); return result; $$ language plv8;
aaa3817913f8be9be63437a02eebd2a32fb5856e
[ "SQL" ]
1
SQL
msinclairstevens/orm
8daf0d684d9c60ef831c7a169d8032bbcbe45d75
a4108a6716db6ba939793463cf35d84bc35cee2c
refs/heads/master
<file_sep>// Import required modules const keypress = require("keypress") const colors = require("colors/safe") module.exports = { // Contains state variable for throttle and both the horizontal and vertical axis state: { thr: 0, // Throttle hor: 0, // Horizontal axis ver: 0 // Vertical axis }, /** * Start in-terminal drone control interface * @param {Fcuntion} endCallback Function to be called when the user quits the script */ start: function(endCallback) { // Init keypress module keypress(process.stdin); // Hide terminal cursor process.stderr.write("\x1B[?25l") // Listen for the "keypress" event process.stdin.on("keypress", function (ch, key) { // Make a shorthand for the state object let state = module.exports.state // Some keys will not be passed, catch that if (!key) { return } // Match pressed key with actions switch (key.name) { // User pressed right, increase horizontal axis power until we hit the maxmimum case "right": if (Math.round(state.hor * 100) >= 100) { state.hor = 1 } else { state.hor += 0.05 } break // User pressed left, decrease horizontal axis power until we hit the minimum case "left": if (Math.round(state.hor * 100) <= -100) { state.hor = -1 } else { state.hor -= 0.05 } break // User pressed up, increase vertical axis power until we hit the maxmimum case "up": if (Math.round(state.ver * 100) >= 100) { state.ver = 1 } else { state.ver += 0.05 } break // User pressed down, decrease vertical axis power until we hit the minimum case "down": if (Math.round(state.ver * 100) <= -100) { state.ver = -1 } else { state.ver -= 0.05 } break // User pressed home (throttle up), increase throttle power until we hit the maxmimum case "home": if (Math.round(state.thr * 100) >= 200) { state.thr = 2 } else { state.thr += 0.05 } break // User pressed home (throttle down), decrease throttle power until we hit the minimum case "end": if (Math.round(state.thr * 100) <= 0) { state.thr = 0 } else { state.thr -= 0.05 } break // User pressed clear or num5 (reset), decrease throttle to landing power and reset the horizontal and vertical axis case "clear": state.thr = .35 state.hor = 0 state.ver = 0 break; } // Print new state to the console printState() // Catch a ctrl+C (SIGINT) or an escape or q keypress to quit the script if ((key.ctrl && key.name == "c") || key.name == "q" || key.name == "escape") { // Print a special state printState("END") // Let the index script clean up endCallback() // Give the terminal its cursor back and add some newlines process.stderr.write('\x1B[?25h') process.stdout.write("\n\n") } }) // Make STDIN ready to receive keypresses process.stdin.setRawMode(true) process.stdin.resume() // Print the first state printState("FIRST") } } /** * Print a nicely formatted view of the drone status * @param {String} special Set to specific values for specal events */ function printState(special) { // If this is the first time we're printing the state, add a new line if (special == "FIRST") { process.stdout.write("\n") } // Otherwise, return to the start of the old line to overwrite it else { process.stdout.write("\r") } // Round the throttle to a human readable format let thr = Math.round(module.exports.state.thr * 100) / 100 // Set the text as black and round it to 2 decimals thr = colors.black(` ${thr.toFixed(2)} `) // Color the background red if the throttle is dangerously high if (module.exports.state.thr > 1.2) thr = colors.bgRed(thr) // Color the background yellow if the throttle is higher than normal else if (module.exports.state.thr > .7) thr = colors.bgYellow(thr) // Give it a normal white background for normal values else thr = colors.bgWhite(thr) // Round the horizontal axis to a human readable format let hor = Math.round(module.exports.state.hor * 100) / 100 // Set the text as black, round it to 2 decimals and add extra space in front if it's a positive number (makes natative and positive numbers have the same position) hor = colors.black(` ${(hor < 0 ? "" : " ")}${hor.toFixed(2)} `) // Color the background red if the horizontal axis is dangerously high or low if (module.exports.state.hor > .5 || module.exports.state.hor < -.5) hor = colors.bgRed(hor) // Color the background yellow if the horizontal axis is higher or lower than normal else if (module.exports.state.hor > .25 || module.exports.state.hor < -.25) hor = colors.bgYellow(hor) // Give it a normal white background for normal values else hor = colors.bgWhite(hor) // Round the vertical axis to a human readable format let ver = Math.round(module.exports.state.ver * 100) / 100 // Set the text as black, round it to 2 decimals and add extra space in front if it's a positive number (see above) ver = colors.black(` ${(ver < 0 ? "" : " ")}${ver.toFixed(2)} `) // Color the background red if the vertical axis is dangerously high or low if (module.exports.state.ver > .5 || module.exports.state.ver < -.5) ver = colors.bgRed(ver) // Color the background yellow if the vertical axis is higher or lower than normal else if (module.exports.state.ver > .25 || module.exports.state.ver < -.25) ver = colors.bgYellow(ver) // Give it a normal white background for normal values else ver = colors.bgWhite(ver) // Default the status line to In flight let status = colors.bold.red("In flight ") // If the throttle is very low the engines will turn off and it will be in idle if (module.exports.state.thr < .25) status = colors.bold.green("Idle ") // If the throttle is low but not too low, the engine power will not be enough to lift off else if (module.exports.state.thr < .4) status = colors.bold.yellow("Armed ") // If this is the final print show the status as Stopped if (special == "END") { status = colors.bold.red("Stopped ") } // Print everything to the console process.stdout.write(` T: ${thr} H: ${hor} V: ${ver} ${status}`) } <file_sep># RC Leading RC127 control/hijack script ## Compatible drones This script probably works with a huge range of very similar drones. For example this is the one i own: ![HEMA Rebrand](http://i.imgur.com/qv9uDMw.png) But if your drone is controllable by connecting to a wifi network with an SSID that starts with "RC Leading" this script should be able to control/hijack it. Sidenote: If your drone can be controlled by an android app created by [MARK mai](https://play.google.com/store/apps/developer?id=MARK%20mai) but has a different wifi AP name, this script will probably still work. You can either try to bypass the wifi connection part of the script or [open an issue](https://github.com/Boltgolt/rcl-rc127/issues/new). ## Usage 1. Clone this repo `git clone https://github.com/Boltgolt/rcl-rc127.git`. 2. Install required node modules `npm install`. 3. Turn on your done and **wait for at least 15 to 30 seconds** to allow your PC to pick up the new wifi AP. 4. Run `node index.js` to launch the script. ## Controls The drone is controlled using the numpad: Key | Number | Action ------- | ------ | ------------- Up | 8 | Forward Down | 2 | Backward Left | 4 | Left Right | 6 | Right Home | 7 | Throttle up End | 1 | Throttle down None | 5 | Reset Q / Esc | | Quit script <file_sep>// Contains magic packets to send to drone module.exports = { // Starts TPC control session tcpStart: new Buffer([ 0x49, 0x54, 0x64, 0x00, 0x00, 0x00, 0x5D, 0x00, 0x00, 0x00, 0x81, 0x85, 0xFF, 0xBD, 0x2A, 0x29, 0x5C, 0xAD, 0x67, 0x82, 0x5C, 0x57, 0xBE, 0x41, 0x03, 0xF8, 0xCA, 0xE2, 0x64, 0x30, 0xA3, 0xC1, 0x5E, 0x40, 0xDE, 0x30, 0xF6, 0xD6, 0x95, 0xE0, 0x30, 0xB7, 0xC2, 0xE5, 0xB7, 0xD6, 0x5D, 0xA8, 0x65, 0x9E, 0xB2, 0xE2, 0xD5, 0xE0, 0xC2, 0xCB, 0x6C, 0x59, 0xCD, 0xCB, 0x66, 0x1E, 0x7E, 0x1E, 0xB0, 0xCE, 0x8E, 0xE8, 0xDF, 0x32, 0x45, 0x6F, 0xA8, 0x42, 0xEE, 0x2E, 0x09, 0xA3, 0x9B, 0xDD, 0x05, 0xC8, 0x30, 0xA2, 0x81, 0xC8, 0x2A, 0x9E, 0xDA, 0x7F, 0xD5, 0x86, 0x0E, 0xAF, 0xAB, 0xFE, 0xFA, 0x3C, 0x7E, 0x54, 0x4F, 0xF2, 0x8A, 0xD2, 0x93, 0xCD ]), // Default datagram to send, individual values can be changed to control drone defaultUdp: new Buffer([ 0xCC, 0x80, 0x80, 0x00, 0x80, 0x00, 0x80, 0x33 ]) } <file_sep>// Import required modules const wifi = require("node-wifi") const colors = require("colors/safe") const dgram = require("dgram") const net = require("net") // Import other node files const magic = require("./magic.js") const controller = require("./controller.js") // Hardcode drone IP and ports const drone = { ip: "172.16.10.1", tcpPort: 8888, udpPort: 8895 } // Init TCP socket object, this socket is olny keeping the drone awake let tcpControl = new net.Socket() // Init TCP socket object, this sockets is sending instructions to the drone let udpControl = dgram.createSocket("udp4") // Will shut down drone when true let shutDown = false // Init OS wifi integration wifi.init({ // Allow any wifi interface iface: null }) /** * Prints a nice massage to the console * @param {String} text Message to be shown * @param {Bool} error When true, will print as error and quit the program */ global.print = function(text, error) { // Get the current time and add a leading 0 when needed let d = new Date() let h = (d.getHours() < 10 ? "0" : "") + d.getHours() let m = (d.getMinutes() < 10 ? "0" : "") + d.getMinutes() let s = (d.getSeconds() < 10 ? "0" : "") + d.getSeconds() // Turn the text red if this is a critical error if (error) { text = colors.red.bold(text) } // Write it all to console process.stdout.write(`[${h}:${m}:${s}] ${text}\n`) // If an error, stop the script if (error) { process.exit(1) } } // Let the user know we're starting the scan print("Scanning for drone wifi network...") // Scan for availible wifi networks wifi.scan(function(err, networks) { // Catch error and quit script if (err) { print("Could not scan for wifi networks", true) } else { // Default to false to catch no-drone error let network = false // Loop through wifi networks for (let i in networks) { // If network SSID looks like a done network, save that and stop the loop if (/RC Leading-[a-f0-9]{6}/.test(networks[i].ssid)) { network = networks[i] break } } // If we couldn't find a network, stop script with error if (network === false) { print("Could not find drone network", true) } else { // Let the user know to what drone we're connecting print(`Connecting to "${network.ssid}" (${network.mac})...`) // Connect to drone network without a password (it's an open network) wifi.connect({ ssid: network.ssid, password: "" }, function(err) { // Crash with error if connecting failed if (err) { print("Could not connect to drone network", true) } // Let the user know we're opening the TCP socket to the dronw print("Opening control socket to drone...") // Connect to the TCP server on the drone tcpControl.connect(drone.tcpPort, drone.ip, function() { // Send the magic packet that will wake the drone up (lights will stop flashing at this point) tcpControl.write(magic.tcpStart) // Let the user know we have a connection now print(colors.green("Connected to drone!")) // Start the controller terminal interface controller.start(stopDrone) // Send the first UDP packet with all default fields, which will put al conrols in the natural position udpControl.send(magic.defaultUdp, 0, magic.defaultUdp.length, drone.udpPort, drone.ip) // Send a control UDP packet every 50ms setInterval(function() { // If the user has send the quit signal if (shutDown) { // Get the natural UDP datagram let stopUdp = magic.defaultUdp // Set the throttle to 1/256, which will shut down the rotors from any state stopUdp[3] = 0x01 // Send the datagram aff to the drone and stop here return udpControl.send(stopUdp, 0, stopUdp.length, drone.udpPort, drone.ip) } // Get the natural UDP datagram let data = magic.defaultUdp // Translate the -1 to 1 value of the horizontal axis to 0-256 and insert it into the natural datagram data[1] = Math.round((controller.state.hor + 1) * 127) // Translate the -1 to 1 value of the vertical axis to 0-256 and insert it into the natural datagram data[2] = Math.round((controller.state.ver + 1) * 127) // Translate the 0 to 2 value of the throttle to 0-256 and insert it into the natural datagram data[3] = Math.round(controller.state.thr * 127) // Generate the mew XOR checksum for this datagram data[6] = data[1] ^ data[2] ^ data[3] ^ 0x80 // Send the datagram off to the drone udpControl.send(data, 0, magic.defaultUdp.length, drone.udpPort, drone.ip) }, 50) }) }) } } }) /** * Stops drone gracefully */ function stopDrone() { // Set the global accordingly shutDown = true // Wait .2s for the shutdown to reach the drone and stop the script setTimeout(function () { process.exit() }, 200) } // If the TCP socket gets broken, let the user know and stop the script tcpControl.on("close", function() { print("Connection closed by drone", true) })
326a83c55dbaeabd5b0017d235b9170ef89161d2
[ "JavaScript", "Markdown" ]
4
JavaScript
boltgolt/rcl-rc127
044b3404a706f76b75bcabde5d44c5d69d69672f
5e0bf78daa5ceb598f85324ca441411bc23df76f
refs/heads/main
<repo_name>cmarincia/Aya<file_sep>/test/integration-test/src/tests/load.rs use std::{process::Command, thread, time}; use aya::{ include_bytes_aligned, maps::Array, programs::{ links::{FdLink, PinnedLink}, KProbe, TracePoint, Xdp, XdpFlags, }, Bpf, }; use log::warn; use crate::tests::kernel_version; use super::{integration_test, IntegrationTest}; const MAX_RETRIES: u32 = 100; const RETRY_DURATION_MS: u64 = 10; #[integration_test] fn long_name() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/name_test"); let mut bpf = Bpf::load(bytes).unwrap(); let name_prog: &mut Xdp = bpf .program_mut("ihaveaverylongname") .unwrap() .try_into() .unwrap(); name_prog.load().unwrap(); name_prog.attach("lo", XdpFlags::default()).unwrap(); // We used to be able to assert with bpftool that the program name was short. // It seem though that it now uses the name from the ELF symbol table instead. // Therefore, as long as we were able to load the program, this is good enough. } #[integration_test] fn multiple_btf_maps() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/multimap-btf.bpf.o"); let mut bpf = Bpf::load(bytes).unwrap(); let map_1: Array<_, u64> = bpf.take_map("map_1").unwrap().try_into().unwrap(); let map_2: Array<_, u64> = bpf.take_map("map_2").unwrap().try_into().unwrap(); let prog: &mut TracePoint = bpf.program_mut("tracepoint").unwrap().try_into().unwrap(); prog.load().unwrap(); prog.attach("sched", "sched_switch").unwrap(); thread::sleep(time::Duration::from_secs(3)); let key = 0; let val_1 = map_1.get(&key, 0).unwrap(); let val_2 = map_2.get(&key, 0).unwrap(); assert_eq!(val_1, 24); assert_eq!(val_2, 42); } fn is_loaded(name: &str) -> bool { let output = Command::new("bpftool").args(["prog"]).output(); let output = match output { Err(e) => panic!("Failed to run 'bpftool prog': {e}"), Ok(out) => out, }; let stdout = String::from_utf8(output.stdout).unwrap(); stdout.contains(name) } macro_rules! assert_loaded { ($name:literal, $loaded:expr) => { for i in 0..(MAX_RETRIES + 1) { let state = is_loaded($name); if state == $loaded { break; } if i == MAX_RETRIES { panic!("Expected loaded: {} but was loaded: {}", $loaded, state); } thread::sleep(time::Duration::from_millis(RETRY_DURATION_MS)); } }; } #[integration_test] fn unload_xdp() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/test"); let mut bpf = Bpf::load(bytes).unwrap(); let prog: &mut Xdp = bpf .program_mut("test_unload_xdp") .unwrap() .try_into() .unwrap(); prog.load().unwrap(); assert_loaded!("test_unload_xdp", true); let link = prog.attach("lo", XdpFlags::default()).unwrap(); { let _link_owned = prog.take_link(link).unwrap(); prog.unload().unwrap(); assert_loaded!("test_unload_xdp", true); }; assert_loaded!("test_unload_xdp", false); prog.load().unwrap(); assert_loaded!("test_unload_xdp", true); prog.attach("lo", XdpFlags::default()).unwrap(); assert_loaded!("test_unload_xdp", true); prog.unload().unwrap(); assert_loaded!("test_unload_xdp", false); } #[integration_test] fn unload_kprobe() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/test"); let mut bpf = Bpf::load(bytes).unwrap(); let prog: &mut KProbe = bpf .program_mut("test_unload_kpr") .unwrap() .try_into() .unwrap(); prog.load().unwrap(); assert_loaded!("test_unload_kpr", true); let link = prog.attach("try_to_wake_up", 0).unwrap(); { let _link_owned = prog.take_link(link).unwrap(); prog.unload().unwrap(); assert_loaded!("test_unload_kpr", true); }; assert_loaded!("test_unload_kpr", false); prog.load().unwrap(); assert_loaded!("test_unload_kpr", true); prog.attach("try_to_wake_up", 0).unwrap(); assert_loaded!("test_unload_kpr", true); prog.unload().unwrap(); assert_loaded!("test_unload_kpr", false); } #[integration_test] fn pin_link() { if kernel_version().unwrap() < (5, 9, 0) { warn!("skipping test, XDP uses netlink"); return; } let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/test"); let mut bpf = Bpf::load(bytes).unwrap(); let prog: &mut Xdp = bpf .program_mut("test_unload_xdp") .unwrap() .try_into() .unwrap(); prog.load().unwrap(); let link_id = prog.attach("lo", XdpFlags::default()).unwrap(); let link = prog.take_link(link_id).unwrap(); assert_loaded!("test_unload_xdp", true); let fd_link: FdLink = link.try_into().unwrap(); let pinned = fd_link.pin("/sys/fs/bpf/aya-xdp-test-lo").unwrap(); // because of the pin, the program is still attached prog.unload().unwrap(); assert_loaded!("test_unload_xdp", true); // delete the pin, but the program is still attached let new_link = pinned.unpin().unwrap(); assert_loaded!("test_unload_xdp", true); // finally when new_link is dropped we're detached drop(new_link); assert_loaded!("test_unload_xdp", false); } #[integration_test] fn pin_lifecycle() { if kernel_version().unwrap() < (5, 9, 0) { warn!("skipping test, XDP uses netlink"); return; } let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/pass"); // 1. Load Program and Pin { let mut bpf = Bpf::load(bytes).unwrap(); let prog: &mut Xdp = bpf.program_mut("pass").unwrap().try_into().unwrap(); prog.load().unwrap(); let link_id = prog.attach("lo", XdpFlags::default()).unwrap(); let link = prog.take_link(link_id).unwrap(); let fd_link: FdLink = link.try_into().unwrap(); fd_link.pin("/sys/fs/bpf/aya-xdp-test-lo").unwrap(); } // should still be loaded since link was pinned assert_loaded!("pass", true); // 2. Load a new version of the program, unpin link, and atomically replace old program { let mut bpf = Bpf::load(bytes).unwrap(); let prog: &mut Xdp = bpf.program_mut("pass").unwrap().try_into().unwrap(); prog.load().unwrap(); let link = PinnedLink::from_pin("/sys/fs/bpf/aya-xdp-test-lo") .unwrap() .unpin() .unwrap(); prog.attach_to_link(link.try_into().unwrap()).unwrap(); assert_loaded!("pass", true); } // program should be unloaded assert_loaded!("pass", false); } <file_sep>/xtask/src/build_ebpf.rs use std::{ env, fs, path::{Path, PathBuf}, process::Command, }; use anyhow::{bail, Context}; use clap::Parser; use crate::utils::WORKSPACE_ROOT; #[derive(Debug, Copy, Clone)] pub enum Architecture { BpfEl, BpfEb, } impl std::str::FromStr for Architecture { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "bpfel-unknown-none" => Architecture::BpfEl, "bpfeb-unknown-none" => Architecture::BpfEb, _ => return Err("invalid target".to_owned()), }) } } impl std::fmt::Display for Architecture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Architecture::BpfEl => "bpfel-unknown-none", Architecture::BpfEb => "bpfeb-unknown-none", }) } } #[derive(Debug, Parser)] pub struct BuildEbpfOptions { /// Set the endianness of the BPF target #[clap(default_value = "bpfel-unknown-none", long)] pub target: Architecture, /// Build the release target #[clap(long)] pub release: bool, /// Libbpf dir, required for compiling C code #[clap(long, action)] pub libbpf_dir: PathBuf, } pub fn build_ebpf(opts: BuildEbpfOptions) -> anyhow::Result<()> { build_rust_ebpf(&opts)?; build_c_ebpf(&opts) } fn build_rust_ebpf(opts: &BuildEbpfOptions) -> anyhow::Result<()> { let mut dir = PathBuf::from(WORKSPACE_ROOT.to_string()); dir.push("test/integration-ebpf"); let target = format!("--target={}", opts.target); let mut args = vec![ "+nightly", "build", "--verbose", target.as_str(), "-Z", "build-std=core", ]; if opts.release { args.push("--release") } let status = Command::new("cargo") .current_dir(&dir) .args(&args) .status() .expect("failed to build bpf program"); assert!(status.success()); Ok(()) } fn get_libbpf_headers<P: AsRef<Path>>(libbpf_dir: P, include_path: P) -> anyhow::Result<()> { let dir = include_path.as_ref(); fs::create_dir_all(dir)?; let status = Command::new("make") .current_dir(libbpf_dir.as_ref().join("src")) .arg(format!("INCLUDEDIR={}", dir.as_os_str().to_string_lossy())) .arg("install_headers") .status() .expect("failed to build get libbpf headers"); assert!(status.success()); Ok(()) } fn build_c_ebpf(opts: &BuildEbpfOptions) -> anyhow::Result<()> { let mut src = PathBuf::from(WORKSPACE_ROOT.to_string()); src.push("test/integration-ebpf/src/bpf"); let mut out_path = PathBuf::from(WORKSPACE_ROOT.to_string()); out_path.push("target"); out_path.push(opts.target.to_string()); out_path.push(if opts.release { "release " } else { "debug" }); let include_path = out_path.join("include"); get_libbpf_headers(&opts.libbpf_dir, &include_path)?; let files = fs::read_dir(&src).unwrap(); for file in files { let p = file.unwrap().path(); if let Some(ext) = p.extension() { if ext == "c" { let mut out = PathBuf::from(&out_path); out.push(p.file_name().unwrap()); out.set_extension("o"); compile_with_clang(&p, &out, &include_path)?; } } } Ok(()) } /// Build eBPF programs with clang and libbpf headers. fn compile_with_clang<P: Clone + AsRef<Path>>( src: P, out: P, include_path: P, ) -> anyhow::Result<()> { let clang = match env::var("CLANG") { Ok(val) => val, Err(_) => String::from("/usr/bin/clang"), }; let arch = match std::env::consts::ARCH { "x86_64" => "x86", "aarch64" => "arm64", _ => std::env::consts::ARCH, }; let mut cmd = Command::new(clang); cmd.arg(format!("-I{}", include_path.as_ref().to_string_lossy())) .arg("-g") .arg("-O2") .arg("-target") .arg("bpf") .arg("-c") .arg(format!("-D__TARGET_ARCH_{arch}")) .arg(src.as_ref().as_os_str()) .arg("-o") .arg(out.as_ref().as_os_str()); let output = cmd.output().context("Failed to execute clang")?; if !output.status.success() { bail!( "Failed to compile eBPF programs\n \ stdout=\n \ {}\n \ stderr=\n \ {}\n", String::from_utf8(output.stdout).unwrap(), String::from_utf8(output.stderr).unwrap() ); } Ok(()) } <file_sep>/aya/src/programs/fexit.rs //! Fexit programs. use crate::{ generated::{bpf_attach_type::BPF_TRACE_FEXIT, bpf_prog_type::BPF_PROG_TYPE_TRACING}, obj::btf::{Btf, BtfKind}, programs::{ define_link_wrapper, load_program, utils::attach_raw_tracepoint, FdLink, FdLinkId, ProgramData, ProgramError, }, }; /// A program that can be attached to the exit point of (almost) anny kernel /// function. /// /// [`FExit`] programs are similar to [kretprobes](crate::programs::KProbe), /// but the difference is that fexit has practically zero overhead to call /// before kernel function. Fexit programs can be also attached to other eBPF /// programs. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # BtfError(#[from] aya::BtfError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # } /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::FExit, BtfError, Btf}; /// /// let btf = Btf::from_sys_fs()?; /// let program: &mut FExit = bpf.program_mut("filename_lookup").unwrap().try_into()?; /// program.load("filename_lookup", &btf)?; /// program.attach()?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_TRACE_FEXIT")] #[doc(alias = "BPF_PROG_TYPE_TRACING")] pub struct FExit { pub(crate) data: ProgramData<FExitLink>, } impl FExit { /// Loads the program inside the kernel. /// /// Loads the program so it's executed when the kernel function `fn_name` /// is exited. The `btf` argument must contain the BTF info for the running /// kernel. pub fn load(&mut self, fn_name: &str, btf: &Btf) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(BPF_TRACE_FEXIT); self.data.attach_btf_id = Some(btf.id_by_type_name_kind(fn_name, BtfKind::Func)?); load_program(BPF_PROG_TYPE_TRACING, &mut self.data) } /// Attaches the program. /// /// The returned value can be used to detach, see [FExit::detach]. pub fn attach(&mut self) -> Result<FExitLinkId, ProgramError> { attach_raw_tracepoint(&mut self.data, None) } /// Detaches the program. /// /// See [FExit::attach]. pub fn detach(&mut self, link_id: FExitLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: FExitLinkId) -> Result<FExitLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [FExit] programs. FExitLink, /// The type returned by [FExit::attach]. Can be passed to [FExit::detach]. FExitLinkId, FdLink, FdLinkId ); <file_sep>/aya/src/programs/cgroup_sock_addr.rs //! Cgroup socket address programs. use thiserror::Error; use crate::generated::bpf_attach_type; use std::{ hash::Hash, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ generated::bpf_prog_type::BPF_PROG_TYPE_CGROUP_SOCK_ADDR, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program that can be used to inspect or modify socket addresses (`struct sockaddr`). /// /// [`CgroupSockAddr`] programs can be used to inspect or modify socket addresses passed to /// various syscalls within a [cgroup]. They can be attached to a number of different /// places as described in [`CgroupSockAddrAttachType`]. /// /// [cgroup]: https://man7.org/linux/man-pages/man7/cgroups.7.html /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.17. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::{CgroupSockAddr, CgroupSockAddrAttachType}; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let egress: &mut CgroupSockAddr = bpf.program_mut("connect4").unwrap().try_into()?; /// egress.load()?; /// egress.attach(file)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SOCK_ADDR")] pub struct CgroupSockAddr { pub(crate) data: ProgramData<CgroupSockAddrLink>, pub(crate) attach_type: CgroupSockAddrAttachType, } impl CgroupSockAddr { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(self.attach_type.into()); load_program(BPF_PROG_TYPE_CGROUP_SOCK_ADDR, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSockAddr::detach]. pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<CgroupSockAddrLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let attach_type = self.data.expected_attach_type.unwrap(); let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupSockAddrLink::new(CgroupSockAddrLinkInner::Fd( FdLink::new(link_fd), ))) } else { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data.links.insert(CgroupSockAddrLink::new( CgroupSockAddrLinkInner::ProgAttach(ProgAttachLink::new( prog_fd, cgroup_fd, attach_type, )), )) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: CgroupSockAddrLinkId, ) -> Result<CgroupSockAddrLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [CgroupSockAddr::attach]. pub fn detach(&mut self, link_id: CgroupSockAddrLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupSockAddrLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupSockAddrLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupSockAddrLinkInner { type Id = CgroupSockAddrLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupSockAddrLinkInner::Fd(fd) => CgroupSockAddrLinkIdInner::Fd(fd.id()), CgroupSockAddrLinkInner::ProgAttach(p) => CgroupSockAddrLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupSockAddrLinkInner::Fd(fd) => fd.detach(), CgroupSockAddrLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupSockAddr] programs. CgroupSockAddrLink, /// The type returned by [CgroupSockAddr::attach]. Can be passed to [CgroupSockAddr::detach]. CgroupSockAddrLinkId, CgroupSockAddrLinkInner, CgroupSockAddrLinkIdInner ); /// Defines where to attach a [`CgroupSockAddr`] program. #[derive(Copy, Clone, Debug)] pub enum CgroupSockAddrAttachType { /// Attach to IPv4 bind events. Bind4, /// Attach to IPv6 bind events. Bind6, /// Attach to IPv4 connect events. Connect4, /// Attach to IPv6 connect events. Connect6, /// Attach to IPv4 getpeername events. GetPeerName4, /// Attach to IPv6 getpeername events. GetPeerName6, /// Attach to IPv4 getsockname events. GetSockName4, /// Attach to IPv6 getsockname events. GetSockName6, /// Attach to IPv4 udp_sendmsg events. UDPSendMsg4, /// Attach to IPv6 udp_sendmsg events. UDPSendMsg6, /// Attach to IPv4 udp_recvmsg events. UDPRecvMsg4, /// Attach to IPv6 udp_recvmsg events. UDPRecvMsg6, } impl From<CgroupSockAddrAttachType> for bpf_attach_type { fn from(s: CgroupSockAddrAttachType) -> bpf_attach_type { match s { CgroupSockAddrAttachType::Bind4 => bpf_attach_type::BPF_CGROUP_INET4_BIND, CgroupSockAddrAttachType::Bind6 => bpf_attach_type::BPF_CGROUP_INET6_BIND, CgroupSockAddrAttachType::Connect4 => bpf_attach_type::BPF_CGROUP_INET4_CONNECT, CgroupSockAddrAttachType::Connect6 => bpf_attach_type::BPF_CGROUP_INET6_CONNECT, CgroupSockAddrAttachType::GetPeerName4 => bpf_attach_type::BPF_CGROUP_INET4_GETPEERNAME, CgroupSockAddrAttachType::GetPeerName6 => bpf_attach_type::BPF_CGROUP_INET6_GETPEERNAME, CgroupSockAddrAttachType::GetSockName4 => bpf_attach_type::BPF_CGROUP_INET4_GETSOCKNAME, CgroupSockAddrAttachType::GetSockName6 => bpf_attach_type::BPF_CGROUP_INET6_GETSOCKNAME, CgroupSockAddrAttachType::UDPSendMsg4 => bpf_attach_type::BPF_CGROUP_UDP4_SENDMSG, CgroupSockAddrAttachType::UDPSendMsg6 => bpf_attach_type::BPF_CGROUP_UDP6_SENDMSG, CgroupSockAddrAttachType::UDPRecvMsg4 => bpf_attach_type::BPF_CGROUP_UDP4_RECVMSG, CgroupSockAddrAttachType::UDPRecvMsg6 => bpf_attach_type::BPF_CGROUP_UDP6_RECVMSG, } } } #[derive(Debug, Error)] #[error("{0} is not a valid attach type for a CGROUP_SOCK_ADDR program")] pub(crate) struct InvalidAttachType(String); impl CgroupSockAddrAttachType { pub(crate) fn try_from(value: &str) -> Result<CgroupSockAddrAttachType, InvalidAttachType> { match value { "bind4" => Ok(CgroupSockAddrAttachType::Bind4), "bind6" => Ok(CgroupSockAddrAttachType::Bind6), "connect4" => Ok(CgroupSockAddrAttachType::Connect4), "connect6" => Ok(CgroupSockAddrAttachType::Connect6), "getpeername4" => Ok(CgroupSockAddrAttachType::GetPeerName4), "getpeername6" => Ok(CgroupSockAddrAttachType::GetPeerName6), "getsockname4" => Ok(CgroupSockAddrAttachType::GetSockName4), "getsockname6" => Ok(CgroupSockAddrAttachType::GetSockName6), "sendmsg4" => Ok(CgroupSockAddrAttachType::UDPSendMsg4), "sendmsg6" => Ok(CgroupSockAddrAttachType::UDPSendMsg6), "recvmsg4" => Ok(CgroupSockAddrAttachType::UDPRecvMsg4), "recvmsg6" => Ok(CgroupSockAddrAttachType::UDPRecvMsg6), _ => Err(InvalidAttachType(value.to_owned())), } } } <file_sep>/aya/src/programs/cgroup_sock.rs //! Cgroup socket programs. use thiserror::Error; use crate::generated::bpf_attach_type; use std::{ hash::Hash, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ generated::bpf_prog_type::BPF_PROG_TYPE_CGROUP_SOCK, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program that is called on socket creation, bind and release. /// /// [`CgroupSock`] programs can be used to allow or deny socket creation from /// within a [cgroup], or they can be used to monitor and gather statistics. /// /// [cgroup]: https://man7.org/linux/man-pages/man7/cgroups.7.html /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.10. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::{CgroupSock, CgroupSockAttachType}; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let bind: &mut CgroupSock = bpf.program_mut("bind").unwrap().try_into()?; /// bind.load()?; /// bind.attach(file)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SOCK")] pub struct CgroupSock { pub(crate) data: ProgramData<CgroupSockLink>, pub(crate) attach_type: CgroupSockAttachType, } impl CgroupSock { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(self.attach_type.into()); load_program(BPF_PROG_TYPE_CGROUP_SOCK, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSock::detach]. pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<CgroupSockLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let attach_type = self.data.expected_attach_type.unwrap(); let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupSockLink::new(CgroupSockLinkInner::Fd(FdLink::new( link_fd, )))) } else { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data .links .insert(CgroupSockLink::new(CgroupSockLinkInner::ProgAttach( ProgAttachLink::new(prog_fd, cgroup_fd, attach_type), ))) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: CgroupSockLinkId) -> Result<CgroupSockLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [CgroupSock::attach]. pub fn detach(&mut self, link_id: CgroupSockLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupSockLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupSockLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupSockLinkInner { type Id = CgroupSockLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupSockLinkInner::Fd(fd) => CgroupSockLinkIdInner::Fd(fd.id()), CgroupSockLinkInner::ProgAttach(p) => CgroupSockLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupSockLinkInner::Fd(fd) => fd.detach(), CgroupSockLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupSock] programs. CgroupSockLink, /// The type returned by [CgroupSock::attach]. Can be passed to [CgroupSock::detach]. CgroupSockLinkId, CgroupSockLinkInner, CgroupSockLinkIdInner ); /// Defines where to attach a [`CgroupSock`] program. #[derive(Copy, Clone, Debug)] pub enum CgroupSockAttachType { /// Called after the IPv4 bind events. PostBind4, /// Called after the IPv6 bind events. PostBind6, /// Attach to IPv4 connect events. SockCreate, /// Attach to IPv6 connect events. SockRelease, } impl Default for CgroupSockAttachType { // The kernel checks for a 0 attach_type and sets it to sock_create // We may as well do that here also fn default() -> Self { CgroupSockAttachType::SockCreate } } impl From<CgroupSockAttachType> for bpf_attach_type { fn from(s: CgroupSockAttachType) -> bpf_attach_type { match s { CgroupSockAttachType::PostBind4 => bpf_attach_type::BPF_CGROUP_INET4_POST_BIND, CgroupSockAttachType::PostBind6 => bpf_attach_type::BPF_CGROUP_INET6_POST_BIND, CgroupSockAttachType::SockCreate => bpf_attach_type::BPF_CGROUP_INET_SOCK_CREATE, CgroupSockAttachType::SockRelease => bpf_attach_type::BPF_CGROUP_INET_SOCK_RELEASE, } } } #[derive(Debug, Error)] #[error("{0} is not a valid attach type for a CGROUP_SOCK program")] pub(crate) struct InvalidAttachType(String); impl CgroupSockAttachType { pub(crate) fn try_from(value: &str) -> Result<CgroupSockAttachType, InvalidAttachType> { match value { "post_bind4" => Ok(CgroupSockAttachType::PostBind4), "post_bind6" => Ok(CgroupSockAttachType::PostBind6), "sock_create" => Ok(CgroupSockAttachType::SockCreate), "sock_release" => Ok(CgroupSockAttachType::SockRelease), _ => Err(InvalidAttachType(value.to_owned())), } } } <file_sep>/bpf/aya-bpf/src/maps/array.rs use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull}; use aya_bpf_cty::c_void; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_ARRAY}, helpers::bpf_map_lookup_elem, maps::PinningType, }; #[repr(transparent)] pub struct Array<T> { def: UnsafeCell<bpf_map_def>, _t: PhantomData<T>, } unsafe impl<T: Sync> Sync for Array<T> {} impl<T> Array<T> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> Array<T> { Array { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), _t: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> Array<T> { Array { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), _t: PhantomData, } } pub fn get(&self, index: u32) -> Option<&T> { unsafe { let value = bpf_map_lookup_elem( self.def.get() as *mut _, &index as *const _ as *const c_void, ); // FIXME: alignment NonNull::new(value as *mut T).map(|p| p.as_ref()) } } } <file_sep>/aya-bpf-macros/src/lib.rs mod expand; use expand::{ Args, BtfTracePoint, CgroupDevice, CgroupSkb, CgroupSock, CgroupSockAddr, CgroupSockopt, CgroupSysctl, FEntry, FExit, Lsm, Map, PerfEvent, Probe, ProbeKind, RawTracePoint, SchedClassifier, SkLookup, SkMsg, SkSkb, SkSkbKind, SockAddrArgs, SockOps, SocketFilter, SockoptArgs, TracePoint, Xdp, }; use proc_macro::TokenStream; use syn::{parse_macro_input, ItemFn, ItemStatic}; #[proc_macro_attribute] pub fn map(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemStatic); Map::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn kprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { probe(ProbeKind::KProbe, attrs, item) } #[proc_macro_attribute] pub fn kretprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { probe(ProbeKind::KRetProbe, attrs, item) } #[proc_macro_attribute] pub fn uprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { probe(ProbeKind::UProbe, attrs, item) } #[proc_macro_attribute] pub fn uretprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { probe(ProbeKind::URetProbe, attrs, item) } #[proc_macro_attribute] pub fn sock_ops(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SockOps::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn sk_msg(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SkMsg::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn xdp(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); Xdp::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn classifier(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SchedClassifier::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn cgroup_sysctl(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); CgroupSysctl::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn cgroup_sockopt(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as SockoptArgs); let attach_type = args.attach_type.to_string(); let item = parse_macro_input!(item as ItemFn); CgroupSockopt::from_syn(args.args, item, attach_type) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn cgroup_skb(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); CgroupSkb::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn cgroup_sock_addr(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as SockAddrArgs); let attach_type = args.attach_type.to_string(); let item = parse_macro_input!(item as ItemFn); CgroupSockAddr::from_syn(args.args, item, attach_type) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn cgroup_sock(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); CgroupSock::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } fn probe(kind: ProbeKind, attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); Probe::from_syn(kind, args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn tracepoint(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); TracePoint::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn perf_event(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); PerfEvent::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a raw tracepoint eBPF program that can be attached at a /// pre-defined kernel trace point. /// /// The kernel provides a set of pre-defined trace points that eBPF programs can /// be attached to. See `/sys/kernel/debug/tracing/events` for a list of which /// events can be traced. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.7. /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::raw_tracepoint, programs::RawTracePointContext}; /// /// #[raw_tracepoint(name = "sys_enter")] /// pub fn sys_enter(ctx: RawTracePointContext) -> i32 { /// match unsafe { try_sys_enter(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } /// } /// /// unsafe fn try_sys_enter(_ctx: RawTracePointContext) -> Result<i32, i32> { /// Ok(0) /// } /// ``` #[proc_macro_attribute] pub fn raw_tracepoint(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); RawTracePoint::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as an LSM program that can be attached to Linux LSM hooks. /// Used to implement security policy and audit logging. /// /// LSM probes can be attached to the kernel's security hooks to implement mandatory /// access control policy and security auditing. /// /// LSM probes require a kernel compiled with `CONFIG_BPF_LSM=y` and `CONFIG_DEBUG_INFO_BTF=y`. /// In order for the probes to fire, you also need the BPF LSM to be enabled through your /// kernel's boot paramters (like `lsm=lockdown,yama,bpf`). /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.7. /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::lsm, programs::LsmContext}; /// /// #[lsm(name = "file_open")] /// pub fn file_open(ctx: LsmContext) -> i32 { /// match unsafe { try_file_open(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } /// } /// /// unsafe fn try_file_open(_ctx: LsmContext) -> Result<i32, i32> { /// Ok(0) /// } /// ``` #[proc_macro_attribute] pub fn lsm(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); Lsm::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a [BTF-enabled raw tracepoint][1] eBPF program that can be attached at /// a pre-defined kernel trace point. /// /// The kernel provides a set of pre-defined trace points that eBPF programs can /// be attached to. See `/sys/kernel/debug/tracing/events` for a list of which /// events can be traced. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::btf_tracepoint, programs::BtfTracePointContext}; /// /// #[btf_tracepoint(name = "sched_process_fork")] /// pub fn sched_process_fork(ctx: BtfTracePointContext) -> u32 { /// match unsafe { try_sched_process_fork(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } /// } /// /// unsafe fn try_sched_process_fork(_ctx: BtfTracePointContext) -> Result<u32, u32> { /// Ok(0) /// } /// ``` /// /// [1]: https://github.com/torvalds/linux/commit/9e15db66136a14cde3f35691f1d839d950118826 #[proc_macro_attribute] pub fn btf_tracepoint(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); BtfTracePoint::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a SK_SKB Stream Parser eBPF program that can be attached /// to a SockMap /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.14 /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::stream_parser, programs::SkBuffContext}; /// /// ///#[stream_parser] ///fn stream_parser(ctx: SkBuffContext) -> u32 { /// match { try_stream_parser(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } ///} /// ///fn try_stream_parser(ctx: SkBuffContext) -> Result<u32, u32> { /// Ok(ctx.len()) ///} /// ``` #[proc_macro_attribute] pub fn stream_parser(attrs: TokenStream, item: TokenStream) -> TokenStream { sk_skb(SkSkbKind::StreamParser, attrs, item) } /// Marks a function as a SK_SKB Stream Verdict eBPF program that can be attached /// to a SockMap /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.14 /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::stream_verdict, programs::SkBuffContext, bindings::sk_action}; /// /// ///#[stream_verdict] ///fn stream_verdict(ctx: SkBuffContext) -> u32 { /// match { try_stream_verdict(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } ///} /// ///fn try_stream_verdict(_ctx: SkBuffContext) -> Result<u32, u32> { /// Ok(sk_action::SK_PASS) ///} /// ``` #[proc_macro_attribute] pub fn stream_verdict(attrs: TokenStream, item: TokenStream) -> TokenStream { sk_skb(SkSkbKind::StreamVerdict, attrs, item) } fn sk_skb(kind: SkSkbKind, attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SkSkb::from_syn(kind, args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a eBPF Socket Filter program that can be attached to /// a socket. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 3.19 /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::socket_filter, programs::SkBuffContext}; /// /// #[socket_filter(name = "accept_all")] /// pub fn accept_all(_ctx: SkBuffContext) -> i64 { /// return 0 /// } /// ``` #[proc_macro_attribute] pub fn socket_filter(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SocketFilter::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a fentry eBPF program that can be attached to almost /// any function inside the kernel. The difference between fentry and kprobe /// is that fexit has practically zero overhead to call before kernel function. /// fentry programs can be also attached to other eBPF programs. /// /// # Minimumm kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// # #![allow(non_camel_case_types)] /// use aya_bpf::{macros::fentry, programs::FEntryContext}; /// # type filename = u32; /// # type path = u32; /// /// #[fentry(name = "filename_lookup")] /// fn filename_lookup(ctx: FEntryContext) -> i32 { /// match unsafe { try_filename_lookup(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } /// } /// /// unsafe fn try_filename_lookup(ctx: FEntryContext) -> Result<i32, i32> { /// let _f: *const filename = ctx.arg(1); /// let _p: *const path = ctx.arg(3); /// /// Ok(0) /// } /// ``` #[proc_macro_attribute] pub fn fentry(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); FEntry::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a fexit eBPF program that can be attached to almost /// any function inside the kernel. The difference between fexit and kretprobe /// is that fexit has practically zero overhead to call after kernel function /// and it focuses on access to arguments rather than the return value. fexit /// programs can be also attached to other eBPF programs /// /// # Minimumm kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// # #![allow(non_camel_case_types)] /// use aya_bpf::{macros::fexit, programs::FExitContext}; /// # type filename = u32; /// # type path = u32; /// /// #[fexit(name = "filename_lookup")] /// fn filename_lookup(ctx: FExitContext) -> i32 { /// match unsafe { try_filename_lookup(ctx) } { /// Ok(ret) => ret, /// Err(ret) => ret, /// } /// } /// /// unsafe fn try_filename_lookup(ctx: FExitContext) -> Result<i32, i32> { /// let _f: *const filename = ctx.arg(1); /// let _p: *const path = ctx.arg(3); /// /// Ok(0) /// } /// ``` #[proc_macro_attribute] pub fn fexit(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); FExit::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as an eBPF Socket Lookup program that can be attached to /// a network namespace. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.9 /// /// # Examples /// /// ```no_run /// use aya_bpf::{macros::sk_lookup, programs::SkLookupContext}; /// /// #[sk_lookup(name = "redirect")] /// pub fn accept_all(_ctx: SkLookupContext) -> u32 { /// // use sk_assign to redirect /// return 0 /// } /// ``` #[proc_macro_attribute] pub fn sk_lookup(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); SkLookup::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Marks a function as a cgroup device eBPF program that can be attached to a /// cgroup. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.15. /// /// # Examples /// /// ```no_run /// use aya_bpf::{ /// macros::cgroup_device, /// programs::DeviceContext, /// }; /// /// #[cgroup_device(name="cgroup_dev")] /// pub fn cgroup_dev(ctx: DeviceContext) -> i32 { /// // Reject all device access /// return 0; /// } /// ``` #[proc_macro_attribute] pub fn cgroup_device(attrs: TokenStream, item: TokenStream) -> TokenStream { let args = parse_macro_input!(attrs as Args); let item = parse_macro_input!(item as ItemFn); CgroupDevice::from_syn(args, item) .and_then(|u| u.expand()) .unwrap_or_else(|err| err.to_compile_error()) .into() } <file_sep>/aya-log/release.toml shared-version = true <file_sep>/aya/src/pin.rs //! Pinning BPF objects to the BPF filesystem. use std::io; use thiserror::Error; /// An error ocurred working with a pinned BPF object. #[derive(Error, Debug)] pub enum PinError { /// The object has already been pinned. #[error("the BPF object `{name}` has already been pinned")] AlreadyPinned { /// Object name. name: String, }, /// The object FD is not known by Aya. #[error("the BPF object `{name}`'s FD is not known")] NoFd { /// Object name. name: String, }, /// The path for the BPF object is not valid. #[error("invalid pin path `{error}`")] InvalidPinPath { /// The error message. error: String, }, /// An error ocurred making a syscall. #[error("{name} failed")] SyscallError { /// The syscall name. name: String, /// The [`io::Error`] returned by the syscall. #[source] io_error: io::Error, }, } <file_sep>/bpf/aya-bpf/src/programs/sk_buff.rs use core::{ cmp, ffi::c_void, mem::{self, MaybeUninit}, }; use aya_bpf_bindings::helpers::{ bpf_clone_redirect, bpf_get_socket_uid, bpf_l3_csum_replace, bpf_l4_csum_replace, bpf_skb_adjust_room, bpf_skb_change_type, bpf_skb_load_bytes, bpf_skb_pull_data, bpf_skb_store_bytes, }; use aya_bpf_cty::c_long; use crate::{bindings::__sk_buff, BpfContext}; pub struct SkBuff { pub skb: *mut __sk_buff, } impl SkBuff { pub fn new(skb: *mut __sk_buff) -> SkBuff { SkBuff { skb } } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> u32 { unsafe { (*self.skb).len } } #[inline] pub(crate) fn data(&self) -> usize { unsafe { (*self.skb).data as usize } } #[inline] pub(crate) fn data_end(&self) -> usize { unsafe { (*self.skb).data_end as usize } } #[inline] pub fn set_mark(&mut self, mark: u32) { unsafe { (*self.skb).mark = mark } } #[inline] pub fn cb(&self) -> &[u32] { unsafe { &(*self.skb).cb } } #[inline] pub fn cb_mut(&mut self) -> &mut [u32] { unsafe { &mut (*self.skb).cb } } /// Returns the owner UID of the socket associated to the SKB context. #[inline] pub fn get_socket_uid(&self) -> u32 { unsafe { bpf_get_socket_uid(self.skb) } } #[inline] pub fn load<T>(&self, offset: usize) -> Result<T, c_long> { unsafe { let mut data = MaybeUninit::<T>::uninit(); let ret = bpf_skb_load_bytes( self.skb as *const _, offset as u32, &mut data as *mut _ as *mut _, mem::size_of::<T>() as u32, ); if ret == 0 { Ok(data.assume_init()) } else { Err(ret) } } } /// Reads some bytes from the packet into the specified buffer, returning /// how many bytes were read. /// /// Starts reading at `offset` and reads at most `dst.len()` or /// `self.len() - offset` bytes, depending on which one is smaller. /// /// # Examples /// /// Read into a `PerCpuArray`. #[inline(always)] pub fn load_bytes(&self, offset: usize, dst: &mut [u8]) -> Result<usize, c_long> { if offset >= self.len() as usize { return Err(-1); } let len = cmp::min(self.len() as isize - offset as isize, dst.len() as isize); // The verifier rejects the program if it can't see that `len > 0`. if len <= 0 { return Err(-1); } // This is only needed to ensure the verifier can see the upper bound. if len > dst.len() as isize { return Err(-1); } let ret = unsafe { bpf_skb_load_bytes( self.skb as *const _, offset as u32, dst.as_mut_ptr() as *mut _, len as u32, ) }; if ret == 0 { Ok(len as usize) } else { Err(ret) } } #[inline] pub fn store<T>(&mut self, offset: usize, v: &T, flags: u64) -> Result<(), c_long> { unsafe { let ret = bpf_skb_store_bytes( self.skb as *mut _, offset as u32, v as *const _ as *const _, mem::size_of::<T>() as u32, flags, ); if ret == 0 { Ok(()) } else { Err(ret) } } } #[inline] pub fn l3_csum_replace( &self, offset: usize, from: u64, to: u64, size: u64, ) -> Result<(), c_long> { unsafe { let ret = bpf_l3_csum_replace(self.skb as *mut _, offset as u32, from, to, size); if ret == 0 { Ok(()) } else { Err(ret) } } } #[inline] pub fn l4_csum_replace( &self, offset: usize, from: u64, to: u64, flags: u64, ) -> Result<(), c_long> { unsafe { let ret = bpf_l4_csum_replace(self.skb as *mut _, offset as u32, from, to, flags); if ret == 0 { Ok(()) } else { Err(ret) } } } #[inline] pub fn adjust_room(&self, len_diff: i32, mode: u32, flags: u64) -> Result<(), c_long> { let ret = unsafe { bpf_skb_adjust_room(self.as_ptr() as *mut _, len_diff, mode, flags) }; if ret == 0 { Ok(()) } else { Err(ret) } } #[inline] pub fn clone_redirect(&self, if_index: u32, flags: u64) -> Result<(), c_long> { let ret = unsafe { bpf_clone_redirect(self.as_ptr() as *mut _, if_index, flags) }; if ret == 0 { Ok(()) } else { Err(ret) } } #[inline] pub fn change_type(&self, ty: u32) -> Result<(), c_long> { let ret = unsafe { bpf_skb_change_type(self.as_ptr() as *mut _, ty) }; if ret == 0 { Ok(()) } else { Err(ret) } } /// Pulls in non-linear data in case the skb is non-linear. /// /// Make len bytes from skb readable and writable. If a zero value is passed for /// `len`, then the whole length of the skb is pulled. This helper is only needed /// for reading and writing with direct packet access. #[inline(always)] pub fn pull_data(&self, len: u32) -> Result<(), c_long> { let ret = unsafe { bpf_skb_pull_data(self.as_ptr() as *mut _, len) }; if ret == 0 { Ok(()) } else { Err(ret) } } pub(crate) fn as_ptr(&self) -> *mut c_void { self.skb as *mut _ } } pub struct SkBuffContext { pub skb: SkBuff, } impl SkBuffContext { pub fn new(skb: *mut __sk_buff) -> SkBuffContext { let skb = SkBuff { skb }; SkBuffContext { skb } } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> u32 { self.skb.len() } #[inline] pub fn set_mark(&mut self, mark: u32) { self.skb.set_mark(mark) } #[inline] pub fn cb(&self) -> &[u32] { self.skb.cb() } #[inline] pub fn cb_mut(&mut self) -> &mut [u32] { self.skb.cb_mut() } /// Returns the owner UID of the socket associated to the SKB context. #[inline] pub fn get_socket_uid(&self) -> u32 { self.skb.get_socket_uid() } #[inline] pub fn load<T>(&self, offset: usize) -> Result<T, c_long> { self.skb.load(offset) } /// Reads some bytes from the packet into the specified buffer, returning /// how many bytes were read. /// /// Starts reading at `offset` and reads at most `dst.len()` or /// `self.len() - offset` bytes, depending on which one is smaller. /// /// # Examples /// /// Read into a `PerCpuArray`. /// /// ```no_run /// use core::mem; /// /// use aya_bpf::{bindings::TC_ACT_PIPE, macros::map, maps::PerCpuArray, programs::SkBuffContext}; /// # #[allow(non_camel_case_types)] /// # struct ethhdr {}; /// # #[allow(non_camel_case_types)] /// # struct iphdr {}; /// # #[allow(non_camel_case_types)] /// # struct tcphdr {}; /// /// const ETH_HDR_LEN: usize = mem::size_of::<ethhdr>(); /// const IP_HDR_LEN: usize = mem::size_of::<iphdr>(); /// const TCP_HDR_LEN: usize = mem::size_of::<tcphdr>(); /// /// #[repr(C)] /// pub struct Buf { /// pub buf: [u8; 1500], /// } /// /// #[map] /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// /// fn try_cgroup_skb(ctx: SkBuffContext) -> Result<i32, i32> { /// let buf = unsafe { /// let ptr = BUF.get_ptr_mut(0).ok_or(TC_ACT_PIPE)?; /// &mut *ptr /// }; /// let offset = ETH_HDR_LEN + IP_HDR_LEN + TCP_HDR_LEN; /// ctx.load_bytes(offset, &mut buf.buf).map_err(|_| TC_ACT_PIPE)?; /// /// // do something with `buf` /// /// Ok(TC_ACT_PIPE) /// } /// ``` #[inline(always)] pub fn load_bytes(&self, offset: usize, dst: &mut [u8]) -> Result<usize, c_long> { self.skb.load_bytes(offset, dst) } #[inline] pub fn store<T>(&mut self, offset: usize, v: &T, flags: u64) -> Result<(), c_long> { self.skb.store(offset, v, flags) } #[inline] pub fn l3_csum_replace( &self, offset: usize, from: u64, to: u64, size: u64, ) -> Result<(), c_long> { self.skb.l3_csum_replace(offset, from, to, size) } #[inline] pub fn l4_csum_replace( &self, offset: usize, from: u64, to: u64, flags: u64, ) -> Result<(), c_long> { self.skb.l4_csum_replace(offset, from, to, flags) } #[inline] pub fn adjust_room(&self, len_diff: i32, mode: u32, flags: u64) -> Result<(), c_long> { self.skb.adjust_room(len_diff, mode, flags) } #[inline] pub fn clone_redirect(&self, if_index: u32, flags: u64) -> Result<(), c_long> { self.skb.clone_redirect(if_index, flags) } #[inline] pub fn change_type(&self, ty: u32) -> Result<(), c_long> { self.skb.change_type(ty) } /// Pulls in non-linear data in case the skb is non-linear. /// /// Make len bytes from skb readable and writable. If a zero value is passed for /// `len`, then the whole length of the skb is pulled. This helper is only needed /// for reading and writing with direct packet access. /// /// # Examples /// /// ```no_run /// mod bindings; /// use bindings::{ethhdr, iphdr, udphdr}; /// /// const ETH_HLEN: usize = core::mem::size_of::<ethhdr>(); /// const IP_HLEN: usize = core::mem::size_of::<iphdr>(); /// const UDP_HLEN: usize = core::mem::size_of::<udphdr>(); /// /// fn try_cgroup_skb(ctx: SkBuffContext) -> Result<i32, i32> { /// let len = ETH_HLEN + IP_HLEN + UDP_HLEN; /// match ctx.pull_data(len as u32) { /// Ok(_) => return Ok(0), /// Err(ret) => return Err(ret as i32), /// } /// } /// ``` #[inline(always)] pub fn pull_data(&self, len: u32) -> Result<(), c_long> { self.skb.pull_data(len) } } impl BpfContext for SkBuffContext { fn as_ptr(&self) -> *mut c_void { self.skb.as_ptr() } } <file_sep>/test/integration-ebpf/src/test.rs #![no_std] #![no_main] use aya_bpf::{ bindings::xdp_action, macros::{kprobe, xdp}, programs::{ProbeContext, XdpContext}, }; #[xdp(name = "test_unload_xdp")] pub fn pass(ctx: XdpContext) -> u32 { match unsafe { try_pass(ctx) } { Ok(ret) => ret, Err(_) => xdp_action::XDP_ABORTED, } } unsafe fn try_pass(_ctx: XdpContext) -> Result<u32, u32> { Ok(xdp_action::XDP_PASS) } #[kprobe] // truncated name to match bpftool output pub fn test_unload_kpr(_ctx: ProbeContext) -> u32 { 0 } #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachable_unchecked() } } <file_sep>/aya-log/README.md # aya-log - a logging library for eBPF programs ## Overview `aya-log` is a logging library for eBPF programs written using [aya]. Think of it as the [log] crate for eBPF. ## Installation ### User space Add `aya-log` to `Cargo.toml`: ```toml [dependencies] aya-log = { git = "https://github.com/aya-rs/aya", branch = "main" } ``` ### eBPF side Add `aya-log-ebpf` to `Cargo.toml`: ```toml [dependencies] aya-log-ebpf = { git = "https://github.com/aya-rs/aya", branch = "main" } ``` ## Example Here's an example that uses `aya-log` in conjunction with the [env_logger] crate to log eBPF messages to the terminal. ### User space code ```rust use aya_log::BpfLogger; env_logger::init(); // Will log using the default logger, which is TermLogger in this case BpfLogger::init(&mut bpf).unwrap(); ``` ### eBPF code ```rust use aya_log_ebpf::info; fn try_xdp_firewall(ctx: XdpContext) -> Result<u32, ()> { if let Some(port) = tcp_dest_port(&ctx)? { if block_port(port) { info!(&ctx, "❌ blocked incoming connection on port: {}", port); return Ok(XDP_DROP); } } Ok(XDP_PASS) } ``` [aya]: https://github.com/aya-rs/aya [log]: https://docs.rs/log [env_logger]: https://docs.rs/env_logger <file_sep>/bpf/aya-bpf/src/programs/mod.rs pub mod device; pub mod fentry; pub mod fexit; pub mod lsm; pub mod perf_event; pub mod probe; pub mod raw_tracepoint; pub mod sk_buff; pub mod sk_lookup; pub mod sk_msg; pub mod sock; pub mod sock_addr; pub mod sock_ops; pub mod sockopt; pub mod sysctl; pub mod tc; pub mod tp_btf; pub mod tracepoint; pub mod xdp; pub use device::DeviceContext; pub use fentry::FEntryContext; pub use fexit::FExitContext; pub use lsm::LsmContext; pub use perf_event::PerfEventContext; pub use probe::ProbeContext; pub use raw_tracepoint::RawTracePointContext; pub use sk_buff::SkBuffContext; pub use sk_lookup::SkLookupContext; pub use sk_msg::SkMsgContext; pub use sock::SockContext; pub use sock_addr::SockAddrContext; pub use sock_ops::SockOpsContext; pub use sockopt::SockoptContext; pub use sysctl::SysctlContext; pub use tc::TcContext; pub use tp_btf::BtfTracePointContext; pub use tracepoint::TracePointContext; pub use xdp::XdpContext; <file_sep>/aya/src/maps/sock/sock_map.rs //! An array of eBPF program file descriptors used as a jump table. use std::{ convert::{AsMut, AsRef}, os::unix::{io::AsRawFd, prelude::RawFd}, }; use crate::{ maps::{check_bounds, check_kv_size, sock::SockMapFd, MapData, MapError, MapKeys}, sys::{bpf_map_delete_elem, bpf_map_update_elem}, }; /// An array of TCP or UDP sockets. /// /// A `SockMap` is used to store TCP or UDP sockets. eBPF programs can then be /// attached to the map to inspect, filter or redirect network buffers on those /// sockets. /// /// A `SockMap` can also be used to redirect packets to sockets contained by the /// map using `bpf_redirect_map()`, `bpf_sk_redirect_map()` etc. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.14. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::SockMap; /// use aya::programs::SkSkb; /// /// let intercept_ingress = SockMap::try_from(bpf.map("INTERCEPT_INGRESS").unwrap())?; /// let map_fd = intercept_ingress.fd()?; /// /// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?; /// prog.load()?; /// prog.attach(map_fd)?; /// /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_SOCKMAP")] pub struct SockMap<T> { pub(crate) inner: T, } impl<T: AsRef<MapData>> SockMap<T> { pub(crate) fn new(map: T) -> Result<SockMap<T>, MapError> { let data = map.as_ref(); check_kv_size::<u32, RawFd>(data)?; let _fd = data.fd_or_err()?; Ok(SockMap { inner: map }) } /// An iterator over the indices of the array that point to a program. The iterator item type /// is `Result<u32, MapError>`. pub fn indices(&self) -> MapKeys<'_, u32> { MapKeys::new(self.inner.as_ref()) } /// Returns the map's file descriptor. /// /// The returned file descriptor can be used to attach programs that work with /// socket maps, like [`SkMsg`](crate::programs::SkMsg) and [`SkSkb`](crate::programs::SkSkb). pub fn fd(&self) -> Result<SockMapFd, MapError> { Ok(SockMapFd(self.inner.as_ref().fd_or_err()?)) } } impl<T: AsMut<MapData>> SockMap<T> { /// Stores a socket into the map. pub fn set<I: AsRawFd>(&mut self, index: u32, socket: &I, flags: u64) -> Result<(), MapError> { let data = self.inner.as_mut(); let fd = data.fd_or_err()?; check_bounds(data, index)?; bpf_map_update_elem(fd, Some(&index), &socket.as_raw_fd(), flags).map_err( |(_, io_error)| MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, }, )?; Ok(()) } /// Removes the socket stored at `index` from the map. pub fn clear_index(&mut self, index: &u32) -> Result<(), MapError> { let data = self.inner.as_mut(); let fd = data.fd_or_err()?; check_bounds(data, *index)?; bpf_map_delete_elem(fd, index) .map(|_| ()) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_delete_elem".to_owned(), io_error, }) } } <file_sep>/aya/src/sys/bpf.rs use std::{ cmp::{self, min}, ffi::{CStr, CString}, io, mem::{self, MaybeUninit}, os::unix::io::RawFd, slice, }; use libc::{c_char, c_long, close, ENOENT, ENOSPC}; use crate::{ generated::{ bpf_attach_type, bpf_attr, bpf_btf_info, bpf_cmd, bpf_insn, bpf_link_info, bpf_map_info, bpf_prog_info, bpf_prog_type, BPF_F_REPLACE, }, maps::PerCpuValues, obj::{ self, btf::{ BtfParam, BtfType, DataSec, DataSecEntry, DeclTag, Float, Func, FuncLinkage, FuncProto, FuncSecInfo, Int, IntEncoding, LineSecInfo, Ptr, TypeTag, Var, VarLinkage, }, copy_instructions, }, sys::{kernel_version, syscall, SysResult, Syscall}, util::VerifierLog, Btf, Pod, BPF_OBJ_NAME_LEN, }; pub(crate) fn bpf_create_map(name: &CStr, def: &obj::Map, btf_fd: Option<RawFd>) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_1 }; u.map_type = def.map_type(); u.key_size = def.key_size(); u.value_size = def.value_size(); u.max_entries = def.max_entries(); u.map_flags = def.map_flags(); if let obj::Map::Btf(m) = def { u.btf_key_type_id = m.def.btf_key_type_id; u.btf_value_type_id = m.def.btf_value_type_id; u.btf_fd = btf_fd.unwrap() as u32; } // https://github.com/torvalds/linux/commit/ad5b177bd73f5107d97c36f56395c4281fb6f089 // The map name was added as a parameter in kernel 4.15+ so we skip adding it on // older kernels for compatibility let k_ver = kernel_version().unwrap(); if k_ver >= (4, 15, 0) { // u.map_name is 16 bytes max and must be NULL terminated let name_len = cmp::min(name.to_bytes().len(), BPF_OBJ_NAME_LEN - 1); u.map_name[..name_len] .copy_from_slice(unsafe { slice::from_raw_parts(name.as_ptr(), name_len) }); } sys_bpf(bpf_cmd::BPF_MAP_CREATE, &attr) } pub(crate) fn bpf_pin_object(fd: RawFd, path: &CStr) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_4 }; u.bpf_fd = fd as u32; u.pathname = path.as_ptr() as u64; sys_bpf(bpf_cmd::BPF_OBJ_PIN, &attr) } pub(crate) fn bpf_get_object(path: &CStr) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_4 }; u.pathname = path.as_ptr() as u64; sys_bpf(bpf_cmd::BPF_OBJ_GET, &attr) } pub(crate) struct BpfLoadProgramAttrs<'a> { pub(crate) name: Option<CString>, pub(crate) ty: bpf_prog_type, pub(crate) insns: &'a [bpf_insn], pub(crate) license: &'a CStr, pub(crate) kernel_version: u32, pub(crate) expected_attach_type: Option<bpf_attach_type>, pub(crate) prog_btf_fd: Option<RawFd>, pub(crate) attach_btf_obj_fd: Option<u32>, pub(crate) attach_btf_id: Option<u32>, pub(crate) attach_prog_fd: Option<RawFd>, pub(crate) func_info_rec_size: usize, pub(crate) func_info: FuncSecInfo, pub(crate) line_info_rec_size: usize, pub(crate) line_info: LineSecInfo, } pub(crate) fn bpf_load_program( aya_attr: &BpfLoadProgramAttrs, logger: &mut VerifierLog, verifier_log_level: u32, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_3 }; if let Some(prog_name) = &aya_attr.name { let mut name: [c_char; 16] = [0; 16]; let name_bytes = prog_name.to_bytes(); let len = min(name.len(), name_bytes.len()); name[..len].copy_from_slice(unsafe { slice::from_raw_parts(name_bytes.as_ptr() as *const c_char, len) }); u.prog_name = name; } u.prog_type = aya_attr.ty as u32; if let Some(v) = aya_attr.expected_attach_type { u.expected_attach_type = v as u32; } u.insns = aya_attr.insns.as_ptr() as u64; u.insn_cnt = aya_attr.insns.len() as u32; u.license = aya_attr.license.as_ptr() as u64; u.kern_version = aya_attr.kernel_version; // these must be allocated here to ensure the slice outlives the pointer // so .as_ptr below won't point to garbage let line_info_buf = aya_attr.line_info.line_info_bytes(); let func_info_buf = aya_attr.func_info.func_info_bytes(); if let Some(btf_fd) = aya_attr.prog_btf_fd { u.prog_btf_fd = btf_fd as u32; if aya_attr.line_info_rec_size > 0 { u.line_info = line_info_buf.as_ptr() as *const _ as u64; u.line_info_cnt = aya_attr.line_info.len() as u32; u.line_info_rec_size = aya_attr.line_info_rec_size as u32; } if aya_attr.func_info_rec_size > 0 { u.func_info = func_info_buf.as_ptr() as *const _ as u64; u.func_info_cnt = aya_attr.func_info.len() as u32; u.func_info_rec_size = aya_attr.func_info_rec_size as u32; } } let log_buf = logger.buf(); if log_buf.capacity() > 0 { u.log_level = verifier_log_level; u.log_buf = log_buf.as_mut_ptr() as u64; u.log_size = log_buf.capacity() as u32; } if let Some(v) = aya_attr.attach_btf_obj_fd { u.__bindgen_anon_1.attach_btf_obj_fd = v; } if let Some(v) = aya_attr.attach_prog_fd { u.__bindgen_anon_1.attach_prog_fd = v as u32; } if let Some(v) = aya_attr.attach_btf_id { u.attach_btf_id = v; } sys_bpf(bpf_cmd::BPF_PROG_LOAD, &attr) } fn lookup<K: Pod, V: Pod>( fd: RawFd, key: Option<&K>, flags: u64, cmd: bpf_cmd, ) -> Result<Option<V>, (c_long, io::Error)> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let mut value = MaybeUninit::zeroed(); let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; if let Some(key) = key { u.key = key as *const _ as u64; } u.__bindgen_anon_1.value = &mut value as *mut _ as u64; u.flags = flags; match sys_bpf(cmd, &attr) { Ok(_) => Ok(Some(unsafe { value.assume_init() })), Err((_, io_error)) if io_error.raw_os_error() == Some(ENOENT) => Ok(None), Err(e) => Err(e), } } pub(crate) fn bpf_map_lookup_elem<K: Pod, V: Pod>( fd: RawFd, key: &K, flags: u64, ) -> Result<Option<V>, (c_long, io::Error)> { lookup(fd, Some(key), flags, bpf_cmd::BPF_MAP_LOOKUP_ELEM) } pub(crate) fn bpf_map_lookup_and_delete_elem<K: Pod, V: Pod>( fd: RawFd, key: Option<&K>, flags: u64, ) -> Result<Option<V>, (c_long, io::Error)> { lookup(fd, key, flags, bpf_cmd::BPF_MAP_LOOKUP_AND_DELETE_ELEM) } pub(crate) fn bpf_map_lookup_elem_per_cpu<K: Pod, V: Pod>( fd: RawFd, key: &K, flags: u64, ) -> Result<Option<PerCpuValues<V>>, (c_long, io::Error)> { let mut mem = PerCpuValues::<V>::alloc_kernel_mem().map_err(|io_error| (-1, io_error))?; match bpf_map_lookup_elem_ptr(fd, Some(key), mem.as_mut_ptr(), flags) { Ok(_) => Ok(Some(unsafe { PerCpuValues::from_kernel_mem(mem) })), Err((_, io_error)) if io_error.raw_os_error() == Some(ENOENT) => Ok(None), Err(e) => Err(e), } } pub(crate) fn bpf_map_lookup_elem_ptr<K: Pod, V>( fd: RawFd, key: Option<&K>, value: *mut V, flags: u64, ) -> Result<Option<()>, (c_long, io::Error)> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; if let Some(key) = key { u.key = key as *const _ as u64; } u.__bindgen_anon_1.value = value as u64; u.flags = flags; match sys_bpf(bpf_cmd::BPF_MAP_LOOKUP_ELEM, &attr) { Ok(_) => Ok(Some(())), Err((_, io_error)) if io_error.raw_os_error() == Some(ENOENT) => Ok(None), Err(e) => Err(e), } } pub(crate) fn bpf_map_update_elem<K: Pod, V: Pod>( fd: RawFd, key: Option<&K>, value: &V, flags: u64, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; if let Some(key) = key { u.key = key as *const _ as u64; } u.__bindgen_anon_1.value = value as *const _ as u64; u.flags = flags; sys_bpf(bpf_cmd::BPF_MAP_UPDATE_ELEM, &attr) } pub(crate) fn bpf_map_push_elem<V: Pod>(fd: RawFd, value: &V, flags: u64) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; u.__bindgen_anon_1.value = value as *const _ as u64; u.flags = flags; sys_bpf(bpf_cmd::BPF_MAP_UPDATE_ELEM, &attr) } pub(crate) fn bpf_map_update_elem_ptr<K, V>( fd: RawFd, key: *const K, value: *mut V, flags: u64, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; u.key = key as u64; u.__bindgen_anon_1.value = value as u64; u.flags = flags; sys_bpf(bpf_cmd::BPF_MAP_UPDATE_ELEM, &attr) } pub(crate) fn bpf_map_update_elem_per_cpu<K: Pod, V: Pod>( fd: RawFd, key: &K, values: &PerCpuValues<V>, flags: u64, ) -> SysResult { let mut mem = values.build_kernel_mem().map_err(|e| (-1, e))?; bpf_map_update_elem_ptr(fd, key, mem.as_mut_ptr(), flags) } pub(crate) fn bpf_map_delete_elem<K: Pod>(fd: RawFd, key: &K) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; u.key = key as *const _ as u64; sys_bpf(bpf_cmd::BPF_MAP_DELETE_ELEM, &attr) } pub(crate) fn bpf_map_get_next_key<K: Pod>( fd: RawFd, key: Option<&K>, ) -> Result<Option<K>, (c_long, io::Error)> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let mut next_key = MaybeUninit::uninit(); let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; if let Some(key) = key { u.key = key as *const _ as u64; } u.__bindgen_anon_1.next_key = &mut next_key as *mut _ as u64; match sys_bpf(bpf_cmd::BPF_MAP_GET_NEXT_KEY, &attr) { Ok(_) => Ok(Some(unsafe { next_key.assume_init() })), Err((_, io_error)) if io_error.raw_os_error() == Some(ENOENT) => Ok(None), Err(e) => Err(e), } } // since kernel 5.2 pub(crate) fn bpf_map_freeze(fd: RawFd) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_2 }; u.map_fd = fd as u32; sys_bpf(bpf_cmd::BPF_MAP_FREEZE, &attr) } // since kernel 5.7 pub(crate) fn bpf_link_create( prog_fd: RawFd, target_fd: RawFd, attach_type: bpf_attach_type, btf_id: Option<u32>, flags: u32, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.link_create.prog_fd = prog_fd as u32; attr.link_create.__bindgen_anon_1.target_fd = target_fd as u32; attr.link_create.attach_type = attach_type as u32; attr.link_create.flags = flags; if let Some(btf_id) = btf_id { attr.link_create.__bindgen_anon_2.target_btf_id = btf_id; } sys_bpf(bpf_cmd::BPF_LINK_CREATE, &attr) } // since kernel 5.7 pub(crate) fn bpf_link_update( link_fd: RawFd, new_prog_fd: RawFd, old_prog_fd: Option<RawFd>, flags: u32, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.link_update.link_fd = link_fd as u32; attr.link_update.new_prog_fd = new_prog_fd as u32; if let Some(fd) = old_prog_fd { attr.link_update.old_prog_fd = fd as u32; attr.link_update.flags = flags | BPF_F_REPLACE; } else { attr.link_update.flags = flags; } sys_bpf(bpf_cmd::BPF_LINK_UPDATE, &attr) } pub(crate) fn bpf_prog_attach( prog_fd: RawFd, target_fd: RawFd, attach_type: bpf_attach_type, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.__bindgen_anon_5.attach_bpf_fd = prog_fd as u32; attr.__bindgen_anon_5.target_fd = target_fd as u32; attr.__bindgen_anon_5.attach_type = attach_type as u32; sys_bpf(bpf_cmd::BPF_PROG_ATTACH, &attr) } pub(crate) fn bpf_prog_detach( prog_fd: RawFd, map_fd: RawFd, attach_type: bpf_attach_type, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.__bindgen_anon_5.attach_bpf_fd = prog_fd as u32; attr.__bindgen_anon_5.target_fd = map_fd as u32; attr.__bindgen_anon_5.attach_type = attach_type as u32; sys_bpf(bpf_cmd::BPF_PROG_DETACH, &attr) } pub(crate) fn bpf_prog_query( target_fd: RawFd, attach_type: bpf_attach_type, query_flags: u32, attach_flags: Option<&mut u32>, prog_ids: &mut [u32], prog_cnt: &mut u32, ) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.query.target_fd = target_fd as u32; attr.query.attach_type = attach_type as u32; attr.query.query_flags = query_flags; attr.query.prog_cnt = prog_ids.len() as u32; attr.query.prog_ids = prog_ids.as_mut_ptr() as u64; let ret = sys_bpf(bpf_cmd::BPF_PROG_QUERY, &attr); *prog_cnt = unsafe { attr.query.prog_cnt }; if let Some(attach_flags) = attach_flags { *attach_flags = unsafe { attr.query.attach_flags }; } ret } pub(crate) fn bpf_prog_get_fd_by_id(prog_id: u32) -> Result<RawFd, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.__bindgen_anon_6.__bindgen_anon_1.prog_id = prog_id; match sys_bpf(bpf_cmd::BPF_PROG_GET_FD_BY_ID, &attr) { Ok(v) => Ok(v as RawFd), Err((_, err)) => Err(err), } } pub(crate) fn bpf_prog_get_info_by_fd(prog_fd: RawFd) -> Result<bpf_prog_info, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; // info gets entirely populated by the kernel let info = MaybeUninit::zeroed(); attr.info.bpf_fd = prog_fd as u32; attr.info.info = &info as *const _ as u64; attr.info.info_len = mem::size_of::<bpf_prog_info>() as u32; match sys_bpf(bpf_cmd::BPF_OBJ_GET_INFO_BY_FD, &attr) { Ok(_) => Ok(unsafe { info.assume_init() }), Err((_, err)) => Err(err), } } pub(crate) fn bpf_map_get_info_by_fd(prog_fd: RawFd) -> Result<bpf_map_info, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; // info gets entirely populated by the kernel let info = MaybeUninit::zeroed(); attr.info.bpf_fd = prog_fd as u32; attr.info.info = info.as_ptr() as *const _ as u64; attr.info.info_len = mem::size_of::<bpf_map_info>() as u32; match sys_bpf(bpf_cmd::BPF_OBJ_GET_INFO_BY_FD, &attr) { Ok(_) => Ok(unsafe { info.assume_init() }), Err((_, err)) => Err(err), } } pub(crate) fn bpf_link_get_info_by_fd(link_fd: RawFd) -> Result<bpf_link_info, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; // info gets entirely populated by the kernel let info = unsafe { MaybeUninit::zeroed().assume_init() }; attr.info.bpf_fd = link_fd as u32; attr.info.info = &info as *const _ as u64; attr.info.info_len = mem::size_of::<bpf_link_info>() as u32; match sys_bpf(bpf_cmd::BPF_OBJ_GET_INFO_BY_FD, &attr) { Ok(_) => Ok(info), Err((_, err)) => Err(err), } } pub(crate) fn btf_obj_get_info_by_fd( prog_fd: RawFd, buf: &mut [u8], ) -> Result<bpf_btf_info, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let mut info = unsafe { mem::zeroed::<bpf_btf_info>() }; let buf_size = buf.len() as u32; info.btf = buf.as_ptr() as u64; info.btf_size = buf_size; attr.info.bpf_fd = prog_fd as u32; attr.info.info = &info as *const bpf_btf_info as u64; attr.info.info_len = mem::size_of::<bpf_btf_info>() as u32; match sys_bpf(bpf_cmd::BPF_OBJ_GET_INFO_BY_FD, &attr) { Ok(_) => Ok(info), Err((_, err)) => Err(err), } } pub(crate) fn bpf_raw_tracepoint_open(name: Option<&CStr>, prog_fd: RawFd) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.raw_tracepoint.name = match name { Some(n) => n.as_ptr() as u64, None => 0, }; attr.raw_tracepoint.prog_fd = prog_fd as u32; sys_bpf(bpf_cmd::BPF_RAW_TRACEPOINT_OPEN, &attr) } pub(crate) fn bpf_load_btf(raw_btf: &[u8], log: &mut VerifierLog) -> SysResult { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = raw_btf.as_ptr() as *const _ as u64; u.btf_size = mem::size_of_val(raw_btf) as u32; let log_buf = log.buf(); if log_buf.capacity() > 0 { u.btf_log_level = 1; u.btf_log_buf = log_buf.as_mut_ptr() as u64; u.btf_log_size = log_buf.capacity() as u32; } sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) } pub(crate) fn bpf_btf_get_fd_by_id(id: u32) -> Result<RawFd, io::Error> { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; attr.__bindgen_anon_6.__bindgen_anon_1.btf_id = id; match sys_bpf(bpf_cmd::BPF_BTF_GET_FD_BY_ID, &attr) { Ok(v) => Ok(v as RawFd), Err((_, err)) => Err(err), } } pub(crate) fn is_prog_name_supported() -> bool { let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_3 }; let mut name: [c_char; 16] = [0; 16]; let cstring = CString::new("aya_name_check").unwrap(); let name_bytes = cstring.to_bytes(); let len = min(name.len(), name_bytes.len()); name[..len].copy_from_slice(unsafe { slice::from_raw_parts(name_bytes.as_ptr() as *const c_char, len) }); u.prog_name = name; let prog: &[u8] = &[ 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov64 r0 = 0 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // exit ]; let gpl = b"GPL\0"; u.license = gpl.as_ptr() as u64; let insns = copy_instructions(prog).unwrap(); u.insn_cnt = insns.len() as u32; u.insns = insns.as_ptr() as u64; u.prog_type = bpf_prog_type::BPF_PROG_TYPE_SOCKET_FILTER as u32; match sys_bpf(bpf_cmd::BPF_PROG_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); btf.add_type(int_type); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_func_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let a_name = btf.add_string("a".to_string()); let b_name = btf.add_string("b".to_string()); let params = vec![ BtfParam { name_offset: a_name, btf_type: int_type_id, }, BtfParam { name_offset: b_name, btf_type: int_type_id, }, ]; let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id)); let func_proto_type_id = btf.add_type(func_proto); let add = btf.add_string("inc".to_string()); let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Static)); btf.add_type(func); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_func_global_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let a_name = btf.add_string("a".to_string()); let b_name = btf.add_string("b".to_string()); let params = vec![ BtfParam { name_offset: a_name, btf_type: int_type_id, }, BtfParam { name_offset: b_name, btf_type: int_type_id, }, ]; let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id)); let func_proto_type_id = btf.add_type(func_proto); let add = btf.add_string("inc".to_string()); let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Global)); btf.add_type(func); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_datasec_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let name_offset = btf.add_string("foo".to_string()); let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static)); let var_type_id = btf.add_type(var_type); let name_offset = btf.add_string(".data".to_string()); let variables = vec![DataSecEntry { btf_type: var_type_id, offset: 0, size: 4, }]; let datasec_type = BtfType::DataSec(DataSec::new(name_offset, variables, 4)); btf.add_type(datasec_type); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_float_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("float".to_string()); let float_type = BtfType::Float(Float::new(name_offset, 16)); btf.add_type(float_type); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_decl_tag_supported() -> bool { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let name_offset = btf.add_string("foo".to_string()); let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static)); let var_type_id = btf.add_type(var_type); let name_offset = btf.add_string("decl_tag".to_string()); let decl_tag = BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1)); btf.add_type(decl_tag); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub(crate) fn is_btf_type_tag_supported() -> bool { let mut btf = Btf::new(); let int_type = BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let name_offset = btf.add_string("int".to_string()); let type_tag = BtfType::TypeTag(TypeTag::new(name_offset, int_type_id)); let type_tag_type = btf.add_type(type_tag); btf.add_type(BtfType::Ptr(Ptr::new(0, type_tag_type))); let btf_bytes = btf.to_bytes(); let mut attr = unsafe { mem::zeroed::<bpf_attr>() }; let u = unsafe { &mut attr.__bindgen_anon_7 }; u.btf = btf_bytes.as_ptr() as u64; u.btf_size = btf_bytes.len() as u32; match sys_bpf(bpf_cmd::BPF_BTF_LOAD, &attr) { Ok(v) => { let fd = v as RawFd; unsafe { close(fd) }; true } Err(_) => false, } } pub fn sys_bpf(cmd: bpf_cmd, attr: &bpf_attr) -> SysResult { syscall(Syscall::Bpf { cmd, attr }) } pub(crate) fn retry_with_verifier_logs<F>( max_retries: usize, log: &mut VerifierLog, f: F, ) -> SysResult where F: Fn(&mut VerifierLog) -> SysResult, { // 1. Try the syscall let ret = f(log); if ret.is_ok() { return ret; } // 2. Grow the log buffer so we can capture verifier output // Retry this up to max_retries times log.grow(); let mut retries = 0; loop { let ret = f(log); match ret { Err((v, io_error)) if retries == 0 || io_error.raw_os_error() == Some(ENOSPC) => { if retries == max_retries { return Err((v, io_error)); } retries += 1; log.grow(); } r => return r, } } } <file_sep>/xtask/src/docs/mod.rs use std::{ path::{Path, PathBuf}, process::Command, }; use std::{fs, io, io::Write}; use indoc::indoc; pub fn docs() -> Result<(), anyhow::Error> { let current_dir = PathBuf::from("."); let header_path = current_dir.join("header.html"); let mut header = fs::File::create(&header_path).expect("can't create header.html"); header .write_all(r#"<meta name="robots" content="noindex">"#.as_bytes()) .expect("can't write header.html contents"); header.flush().expect("couldn't flush contents"); let abs_header_path = fs::canonicalize(&header_path).unwrap(); build_docs(&current_dir.join("aya"), &abs_header_path)?; build_docs(&current_dir.join("bpf/aya-bpf"), &abs_header_path)?; copy_dir_all("./target/doc", "./site/user")?; copy_dir_all("./target/bpfel-unknown-none/doc", "./site/bpf")?; let mut robots = fs::File::create("site/robots.txt").expect("can't create robots.txt"); robots .write_all( indoc! {r#" User-Agent:* Disallow: / "#} .as_bytes(), ) .expect("can't write robots.txt"); let mut index = fs::File::create("site/index.html").expect("can't create index.html"); index .write_all( indoc! {r#" <html> <meta name="robots" content="noindex"> <body> <ul> <li><a href="user/aya/index.html">Aya User-space Development Documentation</a></li> <li><a href="bpf/aya_bpf/index.html">Aya Kernel-space Development Documentation</a></li> </ul> </body> </html> "#} .as_bytes(), ) .expect("can't write index.html"); Ok(()) } fn build_docs(working_dir: &PathBuf, abs_header_path: &Path) -> Result<(), anyhow::Error> { let replace = Command::new("sed") .current_dir(working_dir) .args(vec!["-i.bak", "s/crabby.svg/crabby_dev.svg/", "src/lib.rs"]) .status() .expect("failed to replace logo"); assert!(replace.success()); let args = vec!["+nightly", "doc", "--no-deps", "--all-features"]; let status = Command::new("cargo") .current_dir(working_dir) .env( "RUSTDOCFLAGS", format!( "--cfg docsrs --html-in-header {} -D warnings", abs_header_path.to_str().unwrap() ), ) .args(&args) .status() .expect("failed to build aya docs"); assert!(status.success()); fs::rename( working_dir.join("src/lib.rs.bak"), working_dir.join("src/lib.rs"), ) .unwrap(); Ok(()) } fn copy_dir_all<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) -> io::Result<()> { fs::create_dir_all(&dst)?; for entry in fs::read_dir(src)? { let entry = entry?; let ty = entry.file_type()?; if ty.is_dir() { copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?; } else { let new_path = dst.as_ref().join(entry.file_name()); if !new_path.exists() { fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?; } } } Ok(()) } <file_sep>/aya/src/programs/links.rs //! Program links. use libc::{close, dup}; use thiserror::Error; use std::{ collections::{hash_map::Entry, HashMap}, ffi::CString, io, os::unix::prelude::RawFd, path::{Path, PathBuf}, }; use crate::{ generated::bpf_attach_type, pin::PinError, programs::ProgramError, sys::{bpf_get_object, bpf_pin_object, bpf_prog_detach}, }; /// A Link. pub trait Link: std::fmt::Debug + 'static { /// Unique Id type Id: std::fmt::Debug + std::hash::Hash + Eq + PartialEq; /// Returns the link id fn id(&self) -> Self::Id; /// Detaches the LinkOwnedLink is gone... but this doesn't work :( fn detach(self) -> Result<(), ProgramError>; } #[derive(Debug)] pub(crate) struct LinkMap<T: Link> { links: HashMap<T::Id, T>, } impl<T: Link> LinkMap<T> { pub(crate) fn new() -> LinkMap<T> { LinkMap { links: HashMap::new(), } } pub(crate) fn insert(&mut self, link: T) -> Result<T::Id, ProgramError> { let id = link.id(); match self.links.entry(link.id()) { Entry::Occupied(_) => return Err(ProgramError::AlreadyAttached), Entry::Vacant(e) => e.insert(link), }; Ok(id) } pub(crate) fn remove(&mut self, link_id: T::Id) -> Result<(), ProgramError> { self.links .remove(&link_id) .ok_or(ProgramError::NotAttached)? .detach() } pub(crate) fn remove_all(&mut self) -> Result<(), ProgramError> { for (_, link) in self.links.drain() { link.detach()?; } Ok(()) } pub(crate) fn forget(&mut self, link_id: T::Id) -> Result<T, ProgramError> { self.links.remove(&link_id).ok_or(ProgramError::NotAttached) } } impl<T: Link> Drop for LinkMap<T> { fn drop(&mut self) { let _ = self.remove_all(); } } /// The identifier of an `FdLink`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct FdLinkId(pub(crate) RawFd); /// A file descriptor link. #[derive(Debug)] pub struct FdLink { pub(crate) fd: RawFd, } impl FdLink { pub(crate) fn new(fd: RawFd) -> FdLink { FdLink { fd } } /// Pins the link to a BPF file system. /// /// When a link is pinned it will remain attached even after the link instance is dropped, /// and will only be detached once the pinned file is removed. To unpin, see [`PinnedLink::unpin()`]. /// /// The parent directories in the provided path must already exist before calling this method, /// and must be on a BPF file system (bpffs). /// /// # Example /// ```no_run /// # use aya::programs::{links::FdLink, Extension}; /// # use std::convert::TryInto; /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # #[error(transparent)] /// # Pin(#[from] aya::pin::PinError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// # let prog: &mut Extension = bpf.program_mut("example").unwrap().try_into()?; /// let link_id = prog.attach()?; /// let owned_link = prog.take_link(link_id)?; /// let fd_link: FdLink = owned_link.into(); /// let pinned_link = fd_link.pin("/sys/fs/bpf/example")?; /// # Ok::<(), Error>(()) /// ``` pub fn pin<P: AsRef<Path>>(self, path: P) -> Result<PinnedLink, PinError> { let path_string = CString::new(path.as_ref().to_string_lossy().into_owned()).map_err(|e| { PinError::InvalidPinPath { error: e.to_string(), } })?; bpf_pin_object(self.fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { name: "BPF_OBJ_PIN".to_string(), io_error, })?; Ok(PinnedLink::new(PathBuf::from(path.as_ref()), self)) } } impl Link for FdLink { type Id = FdLinkId; fn id(&self) -> Self::Id { FdLinkId(self.fd) } fn detach(self) -> Result<(), ProgramError> { // detach is a noop since it consumes self. once self is consumed, drop will be triggered // and the link will be detached. // // Other links don't need to do this since they use define_link_wrapper!, but FdLink is a // bit special in that it defines a custom ::new() so it can't use the macro. Ok(()) } } impl From<PinnedLink> for FdLink { fn from(p: PinnedLink) -> Self { p.inner } } impl Drop for FdLink { fn drop(&mut self) { unsafe { close(self.fd) }; } } /// A pinned file descriptor link. /// /// This link has been pinned to the BPF filesystem. On drop, the file descriptor that backs /// this link will be closed. Whether or not the program remains attached is dependent /// on the presence of the file in BPFFS. #[derive(Debug)] pub struct PinnedLink { inner: FdLink, path: PathBuf, } impl PinnedLink { fn new(path: PathBuf, link: FdLink) -> Self { PinnedLink { inner: link, path } } /// Creates a [`PinnedLink`] from a valid path on bpffs. pub fn from_pin<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> { let path_string = CString::new(path.as_ref().to_string_lossy().to_string()).unwrap(); let fd = bpf_get_object(&path_string).map_err(|(code, io_error)| LinkError::SyscallError { call: "BPF_OBJ_GET".to_string(), code, io_error, })? as RawFd; Ok(PinnedLink::new( path.as_ref().to_path_buf(), FdLink::new(fd), )) } /// Removes the pinned link from the filesystem and returns an [`FdLink`]. pub fn unpin(self) -> Result<FdLink, io::Error> { std::fs::remove_file(self.path)?; Ok(self.inner) } } /// The identifier of a `ProgAttachLink`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct ProgAttachLinkId(RawFd, RawFd, bpf_attach_type); /// The Link type used by programs that are attached with `bpf_prog_attach`. #[derive(Debug)] pub struct ProgAttachLink { prog_fd: RawFd, target_fd: RawFd, attach_type: bpf_attach_type, } impl ProgAttachLink { pub(crate) fn new( prog_fd: RawFd, target_fd: RawFd, attach_type: bpf_attach_type, ) -> ProgAttachLink { ProgAttachLink { prog_fd, target_fd: unsafe { dup(target_fd) }, attach_type, } } } impl Link for ProgAttachLink { type Id = ProgAttachLinkId; fn id(&self) -> Self::Id { ProgAttachLinkId(self.prog_fd, self.target_fd, self.attach_type) } fn detach(self) -> Result<(), ProgramError> { let _ = bpf_prog_detach(self.prog_fd, self.target_fd, self.attach_type); unsafe { close(self.target_fd) }; Ok(()) } } macro_rules! define_link_wrapper { (#[$doc1:meta] $wrapper:ident, #[$doc2:meta] $wrapper_id:ident, $base:ident, $base_id:ident) => { #[$doc2] #[derive(Debug, Hash, Eq, PartialEq)] pub struct $wrapper_id($base_id); #[$doc1] #[derive(Debug)] pub struct $wrapper(Option<$base>); #[allow(dead_code)] // allow dead code since currently XDP is the only consumer of inner and // into_inner impl $wrapper { fn new(base: $base) -> $wrapper { $wrapper(Some(base)) } fn inner(&self) -> &$base { self.0.as_ref().unwrap() } fn into_inner(mut self) -> $base { self.0.take().unwrap() } } impl Drop for $wrapper { fn drop(&mut self) { use crate::programs::links::Link; if let Some(base) = self.0.take() { let _ = base.detach(); } } } impl crate::programs::Link for $wrapper { type Id = $wrapper_id; fn id(&self) -> Self::Id { $wrapper_id(self.0.as_ref().unwrap().id()) } fn detach(mut self) -> Result<(), ProgramError> { self.0.take().unwrap().detach() } } impl From<$base> for $wrapper { fn from(b: $base) -> $wrapper { $wrapper(Some(b)) } } impl From<$wrapper> for $base { fn from(mut w: $wrapper) -> $base { w.0.take().unwrap() } } }; } pub(crate) use define_link_wrapper; #[derive(Error, Debug)] /// Errors from operations on links. pub enum LinkError { /// Invalid link. #[error("Invalid link")] InvalidLink, /// Syscall failed. #[error("the `{call}` syscall failed with code {code}")] SyscallError { /// Syscall Name. call: String, /// Error code. code: libc::c_long, #[source] /// Original io::Error. io_error: io::Error, }, } #[cfg(test)] mod tests { use std::{cell::RefCell, env, fs::File, mem, os::unix::io::AsRawFd, rc::Rc}; use crate::{programs::ProgramError, sys::override_syscall}; use super::{FdLink, Link, LinkMap}; #[derive(Debug, Hash, Eq, PartialEq)] struct TestLinkId(u8, u8); #[derive(Debug)] struct TestLink { id: (u8, u8), detached: Rc<RefCell<u8>>, } impl TestLink { fn new(a: u8, b: u8) -> TestLink { TestLink { id: (a, b), detached: Rc::new(RefCell::new(0)), } } } impl Link for TestLink { type Id = TestLinkId; fn id(&self) -> Self::Id { TestLinkId(self.id.0, self.id.1) } fn detach(self) -> Result<(), ProgramError> { *self.detached.borrow_mut() += 1; Ok(()) } } #[test] fn test_link_map() { let mut links = LinkMap::new(); let l1 = TestLink::new(1, 2); let l1_detached = Rc::clone(&l1.detached); let l2 = TestLink::new(1, 3); let l2_detached = Rc::clone(&l2.detached); let id1 = links.insert(l1).unwrap(); let id2 = links.insert(l2).unwrap(); assert!(*l1_detached.borrow() == 0); assert!(*l2_detached.borrow() == 0); assert!(links.remove(id1).is_ok()); assert!(*l1_detached.borrow() == 1); assert!(*l2_detached.borrow() == 0); assert!(links.remove(id2).is_ok()); assert!(*l1_detached.borrow() == 1); assert!(*l2_detached.borrow() == 1); } #[test] fn test_already_attached() { let mut links = LinkMap::new(); links.insert(TestLink::new(1, 2)).unwrap(); assert!(matches!( links.insert(TestLink::new(1, 2)), Err(ProgramError::AlreadyAttached) )); } #[test] fn test_not_attached() { let mut links = LinkMap::new(); let l1 = TestLink::new(1, 2); let l1_id1 = l1.id(); let l1_id2 = l1.id(); links.insert(TestLink::new(1, 2)).unwrap(); links.remove(l1_id1).unwrap(); assert!(matches!( links.remove(l1_id2), Err(ProgramError::NotAttached) )); } #[test] fn test_drop_detach() { let l1 = TestLink::new(1, 2); let l1_detached = Rc::clone(&l1.detached); let l2 = TestLink::new(1, 3); let l2_detached = Rc::clone(&l2.detached); { let mut links = LinkMap::new(); let id1 = links.insert(l1).unwrap(); links.insert(l2).unwrap(); // manually remove one link assert!(links.remove(id1).is_ok()); assert!(*l1_detached.borrow() == 1); assert!(*l2_detached.borrow() == 0); } // remove the other on drop assert!(*l1_detached.borrow() == 1); assert!(*l2_detached.borrow() == 1); } #[test] fn test_owned_detach() { let l1 = TestLink::new(1, 2); let l1_detached = Rc::clone(&l1.detached); let l2 = TestLink::new(1, 3); let l2_detached = Rc::clone(&l2.detached); let owned_l1 = { let mut links = LinkMap::new(); let id1 = links.insert(l1).unwrap(); links.insert(l2).unwrap(); // manually forget one link let owned_l1 = links.forget(id1); assert!(*l1_detached.borrow() == 0); assert!(*l2_detached.borrow() == 0); owned_l1.unwrap() }; // l2 is detached on `Drop`, but l1 is still alive assert!(*l1_detached.borrow() == 0); assert!(*l2_detached.borrow() == 1); // manually detach l1 assert!(owned_l1.detach().is_ok()); assert!(*l1_detached.borrow() == 1); assert!(*l2_detached.borrow() == 1); } #[test] #[cfg_attr(miri, ignore)] fn test_pin() { let dir = env::temp_dir(); let f1 = File::create(dir.join("f1")).expect("unable to create file in tmpdir"); let fd_link = FdLink::new(f1.as_raw_fd()); // leak the fd, it will get closed when our pinned link is dropped mem::forget(f1); // override syscall to allow for pin to happen in our tmpdir override_syscall(|_| Ok(0)); // create the file that would have happened as a side-effect of a real pin operation File::create(dir.join("f1-pin")).expect("unable to create file in tmpdir"); assert!(dir.join("f1-pin").exists()); let pinned_link = fd_link.pin(dir.join("f1-pin")).expect("pin failed"); pinned_link.unpin().expect("unpin failed"); assert!(!dir.join("f1-pin").exists()); } } <file_sep>/test/integration-ebpf/src/bpf/multimap-btf.bpf.c #include <linux/bpf.h> #include <bpf/bpf_helpers.h> struct { __uint(type, BPF_MAP_TYPE_ARRAY); __type(key, __u32); __type(value, __u64); __uint(max_entries, 1); } map_1 SEC(".maps"); struct { __uint(type, BPF_MAP_TYPE_ARRAY); __type(key, __u32); __type(value, __u64); __uint(max_entries, 1); } map_2 SEC(".maps"); SEC("tracepoint") int bpf_prog(void *ctx) { __u32 key = 0; __u64 twenty_four = 24; __u64 forty_two = 42; bpf_map_update_elem(&map_1, &key, &twenty_four, BPF_ANY); bpf_map_update_elem(&map_2, &key, &forty_two, BPF_ANY); return 0; } char _license[] SEC("license") = "GPL"; <file_sep>/bpf/aya-bpf/src/programs/sockopt.rs use core::ffi::c_void; use crate::{bindings::bpf_sockopt, BpfContext}; pub struct SockoptContext { pub sockopt: *mut bpf_sockopt, } impl SockoptContext { pub fn new(sockopt: *mut bpf_sockopt) -> SockoptContext { SockoptContext { sockopt } } } impl BpfContext for SockoptContext { fn as_ptr(&self) -> *mut c_void { self.sockopt as *mut _ } } <file_sep>/bpf/aya-bpf/src/maps/program_array.rs use core::{cell::UnsafeCell, hint::unreachable_unchecked, mem}; use aya_bpf_cty::c_long; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_PROG_ARRAY}, helpers::bpf_tail_call, maps::PinningType, BpfContext, }; /// A BPF map that stores an array of program indices for tail calling. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// use aya_bpf::{macros::map, maps::ProgramArray, cty::c_long}; /// # use aya_bpf::{programs::LsmContext}; /// /// #[map] /// static JUMP_TABLE: ProgramArray = ProgramArray::with_max_entries(16, 0); /// /// # unsafe fn try_test(ctx: &LsmContext) -> Result<(), c_long> { /// let index: u32 = 13; /// /// if let Err(e) = JUMP_TABLE.tail_call(ctx, index) { /// return Err(e); /// } /// /// # Err(-1) /// } /// ``` #[repr(transparent)] pub struct ProgramArray { def: UnsafeCell<bpf_map_def>, } unsafe impl Sync for ProgramArray {} impl ProgramArray { pub const fn with_max_entries(max_entries: u32, flags: u32) -> ProgramArray { ProgramArray { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_PROG_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), } } pub const fn pinned(max_entries: u32, flags: u32) -> ProgramArray { ProgramArray { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_PROG_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), } } /// Perform a tail call into a program indexed by this map. /// /// # Safety /// /// This function is inherently unsafe, since it causes control flow to jump into /// another eBPF program. This can have side effects, such as drop methods not being /// called. Note that tail calling into an eBPF program is not the same thing as /// a function call -- control flow never returns to the caller. /// /// # Return Value /// /// On success, this function **does not return** into the original program. /// On failure, a negative error is returned, wrapped in `Err()`. #[cfg(not(unstable))] pub unsafe fn tail_call<C: BpfContext>(&self, ctx: &C, index: u32) -> Result<(), c_long> { let res = bpf_tail_call(ctx.as_ptr(), self.def.get() as *mut _, index); if res != 0 { Err(res) } else { unreachable_unchecked() } } /// Perform a tail call into a program indexed by this map. /// /// # Safety /// /// This function is inherently unsafe, since it causes control flow to jump into /// another eBPF program. This can have side effects, such as drop methods not being /// called. Note that tail calling into an eBPF program is not the same thing as /// a function call -- control flow never returns to the caller. /// /// # Return Value /// /// On success, this function **does not return** into the original program. /// On failure, a negative error is returned, wrapped in `Err()`. #[cfg(unstable)] pub unsafe fn tail_call<C: BpfContext>(&self, ctx: &C, index: u32) -> Result<!, c_long> { let res = bpf_tail_call(ctx.as_ptr(), self.def.get() as *mut _, index); if res != 0 { Err(res) } else { unreachable_unchecked() } } } <file_sep>/xtask/src/main.rs mod build_ebpf; mod build_test; mod codegen; mod docs; mod run; pub(crate) mod utils; use std::process::exit; use clap::Parser; #[derive(Parser)] pub struct XtaskOptions { #[clap(subcommand)] command: Command, } #[derive(Parser)] enum Command { Codegen(codegen::Options), Docs, BuildIntegrationTest(build_test::Options), BuildIntegrationTestEbpf(build_ebpf::BuildEbpfOptions), IntegrationTest(run::Options), } fn main() { let opts = XtaskOptions::parse(); use Command::*; let ret = match opts.command { Codegen(opts) => codegen::codegen(opts), Docs => docs::docs(), BuildIntegrationTest(opts) => build_test::build_test(opts), BuildIntegrationTestEbpf(opts) => build_ebpf::build_ebpf(opts), IntegrationTest(opts) => run::run(opts), }; if let Err(e) = ret { eprintln!("{e:#}"); exit(1); } } <file_sep>/aya/src/util.rs //! Utility functions. use std::{ collections::BTreeMap, ffi::{CStr, CString}, fs::{self, File}, io::{self, BufReader}, mem, slice, str::FromStr, }; use crate::generated::{TC_H_MAJ_MASK, TC_H_MIN_MASK}; use libc::{if_nametoindex, sysconf, _SC_PAGESIZE}; use io::BufRead; const ONLINE_CPUS: &str = "/sys/devices/system/cpu/online"; pub(crate) const POSSIBLE_CPUS: &str = "/sys/devices/system/cpu/possible"; /// Returns the numeric IDs of the CPUs currently online. pub fn online_cpus() -> Result<Vec<u32>, io::Error> { let data = fs::read_to_string(ONLINE_CPUS)?; parse_cpu_ranges(data.trim()).map_err(|_| { io::Error::new( io::ErrorKind::Other, format!("unexpected {ONLINE_CPUS} format"), ) }) } /// Get the number of possible cpus. /// /// See `/sys/devices/system/cpu/possible`. pub fn nr_cpus() -> Result<usize, io::Error> { Ok(possible_cpus()?.len()) } /// Get the list of possible cpus. /// /// See `/sys/devices/system/cpu/possible`. pub(crate) fn possible_cpus() -> Result<Vec<u32>, io::Error> { let data = fs::read_to_string(POSSIBLE_CPUS)?; parse_cpu_ranges(data.trim()).map_err(|_| { io::Error::new( io::ErrorKind::Other, format!("unexpected {POSSIBLE_CPUS} format"), ) }) } fn parse_cpu_ranges(data: &str) -> Result<Vec<u32>, ()> { let mut cpus = Vec::new(); for range in data.split(',') { cpus.extend({ match range .splitn(2, '-') .map(u32::from_str) .collect::<Result<Vec<_>, _>>() .map_err(|_| ())? .as_slice() { &[] | &[_, _, _, ..] => return Err(()), &[start] => start..=start, &[start, end] => start..=end, } }) } Ok(cpus) } /// Loads kernel symbols from `/proc/kallsyms`. /// /// The symbols can be passed to [`StackTrace::resolve`](crate::maps::stack_trace::StackTrace::resolve). pub fn kernel_symbols() -> Result<BTreeMap<u64, String>, io::Error> { let mut reader = BufReader::new(File::open("/proc/kallsyms")?); parse_kernel_symbols(&mut reader) } fn parse_kernel_symbols(reader: impl BufRead) -> Result<BTreeMap<u64, String>, io::Error> { let mut syms = BTreeMap::new(); for line in reader.lines() { let line = line?; let parts = line.splitn(4, ' ').collect::<Vec<_>>(); let addr = u64::from_str_radix(parts[0], 16) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, line.clone()))?; let name = parts[2].to_owned(); syms.insert(addr, name); } Ok(syms) } pub(crate) fn ifindex_from_ifname(if_name: &str) -> Result<u32, io::Error> { let c_str_if_name = CString::new(if_name)?; let c_if_name = c_str_if_name.as_ptr(); // Safety: libc wrapper let if_index = unsafe { if_nametoindex(c_if_name) }; if if_index == 0 { return Err(io::Error::last_os_error()); } Ok(if_index) } pub(crate) fn tc_handler_make(major: u32, minor: u32) -> u32 { (major & TC_H_MAJ_MASK) | (minor & TC_H_MIN_MASK) } /// Include bytes from a file for use in a subsequent [`crate::Bpf::load`]. /// /// This macro differs from the standard `include_bytes!` macro since it also ensures that /// the bytes are correctly aligned to be parsed as an ELF binary. This avoid some nasty /// compilation errors when the resulting byte array is not the correct alignment. /// /// # Examples /// ```ignore /// use aya::{Bpf, include_bytes_aligned}; /// /// let mut bpf = Bpf::load(include_bytes_aligned!( /// "/path/to/bpf.o" /// ))?; /// /// # Ok::<(), aya::BpfError>(()) /// ``` #[macro_export] macro_rules! include_bytes_aligned { ($path:expr) => {{ #[repr(align(32))] pub struct Aligned32; #[repr(C)] pub struct Aligned<Bytes: ?Sized> { pub _align: [Aligned32; 0], pub bytes: Bytes, } static ALIGNED: &Aligned<[u8]> = &Aligned { _align: [], bytes: *include_bytes!($path), }; &ALIGNED.bytes }}; } pub(crate) fn page_size() -> usize { // Safety: libc (unsafe { sysconf(_SC_PAGESIZE) }) as usize } // bytes_of converts a <T> to a byte slice pub(crate) unsafe fn bytes_of<T>(val: &T) -> &[u8] { let size = mem::size_of::<T>(); slice::from_raw_parts(slice::from_ref(val).as_ptr().cast(), size) } const MIN_LOG_BUF_SIZE: usize = 1024 * 10; const MAX_LOG_BUF_SIZE: usize = (std::u32::MAX >> 8) as usize; pub(crate) struct VerifierLog { buf: Vec<u8>, } impl VerifierLog { pub(crate) fn new() -> VerifierLog { VerifierLog { buf: Vec::new() } } pub(crate) fn buf(&mut self) -> &mut Vec<u8> { &mut self.buf } pub(crate) fn grow(&mut self) { let len = (self.buf.capacity() * 10).clamp(MIN_LOG_BUF_SIZE, MAX_LOG_BUF_SIZE); self.buf.resize(len, 0); self.reset(); } pub(crate) fn reset(&mut self) { if !self.buf.is_empty() { self.buf[0] = 0; } } pub(crate) fn truncate(&mut self) { if self.buf.is_empty() { return; } let pos = self .buf .iter() .position(|b| *b == 0) .unwrap_or(self.buf.len() - 1); self.buf[pos] = 0; self.buf.truncate(pos + 1); } pub(crate) fn as_c_str(&self) -> Option<&CStr> { if self.buf.is_empty() { None } else { Some(CStr::from_bytes_with_nul(&self.buf).unwrap()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_online_cpus() { assert_eq!(parse_cpu_ranges("0").unwrap(), vec![0]); assert_eq!(parse_cpu_ranges("0,1").unwrap(), vec![0, 1]); assert_eq!(parse_cpu_ranges("0,1,2").unwrap(), vec![0, 1, 2]); assert_eq!( parse_cpu_ranges("0-7").unwrap(), (0..=7).collect::<Vec<_>>() ); assert_eq!( parse_cpu_ranges("0-3,4-7").unwrap(), (0..=7).collect::<Vec<_>>() ); assert_eq!( parse_cpu_ranges("0-5,6,7").unwrap(), (0..=7).collect::<Vec<_>>() ); assert!(parse_cpu_ranges("").is_err()); assert!(parse_cpu_ranges("0-1,2-").is_err()); assert!(parse_cpu_ranges("foo").is_err()); } #[test] fn test_parse_kernel_symbols() { let data = "0000000000002000 A irq_stack_backing_store\n\ 0000000000006000 A cpu_tss_rw [foo bar]\n" .as_bytes(); let syms = parse_kernel_symbols(&mut BufReader::new(data)).unwrap(); assert_eq!(syms.keys().collect::<Vec<_>>(), vec![&0x2000, &0x6000]); assert_eq!( syms.get(&0x2000u64).unwrap().as_str(), "irq_stack_backing_store" ); assert_eq!(syms.get(&0x6000u64).unwrap().as_str(), "cpu_tss_rw"); } } <file_sep>/aya/src/maps/array/per_cpu_array.rs use std::{ convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_bounds, check_kv_size, IterableMap, MapData, MapError, PerCpuValues}, sys::{bpf_map_lookup_elem_per_cpu, bpf_map_update_elem_per_cpu}, Pod, }; /// A per-CPU fixed-size array. /// /// The size of the array is defined on the eBPF side using the `bpf_map_def::max_entries` field. /// All the entries are zero-initialized when the map is created. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.6. /// /// # Examples /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::{PerCpuArray, PerCpuValues}; /// use aya::util::nr_cpus; /// /// let mut array = PerCpuArray::try_from(bpf.map_mut("ARRAY").unwrap())?; /// /// // set array[1] = 42 for all cpus /// let nr_cpus = nr_cpus()?; /// array.set(1, PerCpuValues::try_from(vec![42u32; nr_cpus])?, 0)?; /// /// // retrieve the values at index 1 for all cpus /// let values = array.get(&1, 0)?; /// assert_eq!(values.len(), nr_cpus); /// for cpu_val in values.iter() { /// assert_eq!(*cpu_val, 42u32); /// } /// # Ok::<(), Error>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_PERCPU_ARRAY")] pub struct PerCpuArray<T, V: Pod> { inner: T, _v: PhantomData<V>, } impl<T: AsRef<MapData>, V: Pod> PerCpuArray<T, V> { pub(crate) fn new(map: T) -> Result<PerCpuArray<T, V>, MapError> { let data = map.as_ref(); check_kv_size::<u32, V>(data)?; let _fd = data.fd_or_err()?; Ok(PerCpuArray { inner: map, _v: PhantomData, }) } /// Returns the number of elements in the array. /// /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side. pub fn len(&self) -> u32 { self.inner.as_ref().obj.max_entries() } /// Returns a slice of values - one for each CPU - stored at the given index. /// /// # Errors /// /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`] /// if `bpf_map_lookup_elem` fails. pub fn get(&self, index: &u32, flags: u64) -> Result<PerCpuValues<V>, MapError> { let data = self.inner.as_ref(); check_bounds(data, *index)?; let fd = data.fd_or_err()?; let value = bpf_map_lookup_elem_per_cpu(fd, index, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; value.ok_or(MapError::KeyNotFound) } /// An iterator over the elements of the array. The iterator item type is /// `Result<PerCpuValues<V>, MapError>`. pub fn iter(&self) -> impl Iterator<Item = Result<PerCpuValues<V>, MapError>> + '_ { (0..self.len()).map(move |i| self.get(&i, 0)) } } impl<T: AsMut<MapData>, V: Pod> PerCpuArray<T, V> { /// Sets the values - one for each CPU - at the given index. /// /// # Errors /// /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`] /// if `bpf_map_update_elem` fails. pub fn set(&mut self, index: u32, values: PerCpuValues<V>, flags: u64) -> Result<(), MapError> { let data = self.inner.as_mut(); check_bounds(data, index)?; let fd = data.fd_or_err()?; bpf_map_update_elem_per_cpu(fd, &index, &values, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } } impl<T: AsRef<MapData>, V: Pod> IterableMap<u32, PerCpuValues<V>> for PerCpuArray<T, V> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, index: &u32) -> Result<PerCpuValues<V>, MapError> { self.get(index, 0) } } <file_sep>/aya/src/programs/sk_lookup.rs use std::os::unix::prelude::{AsRawFd, RawFd}; use crate::{ generated::{bpf_attach_type::BPF_SK_LOOKUP, bpf_prog_type::BPF_PROG_TYPE_SK_LOOKUP}, programs::{define_link_wrapper, load_program, FdLinkId, ProgramData, ProgramError}, sys::bpf_link_create, }; use super::links::FdLink; /// A program used to redirect incoming packets to a local socket. /// /// [`SkLookup`] programs are attached to network namespaces to provide programmable /// socket lookup for TCP/UDP when a packet is to be delievered locally. /// /// You may attach multiple programs to the same namespace and they are executed /// in the order they were attached. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.9. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::SkLookup; /// /// let file = File::open("/var/run/netns/test")?; /// let program: &mut SkLookup = bpf.program_mut("sk_lookup").unwrap().try_into()?; /// program.load()?; /// program.attach(file)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SK_LOOKUP")] pub struct SkLookup { pub(crate) data: ProgramData<SkLookupLink>, } impl SkLookup { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(BPF_SK_LOOKUP); load_program(BPF_PROG_TYPE_SK_LOOKUP, &mut self.data) } /// Attaches the program to the given network namespace. /// /// The returned value can be used to detach, see [SkLookup::detach]. pub fn attach<T: AsRawFd>(&mut self, netns: T) -> Result<SkLookupLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let netns_fd = netns.as_raw_fd(); let link_fd = bpf_link_create(prog_fd, netns_fd, BPF_SK_LOOKUP, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(SkLookupLink::new(FdLink::new(link_fd))) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: SkLookupLinkId) -> Result<SkLookupLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [SkLookup::attach]. pub fn detach(&mut self, link_id: SkLookupLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } define_link_wrapper!( /// The link used by [SkLookup] programs. SkLookupLink, /// The type returned by [SkLookup::attach]. Can be passed to [SkLookup::detach]. SkLookupLinkId, FdLink, FdLinkId ); <file_sep>/aya/src/obj/mod.rs pub(crate) mod btf; mod relocation; use log::debug; use object::{ read::{Object as ElfObject, ObjectSection, Section as ObjSection}, Endianness, ObjectSymbol, ObjectSymbolTable, RelocationTarget, SectionIndex, SectionKind, SymbolKind, }; use std::{ collections::HashMap, ffi::{CStr, CString}, mem, ptr, str::FromStr, }; use thiserror::Error; use relocation::*; use crate::{ bpf_map_def, generated::{bpf_insn, bpf_map_info, bpf_map_type::BPF_MAP_TYPE_ARRAY, BPF_F_RDONLY_PROG}, obj::btf::{Btf, BtfError, BtfExt, BtfType}, programs::{CgroupSockAddrAttachType, CgroupSockAttachType, CgroupSockoptAttachType}, BpfError, BtfMapDef, PinningType, }; use std::slice::from_raw_parts_mut; use self::btf::{Array, DataSecEntry, FuncSecInfo, LineSecInfo}; const KERNEL_VERSION_ANY: u32 = 0xFFFF_FFFE; /// The first five __u32 of `bpf_map_def` must be defined. const MINIMUM_MAP_SIZE: usize = mem::size_of::<u32>() * 5; #[derive(Clone)] pub struct Object { pub(crate) endianness: Endianness, pub license: CString, pub kernel_version: KernelVersion, pub btf: Option<Btf>, pub btf_ext: Option<BtfExt>, pub(crate) maps: HashMap<String, Map>, pub(crate) programs: HashMap<String, Program>, pub(crate) functions: HashMap<u64, Function>, pub(crate) relocations: HashMap<SectionIndex, HashMap<u64, Relocation>>, pub(crate) symbols_by_index: HashMap<usize, Symbol>, pub(crate) section_sizes: HashMap<String, u64>, // symbol_offset_by_name caches symbols that could be referenced from a // BTF VAR type so the offsets can be fixed up pub(crate) symbol_offset_by_name: HashMap<String, u64>, pub(crate) text_section_index: Option<usize>, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum MapKind { Bss, Data, Rodata, Other, } impl From<&str> for MapKind { fn from(s: &str) -> Self { if s == ".bss" { MapKind::Bss } else if s.starts_with(".data") { MapKind::Data } else if s.starts_with(".rodata") { MapKind::Rodata } else { MapKind::Other } } } #[derive(Debug, Clone)] pub enum Map { Legacy(LegacyMap), Btf(BtfMap), } impl Map { pub(crate) fn map_type(&self) -> u32 { match self { Map::Legacy(m) => m.def.map_type, Map::Btf(m) => m.def.map_type, } } pub(crate) fn key_size(&self) -> u32 { match self { Map::Legacy(m) => m.def.key_size, Map::Btf(m) => m.def.key_size, } } pub(crate) fn value_size(&self) -> u32 { match self { Map::Legacy(m) => m.def.value_size, Map::Btf(m) => m.def.value_size, } } pub(crate) fn max_entries(&self) -> u32 { match self { Map::Legacy(m) => m.def.max_entries, Map::Btf(m) => m.def.max_entries, } } pub(crate) fn set_max_entries(&mut self, v: u32) { match self { Map::Legacy(m) => m.def.max_entries = v, Map::Btf(m) => m.def.max_entries = v, } } pub(crate) fn map_flags(&self) -> u32 { match self { Map::Legacy(m) => m.def.map_flags, Map::Btf(m) => m.def.map_flags, } } pub(crate) fn pinning(&self) -> PinningType { match self { Map::Legacy(m) => m.def.pinning, Map::Btf(m) => m.def.pinning, } } pub(crate) fn data(&self) -> &[u8] { match self { Map::Legacy(m) => &m.data, Map::Btf(m) => &m.data, } } pub(crate) fn data_mut(&mut self) -> &mut Vec<u8> { match self { Map::Legacy(m) => m.data.as_mut(), Map::Btf(m) => m.data.as_mut(), } } pub(crate) fn kind(&self) -> MapKind { match self { Map::Legacy(m) => m.kind, Map::Btf(m) => m.kind, } } pub(crate) fn section_index(&self) -> usize { match self { Map::Legacy(m) => m.section_index, Map::Btf(m) => m.section_index, } } pub(crate) fn symbol_index(&self) -> usize { match self { Map::Legacy(m) => m.symbol_index, Map::Btf(m) => m.symbol_index, } } } #[derive(Debug, Clone)] pub struct LegacyMap { pub(crate) def: bpf_map_def, pub(crate) section_index: usize, pub(crate) symbol_index: usize, pub(crate) data: Vec<u8>, pub(crate) kind: MapKind, } #[derive(Debug, Clone)] pub struct BtfMap { pub(crate) def: BtfMapDef, pub(crate) section_index: usize, pub(crate) symbol_index: usize, pub(crate) kind: MapKind, pub(crate) data: Vec<u8>, } #[derive(Debug, Clone)] pub(crate) struct Program { pub(crate) license: CString, pub(crate) kernel_version: KernelVersion, pub(crate) section: ProgramSection, pub(crate) function: Function, } #[derive(Debug, Clone)] pub(crate) struct Function { pub(crate) address: u64, pub(crate) name: String, pub(crate) section_index: SectionIndex, pub(crate) section_offset: usize, pub(crate) instructions: Vec<bpf_insn>, pub(crate) func_info: FuncSecInfo, pub(crate) line_info: LineSecInfo, pub(crate) func_info_rec_size: usize, pub(crate) line_info_rec_size: usize, } #[derive(Debug, Clone)] pub enum ProgramSection { KRetProbe { name: String, }, KProbe { name: String, }, UProbe { name: String, }, URetProbe { name: String, }, TracePoint { name: String, }, SocketFilter { name: String, }, Xdp { name: String, }, SkMsg { name: String, }, SkSkbStreamParser { name: String, }, SkSkbStreamVerdict { name: String, }, SockOps { name: String, }, SchedClassifier { name: String, }, CgroupSkb { name: String, }, CgroupSkbIngress { name: String, }, CgroupSkbEgress { name: String, }, CgroupSockAddr { name: String, attach_type: CgroupSockAddrAttachType, }, CgroupSysctl { name: String, }, CgroupSockopt { name: String, attach_type: CgroupSockoptAttachType, }, LircMode2 { name: String, }, PerfEvent { name: String, }, RawTracePoint { name: String, }, Lsm { name: String, }, BtfTracePoint { name: String, }, FEntry { name: String, }, FExit { name: String, }, Extension { name: String, }, SkLookup { name: String, }, CgroupSock { name: String, attach_type: CgroupSockAttachType, }, CgroupDevice { name: String, }, } impl ProgramSection { fn name(&self) -> &str { match self { ProgramSection::KRetProbe { name } => name, ProgramSection::KProbe { name } => name, ProgramSection::UProbe { name } => name, ProgramSection::URetProbe { name } => name, ProgramSection::TracePoint { name } => name, ProgramSection::SocketFilter { name } => name, ProgramSection::Xdp { name } => name, ProgramSection::SkMsg { name } => name, ProgramSection::SkSkbStreamParser { name } => name, ProgramSection::SkSkbStreamVerdict { name } => name, ProgramSection::SockOps { name } => name, ProgramSection::SchedClassifier { name } => name, ProgramSection::CgroupSkb { name, .. } => name, ProgramSection::CgroupSkbIngress { name, .. } => name, ProgramSection::CgroupSkbEgress { name, .. } => name, ProgramSection::CgroupSockAddr { name, .. } => name, ProgramSection::CgroupSysctl { name } => name, ProgramSection::CgroupSockopt { name, .. } => name, ProgramSection::LircMode2 { name } => name, ProgramSection::PerfEvent { name } => name, ProgramSection::RawTracePoint { name } => name, ProgramSection::Lsm { name } => name, ProgramSection::BtfTracePoint { name } => name, ProgramSection::FEntry { name } => name, ProgramSection::FExit { name } => name, ProgramSection::Extension { name } => name, ProgramSection::SkLookup { name } => name, ProgramSection::CgroupSock { name, .. } => name, ProgramSection::CgroupDevice { name } => name, } } } impl FromStr for ProgramSection { type Err = ParseError; fn from_str(section: &str) -> Result<ProgramSection, ParseError> { use ProgramSection::*; // parse the common case, eg "xdp/program_name" or // "sk_skb/stream_verdict/program_name" let mut parts = section.rsplitn(2, '/').collect::<Vec<_>>(); if parts.len() == 1 { parts.push(parts[0]); } let kind = parts[1]; let name = parts[0].to_owned(); Ok(match kind { "kprobe" => KProbe { name }, "kretprobe" => KRetProbe { name }, "uprobe" => UProbe { name }, "uretprobe" => URetProbe { name }, "xdp" => Xdp { name }, "tp_btf" => BtfTracePoint { name }, _ if kind.starts_with("tracepoint") || kind.starts_with("tp") => { // tracepoint sections are named `tracepoint/category/event_name`, // and we want to parse the name as "category/event_name" let name = section.splitn(2, '/').last().unwrap().to_owned(); TracePoint { name } } "socket" => SocketFilter { name }, "sk_msg" => SkMsg { name }, "sk_skb" => match &*name { "stream_parser" => SkSkbStreamParser { name }, "stream_verdict" => SkSkbStreamVerdict { name }, _ => { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }) } }, "sk_skb/stream_parser" => SkSkbStreamParser { name }, "sk_skb/stream_verdict" => SkSkbStreamVerdict { name }, "sockops" => SockOps { name }, "classifier" => SchedClassifier { name }, "cgroup_skb" => match &*name { "ingress" => CgroupSkbIngress { name }, "egress" => CgroupSkbEgress { name }, _ => { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }) } }, "cgroup_skb/ingress" => CgroupSkbIngress { name }, "cgroup_skb/egress" => CgroupSkbEgress { name }, "cgroup/skb" => CgroupSkb { name }, "cgroup/sock" => CgroupSock { name, attach_type: CgroupSockAttachType::default(), }, "cgroup/sysctl" => CgroupSysctl { name }, "cgroup/dev" => CgroupDevice { name }, "cgroup/getsockopt" => CgroupSockopt { name, attach_type: CgroupSockoptAttachType::Get, }, "cgroup/setsockopt" => CgroupSockopt { name, attach_type: CgroupSockoptAttachType::Set, }, "cgroup" => match &*name { "skb" => CgroupSkb { name }, "sysctl" => CgroupSysctl { name }, "dev" => CgroupDevice { name }, "getsockopt" | "setsockopt" => { if let Ok(attach_type) = CgroupSockoptAttachType::try_from(name.as_str()) { CgroupSockopt { name, attach_type } } else { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }); } } "sock" => CgroupSock { name, attach_type: CgroupSockAttachType::default(), }, "post_bind4" | "post_bind6" | "sock_create" | "sock_release" => { if let Ok(attach_type) = CgroupSockAttachType::try_from(name.as_str()) { CgroupSock { name, attach_type } } else { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }); } } _ => { if let Ok(attach_type) = CgroupSockAddrAttachType::try_from(name.as_str()) { CgroupSockAddr { name, attach_type } } else { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }); } } }, "cgroup/post_bind4" => CgroupSock { name, attach_type: CgroupSockAttachType::PostBind4, }, "cgroup/post_bind6" => CgroupSock { name, attach_type: CgroupSockAttachType::PostBind6, }, "cgroup/sock_create" => CgroupSock { name, attach_type: CgroupSockAttachType::SockCreate, }, "cgroup/sock_release" => CgroupSock { name, attach_type: CgroupSockAttachType::SockRelease, }, "cgroup/bind4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::Bind4, }, "cgroup/bind6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::Bind6, }, "cgroup/connect4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::Connect4, }, "cgroup/connect6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::Connect6, }, "cgroup/getpeername4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::GetPeerName4, }, "cgroup/getpeername6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::GetPeerName6, }, "cgroup/getsockname4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::GetSockName4, }, "cgroup/getsockname6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::GetSockName6, }, "cgroup/sendmsg4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::UDPSendMsg4, }, "cgroup/sendmsg6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::UDPSendMsg6, }, "cgroup/recvmsg4" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::UDPRecvMsg4, }, "cgroup/recvmsg6" => CgroupSockAddr { name, attach_type: CgroupSockAddrAttachType::UDPRecvMsg6, }, "lirc_mode2" => LircMode2 { name }, "perf_event" => PerfEvent { name }, "raw_tp" | "raw_tracepoint" => RawTracePoint { name }, "lsm" => Lsm { name }, "fentry" => FEntry { name }, "fexit" => FExit { name }, "freplace" => Extension { name }, "sk_lookup" => SkLookup { name }, _ => { return Err(ParseError::InvalidProgramSection { section: section.to_owned(), }) } }) } } impl Object { pub(crate) fn parse(data: &[u8]) -> Result<Object, BpfError> { let obj = object::read::File::parse(data).map_err(ParseError::ElfError)?; let endianness = obj.endianness(); let license = if let Some(section) = obj.section_by_name("license") { parse_license(Section::try_from(&section)?.data)? } else { CString::new("GPL").unwrap() }; let kernel_version = if let Some(section) = obj.section_by_name("version") { parse_version(Section::try_from(&section)?.data, endianness)? } else { KernelVersion::Any }; let mut bpf_obj = Object::new(endianness, license, kernel_version); if let Some(symbol_table) = obj.symbol_table() { for symbol in symbol_table.symbols() { let name = symbol .name() .ok() .map(String::from) .ok_or(BtfError::InvalidSymbolName)?; let sym = Symbol { index: symbol.index().0, name: Some(name.clone()), section_index: symbol.section().index().map(|i| i.0), address: symbol.address(), size: symbol.size(), is_definition: symbol.is_definition(), kind: symbol.kind(), }; bpf_obj.symbols_by_index.insert(symbol.index().0, sym); if symbol.is_global() || symbol.kind() == SymbolKind::Data { bpf_obj.symbol_offset_by_name.insert(name, symbol.address()); } } } // .BTF and .BTF.ext sections must be parsed first // as they're required to prepare function and line information // when parsing program sections if let Some(s) = obj.section_by_name(".BTF") { bpf_obj.parse_section(Section::try_from(&s)?)?; if let Some(s) = obj.section_by_name(".BTF.ext") { bpf_obj.parse_section(Section::try_from(&s)?)?; } } for s in obj.sections() { if let Ok(name) = s.name() { if name == ".BTF" || name == ".BTF.ext" { continue; } } bpf_obj.parse_section(Section::try_from(&s)?)?; } Ok(bpf_obj) } fn new(endianness: Endianness, license: CString, kernel_version: KernelVersion) -> Object { Object { endianness, license, kernel_version, btf: None, btf_ext: None, maps: HashMap::new(), programs: HashMap::new(), functions: HashMap::new(), relocations: HashMap::new(), symbols_by_index: HashMap::new(), section_sizes: HashMap::new(), symbol_offset_by_name: HashMap::new(), text_section_index: None, } } pub fn patch_map_data(&mut self, globals: HashMap<&str, &[u8]>) -> Result<(), ParseError> { let symbols: HashMap<String, &Symbol> = self .symbols_by_index .iter() .filter(|(_, s)| s.name.is_some()) .map(|(_, s)| (s.name.as_ref().unwrap().clone(), s)) .collect(); for (name, data) in globals { if let Some(symbol) = symbols.get(name) { if data.len() as u64 != symbol.size { return Err(ParseError::InvalidGlobalData { name: name.to_string(), sym_size: symbol.size, data_size: data.len(), }); } let (_, map) = self .maps .iter_mut() // assumption: there is only one map created per section where we're trying to // patch data. this assumption holds true for the .rodata section at least .find(|(_, m)| symbol.section_index == Some(m.section_index())) .ok_or_else(|| ParseError::MapNotFound { index: symbol.section_index.unwrap_or(0), })?; let start = symbol.address as usize; let end = start + symbol.size as usize; if start > end || end > map.data().len() { return Err(ParseError::InvalidGlobalData { name: name.to_string(), sym_size: symbol.size, data_size: data.len(), }); } map.data_mut().splice(start..end, data.iter().cloned()); } else { return Err(ParseError::SymbolNotFound { name: name.to_owned(), }); } } Ok(()) } fn parse_btf(&mut self, section: &Section) -> Result<(), BtfError> { self.btf = Some(Btf::parse(section.data, self.endianness)?); Ok(()) } fn parse_btf_ext(&mut self, section: &Section) -> Result<(), BtfError> { self.btf_ext = Some(BtfExt::parse( section.data, self.endianness, self.btf.as_ref().unwrap(), )?); Ok(()) } fn parse_program(&self, section: &Section) -> Result<Program, ParseError> { let prog_sec = ProgramSection::from_str(section.name)?; let name = prog_sec.name().to_owned(); let (func_info, line_info, func_info_rec_size, line_info_rec_size) = if let Some(btf_ext) = &self.btf_ext { let func_info = btf_ext.func_info.get(section.name); let line_info = btf_ext.line_info.get(section.name); ( func_info, line_info, btf_ext.func_info_rec_size(), btf_ext.line_info_rec_size(), ) } else { (FuncSecInfo::default(), LineSecInfo::default(), 0, 0) }; Ok(Program { license: self.license.clone(), kernel_version: self.kernel_version, section: prog_sec, function: Function { name, address: section.address, section_index: section.index, section_offset: 0, instructions: copy_instructions(section.data)?, func_info, line_info, func_info_rec_size, line_info_rec_size, }, }) } fn parse_text_section(&mut self, mut section: Section) -> Result<(), ParseError> { self.text_section_index = Some(section.index.0); let mut symbols_by_address = HashMap::new(); for sym in self.symbols_by_index.values() { if sym.is_definition && sym.kind == SymbolKind::Text && sym.section_index == Some(section.index.0) { if symbols_by_address.contains_key(&sym.address) { return Err(ParseError::SymbolTableConflict { section_index: section.index.0, address: sym.address, }); } symbols_by_address.insert(sym.address, sym); } } let mut offset = 0; while offset < section.data.len() { let address = section.address + offset as u64; let sym = symbols_by_address .get(&address) .ok_or(ParseError::UnknownSymbol { section_index: section.index.0, address, })?; if sym.size == 0 { return Err(ParseError::InvalidSymbol { index: sym.index, name: sym.name.clone(), }); } let (func_info, line_info, func_info_rec_size, line_info_rec_size) = if let Some(btf_ext) = &self.btf_ext { let bytes_offset = offset as u32 / INS_SIZE as u32; let section_size_bytes = sym.size as u32 / INS_SIZE as u32; let mut func_info = btf_ext.func_info.get(section.name); func_info.func_info.retain(|f| f.insn_off == bytes_offset); let mut line_info = btf_ext.line_info.get(section.name); line_info.line_info.retain(|l| { l.insn_off >= bytes_offset && l.insn_off < (bytes_offset + section_size_bytes) }); ( func_info, line_info, btf_ext.func_info_rec_size(), btf_ext.line_info_rec_size(), ) } else { (FuncSecInfo::default(), LineSecInfo::default(), 0, 0) }; self.functions.insert( sym.address, Function { address, name: sym.name.clone().unwrap(), section_index: section.index, section_offset: offset, instructions: copy_instructions( &section.data[offset..offset + sym.size as usize], )?, func_info, line_info, func_info_rec_size, line_info_rec_size, }, ); offset += sym.size as usize; } if !section.relocations.is_empty() { self.relocations.insert( section.index, section .relocations .drain(..) .map(|rel| (rel.offset, rel)) .collect(), ); } Ok(()) } fn parse_map_section( &mut self, section: &Section, symbols: Vec<Symbol>, ) -> Result<(), ParseError> { if symbols.is_empty() { return Err(ParseError::NoSymbolsInMapSection {}); } for (i, sym) in symbols.iter().enumerate() { let start = sym.address as usize; let end = start + sym.size as usize; let data = &section.data[start..end]; let name = sym .name .as_ref() .ok_or(ParseError::MapSymbolNameNotFound { i })?; let def = parse_map_def(name, data)?; self.maps.insert( name.to_string(), Map::Legacy(LegacyMap { section_index: section.index.0, symbol_index: sym.index, def, data: Vec::new(), kind: MapKind::Other, }), ); } Ok(()) } fn parse_btf_maps( &mut self, section: &Section, symbols: HashMap<String, Symbol>, ) -> Result<(), BpfError> { if self.btf.is_none() { return Err(BpfError::NoBTF); } let btf = self.btf.as_ref().unwrap(); for t in btf.types() { if let BtfType::DataSec(datasec) = &t { let type_name = match btf.type_name(t) { Ok(name) => name, _ => continue, }; if type_name == section.name { // each btf_var_secinfo contains a map for info in &datasec.entries { let (map_name, def) = parse_btf_map_def(btf, info)?; let symbol_index = symbols .get(&map_name) .ok_or_else(|| { BpfError::ParseError(ParseError::SymbolNotFound { name: map_name.to_string(), }) })? .index; self.maps.insert( map_name, Map::Btf(BtfMap { def, section_index: section.index.0, symbol_index, kind: MapKind::Other, data: Vec::new(), }), ); } } } } Ok(()) } fn parse_section(&mut self, mut section: Section) -> Result<(), BpfError> { let mut parts = section.name.rsplitn(2, '/').collect::<Vec<_>>(); parts.reverse(); if parts.len() == 1 && (parts[0] == "xdp" || parts[0] == "sk_msg" || parts[0] == "sockops" || parts[0] == "classifier") { parts.push(parts[0]); } self.section_sizes .insert(section.name.to_owned(), section.size); match section.kind { BpfSectionKind::Data => { self.maps .insert(section.name.to_string(), parse_map(&section, section.name)?); } BpfSectionKind::Text => self.parse_text_section(section)?, BpfSectionKind::Btf => self.parse_btf(&section)?, BpfSectionKind::BtfExt => self.parse_btf_ext(&section)?, BpfSectionKind::BtfMaps => { let symbols: HashMap<String, Symbol> = self .symbols_by_index .values() .filter(|s| { if let Some(idx) = s.section_index { idx == section.index.0 && s.name.is_some() } else { false } }) .cloned() .map(|s| (s.name.as_ref().unwrap().to_string(), s)) .collect(); self.parse_btf_maps(&section, symbols)? } BpfSectionKind::Maps => { let symbols: Vec<Symbol> = self .symbols_by_index .values() .filter(|s| { if let Some(idx) = s.section_index { idx == section.index.0 } else { false } }) .cloned() .collect(); self.parse_map_section(&section, symbols)? } BpfSectionKind::Program => { let program = self.parse_program(&section)?; self.programs .insert(program.section.name().to_owned(), program); if !section.relocations.is_empty() { self.relocations.insert( section.index, section .relocations .drain(..) .map(|rel| (rel.offset, rel)) .collect(), ); } } BpfSectionKind::Undefined | BpfSectionKind::License | BpfSectionKind::Version => {} } Ok(()) } } #[derive(Debug, Clone, Error)] pub enum ParseError { #[error("error parsing ELF data")] ElfError(#[from] object::read::Error), #[error("invalid license `{data:?}`: missing NULL terminator")] MissingLicenseNullTerminator { data: Vec<u8> }, #[error("invalid license `{data:?}`")] InvalidLicense { data: Vec<u8> }, #[error("invalid kernel version `{data:?}`")] InvalidKernelVersion { data: Vec<u8> }, #[error("error parsing section with index {index}")] SectionError { index: usize, #[source] source: object::read::Error, }, #[error("unsupported relocation target")] UnsupportedRelocationTarget, #[error("invalid program section `{section}`")] InvalidProgramSection { section: String }, #[error("invalid program code")] InvalidProgramCode, #[error("error parsing map `{name}`")] InvalidMapDefinition { name: String }, #[error("two or more symbols in section `{section_index}` have the same address {address:#X}")] SymbolTableConflict { section_index: usize, address: u64 }, #[error("unknown symbol in section `{section_index}` at address {address:#X}")] UnknownSymbol { section_index: usize, address: u64 }, #[error("invalid symbol, index `{index}` name: {}", .name.as_ref().unwrap_or(&"[unknown]".into()))] InvalidSymbol { index: usize, name: Option<String> }, #[error("symbol {name} has size `{sym_size}`, but provided data is of size `{data_size}`")] InvalidGlobalData { name: String, sym_size: u64, data_size: usize, }, #[error("symbol with name {name} not found in the symbols table")] SymbolNotFound { name: String }, #[error("map for section with index {index} not found")] MapNotFound { index: usize }, #[error("the map number {i} in the `maps` section doesn't have a symbol name")] MapSymbolNameNotFound { i: usize }, #[error("no symbols found for the maps included in the maps section")] NoSymbolsInMapSection {}, } #[derive(Debug)] enum BpfSectionKind { Undefined, Maps, BtfMaps, Program, Data, Text, Btf, BtfExt, License, Version, } impl BpfSectionKind { fn from_name(name: &str) -> BpfSectionKind { if name.starts_with("license") { BpfSectionKind::License } else if name.starts_with("version") { BpfSectionKind::Version } else if name.starts_with("maps") { BpfSectionKind::Maps } else if name.starts_with(".maps") { BpfSectionKind::BtfMaps } else if name.starts_with(".text") { BpfSectionKind::Text } else if name.starts_with(".bss") || name.starts_with(".data") || name.starts_with(".rodata") { BpfSectionKind::Data } else if name == ".BTF" { BpfSectionKind::Btf } else if name == ".BTF.ext" { BpfSectionKind::BtfExt } else { BpfSectionKind::Undefined } } } #[derive(Debug)] struct Section<'a> { index: SectionIndex, kind: BpfSectionKind, address: u64, name: &'a str, data: &'a [u8], size: u64, relocations: Vec<Relocation>, } impl<'data, 'file, 'a> TryFrom<&'a ObjSection<'data, 'file>> for Section<'a> { type Error = ParseError; fn try_from(section: &'a ObjSection) -> Result<Section<'a>, ParseError> { let index = section.index(); let map_err = |source| ParseError::SectionError { index: index.0, source, }; let name = section.name().map_err(map_err)?; let kind = match BpfSectionKind::from_name(name) { BpfSectionKind::Undefined => { if section.kind() == SectionKind::Text && section.size() > 0 { BpfSectionKind::Program } else { BpfSectionKind::Undefined } } k => k, }; Ok(Section { index, kind, address: section.address(), name, data: section.data().map_err(map_err)?, size: section.size(), relocations: section .relocations() .map(|(offset, r)| { Ok(Relocation { symbol_index: match r.target() { RelocationTarget::Symbol(index) => index.0, _ => return Err(ParseError::UnsupportedRelocationTarget), }, offset, }) }) .collect::<Result<Vec<_>, _>>()?, }) } } fn parse_license(data: &[u8]) -> Result<CString, ParseError> { if data.len() < 2 { return Err(ParseError::InvalidLicense { data: data.to_vec(), }); } if data[data.len() - 1] != 0 { return Err(ParseError::MissingLicenseNullTerminator { data: data.to_vec(), }); } Ok(CStr::from_bytes_with_nul(data) .map_err(|_| ParseError::InvalidLicense { data: data.to_vec(), })? .to_owned()) } fn parse_version(data: &[u8], endianness: object::Endianness) -> Result<KernelVersion, ParseError> { let data = match data.len() { 4 => data.try_into().unwrap(), _ => { return Err(ParseError::InvalidKernelVersion { data: data.to_vec(), }) } }; let v = match endianness { object::Endianness::Big => u32::from_be_bytes(data), object::Endianness::Little => u32::from_le_bytes(data), }; Ok(match v { KERNEL_VERSION_ANY => KernelVersion::Any, v => KernelVersion::Version(v), }) } // Gets an integer value from a BTF map defintion K/V pair. // type_id should be a PTR to an ARRAY. // the value is encoded in the array nr_elems field. fn get_map_field(btf: &Btf, type_id: u32) -> Result<u32, BtfError> { let pty = match &btf.type_by_id(type_id)? { BtfType::Ptr(pty) => pty, other => { return Err(BtfError::UnexpectedBtfType { type_id: other.btf_type().unwrap_or(0), }) } }; // Safety: union let arr = match &btf.type_by_id(pty.btf_type)? { BtfType::Array(Array { array, .. }) => array, other => { return Err(BtfError::UnexpectedBtfType { type_id: other.btf_type().unwrap_or(0), }) } }; Ok(arr.len) } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum KernelVersion { Version(u32), Any, } impl From<KernelVersion> for u32 { fn from(version: KernelVersion) -> u32 { match version { KernelVersion::Any => KERNEL_VERSION_ANY, KernelVersion::Version(v) => v, } } } fn parse_map(section: &Section, name: &str) -> Result<Map, ParseError> { let kind = MapKind::from(name); let (def, data) = match kind { MapKind::Bss | MapKind::Data | MapKind::Rodata => { let def = bpf_map_def { map_type: BPF_MAP_TYPE_ARRAY as u32, key_size: mem::size_of::<u32>() as u32, // We need to use section.size here since // .bss will always have data.len() == 0 value_size: section.size as u32, max_entries: 1, map_flags: if kind == MapKind::Rodata { BPF_F_RDONLY_PROG } else { 0 }, ..Default::default() }; (def, section.data.to_vec()) } MapKind::Other => (parse_map_def(name, section.data)?, Vec::new()), }; Ok(Map::Legacy(LegacyMap { section_index: section.index.0, symbol_index: 0, def, data, kind, })) } fn parse_map_def(name: &str, data: &[u8]) -> Result<bpf_map_def, ParseError> { if data.len() < MINIMUM_MAP_SIZE { return Err(ParseError::InvalidMapDefinition { name: name.to_owned(), }); } if data.len() < mem::size_of::<bpf_map_def>() { let mut map_def = bpf_map_def::default(); unsafe { let map_def_ptr = from_raw_parts_mut(&mut map_def as *mut bpf_map_def as *mut u8, data.len()); map_def_ptr.copy_from_slice(data); } Ok(map_def) } else { Ok(unsafe { ptr::read_unaligned(data.as_ptr() as *const bpf_map_def) }) } } fn parse_btf_map_def(btf: &Btf, info: &DataSecEntry) -> Result<(String, BtfMapDef), BtfError> { let ty = match btf.type_by_id(info.btf_type)? { BtfType::Var(var) => var, other => { return Err(BtfError::UnexpectedBtfType { type_id: other.btf_type().unwrap_or(0), }) } }; let map_name = btf.string_at(ty.name_offset)?; let mut map_def = BtfMapDef::default(); // Safety: union let root_type = btf.resolve_type(ty.btf_type)?; let s = match btf.type_by_id(root_type)? { BtfType::Struct(s) => s, other => { return Err(BtfError::UnexpectedBtfType { type_id: other.btf_type().unwrap_or(0), }) } }; for m in &s.members { match btf.string_at(m.name_offset)?.as_ref() { "type" => { map_def.map_type = get_map_field(btf, m.btf_type)?; } "key" => { if let BtfType::Ptr(pty) = btf.type_by_id(m.btf_type)? { // Safety: union let t = pty.btf_type; map_def.key_size = btf.type_size(t)? as u32; map_def.btf_key_type_id = t; } else { return Err(BtfError::UnexpectedBtfType { type_id: m.btf_type, }); } } "key_size" => { map_def.key_size = get_map_field(btf, m.btf_type)?; } "value" => { if let BtfType::Ptr(pty) = btf.type_by_id(m.btf_type)? { let t = pty.btf_type; map_def.value_size = btf.type_size(t)? as u32; map_def.btf_value_type_id = t; } else { return Err(BtfError::UnexpectedBtfType { type_id: m.btf_type, }); } } "value_size" => { map_def.value_size = get_map_field(btf, m.btf_type)?; } "max_entries" => { map_def.max_entries = get_map_field(btf, m.btf_type)?; } "map_flags" => { map_def.map_flags = get_map_field(btf, m.btf_type)?; } "pinning" => { let pinning = get_map_field(btf, m.btf_type)?; map_def.pinning = PinningType::try_from(pinning).unwrap_or_else(|_| { debug!("{} is not a valid pin type. using PIN_NONE", pinning); PinningType::None }); } other => { debug!("skipping unknown map section: {}", other); continue; } } } Ok((map_name.to_string(), map_def)) } pub(crate) fn parse_map_info(info: bpf_map_info, pinned: PinningType) -> Map { if info.btf_key_type_id != 0 { Map::Btf(BtfMap { def: BtfMapDef { map_type: info.type_, key_size: info.key_size, value_size: info.value_size, max_entries: info.max_entries, map_flags: info.map_flags, pinning: pinned, btf_key_type_id: info.btf_key_type_id, btf_value_type_id: info.btf_value_type_id, }, section_index: 0, symbol_index: 0, data: Vec::new(), // We should never be loading the .bss or .data or .rodata FDs kind: MapKind::Other, }) } else { Map::Legacy(LegacyMap { def: bpf_map_def { map_type: info.type_, key_size: info.key_size, value_size: info.value_size, max_entries: info.max_entries, map_flags: info.map_flags, pinning: pinned, id: info.id, }, section_index: 0, symbol_index: 0, data: Vec::new(), // We should never be loading the .bss or .data or .rodata FDs kind: MapKind::Other, }) } } pub(crate) fn copy_instructions(data: &[u8]) -> Result<Vec<bpf_insn>, ParseError> { if data.len() % mem::size_of::<bpf_insn>() > 0 { return Err(ParseError::InvalidProgramCode); } let instructions = data .chunks_exact(mem::size_of::<bpf_insn>()) .map(|d| unsafe { ptr::read_unaligned(d.as_ptr() as *const bpf_insn) }) .collect::<Vec<_>>(); Ok(instructions) } #[cfg(test)] mod tests { use matches::assert_matches; use object::Endianness; use super::*; use crate::PinningType; fn fake_section<'a>(kind: BpfSectionKind, name: &'a str, data: &'a [u8]) -> Section<'a> { Section { index: SectionIndex(0), kind, address: 0, name, data, size: data.len() as u64, relocations: Vec::new(), } } fn fake_ins() -> bpf_insn { bpf_insn { code: 0, _bitfield_align_1: [], _bitfield_1: bpf_insn::new_bitfield_1(0, 0), off: 0, imm: 0, } } fn fake_sym(obj: &mut Object, section_index: usize, address: u64, name: &str, size: u64) { let idx = obj.symbols_by_index.len(); obj.symbols_by_index.insert( idx + 1, Symbol { index: idx + 1, section_index: Some(section_index), name: Some(name.to_string()), address, size, is_definition: false, kind: SymbolKind::Data, }, ); } fn bytes_of<T>(val: &T) -> &[u8] { // Safety: This is for testing only unsafe { crate::util::bytes_of(val) } } #[test] fn test_parse_generic_error() { assert!(matches!( Object::parse(&b"foo"[..]), Err(BpfError::ParseError(ParseError::ElfError(_))) )) } #[test] fn test_parse_license() { assert!(matches!( parse_license(b""), Err(ParseError::InvalidLicense { .. }) )); assert!(matches!( parse_license(b"\0"), Err(ParseError::InvalidLicense { .. }) )); assert!(matches!( parse_license(b"GPL"), Err(ParseError::MissingLicenseNullTerminator { .. }) )); assert_eq!(parse_license(b"GPL\0").unwrap().to_str().unwrap(), "GPL"); } #[test] fn test_parse_version() { assert!(matches!( parse_version(b"", Endianness::Little), Err(ParseError::InvalidKernelVersion { .. }) )); assert!(matches!( parse_version(b"123", Endianness::Little), Err(ParseError::InvalidKernelVersion { .. }) )); assert_eq!( parse_version(&0xFFFF_FFFEu32.to_le_bytes(), Endianness::Little) .expect("failed to parse magic version"), KernelVersion::Any ); assert_eq!( parse_version(&0xFFFF_FFFEu32.to_be_bytes(), Endianness::Big) .expect("failed to parse magic version"), KernelVersion::Any ); assert_eq!( parse_version(&1234u32.to_le_bytes(), Endianness::Little) .expect("failed to parse magic version"), KernelVersion::Version(1234) ); } #[test] fn test_parse_map_def_error() { assert!(matches!( parse_map_def("foo", &[]), Err(ParseError::InvalidMapDefinition { .. }) )); } #[test] fn test_parse_map_short() { let def = bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, id: 0, pinning: PinningType::None, ..Default::default() }; assert_eq!( parse_map_def("foo", &bytes_of(&def)[..MINIMUM_MAP_SIZE]).unwrap(), def ); } #[test] fn test_parse_map_def() { let def = bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, id: 6, pinning: PinningType::ByName, ..Default::default() }; assert_eq!(parse_map_def("foo", bytes_of(&def)).unwrap(), def); } #[test] fn test_parse_map_def_with_padding() { let def = bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, id: 6, pinning: PinningType::ByName, ..Default::default() }; let mut buf = [0u8; 128]; unsafe { ptr::write_unaligned(buf.as_mut_ptr() as *mut _, def) }; assert_eq!(parse_map_def("foo", &buf).unwrap(), def); } #[test] fn test_parse_map_error() { assert!(matches!( parse_map(&fake_section(BpfSectionKind::Maps, "maps/foo", &[]), "foo",), Err(ParseError::InvalidMapDefinition { .. }) )); } #[test] fn test_parse_map() { assert!(matches!( parse_map( &fake_section( BpfSectionKind::Maps, "maps/foo", bytes_of(&bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, id: 0, pinning: PinningType::None, ..Default::default() }) ), "foo" ), Ok(Map::Legacy(LegacyMap{ section_index: 0, def: bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, id: 0, pinning: PinningType::None, }, data, .. })) if data.is_empty() )) } #[test] fn test_parse_map_data() { let map_data = b"map data"; assert!(matches!( parse_map( &fake_section( BpfSectionKind::Data, ".bss", map_data, ), ".bss" ), Ok(Map::Legacy(LegacyMap { section_index: 0, symbol_index: 0, def: bpf_map_def { map_type: _map_type, key_size: 4, value_size, max_entries: 1, map_flags: 0, id: 0, pinning: PinningType::None, }, data, kind })) if data == map_data && value_size == map_data.len() as u32 && kind == MapKind::Bss )) } fn fake_obj() -> Object { Object::new( Endianness::Little, CString::new("GPL").unwrap(), KernelVersion::Any, ) } #[test] fn test_parse_program_error() { let obj = fake_obj(); assert_matches!( obj.parse_program(&fake_section( BpfSectionKind::Program, "kprobe/foo", &42u32.to_ne_bytes(), )), Err(ParseError::InvalidProgramCode) ); } #[test] fn test_parse_program() { let obj = fake_obj(); assert_matches!( obj.parse_program(&fake_section(BpfSectionKind::Program,"kprobe/foo", bytes_of(&fake_ins()))), Ok(Program { license, kernel_version: KernelVersion::Any, section: ProgramSection::KProbe { .. }, function: Function { name, address: 0, section_index: SectionIndex(0), section_offset: 0, instructions, ..} }) if license.to_string_lossy() == "GPL" && name == "foo" && instructions.len() == 1 ); } #[test] fn test_parse_section_map() { let mut obj = fake_obj(); fake_sym(&mut obj, 0, 0, "foo", mem::size_of::<bpf_map_def>() as u64); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Maps, "maps/foo", bytes_of(&bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, ..Default::default() }) )), Ok(()) ); assert!(obj.maps.get("foo").is_some()); } #[test] fn test_parse_section_multiple_maps() { let mut obj = fake_obj(); fake_sym(&mut obj, 0, 0, "foo", mem::size_of::<bpf_map_def>() as u64); fake_sym(&mut obj, 0, 28, "bar", mem::size_of::<bpf_map_def>() as u64); fake_sym(&mut obj, 0, 60, "baz", mem::size_of::<bpf_map_def>() as u64); let def = &bpf_map_def { map_type: 1, key_size: 2, value_size: 3, max_entries: 4, map_flags: 5, ..Default::default() }; let map_data = bytes_of(def).to_vec(); let mut buf = vec![]; buf.extend(&map_data); buf.extend(&map_data); // throw in some padding buf.extend(&[0, 0, 0, 0]); buf.extend(&map_data); assert_matches!( obj.parse_section(fake_section(BpfSectionKind::Maps, "maps", buf.as_slice(),)), Ok(()) ); assert!(obj.maps.get("foo").is_some()); assert!(obj.maps.get("bar").is_some()); assert!(obj.maps.get("baz").is_some()); for map in obj.maps.values() { if let Map::Legacy(m) = map { assert_eq!(&m.def, def); } else { panic!("expected a BTF map") } } } #[test] fn test_parse_section_data() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section(BpfSectionKind::Data, ".bss", b"map data")), Ok(()) ); assert!(obj.maps.get(".bss").is_some()); assert_matches!( obj.parse_section(fake_section(BpfSectionKind::Data, ".rodata", b"map data")), Ok(()) ); assert!(obj.maps.get(".rodata").is_some()); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Data, ".rodata.boo", b"map data" )), Ok(()) ); assert!(obj.maps.get(".rodata.boo").is_some()); assert_matches!( obj.parse_section(fake_section(BpfSectionKind::Data, ".data", b"map data")), Ok(()) ); assert!(obj.maps.get(".data").is_some()); assert_matches!( obj.parse_section(fake_section(BpfSectionKind::Data, ".data.boo", b"map data")), Ok(()) ); assert!(obj.maps.get(".data.boo").is_some()); } #[test] fn test_parse_section_kprobe() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "kprobe/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::KProbe { .. }, .. }) ); } #[test] fn test_parse_section_uprobe() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "uprobe/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::UProbe { .. }, .. }) ); } #[test] fn test_parse_section_trace_point() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "tracepoint/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::TracePoint { .. }, .. }) ); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "tp/foo/bar", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo/bar"), Some(Program { section: ProgramSection::TracePoint { .. }, .. }) ); } #[test] fn test_parse_section_socket_filter() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "socket/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::SocketFilter { .. }, .. }) ); } #[test] fn test_parse_section_xdp() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "xdp/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::Xdp { .. }, .. }) ); } #[test] fn test_parse_section_raw_tp() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "raw_tp/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::RawTracePoint { .. }, .. }) ); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "raw_tracepoint/bar", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("bar"), Some(Program { section: ProgramSection::RawTracePoint { .. }, .. }) ); } #[test] fn test_parse_section_lsm() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "lsm/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::Lsm { .. }, .. }) ); } #[test] fn test_parse_section_btf_tracepoint() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "tp_btf/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::BtfTracePoint { .. }, .. }) ); } #[test] fn test_parse_section_skskb_unnamed() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "sk_skb/stream_parser", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("stream_parser"), Some(Program { section: ProgramSection::SkSkbStreamParser { .. }, .. }) ); } #[test] fn test_parse_section_skskb_named() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "sk_skb/stream_parser/my_parser", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("my_parser"), Some(Program { section: ProgramSection::SkSkbStreamParser { .. }, .. }) ); } #[test] fn test_parse_section_fentry() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "fentry/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::FEntry { .. }, .. }) ); } #[test] fn test_parse_section_fexit() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "fexit/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::FExit { .. }, .. }) ); } #[test] fn test_parse_section_cgroup_skb_ingress_unnamed() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup_skb/ingress", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("ingress"), Some(Program { section: ProgramSection::CgroupSkbIngress { .. }, .. }) ); } #[test] fn test_parse_section_cgroup_skb_ingress_named() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup_skb/ingress/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::CgroupSkbIngress { .. }, .. }) ); } #[test] fn test_parse_section_cgroup_skb_no_direction_unamed() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/skb", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("skb"), Some(Program { section: ProgramSection::CgroupSkb { .. }, .. }) ); } #[test] fn test_parse_section_cgroup_skb_no_direction_named() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/skb/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::CgroupSkb { .. }, .. }) ); } #[test] fn test_parse_section_sock_addr_named() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/connect4/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::CgroupSockAddr { attach_type: CgroupSockAddrAttachType::Connect4, .. }, .. }) ); } #[test] fn test_parse_section_sock_addr_unnamed() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/connect4", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("connect4"), Some(Program { section: ProgramSection::CgroupSockAddr { attach_type: CgroupSockAddrAttachType::Connect4, .. }, .. }) ); } #[test] fn test_parse_section_sockopt_named() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/getsockopt/foo", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("foo"), Some(Program { section: ProgramSection::CgroupSockopt { attach_type: CgroupSockoptAttachType::Get, .. }, .. }) ); } #[test] fn test_parse_section_sockopt_unnamed() { let mut obj = fake_obj(); assert_matches!( obj.parse_section(fake_section( BpfSectionKind::Program, "cgroup/getsockopt", bytes_of(&fake_ins()) )), Ok(()) ); assert_matches!( obj.programs.get("getsockopt"), Some(Program { section: ProgramSection::CgroupSockopt { attach_type: CgroupSockoptAttachType::Get, .. }, .. }) ); } #[test] fn test_patch_map_data() { let mut obj = fake_obj(); obj.maps.insert( ".rodata".to_string(), Map::Legacy(LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_ARRAY as u32, key_size: mem::size_of::<u32>() as u32, value_size: 3, max_entries: 1, map_flags: BPF_F_RDONLY_PROG, id: 1, pinning: PinningType::None, ..Default::default() }, section_index: 1, symbol_index: 1, data: vec![0, 0, 0], kind: MapKind::Rodata, }), ); obj.symbols_by_index.insert( 1, Symbol { index: 1, section_index: Some(1), name: Some("my_config".to_string()), address: 0, size: 3, is_definition: true, kind: SymbolKind::Data, }, ); let test_data: &[u8] = &[1, 2, 3]; obj.patch_map_data(HashMap::from([("my_config", test_data)])) .unwrap(); let map = obj.maps.get(".rodata").unwrap(); assert_eq!(test_data, map.data()); } #[test] fn test_parse_btf_map_section() { let mut obj = fake_obj(); fake_sym(&mut obj, 0, 0, "map_1", 0); fake_sym(&mut obj, 0, 0, "map_2", 0); // generated from: // objcopy --dump-section .BTF=test.btf ./target/bpfel-unknown-none/debug/multimap-btf.bpf.o // hexdump -v -e '7/1 "0x%02X, " 1/1 " 0x%02X,\n"' test.btf let data: &[u8] = &[ 0x9F, 0xEB, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x01, 0x00, 0x00, 0xF0, 0x01, 0x00, 0x00, 0xCC, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x07, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x09, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x0A, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x4E, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x04, 0x20, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x4E, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0C, 0x12, 0x00, 0x00, 0x00, 0xB0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xB5, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x15, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xBE, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xC4, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x69, 0x6E, 0x74, 0x00, 0x5F, 0x5F, 0x41, 0x52, 0x52, 0x41, 0x59, 0x5F, 0x53, 0x49, 0x5A, 0x45, 0x5F, 0x54, 0x59, 0x50, 0x45, 0x5F, 0x5F, 0x00, 0x5F, 0x5F, 0x75, 0x33, 0x32, 0x00, 0x75, 0x6E, 0x73, 0x69, 0x67, 0x6E, 0x65, 0x64, 0x20, 0x69, 0x6E, 0x74, 0x00, 0x5F, 0x5F, 0x75, 0x36, 0x34, 0x00, 0x75, 0x6E, 0x73, 0x69, 0x67, 0x6E, 0x65, 0x64, 0x20, 0x6C, 0x6F, 0x6E, 0x67, 0x20, 0x6C, 0x6F, 0x6E, 0x67, 0x00, 0x74, 0x79, 0x70, 0x65, 0x00, 0x6B, 0x65, 0x79, 0x00, 0x76, 0x61, 0x6C, 0x75, 0x65, 0x00, 0x6D, 0x61, 0x78, 0x5F, 0x65, 0x6E, 0x74, 0x72, 0x69, 0x65, 0x73, 0x00, 0x6D, 0x61, 0x70, 0x5F, 0x31, 0x00, 0x6D, 0x61, 0x70, 0x5F, 0x32, 0x00, 0x63, 0x74, 0x78, 0x00, 0x62, 0x70, 0x66, 0x5F, 0x70, 0x72, 0x6F, 0x67, 0x00, 0x74, 0x72, 0x61, 0x63, 0x65, 0x70, 0x6F, 0x69, 0x6E, 0x74, 0x00, 0x2F, 0x76, 0x61, 0x72, 0x2F, 0x68, 0x6F, 0x6D, 0x65, 0x2F, 0x64, 0x61, 0x76, 0x65, 0x2F, 0x64, 0x65, 0x76, 0x2F, 0x61, 0x79, 0x61, 0x2D, 0x72, 0x73, 0x2F, 0x61, 0x79, 0x61, 0x2F, 0x74, 0x65, 0x73, 0x74, 0x2F, 0x69, 0x6E, 0x74, 0x65, 0x67, 0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2D, 0x65, 0x62, 0x70, 0x66, 0x2F, 0x73, 0x72, 0x63, 0x2F, 0x62, 0x70, 0x66, 0x2F, 0x6D, 0x75, 0x6C, 0x74, 0x69, 0x6D, 0x61, 0x70, 0x2D, 0x62, 0x74, 0x66, 0x2E, 0x62, 0x70, 0x66, 0x2E, 0x63, 0x00, 0x69, 0x6E, 0x74, 0x20, 0x62, 0x70, 0x66, 0x5F, 0x70, 0x72, 0x6F, 0x67, 0x28, 0x76, 0x6F, 0x69, 0x64, 0x20, 0x2A, 0x63, 0x74, 0x78, 0x29, 0x00, 0x09, 0x5F, 0x5F, 0x75, 0x33, 0x32, 0x20, 0x6B, 0x65, 0x79, 0x20, 0x3D, 0x20, 0x30, 0x3B, 0x00, 0x09, 0x5F, 0x5F, 0x75, 0x36, 0x34, 0x20, 0x74, 0x77, 0x65, 0x6E, 0x74, 0x79, 0x5F, 0x66, 0x6F, 0x75, 0x72, 0x20, 0x3D, 0x20, 0x32, 0x34, 0x3B, 0x00, 0x09, 0x5F, 0x5F, 0x75, 0x36, 0x34, 0x20, 0x66, 0x6F, 0x72, 0x74, 0x79, 0x5F, 0x74, 0x77, 0x6F, 0x20, 0x3D, 0x20, 0x34, 0x32, 0x3B, 0x00, 0x20, 0x20, 0x20, 0x20, 0x62, 0x70, 0x66, 0x5F, 0x6D, 0x61, 0x70, 0x5F, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5F, 0x65, 0x6C, 0x65, 0x6D, 0x28, 0x26, 0x6D, 0x61, 0x70, 0x5F, 0x31, 0x2C, 0x20, 0x26, 0x6B, 0x65, 0x79, 0x2C, 0x20, 0x26, 0x74, 0x77, 0x65, 0x6E, 0x74, 0x79, 0x5F, 0x66, 0x6F, 0x75, 0x72, 0x2C, 0x20, 0x42, 0x50, 0x46, 0x5F, 0x41, 0x4E, 0x59, 0x29, 0x3B, 0x00, 0x20, 0x20, 0x20, 0x20, 0x62, 0x70, 0x66, 0x5F, 0x6D, 0x61, 0x70, 0x5F, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5F, 0x65, 0x6C, 0x65, 0x6D, 0x28, 0x26, 0x6D, 0x61, 0x70, 0x5F, 0x32, 0x2C, 0x20, 0x26, 0x6B, 0x65, 0x79, 0x2C, 0x20, 0x26, 0x66, 0x6F, 0x72, 0x74, 0x79, 0x5F, 0x74, 0x77, 0x6F, 0x2C, 0x20, 0x42, 0x50, 0x46, 0x5F, 0x41, 0x4E, 0x59, 0x29, 0x3B, 0x00, 0x09, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x20, 0x30, 0x3B, 0x00, 0x63, 0x68, 0x61, 0x72, 0x00, 0x5F, 0x6C, 0x69, 0x63, 0x65, 0x6E, 0x73, 0x65, 0x00, 0x2E, 0x6D, 0x61, 0x70, 0x73, 0x00, 0x6C, 0x69, 0x63, 0x65, 0x6E, 0x73, 0x65, 0x00, ]; let btf_section = fake_section(BpfSectionKind::Btf, ".BTF", data); obj.parse_section(btf_section).unwrap(); let map_section = fake_section(BpfSectionKind::BtfMaps, ".maps", &[]); obj.parse_section(map_section).unwrap(); let map = obj.maps.get("map_1").unwrap(); if let Map::Btf(m) = map { assert_eq!(m.def.key_size, 4); assert_eq!(m.def.value_size, 8); assert_eq!(m.def.max_entries, 1); } else { panic!("expected a BTF map") } } } <file_sep>/aya/src/programs/raw_trace_point.rs //! Raw tracepoints. use std::ffi::CString; use crate::{ generated::bpf_prog_type::BPF_PROG_TYPE_RAW_TRACEPOINT, programs::{ define_link_wrapper, load_program, utils::attach_raw_tracepoint, FdLink, FdLinkId, ProgramData, ProgramError, }, }; /// A program that can be attached at a pre-defined kernel trace point, but also /// has an access to kernel internal arguments of trace points, which /// differentiates them from traditional tracepoint eBPF programs. /// /// The kernel provides a set of pre-defined trace points that eBPF programs can /// be attached to. See`/sys/kernel/debug/tracing/events` for a list of which /// events can be traced. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.17. /// /// # Examples /// /// ```no_run /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::RawTracePoint}; /// /// let program: &mut RawTracePoint = bpf.program_mut("sys_enter").unwrap().try_into()?; /// program.load()?; /// program.attach("sys_enter")?; /// # Ok::<(), aya::BpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_RAW_TRACEPOINT")] pub struct RawTracePoint { pub(crate) data: ProgramData<RawTracePointLink>, } impl RawTracePoint { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_RAW_TRACEPOINT, &mut self.data) } /// Attaches the program to the given tracepoint. /// /// The returned value can be used to detach, see [RawTracePoint::detach]. pub fn attach(&mut self, tp_name: &str) -> Result<RawTracePointLinkId, ProgramError> { let tp_name_c = CString::new(tp_name).unwrap(); attach_raw_tracepoint(&mut self.data, Some(&tp_name_c)) } /// Detaches from a tracepoint. /// /// See [RawTracePoint::attach]. pub fn detach(&mut self, link_id: RawTracePointLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: RawTracePointLinkId, ) -> Result<RawTracePointLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [RawTracePoint] programs. RawTracePointLink, /// The type returned by [RawTracePoint::attach]. Can be passed to [RawTracePoint::detach]. RawTracePointLinkId, FdLink, FdLinkId ); <file_sep>/aya/src/programs/tp_btf.rs //! BTF-enabled raw tracepoints. use crate::{ generated::{bpf_attach_type::BPF_TRACE_RAW_TP, bpf_prog_type::BPF_PROG_TYPE_TRACING}, obj::btf::{Btf, BtfKind}, programs::{ define_link_wrapper, load_program, utils::attach_raw_tracepoint, FdLink, FdLinkId, ProgramData, ProgramError, }, }; /// Marks a function as a [BTF-enabled raw tracepoint][1] eBPF program that can be attached at /// a pre-defined kernel trace point. /// /// The kernel provides a set of pre-defined trace points that eBPF programs can /// be attached to. See `/sys/kernel/debug/tracing/events` for a list of which /// events can be traced. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # BtfError(#[from] aya::BtfError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # } /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::BtfTracePoint, BtfError, Btf}; /// /// let btf = Btf::from_sys_fs()?; /// let program: &mut BtfTracePoint = bpf.program_mut("sched_process_fork").unwrap().try_into()?; /// program.load("sched_process_fork", &btf)?; /// program.attach()?; /// # Ok::<(), Error>(()) /// ``` /// /// [1]: https://github.com/torvalds/linux/commit/9e15db66136a14cde3f35691f1d839d950118826 #[derive(Debug)] #[doc(alias = "BPF_TRACE_RAW_TP")] #[doc(alias = "BPF_PROG_TYPE_TRACING")] pub struct BtfTracePoint { pub(crate) data: ProgramData<BtfTracePointLink>, } impl BtfTracePoint { /// Loads the program inside the kernel. /// /// # Arguments /// /// * `tracepoint` - full name of the tracepoint that we should attach to /// * `btf` - btf information for the target system pub fn load(&mut self, tracepoint: &str, btf: &Btf) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(BPF_TRACE_RAW_TP); let type_name = format!("btf_trace_{tracepoint}"); self.data.attach_btf_id = Some(btf.id_by_type_name_kind(type_name.as_str(), BtfKind::Typedef)?); load_program(BPF_PROG_TYPE_TRACING, &mut self.data) } /// Attaches the program. /// /// The returned value can be used to detach, see [BtfTracePoint::detach]. pub fn attach(&mut self) -> Result<BtfTracePointLinkId, ProgramError> { attach_raw_tracepoint(&mut self.data, None) } /// Detaches the program. /// /// See [BtfTracePoint::attach]. pub fn detach(&mut self, link_id: BtfTracePointLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: BtfTracePointLinkId, ) -> Result<BtfTracePointLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [BtfTracePoint] programs. BtfTracePointLink, /// The type returned by [BtfTracePoint::attach]. Can be passed to [BtfTracePoint::detach]. BtfTracePointLinkId, FdLink, FdLinkId ); <file_sep>/aya/src/maps/sock/mod.rs //! Socket maps. mod sock_hash; mod sock_map; pub use sock_hash::SockHash; pub use sock_map::SockMap; use std::os::unix::io::{AsRawFd, RawFd}; /// A socket map file descriptor. #[derive(Copy, Clone)] pub struct SockMapFd(RawFd); impl AsRawFd for SockMapFd { fn as_raw_fd(&self) -> RawFd { self.0 } } <file_sep>/aya/src/programs/extension.rs //! Extension programs. use std::os::unix::prelude::{AsRawFd, RawFd}; use thiserror::Error; use object::Endianness; use crate::{ generated::{bpf_attach_type::BPF_CGROUP_INET_INGRESS, bpf_prog_type::BPF_PROG_TYPE_EXT}, obj::btf::BtfKind, programs::{ define_link_wrapper, load_program, FdLink, FdLinkId, ProgramData, ProgramError, ProgramFd, }, sys::{self, bpf_link_create}, Btf, }; /// The type returned when loading or attaching an [`Extension`] fails. #[derive(Debug, Error)] pub enum ExtensionError { /// Target BPF program does not have BTF loaded to the kernel. #[error("target BPF program does not have BTF loaded to the kernel")] NoBTF, } /// A program used to extend existing BPF programs. /// /// [`Extension`] programs can be loaded to replace a global /// function in a program that has already been loaded. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.9 /// /// # Examples /// /// ```no_run /// use aya::{BpfLoader, programs::{Xdp, XdpFlags, Extension}}; /// /// let mut bpf = BpfLoader::new().extension("extension").load_file("app.o")?; /// let prog: &mut Xdp = bpf.program_mut("main").unwrap().try_into()?; /// prog.load()?; /// prog.attach("eth0", XdpFlags::default())?; /// /// let prog_fd = prog.fd().unwrap(); /// let ext: &mut Extension = bpf.program_mut("extension").unwrap().try_into()?; /// ext.load(prog_fd, "function_to_replace")?; /// ext.attach()?; /// Ok::<(), aya::BpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_EXT")] pub struct Extension { pub(crate) data: ProgramData<ExtensionLink>, } impl Extension { /// Loads the extension inside the kernel. /// /// Prepares the code included in the extension to replace the code of the function /// `func_name` within the eBPF program represented by the `program` file descriptor. /// This requires that both the [`Extension`] and `program` have had their BTF /// loaded into the kernel. /// /// The BPF verifier requires that we specify the target program and function name /// at load time, so it can identify that the program and target are BTF compatible /// and to enforce this constraint when programs are attached. /// /// The extension code will be loaded but inactive until it's attached. /// There are no restrictions on what functions may be replaced, so you could replace /// the main entry point of your program with an extension. pub fn load(&mut self, program: ProgramFd, func_name: &str) -> Result<(), ProgramError> { let target_prog_fd = program.as_raw_fd(); let (btf_fd, btf_id) = get_btf_info(target_prog_fd, func_name)?; self.data.attach_btf_obj_fd = Some(btf_fd as u32); self.data.attach_prog_fd = Some(target_prog_fd); self.data.attach_btf_id = Some(btf_id); load_program(BPF_PROG_TYPE_EXT, &mut self.data) } /// Attaches the extension. /// /// Attaches the extension to the program and function name specified at load time, /// effectively replacing the original target function. /// /// The returned value can be used to detach the extension and restore the /// original function, see [Extension::detach]. pub fn attach(&mut self) -> Result<ExtensionLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let target_fd = self.data.attach_prog_fd.ok_or(ProgramError::NotLoaded)?; let btf_id = self.data.attach_btf_id.ok_or(ProgramError::NotLoaded)?; // the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0) .map_err(|(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, })? as RawFd; self.data .links .insert(ExtensionLink::new(FdLink::new(link_fd))) } /// Attaches the extension to another program. /// /// Attaches the extension to a program and/or function other than the one provided /// at load time. You may only attach to another program/function if the BTF /// type signature is identical to that which was verified on load. Attempting to /// attach to an invalid program/function will result in an error. /// /// Once attached, the extension effectively replaces the original target function. /// /// The returned value can be used to detach the extension and restore the /// original function, see [Extension::detach]. pub fn attach_to_program( &mut self, program: ProgramFd, func_name: &str, ) -> Result<ExtensionLinkId, ProgramError> { let target_fd = program.as_raw_fd(); let (_, btf_id) = get_btf_info(target_fd, func_name)?; let prog_fd = self.data.fd_or_err()?; // the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0) .map_err(|(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, })? as RawFd; self.data .links .insert(ExtensionLink::new(FdLink::new(link_fd))) } /// Detaches the extension. /// /// Detaching restores the original code overridden by the extension program. /// See [Extension::attach]. pub fn detach(&mut self, link_id: ExtensionLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: ExtensionLinkId) -> Result<ExtensionLink, ProgramError> { self.data.take_link(link_id) } } /// Retrieves the FD of the BTF object for the provided `prog_fd` and the BTF ID of the function /// with the name `func_name` within that BTF object. fn get_btf_info(prog_fd: i32, func_name: &str) -> Result<(RawFd, u32), ProgramError> { // retrieve program information let info = sys::bpf_prog_get_info_by_fd(prog_fd).map_err(|io_error| ProgramError::SyscallError { call: "bpf_prog_get_info_by_fd".to_owned(), io_error, })?; // btf_id refers to the ID of the program btf that was loaded with bpf(BPF_BTF_LOAD) if info.btf_id == 0 { return Err(ProgramError::ExtensionError(ExtensionError::NoBTF)); } // the bpf fd of the BTF object let btf_fd = sys::bpf_btf_get_fd_by_id(info.btf_id).map_err(|io_error| ProgramError::SyscallError { call: "bpf_btf_get_fd_by_id".to_owned(), io_error, })?; // we need to read the btf bytes into a buffer but we don't know the size ahead of time. // assume 4kb. if this is too small we can resize based on the size obtained in the response. let mut buf = vec![0u8; 4096]; let btf_info = match sys::btf_obj_get_info_by_fd(btf_fd, &mut buf) { Ok(info) => { if info.btf_size > buf.len() as u32 { buf.resize(info.btf_size as usize, 0u8); let btf_info = sys::btf_obj_get_info_by_fd(btf_fd, &mut buf).map_err(|io_error| { ProgramError::SyscallError { call: "bpf_prog_get_info_by_fd".to_owned(), io_error, } })?; Ok(btf_info) } else { Ok(info) } } Err(io_error) => Err(ProgramError::SyscallError { call: "bpf_prog_get_info_by_fd".to_owned(), io_error, }), }?; let btf = Btf::parse(&buf[0..btf_info.btf_size as usize], Endianness::default()) .map_err(ProgramError::Btf)?; let btf_id = btf .id_by_type_name_kind(func_name, BtfKind::Func) .map_err(ProgramError::Btf)?; Ok((btf_fd, btf_id)) } define_link_wrapper!( /// The link used by [Extension] programs. ExtensionLink, /// The type returned by [Extension::attach]. Can be passed to [Extension::detach]. ExtensionLinkId, FdLink, FdLinkId ); <file_sep>/aya/src/programs/perf_attach.rs //! Perf attach links. use libc::close; use std::os::unix::io::RawFd; use crate::{ programs::{probe::detach_debug_fs, Link, ProbeKind, ProgramData, ProgramError}, sys::perf_event_ioctl, PERF_EVENT_IOC_DISABLE, PERF_EVENT_IOC_ENABLE, PERF_EVENT_IOC_SET_BPF, }; /// The identifer of a PerfLink. #[derive(Debug, Hash, Eq, PartialEq)] pub struct PerfLinkId(RawFd); /// The attachment type of PerfEvent programs. #[derive(Debug)] pub struct PerfLink { perf_fd: RawFd, probe_kind: Option<ProbeKind>, event_alias: Option<String>, } impl Link for PerfLink { type Id = PerfLinkId; fn id(&self) -> Self::Id { PerfLinkId(self.perf_fd) } fn detach(mut self) -> Result<(), ProgramError> { let _ = perf_event_ioctl(self.perf_fd, PERF_EVENT_IOC_DISABLE, 0); unsafe { close(self.perf_fd) }; if let Some(probe_kind) = self.probe_kind.take() { if let Some(event_alias) = self.event_alias.take() { let _ = detach_debug_fs(probe_kind, &event_alias); } } Ok(()) } } pub(crate) fn perf_attach<T: Link + From<PerfLink>>( data: &mut ProgramData<T>, fd: RawFd, ) -> Result<T::Id, ProgramError> { perf_attach_either(data, fd, None, None) } pub(crate) fn perf_attach_debugfs<T: Link + From<PerfLink>>( data: &mut ProgramData<T>, fd: RawFd, probe_kind: ProbeKind, event_alias: String, ) -> Result<T::Id, ProgramError> { perf_attach_either(data, fd, Some(probe_kind), Some(event_alias)) } fn perf_attach_either<T: Link + From<PerfLink>>( data: &mut ProgramData<T>, fd: RawFd, probe_kind: Option<ProbeKind>, event_alias: Option<String>, ) -> Result<T::Id, ProgramError> { let prog_fd = data.fd_or_err()?; perf_event_ioctl(fd, PERF_EVENT_IOC_SET_BPF, prog_fd).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "PERF_EVENT_IOC_SET_BPF".to_owned(), io_error, } })?; perf_event_ioctl(fd, PERF_EVENT_IOC_ENABLE, 0).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "PERF_EVENT_IOC_ENABLE".to_owned(), io_error, } })?; data.links.insert( PerfLink { perf_fd: fd, probe_kind, event_alias, } .into(), ) } <file_sep>/test/integration-test/src/tests/smoke.rs use aya::{ include_bytes_aligned, programs::{Extension, Xdp, XdpFlags}, Bpf, BpfLoader, }; use log::info; use super::{integration_test, kernel_version, IntegrationTest}; #[integration_test] fn xdp() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/pass"); let mut bpf = Bpf::load(bytes).unwrap(); let dispatcher: &mut Xdp = bpf.program_mut("pass").unwrap().try_into().unwrap(); dispatcher.load().unwrap(); dispatcher.attach("lo", XdpFlags::default()).unwrap(); } #[integration_test] fn extension() { let (major, minor, _) = kernel_version().unwrap(); if major < 5 || minor < 9 { info!( "skipping as {}.{} does not meet version requirement of 5.9", major, minor ); return; } // TODO: Check kernel version == 5.9 or later let main_bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/main.bpf.o"); let mut bpf = Bpf::load(main_bytes).unwrap(); let pass: &mut Xdp = bpf.program_mut("pass").unwrap().try_into().unwrap(); pass.load().unwrap(); pass.attach("lo", XdpFlags::default()).unwrap(); let ext_bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/ext.bpf.o"); let mut bpf = BpfLoader::new().extension("drop").load(ext_bytes).unwrap(); let drop_: &mut Extension = bpf.program_mut("drop").unwrap().try_into().unwrap(); drop_.load(pass.fd().unwrap(), "xdp_pass").unwrap(); } <file_sep>/bpf/aya-bpf/src/maps/sock_map.rs use core::{cell::UnsafeCell, mem}; use aya_bpf_cty::c_void; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_SOCKMAP, bpf_sock_ops}, helpers::{ bpf_map_lookup_elem, bpf_msg_redirect_map, bpf_sk_assign, bpf_sk_redirect_map, bpf_sk_release, bpf_sock_map_update, }, maps::PinningType, programs::{SkBuffContext, SkLookupContext, SkMsgContext}, BpfContext, }; #[repr(transparent)] pub struct SockMap { def: UnsafeCell<bpf_map_def>, } unsafe impl Sync for SockMap {} impl SockMap { pub const fn with_max_entries(max_entries: u32, flags: u32) -> SockMap { SockMap { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_SOCKMAP, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), } } pub const fn pinned(max_entries: u32, flags: u32) -> SockMap { SockMap { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_SOCKMAP, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), } } pub unsafe fn update( &self, mut index: u32, sk_ops: *mut bpf_sock_ops, flags: u64, ) -> Result<(), i64> { let ret = bpf_sock_map_update( sk_ops, self.def.get() as *mut _, &mut index as *mut _ as *mut c_void, flags, ); if ret == 0 { Ok(()) } else { Err(ret) } } pub unsafe fn redirect_msg(&self, ctx: &SkMsgContext, index: u32, flags: u64) -> i64 { bpf_msg_redirect_map( ctx.as_ptr() as *mut _, self.def.get() as *mut _, index, flags, ) } pub unsafe fn redirect_skb(&self, ctx: &SkBuffContext, index: u32, flags: u64) -> i64 { bpf_sk_redirect_map( ctx.as_ptr() as *mut _, self.def.get() as *mut _, index, flags, ) } pub fn redirect_sk_lookup( &mut self, ctx: &SkLookupContext, index: u32, flags: u64, ) -> Result<(), u32> { unsafe { let sk = bpf_map_lookup_elem( &mut self.def as *mut _ as *mut _, &index as *const _ as *const c_void, ); if sk.is_null() { return Err(1); } let ret = bpf_sk_assign(ctx.as_ptr() as *mut _, sk, flags); bpf_sk_release(sk); (ret == 0).then_some(()).ok_or(1) } } } <file_sep>/aya/src/maps/array/array.rs use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_bounds, check_kv_size, IterableMap, MapData, MapError}, sys::{bpf_map_lookup_elem, bpf_map_update_elem}, Pod, }; /// A fixed-size array. /// /// The size of the array is defined on the eBPF side using the `bpf_map_def::max_entries` field. /// All the entries are zero-initialized when the map is created. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 3.19. /// /// # Examples /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::Array; /// /// let mut array = Array::try_from(bpf.map_mut("ARRAY").unwrap())?; /// array.set(1, 42, 0)?; /// assert_eq!(array.get(&1, 0)?, 42); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_ARRAY")] pub struct Array<T, V: Pod> { inner: T, _v: PhantomData<V>, } impl<T: AsRef<MapData>, V: Pod> Array<T, V> { pub(crate) fn new(map: T) -> Result<Array<T, V>, MapError> { let data = map.as_ref(); check_kv_size::<u32, V>(data)?; let _fd = data.fd_or_err()?; Ok(Array { inner: map, _v: PhantomData, }) } /// Returns the number of elements in the array. /// /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side. pub fn len(&self) -> u32 { self.inner.as_ref().obj.max_entries() } /// Returns the value stored at the given index. /// /// # Errors /// /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`] /// if `bpf_map_lookup_elem` fails. pub fn get(&self, index: &u32, flags: u64) -> Result<V, MapError> { let data = self.inner.as_ref(); check_bounds(data, *index)?; let fd = data.fd_or_err()?; let value = bpf_map_lookup_elem(fd, index, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; value.ok_or(MapError::KeyNotFound) } /// An iterator over the elements of the array. The iterator item type is `Result<V, /// MapError>`. pub fn iter(&self) -> impl Iterator<Item = Result<V, MapError>> + '_ { (0..self.len()).map(move |i| self.get(&i, 0)) } } impl<T: AsMut<MapData>, V: Pod> Array<T, V> { /// Sets the value of the element at the given index. /// /// # Errors /// /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`] /// if `bpf_map_update_elem` fails. pub fn set(&mut self, index: u32, value: impl Borrow<V>, flags: u64) -> Result<(), MapError> { let data = self.inner.as_mut(); check_bounds(data, index)?; let fd = data.fd_or_err()?; bpf_map_update_elem(fd, Some(&index), value.borrow(), flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } } impl<T: AsRef<MapData>, V: Pod> IterableMap<u32, V> for Array<T, V> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, index: &u32) -> Result<V, MapError> { self.get(index, 0) } } <file_sep>/aya/src/maps/bloom_filter.rs //! A Bloom Filter. use std::{borrow::Borrow, convert::AsRef, marker::PhantomData}; use crate::{ maps::{check_v_size, MapData, MapError}, sys::{bpf_map_lookup_elem_ptr, bpf_map_push_elem}, Pod, }; /// A Bloom Filter. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.16. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::bloom_filter::BloomFilter; /// /// let mut bloom_filter = BloomFilter::try_from(bpf.map_mut("BLOOM_FILTER").unwrap())?; /// /// bloom_filter.insert(1, 0)?; /// /// assert!(bloom_filter.contains(&1, 0).is_ok()); /// assert!(bloom_filter.contains(&2, 0).is_err()); /// /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_BLOOM_FILTER")] pub struct BloomFilter<T, V: Pod> { inner: T, _v: PhantomData<V>, } impl<T: AsRef<MapData>, V: Pod> BloomFilter<T, V> { pub(crate) fn new(map: T) -> Result<BloomFilter<T, V>, MapError> { let data = map.as_ref(); check_v_size::<V>(data)?; let _ = data.fd_or_err()?; Ok(BloomFilter { inner: map, _v: PhantomData, }) } /// Query the existence of the element. pub fn contains(&self, mut value: &V, flags: u64) -> Result<(), MapError> { let fd = self.inner.as_ref().fd_or_err()?; bpf_map_lookup_elem_ptr::<u32, _>(fd, None, &mut value, flags) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, })? .ok_or(MapError::ElementNotFound)?; Ok(()) } /// Inserts a value into the map. pub fn insert(&self, value: impl Borrow<V>, flags: u64) -> Result<(), MapError> { let fd = self.inner.as_ref().fd_or_err()?; bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_push_elem".to_owned(), io_error, } })?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::{ bpf_map_def, generated::{ bpf_cmd, bpf_map_type::{BPF_MAP_TYPE_BLOOM_FILTER, BPF_MAP_TYPE_PERF_EVENT_ARRAY}, }, maps::{Map, MapData}, obj, sys::{override_syscall, SysResult, Syscall}, }; use libc::{EFAULT, ENOENT}; use std::io; fn new_obj_map() -> obj::Map { obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_BLOOM_FILTER as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: obj::MapKind::Other, }) } fn sys_error(value: i32) -> SysResult { Err((-1, io::Error::from_raw_os_error(value))) } #[test] fn test_wrong_value_size() { let map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( BloomFilter::<_, u16>::new(&map), Err(MapError::InvalidValueSize { size: 2, expected: 4 }) )); } #[test] fn test_try_from_wrong_map() { let map_data = MapData { obj: obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: obj::MapKind::Other, }), fd: None, pinned: false, btf_fd: None, }; let map = Map::PerfEventArray(map_data); assert!(matches!( BloomFilter::<_, u32>::try_from(&map), Err(MapError::InvalidMapType { .. }) )); } #[test] fn test_new_not_created() { let mut map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( BloomFilter::<_, u32>::new(&mut map), Err(MapError::NotCreated { .. }) )); } #[test] fn test_new_ok() { let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; assert!(BloomFilter::<_, u32>::new(&mut map).is_ok()); } #[test] fn test_try_from_ok() { let map_data = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let map = Map::BloomFilter(map_data); assert!(BloomFilter::<_, u32>::try_from(&map).is_ok()) } #[test] fn test_insert_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let bloom_filter = BloomFilter::<_, u32>::new(&mut map).unwrap(); assert!(matches!( bloom_filter.insert(1, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_push_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_insert_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_UPDATE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let bloom_filter = BloomFilter::<_, u32>::new(&mut map).unwrap(); assert!(bloom_filter.insert(0, 42).is_ok()); } #[test] fn test_contains_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let bloom_filter = BloomFilter::<_, u32>::new(&map).unwrap(); assert!(matches!( bloom_filter.contains(&1, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_lookup_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_contains_not_found() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, .. } => sys_error(ENOENT), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let bloom_filter = BloomFilter::<_, u32>::new(&map).unwrap(); assert!(matches!( bloom_filter.contains(&1, 0), Err(MapError::ElementNotFound) )); } } <file_sep>/bpf/aya-bpf-bindings/src/lib.rs #![no_std] #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #[cfg(bpf_target_arch = "x86_64")] mod x86_64; #[cfg(bpf_target_arch = "arm")] mod armv7; #[cfg(bpf_target_arch = "aarch64")] mod aarch64; #[cfg(bpf_target_arch = "riscv64")] mod riscv64; mod gen { #[cfg(bpf_target_arch = "x86_64")] pub use super::x86_64::*; #[cfg(bpf_target_arch = "arm")] pub use super::armv7::*; #[cfg(bpf_target_arch = "aarch64")] pub use super::aarch64::*; #[cfg(bpf_target_arch = "riscv64")] pub use super::riscv64::*; } pub use gen::helpers; pub mod bindings { pub use crate::gen::bindings::*; pub const TC_ACT_OK: i32 = crate::gen::bindings::TC_ACT_OK as i32; pub const TC_ACT_RECLASSIFY: i32 = crate::gen::bindings::TC_ACT_RECLASSIFY as i32; pub const TC_ACT_SHOT: i32 = crate::gen::bindings::TC_ACT_SHOT as i32; pub const TC_ACT_PIPE: i32 = crate::gen::bindings::TC_ACT_PIPE as i32; pub const TC_ACT_STOLEN: i32 = crate::gen::bindings::TC_ACT_STOLEN as i32; pub const TC_ACT_QUEUED: i32 = crate::gen::bindings::TC_ACT_QUEUED as i32; pub const TC_ACT_REPEAT: i32 = crate::gen::bindings::TC_ACT_REPEAT as i32; pub const TC_ACT_REDIRECT: i32 = crate::gen::bindings::TC_ACT_REDIRECT as i32; pub const TC_ACT_TRAP: i32 = crate::gen::bindings::TC_ACT_TRAP as i32; pub const TC_ACT_VALUE_MAX: i32 = crate::gen::bindings::TC_ACT_VALUE_MAX as i32; pub const TC_ACT_EXT_VAL_MASK: i32 = 268435455; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct bpf_map_def { pub type_: ::aya_bpf_cty::c_uint, pub key_size: ::aya_bpf_cty::c_uint, pub value_size: ::aya_bpf_cty::c_uint, pub max_entries: ::aya_bpf_cty::c_uint, pub map_flags: ::aya_bpf_cty::c_uint, pub id: ::aya_bpf_cty::c_uint, pub pinning: ::aya_bpf_cty::c_uint, } } <file_sep>/bpf/aya-bpf/src/maps/sock_hash.rs use core::{borrow::Borrow, cell::UnsafeCell, marker::PhantomData, mem}; use aya_bpf_cty::c_void; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_SOCKHASH, bpf_sock_ops}, helpers::{ bpf_map_lookup_elem, bpf_msg_redirect_hash, bpf_sk_assign, bpf_sk_redirect_hash, bpf_sk_release, bpf_sock_hash_update, }, maps::PinningType, programs::{SkBuffContext, SkLookupContext, SkMsgContext}, BpfContext, }; #[repr(transparent)] pub struct SockHash<K> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, } unsafe impl<K: Sync> Sync for SockHash<K> {} impl<K> SockHash<K> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> SockHash<K> { SockHash { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_SOCKHASH, key_size: mem::size_of::<K>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), _k: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> SockHash<K> { SockHash { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_SOCKHASH, key_size: mem::size_of::<K>() as u32, value_size: mem::size_of::<u32>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), _k: PhantomData, } } pub fn update(&self, key: &mut K, sk_ops: &mut bpf_sock_ops, flags: u64) -> Result<(), i64> { let ret = unsafe { bpf_sock_hash_update( sk_ops as *mut _, self.def.get() as *mut _, key as *mut _ as *mut c_void, flags, ) }; (ret == 0).then_some(()).ok_or(ret) } pub fn redirect_msg(&self, ctx: &SkMsgContext, key: &mut K, flags: u64) -> i64 { unsafe { bpf_msg_redirect_hash( ctx.as_ptr() as *mut _, self.def.get() as *mut _, key as *mut _ as *mut _, flags, ) } } pub fn redirect_skb(&self, ctx: &SkBuffContext, key: &mut K, flags: u64) -> i64 { unsafe { bpf_sk_redirect_hash( ctx.as_ptr() as *mut _, self.def.get() as *mut _, key as *mut _ as *mut _, flags, ) } } pub fn redirect_sk_lookup( &mut self, ctx: &SkLookupContext, key: impl Borrow<K>, flags: u64, ) -> Result<(), u32> { unsafe { let sk = bpf_map_lookup_elem( &mut self.def as *mut _ as *mut _, &key as *const _ as *const c_void, ); if sk.is_null() { return Err(1); } let ret = bpf_sk_assign(ctx.as_ptr() as *mut _, sk, flags); bpf_sk_release(sk); (ret == 0).then_some(()).ok_or(1) } } } <file_sep>/aya/src/programs/cgroup_sockopt.rs //! Cgroup socket option programs. use thiserror::Error; use std::{ hash::Hash, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ generated::bpf_prog_type::BPF_PROG_TYPE_CGROUP_SOCKOPT, programs::{ bpf_attach_type, define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program that can be used to get or set options on sockets. /// /// [`CgroupSockopt`] programs can be attached to a cgroup and will be called every /// time a process executes getsockopt or setsockopt system call. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.3. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::CgroupSockopt; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let program: &mut CgroupSockopt = bpf.program_mut("cgroup_sockopt").unwrap().try_into()?; /// program.load()?; /// program.attach(file)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SOCKOPT")] pub struct CgroupSockopt { pub(crate) data: ProgramData<CgroupSockoptLink>, pub(crate) attach_type: CgroupSockoptAttachType, } impl CgroupSockopt { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(self.attach_type.into()); load_program(BPF_PROG_TYPE_CGROUP_SOCKOPT, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSockopt::detach]. pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<CgroupSockoptLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let attach_type = self.data.expected_attach_type.unwrap(); let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupSockoptLink::new(CgroupSockoptLinkInner::Fd( FdLink::new(link_fd), ))) } else { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data .links .insert(CgroupSockoptLink::new(CgroupSockoptLinkInner::ProgAttach( ProgAttachLink::new(prog_fd, cgroup_fd, attach_type), ))) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: CgroupSockoptLinkId, ) -> Result<CgroupSockoptLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [CgroupSockopt::attach]. pub fn detach(&mut self, link_id: CgroupSockoptLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupSockoptLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupSockoptLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupSockoptLinkInner { type Id = CgroupSockoptLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupSockoptLinkInner::Fd(fd) => CgroupSockoptLinkIdInner::Fd(fd.id()), CgroupSockoptLinkInner::ProgAttach(p) => CgroupSockoptLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupSockoptLinkInner::Fd(fd) => fd.detach(), CgroupSockoptLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupSockopt] programs. CgroupSockoptLink, /// The type returned by [CgroupSockopt::attach]. Can be passed to [CgroupSockopt::detach]. CgroupSockoptLinkId, CgroupSockoptLinkInner, CgroupSockoptLinkIdInner ); /// Defines where to attach a [`CgroupSockopt`] program. #[derive(Copy, Clone, Debug)] pub enum CgroupSockoptAttachType { /// Attach to GetSockopt. Get, /// Attach to SetSockopt. Set, } impl From<CgroupSockoptAttachType> for bpf_attach_type { fn from(s: CgroupSockoptAttachType) -> bpf_attach_type { match s { CgroupSockoptAttachType::Get => bpf_attach_type::BPF_CGROUP_GETSOCKOPT, CgroupSockoptAttachType::Set => bpf_attach_type::BPF_CGROUP_SETSOCKOPT, } } } #[derive(Debug, Error)] #[error("{0} is not a valid attach type for a CGROUP_SOCKOPT program")] pub(crate) struct InvalidAttachType(String); impl CgroupSockoptAttachType { pub(crate) fn try_from(value: &str) -> Result<CgroupSockoptAttachType, InvalidAttachType> { match value { "getsockopt" => Ok(CgroupSockoptAttachType::Get), "setsockopt" => Ok(CgroupSockoptAttachType::Set), _ => Err(InvalidAttachType(value.to_owned())), } } } <file_sep>/aya/src/maps/hash_map/mod.rs //! Hash map types. use crate::{ maps::MapError, sys::{bpf_map_delete_elem, bpf_map_update_elem}, Pod, }; #[allow(clippy::module_inception)] mod hash_map; mod per_cpu_hash_map; pub use hash_map::*; pub use per_cpu_hash_map::*; use super::MapData; pub(crate) fn insert<K: Pod, V: Pod>( map: &mut MapData, key: &K, value: &V, flags: u64, ) -> Result<(), MapError> { let fd = map.fd_or_err()?; bpf_map_update_elem(fd, Some(key), value, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } pub(crate) fn remove<K: Pod>(map: &mut MapData, key: &K) -> Result<(), MapError> { let fd = map.fd_or_err()?; bpf_map_delete_elem(fd, key) .map(|_| ()) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_delete_elem".to_owned(), io_error, }) } <file_sep>/Cargo.toml [workspace] members = [ "aya", "aya-tool", "aya-log", "aya-log-common", "aya-log-parser", "test/integration-test", "test/integration-test-macros", "xtask", # macros "aya-bpf-macros", "aya-log-ebpf-macros", # ebpf crates "bpf/aya-bpf", "bpf/aya-bpf-bindings", "bpf/aya-log-ebpf", "test/integration-ebpf" ] default-members = ["aya", "aya-tool", "aya-log", "aya-bpf-macros", "aya-log-ebpf-macros"] [profile.dev] panic = "abort" [profile.release] panic = "abort" [profile.dev.package.integration-ebpf] opt-level = 2 overflow-checks = false [profile.release.package.integration-ebpf] debug = 2 <file_sep>/aya/src/programs/lsm.rs //! LSM probes. use crate::{ generated::{bpf_attach_type::BPF_LSM_MAC, bpf_prog_type::BPF_PROG_TYPE_LSM}, obj::btf::{Btf, BtfKind}, programs::{ define_link_wrapper, load_program, utils::attach_raw_tracepoint, FdLink, FdLinkId, ProgramData, ProgramError, }, }; /// A program that attaches to Linux LSM hooks. Used to implement security policy and /// audit logging. /// /// LSM probes can be attached to the kernel's [security hooks][1] to implement mandatory /// access control policy and security auditing. /// /// LSM probes require a kernel compiled with `CONFIG_BPF_LSM=y` and `CONFIG_DEBUG_INFO_BTF=y`. /// In order for the probes to fire, you also need the BPF LSM to be enabled through your /// kernel's boot paramters (like `lsm=lockdown,yama,bpf`). /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.7. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum LsmError { /// # #[error(transparent)] /// # BtfError(#[from] aya::BtfError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # } /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::Lsm, BtfError, Btf}; /// /// let btf = Btf::from_sys_fs()?; /// let program: &mut Lsm = bpf.program_mut("lsm_prog").unwrap().try_into()?; /// program.load("security_bprm_exec", &btf)?; /// program.attach()?; /// # Ok::<(), LsmError>(()) /// ``` /// /// [1]: https://elixir.bootlin.com/linux/latest/source/include/linux/lsm_hook_defs.h #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_LSM")] pub struct Lsm { pub(crate) data: ProgramData<LsmLink>, } impl Lsm { /// Loads the program inside the kernel. /// /// # Arguments /// /// * `lsm_hook_name` - full name of the LSM hook that the program should /// be attached to pub fn load(&mut self, lsm_hook_name: &str, btf: &Btf) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(BPF_LSM_MAC); let type_name = format!("bpf_lsm_{lsm_hook_name}"); self.data.attach_btf_id = Some(btf.id_by_type_name_kind(type_name.as_str(), BtfKind::Func)?); load_program(BPF_PROG_TYPE_LSM, &mut self.data) } /// Attaches the program. /// /// The returned value can be used to detach, see [Lsm::detach]. pub fn attach(&mut self) -> Result<LsmLinkId, ProgramError> { attach_raw_tracepoint(&mut self.data, None) } /// Detaches the program. /// /// See [Lsm::attach]. pub fn detach(&mut self, link_id: LsmLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: LsmLinkId) -> Result<LsmLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [Lsm] programs. LsmLink, /// The type returned by [Lsm::attach]. Can be passed to [Lsm::detach]. LsmLinkId, FdLink, FdLinkId ); <file_sep>/aya-log-parser/Cargo.toml [package] name = "aya-log-parser" version = "0.1.11-dev.0" edition = "2018" [dependencies] aya-log-common = { path = "../aya-log-common" } [lib] path = "src/lib.rs" <file_sep>/aya-bpf-macros/src/expand.rs use proc_macro2::TokenStream; use quote::quote; use syn::{ parse::{Parse, ParseStream}, punctuated::{Pair, Punctuated}, token::Eq, Error, Ident, ItemFn, ItemStatic, LitStr, Result, Token, }; pub struct NameValue { name: Ident, _eq: Eq, value: LitStr, } pub struct Args { args: Vec<NameValue>, } impl Parse for Args { fn parse(input: ParseStream) -> Result<Args> { let args = Punctuated::<NameValue, Token![,]>::parse_terminated_with(input, |input| { Ok(NameValue { name: input.parse()?, _eq: input.parse()?, value: input.parse()?, }) })? .into_pairs() .map(|pair| match pair { Pair::Punctuated(name_val, _) => name_val, Pair::End(name_val) => name_val, }) .collect(); Ok(Args { args }) } } pub struct SockAddrArgs { pub(crate) attach_type: Ident, pub(crate) args: Args, } impl Parse for SockAddrArgs { fn parse(input: ParseStream) -> Result<SockAddrArgs> { let attach_type: Ident = input.parse()?; match attach_type.to_string().as_str() { "connect4" | "connect6" | "bind4" | "bind6" | "getpeername4" | "getpeername6" | "getsockname4" | "getsockname6" | "sendmsg4" | "sendmsg6" | "recvmsg4" | "recvmsg6" => (), _ => return Err(input.error("invalid attach type")), } let args = if input.parse::<Token![,]>().is_ok() { Args::parse(input)? } else { Args { args: vec![] } }; Ok(SockAddrArgs { attach_type, args }) } } pub struct SockoptArgs { pub(crate) attach_type: Ident, pub(crate) args: Args, } impl Parse for SockoptArgs { fn parse(input: ParseStream) -> Result<SockoptArgs> { let attach_type: Ident = input.parse()?; match attach_type.to_string().as_str() { "getsockopt" | "setsockopt" => (), _ => return Err(input.error("invalid attach type")), } let args = if input.parse::<Token![,]>().is_ok() { Args::parse(input)? } else { Args { args: vec![] } }; Ok(SockoptArgs { attach_type, args }) } } pub struct Map { item: ItemStatic, name: String, } impl Map { pub fn from_syn(mut args: Args, item: ItemStatic) -> Result<Map> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.ident.to_string()); Ok(Map { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = "maps".to_string(); let name = &self.name; let item = &self.item; Ok(quote! { #[link_section = #section_name] #[export_name = #name] #item }) } } pub struct Probe { kind: ProbeKind, item: ItemFn, name: String, } impl Probe { pub fn from_syn(kind: ProbeKind, mut args: Args, item: ItemFn) -> Result<Probe> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(Probe { kind, item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("{}/{}", self.kind, self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> u32 { let _ = #fn_name(::aya_bpf::programs::ProbeContext::new(ctx)); return 0; #item } }) } } pub struct SockOps { item: ItemFn, name: Option<String>, } impl SockOps { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<SockOps> { let name = name_arg(&mut args)?; Ok(SockOps { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("sockops/{name}") } else { "sockops".to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sock_ops) -> u32 { return #fn_name(::aya_bpf::programs::SockOpsContext::new(ctx)); #item } }) } } pub struct SkMsg { item: ItemFn, name: String, } impl SkMsg { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<SkMsg> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(SkMsg { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("sk_msg/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::sk_msg_md) -> u32 { return #fn_name(::aya_bpf::programs::SkMsgContext::new(ctx)); #item } }) } } pub struct Xdp { item: ItemFn, name: Option<String>, } impl Xdp { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<Xdp> { let name = name_arg(&mut args)?; Ok(Xdp { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("xdp/{name}") } else { "xdp".to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::xdp_md) -> u32 { return #fn_name(::aya_bpf::programs::XdpContext::new(ctx)); #item } }) } } pub struct SchedClassifier { item: ItemFn, name: Option<String>, } impl SchedClassifier { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<SchedClassifier> { let name = name_arg(&mut args)?; Ok(SchedClassifier { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("classifier/{name}") } else { "classifier".to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::__sk_buff) -> i32 { return #fn_name(::aya_bpf::programs::TcContext::new(ctx)); #item } }) } } pub struct CgroupSysctl { item: ItemFn, name: Option<String>, } impl CgroupSysctl { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<CgroupSysctl> { let name = name_arg(&mut args)?; Ok(CgroupSysctl { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("cgroup/sysctl/{name}") } else { ("cgroup/sysctl").to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sysctl) -> i32 { return #fn_name(::aya_bpf::programs::SysctlContext::new(ctx)); #item } }) } } pub struct CgroupSockopt { item: ItemFn, attach_type: String, name: Option<String>, } impl CgroupSockopt { pub fn from_syn(mut args: Args, item: ItemFn, attach_type: String) -> Result<CgroupSockopt> { let name = pop_arg(&mut args, "name"); err_on_unknown_args(&args)?; Ok(CgroupSockopt { item, attach_type, name, }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("cgroup/{}/{}", self.attach_type, name) } else { format!("cgroup/{}", self.attach_type) }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sockopt) -> i32 { return #fn_name(::aya_bpf::programs::SockoptContext::new(ctx)); #item } }) } } pub struct CgroupSkb { item: ItemFn, expected_attach_type: Option<String>, name: Option<String>, } impl CgroupSkb { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<CgroupSkb> { let name = pop_arg(&mut args, "name"); let expected_attach_type = pop_arg(&mut args, "attach"); err_on_unknown_args(&args)?; Ok(CgroupSkb { item, expected_attach_type, name, }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(attach) = &self.expected_attach_type { if let Some(name) = &self.name { format!("cgroup_skb/{attach}/{name}") } else { format!("cgroup_skb/{attach}") } } else if let Some(name) = &self.name { format!("cgroup/skb/{name}") } else { ("cgroup/skb").to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::__sk_buff) -> i32 { return #fn_name(::aya_bpf::programs::SkBuffContext::new(ctx)); #item } }) } } pub struct CgroupSockAddr { item: ItemFn, attach_type: String, name: Option<String>, } impl CgroupSockAddr { pub fn from_syn(mut args: Args, item: ItemFn, attach_type: String) -> Result<CgroupSockAddr> { let name = pop_arg(&mut args, "name"); err_on_unknown_args(&args)?; Ok(CgroupSockAddr { item, attach_type, name, }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("cgroup/{}/{}", self.attach_type, name) } else { format!("cgroup/{}", self.attach_type) }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sock_addr) -> i32 { return #fn_name(::aya_bpf::programs::SockAddrContext::new(ctx)); #item } }) } } pub struct CgroupSock { item: ItemFn, attach_type: Option<String>, name: Option<String>, } impl CgroupSock { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<CgroupSock> { let name = pop_arg(&mut args, "name"); let attach_type = pop_arg(&mut args, "attach"); err_on_unknown_args(&args)?; Ok(CgroupSock { item, attach_type, name, }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { if let Some(attach_type) = &self.attach_type { format!("cgroup/{attach_type}/{name}") } else { format!("cgroup/sock/{name}") } } else if let Some(attach_type) = &self.attach_type { format!("cgroup/{attach_type}") } else { "cgroup/sock".to_string() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sock) -> i32 { return #fn_name(::aya_bpf::programs::SockContext::new(ctx)); #item } }) } } fn pop_arg(args: &mut Args, name: &str) -> Option<String> { match args.args.iter().position(|arg| arg.name == name) { Some(index) => Some(args.args.remove(index).value.value()), None => None, } } fn err_on_unknown_args(args: &Args) -> Result<()> { if let Some(arg) = args.args.get(0) { return Err(Error::new_spanned(&arg.name, "invalid argument")); } Ok(()) } fn name_arg(args: &mut Args) -> Result<Option<String>> { let name = pop_arg(args, "name"); err_on_unknown_args(args)?; Ok(name) } #[allow(clippy::enum_variant_names)] #[derive(Debug, Copy, Clone)] pub enum ProbeKind { KProbe, KRetProbe, UProbe, URetProbe, } impl std::fmt::Display for ProbeKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use ProbeKind::*; match self { KProbe => write!(f, "kprobe"), KRetProbe => write!(f, "kretprobe"), UProbe => write!(f, "uprobe"), URetProbe => write!(f, "uretprobe"), } } } pub struct TracePoint { item: ItemFn, name: String, } impl TracePoint { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<TracePoint> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(TracePoint { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("tp/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> u32 { let _ = #fn_name(::aya_bpf::programs::TracePointContext::new(ctx)); return 0; #item } }) } } pub struct PerfEvent { item: ItemFn, name: String, } impl PerfEvent { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<PerfEvent> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(PerfEvent { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("perf_event/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> u32 { let _ = #fn_name(::aya_bpf::programs::PerfEventContext::new(ctx)); return 0; #item } }) } } pub struct RawTracePoint { item: ItemFn, name: String, } impl RawTracePoint { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<RawTracePoint> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(RawTracePoint { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("raw_tp/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> u32 { let _ = #fn_name(::aya_bpf::programs::RawTracePointContext::new(ctx)); return 0; #item } }) } } pub struct Lsm { item: ItemFn, name: String, } impl Lsm { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<Lsm> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(Lsm { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("lsm/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; // LSM probes need to return an integer corresponding to the correct // policy decision. Therefore we do not simply default to a return value // of 0 as in other program types. Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> i32 { return #fn_name(::aya_bpf::programs::LsmContext::new(ctx)); #item } }) } } pub struct BtfTracePoint { item: ItemFn, name: String, } impl BtfTracePoint { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<BtfTracePoint> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(BtfTracePoint { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("tp_btf/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> i32 { let _ = #fn_name(::aya_bpf::programs::BtfTracePointContext::new(ctx)); return 0; #item } }) } } #[allow(clippy::enum_variant_names)] #[derive(Debug, Copy, Clone)] pub enum SkSkbKind { StreamVerdict, StreamParser, } impl std::fmt::Display for SkSkbKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use SkSkbKind::*; match self { StreamVerdict => write!(f, "stream_verdict"), StreamParser => write!(f, "stream_parser"), } } } pub struct SkSkb { kind: SkSkbKind, item: ItemFn, name: Option<String>, } impl SkSkb { pub fn from_syn(kind: SkSkbKind, mut args: Args, item: ItemFn) -> Result<SkSkb> { let name = pop_arg(&mut args, "name"); err_on_unknown_args(&args)?; Ok(SkSkb { item, kind, name }) } pub fn expand(&self) -> Result<TokenStream> { let kind = &self.kind; let section_name = if let Some(name) = &self.name { format!("sk_skb/{kind}/{name}") } else { format!("sk_skb/{kind}") }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::__sk_buff) -> u32 { return #fn_name(::aya_bpf::programs::SkBuffContext::new(ctx)); #item } }) } } pub struct SocketFilter { item: ItemFn, name: Option<String>, } impl SocketFilter { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<SocketFilter> { let name = name_arg(&mut args)?; err_on_unknown_args(&args)?; Ok(SocketFilter { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("socket/{name}") } else { "socket".to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::__sk_buff) -> i64 { return #fn_name(::aya_bpf::programs::SkBuffContext::new(ctx)); #item } }) } } pub struct FEntry { item: ItemFn, name: String, } impl FEntry { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<FEntry> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(FEntry { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("fentry/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> i32 { let _ = #fn_name(::aya_bpf::programs::FEntryContext::new(ctx)); return 0; #item } }) } } pub struct FExit { item: ItemFn, name: String, } impl FExit { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<FExit> { let name = name_arg(&mut args)?.unwrap_or_else(|| item.sig.ident.to_string()); Ok(FExit { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = format!("fexit/{}", self.name); let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::core::ffi::c_void) -> i32 { let _ = #fn_name(::aya_bpf::programs::FExitContext::new(ctx)); return 0; #item } }) } } pub struct SkLookup { item: ItemFn, name: Option<String>, } impl SkLookup { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<SkLookup> { let name = name_arg(&mut args)?; Ok(SkLookup { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("sk_lookup/{name}") } else { "sk_lookup".to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_sk_lookup) -> u32 { return #fn_name(::aya_bpf::programs::SkLookupContext::new(ctx)); #item } }) } } pub struct CgroupDevice { item: ItemFn, name: Option<String>, } impl CgroupDevice { pub fn from_syn(mut args: Args, item: ItemFn) -> Result<Self> { let name = name_arg(&mut args)?; Ok(CgroupDevice { item, name }) } pub fn expand(&self) -> Result<TokenStream> { let section_name = if let Some(name) = &self.name { format!("cgroup/dev/{name}") } else { ("cgroup/dev").to_owned() }; let fn_name = &self.item.sig.ident; let item = &self.item; Ok(quote! { #[no_mangle] #[link_section = #section_name] fn #fn_name(ctx: *mut ::aya_bpf::bindings::bpf_cgroup_dev_ctx) -> i32 { return #fn_name(::aya_bpf::programs::DeviceContext::new(ctx)); #item } }) } } #[cfg(test)] mod tests { use syn::parse_quote; use super::*; #[test] fn cgroup_skb_with_attach_and_name() { let prog = CgroupSkb::from_syn( parse_quote!(name = "foo", attach = "ingress"), parse_quote!( fn foo(ctx: SkBuffContext) -> i32 { 0 } ), ) .unwrap(); let stream = prog.expand().unwrap(); assert!(stream .to_string() .contains("[link_section = \"cgroup_skb/ingress/foo\"]")); } #[test] fn cgroup_skb_with_name() { let prog = CgroupSkb::from_syn( parse_quote!(name = "foo"), parse_quote!( fn foo(ctx: SkBuffContext) -> i32 { 0 } ), ) .unwrap(); let stream = prog.expand().unwrap(); assert!(stream .to_string() .contains("[link_section = \"cgroup/skb/foo\"]")); } #[test] fn cgroup_skb_no_name() { let prog = CgroupSkb::from_syn( parse_quote!(), parse_quote!( fn foo(ctx: SkBuffContext) -> i32 { 0 } ), ) .unwrap(); let stream = prog.expand().unwrap(); assert!(stream .to_string() .contains("[link_section = \"cgroup/skb\"]")); } #[test] fn cgroup_skb_with_attach_no_name() { let prog = CgroupSkb::from_syn( parse_quote!(attach = "egress"), parse_quote!( fn foo(ctx: SkBuffContext) -> i32 { 0 } ), ) .unwrap(); let stream = prog.expand().unwrap(); assert!(stream .to_string() .contains("[link_section = \"cgroup_skb/egress\"]")); } #[test] fn cgroup_device_no_name() { let prog = CgroupDevice::from_syn( parse_quote!(), parse_quote!( fn foo(ctx: DeviceContext) -> i32 { 0 } ), ) .unwrap(); let stream = prog.expand().unwrap(); assert!(stream .to_string() .contains("[link_section = \"cgroup/dev\"]")); } } <file_sep>/xtask/src/run.rs use std::{os::unix::process::CommandExt, path::PathBuf, process::Command}; use anyhow::Context as _; use clap::Parser; use crate::build_ebpf::{build_ebpf, Architecture, BuildEbpfOptions as BuildOptions}; #[derive(Debug, Parser)] pub struct Options { /// Set the endianness of the BPF target #[clap(default_value = "bpfel-unknown-none", long)] pub bpf_target: Architecture, /// Build and run the release target #[clap(long)] pub release: bool, /// The command used to wrap your application #[clap(short, long, default_value = "sudo -E")] pub runner: String, /// libbpf directory #[clap(long, action)] pub libbpf_dir: String, /// Arguments to pass to your application #[clap(name = "args", last = true)] pub run_args: Vec<String>, } /// Build the project fn build(opts: &Options) -> Result<(), anyhow::Error> { let mut args = vec!["build"]; if opts.release { args.push("--release") } args.push("-p"); args.push("integration-test"); let status = Command::new("cargo") .args(&args) .status() .expect("failed to build userspace"); assert!(status.success()); Ok(()) } /// Build and run the project pub fn run(opts: Options) -> Result<(), anyhow::Error> { // build our ebpf program followed by our application build_ebpf(BuildOptions { target: opts.bpf_target, release: opts.release, libbpf_dir: PathBuf::from(&opts.libbpf_dir), }) .context("Error while building eBPF program")?; build(&opts).context("Error while building userspace application")?; // profile we are building (release or debug) let profile = if opts.release { "release" } else { "debug" }; let bin_path = format!("target/{profile}/integration-test"); // arguments to pass to the application let mut run_args: Vec<_> = opts.run_args.iter().map(String::as_str).collect(); // configure args let mut args: Vec<_> = opts.runner.trim().split_terminator(' ').collect(); args.push(bin_path.as_str()); args.append(&mut run_args); // spawn the command let err = Command::new(args.first().expect("No first argument")) .args(args.iter().skip(1)) .exec(); // we shouldn't get here unless the command failed to spawn Err(anyhow::Error::from(err).context(format!("Failed to run `{}`", args.join(" ")))) } <file_sep>/aya/src/programs/utils.rs //! Common functions shared between multiple eBPF program types. use std::{ffi::CStr, os::unix::io::RawFd}; use crate::{ programs::{FdLink, Link, ProgramData, ProgramError}, sys::bpf_raw_tracepoint_open, }; /// Attaches the program to a raw tracepoint. pub(crate) fn attach_raw_tracepoint<T: Link + From<FdLink>>( program_data: &mut ProgramData<T>, tp_name: Option<&CStr>, ) -> Result<T::Id, ProgramError> { let prog_fd = program_data.fd_or_err()?; let pfd = bpf_raw_tracepoint_open(tp_name, prog_fd).map_err(|(_code, io_error)| { ProgramError::SyscallError { call: "bpf_raw_tracepoint_open".to_owned(), io_error, } })? as RawFd; program_data.links.insert(FdLink::new(pfd).into()) } <file_sep>/aya-log-common/Cargo.toml [package] name = "aya-log-common" version = "0.1.13" description = "A logging library for eBPF programs." keywords = ["ebpf", "bpf", "log", "logging"] license = "MIT OR Apache-2.0" authors = ["<NAME>"] repository = "https://github.com/aya-rs/aya-log" documentation = "https://docs.rs/aya-log" edition = "2021" [features] default = [] userspace = [ "aya" ] [dependencies] aya = { path = "../aya", version = "0.11.0", optional=true } num_enum = { version = "0.5", default-features = false } [lib] path = "src/lib.rs" <file_sep>/aya/src/maps/stack.rs //! A LIFO stack. use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_kv_size, MapData, MapError}, sys::{bpf_map_lookup_and_delete_elem, bpf_map_update_elem}, Pod, }; /// A LIFO stack. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.20. /// /// # Examples /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::Stack; /// /// let mut stack = Stack::try_from(bpf.map_mut("STACK").unwrap())?; /// stack.push(42, 0)?; /// stack.push(43, 0)?; /// assert_eq!(stack.pop(0)?, 43); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_STACK")] pub struct Stack<T, V: Pod> { inner: T, _v: PhantomData<V>, } impl<T: AsRef<MapData>, V: Pod> Stack<T, V> { pub(crate) fn new(map: T) -> Result<Stack<T, V>, MapError> { let data = map.as_ref(); check_kv_size::<(), V>(data)?; let _fd = data.fd_or_err()?; Ok(Stack { inner: map, _v: PhantomData, }) } /// Returns the number of elements the stack can hold. /// /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side. pub fn capacity(&self) -> u32 { self.inner.as_ref().obj.max_entries() } } impl<T: AsMut<MapData>, V: Pod> Stack<T, V> { /// Removes the last element and returns it. /// /// # Errors /// /// Returns [`MapError::ElementNotFound`] if the stack is empty, [`MapError::SyscallError`] /// if `bpf_map_lookup_and_delete_elem` fails. pub fn pop(&mut self, flags: u64) -> Result<V, MapError> { let fd = self.inner.as_mut().fd_or_err()?; let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err( |(_, io_error)| MapError::SyscallError { call: "bpf_map_lookup_and_delete_elem".to_owned(), io_error, }, )?; value.ok_or(MapError::ElementNotFound) } /// Pushes an element on the stack. /// /// # Errors /// /// [`MapError::SyscallError`] if `bpf_map_update_elem` fails. pub fn push(&mut self, value: impl Borrow<V>, flags: u64) -> Result<(), MapError> { let fd = self.inner.as_mut().fd_or_err()?; bpf_map_update_elem(fd, None::<&u32>, value.borrow(), flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } } <file_sep>/test/integration-test-macros/src/lib.rs use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, ItemFn}; #[proc_macro_attribute] pub fn integration_test(_attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as ItemFn); let name = &item.sig.ident; let name_str = &item.sig.ident.to_string(); let expanded = quote! { #item inventory::submit!(IntegrationTest { name: concat!(module_path!(), "::", #name_str), test_fn: #name, }); }; TokenStream::from(expanded) } <file_sep>/aya-log/Cargo.toml [package] name = "aya-log" version = "0.1.13" description = "A logging library for eBPF programs." keywords = ["ebpf", "bpf", "log", "logging"] license = "MIT OR Apache-2.0" authors = ["<NAME>"] repository = "https://github.com/aya-rs/aya-log" readme = "README.md" documentation = "https://docs.rs/aya-log" edition = "2021" [dependencies] aya = { path = "../aya", version = "0.11.0", features=["async_tokio"] } aya-log-common = { path = "../aya-log-common", version = "0.1.13", features=["userspace"] } thiserror = "1" log = "0.4" bytes = "1.1" tokio = { version = "1.2.0" } [dev-dependencies] env_logger = "0.10" testing_logger = "0.1.1" [lib] path = "src/lib.rs" <file_sep>/aya/src/maps/hash_map/per_cpu_hash_map.rs //! Per-CPU hash map. use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{ check_kv_size, hash_map, IterableMap, MapData, MapError, MapIter, MapKeys, PerCpuValues, }, sys::{bpf_map_lookup_elem_per_cpu, bpf_map_update_elem_per_cpu}, Pod, }; /// Similar to [`HashMap`](crate::maps::HashMap) but each CPU holds a separate value for a given key. Tipically used to /// minimize lock contention in eBPF programs. /// /// This type can be used with eBPF maps of type `BPF_MAP_TYPE_PERCPU_HASH` and /// `BPF_MAP_TYPE_LRU_PERCPU_HASH`. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.6. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::PerCpuHashMap; /// /// const CPU_IDS: u8 = 1; /// const WAKEUPS: u8 = 2; /// /// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE").unwrap())?; /// let cpu_ids = unsafe { hm.get(&CPU_IDS, 0)? }; /// let wakeups = unsafe { hm.get(&WAKEUPS, 0)? }; /// for (cpu_id, wakeups) in cpu_ids.iter().zip(wakeups.iter()) { /// println!("cpu {} woke up {} times", cpu_id, wakeups); /// } /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_LRU_PERCPU_HASH")] #[doc(alias = "BPF_MAP_TYPE_PERCPU_HASH")] pub struct PerCpuHashMap<T, K: Pod, V: Pod> { inner: T, _k: PhantomData<K>, _v: PhantomData<V>, } impl<T: AsRef<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> { pub(crate) fn new(map: T) -> Result<PerCpuHashMap<T, K, V>, MapError> { let data = map.as_ref(); check_kv_size::<K, V>(data)?; let _ = data.fd_or_err()?; Ok(PerCpuHashMap { inner: map, _k: PhantomData, _v: PhantomData, }) } /// Returns a slice of values - one for each CPU - associated with the key. pub fn get(&self, key: &K, flags: u64) -> Result<PerCpuValues<V>, MapError> { let fd = self.inner.as_ref().fd_or_err()?; let values = bpf_map_lookup_elem_per_cpu(fd, key, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; values.ok_or(MapError::KeyNotFound) } /// An iterator visiting all key-value pairs in arbitrary order. The /// iterator item type is `Result<(K, PerCpuValues<V>), MapError>`. pub fn iter(&self) -> MapIter<'_, K, PerCpuValues<V>, Self> { MapIter::new(self) } /// An iterator visiting all keys in arbitrary order. The iterator element /// type is `Result<K, MapError>`. pub fn keys(&self) -> MapKeys<'_, K> { MapKeys::new(self.inner.as_ref()) } } impl<T: AsMut<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> { /// Inserts a slice of values - one for each CPU - for the given key. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::{PerCpuHashMap, PerCpuValues}; /// use aya::util::nr_cpus; /// /// const RETRIES: u8 = 1; /// /// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE").unwrap())?; /// hm.insert( /// RETRIES, /// PerCpuValues::try_from(vec![3u32; nr_cpus()?])?, /// 0, /// )?; /// # Ok::<(), Error>(()) /// ``` pub fn insert( &mut self, key: impl Borrow<K>, values: PerCpuValues<V>, flags: u64, ) -> Result<(), MapError> { let fd = self.inner.as_mut().fd_or_err()?; bpf_map_update_elem_per_cpu(fd, key.borrow(), &values, flags).map_err( |(_, io_error)| MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, }, )?; Ok(()) } /// Removes a key from the map. pub fn remove(&mut self, key: &K) -> Result<(), MapError> { hash_map::remove(self.inner.as_mut(), key) } } impl<T: AsRef<MapData>, K: Pod, V: Pod> IterableMap<K, PerCpuValues<V>> for PerCpuHashMap<T, K, V> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, key: &K) -> Result<PerCpuValues<V>, MapError> { PerCpuHashMap::get(self, key, 0) } } <file_sep>/aya-log-ebpf-macros/src/lib.rs use proc_macro::TokenStream; use syn::parse_macro_input; mod expand; #[proc_macro] pub fn log(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::log(args, None) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn error(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::error(args) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn warn(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::warn(args) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn info(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::info(args) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn debug(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::debug(args) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn trace(args: TokenStream) -> TokenStream { let args = parse_macro_input!(args as expand::LogArgs); expand::trace(args) .unwrap_or_else(|err| err.to_compile_error()) .into() } <file_sep>/aya/src/programs/cgroup_sysctl.rs //! Cgroup sysctl programs. use std::{ hash::Hash, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ generated::{bpf_attach_type::BPF_CGROUP_SYSCTL, bpf_prog_type::BPF_PROG_TYPE_CGROUP_SYSCTL}, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program used to watch for sysctl changes. /// /// [`CgroupSysctl`] programs can be attached to a cgroup and will be called every /// time a process inside that cgroup tries to read from or write to a sysctl knob in proc. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.2. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::CgroupSysctl; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let program: &mut CgroupSysctl = bpf.program_mut("cgroup_sysctl").unwrap().try_into()?; /// program.load()?; /// program.attach(file)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SYSCTL")] pub struct CgroupSysctl { pub(crate) data: ProgramData<CgroupSysctlLink>, } impl CgroupSysctl { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_CGROUP_SYSCTL, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSysctl::detach]. pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<CgroupSysctlLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupSysctlLink::new(CgroupSysctlLinkInner::Fd( FdLink::new(link_fd), ))) } else { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data .links .insert(CgroupSysctlLink::new(CgroupSysctlLinkInner::ProgAttach( ProgAttachLink::new(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL), ))) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: CgroupSysctlLinkId, ) -> Result<CgroupSysctlLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [CgroupSysctl::attach]. pub fn detach(&mut self, link_id: CgroupSysctlLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupSysctlLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupSysctlLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupSysctlLinkInner { type Id = CgroupSysctlLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupSysctlLinkInner::Fd(fd) => CgroupSysctlLinkIdInner::Fd(fd.id()), CgroupSysctlLinkInner::ProgAttach(p) => CgroupSysctlLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupSysctlLinkInner::Fd(fd) => fd.detach(), CgroupSysctlLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupSysctl] programs. CgroupSysctlLink, /// The type returned by [CgroupSysctl::attach]. Can be passed to [CgroupSysctl::detach]. CgroupSysctlLinkId, CgroupSysctlLinkInner, CgroupSysctlLinkIdInner ); <file_sep>/test/README.md Aya Integration Tests ===================== The aya integration test suite is a set of tests to ensure that common usage behaviours work on real Linux distros ## Prerequisites ### Linux To run locally all you need is: 1. Rust nightly 2. `libelf` 3. A checkout of [libbpf](https://github.com/libbpf/libbpf) 4. `cargo install bpf-linker` 5. `bpftool` ### Other OSs 1. A POSIX shell 1. A checkout of [libbpf](https://github.com/libbpf/libbpf) 1. `rustup target add x86_64-unknown-linux-musl` 1. `cargo install bpf-linker` 1. Install `qemu` and `cloud-init-utils` package - or any package that provides `cloud-localds` ## Usage From the root of this repository: ### Native ``` cargo xtask integration-test --libbpf-dir /path/to/libbpf ``` ### Virtualized ``` ./test/run.sh /path/to/libbpf ``` ### Writing a test Tests should follow these guidelines: - Rust eBPF code should live in `integration-ebpf/${NAME}.rs` and included in `integration-ebpf/Cargo.toml` - C eBPF code should live in `integration-test/src/bpf/${NAME}.bpf.c`. It's automatically compiled and made available as `${OUT_DIR}/${NAME}.bpf.o`. - Any bytecode should be included in the integration test binary using `include_bytes_aligned!` - Tests should be added to `integration-test/src/test` - You may add a new module, or use an existing one - Integration tests must use the `#[integration_test]` macro to be included in the build - Test functions should return `anyhow::Result<()>` since this allows the use of `?` to return errors. - You may either `panic!` when an assertion fails or `bail!`. The former is preferred since the stack trace will point directly to the failed line. <file_sep>/test/integration-test-macros/Cargo.toml [package] name = "integration-test-macros" version = "0.1.0" edition = "2021" publish = false [dependencies] quote = "1" syn = {version = "1.0", features = ["full"]} [lib] proc-macro = true <file_sep>/.github/prep-changelog-config.sh #!/bin/bash # Remove "refs/tags/" tag="${GITHUB_REF##*/}" # Extract crate name crate=$(echo $tag | sed 's/-v[0-9].*//g') # Semver portion follows after the ${crate}-v tagPattern="${crate}-v(.+)" echo ::group::Configuring changelog generator jq '.tag_resolver.filter.pattern="'$tagPattern'" | .tag_resolver.transformer.pattern="'$tagPattern'" | .categories[].labels += ["'$crate'"]' \ .github/changelog-base.json | tee .github/changelog-config.json echo ::endgroup::<file_sep>/xtask/Cargo.toml [package] name = "xtask" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2021" [dependencies] aya-tool = { path = "../aya-tool" } clap = { version = "4", features = ["derive"] } anyhow = "1" syn = "1" quote = "1" proc-macro2 = "1" indoc = "1.0" lazy_static = "1" serde_json = "1" <file_sep>/aya/src/obj/btf/info.rs use std::collections::HashMap; use bytes::BufMut; use object::Endianness; use crate::{ generated::{bpf_func_info, bpf_line_info}, obj::relocation::INS_SIZE, util::bytes_of, }; /* The func_info subsection layout: * record size for struct bpf_func_info in the func_info subsection * struct btf_sec_func_info for section #1 * a list of bpf_func_info records for section #1 * where struct bpf_func_info mimics one in include/uapi/linux/bpf.h * but may not be identical * struct btf_sec_func_info for section #2 * a list of bpf_func_info records for section #2 * ...... */ #[derive(Debug, Clone, Default)] pub(crate) struct FuncSecInfo { pub _sec_name_offset: u32, pub num_info: u32, pub func_info: Vec<bpf_func_info>, } impl FuncSecInfo { pub(crate) fn parse( sec_name_offset: u32, num_info: u32, rec_size: usize, func_info_data: &[u8], endianness: Endianness, ) -> FuncSecInfo { let func_info = func_info_data .chunks(rec_size) .map(|data| { let read_u32 = if endianness == Endianness::Little { u32::from_le_bytes } else { u32::from_be_bytes }; let mut offset = 0; // ELF instruction offsets are in bytes // Kernel instruction offsets are in instructions units // We can convert by dividing the length in bytes by INS_SIZE let insn_off = read_u32(data[offset..offset + 4].try_into().unwrap()) / INS_SIZE as u32; offset += 4; let type_id = read_u32(data[offset..offset + 4].try_into().unwrap()); bpf_func_info { insn_off, type_id } }) .collect(); FuncSecInfo { _sec_name_offset: sec_name_offset, num_info, func_info, } } pub(crate) fn func_info_bytes(&self) -> Vec<u8> { let mut buf = vec![]; for l in &self.func_info { // Safety: bpf_func_info is POD buf.put(unsafe { bytes_of::<bpf_func_info>(l) }) } buf } pub(crate) fn len(&self) -> usize { self.func_info.len() } } #[derive(Debug, Clone)] pub(crate) struct FuncInfo { pub data: HashMap<String, FuncSecInfo>, } impl FuncInfo { pub(crate) fn new() -> FuncInfo { FuncInfo { data: HashMap::new(), } } pub(crate) fn get(&self, name: &str) -> FuncSecInfo { match self.data.get(name) { Some(d) => d.clone(), None => FuncSecInfo::default(), } } } #[derive(Debug, Clone, Default)] pub(crate) struct LineSecInfo { // each line info section has a header pub _sec_name_offset: u32, pub num_info: u32, // followed by one or more bpf_line_info structs pub line_info: Vec<bpf_line_info>, } impl LineSecInfo { pub(crate) fn parse( sec_name_offset: u32, num_info: u32, rec_size: usize, func_info_data: &[u8], endianness: Endianness, ) -> LineSecInfo { let line_info = func_info_data .chunks(rec_size) .map(|data| { let read_u32 = if endianness == Endianness::Little { u32::from_le_bytes } else { u32::from_be_bytes }; let mut offset = 0; // ELF instruction offsets are in bytes // Kernel instruction offsets are in instructions units // We can convert by dividing the length in bytes by INS_SIZE let insn_off = read_u32(data[offset..offset + 4].try_into().unwrap()) / INS_SIZE as u32; offset += 4; let file_name_off = read_u32(data[offset..offset + 4].try_into().unwrap()); offset += 4; let line_off = read_u32(data[offset..offset + 4].try_into().unwrap()); offset += 4; let line_col = read_u32(data[offset..offset + 4].try_into().unwrap()); bpf_line_info { insn_off, file_name_off, line_off, line_col, } }) .collect(); LineSecInfo { _sec_name_offset: sec_name_offset, num_info, line_info, } } pub(crate) fn line_info_bytes(&self) -> Vec<u8> { let mut buf = vec![]; for l in &self.line_info { // Safety: bpf_func_info is POD buf.put(unsafe { bytes_of::<bpf_line_info>(l) }) } buf } pub(crate) fn len(&self) -> usize { self.line_info.len() } } #[derive(Debug, Clone)] pub(crate) struct LineInfo { pub data: HashMap<String, LineSecInfo>, } impl LineInfo { pub(crate) fn new() -> LineInfo { LineInfo { data: HashMap::new(), } } pub(crate) fn get(&self, name: &str) -> LineSecInfo { match self.data.get(name) { Some(d) => d.clone(), None => LineSecInfo::default(), } } } <file_sep>/bpf/aya-bpf/src/helpers.rs //! This module contains kernel helper functions that may be exposed to specific BPF //! program types. These helpers can be used to perform common tasks, query and operate on //! data exposed by the kernel, and perform some operations that would normally be denied //! by the BPF verifier. //! //! Here, we provide some higher-level wrappers around the underlying kernel helpers, but //! also expose bindings to the underlying helpers as a fall-back in case of a missing //! implementation. use core::mem::{self, MaybeUninit}; pub use aya_bpf_bindings::helpers as gen; #[doc(hidden)] pub use gen::*; use crate::cty::{c_char, c_long, c_void}; /// Read bytes stored at `src` and store them as a `T`. /// /// Generally speaking, the more specific [`bpf_probe_read_user`] and /// [`bpf_probe_read_kernel`] should be preferred over this function. /// /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const c_int = 0 as _; /// let my_int: c_int = unsafe { bpf_probe_read(kernel_ptr)? }; /// /// // Do something with my_int /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read<T>(src: *const T) -> Result<T, c_long> { let mut v: MaybeUninit<T> = MaybeUninit::uninit(); let ret = gen::bpf_probe_read( v.as_mut_ptr() as *mut c_void, mem::size_of::<T>() as u32, src as *const c_void, ); if ret == 0 { Ok(v.assume_init()) } else { Err(ret) } } /// Read bytes from the pointer `src` into the provided destination buffer. /// /// Generally speaking, the more specific [`bpf_probe_read_user_buf`] and /// [`bpf_probe_read_kernel_buf`] should be preferred over this function. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_buf}; /// # fn try_test() -> Result<(), c_long> { /// # let ptr: *const u8 = 0 as _; /// let mut buf = [0u8; 16]; /// unsafe { bpf_probe_read_buf(ptr, &mut buf)? }; /// /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> { let ret = gen::bpf_probe_read( dst.as_mut_ptr() as *mut c_void, dst.len() as u32, src as *const c_void, ); if ret == 0 { Ok(()) } else { Err(ret) } } /// Read bytes stored at the _user space_ pointer `src` and store them as a `T`. /// /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user}; /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const c_int = 0 as _; /// let my_int: c_int = unsafe { bpf_probe_read_user(user_ptr)? }; /// /// // Do something with my_int /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read_user<T>(src: *const T) -> Result<T, c_long> { let mut v: MaybeUninit<T> = MaybeUninit::uninit(); let ret = gen::bpf_probe_read_user( v.as_mut_ptr() as *mut c_void, mem::size_of::<T>() as u32, src as *const c_void, ); if ret == 0 { Ok(v.assume_init()) } else { Err(ret) } } /// Read bytes from the _user space_ pointer `src` into the provided destination /// buffer. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user_buf}; /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const u8 = 0 as _; /// let mut buf = [0u8; 16]; /// unsafe { bpf_probe_read_user_buf(user_ptr, &mut buf)? }; /// /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read_user_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> { let ret = gen::bpf_probe_read_user( dst.as_mut_ptr() as *mut c_void, dst.len() as u32, src as *const c_void, ); if ret == 0 { Ok(()) } else { Err(ret) } } /// Read bytes stored at the _kernel space_ pointer `src` and store them as a `T`. /// /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the kernel space address /// `src`. See `bpf_probe_read_user` for reading user space memory. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const c_int = 0 as _; /// let my_int: c_int = unsafe { bpf_probe_read_kernel(kernel_ptr)? }; /// /// // Do something with my_int /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read_kernel<T>(src: *const T) -> Result<T, c_long> { let mut v: MaybeUninit<T> = MaybeUninit::uninit(); let ret = gen::bpf_probe_read_kernel( v.as_mut_ptr() as *mut c_void, mem::size_of::<T>() as u32, src as *const c_void, ); if ret == 0 { Ok(v.assume_init()) } else { Err(ret) } } /// Read bytes from the _kernel space_ pointer `src` into the provided destination /// buffer. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel_buf}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// let mut buf = [0u8; 16]; /// unsafe { bpf_probe_read_kernel_buf(kernel_ptr, &mut buf)? }; /// /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub unsafe fn bpf_probe_read_kernel_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> { let ret = gen::bpf_probe_read_kernel( dst.as_mut_ptr() as *mut c_void, dst.len() as u32, src as *const c_void, ); if ret == 0 { Ok(()) } else { Err(ret) } } /// Read a null-terminated string stored at `src` into `dest`. /// /// Generally speaking, the more specific [`bpf_probe_read_user_str`] and /// [`bpf_probe_read_kernel_str`] should be preferred over this function. /// /// In case the length of `dest` is smaller then the length of `src`, the read bytes will /// be truncated to the size of `dest`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_str}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// let mut my_str = [0u8; 16]; /// let num_read = unsafe { bpf_probe_read_str(kernel_ptr, &mut my_str)? }; /// /// // Do something with num_read and my_str /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns Err(-1). #[deprecated( note = "Use `bpf_probe_read_user_str_bytes` or `bpf_probe_read_kernel_str_bytes` instead" )] #[inline] pub unsafe fn bpf_probe_read_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> { let len = gen::bpf_probe_read_str( dest.as_mut_ptr() as *mut c_void, dest.len() as u32, src as *const c_void, ); if len < 0 { return Err(-1); } let mut len = len as usize; if len > dest.len() { // this can never happen, it's needed to tell the verifier that len is // bounded len = dest.len(); } Ok(len) } /// Read a null-terminated string from _user space_ stored at `src` into `dest`. /// /// In case the length of `dest` is smaller then the length of `src`, the read bytes will /// be truncated to the size of `dest`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str}; /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const u8 = 0 as _; /// let mut my_str = [0u8; 16]; /// let num_read = unsafe { bpf_probe_read_user_str(user_ptr, &mut my_str)? }; /// /// // Do something with num_read and my_str /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns Err(-1). #[deprecated(note = "Use `bpf_probe_read_user_str_bytes` instead")] #[inline] pub unsafe fn bpf_probe_read_user_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> { let len = gen::bpf_probe_read_user_str( dest.as_mut_ptr() as *mut c_void, dest.len() as u32, src as *const c_void, ); if len < 0 { return Err(-1); } let mut len = len as usize; if len > dest.len() { // this can never happen, it's needed to tell the verifier that len is // bounded len = dest.len(); } Ok(len) } /// Returns a byte slice read from _user space_ address `src`. /// /// Reads at most `dest.len()` bytes from the `src` address, truncating if the /// length of the source string is larger than `dest`. On success, the /// destination buffer is always null terminated, and the returned slice /// includes the bytes up to and not including NULL. /// /// # Examples /// /// With an array allocated on the stack (not recommended for bigger strings, /// eBPF stack limit is 512 bytes): /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes}; /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const u8 = 0 as _; /// let mut buf = [0u8; 16]; /// let my_str_bytes = unsafe { bpf_probe_read_user_str_bytes(user_ptr, &mut buf)? }; /// /// // Do something with my_str_bytes /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// With a `PerCpuArray` (with size defined by us): /// /// ```no_run /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes}; /// use aya_bpf::{macros::map, maps::PerCpuArray}; /// /// #[repr(C)] /// pub struct Buf { /// pub buf: [u8; 4096], /// } /// /// #[map] /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const u8 = 0 as _; /// let buf = unsafe { /// let ptr = BUF.get_ptr_mut(0).ok_or(0)?; /// &mut *ptr /// }; /// let my_str_bytes = unsafe { bpf_probe_read_user_str_bytes(user_ptr, &mut buf.buf)? }; /// /// // Do something with my_str_bytes /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// You can also convert the resulted bytes slice into `&str` using /// [core::str::from_utf8_unchecked]: /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes}; /// # use aya_bpf::{macros::map, maps::PerCpuArray}; /// # #[repr(C)] /// # pub struct Buf { /// # pub buf: [u8; 4096], /// # } /// # #[map] /// # pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// # fn try_test() -> Result<(), c_long> { /// # let user_ptr: *const u8 = 0 as _; /// # let buf = unsafe { /// # let ptr = BUF.get_ptr_mut(0).ok_or(0)?; /// # &mut *ptr /// # }; /// let my_str = unsafe { /// core::str::from_utf8_unchecked(bpf_probe_read_user_str_bytes(user_ptr, &mut buf.buf)?) /// }; /// /// // Do something with my_str /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns Err(-1). #[inline] pub unsafe fn bpf_probe_read_user_str_bytes( src: *const u8, dest: &mut [u8], ) -> Result<&[u8], c_long> { let len = gen::bpf_probe_read_user_str( dest.as_mut_ptr() as *mut c_void, dest.len() as u32, src as *const c_void, ); if len < 0 { return Err(-1); } let len = len as usize; if len >= dest.len() { // this can never happen, it's needed to tell the verifier that len is // bounded return Err(-1); } Ok(&dest[..len]) } /// Read a null-terminated string from _kernel space_ stored at `src` into `dest`. /// /// In case the length of `dest` is smaller then the length of `src`, the read bytes will /// be truncated to the size of `dest`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// let mut my_str = [0u8; 16]; /// let num_read = unsafe { bpf_probe_read_kernel_str(kernel_ptr, &mut my_str)? }; /// /// // Do something with num_read and my_str /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns Err(-1). #[deprecated(note = "Use bpf_probe_read_kernel_str_bytes instead")] #[inline] pub unsafe fn bpf_probe_read_kernel_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> { let len = gen::bpf_probe_read_kernel_str( dest.as_mut_ptr() as *mut c_void, dest.len() as u32, src as *const c_void, ); if len < 0 { return Err(-1); } let mut len = len as usize; if len > dest.len() { // this can never happen, it's needed to tell the verifier that len is // bounded len = dest.len(); } Ok(len) } /// Returns a byte slice read from _kernel space_ address `src`. /// /// Reads at most `dest.len()` bytes from the `src` address, truncating if the /// length of the source string is larger than `dest`. On success, the /// destination buffer is always null terminated, and the returned slice /// includes the bytes up to and not including NULL. /// /// # Examples /// /// With an array allocated on the stack (not recommended for bigger strings, /// eBPF stack limit is 512 bytes): /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes}; /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// let mut buf = [0u8; 16]; /// let my_str_bytes = unsafe { bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf)? }; /// /// // Do something with my_str_bytes /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// With a `PerCpuArray` (with size defined by us): /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes}; /// use aya_bpf::{macros::map, maps::PerCpuArray}; /// /// #[repr(C)] /// pub struct Buf { /// pub buf: [u8; 4096], /// } /// /// #[map] /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// let buf = unsafe { /// let ptr = BUF.get_ptr_mut(0).ok_or(0)?; /// &mut *ptr /// }; /// let my_str_bytes = unsafe { bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf.buf)? }; /// /// // Do something with my_str_bytes /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// You can also convert the resulted bytes slice into `&str` using /// [core::str::from_utf8_unchecked]: /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes}; /// # use aya_bpf::{macros::map, maps::PerCpuArray}; /// # #[repr(C)] /// # pub struct Buf { /// # pub buf: [u8; 4096], /// # } /// # #[map] /// # pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// # fn try_test() -> Result<(), c_long> { /// # let kernel_ptr: *const u8 = 0 as _; /// # let buf = unsafe { /// # let ptr = BUF.get_ptr_mut(0).ok_or(0)?; /// # &mut *ptr /// # }; /// let my_str = unsafe { /// core::str::from_utf8_unchecked(bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf.buf)?) /// }; /// /// // Do something with my_str /// # Ok::<(), c_long>(()) /// # } /// ``` /// /// # Errors /// /// On failure, this function returns Err(-1). #[inline] pub unsafe fn bpf_probe_read_kernel_str_bytes( src: *const u8, dest: &mut [u8], ) -> Result<&[u8], c_long> { let len = gen::bpf_probe_read_kernel_str( dest.as_mut_ptr() as *mut c_void, dest.len() as u32, src as *const c_void, ); if len < 0 { return Err(-1); } let len = len as usize; if len >= dest.len() { // this can never happen, it's needed to tell the verifier that len is // bounded return Err(-1); } Ok(&dest[..len]) } /// Write bytes to the _user space_ pointer `src` and store them as a `T`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::{ /// # cty::{c_int, c_long}, /// # helpers::bpf_probe_write_user, /// # programs::ProbeContext, /// # }; /// fn try_test(ctx: ProbeContext) -> Result<(), c_long> { /// let retp: *mut c_int = ctx.arg(0).ok_or(1)?; /// let val: i32 = 1; /// // Write the value to the userspace pointer. /// unsafe { bpf_probe_write_user(retp, &val as *const i32)? }; /// /// Ok::<(), c_long>(()) /// } /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[allow(clippy::fn_to_numeric_cast_with_truncation)] #[inline] pub unsafe fn bpf_probe_write_user<T>(dst: *mut T, src: *const T) -> Result<(), c_long> { let ret = gen::bpf_probe_write_user( dst as *mut c_void, src as *const c_void, mem::size_of::<T>() as u32, ); if ret == 0 { Ok(()) } else { Err(ret) } } /// Read the `comm` field associated with the current task struct /// as a `[u8; 16]`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::helpers::bpf_get_current_comm; /// let comm = bpf_get_current_comm(); /// /// // Do something with comm /// ``` /// /// # Errors /// /// On failure, this function returns a negative value wrapped in an `Err`. #[inline] pub fn bpf_get_current_comm() -> Result<[u8; 16], c_long> { let mut comm: [u8; 16usize] = [0; 16]; let ret = unsafe { gen::bpf_get_current_comm(&mut comm as *mut _ as *mut c_void, 16u32) }; if ret == 0 { Ok(comm) } else { Err(ret) } } /// Read the process id and thread group id associated with the current task struct as /// a `u64`. /// /// In the return value, the upper 32 bits are the `tgid`, and the lower 32 bits are the /// `pid`. That is, the returned value is equal to: `(tgid << 32) | pid`. A caller may /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit /// shift and casting to a `u32`. /// /// Note that the naming conventions used in the kernel differ from user space. From the /// perspective of user space, `pid` may be thought of as the thread id, and `tgid` may be /// thought of as the process id. For single-threaded processes, these values are /// typically the same. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::helpers::bpf_get_current_pid_tgid; /// let tgid = (bpf_get_current_pid_tgid() >> 32) as u32; /// let pid = bpf_get_current_pid_tgid() as u32; /// /// // Do something with pid and tgid /// ``` #[inline] pub fn bpf_get_current_pid_tgid() -> u64 { unsafe { gen::bpf_get_current_pid_tgid() } } /// Read the user id and group id associated with the current task struct as /// a `u64`. /// /// In the return value, the upper 32 bits are the `gid`, and the lower 32 bits are the /// `uid`. That is, the returned value is equal to: `(gid << 32) | uid`. A caller may /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit /// shift and casting to a `u32`. /// /// # Examples /// /// ```no_run /// # #![allow(dead_code)] /// # use aya_bpf::helpers::bpf_get_current_uid_gid; /// let gid = (bpf_get_current_uid_gid() >> 32) as u32; /// let uid = bpf_get_current_uid_gid() as u32; /// /// // Do something with uid and gid /// ``` #[inline] pub fn bpf_get_current_uid_gid() -> u64 { unsafe { gen::bpf_get_current_uid_gid() } } /// Prints a debug message to the BPF debugging pipe. /// /// The [format string syntax][fmt] is the same as that of the `printk` kernel /// function. It is passed in as a fixed-size byte array (`&[u8; N]`), so you /// will have to prefix your string literal with a `b`. A terminating zero byte /// is appended automatically. /// /// The macro can read from arbitrary pointers, so it must be used in an `unsafe` /// scope in order to compile. /// /// Invocations with less than 4 arguments call the `bpf_trace_printk` helper, /// otherwise the `bpf_trace_vprintk` function is called. The latter function /// requires a kernel version >= 5.16 whereas the former has been around since /// the dawn of eBPF. The return value of the BPF helper is also returned from /// this macro. /// /// Messages can be read by executing the following command in a second terminal: /// /// ```bash /// sudo cat /sys/kernel/debug/tracing/trace_pipe /// ``` /// /// If no messages are printed when calling [`bpf_printk!`] after executing the /// above command, it is possible that tracing must first be enabled by running: /// /// ```bash /// echo 1 | sudo tee /sys/kernel/debug/tracing/tracing_on /// ``` /// /// # Example /// /// ```no_run /// # use aya_bpf::helpers::bpf_printk; /// unsafe { /// bpf_printk!(b"hi there! dec: %d, hex: 0x%08X", 42, 0x1234); /// } /// ``` /// /// [fmt]: https://www.kernel.org/doc/html/latest/core-api/printk-formats.html#printk-specifiers #[macro_export] macro_rules! bpf_printk { ($fmt:literal $(,)? $($arg:expr),* $(,)?) => {{ use $crate::helpers::PrintkArg; const FMT: [u8; { $fmt.len() + 1 }] = $crate::helpers::zero_pad_array::< { $fmt.len() }, { $fmt.len() + 1 }>(*$fmt); let data = [$(PrintkArg::from($arg)),*]; $crate::helpers::bpf_printk_impl(&FMT, &data) }}; } // Macros are always exported from the crate root. Also export it from `helpers`. #[doc(inline)] pub use bpf_printk; /// Argument ready to be passed to `printk` BPF helper. #[repr(transparent)] #[derive(Copy, Clone)] pub struct PrintkArg(u64); impl PrintkArg { /// Manually construct a `printk` BPF helper argument. #[inline] pub fn from_raw(x: u64) -> Self { Self(x) } } macro_rules! impl_integer_promotion { ($($ty:ty : via $via:ty),* $(,)?) => {$( /// Create `printk` arguments from integer types. impl From<$ty> for PrintkArg { #[inline] fn from(x: $ty) -> PrintkArg { PrintkArg(x as $via as u64) } } )*} } impl_integer_promotion!( char: via u64, u8: via u64, u16: via u64, u32: via u64, u64: via u64, usize: via u64, i8: via i64, i16: via i64, i32: via i64, i64: via i64, isize: via i64, ); /// Construct `printk` BPF helper arguments from constant pointers. impl<T> From<*const T> for PrintkArg { #[inline] fn from(x: *const T) -> Self { PrintkArg(x as usize as u64) } } /// Construct `printk` BPF helper arguments from mutable pointers. impl<T> From<*mut T> for PrintkArg { #[inline] fn from(x: *mut T) -> Self { PrintkArg(x as usize as u64) } } /// Expands the given byte array to `DST_LEN`, right-padding it with zeros. If /// `DST_LEN` is smaller than `SRC_LEN`, the array is instead truncated. /// /// This function serves as a helper for the [`bpf_printk!`] macro. #[doc(hidden)] pub const fn zero_pad_array<const SRC_LEN: usize, const DST_LEN: usize>( src: [u8; SRC_LEN], ) -> [u8; DST_LEN] { let mut out: [u8; DST_LEN] = [0u8; DST_LEN]; // The `min` function is not `const`. Hand-roll it. let mut i = if DST_LEN > SRC_LEN { SRC_LEN } else { DST_LEN }; while i > 0 { i -= 1; out[i] = src[i]; } out } /// Internal helper function for the [`bpf_printk!`] macro. /// /// The BPF helpers require the length for both the format string as well as /// the argument array to be of constant size to pass the verifier. Const /// generics are used to represent this requirement in Rust. #[inline] #[doc(hidden)] pub unsafe fn bpf_printk_impl<const FMT_LEN: usize, const NUM_ARGS: usize>( fmt: &[u8; FMT_LEN], args: &[PrintkArg; NUM_ARGS], ) -> i64 { // This function can't be wrapped in `helpers.rs` because it has variadic // arguments. We also can't turn the definitions in `helpers.rs` into // `const`s because MIRI believes casting arbitrary integers to function // pointers to be an error. let printk: unsafe extern "C" fn(fmt: *const c_char, fmt_size: u32, ...) -> c_long = mem::transmute(6usize); let fmt_ptr = fmt.as_ptr() as *const c_char; let fmt_size = fmt.len() as u32; match NUM_ARGS { 0 => printk(fmt_ptr, fmt_size), 1 => printk(fmt_ptr, fmt_size, args[0]), 2 => printk(fmt_ptr, fmt_size, args[0], args[1]), 3 => printk(fmt_ptr, fmt_size, args[0], args[1], args[2]), _ => gen::bpf_trace_vprintk(fmt_ptr, fmt_size, args.as_ptr() as _, (NUM_ARGS * 8) as _), } } <file_sep>/aya/src/programs/perf_event.rs //! Perf event programs. pub use crate::generated::{ perf_hw_cache_id, perf_hw_cache_op_id, perf_hw_cache_op_result_id, perf_hw_id, perf_sw_ids, }; use crate::{ generated::{ bpf_prog_type::BPF_PROG_TYPE_PERF_EVENT, perf_type_id::{ PERF_TYPE_BREAKPOINT, PERF_TYPE_HARDWARE, PERF_TYPE_HW_CACHE, PERF_TYPE_RAW, PERF_TYPE_SOFTWARE, PERF_TYPE_TRACEPOINT, }, }, programs::{ load_program, perf_attach, perf_attach::{PerfLink, PerfLinkId}, ProgramData, ProgramError, }, sys::perf_event_open, }; /// The type of perf event #[repr(u32)] #[derive(Debug, Clone)] pub enum PerfTypeId { /// PERF_TYPE_HARDWARE Hardware = PERF_TYPE_HARDWARE as u32, /// PERF_TYPE_SOFTWARE Software = PERF_TYPE_SOFTWARE as u32, /// PERF_TYPE_TRACEPOINT TracePoint = PERF_TYPE_TRACEPOINT as u32, /// PERF_TYPE_HW_CACHE HwCache = PERF_TYPE_HW_CACHE as u32, /// PERF_TYPE_RAW Raw = PERF_TYPE_RAW as u32, /// PERF_TYPE_BREAKPOINT Breakpoint = PERF_TYPE_BREAKPOINT as u32, } /// Sample Policy #[derive(Debug, Clone)] pub enum SamplePolicy { /// Period Period(u64), /// Frequency Frequency(u64), } /// The scope of a PerfEvent #[derive(Debug, Clone)] #[allow(clippy::enum_variant_names)] pub enum PerfEventScope { /// Calling process, any cpu CallingProcessAnyCpu, /// calling process, one cpu CallingProcessOneCpu { /// cpu id cpu: u32, }, /// one process, any cpu OneProcessAnyCpu { /// process id pid: u32, }, /// one process, one cpu OneProcessOneCpu { /// cpu id cpu: u32, /// process id pid: u32, }, /// all processes, one cpu AllProcessesOneCpu { /// cpu id cpu: u32, }, } /// A program that can be attached at a perf event. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.9. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::util::online_cpus; /// use aya::programs::perf_event::{ /// perf_sw_ids::PERF_COUNT_SW_CPU_CLOCK, PerfEvent, PerfEventScope, PerfTypeId, SamplePolicy, /// }; /// /// let prog: &mut PerfEvent = bpf.program_mut("observe_cpu_clock").unwrap().try_into()?; /// prog.load()?; /// /// for cpu in online_cpus()? { /// prog.attach( /// PerfTypeId::Software, /// PERF_COUNT_SW_CPU_CLOCK as u64, /// PerfEventScope::AllProcessesOneCpu { cpu }, /// SamplePolicy::Period(1000000), /// )?; /// } /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_PERF_EVENT")] pub struct PerfEvent { pub(crate) data: ProgramData<PerfLink>, } impl PerfEvent { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_PERF_EVENT, &mut self.data) } /// Attaches to the given perf event. /// /// The possible values and encoding of the `config` argument depends on the /// `perf_type`. See `perf_sw_ids`, `perf_hw_id`, `perf_hw_cache_id`, /// `perf_hw_cache_op_id` and `perf_hw_cache_op_result_id`. /// /// The returned value can be used to detach, see [PerfEvent::detach]. pub fn attach( &mut self, perf_type: PerfTypeId, config: u64, scope: PerfEventScope, sample_policy: SamplePolicy, ) -> Result<PerfLinkId, ProgramError> { let (sample_period, sample_frequency) = match sample_policy { SamplePolicy::Period(period) => (period, None), SamplePolicy::Frequency(frequency) => (0, Some(frequency)), }; let (pid, cpu) = match scope { PerfEventScope::CallingProcessAnyCpu => (0, -1), PerfEventScope::CallingProcessOneCpu { cpu } => (0, cpu as i32), PerfEventScope::OneProcessAnyCpu { pid } => (pid as i32, -1), PerfEventScope::OneProcessOneCpu { cpu, pid } => (pid as i32, cpu as i32), PerfEventScope::AllProcessesOneCpu { cpu } => (-1, cpu as i32), }; let fd = perf_event_open( perf_type as u32, config, pid, cpu, sample_period, sample_frequency, false, 0, ) .map_err(|(_code, io_error)| ProgramError::SyscallError { call: "perf_event_open".to_owned(), io_error, })? as i32; perf_attach(&mut self.data, fd) } /// Detaches the program. /// /// See [PerfEvent::attach]. pub fn detach(&mut self, link_id: PerfLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: PerfLinkId) -> Result<PerfLink, ProgramError> { self.data.take_link(link_id) } } <file_sep>/aya/src/maps/sock/sock_hash.rs use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, os::unix::io::{AsRawFd, RawFd}, }; use crate::{ maps::{ check_kv_size, hash_map, sock::SockMapFd, IterableMap, MapData, MapError, MapIter, MapKeys, }, sys::bpf_map_lookup_elem, Pod, }; /// A hash map of TCP or UDP sockets. /// /// A `SockHash` is used to store TCP or UDP sockets. eBPF programs can then be /// attached to the map to inspect, filter or redirect network buffers on those /// sockets. /// /// A `SockHash` can also be used to redirect packets to sockets contained by the /// map using `bpf_redirect_map()`, `bpf_sk_redirect_hash()` etc. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.18. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::io::Write; /// use std::net::TcpStream; /// use std::os::unix::io::AsRawFd; /// use aya::maps::SockHash; /// use aya::programs::SkMsg; /// /// let mut intercept_egress = SockHash::<_, u32>::try_from(bpf.map("INTERCEPT_EGRESS").unwrap())?; /// let map_fd = intercept_egress.fd()?; /// /// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; /// prog.load()?; /// prog.attach(map_fd)?; /// /// let mut client = TcpStream::connect("127.0.0.1:1234")?; /// let mut intercept_egress = SockHash::try_from(bpf.map_mut("INTERCEPT_EGRESS").unwrap())?; /// /// intercept_egress.insert(1234, client.as_raw_fd(), 0)?; /// /// // the write will be intercepted /// client.write_all(b"foo")?; /// # Ok::<(), Error>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_SOCKHASH")] pub struct SockHash<T, K> { inner: T, _k: PhantomData<K>, } impl<T: AsRef<MapData>, K: Pod> SockHash<T, K> { pub(crate) fn new(map: T) -> Result<SockHash<T, K>, MapError> { let data = map.as_ref(); check_kv_size::<K, u32>(data)?; let _ = data.fd_or_err()?; Ok(SockHash { inner: map, _k: PhantomData, }) } /// Returns the fd of the socket stored at the given key. pub fn get(&self, key: &K, flags: u64) -> Result<RawFd, MapError> { let fd = self.inner.as_ref().fd_or_err()?; let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; value.ok_or(MapError::KeyNotFound) } /// An iterator visiting all key-value pairs in arbitrary order. The /// iterator item type is `Result<(K, V), MapError>`. pub fn iter(&self) -> MapIter<'_, K, RawFd, Self> { MapIter::new(self) } /// An iterator visiting all keys in arbitrary order. The iterator element /// type is `Result<K, MapError>`. pub fn keys(&self) -> MapKeys<'_, K> { MapKeys::new(self.inner.as_ref()) } /// Returns the map's file descriptor. /// /// The returned file descriptor can be used to attach programs that work with /// socket maps, like [`SkMsg`](crate::programs::SkMsg) and [`SkSkb`](crate::programs::SkSkb). pub fn fd(&self) -> Result<SockMapFd, MapError> { Ok(SockMapFd(self.inner.as_ref().fd_or_err()?)) } } impl<T: AsMut<MapData>, K: Pod> SockHash<T, K> { /// Inserts a socket under the given key. pub fn insert<I: AsRawFd>( &mut self, key: impl Borrow<K>, value: I, flags: u64, ) -> Result<(), MapError> { hash_map::insert(self.inner.as_mut(), key.borrow(), &value.as_raw_fd(), flags) } /// Removes a socket from the map. pub fn remove(&mut self, key: &K) -> Result<(), MapError> { hash_map::remove(self.inner.as_mut(), key) } } impl<T: AsRef<MapData>, K: Pod> IterableMap<K, RawFd> for SockHash<T, K> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, key: &K) -> Result<RawFd, MapError> { SockHash::get(self, key, 0) } } <file_sep>/bpf/aya-bpf/src/maps/hash_map.rs use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull}; use aya_bpf_bindings::bindings::bpf_map_type::{ BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, BPF_MAP_TYPE_PERCPU_HASH, }; use aya_bpf_cty::{c_long, c_void}; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_HASH}, helpers::{bpf_map_delete_elem, bpf_map_lookup_elem, bpf_map_update_elem}, maps::PinningType, }; #[repr(transparent)] pub struct HashMap<K, V> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, _v: PhantomData<V>, } unsafe impl<K: Sync, V: Sync> Sync for HashMap<K, V> {} impl<K, V> HashMap<K, V> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> HashMap<K, V> { HashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_HASH, max_entries, flags, PinningType::None, )), _k: PhantomData, _v: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> HashMap<K, V> { HashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_HASH, max_entries, flags, PinningType::ByName, )), _k: PhantomData, _v: PhantomData, } } /// Retrieve the value associate with `key` from the map. /// This function is unsafe. Unless the map flag `BPF_F_NO_PREALLOC` is used, the kernel does not /// make guarantee on the atomicity of `insert` or `remove`, and any element removed from the /// map might get aliased by another element in the map, causing garbage to be read, or /// corruption in case of writes. #[inline] pub unsafe fn get(&self, key: &K) -> Option<&V> { get(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, but this returns a raw pointer and it's up to the caller /// to decide whether it's safe to dereference the pointer or not. #[inline] pub fn get_ptr(&self, key: &K) -> Option<*const V> { get_ptr(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, and additionally cares should be taken to avoid /// concurrent writes, but it's up to the caller to decide whether it's safe to dereference the /// pointer or not. #[inline] pub fn get_ptr_mut(&self, key: &K) -> Option<*mut V> { get_ptr_mut(self.def.get(), key) } #[inline] pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> { insert(self.def.get(), key, value, flags) } #[inline] pub fn remove(&self, key: &K) -> Result<(), c_long> { remove(self.def.get(), key) } } #[repr(transparent)] pub struct LruHashMap<K, V> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, _v: PhantomData<V>, } unsafe impl<K: Sync, V: Sync> Sync for LruHashMap<K, V> {} impl<K, V> LruHashMap<K, V> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> LruHashMap<K, V> { LruHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LRU_HASH, max_entries, flags, PinningType::None, )), _k: PhantomData, _v: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> LruHashMap<K, V> { LruHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LRU_HASH, max_entries, flags, PinningType::ByName, )), _k: PhantomData, _v: PhantomData, } } /// Retrieve the value associate with `key` from the map. /// This function is unsafe. Unless the map flag `BPF_F_NO_PREALLOC` is used, the kernel does not /// make guarantee on the atomicity of `insert` or `remove`, and any element removed from the /// map might get aliased by another element in the map, causing garbage to be read, or /// corruption in case of writes. #[inline] pub unsafe fn get(&self, key: &K) -> Option<&V> { get(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, but this returns a raw pointer and it's up to the caller /// to decide whether it's safe to dereference the pointer or not. #[inline] pub fn get_ptr(&self, key: &K) -> Option<*const V> { get_ptr(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, and additionally cares should be taken to avoid /// concurrent writes, but it's up to the caller to decide whether it's safe to dereference the /// pointer or not. #[inline] pub fn get_ptr_mut(&self, key: &K) -> Option<*mut V> { get_ptr_mut(self.def.get(), key) } #[inline] pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> { insert(self.def.get(), key, value, flags) } #[inline] pub fn remove(&self, key: &K) -> Result<(), c_long> { remove(self.def.get(), key) } } #[repr(transparent)] pub struct PerCpuHashMap<K, V> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, _v: PhantomData<V>, } unsafe impl<K, V> Sync for PerCpuHashMap<K, V> {} impl<K, V> PerCpuHashMap<K, V> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> PerCpuHashMap<K, V> { PerCpuHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_PERCPU_HASH, max_entries, flags, PinningType::None, )), _k: PhantomData, _v: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> PerCpuHashMap<K, V> { PerCpuHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_PERCPU_HASH, max_entries, flags, PinningType::ByName, )), _k: PhantomData, _v: PhantomData, } } /// Retrieve the value associate with `key` from the map. /// This function is unsafe. Unless the map flag `BPF_F_NO_PREALLOC` is used, the kernel does not /// make guarantee on the atomicity of `insert` or `remove`, and any element removed from the /// map might get aliased by another element in the map, causing garbage to be read, or /// corruption in case of writes. #[inline] pub unsafe fn get(&self, key: &K) -> Option<&V> { get(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, but this returns a raw pointer and it's up to the caller /// to decide whether it's safe to dereference the pointer or not. #[inline] pub fn get_ptr(&self, key: &K) -> Option<*const V> { get_ptr(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, and additionally cares should be taken to avoid /// concurrent writes, but it's up to the caller to decide whether it's safe to dereference the /// pointer or not. #[inline] pub fn get_ptr_mut(&self, key: &K) -> Option<*mut V> { get_ptr_mut(self.def.get(), key) } #[inline] pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> { insert(self.def.get(), key, value, flags) } #[inline] pub fn remove(&self, key: &K) -> Result<(), c_long> { remove(self.def.get(), key) } } #[repr(transparent)] pub struct LruPerCpuHashMap<K, V> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, _v: PhantomData<V>, } unsafe impl<K, V> Sync for LruPerCpuHashMap<K, V> {} impl<K, V> LruPerCpuHashMap<K, V> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> LruPerCpuHashMap<K, V> { LruPerCpuHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LRU_PERCPU_HASH, max_entries, flags, PinningType::None, )), _k: PhantomData, _v: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> LruPerCpuHashMap<K, V> { LruPerCpuHashMap { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LRU_PERCPU_HASH, max_entries, flags, PinningType::ByName, )), _k: PhantomData, _v: PhantomData, } } /// Retrieve the value associate with `key` from the map. /// This function is unsafe. Unless the map flag `BPF_F_NO_PREALLOC` is used, the kernel does not /// make guarantee on the atomicity of `insert` or `remove`, and any element removed from the /// map might get aliased by another element in the map, causing garbage to be read, or /// corruption in case of writes. #[inline] pub unsafe fn get(&self, key: &K) -> Option<&V> { get(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, but this returns a raw pointer and it's up to the caller /// to decide whether it's safe to dereference the pointer or not. #[inline] pub fn get_ptr(&self, key: &K) -> Option<*const V> { get_ptr(self.def.get(), key) } /// Retrieve the value associate with `key` from the map. /// The same caveat as `get` applies, and additionally cares should be taken to avoid /// concurrent writes, but it's up to the caller to decide whether it's safe to dereference the /// pointer or not. #[inline] pub fn get_ptr_mut(&self, key: &K) -> Option<*mut V> { get_ptr_mut(self.def.get(), key) } #[inline] pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> { insert(self.def.get(), key, value, flags) } #[inline] pub fn remove(&self, key: &K) -> Result<(), c_long> { remove(self.def.get(), key) } } const fn build_def<K, V>(ty: u32, max_entries: u32, flags: u32, pin: PinningType) -> bpf_map_def { bpf_map_def { type_: ty, key_size: mem::size_of::<K>() as u32, value_size: mem::size_of::<V>() as u32, max_entries, map_flags: flags, id: 0, pinning: pin as u32, } } #[inline] fn get_ptr_mut<K, V>(def: *mut bpf_map_def, key: &K) -> Option<*mut V> { unsafe { let value = bpf_map_lookup_elem(def as *mut _, key as *const _ as *const c_void); // FIXME: alignment NonNull::new(value as *mut V).map(|p| p.as_ptr()) } } #[inline] fn get_ptr<K, V>(def: *mut bpf_map_def, key: &K) -> Option<*const V> { get_ptr_mut(def, key).map(|p| p as *const V) } #[inline] unsafe fn get<'a, K, V>(def: *mut bpf_map_def, key: &K) -> Option<&'a V> { get_ptr(def, key).map(|p| &*p) } #[inline] fn insert<K, V>(def: *mut bpf_map_def, key: &K, value: &V, flags: u64) -> Result<(), c_long> { let ret = unsafe { bpf_map_update_elem( def as *mut _, key as *const _ as *const _, value as *const _ as *const _, flags, ) }; (ret == 0).then_some(()).ok_or(ret) } #[inline] fn remove<K>(def: *mut bpf_map_def, key: &K) -> Result<(), c_long> { let ret = unsafe { bpf_map_delete_elem(def as *mut _, key as *const _ as *const c_void) }; (ret == 0).then_some(()).ok_or(ret) } <file_sep>/bpf/aya-bpf/src/programs/sk_lookup.rs use core::ffi::c_void; use crate::{bindings::bpf_sk_lookup, BpfContext}; pub struct SkLookupContext { pub lookup: *mut bpf_sk_lookup, } impl SkLookupContext { pub fn new(lookup: *mut bpf_sk_lookup) -> SkLookupContext { SkLookupContext { lookup } } } impl BpfContext for SkLookupContext { fn as_ptr(&self) -> *mut c_void { self.lookup as *mut _ } } <file_sep>/bpf/aya-log-ebpf/Cargo.toml [package] name = "aya-log-ebpf" version = "0.1.0" edition = "2021" [dependencies] aya-bpf = { path = "../aya-bpf" } aya-log-common = { path = "../../aya-log-common" } aya-log-ebpf-macros = { path = "../../aya-log-ebpf-macros" } [lib] path = "src/lib.rs" <file_sep>/xtask/src/build_test.rs use clap::Parser; use std::process::Command; use crate::build_ebpf; #[derive(Parser)] pub struct Options { /// Whether to compile for the musl libc target #[clap(short, long)] pub musl: bool, #[clap(flatten)] pub ebpf_options: build_ebpf::BuildEbpfOptions, } pub fn build_test(opts: Options) -> anyhow::Result<()> { build_ebpf::build_ebpf(opts.ebpf_options)?; let mut args = vec!["build", "-p", "integration-test", "--verbose"]; if opts.musl { args.push("--target=x86_64-unknown-linux-musl"); } let status = Command::new("cargo") .args(&args) .status() .expect("failed to build bpf program"); assert!(status.success()); Ok(()) } <file_sep>/aya/src/obj/btf/types.rs use std::{fmt::Display, mem, ptr}; use object::Endianness; use crate::obj::btf::{Btf, BtfError, MAX_RESOLVE_DEPTH}; #[derive(Clone, Debug)] pub(crate) enum BtfType { Unknown, Fwd(Fwd), Const(Const), Volatile(Volatile), Restrict(Restrict), Ptr(Ptr), Typedef(Typedef), Func(Func), Int(Int), Float(Float), Enum(Enum), Array(Array), Struct(Struct), Union(Union), FuncProto(FuncProto), Var(Var), DataSec(DataSec), DeclTag(DeclTag), TypeTag(TypeTag), } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Fwd { pub(crate) name_offset: u32, info: u32, _unused: u32, } impl Fwd { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Fwd>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Fwd } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Const { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } impl Const { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Const>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Const } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(btf_type: u32) -> Self { let info = (BtfKind::Const as u32) << 24; Const { name_offset: 0, info, btf_type, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Volatile { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } impl Volatile { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Volatile>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Volatile } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } } #[derive(Clone, Debug)] pub(crate) struct Restrict { pub(crate) name_offset: u32, _info: u32, pub(crate) btf_type: u32, } impl Restrict { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Restrict>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Restrict } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Ptr { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } impl Ptr { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Self>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Ptr } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, btf_type: u32) -> Self { let info = (BtfKind::Ptr as u32) << 24; Ptr { name_offset, info, btf_type, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Typedef { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } impl Typedef { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Self>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Typedef } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, btf_type: u32) -> Self { let info = (BtfKind::Typedef as u32) << 24; Typedef { name_offset, info, btf_type, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Float { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, } impl Float { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Self>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Float } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, size: u32) -> Self { let info = (BtfKind::Float as u32) << 24; Float { name_offset, info, size, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Func { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } #[repr(u32)] #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum FuncLinkage { Static = 0, Global = 1, Extern = 2, Unknown, } impl From<u32> for FuncLinkage { fn from(v: u32) -> Self { match v { 0 => FuncLinkage::Static, 1 => FuncLinkage::Global, 2 => FuncLinkage::Extern, _ => FuncLinkage::Unknown, } } } impl Func { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Self>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Func } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, proto: u32, linkage: FuncLinkage) -> Self { let mut info = (BtfKind::Func as u32) << 24; info |= (linkage as u32) & 0xFFFF; Func { name_offset, info, btf_type: proto, } } pub(crate) fn linkage(&self) -> FuncLinkage { (self.info & 0xFFF).into() } pub(crate) fn set_linkage(&mut self, linkage: FuncLinkage) { self.info = (self.info & 0xFFFF0000) | (linkage as u32) & 0xFFFF; } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct TypeTag { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, } impl TypeTag { pub(crate) fn to_bytes(&self) -> Vec<u8> { bytes_of::<Self>(self).to_vec() } pub(crate) fn kind(&self) -> BtfKind { BtfKind::TypeTag } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, btf_type: u32) -> Self { let info = (BtfKind::TypeTag as u32) << 24; TypeTag { name_offset, info, btf_type, } } } #[repr(u32)] #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum IntEncoding { None, Signed = 1, Char = 2, Bool = 4, Unknown, } impl From<u32> for IntEncoding { fn from(v: u32) -> Self { match v { 0 => IntEncoding::None, 1 => IntEncoding::Signed, 2 => IntEncoding::Char, 4 => IntEncoding::Bool, _ => IntEncoding::Unknown, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Int { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, pub(crate) data: u32, } impl Int { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.size)); buf.extend(bytes_of::<u32>(&self.data)); buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Int } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, size: u32, encoding: IntEncoding, offset: u32) -> Self { let info = (BtfKind::Int as u32) << 24; let mut data = 0u32; data |= (encoding as u32 & 0x0f) << 24; data |= (offset & 0xff) << 16; data |= (size * 8) & 0xff; Int { name_offset, info, size, data, } } pub(crate) fn encoding(&self) -> IntEncoding { ((self.data & 0x0f000000) >> 24).into() } pub(crate) fn offset(&self) -> u32 { (self.data & 0x00ff0000) >> 16 } // TODO: Remove directive this when this crate is pub #[cfg(test)] pub(crate) fn bits(&self) -> u32 { self.data & 0x000000ff } } #[repr(C)] #[derive(Debug, Clone)] pub(crate) struct BtfEnum { pub(crate) name_offset: u32, pub(crate) value: i32, } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Enum { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, pub(crate) variants: Vec<BtfEnum>, } impl Enum { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.size)); for v in &self.variants { buf.extend(bytes_of::<u32>(&v.name_offset)); buf.extend(bytes_of::<i32>(&v.value)); } buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Enum } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Fwd>() + mem::size_of::<BtfEnum>() * self.variants.len() } pub(crate) fn new(name_offset: u32, variants: Vec<BtfEnum>) -> Self { let mut info = (BtfKind::Enum as u32) << 24; info |= (variants.len() as u32) & 0xFFFF; Enum { name_offset, info, size: 4, variants, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct BtfMember { pub(crate) name_offset: u32, pub(crate) btf_type: u32, pub(crate) offset: u32, } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Struct { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, pub(crate) members: Vec<BtfMember>, } impl Struct { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.size)); for v in &self.members { buf.extend(bytes_of::<u32>(&v.name_offset)); buf.extend(bytes_of::<u32>(&v.btf_type)); buf.extend(bytes_of::<u32>(&v.offset)); } buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Struct } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Fwd>() + mem::size_of::<BtfMember>() * self.members.len() } pub(crate) fn new(name_offset: u32, members: Vec<BtfMember>, size: u32) -> Self { let mut info = (BtfKind::Struct as u32) << 24; info |= (members.len() as u32) & 0xFFFF; Struct { name_offset, info, size, members, } } pub(crate) fn member_bit_offset(&self, member: &BtfMember) -> usize { let k_flag = self.info >> 31 == 1; let bit_offset = if k_flag { member.offset & 0xFFFFFF } else { member.offset }; bit_offset as usize } pub(crate) fn member_bit_field_size(&self, member: &BtfMember) -> usize { let k_flag = (self.info >> 31) == 1; let size = if k_flag { member.offset >> 24 } else { 0 }; size as usize } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Union { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, pub(crate) members: Vec<BtfMember>, } impl Union { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.size)); for v in &self.members { buf.extend(bytes_of::<u32>(&v.name_offset)); buf.extend(bytes_of::<u32>(&v.btf_type)); buf.extend(bytes_of::<u32>(&v.offset)); } buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Union } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Fwd>() + mem::size_of::<BtfMember>() * self.members.len() } pub(crate) fn member_bit_offset(&self, member: &BtfMember) -> usize { let k_flag = self.info >> 31 == 1; let bit_offset = if k_flag { member.offset & 0xFFFFFF } else { member.offset }; bit_offset as usize } pub(crate) fn member_bit_field_size(&self, member: &BtfMember) -> usize { let k_flag = (self.info >> 31) == 1; let size = if k_flag { member.offset >> 24 } else { 0 }; size as usize } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct BtfArray { pub(crate) element_type: u32, pub(crate) index_type: u32, pub(crate) len: u32, } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Array { pub(crate) name_offset: u32, info: u32, _unused: u32, pub(crate) array: BtfArray, } impl Array { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self._unused)); buf.extend(bytes_of::<BtfArray>(&self.array)); buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Array } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } #[cfg(test)] pub(crate) fn new(name_offset: u32, element_type: u32, index_type: u32, len: u32) -> Self { let info = (BtfKind::Array as u32) << 24; Array { name_offset, info, _unused: 0, array: BtfArray { element_type, index_type, len, }, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct BtfParam { pub(crate) name_offset: u32, pub(crate) btf_type: u32, } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct FuncProto { pub(crate) name_offset: u32, info: u32, pub(crate) return_type: u32, pub(crate) params: Vec<BtfParam>, } impl FuncProto { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.return_type)); for p in &self.params { buf.extend(bytes_of::<u32>(&p.name_offset)); buf.extend(bytes_of::<u32>(&p.btf_type)); } buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::FuncProto } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Fwd>() + mem::size_of::<BtfParam>() * self.params.len() } pub(crate) fn new(params: Vec<BtfParam>, return_type: u32) -> Self { let mut info = (BtfKind::FuncProto as u32) << 24; info |= (params.len() as u32) & 0xFFFF; FuncProto { name_offset: 0, info, return_type, params, } } } #[repr(u32)] #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum VarLinkage { Static, Global, Extern, Unknown, } impl From<u32> for VarLinkage { fn from(v: u32) -> Self { match v { 0 => VarLinkage::Static, 1 => VarLinkage::Global, 2 => VarLinkage::Extern, _ => VarLinkage::Unknown, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct Var { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, pub(crate) linkage: VarLinkage, } impl Var { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.btf_type)); buf.extend(bytes_of::<VarLinkage>(&self.linkage)); buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::Var } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, btf_type: u32, linkage: VarLinkage) -> Self { let info = (BtfKind::Var as u32) << 24; Var { name_offset, info, btf_type, linkage, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct DataSecEntry { pub(crate) btf_type: u32, pub(crate) offset: u32, pub(crate) size: u32, } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct DataSec { pub(crate) name_offset: u32, info: u32, pub(crate) size: u32, pub(crate) entries: Vec<DataSecEntry>, } impl DataSec { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.size)); for e in &self.entries { buf.extend(bytes_of::<u32>(&e.btf_type)); buf.extend(bytes_of::<u32>(&e.offset)); buf.extend(bytes_of::<u32>(&e.size)); } buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::DataSec } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Fwd>() + mem::size_of::<DataSecEntry>() * self.entries.len() } pub(crate) fn new(name_offset: u32, entries: Vec<DataSecEntry>, size: u32) -> Self { let mut info = (BtfKind::DataSec as u32) << 24; info |= (entries.len() as u32) & 0xFFFF; DataSec { name_offset, info, size, entries, } } } #[repr(C)] #[derive(Clone, Debug)] pub(crate) struct DeclTag { pub(crate) name_offset: u32, info: u32, pub(crate) btf_type: u32, pub(crate) component_index: i32, } impl DeclTag { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; buf.extend(bytes_of::<u32>(&self.name_offset)); buf.extend(bytes_of::<u32>(&self.info)); buf.extend(bytes_of::<u32>(&self.btf_type)); buf.extend(bytes_of::<i32>(&self.component_index)); buf } pub(crate) fn kind(&self) -> BtfKind { BtfKind::DeclTag } pub(crate) fn type_info_size(&self) -> usize { mem::size_of::<Self>() } pub(crate) fn new(name_offset: u32, btf_type: u32, component_index: i32) -> Self { let info = (BtfKind::DeclTag as u32) << 24; DeclTag { name_offset, info, btf_type, component_index, } } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u32)] pub(crate) enum BtfKind { Unknown = 0, Int = 1, Ptr = 2, Array = 3, Struct = 4, Union = 5, Enum = 6, Fwd = 7, Typedef = 8, Volatile = 9, Const = 10, Restrict = 11, Func = 12, FuncProto = 13, Var = 14, DataSec = 15, Float = 16, DeclTag = 17, TypeTag = 18, } impl TryFrom<u32> for BtfKind { type Error = BtfError; fn try_from(v: u32) -> Result<Self, Self::Error> { use BtfKind::*; Ok(match v { 0 => Unknown, 1 => Int, 2 => Ptr, 3 => Array, 4 => Struct, 5 => Union, 6 => Enum, 7 => Fwd, 8 => Typedef, 9 => Volatile, 10 => Const, 11 => Restrict, 12 => Func, 13 => FuncProto, 14 => Var, 15 => DataSec, 16 => Float, 17 => DeclTag, 18 => TypeTag, kind => return Err(BtfError::InvalidTypeKind { kind }), }) } } impl Display for BtfKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { BtfKind::Unknown => write!(f, "[UNKNOWN]"), BtfKind::Int => write!(f, "[INT]"), BtfKind::Float => write!(f, "[FLOAT]"), BtfKind::Ptr => write!(f, "[PTR]"), BtfKind::Array => write!(f, "[ARRAY]"), BtfKind::Struct => write!(f, "[STRUCT]"), BtfKind::Union => write!(f, "[UNION]"), BtfKind::Enum => write!(f, "[ENUM]"), BtfKind::Fwd => write!(f, "[FWD]"), BtfKind::Typedef => write!(f, "[TYPEDEF]"), BtfKind::Volatile => write!(f, "[VOLATILE]"), BtfKind::Const => write!(f, "[CONST]"), BtfKind::Restrict => write!(f, "[RESTRICT]"), BtfKind::Func => write!(f, "[FUNC]"), BtfKind::FuncProto => write!(f, "[FUNC_PROTO]"), BtfKind::Var => write!(f, "[VAR]"), BtfKind::DataSec => write!(f, "[DATASEC]"), BtfKind::DeclTag => write!(f, "[DECL_TAG]"), BtfKind::TypeTag => write!(f, "[TYPE_TAG]"), } } } impl Default for BtfKind { fn default() -> Self { BtfKind::Unknown } } unsafe fn read<T>(data: &[u8]) -> Result<T, BtfError> { if mem::size_of::<T>() > data.len() { return Err(BtfError::InvalidTypeInfo); } Ok(ptr::read_unaligned::<T>(data.as_ptr() as *const T)) } unsafe fn read_array<T>(data: &[u8], len: usize) -> Result<Vec<T>, BtfError> { if mem::size_of::<T>() * len > data.len() { return Err(BtfError::InvalidTypeInfo); } let data = &data[0..mem::size_of::<T>() * len]; let r = data .chunks(mem::size_of::<T>()) .map(|chunk| ptr::read_unaligned(chunk.as_ptr() as *const T)) .collect(); Ok(r) } impl BtfType { #[allow(unused_unsafe)] pub(crate) unsafe fn read(data: &[u8], endianness: Endianness) -> Result<BtfType, BtfError> { let ty = unsafe { read_array::<u32>(data, 3)? }; let data = &data[mem::size_of::<u32>() * 3..]; let vlen = type_vlen(ty[1]); Ok(match type_kind(ty[1])? { BtfKind::Unknown => BtfType::Unknown, BtfKind::Fwd => BtfType::Fwd(Fwd { name_offset: ty[0], info: ty[1], _unused: 0, }), BtfKind::Const => BtfType::Const(Const { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), BtfKind::Volatile => BtfType::Volatile(Volatile { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), BtfKind::Restrict => BtfType::Restrict(Restrict { name_offset: ty[0], _info: ty[1], btf_type: ty[2], }), BtfKind::Ptr => BtfType::Ptr(Ptr { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), BtfKind::Typedef => BtfType::Typedef(Typedef { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), BtfKind::Func => BtfType::Func(Func { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), BtfKind::Int => { if mem::size_of::<u32>() > data.len() { return Err(BtfError::InvalidTypeInfo); } let read_u32 = if endianness == Endianness::Little { u32::from_le_bytes } else { u32::from_be_bytes }; BtfType::Int(Int { name_offset: ty[0], info: ty[1], size: ty[2], data: read_u32(data[..mem::size_of::<u32>()].try_into().unwrap()), }) } BtfKind::Float => BtfType::Float(Float { name_offset: ty[0], info: ty[1], size: ty[2], }), BtfKind::Enum => BtfType::Enum(Enum { name_offset: ty[0], info: ty[1], size: ty[2], variants: unsafe { read_array::<BtfEnum>(data, vlen)? }, }), BtfKind::Array => BtfType::Array(Array { name_offset: ty[0], info: ty[1], _unused: 0, array: unsafe { read(data)? }, }), BtfKind::Struct => BtfType::Struct(Struct { name_offset: ty[0], info: ty[1], size: ty[2], members: unsafe { read_array::<BtfMember>(data, vlen)? }, }), BtfKind::Union => BtfType::Union(Union { name_offset: ty[0], info: ty[1], size: ty[2], members: unsafe { read_array::<BtfMember>(data, vlen)? }, }), BtfKind::FuncProto => BtfType::FuncProto(FuncProto { name_offset: ty[0], info: ty[1], return_type: ty[2], params: unsafe { read_array::<BtfParam>(data, vlen)? }, }), BtfKind::Var => BtfType::Var(Var { name_offset: ty[0], info: ty[1], btf_type: ty[2], linkage: unsafe { read(data)? }, }), BtfKind::DataSec => BtfType::DataSec(DataSec { name_offset: ty[0], info: ty[1], size: ty[2], entries: unsafe { read_array::<DataSecEntry>(data, vlen)? }, }), BtfKind::DeclTag => BtfType::DeclTag(DeclTag { name_offset: ty[0], info: ty[1], btf_type: ty[2], component_index: unsafe { read(data)? }, }), BtfKind::TypeTag => BtfType::TypeTag(TypeTag { name_offset: ty[0], info: ty[1], btf_type: ty[2], }), }) } pub(crate) fn to_bytes(&self) -> Vec<u8> { match self { BtfType::Unknown => vec![], BtfType::Fwd(t) => t.to_bytes(), BtfType::Const(t) => t.to_bytes(), BtfType::Volatile(t) => t.to_bytes(), BtfType::Restrict(t) => t.to_bytes(), BtfType::Ptr(t) => t.to_bytes(), BtfType::Typedef(t) => t.to_bytes(), BtfType::Func(t) => t.to_bytes(), BtfType::Int(t) => t.to_bytes(), BtfType::Float(t) => t.to_bytes(), BtfType::Enum(t) => t.to_bytes(), BtfType::Array(t) => t.to_bytes(), BtfType::Struct(t) => t.to_bytes(), BtfType::Union(t) => t.to_bytes(), BtfType::FuncProto(t) => t.to_bytes(), BtfType::Var(t) => t.to_bytes(), BtfType::DataSec(t) => t.to_bytes(), BtfType::DeclTag(t) => t.to_bytes(), BtfType::TypeTag(t) => t.to_bytes(), } } pub(crate) fn size(&self) -> Option<u32> { match self { BtfType::Int(t) => Some(t.size), BtfType::Float(t) => Some(t.size), BtfType::Enum(t) => Some(t.size), BtfType::Struct(t) => Some(t.size), BtfType::Union(t) => Some(t.size), BtfType::DataSec(t) => Some(t.size), _ => None, } } pub(crate) fn btf_type(&self) -> Option<u32> { match self { BtfType::Const(t) => Some(t.btf_type), BtfType::Volatile(t) => Some(t.btf_type), BtfType::Restrict(t) => Some(t.btf_type), BtfType::Ptr(t) => Some(t.btf_type), BtfType::Typedef(t) => Some(t.btf_type), // FuncProto contains the return type here, and doesn't directly reference another type BtfType::FuncProto(t) => Some(t.return_type), BtfType::Var(t) => Some(t.btf_type), BtfType::DeclTag(t) => Some(t.btf_type), BtfType::TypeTag(t) => Some(t.btf_type), _ => None, } } pub(crate) fn type_info_size(&self) -> usize { match self { BtfType::Unknown => mem::size_of::<Fwd>(), BtfType::Fwd(t) => t.type_info_size(), BtfType::Const(t) => t.type_info_size(), BtfType::Volatile(t) => t.type_info_size(), BtfType::Restrict(t) => t.type_info_size(), BtfType::Ptr(t) => t.type_info_size(), BtfType::Typedef(t) => t.type_info_size(), BtfType::Func(t) => t.type_info_size(), BtfType::Int(t) => t.type_info_size(), BtfType::Float(t) => t.type_info_size(), BtfType::Enum(t) => t.type_info_size(), BtfType::Array(t) => t.type_info_size(), BtfType::Struct(t) => t.type_info_size(), BtfType::Union(t) => t.type_info_size(), BtfType::FuncProto(t) => t.type_info_size(), BtfType::Var(t) => t.type_info_size(), BtfType::DataSec(t) => t.type_info_size(), BtfType::DeclTag(t) => t.type_info_size(), BtfType::TypeTag(t) => t.type_info_size(), } } pub(crate) fn name_offset(&self) -> u32 { match self { BtfType::Unknown => 0, BtfType::Fwd(t) => t.name_offset, BtfType::Const(t) => t.name_offset, BtfType::Volatile(t) => t.name_offset, BtfType::Restrict(t) => t.name_offset, BtfType::Ptr(t) => t.name_offset, BtfType::Typedef(t) => t.name_offset, BtfType::Func(t) => t.name_offset, BtfType::Int(t) => t.name_offset, BtfType::Float(t) => t.name_offset, BtfType::Enum(t) => t.name_offset, BtfType::Array(t) => t.name_offset, BtfType::Struct(t) => t.name_offset, BtfType::Union(t) => t.name_offset, BtfType::FuncProto(t) => t.name_offset, BtfType::Var(t) => t.name_offset, BtfType::DataSec(t) => t.name_offset, BtfType::DeclTag(t) => t.name_offset, BtfType::TypeTag(t) => t.name_offset, } } pub(crate) fn kind(&self) -> BtfKind { match self { BtfType::Unknown => BtfKind::Unknown, BtfType::Fwd(t) => t.kind(), BtfType::Const(t) => t.kind(), BtfType::Volatile(t) => t.kind(), BtfType::Restrict(t) => t.kind(), BtfType::Ptr(t) => t.kind(), BtfType::Typedef(t) => t.kind(), BtfType::Func(t) => t.kind(), BtfType::Int(t) => t.kind(), BtfType::Float(t) => t.kind(), BtfType::Enum(t) => t.kind(), BtfType::Array(t) => t.kind(), BtfType::Struct(t) => t.kind(), BtfType::Union(t) => t.kind(), BtfType::FuncProto(t) => t.kind(), BtfType::Var(t) => t.kind(), BtfType::DataSec(t) => t.kind(), BtfType::DeclTag(t) => t.kind(), BtfType::TypeTag(t) => t.kind(), } } pub(crate) fn is_composite(&self) -> bool { matches!(self, BtfType::Struct(_) | BtfType::Union(_)) } pub(crate) fn members(&self) -> Option<impl Iterator<Item = &BtfMember>> { match self { BtfType::Struct(t) => Some(t.members.iter()), BtfType::Union(t) => Some(t.members.iter()), _ => None, } } pub(crate) fn member_bit_field_size(&self, member: &BtfMember) -> Option<usize> { match self { BtfType::Struct(t) => Some(t.member_bit_field_size(member)), BtfType::Union(t) => Some(t.member_bit_field_size(member)), _ => None, } } pub(crate) fn member_bit_offset(&self, member: &BtfMember) -> Option<usize> { match self { BtfType::Struct(t) => Some(t.member_bit_offset(member)), BtfType::Union(t) => Some(t.member_bit_offset(member)), _ => None, } } } fn type_kind(info: u32) -> Result<BtfKind, BtfError> { ((info >> 24) & 0x1F).try_into() } fn type_vlen(info: u32) -> usize { (info & 0xFFFF) as usize } pub(crate) fn types_are_compatible( local_btf: &Btf, root_local_id: u32, target_btf: &Btf, root_target_id: u32, ) -> Result<bool, BtfError> { let mut local_id = root_local_id; let mut target_id = root_target_id; let local_ty = local_btf.type_by_id(local_id)?; let target_ty = target_btf.type_by_id(target_id)?; if local_ty.kind() != target_ty.kind() { return Ok(false); } for _ in 0..MAX_RESOLVE_DEPTH { local_id = local_btf.resolve_type(local_id)?; target_id = target_btf.resolve_type(target_id)?; let local_ty = local_btf.type_by_id(local_id)?; let target_ty = target_btf.type_by_id(target_id)?; if local_ty.kind() != target_ty.kind() { return Ok(false); } match local_ty { BtfType::Unknown | BtfType::Struct(_) | BtfType::Union(_) | BtfType::Enum(_) | BtfType::Fwd(_) | BtfType::Float(_) => return Ok(true), BtfType::Int(local) => { if let BtfType::Int(target) = target_ty { return Ok(local.offset() == 0 && target.offset() == 0); } } BtfType::Ptr(local) => { if let BtfType::Ptr(target) = target_ty { local_id = local.btf_type; target_id = target.btf_type; continue; } } BtfType::Array(Array { array: local, .. }) => { if let BtfType::Array(Array { array: target, .. }) = target_ty { local_id = local.element_type; target_id = target.element_type; continue; } } BtfType::FuncProto(local) => { if let BtfType::FuncProto(target) = target_ty { if local.params.len() != target.params.len() { return Ok(false); } for (l_param, t_param) in local.params.iter().zip(target.params.iter()) { let local_id = local_btf.resolve_type(l_param.btf_type)?; let target_id = target_btf.resolve_type(t_param.btf_type)?; if !types_are_compatible(local_btf, local_id, target_btf, target_id)? { return Ok(false); } } local_id = local.return_type; target_id = target.return_type; continue; } } _ => panic!("this shouldn't be reached"), } } Err(BtfError::MaximumTypeDepthReached { type_id: local_id }) } pub(crate) fn fields_are_compatible( local_btf: &Btf, mut local_id: u32, target_btf: &Btf, mut target_id: u32, ) -> Result<bool, BtfError> { for _ in 0..MAX_RESOLVE_DEPTH { local_id = local_btf.resolve_type(local_id)?; target_id = target_btf.resolve_type(target_id)?; let local_ty = local_btf.type_by_id(local_id)?; let target_ty = target_btf.type_by_id(target_id)?; if local_ty.is_composite() && target_ty.is_composite() { return Ok(true); } if local_ty.kind() != target_ty.kind() { return Ok(false); } match local_ty { BtfType::Fwd(_) | BtfType::Enum(_) => { let flavorless_name = |name: &str| name.split_once("___").map_or(name, |x| x.0).to_string(); let local_name = flavorless_name(&local_btf.type_name(local_ty)?); let target_name = flavorless_name(&target_btf.type_name(target_ty)?); return Ok(local_name == target_name); } BtfType::Int(local) => { if let BtfType::Int(target) = target_ty { return Ok(local.offset() == 0 && target.offset() == 0); } } BtfType::Float(_) => return Ok(true), BtfType::Ptr(_) => return Ok(true), BtfType::Array(Array { array: local, .. }) => { if let BtfType::Array(Array { array: target, .. }) = target_ty { local_id = local.element_type; target_id = target.element_type; continue; } } _ => panic!("this shouldn't be reached"), } } Err(BtfError::MaximumTypeDepthReached { type_id: local_id }) } fn bytes_of<T>(val: &T) -> &[u8] { // Safety: all btf types are POD unsafe { crate::util::bytes_of(val) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_btf_type_int() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Int(new)) => { assert_eq!(new.name_offset, 1); assert_eq!(new.size, 8); assert_eq!(new.bits(), 64); let data2 = new.to_bytes(); assert_eq!(data, data2); } Ok(t) => panic!("expected int type, got {t:#?}"), Err(_) => panic!("unexpected error"), } } #[test] fn test_write_btf_long_unsigned_int() { let data: &[u8] = &[ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, ]; let int = Int::new(1, 8, IntEncoding::None, 0); assert_eq!(int.to_bytes(), data); } #[test] fn test_write_btf_uchar() { let data: &[u8] = &[ 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, ]; let int = Int::new(0x13, 1, IntEncoding::None, 0); assert_eq!(int.to_bytes(), data); } #[test] fn test_write_btf_signed_short_int() { let data: &[u8] = &[ 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x01, ]; let int = Int::new(0x4a, 2, IntEncoding::Signed, 0); assert_eq!(int.to_bytes(), data); } #[test] fn test_read_btf_type_ptr() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Ptr(_)) => {} Ok(t) => panic!("expected ptr type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_array() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Array(_)) => {} Ok(t) => panic!("expected array type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_struct() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00, 0x47, 0x02, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Struct(_)) => {} Ok(t) => panic!("expected struct type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_union() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x05, 0x04, 0x00, 0x00, 0x00, 0x0d, 0x04, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Union(_)) => {} Ok(t) => panic!("expected union type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_enum() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x06, 0x04, 0x00, 0x00, 0x00, 0xc9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcf, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Enum(_)) => {} Ok(t) => panic!("expected enum type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_fwd() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x0b, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Fwd(_)) => {} Ok(t) => panic!("expected fwd type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_typedef() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x0b, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Typedef(_)) => {} Ok(t) => panic!("expected typedef type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_volatile() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x24, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Volatile(_)) => {} Ok(t) => panic!("expected volatile type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_const() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Const(_)) => {} Ok(t) => panic!("expected const type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_restrict() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x04, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Restrict(_)) => {} Ok(t) => panic!("expected restrict type gpt {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_func() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x17, 0x8b, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x0c, 0xf0, 0xe4, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Func(_)) => {} Ok(t) => panic!("expected func type gpt {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_func_proto() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::FuncProto(_)) => {} Ok(t) => panic!("expected func_proto type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_func_var() { let endianness = Endianness::default(); // NOTE: There was no data in /sys/kernell/btf/vmlinux for this type let data: &[u8] = &[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Var(_)) => {} Ok(t) => panic!("expected var type, got {t:#?}"), Err(_) => panic!("unexpected error"), }; let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_func_datasec() { let endianness = Endianness::default(); let data: &[u8] = &[ 0xd9, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match &got { Ok(BtfType::DataSec(ty)) => { assert_eq!(0, ty.size); assert_eq!(11, ty.entries[0].btf_type); assert_eq!(0, ty.entries[0].offset); assert_eq!(4, ty.entries[0].size); } Ok(t) => panic!("expected datasec type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_read_btf_type_float() { let endianness = Endianness::default(); let data: &[u8] = &[ 0x78, 0xfd, 0x02, 0x00, 0x00, 0x00, 0x00, 0x10, 0x08, 0x00, 0x00, 0x00, ]; let got = unsafe { BtfType::read(data, endianness) }; match got { Ok(BtfType::Float(_)) => {} Ok(t) => panic!("expected float type, got {t:#?}"), Err(_) => panic!("unexpected error"), } let data2 = got.unwrap().to_bytes(); assert_eq!(data, data2) } #[test] fn test_write_btf_func_proto() { let params = vec![ BtfParam { name_offset: 1, btf_type: 1, }, BtfParam { name_offset: 3, btf_type: 1, }, ]; let func_proto = FuncProto::new(params, 2); let data = func_proto.to_bytes(); let got = unsafe { BtfType::read(&data, Endianness::default()) }; match got { Ok(BtfType::FuncProto(fp)) => { assert_eq!(fp.params.len(), 2); } Ok(t) => panic!("expected func proto type, got {t:#?}"), Err(_) => panic!("unexpected error"), } } #[test] fn test_types_are_compatible() { let mut btf = Btf::new(); let name_offset = btf.add_string("u32".to_string()); let u32t = btf.add_type(BtfType::Int(Int::new(name_offset, 4, IntEncoding::None, 0))); let name_offset = btf.add_string("u64".to_string()); let u64t = btf.add_type(BtfType::Int(Int::new(name_offset, 8, IntEncoding::None, 0))); let name_offset = btf.add_string("widgets".to_string()); let array_type = btf.add_type(BtfType::Array(Array::new(name_offset, u64t, u32t, 16))); assert!(types_are_compatible(&btf, u32t, &btf, u32t).unwrap()); // int types are compatible if offsets match. size and encoding aren't compared assert!(types_are_compatible(&btf, u32t, &btf, u64t).unwrap()); assert!(types_are_compatible(&btf, array_type, &btf, array_type).unwrap()); } } <file_sep>/aya/src/programs/sock_ops.rs //! Socket option programs. use std::os::unix::io::AsRawFd; use crate::{ generated::{bpf_attach_type::BPF_CGROUP_SOCK_OPS, bpf_prog_type::BPF_PROG_TYPE_SOCK_OPS}, programs::{ define_link_wrapper, load_program, ProgAttachLink, ProgAttachLinkId, ProgramData, ProgramError, }, sys::bpf_prog_attach, }; /// A program used to work with sockets. /// /// [`SockOps`] programs can access or set socket options, connection /// parameters, watch connection state changes and more. They are attached to /// cgroups. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.13. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::SockOps; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let prog: &mut SockOps = bpf.program_mut("intercept_active_sockets").unwrap().try_into()?; /// prog.load()?; /// prog.attach(file)?; /// # Ok::<(), Error>(()) #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SOCK_OPS")] pub struct SockOps { pub(crate) data: ProgramData<SockOpsLink>, } impl SockOps { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SOCK_OPS, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [SockOps::detach]. pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<SockOpsLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SOCK_OPS).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data.links.insert(SockOpsLink::new(ProgAttachLink::new( prog_fd, cgroup_fd, BPF_CGROUP_SOCK_OPS, ))) } /// Detaches the program. /// /// See [SockOps::attach]. pub fn detach(&mut self, link_id: SockOpsLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: SockOpsLinkId) -> Result<SockOpsLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [SockOps] programs. SockOpsLink, /// The type returned by [SockOps::attach]. Can be passed to [SockOps::detach]. SockOpsLinkId, ProgAttachLink, ProgAttachLinkId ); <file_sep>/aya-tool/src/generate.rs use std::{ fs::{self, File}, io::{self, Write}, path::{Path, PathBuf}, process::Command, str, }; use tempfile::tempdir; use thiserror::Error; use crate::bindgen; #[derive(Error, Debug)] pub enum Error { #[error("error executing bpftool")] BpfTool(#[source] io::Error), #[error("{stderr}\nbpftool failed with exit code {code}")] BpfToolExit { code: i32, stderr: String }, #[error("bindgen failed")] Bindgen(#[source] io::Error), #[error("{stderr}\nbindgen failed with exit code {code}")] BindgenExit { code: i32, stderr: String }, #[error("rustfmt failed")] Rustfmt(#[source] io::Error), #[error("error reading header file")] ReadHeaderFile(#[source] io::Error), } pub enum InputFile { Btf(PathBuf), Header(PathBuf), } pub fn generate<T: AsRef<str>>( input_file: InputFile, types: &[T], additional_flags: &[T], ) -> Result<String, Error> { let additional_flags = additional_flags .iter() .map(|s| s.as_ref().into()) .collect::<Vec<_>>(); let mut bindgen = bindgen::bpf_builder(); let (additional_flags, ctypes_prefix) = extract_ctypes_prefix(&additional_flags); if let Some(prefix) = ctypes_prefix { bindgen = bindgen.ctypes_prefix(prefix) } for ty in types { bindgen = bindgen.allowlist_type(ty); } let (c_header, name) = match &input_file { InputFile::Btf(path) => (c_header_from_btf(path)?, "kernel_types.h"), InputFile::Header(header) => ( fs::read_to_string(header).map_err(Error::ReadHeaderFile)?, header.file_name().unwrap().to_str().unwrap(), ), }; let dir = tempdir().unwrap(); let file_path = dir.path().join(name); let mut file = File::create(&file_path).unwrap(); let _ = file.write(c_header.as_bytes()).unwrap(); let flags = combine_flags(&bindgen.command_line_flags(), &additional_flags); let output = Command::new("bindgen") .arg(file_path) .args(&flags) .output() .map_err(Error::Bindgen)?; if !output.status.success() { return Err(Error::BindgenExit { code: output.status.code().unwrap(), stderr: str::from_utf8(&output.stderr).unwrap().to_owned(), }); } Ok(str::from_utf8(&output.stdout).unwrap().to_owned()) } fn c_header_from_btf(path: &Path) -> Result<String, Error> { let output = Command::new("bpftool") .args(["btf", "dump", "file"]) .arg(path) .args(["format", "c"]) .output() .map_err(Error::BpfTool)?; if !output.status.success() { return Err(Error::BpfToolExit { code: output.status.code().unwrap(), stderr: str::from_utf8(&output.stderr).unwrap().to_owned(), }); } Ok(str::from_utf8(&output.stdout).unwrap().to_owned()) } fn extract_ctypes_prefix(s: &[String]) -> (Vec<String>, Option<String>) { if let Some(index) = s.iter().position(|el| el == "--ctypes-prefix") { if index < s.len() - 1 { let mut flags = Vec::new(); flags.extend_from_slice(&s[0..index]); // skip ["--ctypes-prefix", "value"] flags.extend_from_slice(&s[index + 2..]); return (flags, s.get(index + 1).cloned()); } } (s.to_vec(), None) } fn combine_flags(s1: &[String], s2: &[String]) -> Vec<String> { let mut flags = Vec::new(); let mut extra = Vec::new(); for s in [s1, s2] { let mut s = s.splitn(2, |el| el == "--"); // append args flags.extend(s.next().unwrap().iter().cloned()); if let Some(e) = s.next() { // append extra args extra.extend(e.iter().cloned()); } } // append extra args if !extra.is_empty() { flags.push("--".to_string()); flags.extend(extra); } flags } #[cfg(test)] mod test { use super::{combine_flags, extract_ctypes_prefix}; fn to_vec(s: &str) -> Vec<String> { s.split(' ').map(|x| x.into()).collect() } #[test] fn test_extract_ctypes_prefix() { let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefix bar baz")); assert_eq!(flags, to_vec("foo baz")); assert_eq!(prefix, Some("bar".to_string())); let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefi bar baz")); assert_eq!(flags, to_vec("foo --ctypes-prefi bar baz")); assert_eq!(prefix, None); let (flags, prefix) = extract_ctypes_prefix(&to_vec("--foo bar --ctypes-prefix")); assert_eq!(flags, to_vec("--foo bar --ctypes-prefix")); assert_eq!(prefix, None); let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix foo")); let empty: Vec<String> = Vec::new(); assert_eq!(flags, empty); assert_eq!(prefix, Some("foo".to_string())); let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix")); assert_eq!(flags, to_vec("--ctypes-prefix")); assert_eq!(prefix, None); } #[test] fn test_combine_flags() { assert_eq!( combine_flags(&to_vec("a b"), &to_vec("c d"),).join(" "), "a b c d".to_string(), ); assert_eq!( combine_flags(&to_vec("a -- b"), &to_vec("a b"),).join(" "), "a a b -- b".to_string(), ); assert_eq!( combine_flags(&to_vec("a -- b"), &to_vec("c d"),).join(" "), "a c d -- b".to_string(), ); assert_eq!( combine_flags(&to_vec("a b"), &to_vec("c -- d"),).join(" "), "a b c -- d".to_string(), ); assert_eq!( combine_flags(&to_vec("a -- b"), &to_vec("c -- d"),).join(" "), "a c -- b d".to_string(), ); assert_eq!( combine_flags(&to_vec("a -- b"), &to_vec("-- c d"),).join(" "), "a -- b c d".to_string(), ); } } <file_sep>/aya-log-ebpf-macros/Cargo.toml [package] name = "aya-log-ebpf-macros" version = "0.1.0" edition = "2021" [dependencies] aya-log-common = { path = "../aya-log-common" } aya-log-parser = { path = "../aya-log-parser" } proc-macro2 = "1.0" quote = "1.0" syn = "1.0" [lib] proc-macro = true <file_sep>/aya/src/programs/probe.rs use libc::pid_t; use std::{ fs::{self, OpenOptions}, io::{self, Write}, process, }; use crate::{ programs::{ kprobe::KProbeError, perf_attach, perf_attach::PerfLink, perf_attach_debugfs, trace_point::read_sys_fs_trace_point_id, uprobe::UProbeError, Link, ProgramData, ProgramError, }, sys::{kernel_version, perf_event_open_probe, perf_event_open_trace_point}, }; /// Kind of probe program #[derive(Debug, Copy, Clone)] pub enum ProbeKind { /// Kernel probe KProbe, /// Kernel return probe KRetProbe, /// User space probe UProbe, /// User space return probe URetProbe, } impl ProbeKind { fn pmu(&self) -> &'static str { match *self { ProbeKind::KProbe | ProbeKind::KRetProbe => "kprobe", ProbeKind::UProbe | ProbeKind::URetProbe => "uprobe", } } } pub(crate) fn attach<T: Link + From<PerfLink>>( program_data: &mut ProgramData<T>, kind: ProbeKind, fn_name: &str, offset: u64, pid: Option<pid_t>, ) -> Result<T::Id, ProgramError> { // https://github.com/torvalds/linux/commit/e12f03d7031a977356e3d7b75a68c2185ff8d155 // Use debugfs to create probe let k_ver = kernel_version().unwrap(); if k_ver < (4, 17, 0) { let (fd, event_alias) = create_as_trace_point(kind, fn_name, offset, pid)?; return perf_attach_debugfs(program_data, fd, kind, event_alias); }; let fd = create_as_probe(kind, fn_name, offset, pid)?; perf_attach(program_data, fd) } pub(crate) fn detach_debug_fs(kind: ProbeKind, event_alias: &str) -> Result<(), ProgramError> { use ProbeKind::*; match kind { KProbe | KRetProbe => delete_probe_event(kind, event_alias) .map_err(|(filename, io_error)| KProbeError::FileError { filename, io_error })?, UProbe | URetProbe => delete_probe_event(kind, event_alias) .map_err(|(filename, io_error)| UProbeError::FileError { filename, io_error })?, }; Ok(()) } fn create_as_probe( kind: ProbeKind, fn_name: &str, offset: u64, pid: Option<pid_t>, ) -> Result<i32, ProgramError> { use ProbeKind::*; let perf_ty = match kind { KProbe | KRetProbe => read_sys_fs_perf_type(kind.pmu()) .map_err(|(filename, io_error)| KProbeError::FileError { filename, io_error })?, UProbe | URetProbe => read_sys_fs_perf_type(kind.pmu()) .map_err(|(filename, io_error)| UProbeError::FileError { filename, io_error })?, }; let ret_bit = match kind { KRetProbe => Some( read_sys_fs_perf_ret_probe(kind.pmu()) .map_err(|(filename, io_error)| KProbeError::FileError { filename, io_error })?, ), URetProbe => Some( read_sys_fs_perf_ret_probe(kind.pmu()) .map_err(|(filename, io_error)| UProbeError::FileError { filename, io_error })?, ), _ => None, }; let fd = perf_event_open_probe(perf_ty, ret_bit, fn_name, offset, pid).map_err( |(_code, io_error)| ProgramError::SyscallError { call: "perf_event_open".to_owned(), io_error, }, )? as i32; Ok(fd) } fn create_as_trace_point( kind: ProbeKind, name: &str, offset: u64, pid: Option<pid_t>, ) -> Result<(i32, String), ProgramError> { use ProbeKind::*; let event_alias = match kind { KProbe | KRetProbe => create_probe_event(kind, name, offset) .map_err(|(filename, io_error)| KProbeError::FileError { filename, io_error })?, UProbe | URetProbe => create_probe_event(kind, name, offset) .map_err(|(filename, io_error)| UProbeError::FileError { filename, io_error })?, }; let category = format!("{}s", kind.pmu()); let tpid = read_sys_fs_trace_point_id(&category, &event_alias)?; let fd = perf_event_open_trace_point(tpid, pid).map_err(|(_code, io_error)| { ProgramError::SyscallError { call: "perf_event_open".to_owned(), io_error, } })? as i32; Ok((fd, event_alias)) } fn create_probe_event( kind: ProbeKind, fn_name: &str, offset: u64, ) -> Result<String, (String, io::Error)> { use ProbeKind::*; let events_file_name = format!("/sys/kernel/debug/tracing/{}_events", kind.pmu()); let probe_type_prefix = match kind { KProbe | UProbe => 'p', KRetProbe | URetProbe => 'r', }; let event_alias = format!( "aya_{}_{}_{}_{:#x}", process::id(), probe_type_prefix, fn_name, offset ); let offset_suffix = match kind { KProbe => format!("+{offset}"), UProbe => format!(":{offset:#x}"), _ => "".to_string(), }; let probe = format!( "{}:{}s/{} {}{}\n", probe_type_prefix, kind.pmu(), event_alias, fn_name, offset_suffix ); let mut events_file = OpenOptions::new() .append(true) .open(&events_file_name) .map_err(|e| (events_file_name.clone(), e))?; events_file .write_all(probe.as_bytes()) .map_err(|e| (events_file_name.clone(), e))?; Ok(event_alias) } fn delete_probe_event(kind: ProbeKind, event_alias: &str) -> Result<(), (String, io::Error)> { let events_file_name = format!("/sys/kernel/debug/tracing/{}_events", kind.pmu()); let events = fs::read_to_string(&events_file_name).map_err(|e| (events_file_name.clone(), e))?; let found = events.lines().any(|line| line.contains(event_alias)); if found { let mut events_file = OpenOptions::new() .append(true) .open(&events_file_name) .map_err(|e| (events_file_name.to_string(), e))?; let rm = format!("-:{event_alias}\n"); events_file .write_all(rm.as_bytes()) .map_err(|e| (events_file_name.to_string(), e))?; } Ok(()) } fn read_sys_fs_perf_type(pmu: &str) -> Result<u32, (String, io::Error)> { let file = format!("/sys/bus/event_source/devices/{pmu}/type"); let perf_ty = fs::read_to_string(&file).map_err(|e| (file.clone(), e))?; let perf_ty = perf_ty .trim() .parse::<u32>() .map_err(|e| (file, io::Error::new(io::ErrorKind::Other, e)))?; Ok(perf_ty) } fn read_sys_fs_perf_ret_probe(pmu: &str) -> Result<u32, (String, io::Error)> { let file = format!("/sys/bus/event_source/devices/{pmu}/format/retprobe"); let data = fs::read_to_string(&file).map_err(|e| (file.clone(), e))?; let mut parts = data.trim().splitn(2, ':').skip(1); let config = parts.next().ok_or_else(|| { ( file.clone(), io::Error::new(io::ErrorKind::Other, "invalid format"), ) })?; config .parse::<u32>() .map_err(|e| (file, io::Error::new(io::ErrorKind::Other, e))) } <file_sep>/aya/src/programs/sk_skb.rs //! Skskb programs. use std::os::unix::io::AsRawFd; use crate::{ generated::{ bpf_attach_type::{BPF_SK_SKB_STREAM_PARSER, BPF_SK_SKB_STREAM_VERDICT}, bpf_prog_type::BPF_PROG_TYPE_SK_SKB, }, maps::sock::SockMapFd, programs::{ define_link_wrapper, load_program, ProgAttachLink, ProgAttachLinkId, ProgramData, ProgramError, }, sys::bpf_prog_attach, }; /// The kind of [`SkSkb`] program. #[derive(Copy, Clone, Debug)] pub enum SkSkbKind { /// A Stream Parser StreamParser, /// A Stream Verdict StreamVerdict, } /// A program used to intercept ingress socket buffers. /// /// [`SkSkb`] programs are attached to [socket maps], and can be used to /// inspect, redirect or filter incoming packet. See also [`SockMap`] and /// [`SockHash`]. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.14. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::SockMap; /// use aya::programs::SkSkb; /// /// let intercept_ingress: SockMap<_> = bpf.map("INTERCEPT_INGRESS").unwrap().try_into()?; /// let map_fd = intercept_ingress.fd()?; /// /// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?; /// prog.load()?; /// prog.attach(map_fd)?; /// /// # Ok::<(), aya::BpfError>(()) /// ``` /// /// [socket maps]: crate::maps::sock /// [`SockMap`]: crate::maps::SockMap /// [`SockHash`]: crate::maps::SockHash #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SK_SKB")] pub struct SkSkb { pub(crate) data: ProgramData<SkSkbLink>, pub(crate) kind: SkSkbKind, } impl SkSkb { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SK_SKB, &mut self.data) } /// Attaches the program to the given socket map. /// /// The returned value can be used to detach, see [SkSkb::detach]. pub fn attach(&mut self, map: SockMapFd) -> Result<SkSkbLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let map_fd = map.as_raw_fd(); let attach_type = match self.kind { SkSkbKind::StreamParser => BPF_SK_SKB_STREAM_PARSER, SkSkbKind::StreamVerdict => BPF_SK_SKB_STREAM_VERDICT, }; bpf_prog_attach(prog_fd, map_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data.links.insert(SkSkbLink::new(ProgAttachLink::new( prog_fd, map_fd, attach_type, ))) } /// Detaches the program. /// /// See [SkSkb::attach]. pub fn detach(&mut self, link_id: SkSkbLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: SkSkbLinkId) -> Result<SkSkbLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [SkSkb] programs. SkSkbLink, /// The type returned by [SkSkb::attach]. Can be passed to [SkSkb::detach]. SkSkbLinkId, ProgAttachLink, ProgAttachLinkId ); <file_sep>/aya/src/maps/lpm_trie.rs //! A LPM Trie. use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_kv_size, IterableMap, MapData, MapError, MapIter, MapKeys}, sys::{bpf_map_delete_elem, bpf_map_get_next_key, bpf_map_lookup_elem, bpf_map_update_elem}, Pod, }; /// A Longest Prefix Match Trie. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.20. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::lpm_trie::{LpmTrie, Key}; /// use std::net::Ipv4Addr; /// /// let mut trie = LpmTrie::try_from(bpf.map_mut("LPM_TRIE").unwrap())?; /// let ipaddr = Ipv4Addr::new(8, 8, 8, 8); /// // The following represents a key for the "8.8.8.8/16" subnet. /// // The first argument - the prefix length - represents how many bytes should be matched against. The second argument is the actual data to be matched. /// let key = Key::new(16, u32::from(ipaddr).to_be()); /// trie.insert(&key, 1, 0)?; /// /// // LpmTrie matches against the longest (most accurate) key. /// let lookup = Key::new(32, u32::from(ipaddr).to_be()); /// let value = trie.get(&lookup, 0)?; /// assert_eq!(value, 1); /// /// // If we were to insert a key with longer 'prefix_len' /// // our trie should match against it. /// let longer_key = Key::new(24, u32::from(ipaddr).to_be()); /// trie.insert(&longer_key, 2, 0)?; /// let value = trie.get(&lookup, 0)?; /// assert_eq!(value, 2); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_LPM_TRIE")] pub struct LpmTrie<T, K, V> { inner: T, _k: PhantomData<K>, _v: PhantomData<V>, } /// A Key for and LpmTrie map. /// /// # Examples /// /// ```no_run /// use aya::maps::lpm_trie::{LpmTrie, Key}; /// use std::net::Ipv4Addr; /// /// let ipaddr = Ipv4Addr::new(8,8,8,8); /// let key = Key::new(16, u32::from(ipaddr).to_be()); /// ``` #[repr(packed)] pub struct Key<K: Pod> { /// Represents the number of bytes matched against. pub prefix_len: u32, /// Represents arbitrary data stored in the LpmTrie. pub data: K, } impl<K: Pod> Key<K> { /// Creates a new key. /// /// # Examples /// /// ```no_run /// use aya::maps::lpm_trie::{LpmTrie, Key}; /// use std::net::Ipv4Addr; /// /// let ipaddr = Ipv4Addr::new(8, 8, 8, 8); /// let key = Key::new(16, u32::from(ipaddr).to_be()); /// ``` pub fn new(prefix_len: u32, data: K) -> Self { Self { prefix_len, data } } } impl<K: Pod> Copy for Key<K> {} impl<K: Pod> Clone for Key<K> { fn clone(&self) -> Self { *self } } // A Pod impl is required as Key struct is a key for a map. unsafe impl<K: Pod> Pod for Key<K> {} impl<T: AsRef<MapData>, K: Pod, V: Pod> LpmTrie<T, K, V> { pub(crate) fn new(map: T) -> Result<LpmTrie<T, K, V>, MapError> { let data = map.as_ref(); check_kv_size::<Key<K>, V>(data)?; let _ = data.fd_or_err()?; Ok(LpmTrie { inner: map, _k: PhantomData, _v: PhantomData, }) } /// Returns a copy of the value associated with the longest prefix matching key in the LpmTrie. pub fn get(&self, key: &Key<K>, flags: u64) -> Result<V, MapError> { let fd = self.inner.as_ref().fd_or_err()?; let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; value.ok_or(MapError::KeyNotFound) } /// An iterator visiting all key-value pairs in arbitrary order. The /// iterator item type is `Result<(K, V), MapError>`. pub fn iter(&self) -> MapIter<'_, Key<K>, V, Self> { MapIter::new(self) } /// An iterator visiting all keys in arbitrary order. The iterator element /// type is `Result<Key<K>, MapError>`. pub fn keys(&self) -> MapKeys<'_, Key<K>> { MapKeys::new(self.inner.as_ref()) } /// An iterator visiting all keys matching key. The /// iterator item type is `Result<Key<K>, MapError>`. pub fn iter_key(&self, key: Key<K>) -> LpmTrieKeys<'_, K> { LpmTrieKeys::new(self.inner.as_ref(), key) } } impl<T: AsMut<MapData>, K: Pod, V: Pod> LpmTrie<T, K, V> { /// Inserts a key value pair into the map. pub fn insert( &mut self, key: &Key<K>, value: impl Borrow<V>, flags: u64, ) -> Result<(), MapError> { let fd = self.inner.as_mut().fd_or_err()?; bpf_map_update_elem(fd, Some(key), value.borrow(), flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } /// Removes an element from the map. /// /// Both the prefix and data must match exactly - this method does not do a longest prefix match. pub fn remove(&mut self, key: &Key<K>) -> Result<(), MapError> { let fd = self.inner.as_mut().fd_or_err()?; bpf_map_delete_elem(fd, key) .map(|_| ()) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_delete_elem".to_owned(), io_error, }) } } impl<T: AsRef<MapData>, K: Pod, V: Pod> IterableMap<Key<K>, V> for LpmTrie<T, K, V> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, key: &Key<K>) -> Result<V, MapError> { self.get(key, 0) } } /// Iterator returned by `LpmTrie::iter_key()`. pub struct LpmTrieKeys<'coll, K: Pod> { map: &'coll MapData, err: bool, key: Key<K>, } impl<'coll, K: Pod> LpmTrieKeys<'coll, K> { fn new(map: &'coll MapData, key: Key<K>) -> LpmTrieKeys<'coll, K> { LpmTrieKeys { map, err: false, key, } } } impl<K: Pod> Iterator for LpmTrieKeys<'_, K> { type Item = Result<Key<K>, MapError>; fn next(&mut self) -> Option<Result<Key<K>, MapError>> { if self.err { return None; } let fd = match self.map.fd_or_err() { Ok(fd) => fd, Err(e) => { self.err = true; return Some(Err(e)); } }; match bpf_map_get_next_key(fd, Some(&self.key)) { Ok(Some(key)) => { self.key = key; Some(Ok(key)) } Ok(None) => None, Err((_, io_error)) => { self.err = true; Some(Err(MapError::SyscallError { call: "bpf_map_get_next_key".to_owned(), io_error, })) } } } } #[cfg(test)] mod tests { use super::*; use crate::{ bpf_map_def, generated::{ bpf_cmd, bpf_map_type::{BPF_MAP_TYPE_LPM_TRIE, BPF_MAP_TYPE_PERF_EVENT_ARRAY}, }, maps::{Map, MapData}, obj, sys::{override_syscall, SysResult, Syscall}, }; use libc::{EFAULT, ENOENT}; use std::{io, mem, net::Ipv4Addr}; fn new_obj_map() -> obj::Map { obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_LPM_TRIE as u32, key_size: mem::size_of::<Key<u32>>() as u32, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: obj::MapKind::Other, }) } fn sys_error(value: i32) -> SysResult { Err((-1, io::Error::from_raw_os_error(value))) } #[test] fn test_wrong_key_size() { let map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( LpmTrie::<_, u16, u32>::new(&map), Err(MapError::InvalidKeySize { size: 6, expected: 8 // four bytes for prefixlen and four bytes for data. }) )); } #[test] fn test_wrong_value_size() { let map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( LpmTrie::<_, u32, u16>::new(&map), Err(MapError::InvalidValueSize { size: 2, expected: 4 }) )); } #[test] fn test_try_from_wrong_map() { let map_data = MapData { obj: obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: obj::MapKind::Other, }), fd: None, btf_fd: None, pinned: false, }; let map = Map::PerfEventArray(map_data); assert!(matches!( LpmTrie::<_, u32, u32>::try_from(&map), Err(MapError::InvalidMapType { .. }) )); } #[test] fn test_new_not_created() { let mut map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( LpmTrie::<_, u32, u32>::new(&mut map), Err(MapError::NotCreated { .. }) )); } #[test] fn test_new_ok() { let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; assert!(LpmTrie::<_, u32, u32>::new(&mut map).is_ok()); } #[test] fn test_try_from_ok() { let map_data = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let map = Map::LpmTrie(map_data); assert!(LpmTrie::<_, u32, u32>::try_from(&map).is_ok()) } #[test] fn test_insert_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut trie = LpmTrie::<_, u32, u32>::new(&mut map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(matches!( trie.insert(&key, 1, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_update_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_insert_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_UPDATE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut trie = LpmTrie::<_, u32, u32>::new(&mut map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(trie.insert(&key, 1, 0).is_ok()); } #[test] fn test_remove_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut trie = LpmTrie::<_, u32, u32>::new(&mut map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(matches!( trie.remove(&key), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_delete_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_remove_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_DELETE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut trie = LpmTrie::<_, u32, u32>::new(&mut map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(trie.remove(&key).is_ok()); } #[test] fn test_get_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let trie = LpmTrie::<_, u32, u32>::new(&map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(matches!( trie.get(&key, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_lookup_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_get_not_found() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, .. } => sys_error(ENOENT), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let trie = LpmTrie::<_, u32, u32>::new(&map).unwrap(); let ipaddr = Ipv4Addr::new(8, 8, 8, 8); let key = Key::new(16, u32::from(ipaddr).to_be()); assert!(matches!(trie.get(&key, 0), Err(MapError::KeyNotFound))); } } <file_sep>/aya/src/programs/cgroup_skb.rs //! Cgroup skb programs. use std::{ hash::Hash, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ generated::{ bpf_attach_type::{BPF_CGROUP_INET_EGRESS, BPF_CGROUP_INET_INGRESS}, bpf_prog_type::BPF_PROG_TYPE_CGROUP_SKB, }, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program used to inspect or filter network activity for a given cgroup. /// /// [`CgroupSkb`] programs can be used to inspect or filter network activity /// generated on all the sockets belonging to a given [cgroup]. They can be /// attached to both _ingress_ and _egress_. /// /// [cgroup]: https://man7.org/linux/man-pages/man7/cgroups.7.html /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.10. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::fs::File; /// use aya::programs::{CgroupSkb, CgroupSkbAttachType}; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let egress: &mut CgroupSkb = bpf.program_mut("egress_filter").unwrap().try_into()?; /// egress.load()?; /// egress.attach(file, CgroupSkbAttachType::Egress)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SKB")] pub struct CgroupSkb { pub(crate) data: ProgramData<CgroupSkbLink>, pub(crate) expected_attach_type: Option<CgroupSkbAttachType>, } impl CgroupSkb { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = self.expected_attach_type .map(|attach_type| match attach_type { CgroupSkbAttachType::Ingress => BPF_CGROUP_INET_INGRESS, CgroupSkbAttachType::Egress => BPF_CGROUP_INET_EGRESS, }); load_program(BPF_PROG_TYPE_CGROUP_SKB, &mut self.data) } /// Returns the expected attach type of the program. /// /// [`CgroupSkb`] programs can specify the expected attach type in their ELF /// section name, eg `cgroup_skb/ingress` or `cgroup_skb/egress`. This /// method returns `None` for programs defined with the generic section /// `cgroup/skb`. pub fn expected_attach_type(&self) -> &Option<CgroupSkbAttachType> { &self.expected_attach_type } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSkb::detach]. pub fn attach<T: AsRawFd>( &mut self, cgroup: T, attach_type: CgroupSkbAttachType, ) -> Result<CgroupSkbLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let attach_type = match attach_type { CgroupSkbAttachType::Ingress => BPF_CGROUP_INET_INGRESS, CgroupSkbAttachType::Egress => BPF_CGROUP_INET_EGRESS, }; let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupSkbLink::new(CgroupSkbLinkInner::Fd(FdLink::new( link_fd, )))) } else { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data .links .insert(CgroupSkbLink::new(CgroupSkbLinkInner::ProgAttach( ProgAttachLink::new(prog_fd, cgroup_fd, attach_type), ))) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: CgroupSkbLinkId) -> Result<CgroupSkbLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [CgroupSkb::attach]. pub fn detach(&mut self, link_id: CgroupSkbLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupSkbLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupSkbLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupSkbLinkInner { type Id = CgroupSkbLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupSkbLinkInner::Fd(fd) => CgroupSkbLinkIdInner::Fd(fd.id()), CgroupSkbLinkInner::ProgAttach(p) => CgroupSkbLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupSkbLinkInner::Fd(fd) => fd.detach(), CgroupSkbLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupSkb] programs. CgroupSkbLink, /// The type returned by [CgroupSkb::attach]. Can be passed to [CgroupSkb::detach]. CgroupSkbLinkId, CgroupSkbLinkInner, CgroupSkbLinkIdInner ); /// Defines where to attach a [`CgroupSkb`] program. #[derive(Copy, Clone, Debug)] pub enum CgroupSkbAttachType { /// Attach to ingress. Ingress, /// Attach to egress. Egress, } <file_sep>/aya/src/generated/mod.rs #![allow( dead_code, non_camel_case_types, non_snake_case, clippy::all, missing_docs )] mod btf_internal_bindings; #[cfg(target_arch = "aarch64")] mod linux_bindings_aarch64; #[cfg(target_arch = "arm")] mod linux_bindings_armv7; #[cfg(target_arch = "riscv64")] mod linux_bindings_riscv64; #[cfg(target_arch = "x86_64")] mod linux_bindings_x86_64; pub use btf_internal_bindings::*; #[cfg(target_arch = "x86_64")] pub use linux_bindings_x86_64::*; #[cfg(target_arch = "arm")] pub use linux_bindings_armv7::*; #[cfg(target_arch = "aarch64")] pub use linux_bindings_aarch64::*; #[cfg(target_arch = "riscv64")] pub use linux_bindings_riscv64::*; <file_sep>/test/integration-ebpf/Cargo.toml [package] name = "integration-ebpf" version = "0.1.0" edition = "2021" publish = false [dependencies] aya-bpf = { path = "../../bpf/aya-bpf" } [[bin]] name = "map_test" path = "src/map_test.rs" [[bin]] name = "name_test" path = "src/name_test.rs" [[bin]] name = "pass" path = "src/pass.rs" [[bin]] name = "test" path = "src/test.rs" <file_sep>/bpf/aya-bpf-bindings/src/armv7/bindings.rs #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit<Storage> { storage: Storage, } impl<Storage> __BindgenBitfieldUnit<Storage> { #[inline] pub const fn new(storage: Storage) -> Self { Self { storage } } } impl<Storage> __BindgenBitfieldUnit<Storage> where Storage: AsRef<[u8]> + AsMut<[u8]>, { #[inline] pub fn get_bit(&self, index: usize) -> bool { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; let byte = self.storage.as_ref()[byte_index]; let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; byte & mask == mask } #[inline] pub fn set_bit(&mut self, index: usize, val: bool) { debug_assert!(index / 8 < self.storage.as_ref().len()); let byte_index = index / 8; let byte = &mut self.storage.as_mut()[byte_index]; let bit_index = if cfg!(target_endian = "big") { 7 - (index % 8) } else { index % 8 }; let mask = 1 << bit_index; if val { *byte |= mask; } else { *byte &= !mask; } } #[inline] pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); let mut val = 0; for i in 0..(bit_width as usize) { if self.get_bit(i + bit_offset) { let index = if cfg!(target_endian = "big") { bit_width as usize - 1 - i } else { i }; val |= 1 << index; } } val } #[inline] pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); for i in 0..(bit_width as usize) { let mask = 1 << i; let val_bit_is_set = val & mask == mask; let index = if cfg!(target_endian = "big") { bit_width as usize - 1 - i } else { i }; self.set_bit(index + bit_offset, val_bit_is_set); } } } #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::core::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayField(::core::marker::PhantomData, []) } #[inline] pub fn as_ptr(&self) -> *const T { self as *const _ as *const T } #[inline] pub fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut T } #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { ::core::slice::from_raw_parts(self.as_ptr(), len) } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { ::core::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } impl<T> ::core::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.write_str("__IncompleteArrayField") } } pub const BPF_LD: u32 = 0; pub const BPF_LDX: u32 = 1; pub const BPF_ST: u32 = 2; pub const BPF_STX: u32 = 3; pub const BPF_ALU: u32 = 4; pub const BPF_JMP: u32 = 5; pub const BPF_RET: u32 = 6; pub const BPF_MISC: u32 = 7; pub const BPF_W: u32 = 0; pub const BPF_H: u32 = 8; pub const BPF_B: u32 = 16; pub const BPF_IMM: u32 = 0; pub const BPF_ABS: u32 = 32; pub const BPF_IND: u32 = 64; pub const BPF_MEM: u32 = 96; pub const BPF_LEN: u32 = 128; pub const BPF_MSH: u32 = 160; pub const BPF_ADD: u32 = 0; pub const BPF_SUB: u32 = 16; pub const BPF_MUL: u32 = 32; pub const BPF_DIV: u32 = 48; pub const BPF_OR: u32 = 64; pub const BPF_AND: u32 = 80; pub const BPF_LSH: u32 = 96; pub const BPF_RSH: u32 = 112; pub const BPF_NEG: u32 = 128; pub const BPF_MOD: u32 = 144; pub const BPF_XOR: u32 = 160; pub const BPF_JA: u32 = 0; pub const BPF_JEQ: u32 = 16; pub const BPF_JGT: u32 = 32; pub const BPF_JGE: u32 = 48; pub const BPF_JSET: u32 = 64; pub const BPF_K: u32 = 0; pub const BPF_X: u32 = 8; pub const BPF_MAXINSNS: u32 = 4096; pub const BPF_JMP32: u32 = 6; pub const BPF_ALU64: u32 = 7; pub const BPF_DW: u32 = 24; pub const BPF_ATOMIC: u32 = 192; pub const BPF_XADD: u32 = 192; pub const BPF_MOV: u32 = 176; pub const BPF_ARSH: u32 = 192; pub const BPF_END: u32 = 208; pub const BPF_TO_LE: u32 = 0; pub const BPF_TO_BE: u32 = 8; pub const BPF_FROM_LE: u32 = 0; pub const BPF_FROM_BE: u32 = 8; pub const BPF_JNE: u32 = 80; pub const BPF_JLT: u32 = 160; pub const BPF_JLE: u32 = 176; pub const BPF_JSGT: u32 = 96; pub const BPF_JSGE: u32 = 112; pub const BPF_JSLT: u32 = 192; pub const BPF_JSLE: u32 = 208; pub const BPF_CALL: u32 = 128; pub const BPF_EXIT: u32 = 144; pub const BPF_FETCH: u32 = 1; pub const BPF_XCHG: u32 = 225; pub const BPF_CMPXCHG: u32 = 241; pub const BPF_F_ALLOW_OVERRIDE: u32 = 1; pub const BPF_F_ALLOW_MULTI: u32 = 2; pub const BPF_F_REPLACE: u32 = 4; pub const BPF_F_STRICT_ALIGNMENT: u32 = 1; pub const BPF_F_ANY_ALIGNMENT: u32 = 2; pub const BPF_F_TEST_RND_HI32: u32 = 4; pub const BPF_F_TEST_STATE_FREQ: u32 = 8; pub const BPF_F_SLEEPABLE: u32 = 16; pub const BPF_F_XDP_HAS_FRAGS: u32 = 32; pub const BPF_F_KPROBE_MULTI_RETURN: u32 = 1; pub const BPF_PSEUDO_MAP_FD: u32 = 1; pub const BPF_PSEUDO_MAP_IDX: u32 = 5; pub const BPF_PSEUDO_MAP_VALUE: u32 = 2; pub const BPF_PSEUDO_MAP_IDX_VALUE: u32 = 6; pub const BPF_PSEUDO_BTF_ID: u32 = 3; pub const BPF_PSEUDO_FUNC: u32 = 4; pub const BPF_PSEUDO_CALL: u32 = 1; pub const BPF_PSEUDO_KFUNC_CALL: u32 = 2; pub const BPF_F_QUERY_EFFECTIVE: u32 = 1; pub const BPF_F_TEST_RUN_ON_CPU: u32 = 1; pub const BPF_F_TEST_XDP_LIVE_FRAMES: u32 = 2; pub const BPF_BUILD_ID_SIZE: u32 = 20; pub const BPF_OBJ_NAME_LEN: u32 = 16; pub const BPF_TAG_SIZE: u32 = 8; pub const SOL_SOCKET: u32 = 1; pub const SO_DEBUG: u32 = 1; pub const SO_REUSEADDR: u32 = 2; pub const SO_TYPE: u32 = 3; pub const SO_ERROR: u32 = 4; pub const SO_DONTROUTE: u32 = 5; pub const SO_BROADCAST: u32 = 6; pub const SO_SNDBUF: u32 = 7; pub const SO_RCVBUF: u32 = 8; pub const SO_SNDBUFFORCE: u32 = 32; pub const SO_RCVBUFFORCE: u32 = 33; pub const SO_KEEPALIVE: u32 = 9; pub const SO_OOBINLINE: u32 = 10; pub const SO_NO_CHECK: u32 = 11; pub const SO_PRIORITY: u32 = 12; pub const SO_LINGER: u32 = 13; pub const SO_BSDCOMPAT: u32 = 14; pub const SO_REUSEPORT: u32 = 15; pub const SO_PASSCRED: u32 = 16; pub const SO_PEERCRED: u32 = 17; pub const SO_RCVLOWAT: u32 = 18; pub const SO_SNDLOWAT: u32 = 19; pub const SO_RCVTIMEO_OLD: u32 = 20; pub const SO_SNDTIMEO_OLD: u32 = 21; pub const SO_SECURITY_AUTHENTICATION: u32 = 22; pub const SO_SECURITY_ENCRYPTION_TRANSPORT: u32 = 23; pub const SO_SECURITY_ENCRYPTION_NETWORK: u32 = 24; pub const SO_BINDTODEVICE: u32 = 25; pub const SO_ATTACH_FILTER: u32 = 26; pub const SO_DETACH_FILTER: u32 = 27; pub const SO_GET_FILTER: u32 = 26; pub const SO_PEERNAME: u32 = 28; pub const SO_ACCEPTCONN: u32 = 30; pub const SO_PEERSEC: u32 = 31; pub const SO_PASSSEC: u32 = 34; pub const SO_MARK: u32 = 36; pub const SO_PROTOCOL: u32 = 38; pub const SO_DOMAIN: u32 = 39; pub const SO_RXQ_OVFL: u32 = 40; pub const SO_WIFI_STATUS: u32 = 41; pub const SO_PEEK_OFF: u32 = 42; pub const SO_NOFCS: u32 = 43; pub const SO_LOCK_FILTER: u32 = 44; pub const SO_SELECT_ERR_QUEUE: u32 = 45; pub const SO_BUSY_POLL: u32 = 46; pub const SO_MAX_PACING_RATE: u32 = 47; pub const SO_BPF_EXTENSIONS: u32 = 48; pub const SO_INCOMING_CPU: u32 = 49; pub const SO_ATTACH_BPF: u32 = 50; pub const SO_DETACH_BPF: u32 = 27; pub const SO_ATTACH_REUSEPORT_CBPF: u32 = 51; pub const SO_ATTACH_REUSEPORT_EBPF: u32 = 52; pub const SO_CNX_ADVICE: u32 = 53; pub const SO_MEMINFO: u32 = 55; pub const SO_INCOMING_NAPI_ID: u32 = 56; pub const SO_COOKIE: u32 = 57; pub const SO_PEERGROUPS: u32 = 59; pub const SO_ZEROCOPY: u32 = 60; pub const SO_TXTIME: u32 = 61; pub const SO_BINDTOIFINDEX: u32 = 62; pub const SO_TIMESTAMP_OLD: u32 = 29; pub const SO_TIMESTAMPNS_OLD: u32 = 35; pub const SO_TIMESTAMPING_OLD: u32 = 37; pub const SO_TIMESTAMP_NEW: u32 = 63; pub const SO_TIMESTAMPNS_NEW: u32 = 64; pub const SO_TIMESTAMPING_NEW: u32 = 65; pub const SO_RCVTIMEO_NEW: u32 = 66; pub const SO_SNDTIMEO_NEW: u32 = 67; pub const SO_DETACH_REUSEPORT_BPF: u32 = 68; pub const TC_ACT_UNSPEC: i32 = -1; pub const TC_ACT_OK: u32 = 0; pub const TC_ACT_RECLASSIFY: u32 = 1; pub const TC_ACT_SHOT: u32 = 2; pub const TC_ACT_PIPE: u32 = 3; pub const TC_ACT_STOLEN: u32 = 4; pub const TC_ACT_QUEUED: u32 = 5; pub const TC_ACT_REPEAT: u32 = 6; pub const TC_ACT_REDIRECT: u32 = 7; pub const TC_ACT_TRAP: u32 = 8; pub const TC_ACT_VALUE_MAX: u32 = 8; pub const TC_ACT_EXT_VAL_MASK: u32 = 268435455; pub type __u8 = ::aya_bpf_cty::c_uchar; pub type __s16 = ::aya_bpf_cty::c_short; pub type __u16 = ::aya_bpf_cty::c_ushort; pub type __s32 = ::aya_bpf_cty::c_int; pub type __u32 = ::aya_bpf_cty::c_uint; pub type __s64 = ::aya_bpf_cty::c_longlong; pub type __u64 = ::aya_bpf_cty::c_ulonglong; pub type __be16 = __u16; pub type __be32 = __u32; pub type __wsum = __u32; pub const BPF_REG_0: _bindgen_ty_1 = 0; pub const BPF_REG_1: _bindgen_ty_1 = 1; pub const BPF_REG_2: _bindgen_ty_1 = 2; pub const BPF_REG_3: _bindgen_ty_1 = 3; pub const BPF_REG_4: _bindgen_ty_1 = 4; pub const BPF_REG_5: _bindgen_ty_1 = 5; pub const BPF_REG_6: _bindgen_ty_1 = 6; pub const BPF_REG_7: _bindgen_ty_1 = 7; pub const BPF_REG_8: _bindgen_ty_1 = 8; pub const BPF_REG_9: _bindgen_ty_1 = 9; pub const BPF_REG_10: _bindgen_ty_1 = 10; pub const __MAX_BPF_REG: _bindgen_ty_1 = 11; pub type _bindgen_ty_1 = ::aya_bpf_cty::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_insn { pub code: __u8, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>, pub off: __s16, pub imm: __s32, } impl bpf_insn { #[inline] pub fn dst_reg(&self) -> __u8 { unsafe { ::core::mem::transmute(self._bitfield_1.get(0usize, 4u8) as u8) } } #[inline] pub fn set_dst_reg(&mut self, val: __u8) { unsafe { let val: u8 = ::core::mem::transmute(val); self._bitfield_1.set(0usize, 4u8, val as u64) } } #[inline] pub fn src_reg(&self) -> __u8 { unsafe { ::core::mem::transmute(self._bitfield_1.get(4usize, 4u8) as u8) } } #[inline] pub fn set_src_reg(&mut self, val: __u8) { unsafe { let val: u8 = ::core::mem::transmute(val); self._bitfield_1.set(4usize, 4u8, val as u64) } } #[inline] pub fn new_bitfield_1(dst_reg: __u8, src_reg: __u8) -> __BindgenBitfieldUnit<[u8; 1usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default(); __bindgen_bitfield_unit.set(0usize, 4u8, { let dst_reg: u8 = unsafe { ::core::mem::transmute(dst_reg) }; dst_reg as u64 }); __bindgen_bitfield_unit.set(4usize, 4u8, { let src_reg: u8 = unsafe { ::core::mem::transmute(src_reg) }; src_reg as u64 }); __bindgen_bitfield_unit } } #[repr(C)] pub struct bpf_lpm_trie_key { pub prefixlen: __u32, pub data: __IncompleteArrayField<__u8>, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_cgroup_storage_key { pub cgroup_inode_id: __u64, pub attach_type: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_iter_link_info { pub map: bpf_iter_link_info__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_iter_link_info__bindgen_ty_1 { pub map_fd: __u32, } pub mod bpf_cmd { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_MAP_CREATE: Type = 0; pub const BPF_MAP_LOOKUP_ELEM: Type = 1; pub const BPF_MAP_UPDATE_ELEM: Type = 2; pub const BPF_MAP_DELETE_ELEM: Type = 3; pub const BPF_MAP_GET_NEXT_KEY: Type = 4; pub const BPF_PROG_LOAD: Type = 5; pub const BPF_OBJ_PIN: Type = 6; pub const BPF_OBJ_GET: Type = 7; pub const BPF_PROG_ATTACH: Type = 8; pub const BPF_PROG_DETACH: Type = 9; pub const BPF_PROG_TEST_RUN: Type = 10; pub const BPF_PROG_RUN: Type = 10; pub const BPF_PROG_GET_NEXT_ID: Type = 11; pub const BPF_MAP_GET_NEXT_ID: Type = 12; pub const BPF_PROG_GET_FD_BY_ID: Type = 13; pub const BPF_MAP_GET_FD_BY_ID: Type = 14; pub const BPF_OBJ_GET_INFO_BY_FD: Type = 15; pub const BPF_PROG_QUERY: Type = 16; pub const BPF_RAW_TRACEPOINT_OPEN: Type = 17; pub const BPF_BTF_LOAD: Type = 18; pub const BPF_BTF_GET_FD_BY_ID: Type = 19; pub const BPF_TASK_FD_QUERY: Type = 20; pub const BPF_MAP_LOOKUP_AND_DELETE_ELEM: Type = 21; pub const BPF_MAP_FREEZE: Type = 22; pub const BPF_BTF_GET_NEXT_ID: Type = 23; pub const BPF_MAP_LOOKUP_BATCH: Type = 24; pub const BPF_MAP_LOOKUP_AND_DELETE_BATCH: Type = 25; pub const BPF_MAP_UPDATE_BATCH: Type = 26; pub const BPF_MAP_DELETE_BATCH: Type = 27; pub const BPF_LINK_CREATE: Type = 28; pub const BPF_LINK_UPDATE: Type = 29; pub const BPF_LINK_GET_FD_BY_ID: Type = 30; pub const BPF_LINK_GET_NEXT_ID: Type = 31; pub const BPF_ENABLE_STATS: Type = 32; pub const BPF_ITER_CREATE: Type = 33; pub const BPF_LINK_DETACH: Type = 34; pub const BPF_PROG_BIND_MAP: Type = 35; } pub mod bpf_map_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_MAP_TYPE_UNSPEC: Type = 0; pub const BPF_MAP_TYPE_HASH: Type = 1; pub const BPF_MAP_TYPE_ARRAY: Type = 2; pub const BPF_MAP_TYPE_PROG_ARRAY: Type = 3; pub const BPF_MAP_TYPE_PERF_EVENT_ARRAY: Type = 4; pub const BPF_MAP_TYPE_PERCPU_HASH: Type = 5; pub const BPF_MAP_TYPE_PERCPU_ARRAY: Type = 6; pub const BPF_MAP_TYPE_STACK_TRACE: Type = 7; pub const BPF_MAP_TYPE_CGROUP_ARRAY: Type = 8; pub const BPF_MAP_TYPE_LRU_HASH: Type = 9; pub const BPF_MAP_TYPE_LRU_PERCPU_HASH: Type = 10; pub const BPF_MAP_TYPE_LPM_TRIE: Type = 11; pub const BPF_MAP_TYPE_ARRAY_OF_MAPS: Type = 12; pub const BPF_MAP_TYPE_HASH_OF_MAPS: Type = 13; pub const BPF_MAP_TYPE_DEVMAP: Type = 14; pub const BPF_MAP_TYPE_SOCKMAP: Type = 15; pub const BPF_MAP_TYPE_CPUMAP: Type = 16; pub const BPF_MAP_TYPE_XSKMAP: Type = 17; pub const BPF_MAP_TYPE_SOCKHASH: Type = 18; pub const BPF_MAP_TYPE_CGROUP_STORAGE: Type = 19; pub const BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: Type = 20; pub const BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: Type = 21; pub const BPF_MAP_TYPE_QUEUE: Type = 22; pub const BPF_MAP_TYPE_STACK: Type = 23; pub const BPF_MAP_TYPE_SK_STORAGE: Type = 24; pub const BPF_MAP_TYPE_DEVMAP_HASH: Type = 25; pub const BPF_MAP_TYPE_STRUCT_OPS: Type = 26; pub const BPF_MAP_TYPE_RINGBUF: Type = 27; pub const BPF_MAP_TYPE_INODE_STORAGE: Type = 28; pub const BPF_MAP_TYPE_TASK_STORAGE: Type = 29; pub const BPF_MAP_TYPE_BLOOM_FILTER: Type = 30; } pub mod bpf_prog_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_PROG_TYPE_UNSPEC: Type = 0; pub const BPF_PROG_TYPE_SOCKET_FILTER: Type = 1; pub const BPF_PROG_TYPE_KPROBE: Type = 2; pub const BPF_PROG_TYPE_SCHED_CLS: Type = 3; pub const BPF_PROG_TYPE_SCHED_ACT: Type = 4; pub const BPF_PROG_TYPE_TRACEPOINT: Type = 5; pub const BPF_PROG_TYPE_XDP: Type = 6; pub const BPF_PROG_TYPE_PERF_EVENT: Type = 7; pub const BPF_PROG_TYPE_CGROUP_SKB: Type = 8; pub const BPF_PROG_TYPE_CGROUP_SOCK: Type = 9; pub const BPF_PROG_TYPE_LWT_IN: Type = 10; pub const BPF_PROG_TYPE_LWT_OUT: Type = 11; pub const BPF_PROG_TYPE_LWT_XMIT: Type = 12; pub const BPF_PROG_TYPE_SOCK_OPS: Type = 13; pub const BPF_PROG_TYPE_SK_SKB: Type = 14; pub const BPF_PROG_TYPE_CGROUP_DEVICE: Type = 15; pub const BPF_PROG_TYPE_SK_MSG: Type = 16; pub const BPF_PROG_TYPE_RAW_TRACEPOINT: Type = 17; pub const BPF_PROG_TYPE_CGROUP_SOCK_ADDR: Type = 18; pub const BPF_PROG_TYPE_LWT_SEG6LOCAL: Type = 19; pub const BPF_PROG_TYPE_LIRC_MODE2: Type = 20; pub const BPF_PROG_TYPE_SK_REUSEPORT: Type = 21; pub const BPF_PROG_TYPE_FLOW_DISSECTOR: Type = 22; pub const BPF_PROG_TYPE_CGROUP_SYSCTL: Type = 23; pub const BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: Type = 24; pub const BPF_PROG_TYPE_CGROUP_SOCKOPT: Type = 25; pub const BPF_PROG_TYPE_TRACING: Type = 26; pub const BPF_PROG_TYPE_STRUCT_OPS: Type = 27; pub const BPF_PROG_TYPE_EXT: Type = 28; pub const BPF_PROG_TYPE_LSM: Type = 29; pub const BPF_PROG_TYPE_SK_LOOKUP: Type = 30; pub const BPF_PROG_TYPE_SYSCALL: Type = 31; } pub mod bpf_attach_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_CGROUP_INET_INGRESS: Type = 0; pub const BPF_CGROUP_INET_EGRESS: Type = 1; pub const BPF_CGROUP_INET_SOCK_CREATE: Type = 2; pub const BPF_CGROUP_SOCK_OPS: Type = 3; pub const BPF_SK_SKB_STREAM_PARSER: Type = 4; pub const BPF_SK_SKB_STREAM_VERDICT: Type = 5; pub const BPF_CGROUP_DEVICE: Type = 6; pub const BPF_SK_MSG_VERDICT: Type = 7; pub const BPF_CGROUP_INET4_BIND: Type = 8; pub const BPF_CGROUP_INET6_BIND: Type = 9; pub const BPF_CGROUP_INET4_CONNECT: Type = 10; pub const BPF_CGROUP_INET6_CONNECT: Type = 11; pub const BPF_CGROUP_INET4_POST_BIND: Type = 12; pub const BPF_CGROUP_INET6_POST_BIND: Type = 13; pub const BPF_CGROUP_UDP4_SENDMSG: Type = 14; pub const BPF_CGROUP_UDP6_SENDMSG: Type = 15; pub const BPF_LIRC_MODE2: Type = 16; pub const BPF_FLOW_DISSECTOR: Type = 17; pub const BPF_CGROUP_SYSCTL: Type = 18; pub const BPF_CGROUP_UDP4_RECVMSG: Type = 19; pub const BPF_CGROUP_UDP6_RECVMSG: Type = 20; pub const BPF_CGROUP_GETSOCKOPT: Type = 21; pub const BPF_CGROUP_SETSOCKOPT: Type = 22; pub const BPF_TRACE_RAW_TP: Type = 23; pub const BPF_TRACE_FENTRY: Type = 24; pub const BPF_TRACE_FEXIT: Type = 25; pub const BPF_MODIFY_RETURN: Type = 26; pub const BPF_LSM_MAC: Type = 27; pub const BPF_TRACE_ITER: Type = 28; pub const BPF_CGROUP_INET4_GETPEERNAME: Type = 29; pub const BPF_CGROUP_INET6_GETPEERNAME: Type = 30; pub const BPF_CGROUP_INET4_GETSOCKNAME: Type = 31; pub const BPF_CGROUP_INET6_GETSOCKNAME: Type = 32; pub const BPF_XDP_DEVMAP: Type = 33; pub const BPF_CGROUP_INET_SOCK_RELEASE: Type = 34; pub const BPF_XDP_CPUMAP: Type = 35; pub const BPF_SK_LOOKUP: Type = 36; pub const BPF_XDP: Type = 37; pub const BPF_SK_SKB_VERDICT: Type = 38; pub const BPF_SK_REUSEPORT_SELECT: Type = 39; pub const BPF_SK_REUSEPORT_SELECT_OR_MIGRATE: Type = 40; pub const BPF_PERF_EVENT: Type = 41; pub const BPF_TRACE_KPROBE_MULTI: Type = 42; pub const BPF_LSM_CGROUP: Type = 43; pub const __MAX_BPF_ATTACH_TYPE: Type = 44; } pub mod bpf_link_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_LINK_TYPE_UNSPEC: Type = 0; pub const BPF_LINK_TYPE_RAW_TRACEPOINT: Type = 1; pub const BPF_LINK_TYPE_TRACING: Type = 2; pub const BPF_LINK_TYPE_CGROUP: Type = 3; pub const BPF_LINK_TYPE_ITER: Type = 4; pub const BPF_LINK_TYPE_NETNS: Type = 5; pub const BPF_LINK_TYPE_XDP: Type = 6; pub const BPF_LINK_TYPE_PERF_EVENT: Type = 7; pub const BPF_LINK_TYPE_KPROBE_MULTI: Type = 8; pub const BPF_LINK_TYPE_STRUCT_OPS: Type = 9; pub const MAX_BPF_LINK_TYPE: Type = 10; } pub const BPF_ANY: _bindgen_ty_2 = 0; pub const BPF_NOEXIST: _bindgen_ty_2 = 1; pub const BPF_EXIST: _bindgen_ty_2 = 2; pub const BPF_F_LOCK: _bindgen_ty_2 = 4; pub type _bindgen_ty_2 = ::aya_bpf_cty::c_uint; pub const BPF_F_NO_PREALLOC: _bindgen_ty_3 = 1; pub const BPF_F_NO_COMMON_LRU: _bindgen_ty_3 = 2; pub const BPF_F_NUMA_NODE: _bindgen_ty_3 = 4; pub const BPF_F_RDONLY: _bindgen_ty_3 = 8; pub const BPF_F_WRONLY: _bindgen_ty_3 = 16; pub const BPF_F_STACK_BUILD_ID: _bindgen_ty_3 = 32; pub const BPF_F_ZERO_SEED: _bindgen_ty_3 = 64; pub const BPF_F_RDONLY_PROG: _bindgen_ty_3 = 128; pub const BPF_F_WRONLY_PROG: _bindgen_ty_3 = 256; pub const BPF_F_CLONE: _bindgen_ty_3 = 512; pub const BPF_F_MMAPABLE: _bindgen_ty_3 = 1024; pub const BPF_F_PRESERVE_ELEMS: _bindgen_ty_3 = 2048; pub const BPF_F_INNER_MAP: _bindgen_ty_3 = 4096; pub type _bindgen_ty_3 = ::aya_bpf_cty::c_uint; pub mod bpf_stats_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_STATS_RUN_TIME: Type = 0; } pub mod bpf_stack_build_id_status { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_STACK_BUILD_ID_EMPTY: Type = 0; pub const BPF_STACK_BUILD_ID_VALID: Type = 1; pub const BPF_STACK_BUILD_ID_IP: Type = 2; } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_stack_build_id { pub status: __s32, pub build_id: [::aya_bpf_cty::c_uchar; 20usize], pub __bindgen_anon_1: bpf_stack_build_id__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_stack_build_id__bindgen_ty_1 { pub offset: __u64, pub ip: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr { pub __bindgen_anon_1: bpf_attr__bindgen_ty_1, pub __bindgen_anon_2: bpf_attr__bindgen_ty_2, pub batch: bpf_attr__bindgen_ty_3, pub __bindgen_anon_3: bpf_attr__bindgen_ty_4, pub __bindgen_anon_4: bpf_attr__bindgen_ty_5, pub __bindgen_anon_5: bpf_attr__bindgen_ty_6, pub test: bpf_attr__bindgen_ty_7, pub __bindgen_anon_6: bpf_attr__bindgen_ty_8, pub info: bpf_attr__bindgen_ty_9, pub query: bpf_attr__bindgen_ty_10, pub raw_tracepoint: bpf_attr__bindgen_ty_11, pub __bindgen_anon_7: bpf_attr__bindgen_ty_12, pub task_fd_query: bpf_attr__bindgen_ty_13, pub link_create: bpf_attr__bindgen_ty_14, pub link_update: bpf_attr__bindgen_ty_15, pub link_detach: bpf_attr__bindgen_ty_16, pub enable_stats: bpf_attr__bindgen_ty_17, pub iter_create: bpf_attr__bindgen_ty_18, pub prog_bind_map: bpf_attr__bindgen_ty_19, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_1 { pub map_type: __u32, pub key_size: __u32, pub value_size: __u32, pub max_entries: __u32, pub map_flags: __u32, pub inner_map_fd: __u32, pub numa_node: __u32, pub map_name: [::aya_bpf_cty::c_char; 16usize], pub map_ifindex: __u32, pub btf_fd: __u32, pub btf_key_type_id: __u32, pub btf_value_type_id: __u32, pub btf_vmlinux_value_type_id: __u32, pub map_extra: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_2 { pub map_fd: __u32, pub key: __u64, pub __bindgen_anon_1: bpf_attr__bindgen_ty_2__bindgen_ty_1, pub flags: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_2__bindgen_ty_1 { pub value: __u64, pub next_key: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_3 { pub in_batch: __u64, pub out_batch: __u64, pub keys: __u64, pub values: __u64, pub count: __u32, pub map_fd: __u32, pub elem_flags: __u64, pub flags: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_4 { pub prog_type: __u32, pub insn_cnt: __u32, pub insns: __u64, pub license: __u64, pub log_level: __u32, pub log_size: __u32, pub log_buf: __u64, pub kern_version: __u32, pub prog_flags: __u32, pub prog_name: [::aya_bpf_cty::c_char; 16usize], pub prog_ifindex: __u32, pub expected_attach_type: __u32, pub prog_btf_fd: __u32, pub func_info_rec_size: __u32, pub func_info: __u64, pub func_info_cnt: __u32, pub line_info_rec_size: __u32, pub line_info: __u64, pub line_info_cnt: __u32, pub attach_btf_id: __u32, pub __bindgen_anon_1: bpf_attr__bindgen_ty_4__bindgen_ty_1, pub core_relo_cnt: __u32, pub fd_array: __u64, pub core_relos: __u64, pub core_relo_rec_size: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_4__bindgen_ty_1 { pub attach_prog_fd: __u32, pub attach_btf_obj_fd: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_5 { pub pathname: __u64, pub bpf_fd: __u32, pub file_flags: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_6 { pub target_fd: __u32, pub attach_bpf_fd: __u32, pub attach_type: __u32, pub attach_flags: __u32, pub replace_bpf_fd: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_7 { pub prog_fd: __u32, pub retval: __u32, pub data_size_in: __u32, pub data_size_out: __u32, pub data_in: __u64, pub data_out: __u64, pub repeat: __u32, pub duration: __u32, pub ctx_size_in: __u32, pub ctx_size_out: __u32, pub ctx_in: __u64, pub ctx_out: __u64, pub flags: __u32, pub cpu: __u32, pub batch_size: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_8 { pub __bindgen_anon_1: bpf_attr__bindgen_ty_8__bindgen_ty_1, pub next_id: __u32, pub open_flags: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_8__bindgen_ty_1 { pub start_id: __u32, pub prog_id: __u32, pub map_id: __u32, pub btf_id: __u32, pub link_id: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_9 { pub bpf_fd: __u32, pub info_len: __u32, pub info: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_10 { pub target_fd: __u32, pub attach_type: __u32, pub query_flags: __u32, pub attach_flags: __u32, pub prog_ids: __u64, pub prog_cnt: __u32, pub prog_attach_flags: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_11 { pub name: __u64, pub prog_fd: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_12 { pub btf: __u64, pub btf_log_buf: __u64, pub btf_size: __u32, pub btf_log_size: __u32, pub btf_log_level: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_13 { pub pid: __u32, pub fd: __u32, pub flags: __u32, pub buf_len: __u32, pub buf: __u64, pub prog_id: __u32, pub fd_type: __u32, pub probe_offset: __u64, pub probe_addr: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_14 { pub prog_fd: __u32, pub __bindgen_anon_1: bpf_attr__bindgen_ty_14__bindgen_ty_1, pub attach_type: __u32, pub flags: __u32, pub __bindgen_anon_2: bpf_attr__bindgen_ty_14__bindgen_ty_2, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_14__bindgen_ty_1 { pub target_fd: __u32, pub target_ifindex: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_attr__bindgen_ty_14__bindgen_ty_2 { pub target_btf_id: __u32, pub __bindgen_anon_1: bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_1, pub perf_event: bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_2, pub kprobe_multi: bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_3, pub tracing: bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_4, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_1 { pub iter_info: __u64, pub iter_info_len: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_2 { pub bpf_cookie: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_3 { pub flags: __u32, pub cnt: __u32, pub syms: __u64, pub addrs: __u64, pub cookies: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_14__bindgen_ty_2__bindgen_ty_4 { pub target_btf_id: __u32, pub cookie: __u64, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_15 { pub link_fd: __u32, pub new_prog_fd: __u32, pub flags: __u32, pub old_prog_fd: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_16 { pub link_fd: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_17 { pub type_: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_18 { pub link_fd: __u32, pub flags: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_attr__bindgen_ty_19 { pub prog_fd: __u32, pub map_fd: __u32, pub flags: __u32, } pub mod bpf_func_id { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_FUNC_unspec: Type = 0; pub const BPF_FUNC_map_lookup_elem: Type = 1; pub const BPF_FUNC_map_update_elem: Type = 2; pub const BPF_FUNC_map_delete_elem: Type = 3; pub const BPF_FUNC_probe_read: Type = 4; pub const BPF_FUNC_ktime_get_ns: Type = 5; pub const BPF_FUNC_trace_printk: Type = 6; pub const BPF_FUNC_get_prandom_u32: Type = 7; pub const BPF_FUNC_get_smp_processor_id: Type = 8; pub const BPF_FUNC_skb_store_bytes: Type = 9; pub const BPF_FUNC_l3_csum_replace: Type = 10; pub const BPF_FUNC_l4_csum_replace: Type = 11; pub const BPF_FUNC_tail_call: Type = 12; pub const BPF_FUNC_clone_redirect: Type = 13; pub const BPF_FUNC_get_current_pid_tgid: Type = 14; pub const BPF_FUNC_get_current_uid_gid: Type = 15; pub const BPF_FUNC_get_current_comm: Type = 16; pub const BPF_FUNC_get_cgroup_classid: Type = 17; pub const BPF_FUNC_skb_vlan_push: Type = 18; pub const BPF_FUNC_skb_vlan_pop: Type = 19; pub const BPF_FUNC_skb_get_tunnel_key: Type = 20; pub const BPF_FUNC_skb_set_tunnel_key: Type = 21; pub const BPF_FUNC_perf_event_read: Type = 22; pub const BPF_FUNC_redirect: Type = 23; pub const BPF_FUNC_get_route_realm: Type = 24; pub const BPF_FUNC_perf_event_output: Type = 25; pub const BPF_FUNC_skb_load_bytes: Type = 26; pub const BPF_FUNC_get_stackid: Type = 27; pub const BPF_FUNC_csum_diff: Type = 28; pub const BPF_FUNC_skb_get_tunnel_opt: Type = 29; pub const BPF_FUNC_skb_set_tunnel_opt: Type = 30; pub const BPF_FUNC_skb_change_proto: Type = 31; pub const BPF_FUNC_skb_change_type: Type = 32; pub const BPF_FUNC_skb_under_cgroup: Type = 33; pub const BPF_FUNC_get_hash_recalc: Type = 34; pub const BPF_FUNC_get_current_task: Type = 35; pub const BPF_FUNC_probe_write_user: Type = 36; pub const BPF_FUNC_current_task_under_cgroup: Type = 37; pub const BPF_FUNC_skb_change_tail: Type = 38; pub const BPF_FUNC_skb_pull_data: Type = 39; pub const BPF_FUNC_csum_update: Type = 40; pub const BPF_FUNC_set_hash_invalid: Type = 41; pub const BPF_FUNC_get_numa_node_id: Type = 42; pub const BPF_FUNC_skb_change_head: Type = 43; pub const BPF_FUNC_xdp_adjust_head: Type = 44; pub const BPF_FUNC_probe_read_str: Type = 45; pub const BPF_FUNC_get_socket_cookie: Type = 46; pub const BPF_FUNC_get_socket_uid: Type = 47; pub const BPF_FUNC_set_hash: Type = 48; pub const BPF_FUNC_setsockopt: Type = 49; pub const BPF_FUNC_skb_adjust_room: Type = 50; pub const BPF_FUNC_redirect_map: Type = 51; pub const BPF_FUNC_sk_redirect_map: Type = 52; pub const BPF_FUNC_sock_map_update: Type = 53; pub const BPF_FUNC_xdp_adjust_meta: Type = 54; pub const BPF_FUNC_perf_event_read_value: Type = 55; pub const BPF_FUNC_perf_prog_read_value: Type = 56; pub const BPF_FUNC_getsockopt: Type = 57; pub const BPF_FUNC_override_return: Type = 58; pub const BPF_FUNC_sock_ops_cb_flags_set: Type = 59; pub const BPF_FUNC_msg_redirect_map: Type = 60; pub const BPF_FUNC_msg_apply_bytes: Type = 61; pub const BPF_FUNC_msg_cork_bytes: Type = 62; pub const BPF_FUNC_msg_pull_data: Type = 63; pub const BPF_FUNC_bind: Type = 64; pub const BPF_FUNC_xdp_adjust_tail: Type = 65; pub const BPF_FUNC_skb_get_xfrm_state: Type = 66; pub const BPF_FUNC_get_stack: Type = 67; pub const BPF_FUNC_skb_load_bytes_relative: Type = 68; pub const BPF_FUNC_fib_lookup: Type = 69; pub const BPF_FUNC_sock_hash_update: Type = 70; pub const BPF_FUNC_msg_redirect_hash: Type = 71; pub const BPF_FUNC_sk_redirect_hash: Type = 72; pub const BPF_FUNC_lwt_push_encap: Type = 73; pub const BPF_FUNC_lwt_seg6_store_bytes: Type = 74; pub const BPF_FUNC_lwt_seg6_adjust_srh: Type = 75; pub const BPF_FUNC_lwt_seg6_action: Type = 76; pub const BPF_FUNC_rc_repeat: Type = 77; pub const BPF_FUNC_rc_keydown: Type = 78; pub const BPF_FUNC_skb_cgroup_id: Type = 79; pub const BPF_FUNC_get_current_cgroup_id: Type = 80; pub const BPF_FUNC_get_local_storage: Type = 81; pub const BPF_FUNC_sk_select_reuseport: Type = 82; pub const BPF_FUNC_skb_ancestor_cgroup_id: Type = 83; pub const BPF_FUNC_sk_lookup_tcp: Type = 84; pub const BPF_FUNC_sk_lookup_udp: Type = 85; pub const BPF_FUNC_sk_release: Type = 86; pub const BPF_FUNC_map_push_elem: Type = 87; pub const BPF_FUNC_map_pop_elem: Type = 88; pub const BPF_FUNC_map_peek_elem: Type = 89; pub const BPF_FUNC_msg_push_data: Type = 90; pub const BPF_FUNC_msg_pop_data: Type = 91; pub const BPF_FUNC_rc_pointer_rel: Type = 92; pub const BPF_FUNC_spin_lock: Type = 93; pub const BPF_FUNC_spin_unlock: Type = 94; pub const BPF_FUNC_sk_fullsock: Type = 95; pub const BPF_FUNC_tcp_sock: Type = 96; pub const BPF_FUNC_skb_ecn_set_ce: Type = 97; pub const BPF_FUNC_get_listener_sock: Type = 98; pub const BPF_FUNC_skc_lookup_tcp: Type = 99; pub const BPF_FUNC_tcp_check_syncookie: Type = 100; pub const BPF_FUNC_sysctl_get_name: Type = 101; pub const BPF_FUNC_sysctl_get_current_value: Type = 102; pub const BPF_FUNC_sysctl_get_new_value: Type = 103; pub const BPF_FUNC_sysctl_set_new_value: Type = 104; pub const BPF_FUNC_strtol: Type = 105; pub const BPF_FUNC_strtoul: Type = 106; pub const BPF_FUNC_sk_storage_get: Type = 107; pub const BPF_FUNC_sk_storage_delete: Type = 108; pub const BPF_FUNC_send_signal: Type = 109; pub const BPF_FUNC_tcp_gen_syncookie: Type = 110; pub const BPF_FUNC_skb_output: Type = 111; pub const BPF_FUNC_probe_read_user: Type = 112; pub const BPF_FUNC_probe_read_kernel: Type = 113; pub const BPF_FUNC_probe_read_user_str: Type = 114; pub const BPF_FUNC_probe_read_kernel_str: Type = 115; pub const BPF_FUNC_tcp_send_ack: Type = 116; pub const BPF_FUNC_send_signal_thread: Type = 117; pub const BPF_FUNC_jiffies64: Type = 118; pub const BPF_FUNC_read_branch_records: Type = 119; pub const BPF_FUNC_get_ns_current_pid_tgid: Type = 120; pub const BPF_FUNC_xdp_output: Type = 121; pub const BPF_FUNC_get_netns_cookie: Type = 122; pub const BPF_FUNC_get_current_ancestor_cgroup_id: Type = 123; pub const BPF_FUNC_sk_assign: Type = 124; pub const BPF_FUNC_ktime_get_boot_ns: Type = 125; pub const BPF_FUNC_seq_printf: Type = 126; pub const BPF_FUNC_seq_write: Type = 127; pub const BPF_FUNC_sk_cgroup_id: Type = 128; pub const BPF_FUNC_sk_ancestor_cgroup_id: Type = 129; pub const BPF_FUNC_ringbuf_output: Type = 130; pub const BPF_FUNC_ringbuf_reserve: Type = 131; pub const BPF_FUNC_ringbuf_submit: Type = 132; pub const BPF_FUNC_ringbuf_discard: Type = 133; pub const BPF_FUNC_ringbuf_query: Type = 134; pub const BPF_FUNC_csum_level: Type = 135; pub const BPF_FUNC_skc_to_tcp6_sock: Type = 136; pub const BPF_FUNC_skc_to_tcp_sock: Type = 137; pub const BPF_FUNC_skc_to_tcp_timewait_sock: Type = 138; pub const BPF_FUNC_skc_to_tcp_request_sock: Type = 139; pub const BPF_FUNC_skc_to_udp6_sock: Type = 140; pub const BPF_FUNC_get_task_stack: Type = 141; pub const BPF_FUNC_load_hdr_opt: Type = 142; pub const BPF_FUNC_store_hdr_opt: Type = 143; pub const BPF_FUNC_reserve_hdr_opt: Type = 144; pub const BPF_FUNC_inode_storage_get: Type = 145; pub const BPF_FUNC_inode_storage_delete: Type = 146; pub const BPF_FUNC_d_path: Type = 147; pub const BPF_FUNC_copy_from_user: Type = 148; pub const BPF_FUNC_snprintf_btf: Type = 149; pub const BPF_FUNC_seq_printf_btf: Type = 150; pub const BPF_FUNC_skb_cgroup_classid: Type = 151; pub const BPF_FUNC_redirect_neigh: Type = 152; pub const BPF_FUNC_per_cpu_ptr: Type = 153; pub const BPF_FUNC_this_cpu_ptr: Type = 154; pub const BPF_FUNC_redirect_peer: Type = 155; pub const BPF_FUNC_task_storage_get: Type = 156; pub const BPF_FUNC_task_storage_delete: Type = 157; pub const BPF_FUNC_get_current_task_btf: Type = 158; pub const BPF_FUNC_bprm_opts_set: Type = 159; pub const BPF_FUNC_ktime_get_coarse_ns: Type = 160; pub const BPF_FUNC_ima_inode_hash: Type = 161; pub const BPF_FUNC_sock_from_file: Type = 162; pub const BPF_FUNC_check_mtu: Type = 163; pub const BPF_FUNC_for_each_map_elem: Type = 164; pub const BPF_FUNC_snprintf: Type = 165; pub const BPF_FUNC_sys_bpf: Type = 166; pub const BPF_FUNC_btf_find_by_name_kind: Type = 167; pub const BPF_FUNC_sys_close: Type = 168; pub const BPF_FUNC_timer_init: Type = 169; pub const BPF_FUNC_timer_set_callback: Type = 170; pub const BPF_FUNC_timer_start: Type = 171; pub const BPF_FUNC_timer_cancel: Type = 172; pub const BPF_FUNC_get_func_ip: Type = 173; pub const BPF_FUNC_get_attach_cookie: Type = 174; pub const BPF_FUNC_task_pt_regs: Type = 175; pub const BPF_FUNC_get_branch_snapshot: Type = 176; pub const BPF_FUNC_trace_vprintk: Type = 177; pub const BPF_FUNC_skc_to_unix_sock: Type = 178; pub const BPF_FUNC_kallsyms_lookup_name: Type = 179; pub const BPF_FUNC_find_vma: Type = 180; pub const BPF_FUNC_loop: Type = 181; pub const BPF_FUNC_strncmp: Type = 182; pub const BPF_FUNC_get_func_arg: Type = 183; pub const BPF_FUNC_get_func_ret: Type = 184; pub const BPF_FUNC_get_func_arg_cnt: Type = 185; pub const BPF_FUNC_get_retval: Type = 186; pub const BPF_FUNC_set_retval: Type = 187; pub const BPF_FUNC_xdp_get_buff_len: Type = 188; pub const BPF_FUNC_xdp_load_bytes: Type = 189; pub const BPF_FUNC_xdp_store_bytes: Type = 190; pub const BPF_FUNC_copy_from_user_task: Type = 191; pub const BPF_FUNC_skb_set_tstamp: Type = 192; pub const BPF_FUNC_ima_file_hash: Type = 193; pub const BPF_FUNC_kptr_xchg: Type = 194; pub const BPF_FUNC_map_lookup_percpu_elem: Type = 195; pub const BPF_FUNC_skc_to_mptcp_sock: Type = 196; pub const BPF_FUNC_dynptr_from_mem: Type = 197; pub const BPF_FUNC_ringbuf_reserve_dynptr: Type = 198; pub const BPF_FUNC_ringbuf_submit_dynptr: Type = 199; pub const BPF_FUNC_ringbuf_discard_dynptr: Type = 200; pub const BPF_FUNC_dynptr_read: Type = 201; pub const BPF_FUNC_dynptr_write: Type = 202; pub const BPF_FUNC_dynptr_data: Type = 203; pub const BPF_FUNC_tcp_raw_gen_syncookie_ipv4: Type = 204; pub const BPF_FUNC_tcp_raw_gen_syncookie_ipv6: Type = 205; pub const BPF_FUNC_tcp_raw_check_syncookie_ipv4: Type = 206; pub const BPF_FUNC_tcp_raw_check_syncookie_ipv6: Type = 207; pub const BPF_FUNC_ktime_get_tai_ns: Type = 208; pub const __BPF_FUNC_MAX_ID: Type = 209; } pub const BPF_F_RECOMPUTE_CSUM: _bindgen_ty_4 = 1; pub const BPF_F_INVALIDATE_HASH: _bindgen_ty_4 = 2; pub type _bindgen_ty_4 = ::aya_bpf_cty::c_uint; pub const BPF_F_HDR_FIELD_MASK: _bindgen_ty_5 = 15; pub type _bindgen_ty_5 = ::aya_bpf_cty::c_uint; pub const BPF_F_PSEUDO_HDR: _bindgen_ty_6 = 16; pub const BPF_F_MARK_MANGLED_0: _bindgen_ty_6 = 32; pub const BPF_F_MARK_ENFORCE: _bindgen_ty_6 = 64; pub type _bindgen_ty_6 = ::aya_bpf_cty::c_uint; pub const BPF_F_INGRESS: _bindgen_ty_7 = 1; pub type _bindgen_ty_7 = ::aya_bpf_cty::c_uint; pub const BPF_F_TUNINFO_IPV6: _bindgen_ty_8 = 1; pub type _bindgen_ty_8 = ::aya_bpf_cty::c_uint; pub const BPF_F_SKIP_FIELD_MASK: _bindgen_ty_9 = 255; pub const BPF_F_USER_STACK: _bindgen_ty_9 = 256; pub const BPF_F_FAST_STACK_CMP: _bindgen_ty_9 = 512; pub const BPF_F_REUSE_STACKID: _bindgen_ty_9 = 1024; pub const BPF_F_USER_BUILD_ID: _bindgen_ty_9 = 2048; pub type _bindgen_ty_9 = ::aya_bpf_cty::c_uint; pub const BPF_F_ZERO_CSUM_TX: _bindgen_ty_10 = 2; pub const BPF_F_DONT_FRAGMENT: _bindgen_ty_10 = 4; pub const BPF_F_SEQ_NUMBER: _bindgen_ty_10 = 8; pub type _bindgen_ty_10 = ::aya_bpf_cty::c_uint; pub const BPF_F_INDEX_MASK: _bindgen_ty_11 = 4294967295; pub const BPF_F_CURRENT_CPU: _bindgen_ty_11 = 4294967295; pub const BPF_F_CTXLEN_MASK: _bindgen_ty_11 = 4503595332403200; pub type _bindgen_ty_11 = ::aya_bpf_cty::c_ulonglong; pub const BPF_F_CURRENT_NETNS: _bindgen_ty_12 = -1; pub type _bindgen_ty_12 = ::aya_bpf_cty::c_int; pub const BPF_CSUM_LEVEL_QUERY: _bindgen_ty_13 = 0; pub const BPF_CSUM_LEVEL_INC: _bindgen_ty_13 = 1; pub const BPF_CSUM_LEVEL_DEC: _bindgen_ty_13 = 2; pub const BPF_CSUM_LEVEL_RESET: _bindgen_ty_13 = 3; pub type _bindgen_ty_13 = ::aya_bpf_cty::c_uint; pub const BPF_F_ADJ_ROOM_FIXED_GSO: _bindgen_ty_14 = 1; pub const BPF_F_ADJ_ROOM_ENCAP_L3_IPV4: _bindgen_ty_14 = 2; pub const BPF_F_ADJ_ROOM_ENCAP_L3_IPV6: _bindgen_ty_14 = 4; pub const BPF_F_ADJ_ROOM_ENCAP_L4_GRE: _bindgen_ty_14 = 8; pub const BPF_F_ADJ_ROOM_ENCAP_L4_UDP: _bindgen_ty_14 = 16; pub const BPF_F_ADJ_ROOM_NO_CSUM_RESET: _bindgen_ty_14 = 32; pub const BPF_F_ADJ_ROOM_ENCAP_L2_ETH: _bindgen_ty_14 = 64; pub type _bindgen_ty_14 = ::aya_bpf_cty::c_uint; pub const BPF_ADJ_ROOM_ENCAP_L2_MASK: _bindgen_ty_15 = 255; pub const BPF_ADJ_ROOM_ENCAP_L2_SHIFT: _bindgen_ty_15 = 56; pub type _bindgen_ty_15 = ::aya_bpf_cty::c_uint; pub const BPF_F_SYSCTL_BASE_NAME: _bindgen_ty_16 = 1; pub type _bindgen_ty_16 = ::aya_bpf_cty::c_uint; pub const BPF_LOCAL_STORAGE_GET_F_CREATE: _bindgen_ty_17 = 1; pub const BPF_SK_STORAGE_GET_F_CREATE: _bindgen_ty_17 = 1; pub type _bindgen_ty_17 = ::aya_bpf_cty::c_uint; pub const BPF_F_GET_BRANCH_RECORDS_SIZE: _bindgen_ty_18 = 1; pub type _bindgen_ty_18 = ::aya_bpf_cty::c_uint; pub const BPF_RB_NO_WAKEUP: _bindgen_ty_19 = 1; pub const BPF_RB_FORCE_WAKEUP: _bindgen_ty_19 = 2; pub type _bindgen_ty_19 = ::aya_bpf_cty::c_uint; pub const BPF_RB_AVAIL_DATA: _bindgen_ty_20 = 0; pub const BPF_RB_RING_SIZE: _bindgen_ty_20 = 1; pub const BPF_RB_CONS_POS: _bindgen_ty_20 = 2; pub const BPF_RB_PROD_POS: _bindgen_ty_20 = 3; pub type _bindgen_ty_20 = ::aya_bpf_cty::c_uint; pub const BPF_RINGBUF_BUSY_BIT: _bindgen_ty_21 = 2147483648; pub const BPF_RINGBUF_DISCARD_BIT: _bindgen_ty_21 = 1073741824; pub const BPF_RINGBUF_HDR_SZ: _bindgen_ty_21 = 8; pub type _bindgen_ty_21 = ::aya_bpf_cty::c_uint; pub const BPF_SK_LOOKUP_F_REPLACE: _bindgen_ty_22 = 1; pub const BPF_SK_LOOKUP_F_NO_REUSEPORT: _bindgen_ty_22 = 2; pub type _bindgen_ty_22 = ::aya_bpf_cty::c_uint; pub mod bpf_adj_room_mode { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_ADJ_ROOM_NET: Type = 0; pub const BPF_ADJ_ROOM_MAC: Type = 1; } pub mod bpf_hdr_start_off { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_HDR_START_MAC: Type = 0; pub const BPF_HDR_START_NET: Type = 1; } pub mod bpf_lwt_encap_mode { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_LWT_ENCAP_SEG6: Type = 0; pub const BPF_LWT_ENCAP_SEG6_INLINE: Type = 1; pub const BPF_LWT_ENCAP_IP: Type = 2; } pub const BPF_F_BPRM_SECUREEXEC: _bindgen_ty_23 = 1; pub type _bindgen_ty_23 = ::aya_bpf_cty::c_uint; pub const BPF_F_BROADCAST: _bindgen_ty_24 = 8; pub const BPF_F_EXCLUDE_INGRESS: _bindgen_ty_24 = 16; pub type _bindgen_ty_24 = ::aya_bpf_cty::c_uint; pub mod _bindgen_ty_25 { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_SKB_TSTAMP_UNSPEC: Type = 0; pub const BPF_SKB_TSTAMP_DELIVERY_MONO: Type = 1; } #[repr(C)] #[derive(Copy, Clone)] pub struct __sk_buff { pub len: __u32, pub pkt_type: __u32, pub mark: __u32, pub queue_mapping: __u32, pub protocol: __u32, pub vlan_present: __u32, pub vlan_tci: __u32, pub vlan_proto: __u32, pub priority: __u32, pub ingress_ifindex: __u32, pub ifindex: __u32, pub tc_index: __u32, pub cb: [__u32; 5usize], pub hash: __u32, pub tc_classid: __u32, pub data: __u32, pub data_end: __u32, pub napi_id: __u32, pub family: __u32, pub remote_ip4: __u32, pub local_ip4: __u32, pub remote_ip6: [__u32; 4usize], pub local_ip6: [__u32; 4usize], pub remote_port: __u32, pub local_port: __u32, pub data_meta: __u32, pub __bindgen_anon_1: __sk_buff__bindgen_ty_1, pub tstamp: __u64, pub wire_len: __u32, pub gso_segs: __u32, pub __bindgen_anon_2: __sk_buff__bindgen_ty_2, pub gso_size: __u32, pub tstamp_type: __u8, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 3usize]>, pub hwtstamp: __u64, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union __sk_buff__bindgen_ty_1 { pub flow_keys: *mut bpf_flow_keys, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl __sk_buff__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union __sk_buff__bindgen_ty_2 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl __sk_buff__bindgen_ty_2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } impl __sk_buff { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 3usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 3usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_tunnel_key { pub tunnel_id: __u32, pub __bindgen_anon_1: bpf_tunnel_key__bindgen_ty_1, pub tunnel_tos: __u8, pub tunnel_ttl: __u8, pub tunnel_ext: __u16, pub tunnel_label: __u32, pub __bindgen_anon_2: bpf_tunnel_key__bindgen_ty_2, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_tunnel_key__bindgen_ty_1 { pub remote_ipv4: __u32, pub remote_ipv6: [__u32; 4usize], } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_tunnel_key__bindgen_ty_2 { pub local_ipv4: __u32, pub local_ipv6: [__u32; 4usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_xfrm_state { pub reqid: __u32, pub spi: __u32, pub family: __u16, pub ext: __u16, pub __bindgen_anon_1: bpf_xfrm_state__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_xfrm_state__bindgen_ty_1 { pub remote_ipv4: __u32, pub remote_ipv6: [__u32; 4usize], } pub mod bpf_ret_code { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_OK: Type = 0; pub const BPF_DROP: Type = 2; pub const BPF_REDIRECT: Type = 7; pub const BPF_LWT_REROUTE: Type = 128; } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock { pub bound_dev_if: __u32, pub family: __u32, pub type_: __u32, pub protocol: __u32, pub mark: __u32, pub priority: __u32, pub src_ip4: __u32, pub src_ip6: [__u32; 4usize], pub src_port: __u32, pub dst_port: __be16, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, pub dst_ip4: __u32, pub dst_ip6: [__u32; 4usize], pub state: __u32, pub rx_queue_mapping: __s32, } impl bpf_sock { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 2usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_tcp_sock { pub snd_cwnd: __u32, pub srtt_us: __u32, pub rtt_min: __u32, pub snd_ssthresh: __u32, pub rcv_nxt: __u32, pub snd_nxt: __u32, pub snd_una: __u32, pub mss_cache: __u32, pub ecn_flags: __u32, pub rate_delivered: __u32, pub rate_interval_us: __u32, pub packets_out: __u32, pub retrans_out: __u32, pub total_retrans: __u32, pub segs_in: __u32, pub data_segs_in: __u32, pub segs_out: __u32, pub data_segs_out: __u32, pub lost_out: __u32, pub sacked_out: __u32, pub bytes_received: __u64, pub bytes_acked: __u64, pub dsack_dups: __u32, pub delivered: __u32, pub delivered_ce: __u32, pub icsk_retransmits: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock_tuple { pub __bindgen_anon_1: bpf_sock_tuple__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_sock_tuple__bindgen_ty_1 { pub ipv4: bpf_sock_tuple__bindgen_ty_1__bindgen_ty_1, pub ipv6: bpf_sock_tuple__bindgen_ty_1__bindgen_ty_2, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock_tuple__bindgen_ty_1__bindgen_ty_1 { pub saddr: __be32, pub daddr: __be32, pub sport: __be16, pub dport: __be16, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock_tuple__bindgen_ty_1__bindgen_ty_2 { pub saddr: [__be32; 4usize], pub daddr: [__be32; 4usize], pub sport: __be16, pub dport: __be16, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_xdp_sock { pub queue_id: __u32, } pub mod xdp_action { pub type Type = ::aya_bpf_cty::c_uint; pub const XDP_ABORTED: Type = 0; pub const XDP_DROP: Type = 1; pub const XDP_PASS: Type = 2; pub const XDP_TX: Type = 3; pub const XDP_REDIRECT: Type = 4; } #[repr(C)] #[derive(Copy, Clone)] pub struct xdp_md { pub data: __u32, pub data_end: __u32, pub data_meta: __u32, pub ingress_ifindex: __u32, pub rx_queue_index: __u32, pub egress_ifindex: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_devmap_val { pub ifindex: __u32, pub bpf_prog: bpf_devmap_val__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_devmap_val__bindgen_ty_1 { pub fd: ::aya_bpf_cty::c_int, pub id: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_cpumap_val { pub qsize: __u32, pub bpf_prog: bpf_cpumap_val__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_cpumap_val__bindgen_ty_1 { pub fd: ::aya_bpf_cty::c_int, pub id: __u32, } pub mod sk_action { pub type Type = ::aya_bpf_cty::c_uint; pub const SK_DROP: Type = 0; pub const SK_PASS: Type = 1; } #[repr(C)] #[derive(Copy, Clone)] pub struct sk_msg_md { pub __bindgen_anon_1: sk_msg_md__bindgen_ty_1, pub __bindgen_anon_2: sk_msg_md__bindgen_ty_2, pub family: __u32, pub remote_ip4: __u32, pub local_ip4: __u32, pub remote_ip6: [__u32; 4usize], pub local_ip6: [__u32; 4usize], pub remote_port: __u32, pub local_port: __u32, pub size: __u32, pub __bindgen_anon_3: sk_msg_md__bindgen_ty_3, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_msg_md__bindgen_ty_1 { pub data: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_msg_md__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_msg_md__bindgen_ty_2 { pub data_end: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_msg_md__bindgen_ty_2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_msg_md__bindgen_ty_3 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_msg_md__bindgen_ty_3 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct sk_reuseport_md { pub __bindgen_anon_1: sk_reuseport_md__bindgen_ty_1, pub __bindgen_anon_2: sk_reuseport_md__bindgen_ty_2, pub len: __u32, pub eth_protocol: __u32, pub ip_protocol: __u32, pub bind_inany: __u32, pub hash: __u32, pub __bindgen_anon_3: sk_reuseport_md__bindgen_ty_3, pub __bindgen_anon_4: sk_reuseport_md__bindgen_ty_4, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_reuseport_md__bindgen_ty_1 { pub data: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_reuseport_md__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_reuseport_md__bindgen_ty_2 { pub data_end: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_reuseport_md__bindgen_ty_2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_reuseport_md__bindgen_ty_3 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_reuseport_md__bindgen_ty_3 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union sk_reuseport_md__bindgen_ty_4 { pub migrating_sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl sk_reuseport_md__bindgen_ty_4 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_prog_info { pub type_: __u32, pub id: __u32, pub tag: [__u8; 8usize], pub jited_prog_len: __u32, pub xlated_prog_len: __u32, pub jited_prog_insns: __u64, pub xlated_prog_insns: __u64, pub load_time: __u64, pub created_by_uid: __u32, pub nr_map_ids: __u32, pub map_ids: __u64, pub name: [::aya_bpf_cty::c_char; 16usize], pub ifindex: __u32, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, pub netns_dev: __u64, pub netns_ino: __u64, pub nr_jited_ksyms: __u32, pub nr_jited_func_lens: __u32, pub jited_ksyms: __u64, pub jited_func_lens: __u64, pub btf_id: __u32, pub func_info_rec_size: __u32, pub func_info: __u64, pub nr_func_info: __u32, pub nr_line_info: __u32, pub line_info: __u64, pub jited_line_info: __u64, pub nr_jited_line_info: __u32, pub line_info_rec_size: __u32, pub jited_line_info_rec_size: __u32, pub nr_prog_tags: __u32, pub prog_tags: __u64, pub run_time_ns: __u64, pub run_cnt: __u64, pub recursion_misses: __u64, pub verified_insns: __u32, pub attach_btf_obj_id: __u32, pub attach_btf_id: __u32, } impl bpf_prog_info { #[inline] pub fn gpl_compatible(&self) -> __u32 { unsafe { ::core::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) } } #[inline] pub fn set_gpl_compatible(&mut self, val: __u32) { unsafe { let val: u32 = ::core::mem::transmute(val); self._bitfield_1.set(0usize, 1u8, val as u64) } } #[inline] pub fn new_bitfield_1(gpl_compatible: __u32) -> __BindgenBitfieldUnit<[u8; 4usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); __bindgen_bitfield_unit.set(0usize, 1u8, { let gpl_compatible: u32 = unsafe { ::core::mem::transmute(gpl_compatible) }; gpl_compatible as u64 }); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_map_info { pub type_: __u32, pub id: __u32, pub key_size: __u32, pub value_size: __u32, pub max_entries: __u32, pub map_flags: __u32, pub name: [::aya_bpf_cty::c_char; 16usize], pub ifindex: __u32, pub btf_vmlinux_value_type_id: __u32, pub netns_dev: __u64, pub netns_ino: __u64, pub btf_id: __u32, pub btf_key_type_id: __u32, pub btf_value_type_id: __u32, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>, pub map_extra: __u64, } impl bpf_map_info { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 4usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 4usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_btf_info { pub btf: __u64, pub btf_size: __u32, pub id: __u32, pub name: __u64, pub name_len: __u32, pub kernel_btf: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info { pub type_: __u32, pub id: __u32, pub prog_id: __u32, pub __bindgen_anon_1: bpf_link_info__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_link_info__bindgen_ty_1 { pub raw_tracepoint: bpf_link_info__bindgen_ty_1__bindgen_ty_1, pub tracing: bpf_link_info__bindgen_ty_1__bindgen_ty_2, pub cgroup: bpf_link_info__bindgen_ty_1__bindgen_ty_3, pub iter: bpf_link_info__bindgen_ty_1__bindgen_ty_4, pub netns: bpf_link_info__bindgen_ty_1__bindgen_ty_5, pub xdp: bpf_link_info__bindgen_ty_1__bindgen_ty_6, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_1 { pub tp_name: __u64, pub tp_name_len: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_2 { pub attach_type: __u32, pub target_obj_id: __u32, pub target_btf_id: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_3 { pub cgroup_id: __u64, pub attach_type: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_4 { pub target_name: __u64, pub target_name_len: __u32, pub __bindgen_anon_1: bpf_link_info__bindgen_ty_1__bindgen_ty_4__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_link_info__bindgen_ty_1__bindgen_ty_4__bindgen_ty_1 { pub map: bpf_link_info__bindgen_ty_1__bindgen_ty_4__bindgen_ty_1__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_4__bindgen_ty_1__bindgen_ty_1 { pub map_id: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_5 { pub netns_ino: __u32, pub attach_type: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_link_info__bindgen_ty_1__bindgen_ty_6 { pub ifindex: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock_addr { pub user_family: __u32, pub user_ip4: __u32, pub user_ip6: [__u32; 4usize], pub user_port: __u32, pub family: __u32, pub type_: __u32, pub protocol: __u32, pub msg_src_ip4: __u32, pub msg_src_ip6: [__u32; 4usize], pub __bindgen_anon_1: bpf_sock_addr__bindgen_ty_1, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sock_addr__bindgen_ty_1 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sock_addr__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sock_ops { pub op: __u32, pub __bindgen_anon_1: bpf_sock_ops__bindgen_ty_1, pub family: __u32, pub remote_ip4: __u32, pub local_ip4: __u32, pub remote_ip6: [__u32; 4usize], pub local_ip6: [__u32; 4usize], pub remote_port: __u32, pub local_port: __u32, pub is_fullsock: __u32, pub snd_cwnd: __u32, pub srtt_us: __u32, pub bpf_sock_ops_cb_flags: __u32, pub state: __u32, pub rtt_min: __u32, pub snd_ssthresh: __u32, pub rcv_nxt: __u32, pub snd_nxt: __u32, pub snd_una: __u32, pub mss_cache: __u32, pub ecn_flags: __u32, pub rate_delivered: __u32, pub rate_interval_us: __u32, pub packets_out: __u32, pub retrans_out: __u32, pub total_retrans: __u32, pub segs_in: __u32, pub data_segs_in: __u32, pub segs_out: __u32, pub data_segs_out: __u32, pub lost_out: __u32, pub sacked_out: __u32, pub sk_txhash: __u32, pub bytes_received: __u64, pub bytes_acked: __u64, pub __bindgen_anon_2: bpf_sock_ops__bindgen_ty_2, pub __bindgen_anon_3: bpf_sock_ops__bindgen_ty_3, pub __bindgen_anon_4: bpf_sock_ops__bindgen_ty_4, pub skb_len: __u32, pub skb_tcp_flags: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_sock_ops__bindgen_ty_1 { pub args: [__u32; 4usize], pub reply: __u32, pub replylong: [__u32; 4usize], } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sock_ops__bindgen_ty_2 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sock_ops__bindgen_ty_2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sock_ops__bindgen_ty_3 { pub skb_data: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sock_ops__bindgen_ty_3 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sock_ops__bindgen_ty_4 { pub skb_data_end: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sock_ops__bindgen_ty_4 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } pub const BPF_SOCK_OPS_RTO_CB_FLAG: _bindgen_ty_26 = 1; pub const BPF_SOCK_OPS_RETRANS_CB_FLAG: _bindgen_ty_26 = 2; pub const BPF_SOCK_OPS_STATE_CB_FLAG: _bindgen_ty_26 = 4; pub const BPF_SOCK_OPS_RTT_CB_FLAG: _bindgen_ty_26 = 8; pub const BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG: _bindgen_ty_26 = 16; pub const BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG: _bindgen_ty_26 = 32; pub const BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG: _bindgen_ty_26 = 64; pub const BPF_SOCK_OPS_ALL_CB_FLAGS: _bindgen_ty_26 = 127; pub type _bindgen_ty_26 = ::aya_bpf_cty::c_uint; pub const BPF_SOCK_OPS_VOID: _bindgen_ty_27 = 0; pub const BPF_SOCK_OPS_TIMEOUT_INIT: _bindgen_ty_27 = 1; pub const BPF_SOCK_OPS_RWND_INIT: _bindgen_ty_27 = 2; pub const BPF_SOCK_OPS_TCP_CONNECT_CB: _bindgen_ty_27 = 3; pub const BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB: _bindgen_ty_27 = 4; pub const BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: _bindgen_ty_27 = 5; pub const BPF_SOCK_OPS_NEEDS_ECN: _bindgen_ty_27 = 6; pub const BPF_SOCK_OPS_BASE_RTT: _bindgen_ty_27 = 7; pub const BPF_SOCK_OPS_RTO_CB: _bindgen_ty_27 = 8; pub const BPF_SOCK_OPS_RETRANS_CB: _bindgen_ty_27 = 9; pub const BPF_SOCK_OPS_STATE_CB: _bindgen_ty_27 = 10; pub const BPF_SOCK_OPS_TCP_LISTEN_CB: _bindgen_ty_27 = 11; pub const BPF_SOCK_OPS_RTT_CB: _bindgen_ty_27 = 12; pub const BPF_SOCK_OPS_PARSE_HDR_OPT_CB: _bindgen_ty_27 = 13; pub const BPF_SOCK_OPS_HDR_OPT_LEN_CB: _bindgen_ty_27 = 14; pub const BPF_SOCK_OPS_WRITE_HDR_OPT_CB: _bindgen_ty_27 = 15; pub type _bindgen_ty_27 = ::aya_bpf_cty::c_uint; pub const BPF_TCP_ESTABLISHED: _bindgen_ty_28 = 1; pub const BPF_TCP_SYN_SENT: _bindgen_ty_28 = 2; pub const BPF_TCP_SYN_RECV: _bindgen_ty_28 = 3; pub const BPF_TCP_FIN_WAIT1: _bindgen_ty_28 = 4; pub const BPF_TCP_FIN_WAIT2: _bindgen_ty_28 = 5; pub const BPF_TCP_TIME_WAIT: _bindgen_ty_28 = 6; pub const BPF_TCP_CLOSE: _bindgen_ty_28 = 7; pub const BPF_TCP_CLOSE_WAIT: _bindgen_ty_28 = 8; pub const BPF_TCP_LAST_ACK: _bindgen_ty_28 = 9; pub const BPF_TCP_LISTEN: _bindgen_ty_28 = 10; pub const BPF_TCP_CLOSING: _bindgen_ty_28 = 11; pub const BPF_TCP_NEW_SYN_RECV: _bindgen_ty_28 = 12; pub const BPF_TCP_MAX_STATES: _bindgen_ty_28 = 13; pub type _bindgen_ty_28 = ::aya_bpf_cty::c_uint; pub mod _bindgen_ty_30 { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_LOAD_HDR_OPT_TCP_SYN: Type = 1; } pub mod _bindgen_ty_31 { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_WRITE_HDR_TCP_CURRENT_MSS: Type = 1; pub const BPF_WRITE_HDR_TCP_SYNACK_COOKIE: Type = 2; } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_perf_event_value { pub counter: __u64, pub enabled: __u64, pub running: __u64, } pub const BPF_DEVCG_ACC_MKNOD: _bindgen_ty_32 = 1; pub const BPF_DEVCG_ACC_READ: _bindgen_ty_32 = 2; pub const BPF_DEVCG_ACC_WRITE: _bindgen_ty_32 = 4; pub type _bindgen_ty_32 = ::aya_bpf_cty::c_uint; pub const BPF_DEVCG_DEV_BLOCK: _bindgen_ty_33 = 1; pub const BPF_DEVCG_DEV_CHAR: _bindgen_ty_33 = 2; pub type _bindgen_ty_33 = ::aya_bpf_cty::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_cgroup_dev_ctx { pub access_type: __u32, pub major: __u32, pub minor: __u32, } #[repr(C)] pub struct bpf_raw_tracepoint_args { pub args: __IncompleteArrayField<__u64>, } pub const BPF_FIB_LOOKUP_DIRECT: _bindgen_ty_34 = 1; pub const BPF_FIB_LOOKUP_OUTPUT: _bindgen_ty_34 = 2; pub type _bindgen_ty_34 = ::aya_bpf_cty::c_uint; pub const BPF_FIB_LKUP_RET_SUCCESS: _bindgen_ty_35 = 0; pub const BPF_FIB_LKUP_RET_BLACKHOLE: _bindgen_ty_35 = 1; pub const BPF_FIB_LKUP_RET_UNREACHABLE: _bindgen_ty_35 = 2; pub const BPF_FIB_LKUP_RET_PROHIBIT: _bindgen_ty_35 = 3; pub const BPF_FIB_LKUP_RET_NOT_FWDED: _bindgen_ty_35 = 4; pub const BPF_FIB_LKUP_RET_FWD_DISABLED: _bindgen_ty_35 = 5; pub const BPF_FIB_LKUP_RET_UNSUPP_LWT: _bindgen_ty_35 = 6; pub const BPF_FIB_LKUP_RET_NO_NEIGH: _bindgen_ty_35 = 7; pub const BPF_FIB_LKUP_RET_FRAG_NEEDED: _bindgen_ty_35 = 8; pub type _bindgen_ty_35 = ::aya_bpf_cty::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_fib_lookup { pub family: __u8, pub l4_protocol: __u8, pub sport: __be16, pub dport: __be16, pub __bindgen_anon_1: bpf_fib_lookup__bindgen_ty_1, pub ifindex: __u32, pub __bindgen_anon_2: bpf_fib_lookup__bindgen_ty_2, pub __bindgen_anon_3: bpf_fib_lookup__bindgen_ty_3, pub __bindgen_anon_4: bpf_fib_lookup__bindgen_ty_4, pub h_vlan_proto: __be16, pub h_vlan_TCI: __be16, pub smac: [__u8; 6usize], pub dmac: [__u8; 6usize], } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_fib_lookup__bindgen_ty_1 { pub tot_len: __u16, pub mtu_result: __u16, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_fib_lookup__bindgen_ty_2 { pub tos: __u8, pub flowinfo: __be32, pub rt_metric: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_fib_lookup__bindgen_ty_3 { pub ipv4_src: __be32, pub ipv6_src: [__u32; 4usize], } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_fib_lookup__bindgen_ty_4 { pub ipv4_dst: __be32, pub ipv6_dst: [__u32; 4usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_redir_neigh { pub nh_family: __u32, pub __bindgen_anon_1: bpf_redir_neigh__bindgen_ty_1, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_redir_neigh__bindgen_ty_1 { pub ipv4_nh: __be32, pub ipv6_nh: [__u32; 4usize], } pub mod bpf_check_mtu_flags { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_MTU_CHK_SEGS: Type = 1; } pub mod bpf_check_mtu_ret { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_MTU_CHK_RET_SUCCESS: Type = 0; pub const BPF_MTU_CHK_RET_FRAG_NEEDED: Type = 1; pub const BPF_MTU_CHK_RET_SEGS_TOOBIG: Type = 2; } pub mod bpf_task_fd_type { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_FD_TYPE_RAW_TRACEPOINT: Type = 0; pub const BPF_FD_TYPE_TRACEPOINT: Type = 1; pub const BPF_FD_TYPE_KPROBE: Type = 2; pub const BPF_FD_TYPE_KRETPROBE: Type = 3; pub const BPF_FD_TYPE_UPROBE: Type = 4; pub const BPF_FD_TYPE_URETPROBE: Type = 5; } pub const BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG: _bindgen_ty_36 = 1; pub const BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL: _bindgen_ty_36 = 2; pub const BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP: _bindgen_ty_36 = 4; pub type _bindgen_ty_36 = ::aya_bpf_cty::c_uint; #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_flow_keys { pub nhoff: __u16, pub thoff: __u16, pub addr_proto: __u16, pub is_frag: __u8, pub is_first_frag: __u8, pub is_encap: __u8, pub ip_proto: __u8, pub n_proto: __be16, pub sport: __be16, pub dport: __be16, pub __bindgen_anon_1: bpf_flow_keys__bindgen_ty_1, pub flags: __u32, pub flow_label: __be32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_flow_keys__bindgen_ty_1 { pub __bindgen_anon_1: bpf_flow_keys__bindgen_ty_1__bindgen_ty_1, pub __bindgen_anon_2: bpf_flow_keys__bindgen_ty_1__bindgen_ty_2, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_flow_keys__bindgen_ty_1__bindgen_ty_1 { pub ipv4_src: __be32, pub ipv4_dst: __be32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_flow_keys__bindgen_ty_1__bindgen_ty_2 { pub ipv6_src: [__u32; 4usize], pub ipv6_dst: [__u32; 4usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_func_info { pub insn_off: __u32, pub type_id: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_line_info { pub insn_off: __u32, pub file_name_off: __u32, pub line_off: __u32, pub line_col: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_spin_lock { pub val: __u32, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub struct bpf_timer { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, } impl bpf_timer { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 16usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub struct bpf_dynptr { pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 16usize]>, } impl bpf_dynptr { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 16usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 16usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sysctl { pub write: __u32, pub file_pos: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sockopt { pub __bindgen_anon_1: bpf_sockopt__bindgen_ty_1, pub __bindgen_anon_2: bpf_sockopt__bindgen_ty_2, pub __bindgen_anon_3: bpf_sockopt__bindgen_ty_3, pub level: __s32, pub optname: __s32, pub optlen: __s32, pub retval: __s32, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sockopt__bindgen_ty_1 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sockopt__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sockopt__bindgen_ty_2 { pub optval: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sockopt__bindgen_ty_2 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sockopt__bindgen_ty_3 { pub optval_end: *mut ::aya_bpf_cty::c_void, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sockopt__bindgen_ty_3 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_pidns_info { pub pid: __u32, pub tgid: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_sk_lookup { pub __bindgen_anon_1: bpf_sk_lookup__bindgen_ty_1, pub family: __u32, pub protocol: __u32, pub remote_ip4: __u32, pub remote_ip6: [__u32; 4usize], pub remote_port: __be16, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 2usize]>, pub local_ip4: __u32, pub local_ip6: [__u32; 4usize], pub local_port: __u32, pub ingress_ifindex: __u32, } #[repr(C)] #[derive(Copy, Clone)] pub union bpf_sk_lookup__bindgen_ty_1 { pub __bindgen_anon_1: bpf_sk_lookup__bindgen_ty_1__bindgen_ty_1, pub cookie: __u64, } #[repr(C)] #[repr(align(8))] #[derive(Copy, Clone)] pub union bpf_sk_lookup__bindgen_ty_1__bindgen_ty_1 { pub sk: *mut bpf_sock, pub _bitfield_align_1: [u8; 0], pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>, } impl bpf_sk_lookup__bindgen_ty_1__bindgen_ty_1 { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 8usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default(); __bindgen_bitfield_unit } } impl bpf_sk_lookup { #[inline] pub fn new_bitfield_1() -> __BindgenBitfieldUnit<[u8; 2usize]> { let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 2usize]> = Default::default(); __bindgen_bitfield_unit } } #[repr(C)] #[derive(Copy, Clone)] pub struct btf_ptr { pub ptr: *mut ::aya_bpf_cty::c_void, pub type_id: __u32, pub flags: __u32, } pub mod bpf_core_relo_kind { pub type Type = ::aya_bpf_cty::c_uint; pub const BPF_CORE_FIELD_BYTE_OFFSET: Type = 0; pub const BPF_CORE_FIELD_BYTE_SIZE: Type = 1; pub const BPF_CORE_FIELD_EXISTS: Type = 2; pub const BPF_CORE_FIELD_SIGNED: Type = 3; pub const BPF_CORE_FIELD_LSHIFT_U64: Type = 4; pub const BPF_CORE_FIELD_RSHIFT_U64: Type = 5; pub const BPF_CORE_TYPE_ID_LOCAL: Type = 6; pub const BPF_CORE_TYPE_ID_TARGET: Type = 7; pub const BPF_CORE_TYPE_EXISTS: Type = 8; pub const BPF_CORE_TYPE_SIZE: Type = 9; pub const BPF_CORE_ENUMVAL_EXISTS: Type = 10; pub const BPF_CORE_ENUMVAL_VALUE: Type = 11; pub const BPF_CORE_TYPE_MATCHES: Type = 12; } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_core_relo { pub insn_off: __u32, pub type_id: __u32, pub access_str_off: __u32, pub kind: bpf_core_relo_kind::Type, } #[repr(C)] #[derive(Copy, Clone)] pub struct pt_regs { pub uregs: [::aya_bpf_cty::c_long; 18usize], } pub type sa_family_t = ::aya_bpf_cty::c_ushort; #[repr(C)] #[derive(Copy, Clone)] pub struct sockaddr { pub sa_family: sa_family_t, pub sa_data: [::aya_bpf_cty::c_char; 14usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct bpf_perf_event_data { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct linux_binprm { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct tcphdr { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct seq_file { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct tcp6_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct tcp_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct tcp_timewait_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct tcp_request_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct udp6_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct unix_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct task_struct { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct path { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct inode { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct socket { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct file { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct mptcp_sock { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct iphdr { _unused: [u8; 0], } #[repr(C)] #[derive(Copy, Clone)] pub struct ipv6hdr { _unused: [u8; 0], } <file_sep>/bpf/aya-bpf/src/maps/per_cpu_array.rs use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull}; use aya_bpf_cty::c_void; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_PERCPU_ARRAY}, helpers::bpf_map_lookup_elem, maps::PinningType, }; #[repr(transparent)] pub struct PerCpuArray<T> { def: UnsafeCell<bpf_map_def>, _t: PhantomData<T>, } unsafe impl<T> Sync for PerCpuArray<T> {} impl<T> PerCpuArray<T> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> PerCpuArray<T> { PerCpuArray { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_PERCPU_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), _t: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> PerCpuArray<T> { PerCpuArray { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_PERCPU_ARRAY, key_size: mem::size_of::<u32>() as u32, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), _t: PhantomData, } } #[inline(always)] pub fn get(&self, index: u32) -> Option<&T> { unsafe { // FIXME: alignment self.lookup(index).map(|p| p.as_ref()) } } #[inline(always)] pub fn get_ptr(&self, index: u32) -> Option<*const T> { unsafe { self.lookup(index).map(|p| p.as_ptr() as *const T) } } #[inline(always)] pub fn get_ptr_mut(&self, index: u32) -> Option<*mut T> { unsafe { self.lookup(index).map(|p| p.as_ptr()) } } #[inline(always)] unsafe fn lookup(&self, index: u32) -> Option<NonNull<T>> { let ptr = bpf_map_lookup_elem( self.def.get() as *mut _, &index as *const _ as *const c_void, ); NonNull::new(ptr as *mut T) } } <file_sep>/aya/src/programs/socket_filter.rs //! Socket filter programs. use libc::{setsockopt, SOL_SOCKET}; use std::{ io, mem, os::unix::prelude::{AsRawFd, RawFd}, }; use thiserror::Error; use crate::{ generated::{bpf_prog_type::BPF_PROG_TYPE_SOCKET_FILTER, SO_ATTACH_BPF, SO_DETACH_BPF}, programs::{load_program, Link, ProgramData, ProgramError}, }; /// The type returned when attaching a [`SocketFilter`] fails. #[derive(Debug, Error)] pub enum SocketFilterError { /// Setting the `SO_ATTACH_BPF` socket option failed. #[error("setsockopt SO_ATTACH_BPF failed")] SoAttachBpfError { /// original [`io::Error`] #[source] io_error: io::Error, }, } /// A program used to inspect and filter incoming packets on a socket. /// /// [`SocketFilter`] programs are attached on sockets and can be used to inspect /// and filter incoming packets. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.0. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::net::TcpStream; /// use std::os::unix::io::AsRawFd; /// use aya::programs::SocketFilter; /// /// let mut client = TcpStream::connect("127.0.0.1:1234")?; /// let prog: &mut SocketFilter = bpf.program_mut("filter_packets").unwrap().try_into()?; /// prog.load()?; /// prog.attach(client.as_raw_fd())?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SOCKET_FILTER")] pub struct SocketFilter { pub(crate) data: ProgramData<SocketFilterLink>, } impl SocketFilter { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SOCKET_FILTER, &mut self.data) } /// Attaches the filter on the given socket. /// /// The returned value can be used to detach from the socket, see [SocketFilter::detach]. pub fn attach<T: AsRawFd>(&mut self, socket: T) -> Result<SocketFilterLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let socket = socket.as_raw_fd(); let ret = unsafe { setsockopt( socket, SOL_SOCKET, SO_ATTACH_BPF as i32, &prog_fd as *const _ as *const _, mem::size_of::<RawFd>() as u32, ) }; if ret < 0 { return Err(SocketFilterError::SoAttachBpfError { io_error: io::Error::last_os_error(), } .into()); } self.data.links.insert(SocketFilterLink { socket, prog_fd }) } /// Detaches the program. /// /// See [SocketFilter::attach]. pub fn detach(&mut self, link_id: SocketFilterLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: SocketFilterLinkId, ) -> Result<SocketFilterLink, ProgramError> { self.data.take_link(link_id) } } /// The type returned by [SocketFilter::attach]. Can be passed to [SocketFilter::detach]. #[derive(Debug, Hash, Eq, PartialEq)] pub struct SocketFilterLinkId(RawFd, RawFd); /// A SocketFilter Link #[derive(Debug)] pub struct SocketFilterLink { socket: RawFd, prog_fd: RawFd, } impl Link for SocketFilterLink { type Id = SocketFilterLinkId; fn id(&self) -> Self::Id { SocketFilterLinkId(self.socket, self.prog_fd) } fn detach(self) -> Result<(), ProgramError> { unsafe { setsockopt( self.socket, SOL_SOCKET, SO_DETACH_BPF as i32, &self.prog_fd as *const _ as *const _, mem::size_of::<RawFd>() as u32, ); } Ok(()) } } <file_sep>/bpf/aya-bpf/src/maps/queue.rs use core::{cell::UnsafeCell, marker::PhantomData, mem}; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_QUEUE}, helpers::{bpf_map_pop_elem, bpf_map_push_elem}, maps::PinningType, }; #[repr(transparent)] pub struct Queue<T> { def: UnsafeCell<bpf_map_def>, _t: PhantomData<T>, } unsafe impl<T: Sync> Sync for Queue<T> {} impl<T> Queue<T> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> Queue<T> { Queue { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_QUEUE, key_size: 0, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::None as u32, }), _t: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> Queue<T> { Queue { def: UnsafeCell::new(bpf_map_def { type_: BPF_MAP_TYPE_QUEUE, key_size: 0, value_size: mem::size_of::<T>() as u32, max_entries, map_flags: flags, id: 0, pinning: PinningType::ByName as u32, }), _t: PhantomData, } } pub fn push(&self, value: &T, flags: u64) -> Result<(), i64> { let ret = unsafe { bpf_map_push_elem( self.def.get() as *mut _, value as *const _ as *const _, flags, ) }; (ret == 0).then_some(()).ok_or(ret) } pub fn pop(&self) -> Option<T> { unsafe { let mut value = mem::MaybeUninit::uninit(); let ret = bpf_map_pop_elem(self.def.get() as *mut _, value.as_mut_ptr() as *mut _); (ret == 0).then_some(value.assume_init()) } } } <file_sep>/bpf/aya-bpf/src/programs/sock_ops.rs use core::ffi::c_void; use aya_bpf_bindings::helpers::bpf_sock_ops_cb_flags_set; use crate::{bindings::bpf_sock_ops, BpfContext}; pub struct SockOpsContext { pub ops: *mut bpf_sock_ops, } impl SockOpsContext { pub fn new(ops: *mut bpf_sock_ops) -> SockOpsContext { SockOpsContext { ops } } pub fn op(&self) -> u32 { unsafe { (*self.ops).op } } pub fn family(&self) -> u32 { unsafe { (*self.ops).family } } pub fn cb_flags(&self) -> u32 { unsafe { (*self.ops).bpf_sock_ops_cb_flags } } pub fn set_cb_flags(&self, flags: i32) -> Result<(), i64> { let ret = unsafe { bpf_sock_ops_cb_flags_set(self.ops, flags) }; if ret == 0 { Ok(()) } else { Err(ret) } } pub fn remote_ip4(&self) -> u32 { unsafe { (*self.ops).remote_ip4 } } pub fn local_ip4(&self) -> u32 { unsafe { (*self.ops).local_ip4 } } pub fn remote_ip6(&self) -> [u32; 4] { unsafe { (*self.ops).remote_ip6 } } pub fn local_ip6(&self) -> [u32; 4] { unsafe { (*self.ops).local_ip6 } } pub fn local_port(&self) -> u32 { unsafe { (*self.ops).local_port } } pub fn remote_port(&self) -> u32 { unsafe { (*self.ops).remote_port } } pub fn arg(&self, n: usize) -> u32 { unsafe { (*self.ops).__bindgen_anon_1.args[n] } } } impl BpfContext for SockOpsContext { fn as_ptr(&self) -> *mut c_void { self.ops as *mut _ } } <file_sep>/aya-tool/src/bin/aya-tool.rs use aya_tool::generate::{generate, InputFile}; use std::{path::PathBuf, process::exit}; use clap::Parser; #[derive(Parser)] pub struct Options { #[clap(subcommand)] command: Command, } #[derive(Parser)] enum Command { /// Generate Rust bindings to Kernel types using bpftool #[clap(name = "generate", action)] Generate { #[clap(long, default_value = "/sys/kernel/btf/vmlinux", action)] btf: PathBuf, #[clap(long, conflicts_with = "btf", action)] header: Option<PathBuf>, #[clap(action)] names: Vec<String>, #[clap(last = true, action)] bindgen_args: Vec<String>, }, } fn main() { if let Err(e) = try_main() { eprintln!("{e:#}"); exit(1); } } fn try_main() -> Result<(), anyhow::Error> { let opts = Options::parse(); match opts.command { Command::Generate { btf, header, names, bindgen_args, } => { let bindings: String = if let Some(header) = header { generate(InputFile::Header(header), &names, &bindgen_args)? } else { generate(InputFile::Btf(btf), &names, &bindgen_args)? }; println!("{bindings}"); } }; Ok(()) } <file_sep>/bpf/aya-bpf/src/programs/device.rs use core::ffi::c_void; use crate::{bindings::bpf_cgroup_dev_ctx, BpfContext}; pub struct DeviceContext { pub device: *mut bpf_cgroup_dev_ctx, } impl DeviceContext { pub fn new(device: *mut bpf_cgroup_dev_ctx) -> DeviceContext { DeviceContext { device } } } impl BpfContext for DeviceContext { fn as_ptr(&self) -> *mut c_void { self.device as *mut _ } } <file_sep>/aya/src/programs/sk_msg.rs //! Skmsg programs. use std::os::unix::io::AsRawFd; use crate::{ generated::{bpf_attach_type::BPF_SK_MSG_VERDICT, bpf_prog_type::BPF_PROG_TYPE_SK_MSG}, maps::sock::SockMapFd, programs::{ define_link_wrapper, load_program, ProgAttachLink, ProgAttachLinkId, ProgramData, ProgramError, }, sys::bpf_prog_attach, }; /// A program used to intercept messages sent with `sendmsg()`/`sendfile()`. /// /// [`SkMsg`] programs are attached to [socket maps], and can be used inspect, /// filter and redirect messages sent on sockets. See also [`SockMap`] and /// [`SockHash`]. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.17. /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use std::io::Write; /// use std::net::TcpStream; /// use std::os::unix::io::AsRawFd; /// use aya::maps::SockHash; /// use aya::programs::SkMsg; /// /// let intercept_egress: SockHash<_, u32> = bpf.map("INTERCEPT_EGRESS").unwrap().try_into()?; /// let map_fd = intercept_egress.fd()?; /// /// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; /// prog.load()?; /// prog.attach(map_fd)?; /// /// let mut client = TcpStream::connect("127.0.0.1:1234")?; /// let mut intercept_egress: SockHash<_, u32> = bpf.map_mut("INTERCEPT_EGRESS").unwrap().try_into()?; /// /// intercept_egress.insert(1234, client.as_raw_fd(), 0)?; /// /// // the write will be intercepted /// client.write_all(b"foo")?; /// # Ok::<(), Error>(()) /// ``` /// /// [socket maps]: crate::maps::sock /// [`SockMap`]: crate::maps::SockMap /// [`SockHash`]: crate::maps::SockHash #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SK_MSG")] pub struct SkMsg { pub(crate) data: ProgramData<SkMsgLink>, } impl SkMsg { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SK_MSG, &mut self.data) } /// Attaches the program to the given sockmap. /// /// The returned value can be used to detach, see [SkMsg::detach]. pub fn attach(&mut self, map: SockMapFd) -> Result<SkMsgLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let map_fd = map.as_raw_fd(); bpf_prog_attach(prog_fd, map_fd, BPF_SK_MSG_VERDICT).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data.links.insert(SkMsgLink::new(ProgAttachLink::new( prog_fd, map_fd, BPF_SK_MSG_VERDICT, ))) } /// Detaches the program from a sockmap. /// /// See [SkMsg::attach]. pub fn detach(&mut self, link_id: SkMsgLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: SkMsgLinkId) -> Result<SkMsgLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [SkMsg] programs. SkMsgLink, /// The type returned by [SkMsg::attach]. Can be passed to [SkMsg::detach]. SkMsgLinkId, ProgAttachLink, ProgAttachLinkId ); <file_sep>/aya/src/maps/queue.rs //! A FIFO queue. use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_kv_size, MapData, MapError}, sys::{bpf_map_lookup_and_delete_elem, bpf_map_push_elem}, Pod, }; /// A FIFO queue. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.20. /// /// # Examples /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::Queue; /// /// let mut queue = Queue::try_from(bpf.map_mut("ARRAY").unwrap())?; /// queue.push(42, 0)?; /// queue.push(43, 0)?; /// assert_eq!(queue.pop(0)?, 42); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_QUEUE")] pub struct Queue<T, V: Pod> { inner: T, _v: PhantomData<V>, } impl<T: AsRef<MapData>, V: Pod> Queue<T, V> { pub(crate) fn new(map: T) -> Result<Queue<T, V>, MapError> { let data = map.as_ref(); check_kv_size::<(), V>(data)?; let _fd = data.fd_or_err()?; Ok(Queue { inner: map, _v: PhantomData, }) } /// Returns the number of elements the queue can hold. /// /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side. pub fn capacity(&self) -> u32 { self.inner.as_ref().obj.max_entries() } } impl<T: AsMut<MapData>, V: Pod> Queue<T, V> { /// Removes the first element and returns it. /// /// # Errors /// /// Returns [`MapError::ElementNotFound`] if the queue is empty, [`MapError::SyscallError`] /// if `bpf_map_lookup_and_delete_elem` fails. pub fn pop(&mut self, flags: u64) -> Result<V, MapError> { let fd = self.inner.as_mut().fd_or_err()?; let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err( |(_, io_error)| MapError::SyscallError { call: "bpf_map_lookup_and_delete_elem".to_owned(), io_error, }, )?; value.ok_or(MapError::ElementNotFound) } /// Appends an element at the end of the queue. /// /// # Errors /// /// [`MapError::SyscallError`] if `bpf_map_update_elem` fails. pub fn push(&mut self, value: impl Borrow<V>, flags: u64) -> Result<(), MapError> { let fd = self.inner.as_mut().fd_or_err()?; bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_push_elem".to_owned(), io_error, } })?; Ok(()) } } <file_sep>/test/integration-test/src/main.rs use log::info; mod tests; use tests::IntegrationTest; use clap::Parser; #[derive(Debug, Parser)] #[clap(author, version, about, long_about = None)] #[clap(propagate_version = true)] pub struct RunOptions { #[clap(short, long, value_parser)] tests: Option<Vec<String>>, } #[derive(Debug, Parser)] struct Cli { #[clap(subcommand)] command: Option<Command>, } #[derive(Debug, Parser)] enum Command { /// Run one or more tests: ... -- run -t test1 -t test2 Run(RunOptions), /// List all the tests: ... -- list List, } macro_rules! exec_test { ($test:expr) => {{ info!("Running {}", $test.name); ($test.test_fn)(); }}; } macro_rules! exec_all_tests { () => {{ for t in inventory::iter::<IntegrationTest> { exec_test!(t) } }}; } fn main() -> anyhow::Result<()> { env_logger::init(); let cli = Cli::parse(); match &cli.command { Some(Command::Run(opts)) => match &opts.tests { Some(tests) => { for t in inventory::iter::<IntegrationTest> { if tests.contains(&t.name.into()) { exec_test!(t) } } } None => { exec_all_tests!() } }, Some(Command::List) => { for t in inventory::iter::<IntegrationTest> { info!("{}", t.name); } } None => { exec_all_tests!() } } Ok(()) } <file_sep>/test/integration-test/src/tests/mod.rs use anyhow::bail; use lazy_static::lazy_static; use libc::{uname, utsname}; use regex::Regex; use std::{ffi::CStr, mem}; pub mod elf; pub mod load; pub mod smoke; pub use integration_test_macros::integration_test; #[derive(Debug)] pub struct IntegrationTest { pub name: &'static str, pub test_fn: fn(), } pub(crate) fn kernel_version() -> anyhow::Result<(u8, u8, u8)> { lazy_static! { static ref RE: Regex = Regex::new(r"^([0-9]+)\.([0-9]+)\.([0-9]+)").unwrap(); } let mut data: utsname = unsafe { mem::zeroed() }; let ret = unsafe { uname(&mut data) }; assert!(ret >= 0, "libc::uname failed."); let release_cstr = unsafe { CStr::from_ptr(data.release.as_ptr()) }; let release = release_cstr.to_string_lossy(); if let Some(caps) = RE.captures(&release) { let major = caps.get(1).unwrap().as_str().parse().unwrap(); let minor = caps.get(2).unwrap().as_str().parse().unwrap(); let patch = caps.get(3).unwrap().as_str().parse().unwrap(); Ok((major, minor, patch)) } else { bail!("no kernel version found"); } } inventory::collect!(IntegrationTest); <file_sep>/bpf/aya-bpf/src/programs/sock.rs use core::ffi::c_void; use crate::{bindings::bpf_sock, BpfContext}; pub struct SockContext { pub sock: *mut bpf_sock, } impl SockContext { pub fn new(sock: *mut bpf_sock) -> SockContext { SockContext { sock } } } impl BpfContext for SockContext { fn as_ptr(&self) -> *mut c_void { self.sock as *mut _ } } <file_sep>/aya/src/maps/hash_map/hash_map.rs use std::{ borrow::Borrow, convert::{AsMut, AsRef}, marker::PhantomData, }; use crate::{ maps::{check_kv_size, hash_map, IterableMap, MapData, MapError, MapIter, MapKeys}, sys::bpf_map_lookup_elem, Pod, }; /// A hash map that can be shared between eBPF programs and user space. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 3.19. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::HashMap; /// /// let mut redirect_ports = HashMap::try_from(bpf.map_mut("REDIRECT_PORTS").unwrap())?; /// /// // redirect port 80 to 8080 /// redirect_ports.insert(80, 8080, 0); /// // redirect port 443 to 8443 /// redirect_ports.insert(443, 8443, 0); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_HASH")] #[doc(alias = "BPF_MAP_TYPE_LRU_HASH")] #[derive(Debug)] pub struct HashMap<T, K, V> { inner: T, _k: PhantomData<K>, _v: PhantomData<V>, } impl<T: AsRef<MapData>, K: Pod, V: Pod> HashMap<T, K, V> { pub(crate) fn new(map: T) -> Result<HashMap<T, K, V>, MapError> { let data = map.as_ref(); check_kv_size::<K, V>(data)?; let _ = data.fd_or_err()?; Ok(HashMap { inner: map, _k: PhantomData, _v: PhantomData, }) } /// Returns a copy of the value associated with the key. pub fn get(&self, key: &K, flags: u64) -> Result<V, MapError> { let fd = self.inner.as_ref().fd_or_err()?; let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_lookup_elem".to_owned(), io_error, } })?; value.ok_or(MapError::KeyNotFound) } /// An iterator visiting all key-value pairs in arbitrary order. The /// iterator item type is `Result<(K, V), MapError>`. pub fn iter(&self) -> MapIter<'_, K, V, Self> { MapIter::new(self) } /// An iterator visiting all keys in arbitrary order. The iterator element /// type is `Result<K, MapError>`. pub fn keys(&self) -> MapKeys<'_, K> { MapKeys::new(self.inner.as_ref()) } } impl<T: AsMut<MapData>, K: Pod, V: Pod> HashMap<T, K, V> { /// Inserts a key-value pair into the map. pub fn insert( &mut self, key: impl Borrow<K>, value: impl Borrow<V>, flags: u64, ) -> Result<(), MapError> { hash_map::insert(self.inner.as_mut(), key.borrow(), value.borrow(), flags) } /// Removes a key from the map. pub fn remove(&mut self, key: &K) -> Result<(), MapError> { hash_map::remove(self.inner.as_mut(), key) } } impl<T: AsRef<MapData>, K: Pod, V: Pod> IterableMap<K, V> for HashMap<T, K, V> { fn map(&self) -> &MapData { self.inner.as_ref() } fn get(&self, key: &K) -> Result<V, MapError> { HashMap::get(self, key, 0) } } #[cfg(test)] mod tests { use std::io; use libc::{EFAULT, ENOENT}; use crate::{ bpf_map_def, generated::{ bpf_attr, bpf_cmd, bpf_map_type::{BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_LRU_HASH}, }, maps::{Map, MapData}, obj, sys::{override_syscall, SysResult, Syscall}, }; use super::*; fn new_obj_map() -> obj::Map { obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_HASH as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, data: Vec::new(), kind: obj::MapKind::Other, symbol_index: 0, }) } fn sys_error(value: i32) -> SysResult { Err((-1, io::Error::from_raw_os_error(value))) } #[test] fn test_wrong_key_size() { let map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( HashMap::<_, u8, u32>::new(&map), Err(MapError::InvalidKeySize { size: 1, expected: 4 }) )); } #[test] fn test_wrong_value_size() { let map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( HashMap::<_, u32, u16>::new(&map), Err(MapError::InvalidValueSize { size: 2, expected: 4 }) )); } #[test] fn test_try_from_wrong_map() { let map_data = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; let map = Map::Array(map_data); assert!(matches!( HashMap::<_, u8, u32>::try_from(&map), Err(MapError::InvalidMapType { .. }) )); } #[test] fn test_try_from_wrong_map_values() { let map_data = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; let map = Map::HashMap(map_data); assert!(matches!( HashMap::<_, u32, u16>::try_from(&map), Err(MapError::InvalidValueSize { size: 2, expected: 4 }) )); } #[test] fn test_new_not_created() { let mut map = MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, }; assert!(matches!( HashMap::<_, u32, u32>::new(&mut map), Err(MapError::NotCreated { .. }) )); } #[test] fn test_new_ok() { let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; assert!(HashMap::<_, u32, u32>::new(&mut map).is_ok()); } #[test] fn test_try_from_ok() { let map_data = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let map = Map::HashMap(map_data); assert!(HashMap::<_, u32, u32>::try_from(&map).is_ok()) } #[test] fn test_try_from_ok_lru() { let map_data = MapData { obj: obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_LRU_HASH as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: obj::MapKind::Other, }), fd: Some(42), pinned: false, btf_fd: None, }; let map = Map::HashMap(map_data); assert!(HashMap::<_, u32, u32>::try_from(&map).is_ok()) } #[test] fn test_insert_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut hm = HashMap::<_, u32, u32>::new(&mut map).unwrap(); assert!(matches!( hm.insert(1, 42, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_update_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_insert_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_UPDATE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut hm = HashMap::<_, u32, u32>::new(&mut map).unwrap(); assert!(hm.insert(1, 42, 0).is_ok()); } #[test] fn test_insert_boxed_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_UPDATE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut hm = HashMap::<_, u32, u32>::new(&mut map).unwrap(); assert!(hm.insert(Box::new(1), Box::new(42), 0).is_ok()); } #[test] fn test_remove_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut hm = HashMap::<_, u32, u32>::new(&mut map).unwrap(); assert!(matches!( hm.remove(&1), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_delete_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_remove_ok() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_DELETE_ELEM, .. } => Ok(1), _ => sys_error(EFAULT), }); let mut map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let mut hm = HashMap::<_, u32, u32>::new(&mut map).unwrap(); assert!(hm.remove(&1).is_ok()); } #[test] fn test_get_syscall_error() { override_syscall(|_| sys_error(EFAULT)); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); assert!(matches!( hm.get(&1, 0), Err(MapError::SyscallError { call, io_error }) if call == "bpf_map_lookup_elem" && io_error.raw_os_error() == Some(EFAULT) )); } #[test] fn test_get_not_found() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, .. } => sys_error(ENOENT), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); assert!(matches!(hm.get(&1, 0), Err(MapError::KeyNotFound))); } fn bpf_key<T: Copy>(attr: &bpf_attr) -> Option<T> { match unsafe { attr.__bindgen_anon_2.key } as *const T { p if p.is_null() => None, p => Some(unsafe { *p }), } } fn set_next_key<T: Copy>(attr: &bpf_attr, next: T) { let key = unsafe { attr.__bindgen_anon_2.__bindgen_anon_1.next_key } as *const T as *mut T; unsafe { *key = next }; } fn set_ret<T: Copy>(attr: &bpf_attr, ret: T) { let value = unsafe { attr.__bindgen_anon_2.__bindgen_anon_1.value } as *const T as *mut T; unsafe { *value = ret }; } #[test] fn test_keys_empty() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, .. } => sys_error(ENOENT), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let keys = hm.keys().collect::<Result<Vec<_>, _>>(); assert!(matches!(keys, Ok(ks) if ks.is_empty())) } fn get_next_key(attr: &bpf_attr) -> SysResult { match bpf_key(attr) { None => set_next_key(attr, 10), Some(10) => set_next_key(attr, 20), Some(20) => set_next_key(attr, 30), Some(30) => return sys_error(ENOENT), Some(_) => return sys_error(EFAULT), }; Ok(1) } fn lookup_elem(attr: &bpf_attr) -> SysResult { match bpf_key(attr) { Some(10) => set_ret(attr, 100), Some(20) => set_ret(attr, 200), Some(30) => set_ret(attr, 300), Some(_) => return sys_error(ENOENT), None => return sys_error(EFAULT), }; Ok(1) } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_keys() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => get_next_key(attr), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let keys = hm.keys().collect::<Result<Vec<_>, _>>().unwrap(); assert_eq!(&keys, &[10, 20, 30]) } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_keys_error() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => { match bpf_key(attr) { None => set_next_key(attr, 10), Some(10) => set_next_key(attr, 20), Some(_) => return sys_error(EFAULT), }; Ok(1) } _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let mut keys = hm.keys(); assert!(matches!(keys.next(), Some(Ok(10)))); assert!(matches!(keys.next(), Some(Ok(20)))); assert!(matches!( keys.next(), Some(Err(MapError::SyscallError { call, .. })) if call == "bpf_map_get_next_key" )); assert!(matches!(keys.next(), None)); } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_iter() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => get_next_key(attr), Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, attr, } => lookup_elem(attr), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let items = hm.iter().collect::<Result<Vec<_>, _>>().unwrap(); assert_eq!(&items, &[(10, 100), (20, 200), (30, 300)]) } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_iter_key_deleted() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => get_next_key(attr), Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, attr, } => { match bpf_key(attr) { Some(10) => set_ret(attr, 100), Some(20) => return sys_error(ENOENT), Some(30) => set_ret(attr, 300), Some(_) => return sys_error(ENOENT), None => return sys_error(EFAULT), }; Ok(1) } _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let items = hm.iter().collect::<Result<Vec<_>, _>>().unwrap(); assert_eq!(&items, &[(10, 100), (30, 300)]) } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_iter_key_error() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => { match bpf_key(attr) { None => set_next_key(attr, 10), Some(10) => set_next_key(attr, 20), Some(20) => return sys_error(EFAULT), Some(30) => return sys_error(ENOENT), Some(_) => panic!(), }; Ok(1) } Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, attr, } => lookup_elem(attr), _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let mut iter = hm.iter(); assert!(matches!(iter.next(), Some(Ok((10, 100))))); assert!(matches!(iter.next(), Some(Ok((20, 200))))); assert!(matches!( iter.next(), Some(Err(MapError::SyscallError { call, .. })) if call == "bpf_map_get_next_key" )); assert!(matches!(iter.next(), None)); } #[test] // Syscall overrides are performing integer-to-pointer conversions, which // should be done with `ptr::from_exposed_addr` in Rust nightly, but we have // to support stable as well. #[cfg_attr(miri, ignore)] fn test_iter_value_error() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY, attr, } => get_next_key(attr), Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM, attr, } => { match bpf_key(attr) { Some(10) => set_ret(attr, 100), Some(20) => return sys_error(EFAULT), Some(30) => set_ret(attr, 300), Some(_) => return sys_error(ENOENT), None => return sys_error(EFAULT), }; Ok(1) } _ => sys_error(EFAULT), }); let map = MapData { obj: new_obj_map(), fd: Some(42), pinned: false, btf_fd: None, }; let hm = HashMap::<_, u32, u32>::new(&map).unwrap(); let mut iter = hm.iter(); assert!(matches!(iter.next(), Some(Ok((10, 100))))); assert!(matches!( iter.next(), Some(Err(MapError::SyscallError { call, .. })) if call == "bpf_map_lookup_elem" )); assert!(matches!(iter.next(), Some(Ok((30, 300))))); assert!(matches!(iter.next(), None)); } } <file_sep>/bpf/aya-bpf/src/programs/fexit.rs use core::ffi::c_void; use crate::{args::FromBtfArgument, BpfContext}; pub struct FExitContext { ctx: *mut c_void, } impl FExitContext { pub fn new(ctx: *mut c_void) -> FExitContext { FExitContext { ctx } } /// Returns the `n`th argument to passed to the probe function, starting from 0. /// /// # Examples /// /// ```no_run /// # #![allow(non_camel_case_types)] /// # #![allow(dead_code)] /// # use aya_bpf::{cty::c_int, programs::FExitContext}; /// # type pid_t = c_int; /// # struct task_struct { /// # pid: pid_t, /// # } /// unsafe fn try_filename_lookup(ctx: FExitContext) -> Result<u32, u32> { /// let tp: *const task_struct = ctx.arg(0); /// /// // Do something with tp /// /// Ok(0) /// } /// ``` pub unsafe fn arg<T: FromBtfArgument>(&self, n: usize) -> T { T::from_argument(self.ctx as *const _, n) } } impl BpfContext for FExitContext { fn as_ptr(&self) -> *mut c_void { self.ctx } } <file_sep>/bpf/aya-bpf/src/programs/sock_addr.rs use core::ffi::c_void; use crate::{bindings::bpf_sock_addr, BpfContext}; pub struct SockAddrContext { pub sock_addr: *mut bpf_sock_addr, } impl SockAddrContext { pub fn new(sock_addr: *mut bpf_sock_addr) -> SockAddrContext { SockAddrContext { sock_addr } } } impl BpfContext for SockAddrContext { fn as_ptr(&self) -> *mut c_void { self.sock_addr as *mut _ } } <file_sep>/bpf/aya-bpf/src/programs/sysctl.rs use core::ffi::c_void; use crate::{bindings::bpf_sysctl, BpfContext}; pub struct SysctlContext { pub sysctl: *mut bpf_sysctl, } impl SysctlContext { pub fn new(sysctl: *mut bpf_sysctl) -> SysctlContext { SysctlContext { sysctl } } } impl BpfContext for SysctlContext { fn as_ptr(&self) -> *mut c_void { self.sysctl as *mut _ } } <file_sep>/bpf/aya-bpf/src/lib.rs //! [![](https://aya-rs.dev/assets/images/aya_logo_docs.svg)](https://aya-rs.dev) //! //! A library to write eBPF programs. //! //! Aya-bpf is an eBPF library built with a focus on operability and developer experience. //! It is the kernel-space counterpart of [Aya](https://docs.rs/aya) #![doc( html_logo_url = "https://aya-rs.dev/assets/images/crabby.svg", html_favicon_url = "https://aya-rs.dev/assets/images/crabby.svg" )] #![cfg_attr(unstable, feature(never_type))] #![allow(clippy::missing_safety_doc)] #![no_std] pub use aya_bpf_bindings::bindings; mod args; pub use args::PtRegs; pub mod helpers; pub mod maps; pub mod programs; pub use aya_bpf_cty as cty; use core::ffi::c_void; use cty::{c_int, c_long}; use helpers::{bpf_get_current_comm, bpf_get_current_pid_tgid, bpf_get_current_uid_gid}; pub use aya_bpf_macros as macros; pub const TASK_COMM_LEN: usize = 16; pub trait BpfContext { fn as_ptr(&self) -> *mut c_void; #[inline] fn command(&self) -> Result<[u8; TASK_COMM_LEN], c_long> { bpf_get_current_comm() } fn pid(&self) -> u32 { bpf_get_current_pid_tgid() as u32 } fn tgid(&self) -> u32 { (bpf_get_current_pid_tgid() >> 32) as u32 } fn uid(&self) -> u32 { bpf_get_current_uid_gid() as u32 } fn gid(&self) -> u32 { (bpf_get_current_uid_gid() >> 32) as u32 } } #[no_mangle] pub unsafe extern "C" fn memset(s: *mut u8, c: c_int, n: usize) { let base = s as usize; for i in 0..n { *((base + i) as *mut u8) = c as u8; } } #[no_mangle] pub unsafe extern "C" fn memcpy(dest: *mut u8, src: *mut u8, n: usize) { let dest_base = dest as usize; let src_base = src as usize; for i in 0..n { *((dest_base + i) as *mut u8) = *((src_base + i) as *mut u8); } } <file_sep>/aya/src/obj/btf/btf.rs use std::{ borrow::Cow, collections::HashMap, convert::TryInto, ffi::{CStr, CString}, fs, io, mem, path::{Path, PathBuf}, ptr, }; use bytes::BufMut; use log::debug; use object::Endianness; use thiserror::Error; use crate::{ generated::{btf_ext_header, btf_header}, obj::btf::{ info::{FuncSecInfo, LineSecInfo}, relocation::Relocation, Array, BtfEnum, BtfKind, BtfMember, BtfType, Const, Enum, FuncInfo, FuncLinkage, Int, IntEncoding, LineInfo, Struct, Typedef, VarLinkage, }, util::bytes_of, Features, }; pub(crate) const MAX_RESOLVE_DEPTH: u8 = 32; pub(crate) const MAX_SPEC_LEN: usize = 64; /// The error type returned when `BTF` operations fail. #[derive(Error, Debug)] pub enum BtfError { /// Error parsing file #[error("error parsing {path}")] FileError { /// file path path: PathBuf, /// source of the error #[source] error: io::Error, }, /// Error parsing BTF header #[error("error parsing BTF header")] InvalidHeader, /// invalid BTF type info segment #[error("invalid BTF type info segment")] InvalidTypeInfo, /// invalid BTF relocation info segment #[error("invalid BTF relocation info segment")] InvalidRelocationInfo, /// invalid BTF type kind #[error("invalid BTF type kind `{kind}`")] InvalidTypeKind { /// type kind kind: u32, }, /// invalid BTF relocation kind #[error("invalid BTF relocation kind `{kind}`")] InvalidRelocationKind { /// type kind kind: u32, }, /// invalid BTF string offset #[error("invalid BTF string offset: {offset}")] InvalidStringOffset { /// offset offset: usize, }, /// invalid BTF info #[error("invalid BTF info, offset: {offset} len: {len} section_len: {section_len}")] InvalidInfo { /// offset offset: usize, /// length len: usize, /// section length section_len: usize, }, /// invalid BTF line infos #[error("invalid BTF line info, offset: {offset} len: {len} section_len: {section_len}")] InvalidLineInfo { /// offset offset: usize, /// length len: usize, /// section length section_len: usize, }, /// unknown BTF type id #[error("Unknown BTF type id `{type_id}`")] UnknownBtfType { /// type id type_id: u32, }, /// unexpected btf type id #[error("Unexpected BTF type id `{type_id}`")] UnexpectedBtfType { /// type id type_id: u32, }, /// unknown BTF type #[error("Unknown BTF type `{type_name}`")] UnknownBtfTypeName { /// type name type_name: String, }, /// maximum depth reached resolving BTF type #[error("maximum depth reached resolving BTF type")] MaximumTypeDepthReached { /// type id type_id: u32, }, /// Loading the btf failed #[error("the BPF_BTF_LOAD syscall failed. Verifier output: {verifier_log}")] LoadError { /// The [`io::Error`] returned by the `BPF_BTF_LOAD` syscall. #[source] io_error: io::Error, /// The error log produced by the kernel verifier. verifier_log: String, }, /// offset not found for symbol #[error("Offset not found for symbol `{symbol_name}`")] SymbolOffsetNotFound { /// name of the symbol symbol_name: String, }, /// btf type that is not VAR found in DATASEC #[error("BTF type that is not VAR was found in DATASEC")] InvalidDatasec, /// unable to determine the size of section #[error("Unable to determine the size of section `{section_name}`")] UnknownSectionSize { /// name of the section section_name: String, }, /// unable to get symbol name #[error("Unable to get symbol name")] InvalidSymbolName, } /// Bpf Type Format metadata. /// /// BTF is a kind of debug metadata that allows eBPF programs compiled against one kernel version /// to be loaded into different kernel versions. /// /// Aya automatically loads BTF metadata if you use [`Bpf::load_file`](crate::Bpf::load_file). You /// only need to explicitly use this type if you want to load BTF from a non-standard /// location or if you are using [`Bpf::load`](crate::Bpf::load). #[derive(Clone, Debug)] pub struct Btf { header: btf_header, strings: Vec<u8>, types: BtfTypes, _endianness: Endianness, } impl Btf { pub(crate) fn new() -> Btf { Btf { header: btf_header { magic: 0xeb9f, version: 0x01, flags: 0x00, hdr_len: 0x18, type_off: 0x00, type_len: 0x00, str_off: 0x00, str_len: 0x00, }, strings: vec![0], types: BtfTypes::default(), _endianness: Endianness::default(), } } pub(crate) fn types(&self) -> impl Iterator<Item = &BtfType> { self.types.types.iter() } pub(crate) fn add_string(&mut self, name: String) -> u32 { let str = CString::new(name).unwrap(); let name_offset = self.strings.len(); self.strings.extend(str.as_c_str().to_bytes_with_nul()); self.header.str_len = self.strings.len() as u32; name_offset as u32 } pub(crate) fn add_type(&mut self, btf_type: BtfType) -> u32 { let size = btf_type.type_info_size() as u32; let type_id = self.types.len(); self.types.push(btf_type); self.header.type_len += size; self.header.str_off += size; type_id as u32 } /// Loads BTF metadata from `/sys/kernel/btf/vmlinux`. pub fn from_sys_fs() -> Result<Btf, BtfError> { Btf::parse_file("/sys/kernel/btf/vmlinux", Endianness::default()) } /// Loads BTF metadata from the given `path`. pub fn parse_file<P: AsRef<Path>>(path: P, endianness: Endianness) -> Result<Btf, BtfError> { let path = path.as_ref(); Btf::parse( &fs::read(path).map_err(|error| BtfError::FileError { path: path.to_owned(), error, })?, endianness, ) } pub(crate) fn parse(data: &[u8], endianness: Endianness) -> Result<Btf, BtfError> { if data.len() < mem::size_of::<btf_header>() { return Err(BtfError::InvalidHeader); } // safety: btf_header is POD so read_unaligned is safe let header = unsafe { read_btf_header(data) }; let str_off = header.hdr_len as usize + header.str_off as usize; let str_len = header.str_len as usize; if str_off + str_len > data.len() { return Err(BtfError::InvalidHeader); } let strings = data[str_off..str_off + str_len].to_vec(); let types = Btf::read_type_info(&header, data, endianness)?; Ok(Btf { header, strings, types, _endianness: endianness, }) } fn read_type_info( header: &btf_header, data: &[u8], endianness: Endianness, ) -> Result<BtfTypes, BtfError> { let hdr_len = header.hdr_len as usize; let type_off = header.type_off as usize; let type_len = header.type_len as usize; let base = hdr_len + type_off; if base + type_len > data.len() { return Err(BtfError::InvalidTypeInfo); } let mut data = &data[base..base + type_len]; let mut types = BtfTypes::default(); while !data.is_empty() { // Safety: // read() reads POD values from ELF, which is sound, but the values can still contain // internally inconsistent values (like out of bound offsets and such). let ty = unsafe { BtfType::read(data, endianness)? }; data = &data[ty.type_info_size()..]; types.push(ty); } Ok(types) } pub(crate) fn string_at(&self, offset: u32) -> Result<Cow<'_, str>, BtfError> { let btf_header { hdr_len, mut str_off, str_len, .. } = self.header; str_off += hdr_len; if offset >= str_off + str_len { return Err(BtfError::InvalidStringOffset { offset: offset as usize, }); } let offset = offset as usize; let nul = self.strings[offset..] .iter() .position(|c| *c == 0u8) .ok_or(BtfError::InvalidStringOffset { offset })?; let s = CStr::from_bytes_with_nul(&self.strings[offset..=offset + nul]) .map_err(|_| BtfError::InvalidStringOffset { offset })?; Ok(s.to_string_lossy()) } pub(crate) fn type_by_id(&self, type_id: u32) -> Result<&BtfType, BtfError> { self.types.type_by_id(type_id) } pub(crate) fn resolve_type(&self, root_type_id: u32) -> Result<u32, BtfError> { self.types.resolve_type(root_type_id) } pub(crate) fn type_name(&self, ty: &BtfType) -> Result<Cow<'_, str>, BtfError> { self.string_at(ty.name_offset()) } pub(crate) fn err_type_name(&self, ty: &BtfType) -> Option<String> { self.string_at(ty.name_offset()).ok().map(String::from) } pub(crate) fn id_by_type_name_kind(&self, name: &str, kind: BtfKind) -> Result<u32, BtfError> { for (type_id, ty) in self.types().enumerate() { if ty.kind() != kind { continue; } if self.type_name(ty)? == name { return Ok(type_id as u32); } continue; } Err(BtfError::UnknownBtfTypeName { type_name: name.to_string(), }) } pub(crate) fn type_size(&self, root_type_id: u32) -> Result<usize, BtfError> { let mut type_id = root_type_id; let mut n_elems = 1; for _ in 0..MAX_RESOLVE_DEPTH { let ty = self.types.type_by_id(type_id)?; let size = match ty { BtfType::Array(Array { array, .. }) => { n_elems = array.len; type_id = array.element_type; continue; } other => { if let Some(size) = other.size() { size } else if let Some(next) = other.btf_type() { type_id = next; continue; } else { return Err(BtfError::UnexpectedBtfType { type_id }); } } }; return Ok((size * n_elems) as usize); } Err(BtfError::MaximumTypeDepthReached { type_id: root_type_id, }) } pub(crate) fn to_bytes(&self) -> Vec<u8> { // Safety: btf_header is POD let mut buf = unsafe { bytes_of::<btf_header>(&self.header).to_vec() }; // Skip the first type since it's always BtfType::Unknown for type_by_id to work buf.extend(self.types.to_bytes()); buf.put(self.strings.as_slice()); buf } pub(crate) fn fixup_and_sanitize( &mut self, section_sizes: &HashMap<String, u64>, symbol_offsets: &HashMap<String, u64>, features: &Features, ) -> Result<(), BtfError> { let mut types = mem::take(&mut self.types); for i in 0..types.types.len() { let t = &types.types[i]; let kind = t.kind(); match t { // Fixup PTR for Rust // LLVM emits names for Rust pointer types, which the kernel doesn't like // While I figure out if this needs fixing in the Kernel or LLVM, we'll // do a fixup here BtfType::Ptr(ptr) => { let mut fixed_ty = ptr.clone(); fixed_ty.name_offset = 0; types.types[i] = BtfType::Ptr(fixed_ty) } // Sanitize VAR if they are not supported BtfType::Var(v) if !features.btf_datasec => { types.types[i] = BtfType::Int(Int::new(v.name_offset, 1, IntEncoding::None, 0)); } // Sanitize DATASEC if they are not supported BtfType::DataSec(d) if !features.btf_datasec => { debug!("{}: not supported. replacing with STRUCT", kind); let mut members = vec![]; for member in d.entries.iter() { let mt = types.type_by_id(member.btf_type).unwrap(); members.push(BtfMember { name_offset: mt.name_offset(), btf_type: member.btf_type, offset: member.offset * 8, }) } types.types[i] = BtfType::Struct(Struct::new(t.name_offset(), members, 0)); } // Fixup DATASEC // DATASEC sizes aren't always set by LLVM // we need to fix them here before loading the btf to the kernel BtfType::DataSec(d) if features.btf_datasec => { // Start DataSec Fixups let sec_name = self.string_at(d.name_offset)?; let name = sec_name.to_string(); let mut fixed_ty = d.clone(); // Handle any "/" characters in section names // Example: "maps/hashmap" let fixed_name = name.replace('/', "."); if fixed_name != name { fixed_ty.name_offset = self.add_string(fixed_name); } // There are some cases when the compiler does indeed populate the // size if t.size().unwrap() > 0 { debug!("{} {}: size fixup not required", kind, name); } else { // We need to get the size of the section from the ELF file // Fortunately, we cached these when parsing it initially // and we can this up by name in section_sizes let size = section_sizes.get(&name).ok_or_else(|| { BtfError::UnknownSectionSize { section_name: name.clone(), } })?; debug!("{} {}: fixup size to {}", kind, name, size); fixed_ty.size = *size as u32; // The Vec<btf_var_secinfo> contains BTF_KIND_VAR sections // that need to have their offsets adjusted. To do this, // we need to get the offset from the ELF file. // This was also cached during initial parsing and // we can query by name in symbol_offsets for d in &mut fixed_ty.entries.iter_mut() { let var_type = types.type_by_id(d.btf_type)?; let var_kind = var_type.kind(); if let BtfType::Var(var) = var_type { let var_name = self.string_at(var.name_offset)?.to_string(); if var.linkage == VarLinkage::Static { debug!( "{} {}: {} {}: fixup not required", kind, name, var_kind, var_name ); continue; } let offset = symbol_offsets.get(&var_name).ok_or( BtfError::SymbolOffsetNotFound { symbol_name: var_name.clone(), }, )?; d.offset = *offset as u32; debug!( "{} {}: {} {}: fixup offset {}", kind, name, var_kind, var_name, offset ); } else { return Err(BtfError::InvalidDatasec); } } } types.types[i] = BtfType::DataSec(fixed_ty); } // Fixup FUNC_PROTO BtfType::FuncProto(ty) if features.btf_func => { let mut ty = ty.clone(); for (i, mut param) in ty.params.iter_mut().enumerate() { if param.name_offset == 0 && param.btf_type != 0 { param.name_offset = self.add_string(format!("param{i}")); } } types.types[i] = BtfType::FuncProto(ty); } // Sanitize FUNC_PROTO BtfType::FuncProto(ty) if !features.btf_func => { debug!("{}: not supported. replacing with ENUM", kind); let members: Vec<BtfEnum> = ty .params .iter() .map(|p| BtfEnum { name_offset: p.name_offset, value: p.btf_type as i32, }) .collect(); let enum_type = BtfType::Enum(Enum::new(ty.name_offset, members)); types.types[i] = enum_type; } // Sanitize FUNC BtfType::Func(ty) if !features.btf_func => { debug!("{}: not supported. replacing with TYPEDEF", kind); let typedef_type = BtfType::Typedef(Typedef::new(ty.name_offset, ty.btf_type)); types.types[i] = typedef_type; } // Sanitize BTF_FUNC_GLOBAL BtfType::Func(ty) if !features.btf_func_global => { let mut fixed_ty = ty.clone(); if ty.linkage() == FuncLinkage::Global { debug!( "{}: BTF_FUNC_GLOBAL not supported. replacing with BTF_FUNC_STATIC", kind ); fixed_ty.set_linkage(FuncLinkage::Static); } types.types[i] = BtfType::Func(fixed_ty); } // Sanitize FLOAT BtfType::Float(ty) if !features.btf_float => { debug!("{}: not supported. replacing with STRUCT", kind); let struct_ty = BtfType::Struct(Struct::new(0, vec![], ty.size)); types.types[i] = struct_ty; } // Sanitize DECL_TAG BtfType::DeclTag(ty) if !features.btf_decl_tag => { debug!("{}: not supported. replacing with INT", kind); let int_type = BtfType::Int(Int::new(ty.name_offset, 1, IntEncoding::None, 0)); types.types[i] = int_type; } // Sanitize TYPE_TAG BtfType::TypeTag(ty) if !features.btf_type_tag => { debug!("{}: not supported. replacing with CONST", kind); let const_type = BtfType::Const(Const::new(ty.btf_type)); types.types[i] = const_type; } // The type does not need fixing up or sanitization _ => {} } } self.types = types; Ok(()) } } impl Default for Btf { fn default() -> Self { Self::new() } } unsafe fn read_btf_header(data: &[u8]) -> btf_header { // safety: btf_header is POD so read_unaligned is safe ptr::read_unaligned(data.as_ptr() as *const btf_header) } #[derive(Debug, Clone)] pub struct BtfExt { data: Vec<u8>, _endianness: Endianness, relocations: Vec<(u32, Vec<Relocation>)>, header: btf_ext_header, func_info_rec_size: usize, pub(crate) func_info: FuncInfo, line_info_rec_size: usize, pub(crate) line_info: LineInfo, core_relo_rec_size: usize, } impl BtfExt { pub(crate) fn parse( data: &[u8], endianness: Endianness, btf: &Btf, ) -> Result<BtfExt, BtfError> { // Safety: btf_ext_header is POD so read_unaligned is safe let header = unsafe { ptr::read_unaligned::<btf_ext_header>(data.as_ptr() as *const btf_ext_header) }; let rec_size = |offset, len| { let offset = mem::size_of::<btf_ext_header>() + offset as usize; let len = len as usize; // check that there's at least enough space for the `rec_size` field if (len > 0 && len < 4) || offset + len > data.len() { return Err(BtfError::InvalidInfo { offset, len, section_len: data.len(), }); } let read_u32 = if endianness == Endianness::Little { u32::from_le_bytes } else { u32::from_be_bytes }; Ok(if len > 0 { read_u32(data[offset..offset + 4].try_into().unwrap()) as usize } else { 0 }) }; let btf_ext_header { func_info_off, func_info_len, line_info_off, line_info_len, core_relo_off, core_relo_len, .. } = header; let mut ext = BtfExt { header, relocations: Vec::new(), func_info: FuncInfo::new(), line_info: LineInfo::new(), func_info_rec_size: rec_size(func_info_off, func_info_len)?, line_info_rec_size: rec_size(line_info_off, line_info_len)?, core_relo_rec_size: rec_size(core_relo_off, core_relo_len)?, data: data.to_vec(), _endianness: endianness, }; let func_info_rec_size = ext.func_info_rec_size; ext.func_info.data.extend( SecInfoIter::new(ext.func_info_data(), ext.func_info_rec_size, endianness) .map(move |sec| { let name = btf .string_at(sec.name_offset) .ok() .map(String::from) .unwrap(); let info = FuncSecInfo::parse( sec.name_offset, sec.num_info, func_info_rec_size, sec.data, endianness, ); Ok((name, info)) }) .collect::<Result<HashMap<_, _>, _>>()?, ); let line_info_rec_size = ext.line_info_rec_size; ext.line_info.data.extend( SecInfoIter::new(ext.line_info_data(), ext.line_info_rec_size, endianness) .map(move |sec| { let name = btf .string_at(sec.name_offset) .ok() .map(String::from) .unwrap(); let info = LineSecInfo::parse( sec.name_offset, sec.num_info, line_info_rec_size, sec.data, endianness, ); Ok((name, info)) }) .collect::<Result<HashMap<_, _>, _>>()?, ); let rec_size = ext.core_relo_rec_size; ext.relocations.extend( SecInfoIter::new(ext.core_relo_data(), ext.core_relo_rec_size, endianness) .map(move |sec| { let relos = sec .data .chunks(rec_size) .enumerate() .map(|(n, rec)| unsafe { Relocation::parse(rec, n) }) .collect::<Result<Vec<_>, _>>()?; Ok((sec.name_offset, relos)) }) .collect::<Result<Vec<_>, _>>()?, ); Ok(ext) } fn info_data(&self, offset: u32, len: u32) -> &[u8] { let offset = (self.header.hdr_len + offset) as usize; let data = &self.data[offset..offset + len as usize]; if len > 0 { // skip `rec_size` &data[4..] } else { data } } fn core_relo_data(&self) -> &[u8] { self.info_data(self.header.core_relo_off, self.header.core_relo_len) } fn func_info_data(&self) -> &[u8] { self.info_data(self.header.func_info_off, self.header.func_info_len) } fn line_info_data(&self) -> &[u8] { self.info_data(self.header.line_info_off, self.header.line_info_len) } pub(crate) fn relocations(&self) -> impl Iterator<Item = &(u32, Vec<Relocation>)> { self.relocations.iter() } pub(crate) fn func_info_rec_size(&self) -> usize { self.func_info_rec_size } pub(crate) fn line_info_rec_size(&self) -> usize { self.line_info_rec_size } } pub(crate) struct SecInfoIter<'a> { data: &'a [u8], offset: usize, rec_size: usize, endianness: Endianness, } impl<'a> SecInfoIter<'a> { fn new(data: &'a [u8], rec_size: usize, endianness: Endianness) -> Self { Self { data, rec_size, offset: 0, endianness, } } } impl<'a> Iterator for SecInfoIter<'a> { type Item = SecInfo<'a>; fn next(&mut self) -> Option<Self::Item> { let data = self.data; if self.offset + 8 >= data.len() { return None; } let read_u32 = if self.endianness == Endianness::Little { u32::from_le_bytes } else { u32::from_be_bytes }; let name_offset = read_u32(data[self.offset..self.offset + 4].try_into().unwrap()); self.offset += 4; let num_info = u32::from_ne_bytes(data[self.offset..self.offset + 4].try_into().unwrap()); self.offset += 4; let data = &data[self.offset..self.offset + (self.rec_size * num_info as usize)]; self.offset += self.rec_size * num_info as usize; Some(SecInfo { name_offset, num_info, data, }) } } /// BtfTypes allows for access and manipulation of a /// collection of BtfType objects #[derive(Debug, Clone)] pub(crate) struct BtfTypes { pub(crate) types: Vec<BtfType>, } impl Default for BtfTypes { fn default() -> Self { Self { types: vec![BtfType::Unknown], } } } impl BtfTypes { pub(crate) fn to_bytes(&self) -> Vec<u8> { let mut buf = vec![]; for t in self.types.iter().skip(1) { let b = t.to_bytes(); buf.extend(b) } buf } pub(crate) fn len(&self) -> usize { self.types.len() } pub(crate) fn push(&mut self, value: BtfType) { self.types.push(value) } pub(crate) fn type_by_id(&self, type_id: u32) -> Result<&BtfType, BtfError> { self.types .get(type_id as usize) .ok_or(BtfError::UnknownBtfType { type_id }) } pub(crate) fn resolve_type(&self, root_type_id: u32) -> Result<u32, BtfError> { let mut type_id = root_type_id; for _ in 0..MAX_RESOLVE_DEPTH { let ty = self.type_by_id(type_id)?; use BtfType::*; match ty { Volatile(ty) => { type_id = ty.btf_type; continue; } Const(ty) => { type_id = ty.btf_type; continue; } Restrict(ty) => { type_id = ty.btf_type; continue; } Typedef(ty) => { type_id = ty.btf_type; continue; } TypeTag(ty) => { type_id = ty.btf_type; continue; } _ => return Ok(type_id), } } Err(BtfError::MaximumTypeDepthReached { type_id: root_type_id, }) } } #[derive(Debug)] pub(crate) struct SecInfo<'a> { name_offset: u32, num_info: u32, data: &'a [u8], } #[cfg(test)] mod tests { use crate::obj::btf::{ BtfParam, DataSec, DataSecEntry, DeclTag, Float, Func, FuncProto, Ptr, TypeTag, Var, }; use super::*; #[test] fn test_parse_header() { let data: &[u8] = &[ 0x9f, 0xeb, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x54, 0x2a, 0x00, 0x64, 0x54, 0x2a, 0x00, 0x10, 0x64, 0x1c, 0x00, ]; let header = unsafe { read_btf_header(data) }; assert_eq!(header.magic, 0xeb9f); assert_eq!(header.version, 0x01); assert_eq!(header.flags, 0x00); assert_eq!(header.hdr_len, 0x18); assert_eq!(header.type_off, 0x00); assert_eq!(header.type_len, 0x2a5464); assert_eq!(header.str_off, 0x2a5464); assert_eq!(header.str_len, 0x1c6410); } #[test] fn test_parse_btf() { // this generated BTF data is from an XDP program that simply returns XDP_PASS // compiled using clang let data: &[u8] = &[ 0x9f, 0xeb, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x01, 0x00, 0x00, 0x0c, 0x01, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x04, 0x18, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x04, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0d, 0x06, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x69, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0c, 0x05, 0x00, 0x00, 0x00, 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd9, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x78, 0x64, 0x70, 0x5f, 0x6d, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x65, 0x6e, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x72, 0x78, 0x5f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x65, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x5f, 0x5f, 0x75, 0x33, 0x32, 0x00, 0x75, 0x6e, 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x00, 0x63, 0x74, 0x78, 0x00, 0x69, 0x6e, 0x74, 0x00, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x00, 0x78, 0x64, 0x70, 0x2f, 0x70, 0x61, 0x73, 0x73, 0x00, 0x2f, 0x68, 0x6f, 0x6d, 0x65, 0x2f, 0x64, 0x61, 0x76, 0x65, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x62, 0x70, 0x66, 0x64, 0x2f, 0x62, 0x70, 0x66, 0x2f, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x2e, 0x62, 0x70, 0x66, 0x2e, 0x63, 0x00, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x58, 0x44, 0x50, 0x5f, 0x50, 0x41, 0x53, 0x53, 0x3b, 0x00, 0x63, 0x68, 0x61, 0x72, 0x00, 0x5f, 0x5f, 0x41, 0x52, 0x52, 0x41, 0x59, 0x5f, 0x53, 0x49, 0x5a, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x5f, 0x00, 0x5f, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x00, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x00, ]; assert_eq!(data.len(), 517); let got = Btf::parse(data, Endianness::default()); match got { Ok(_) => {} Err(e) => panic!("{}", e), } let btf = got.unwrap(); let data2 = btf.to_bytes(); assert_eq!(data2.len(), 517); assert_eq!(data, data2); let ext_data: &[u8] = &[ 0x9f, 0xeb, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x00, 0xa2, 0x00, 0x00, 0x00, 0x05, 0x2c, 0x00, 0x00, ]; assert_eq!(ext_data.len(), 80); let got = BtfExt::parse(ext_data, Endianness::default(), &btf); if let Err(e) = got { panic!("{}", e) } } #[test] fn test_write_btf() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); btf.add_type(int_type); let name_offset = btf.add_string("widget".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); btf.add_type(int_type); let btf_bytes = btf.to_bytes(); let raw_btf = btf_bytes.as_slice(); let parsed = Btf::parse(raw_btf, Endianness::default()); match parsed { Ok(btf) => { assert_eq!(btf.string_at(1).unwrap(), "int"); assert_eq!(btf.string_at(5).unwrap(), "widget"); } Err(e) => { panic!("{}", e) } } } #[test] fn test_fixup_ptr() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let name_offset = btf.add_string("&mut int".to_string()); let ptr_type_id = btf.add_type(BtfType::Ptr(Ptr::new(name_offset, int_type_id))); let features = Features { ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Ptr(fixed) = btf.type_by_id(ptr_type_id).unwrap() { assert!( fixed.name_offset == 0, "expected offset 0, got {}", fixed.name_offset ) } else { panic!("not a ptr") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_var() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let name_offset = btf.add_string("&mut int".to_string()); let var_type_id = btf.add_type(BtfType::Var(Var::new( name_offset, int_type_id, VarLinkage::Static, ))); let features = Features { btf_datasec: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Int(fixed) = btf.type_by_id(var_type_id).unwrap() { assert!(fixed.name_offset == name_offset) } else { panic!("not an int") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_datasec() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let name_offset = btf.add_string("foo".to_string()); let var_type_id = btf.add_type(BtfType::Var(Var::new( name_offset, int_type_id, VarLinkage::Static, ))); let name_offset = btf.add_string(".data".to_string()); let variables = vec![DataSecEntry { btf_type: var_type_id, offset: 0, size: 4, }]; let datasec_type_id = btf.add_type(BtfType::DataSec(DataSec::new(name_offset, variables, 0))); let features = Features { btf_datasec: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Struct(fixed) = btf.type_by_id(datasec_type_id).unwrap() { assert!(fixed.name_offset == name_offset); assert!(fixed.members.len() == 1); assert!(fixed.members[0].btf_type == var_type_id); assert!(fixed.members[0].offset == 0) } else { panic!("not a struct") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_fixup_datasec() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let name_offset = btf.add_string("foo".to_string()); let var_type_id = btf.add_type(BtfType::Var(Var::new( name_offset, int_type_id, VarLinkage::Global, ))); let name_offset = btf.add_string(".data/foo".to_string()); let variables = vec![DataSecEntry { btf_type: var_type_id, offset: 0, size: 4, }]; let datasec_type_id = btf.add_type(BtfType::DataSec(DataSec::new(name_offset, variables, 0))); let features = Features { btf_datasec: true, ..Default::default() }; btf.fixup_and_sanitize( &HashMap::from([(".data/foo".to_string(), 32u64)]), &HashMap::from([("foo".to_string(), 64u64)]), &features, ) .unwrap(); if let BtfType::DataSec(fixed) = btf.type_by_id(datasec_type_id).unwrap() { assert!(fixed.name_offset != name_offset); assert!(fixed.size == 32); assert!(fixed.entries.len() == 1); assert!(fixed.entries[0].btf_type == var_type_id); assert!( fixed.entries[0].offset == 64, "expected 64, got {}", fixed.entries[0].offset ); assert!(btf.string_at(fixed.name_offset).unwrap() == ".data.foo") } else { panic!("not a datasec") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_func_and_proto() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let params = vec![ BtfParam { name_offset: btf.add_string("a".to_string()), btf_type: int_type_id, }, BtfParam { name_offset: btf.add_string("b".to_string()), btf_type: int_type_id, }, ]; let func_proto_type_id = btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id))); let inc = btf.add_string("inc".to_string()); let func_type_id = btf.add_type(BtfType::Func(Func::new( inc, func_proto_type_id, FuncLinkage::Static, ))); let features = Features { btf_func: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Enum(fixed) = btf.type_by_id(func_proto_type_id).unwrap() { assert!(fixed.name_offset == 0); assert!(fixed.variants.len() == 2); assert!(btf.string_at(fixed.variants[0].name_offset).unwrap() == "a"); assert!(fixed.variants[0].value == int_type_id as i32); assert!(btf.string_at(fixed.variants[1].name_offset).unwrap() == "b"); assert!(fixed.variants[1].value == int_type_id as i32); } else { panic!("not an emum") } if let BtfType::Typedef(fixed) = btf.type_by_id(func_type_id).unwrap() { assert!(fixed.name_offset == inc); assert!(fixed.btf_type == func_proto_type_id); } else { panic!("not a typedef") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_fixup_func_proto() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type_id = btf.add_type(int_type); let params = vec![ BtfParam { name_offset: 0, btf_type: int_type_id, }, BtfParam { name_offset: 0, btf_type: int_type_id, }, ]; let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id)); let func_proto_type_id = btf.add_type(func_proto); let features = Features { btf_func: true, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::FuncProto(fixed) = btf.type_by_id(func_proto_type_id).unwrap() { assert!(btf.string_at(fixed.params[0].name_offset).unwrap() == "param0"); assert!(btf.string_at(fixed.params[1].name_offset).unwrap() == "param1"); } else { panic!("not a func_proto") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_func_global() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let params = vec![ BtfParam { name_offset: btf.add_string("a".to_string()), btf_type: int_type_id, }, BtfParam { name_offset: btf.add_string("b".to_string()), btf_type: int_type_id, }, ]; let func_proto_type_id = btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id))); let inc = btf.add_string("inc".to_string()); let func_type_id = btf.add_type(BtfType::Func(Func::new( inc, func_proto_type_id, FuncLinkage::Global, ))); let features = Features { btf_func: true, btf_func_global: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Func(fixed) = btf.type_by_id(func_type_id).unwrap() { assert!(fixed.linkage() == FuncLinkage::Static); } else { panic!("not a func") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_float() { let mut btf = Btf::new(); let name_offset = btf.add_string("float".to_string()); let float_type_id = btf.add_type(BtfType::Float(Float::new(name_offset, 16))); let features = Features { btf_float: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Struct(fixed) = btf.type_by_id(float_type_id).unwrap() { assert!(fixed.name_offset == 0); assert!(fixed.size == 16); } else { panic!("not a struct") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_decl_tag() { let mut btf = Btf::new(); let name_offset = btf.add_string("int".to_string()); let int_type_id = btf.add_type(BtfType::Int(Int::new( name_offset, 4, IntEncoding::Signed, 0, ))); let name_offset = btf.add_string("foo".to_string()); let var_type_id = btf.add_type(BtfType::Var(Var::new( name_offset, int_type_id, VarLinkage::Static, ))); let name_offset = btf.add_string("decl_tag".to_string()); let decl_tag_type_id = btf.add_type(BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1))); let features = Features { btf_decl_tag: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Int(fixed) = btf.type_by_id(decl_tag_type_id).unwrap() { assert!(fixed.name_offset == name_offset); assert!(fixed.size == 1); } else { panic!("not an int") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] fn test_sanitize_type_tag() { let mut btf = Btf::new(); let int_type_id = btf.add_type(BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0))); let name_offset = btf.add_string("int".to_string()); let type_tag_type = btf.add_type(BtfType::TypeTag(TypeTag::new(name_offset, int_type_id))); btf.add_type(BtfType::Ptr(Ptr::new(0, type_tag_type))); let features = Features { btf_type_tag: false, ..Default::default() }; btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features) .unwrap(); if let BtfType::Const(fixed) = btf.type_by_id(type_tag_type).unwrap() { assert!(fixed.btf_type == int_type_id); } else { panic!("not a const") } // Ensure we can convert to bytes and back again let raw = btf.to_bytes(); Btf::parse(&raw, Endianness::default()).unwrap(); } #[test] #[cfg_attr(miri, ignore)] fn test_read_btf_from_sys_fs() { let btf = Btf::parse_file("/sys/kernel/btf/vmlinux", Endianness::default()).unwrap(); let task_struct_id = btf .id_by_type_name_kind("task_struct", BtfKind::Struct) .unwrap(); // we can't assert on exact ID since this may change across kernel versions assert!(task_struct_id != 0); let netif_id = btf .id_by_type_name_kind("netif_receive_skb", BtfKind::Func) .unwrap(); assert!(netif_id != 0); let u32_def = btf.id_by_type_name_kind("__u32", BtfKind::Typedef).unwrap(); assert!(u32_def != 0); let u32_base = btf.resolve_type(u32_def).unwrap(); assert!(u32_base != 0); let u32_ty = btf.type_by_id(u32_base).unwrap(); assert_eq!(u32_ty.kind(), BtfKind::Int); } } <file_sep>/aya/src/programs/mod.rs //! eBPF program types. //! //! eBPF programs are loaded inside the kernel and attached to one or more hook //! points. Whenever the hook points are reached, the programs are executed. //! //! # Loading and attaching programs //! //! When you call [`Bpf::load_file`] or [`Bpf::load`], all the programs included //! in the object code are parsed and relocated. Programs are not loaded //! automatically though, since often you will need to do some application //! specific setup before you can actually load them. //! //! In order to load and attach a program, you need to retrieve it using [`Bpf::program_mut`], //! then call the `load()` and `attach()` methods, for example: //! //! ```no_run //! use aya::{Bpf, programs::KProbe}; //! //! let mut bpf = Bpf::load_file("ebpf_programs.o")?; //! // intercept_wakeups is the name of the program we want to load //! let program: &mut KProbe = bpf.program_mut("intercept_wakeups").unwrap().try_into()?; //! program.load()?; //! // intercept_wakeups will be called every time try_to_wake_up() is called //! // inside the kernel //! program.attach("try_to_wake_up", 0)?; //! # Ok::<(), aya::BpfError>(()) //! ``` //! //! The signature of the `attach()` method varies depending on what kind of //! program you're trying to attach. //! //! [`Bpf::load_file`]: crate::Bpf::load_file //! [`Bpf::load`]: crate::Bpf::load //! [`Bpf::programs`]: crate::Bpf::programs //! [`Bpf::program`]: crate::Bpf::program //! [`Bpf::program_mut`]: crate::Bpf::program_mut //! [`maps`]: crate::maps pub mod cgroup_device; pub mod cgroup_skb; pub mod cgroup_sock; pub mod cgroup_sock_addr; pub mod cgroup_sockopt; pub mod cgroup_sysctl; pub mod extension; pub mod fentry; pub mod fexit; pub mod kprobe; pub mod links; pub mod lirc_mode2; pub mod lsm; pub mod perf_attach; pub mod perf_event; mod probe; mod raw_trace_point; mod sk_lookup; mod sk_msg; mod sk_skb; mod sock_ops; mod socket_filter; pub mod tc; pub mod tp_btf; pub mod trace_point; pub mod uprobe; mod utils; pub mod xdp; use libc::ENOSPC; use std::{ ffi::CString, io, os::unix::io::{AsRawFd, RawFd}, path::Path, }; use thiserror::Error; pub use cgroup_device::CgroupDevice; pub use cgroup_skb::{CgroupSkb, CgroupSkbAttachType}; pub use cgroup_sock::{CgroupSock, CgroupSockAttachType}; pub use cgroup_sock_addr::{CgroupSockAddr, CgroupSockAddrAttachType}; pub use cgroup_sockopt::{CgroupSockopt, CgroupSockoptAttachType}; pub use cgroup_sysctl::CgroupSysctl; pub use extension::{Extension, ExtensionError}; pub use fentry::FEntry; pub use fexit::FExit; pub use kprobe::{KProbe, KProbeError}; pub use links::Link; use links::*; pub use lirc_mode2::LircMode2; pub use lsm::Lsm; use perf_attach::*; pub use perf_event::{PerfEvent, PerfEventScope, PerfTypeId, SamplePolicy}; pub use probe::ProbeKind; pub use raw_trace_point::RawTracePoint; pub use sk_lookup::SkLookup; pub use sk_msg::SkMsg; pub use sk_skb::{SkSkb, SkSkbKind}; pub use sock_ops::SockOps; pub use socket_filter::{SocketFilter, SocketFilterError}; pub use tc::{SchedClassifier, TcAttachType, TcError}; pub use tp_btf::BtfTracePoint; pub use trace_point::{TracePoint, TracePointError}; pub use uprobe::{UProbe, UProbeError}; pub use xdp::{Xdp, XdpError, XdpFlags}; use crate::{ generated::{bpf_attach_type, bpf_prog_info, bpf_prog_type}, maps::MapError, obj::{self, btf::BtfError, Function, KernelVersion}, pin::PinError, sys::{ bpf_get_object, bpf_load_program, bpf_pin_object, bpf_prog_get_fd_by_id, bpf_prog_get_info_by_fd, bpf_prog_query, retry_with_verifier_logs, BpfLoadProgramAttrs, }, util::VerifierLog, }; /// Error type returned when working with programs. #[derive(Debug, Error)] pub enum ProgramError { /// The program is already loaded. #[error("the program is already loaded")] AlreadyLoaded, /// The program is not loaded. #[error("the program is not loaded")] NotLoaded, /// The program is already attached. #[error("the program was already attached")] AlreadyAttached, /// The program is not attached. #[error("the program is not attached")] NotAttached, /// Loading the program failed. #[error("the BPF_PROG_LOAD syscall failed. Verifier output: {verifier_log}")] LoadError { /// The [`io::Error`] returned by the `BPF_PROG_LOAD` syscall. #[source] io_error: io::Error, /// The error log produced by the kernel verifier. verifier_log: String, }, /// A syscall failed. #[error("`{call}` failed")] SyscallError { /// The name of the syscall which failed. call: String, /// The [`io::Error`] returned by the syscall. #[source] io_error: io::Error, }, /// The network interface does not exist. #[error("unknown network interface {name}")] UnknownInterface { /// interface name name: String, }, /// The program is not of the expected type. #[error("unexpected program type")] UnexpectedProgramType, /// A map error occurred while loading or attaching a program. #[error(transparent)] MapError(#[from] MapError), /// An error occurred while working with a [`KProbe`]. #[error(transparent)] KProbeError(#[from] KProbeError), /// An error occurred while working with an [`UProbe`]. #[error(transparent)] UProbeError(#[from] UProbeError), /// An error occurred while working with a [`TracePoint`]. #[error(transparent)] TracePointError(#[from] TracePointError), /// An error occurred while working with a [`SocketFilter`]. #[error(transparent)] SocketFilterError(#[from] SocketFilterError), /// An error occurred while working with an [`Xdp`] program. #[error(transparent)] XdpError(#[from] XdpError), /// An error occurred while working with a TC program. #[error(transparent)] TcError(#[from] TcError), /// An error occurred while working with an [`Extension`] program. #[error(transparent)] ExtensionError(#[from] ExtensionError), /// An error occurred while working with BTF. #[error(transparent)] Btf(#[from] BtfError), /// The program is not attached. #[error("the program name `{name}` is invalid")] InvalidName { /// program name name: String, }, } /// A [`Program`] file descriptor. #[derive(Copy, Clone)] pub struct ProgramFd(RawFd); impl AsRawFd for ProgramFd { fn as_raw_fd(&self) -> RawFd { self.0 } } /// eBPF program type. #[derive(Debug)] pub enum Program { /// A [`KProbe`] program KProbe(KProbe), /// A [`UProbe`] program UProbe(UProbe), /// A [`TracePoint`] program TracePoint(TracePoint), /// A [`SocketFilter`] program SocketFilter(SocketFilter), /// A [`Xdp`] program Xdp(Xdp), /// A [`SkMsg`] program SkMsg(SkMsg), /// A [`SkSkb`] program SkSkb(SkSkb), /// A [`CgroupSockAddr`] program CgroupSockAddr(CgroupSockAddr), /// A [`SockOps`] program SockOps(SockOps), /// A [`SchedClassifier`] program SchedClassifier(SchedClassifier), /// A [`CgroupSkb`] program CgroupSkb(CgroupSkb), /// A [`CgroupSysctl`] program CgroupSysctl(CgroupSysctl), /// A [`CgroupSockopt`] program CgroupSockopt(CgroupSockopt), /// A [`LircMode2`] program LircMode2(LircMode2), /// A [`PerfEvent`] program PerfEvent(PerfEvent), /// A [`RawTracePoint`] program RawTracePoint(RawTracePoint), /// A [`Lsm`] program Lsm(Lsm), /// A [`BtfTracePoint`] program BtfTracePoint(BtfTracePoint), /// A [`FEntry`] program FEntry(FEntry), /// A [`FExit`] program FExit(FExit), /// A [`Extension`] program Extension(Extension), /// A [`SkLookup`] program SkLookup(SkLookup), /// A [`CgroupSock`] program CgroupSock(CgroupSock), /// A [`CgroupDevice`] program CgroupDevice(CgroupDevice), } impl Program { /// Returns the low level program type. pub fn prog_type(&self) -> bpf_prog_type { use crate::generated::bpf_prog_type::*; match self { Program::KProbe(_) => BPF_PROG_TYPE_KPROBE, Program::UProbe(_) => BPF_PROG_TYPE_KPROBE, Program::TracePoint(_) => BPF_PROG_TYPE_TRACEPOINT, Program::SocketFilter(_) => BPF_PROG_TYPE_SOCKET_FILTER, Program::Xdp(_) => BPF_PROG_TYPE_XDP, Program::SkMsg(_) => BPF_PROG_TYPE_SK_MSG, Program::SkSkb(_) => BPF_PROG_TYPE_SK_SKB, Program::SockOps(_) => BPF_PROG_TYPE_SOCK_OPS, Program::SchedClassifier(_) => BPF_PROG_TYPE_SCHED_CLS, Program::CgroupSkb(_) => BPF_PROG_TYPE_CGROUP_SKB, Program::CgroupSysctl(_) => BPF_PROG_TYPE_CGROUP_SYSCTL, Program::CgroupSockopt(_) => BPF_PROG_TYPE_CGROUP_SOCKOPT, Program::LircMode2(_) => BPF_PROG_TYPE_LIRC_MODE2, Program::PerfEvent(_) => BPF_PROG_TYPE_PERF_EVENT, Program::RawTracePoint(_) => BPF_PROG_TYPE_RAW_TRACEPOINT, Program::Lsm(_) => BPF_PROG_TYPE_LSM, Program::BtfTracePoint(_) => BPF_PROG_TYPE_TRACING, Program::FEntry(_) => BPF_PROG_TYPE_TRACING, Program::FExit(_) => BPF_PROG_TYPE_TRACING, Program::Extension(_) => BPF_PROG_TYPE_EXT, Program::CgroupSockAddr(_) => BPF_PROG_TYPE_CGROUP_SOCK_ADDR, Program::SkLookup(_) => BPF_PROG_TYPE_SK_LOOKUP, Program::CgroupSock(_) => BPF_PROG_TYPE_CGROUP_SOCK, Program::CgroupDevice(_) => BPF_PROG_TYPE_CGROUP_DEVICE, } } /// Pin the program to the provided path pub fn pin<P: AsRef<Path>>(&mut self, path: P) -> Result<(), PinError> { match self { Program::KProbe(p) => p.pin(path), Program::UProbe(p) => p.pin(path), Program::TracePoint(p) => p.pin(path), Program::SocketFilter(p) => p.pin(path), Program::Xdp(p) => p.pin(path), Program::SkMsg(p) => p.pin(path), Program::SkSkb(p) => p.pin(path), Program::SockOps(p) => p.pin(path), Program::SchedClassifier(p) => p.pin(path), Program::CgroupSkb(p) => p.pin(path), Program::CgroupSysctl(p) => p.pin(path), Program::CgroupSockopt(p) => p.pin(path), Program::LircMode2(p) => p.pin(path), Program::PerfEvent(p) => p.pin(path), Program::RawTracePoint(p) => p.pin(path), Program::Lsm(p) => p.pin(path), Program::BtfTracePoint(p) => p.pin(path), Program::FEntry(p) => p.pin(path), Program::FExit(p) => p.pin(path), Program::Extension(p) => p.pin(path), Program::CgroupSockAddr(p) => p.pin(path), Program::SkLookup(p) => p.pin(path), Program::CgroupSock(p) => p.pin(path), Program::CgroupDevice(p) => p.pin(path), } } /// Unload the program fn unload(&mut self) -> Result<(), ProgramError> { match self { Program::KProbe(p) => p.unload(), Program::UProbe(p) => p.unload(), Program::TracePoint(p) => p.unload(), Program::SocketFilter(p) => p.unload(), Program::Xdp(p) => p.unload(), Program::SkMsg(p) => p.unload(), Program::SkSkb(p) => p.unload(), Program::SockOps(p) => p.unload(), Program::SchedClassifier(p) => p.unload(), Program::CgroupSkb(p) => p.unload(), Program::CgroupSysctl(p) => p.unload(), Program::CgroupSockopt(p) => p.unload(), Program::LircMode2(p) => p.unload(), Program::PerfEvent(p) => p.unload(), Program::RawTracePoint(p) => p.unload(), Program::Lsm(p) => p.unload(), Program::BtfTracePoint(p) => p.unload(), Program::FEntry(p) => p.unload(), Program::FExit(p) => p.unload(), Program::Extension(p) => p.unload(), Program::CgroupSockAddr(p) => p.unload(), Program::SkLookup(p) => p.unload(), Program::CgroupSock(p) => p.unload(), Program::CgroupDevice(p) => p.unload(), } } /// Returns the file descriptor of a program. /// /// Can be used to add a program to a [`crate::maps::ProgramArray`] or attach an [`Extension`] program. /// Can be converted to [`RawFd`] using [`AsRawFd`]. pub fn fd(&self) -> Option<ProgramFd> { match self { Program::KProbe(p) => p.fd(), Program::UProbe(p) => p.fd(), Program::TracePoint(p) => p.fd(), Program::SocketFilter(p) => p.fd(), Program::Xdp(p) => p.fd(), Program::SkMsg(p) => p.fd(), Program::SkSkb(p) => p.fd(), Program::SockOps(p) => p.fd(), Program::SchedClassifier(p) => p.fd(), Program::CgroupSkb(p) => p.fd(), Program::CgroupSysctl(p) => p.fd(), Program::CgroupSockopt(p) => p.fd(), Program::LircMode2(p) => p.fd(), Program::PerfEvent(p) => p.fd(), Program::RawTracePoint(p) => p.fd(), Program::Lsm(p) => p.fd(), Program::BtfTracePoint(p) => p.fd(), Program::FEntry(p) => p.fd(), Program::FExit(p) => p.fd(), Program::Extension(p) => p.fd(), Program::CgroupSockAddr(p) => p.fd(), Program::SkLookup(p) => p.fd(), Program::CgroupSock(p) => p.fd(), Program::CgroupDevice(p) => p.fd(), } } } impl Drop for Program { fn drop(&mut self) { let _ = self.unload(); } } #[derive(Debug)] pub(crate) struct ProgramData<T: Link> { pub(crate) name: Option<String>, pub(crate) obj: obj::Program, pub(crate) fd: Option<RawFd>, pub(crate) links: LinkMap<T>, pub(crate) expected_attach_type: Option<bpf_attach_type>, pub(crate) attach_btf_obj_fd: Option<u32>, pub(crate) attach_btf_id: Option<u32>, pub(crate) attach_prog_fd: Option<RawFd>, pub(crate) btf_fd: Option<RawFd>, pub(crate) verifier_log_level: u32, } impl<T: Link> ProgramData<T> { pub(crate) fn new( name: Option<String>, obj: obj::Program, btf_fd: Option<RawFd>, verifier_log_level: u32, ) -> ProgramData<T> { ProgramData { name, obj, fd: None, links: LinkMap::new(), expected_attach_type: None, attach_btf_obj_fd: None, attach_btf_id: None, attach_prog_fd: None, btf_fd, verifier_log_level, } } } impl<T: Link> ProgramData<T> { fn fd_or_err(&self) -> Result<RawFd, ProgramError> { self.fd.ok_or(ProgramError::NotLoaded) } pub(crate) fn take_link(&mut self, link_id: T::Id) -> Result<T, ProgramError> { self.links.forget(link_id) } } fn unload_program<T: Link>(data: &mut ProgramData<T>) -> Result<(), ProgramError> { data.links.remove_all()?; let fd = data.fd.take().ok_or(ProgramError::NotLoaded)?; unsafe { libc::close(fd); } Ok(()) } fn pin_program<T: Link, P: AsRef<Path>>( data: &mut ProgramData<T>, path: P, ) -> Result<(), PinError> { let fd = data.fd.ok_or(PinError::NoFd { name: data .name .as_ref() .unwrap_or(&"<unknown program>".to_string()) .to_string(), })?; let path_string = CString::new(path.as_ref().to_string_lossy().into_owned()).map_err(|e| { PinError::InvalidPinPath { error: e.to_string(), } })?; bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { name: "BPF_OBJ_PIN".to_string(), io_error, })?; Ok(()) } fn load_program<T: Link>( prog_type: bpf_prog_type, data: &mut ProgramData<T>, ) -> Result<(), ProgramError> { let ProgramData { obj, fd, .. } = data; if fd.is_some() { return Err(ProgramError::AlreadyLoaded); } let crate::obj::Program { function: Function { instructions, func_info, line_info, func_info_rec_size, line_info_rec_size, .. }, license, kernel_version, .. } = obj; let target_kernel_version = match *kernel_version { KernelVersion::Any => { let (major, minor, patch) = crate::sys::kernel_version().unwrap(); (major << 16) + (minor << 8) + patch } _ => (*kernel_version).into(), }; let mut logger = VerifierLog::new(); let prog_name = if let Some(name) = &data.name { let mut name = name.clone(); if name.len() > 15 { name.truncate(15); } let prog_name = CString::new(name.clone()) .map_err(|_| ProgramError::InvalidName { name: name.clone() })?; Some(prog_name) } else { None }; let attr = BpfLoadProgramAttrs { name: prog_name, ty: prog_type, insns: instructions, license, kernel_version: target_kernel_version, expected_attach_type: data.expected_attach_type, prog_btf_fd: data.btf_fd, attach_btf_obj_fd: data.attach_btf_obj_fd, attach_btf_id: data.attach_btf_id, attach_prog_fd: data.attach_prog_fd, func_info_rec_size: *func_info_rec_size, func_info: func_info.clone(), line_info_rec_size: *line_info_rec_size, line_info: line_info.clone(), }; let verifier_log_level = data.verifier_log_level; let ret = retry_with_verifier_logs(10, &mut logger, |logger| { bpf_load_program(&attr, logger, verifier_log_level) }); match ret { Ok(prog_fd) => { *fd = Some(prog_fd as RawFd); Ok(()) } Err((_, io_error)) => { logger.truncate(); return Err(ProgramError::LoadError { io_error, verifier_log: logger .as_c_str() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "[none]".to_owned()), }); } } } pub(crate) fn query<T: AsRawFd>( target_fd: T, attach_type: bpf_attach_type, query_flags: u32, attach_flags: &mut Option<u32>, ) -> Result<Vec<u32>, ProgramError> { let mut prog_ids = vec![0u32; 64]; let mut prog_cnt = prog_ids.len() as u32; let mut retries = 0; loop { match bpf_prog_query( target_fd.as_raw_fd(), attach_type, query_flags, attach_flags.as_mut(), &mut prog_ids, &mut prog_cnt, ) { Ok(_) => { prog_ids.resize(prog_cnt as usize, 0); return Ok(prog_ids); } Err((_, io_error)) if retries == 0 && io_error.raw_os_error() == Some(ENOSPC) => { prog_ids.resize(prog_cnt as usize, 0); retries += 1; } Err((_, io_error)) => { return Err(ProgramError::SyscallError { call: "bpf_prog_query".to_owned(), io_error, }); } } } } macro_rules! impl_program_unload { ($($struct_name:ident),+ $(,)?) => { $( impl $struct_name { /// Unloads the program from the kernel. /// /// Links will be detached before unloading the program. Note /// that owned links obtained using `take_link()` will not be /// detached. pub fn unload(&mut self) -> Result<(), ProgramError> { unload_program(&mut self.data) } } )+ } } impl_program_unload!( KProbe, UProbe, TracePoint, SocketFilter, Xdp, SkMsg, SkSkb, SchedClassifier, CgroupSkb, CgroupSysctl, CgroupSockopt, LircMode2, PerfEvent, Lsm, RawTracePoint, BtfTracePoint, FEntry, FExit, Extension, CgroupSockAddr, SkLookup, SockOps, CgroupSock, CgroupDevice, ); macro_rules! impl_fd { ($($struct_name:ident),+ $(,)?) => { $( impl $struct_name { /// Returns the file descriptor of this Program. pub fn fd(&self) -> Option<ProgramFd> { self.data.fd.map(|fd| ProgramFd(fd)) } } )+ } } impl_fd!( KProbe, UProbe, TracePoint, SocketFilter, Xdp, SkMsg, SkSkb, SchedClassifier, CgroupSkb, CgroupSysctl, CgroupSockopt, LircMode2, PerfEvent, Lsm, RawTracePoint, BtfTracePoint, FEntry, FExit, Extension, CgroupSockAddr, SkLookup, SockOps, CgroupSock, CgroupDevice, ); macro_rules! impl_program_pin{ ($($struct_name:ident),+ $(,)?) => { $( impl $struct_name { /// Pins the program to a BPF filesystem. /// /// When a BPF object is pinned to a BPF filesystem it will remain loaded after /// Aya has unloaded the program. /// To remove the program, the file on the BPF filesystem must be removed. /// Any directories in the the path provided should have been created by the caller. pub fn pin<P: AsRef<Path>>(&mut self, path: P) -> Result<(), PinError> { pin_program(&mut self.data, path) } } )+ } } impl_program_pin!( KProbe, UProbe, TracePoint, SocketFilter, Xdp, SkMsg, SkSkb, SchedClassifier, CgroupSkb, CgroupSysctl, CgroupSockopt, LircMode2, PerfEvent, Lsm, RawTracePoint, BtfTracePoint, FEntry, FExit, Extension, CgroupSockAddr, SkLookup, SockOps, CgroupSock, CgroupDevice, ); macro_rules! impl_try_from_program { ($($ty:ident),+ $(,)?) => { $( impl<'a> TryFrom<&'a Program> for &'a $ty { type Error = ProgramError; fn try_from(program: &'a Program) -> Result<&'a $ty, ProgramError> { match program { Program::$ty(p) => Ok(p), _ => Err(ProgramError::UnexpectedProgramType), } } } impl<'a> TryFrom<&'a mut Program> for &'a mut $ty { type Error = ProgramError; fn try_from(program: &'a mut Program) -> Result<&'a mut $ty, ProgramError> { match program { Program::$ty(p) => Ok(p), _ => Err(ProgramError::UnexpectedProgramType), } } } )+ } } impl_try_from_program!( KProbe, UProbe, TracePoint, SocketFilter, Xdp, SkMsg, SkSkb, SockOps, SchedClassifier, CgroupSkb, CgroupSysctl, CgroupSockopt, LircMode2, PerfEvent, Lsm, RawTracePoint, BtfTracePoint, FEntry, FExit, Extension, CgroupSockAddr, SkLookup, CgroupSock, CgroupDevice, ); /// Provides information about a loaded program, like name, id and statistics pub struct ProgramInfo(bpf_prog_info); impl ProgramInfo { /// The name of the program as was provided when it was load. This is limited to 16 bytes pub fn name(&self) -> &[u8] { let length = self .0 .name .iter() .rposition(|ch| *ch != 0) .map(|pos| pos + 1) .unwrap_or(0); // The name field is defined as [std::os::raw::c_char; 16]. c_char may be signed or // unsigned depending on the platform; that's why we're using from_raw_parts here unsafe { std::slice::from_raw_parts(self.0.name.as_ptr() as *const _, length) } } /// The name of the program as a &str. If the name was not valid unicode, None is returned pub fn name_as_str(&self) -> Option<&str> { std::str::from_utf8(self.name()).ok() } /// The program id for this program. Each program has a unique id. pub fn id(&self) -> u32 { self.0.id } /// Returns the fd associated with the program. /// /// The returned fd must be closed when no longer needed. pub fn fd(&self) -> Result<RawFd, ProgramError> { let fd = bpf_prog_get_fd_by_id(self.0.id).map_err(|io_error| ProgramError::SyscallError { call: "bpf_prog_get_fd_by_id".to_owned(), io_error, })?; Ok(fd as RawFd) } /// Loads a program from a pinned path in bpffs. pub fn from_pin<P: AsRef<Path>>(path: P) -> Result<ProgramInfo, ProgramError> { let path_string = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| ProgramError::SyscallError { call: "BPF_OBJ_GET".to_owned(), io_error, })? as RawFd; let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError { call: "bpf_prog_get_info_by_fd".to_owned(), io_error, })?; unsafe { libc::close(fd); } Ok(ProgramInfo(info)) } } <file_sep>/bpf/aya-bpf/src/args.rs use crate::{cty::c_void, helpers::bpf_probe_read}; // aarch64 uses user_pt_regs instead of pt_regs #[cfg(not(bpf_target_arch = "aarch64"))] use crate::bindings::pt_regs; #[cfg(bpf_target_arch = "aarch64")] use crate::bindings::user_pt_regs as pt_regs; /// A trait that indicates a valid type for an argument which can be coerced from a BTF /// context. /// /// Users should not implement this trait. /// /// SAFETY: This trait is _only_ safe to implement on primitive types that can fit into /// a `u64`. For example, integers and raw pointers may be coerced from a BTF context. pub unsafe trait FromBtfArgument: Sized { /// Coerces a `T` from the `n`th argument from a BTF context where `n` starts /// at 0 and increases by 1 for each successive argument. /// /// SAFETY: This function is deeply unsafe, as we are reading raw pointers into kernel /// memory. In particular, the value of `n` must not exceed the number of function /// arguments. Moreover, `ctx` must be a valid pointer to a BTF context, and `T` must /// be the right type for the given argument. unsafe fn from_argument(ctx: *const c_void, n: usize) -> Self; } unsafe impl<T> FromBtfArgument for *const T { unsafe fn from_argument(ctx: *const c_void, n: usize) -> *const T { // BTF arguments are exposed as an array of `usize` where `usize` can // either be treated as a pointer or a primitive type *(ctx as *const usize).add(n) as _ } } /// Helper macro to implement [`FromBtfArgument`] for a primitive type. macro_rules! unsafe_impl_from_btf_argument { ($type:ident) => { unsafe impl FromBtfArgument for $type { unsafe fn from_argument(ctx: *const c_void, n: usize) -> Self { // BTF arguments are exposed as an array of `usize` where `usize` can // either be treated as a pointer or a primitive type *(ctx as *const usize).add(n) as _ } } }; } unsafe_impl_from_btf_argument!(u8); unsafe_impl_from_btf_argument!(u16); unsafe_impl_from_btf_argument!(u32); unsafe_impl_from_btf_argument!(u64); unsafe_impl_from_btf_argument!(i8); unsafe_impl_from_btf_argument!(i16); unsafe_impl_from_btf_argument!(i32); unsafe_impl_from_btf_argument!(i64); unsafe_impl_from_btf_argument!(usize); unsafe_impl_from_btf_argument!(isize); pub struct PtRegs { regs: *mut pt_regs, } /// A portable wrapper around pt_regs and user_pt_regs. impl PtRegs { pub fn new(regs: *mut pt_regs) -> Self { PtRegs { regs } } /// Returns the value of the register used to pass arg `n`. pub fn arg<T: FromPtRegs>(&self, n: usize) -> Option<T> { T::from_argument(unsafe { &*self.regs }, n) } /// Returns the value of the register used to pass the return value. pub fn ret<T: FromPtRegs>(&self) -> Option<T> { T::from_retval(unsafe { &*self.regs }) } /// Returns a pointer to the wrapped value. pub fn as_ptr(&self) -> *mut pt_regs { self.regs } } /// A trait that indicates a valid type for an argument which can be coerced from /// a pt_regs context. /// /// Any implementation of this trait is strictly architecture-specific and depends on the /// layout of the underlying pt_regs struct and the target processor's calling /// conventions. Users should not implement this trait. pub trait FromPtRegs: Sized { /// Coerces a `T` from the `n`th argument of a pt_regs context where `n` starts /// at 0 and increases by 1 for each successive argument. fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self>; /// Coerces a `T` from the return value of a pt_regs context. fn from_retval(ctx: &pt_regs) -> Option<Self>; } #[cfg(bpf_target_arch = "x86_64")] impl<T> FromPtRegs for *const T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { match n { 0 => unsafe { bpf_probe_read(&ctx.rdi).map(|v| v as *const _).ok() }, 1 => unsafe { bpf_probe_read(&ctx.rsi).map(|v| v as *const _).ok() }, 2 => unsafe { bpf_probe_read(&ctx.rdx).map(|v| v as *const _).ok() }, 3 => unsafe { bpf_probe_read(&ctx.rcx).map(|v| v as *const _).ok() }, 4 => unsafe { bpf_probe_read(&ctx.r8).map(|v| v as *const _).ok() }, 5 => unsafe { bpf_probe_read(&ctx.r9).map(|v| v as *const _).ok() }, _ => None, } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.rax).map(|v| v as *const _).ok() } } } #[cfg(bpf_target_arch = "arm")] impl<T> FromPtRegs for *const T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 6 { unsafe { bpf_probe_read(&ctx.uregs[n]).map(|v| v as *const _).ok() } } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.uregs[0]).map(|v| v as *const _).ok() } } } #[cfg(bpf_target_arch = "aarch64")] impl<T> FromPtRegs for *const T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 7 { unsafe { bpf_probe_read(&ctx.regs[n]).map(|v| v as *const _).ok() } } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.regs[0]).map(|v| v as *const _).ok() } } } #[cfg(bpf_target_arch = "x86_64")] impl<T> FromPtRegs for *mut T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { match n { 0 => unsafe { bpf_probe_read(&ctx.rdi).map(|v| v as *mut _).ok() }, 1 => unsafe { bpf_probe_read(&ctx.rsi).map(|v| v as *mut _).ok() }, 2 => unsafe { bpf_probe_read(&ctx.rdx).map(|v| v as *mut _).ok() }, 3 => unsafe { bpf_probe_read(&ctx.rcx).map(|v| v as *mut _).ok() }, 4 => unsafe { bpf_probe_read(&ctx.r8).map(|v| v as *mut _).ok() }, 5 => unsafe { bpf_probe_read(&ctx.r9).map(|v| v as *mut _).ok() }, _ => None, } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.rax).map(|v| v as *mut _).ok() } } } #[cfg(bpf_target_arch = "arm")] impl<T> FromPtRegs for *mut T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 6 { unsafe { bpf_probe_read(&ctx.uregs[n]).map(|v| v as *mut _).ok() } } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.uregs[0]).map(|v| v as *mut _).ok() } } } #[cfg(bpf_target_arch = "aarch64")] impl<T> FromPtRegs for *mut T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 7 { unsafe { bpf_probe_read(&ctx.regs[n]).map(|v| v as *mut _).ok() } } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read(&ctx.regs[0]).map(|v| v as *mut _).ok() } } } /// Helper macro to implement [`FromPtRegs`] for a primitive type. macro_rules! impl_from_pt_regs { ($type:ident) => { #[cfg(bpf_target_arch = "x86_64")] impl FromPtRegs for $type { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { match n { 0 => Some(ctx.rdi as *const $type as _), 1 => Some(ctx.rsi as *const $type as _), 2 => Some(ctx.rdx as *const $type as _), 3 => Some(ctx.rcx as *const $type as _), 4 => Some(ctx.r8 as *const $type as _), 5 => Some(ctx.r9 as *const $type as _), _ => None, } } fn from_retval(ctx: &pt_regs) -> Option<Self> { Some(ctx.rax as *const $type as _) } } #[cfg(bpf_target_arch = "arm")] impl FromPtRegs for $type { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 6 { Some(ctx.uregs[n] as *const $type as _) } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { Some(ctx.uregs[0] as *const $type as _) } } #[cfg(bpf_target_arch = "aarch64")] impl FromPtRegs for $type { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 7 { Some(ctx.regs[n] as *const $type as _) } else { None } } fn from_retval(ctx: &pt_regs) -> Option<Self> { Some(ctx.regs[0] as *const $type as _) } } }; } impl_from_pt_regs!(u8); impl_from_pt_regs!(u16); impl_from_pt_regs!(u32); impl_from_pt_regs!(u64); impl_from_pt_regs!(i8); impl_from_pt_regs!(i16); impl_from_pt_regs!(i32); impl_from_pt_regs!(i64); impl_from_pt_regs!(usize); impl_from_pt_regs!(isize); <file_sep>/release.toml pre-release-commit-message = "{{crate_name}}: release version {{version}}" post-release-commit-message = "{{crate_name}}: start next development iteration {{next_version}}" consolidate-commits = true <file_sep>/aya-log/src/lib.rs //! A logging framework for eBPF programs. //! //! This is the user space side of the [Aya] logging framework. For the eBPF //! side, see the `aya-log-ebpf` crate. //! //! `aya-log` provides the [BpfLogger] type, which reads log records created by //! `aya-log-ebpf` and logs them using the [log] crate. Any logger that //! implements the [Log] trait can be used with this crate. //! //! # Example: //! //! This example uses the [env_logger] crate to log messages to the terminal. //! //! ```no_run //! # let mut bpf = aya::Bpf::load(&[]).unwrap(); //! use aya_log::BpfLogger; //! //! // initialize env_logger as the default logger //! env_logger::init(); //! //! // start reading aya-log records and log them using the default logger //! BpfLogger::init(&mut bpf).unwrap(); //! ``` //! //! With the following eBPF code: //! //! ```ignore //! # let ctx = (); //! use aya_log_ebpf::{debug, error, info, trace, warn}; //! //! error!(&ctx, "this is an error message 🚨"); //! warn!(&ctx, "this is a warning message ⚠️"); //! info!(&ctx, "this is an info message ℹ️"); //! debug!(&ctx, "this is a debug message ️🐝"); //! trace!(&ctx, "this is a trace message 🔍"); //! ``` //! Outputs: //! //! ```text //! 21:58:55 [ERROR] xxx: [src/main.rs:35] this is an error message 🚨 //! 21:58:55 [WARN] xxx: [src/main.rs:36] this is a warning message ⚠️ //! 21:58:55 [INFO] xxx: [src/main.rs:37] this is an info message ℹ️ //! 21:58:55 [DEBUG] (7) xxx: [src/main.rs:38] this is a debug message ️🐝 //! 21:58:55 [TRACE] (7) xxx: [src/main.rs:39] this is a trace message 🔍 //! ``` //! //! [Aya]: https://docs.rs/aya //! [env_logger]: https://docs.rs/env_logger //! [Log]: https://docs.rs/log/0.4.14/log/trait.Log.html //! [log]: https://docs.rs/log //! use std::{ fmt::{LowerHex, UpperHex}, io, mem, net::{Ipv4Addr, Ipv6Addr}, ptr, str, sync::Arc, }; const MAP_NAME: &str = "AYA_LOGS"; use aya_log_common::{Argument, DisplayHint, RecordField, LOG_BUF_CAPACITY, LOG_FIELDS}; use bytes::BytesMut; use log::{error, Level, Log, Record}; use thiserror::Error; use aya::{ maps::{ perf::{AsyncPerfEventArray, PerfBufferError}, MapError, }, util::online_cpus, Bpf, Pod, }; /// Log messages generated by `aya_log_ebpf` using the [log] crate. /// /// For more details see the [module level documentation](crate). pub struct BpfLogger; impl BpfLogger { /// Starts reading log records created with `aya-log-ebpf` and logs them /// with the default logger. See [log::logger]. pub fn init(bpf: &mut Bpf) -> Result<BpfLogger, Error> { BpfLogger::init_with_logger(bpf, DefaultLogger {}) } /// Starts reading log records created with `aya-log-ebpf` and logs them /// with the given logger. pub fn init_with_logger<T: Log + 'static>( bpf: &mut Bpf, logger: T, ) -> Result<BpfLogger, Error> { let logger = Arc::new(logger); let mut logs: AsyncPerfEventArray<_> = bpf .take_map(MAP_NAME) .ok_or(Error::MapNotFound)? .try_into()?; for cpu_id in online_cpus().map_err(Error::InvalidOnlineCpu)? { let mut buf = logs.open(cpu_id, None)?; let log = logger.clone(); tokio::spawn(async move { let mut buffers = (0..10) .map(|_| BytesMut::with_capacity(LOG_BUF_CAPACITY)) .collect::<Vec<_>>(); loop { let events = buf.read_events(&mut buffers).await.unwrap(); #[allow(clippy::needless_range_loop)] for i in 0..events.read { let buf = &mut buffers[i]; log_buf(buf, &*log).unwrap(); } } }); } Ok(BpfLogger {}) } } pub trait Formatter<T> { fn format(v: T) -> String; } pub struct DefaultFormatter; impl<T> Formatter<T> for DefaultFormatter where T: ToString, { fn format(v: T) -> String { v.to_string() } } pub struct LowerHexFormatter; impl<T> Formatter<T> for LowerHexFormatter where T: LowerHex, { fn format(v: T) -> String { format!("{v:x}") } } pub struct UpperHexFormatter; impl<T> Formatter<T> for UpperHexFormatter where T: UpperHex, { fn format(v: T) -> String { format!("{v:X}") } } pub struct Ipv4Formatter; impl<T> Formatter<T> for Ipv4Formatter where T: Into<Ipv4Addr>, { fn format(v: T) -> String { v.into().to_string() } } pub struct Ipv6Formatter; impl<T> Formatter<T> for Ipv6Formatter where T: Into<Ipv6Addr>, { fn format(v: T) -> String { v.into().to_string() } } pub struct LowerMacFormatter; impl Formatter<[u8; 6]> for LowerMacFormatter { fn format(v: [u8; 6]) -> String { format!( "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", v[0], v[1], v[2], v[3], v[4], v[5] ) } } pub struct UpperMacFormatter; impl Formatter<[u8; 6]> for UpperMacFormatter { fn format(v: [u8; 6]) -> String { format!( "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", v[0], v[1], v[2], v[3], v[4], v[5] ) } } trait Format { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()>; } impl Format for u32 { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)), Some(DisplayHint::LowerHex) => Ok(LowerHexFormatter::format(self)), Some(DisplayHint::UpperHex) => Ok(UpperHexFormatter::format(self)), Some(DisplayHint::Ipv4) => Ok(Ipv4Formatter::format(*self)), Some(DisplayHint::Ipv6) => Err(()), Some(DisplayHint::LowerMac) => Err(()), Some(DisplayHint::UpperMac) => Err(()), _ => Ok(DefaultFormatter::format(self)), } } } impl Format for [u8; 6] { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Err(()), Some(DisplayHint::LowerHex) => Err(()), Some(DisplayHint::UpperHex) => Err(()), Some(DisplayHint::Ipv4) => Err(()), Some(DisplayHint::Ipv6) => Err(()), Some(DisplayHint::LowerMac) => Ok(LowerMacFormatter::format(*self)), Some(DisplayHint::UpperMac) => Ok(UpperMacFormatter::format(*self)), _ => Err(()), } } } impl Format for [u8; 16] { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Err(()), Some(DisplayHint::LowerHex) => Err(()), Some(DisplayHint::UpperHex) => Err(()), Some(DisplayHint::Ipv4) => Err(()), Some(DisplayHint::Ipv6) => Ok(Ipv6Formatter::format(*self)), Some(DisplayHint::LowerMac) => Err(()), Some(DisplayHint::UpperMac) => Err(()), _ => Err(()), } } } impl Format for [u16; 8] { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Err(()), Some(DisplayHint::LowerHex) => Err(()), Some(DisplayHint::UpperHex) => Err(()), Some(DisplayHint::Ipv4) => Err(()), Some(DisplayHint::Ipv6) => Ok(Ipv6Formatter::format(*self)), Some(DisplayHint::LowerMac) => Err(()), Some(DisplayHint::UpperMac) => Err(()), _ => Err(()), } } } macro_rules! impl_format { ($type:ident) => { impl Format for $type { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)), Some(DisplayHint::LowerHex) => Ok(LowerHexFormatter::format(self)), Some(DisplayHint::UpperHex) => Ok(UpperHexFormatter::format(self)), Some(DisplayHint::Ipv4) => Err(()), Some(DisplayHint::Ipv6) => Err(()), Some(DisplayHint::LowerMac) => Err(()), Some(DisplayHint::UpperMac) => Err(()), _ => Ok(DefaultFormatter::format(self)), } } } }; } impl_format!(i8); impl_format!(i16); impl_format!(i32); impl_format!(i64); impl_format!(isize); impl_format!(u8); impl_format!(u16); impl_format!(u64); impl_format!(usize); macro_rules! impl_format_float { ($type:ident) => { impl Format for $type { fn format(&self, last_hint: Option<DisplayHint>) -> Result<String, ()> { match last_hint { Some(DisplayHint::Default) => Ok(DefaultFormatter::format(self)), Some(DisplayHint::LowerHex) => Err(()), Some(DisplayHint::UpperHex) => Err(()), Some(DisplayHint::Ipv4) => Err(()), Some(DisplayHint::Ipv6) => Err(()), Some(DisplayHint::LowerMac) => Err(()), Some(DisplayHint::UpperMac) => Err(()), _ => Ok(DefaultFormatter::format(self)), } } } }; } impl_format_float!(f32); impl_format_float!(f64); #[derive(Copy, Clone, Debug)] struct DefaultLogger; impl Log for DefaultLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { log::logger().enabled(metadata) } fn log(&self, record: &Record) { log::logger().log(record) } fn flush(&self) { log::logger().flush() } } #[derive(Error, Debug)] pub enum Error { #[error("log event array {} doesn't exist", MAP_NAME)] MapNotFound, #[error("error opening log event array")] MapError(#[from] MapError), #[error("error opening log buffer")] PerfBufferError(#[from] PerfBufferError), #[error("invalid /sys/devices/system/cpu/online format")] InvalidOnlineCpu(#[source] io::Error), } fn log_buf(mut buf: &[u8], logger: &dyn Log) -> Result<(), ()> { let mut target = None; let mut level = Level::Trace; let mut module = None; let mut file = None; let mut line = None; let mut num_args = None; for _ in 0..LOG_FIELDS { let (attr, rest) = unsafe { TagLenValue::<'_, RecordField>::try_read(buf)? }; match attr.tag { RecordField::Target => { target = Some(std::str::from_utf8(attr.value).map_err(|_| ())?); } RecordField::Level => { level = unsafe { ptr::read_unaligned(attr.value.as_ptr() as *const _) } } RecordField::Module => { module = Some(std::str::from_utf8(attr.value).map_err(|_| ())?); } RecordField::File => { file = Some(std::str::from_utf8(attr.value).map_err(|_| ())?); } RecordField::Line => { line = Some(u32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)); } RecordField::NumArgs => { num_args = Some(usize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?)); } } buf = rest; } let mut full_log_msg = String::new(); let mut last_hint: Option<DisplayHint> = None; for _ in 0..num_args.ok_or(())? { let (attr, rest) = unsafe { TagLenValue::<'_, Argument>::try_read(buf)? }; match attr.tag { Argument::DisplayHint => { last_hint = Some(unsafe { ptr::read_unaligned(attr.value.as_ptr() as *const _) }); } Argument::I8 => { full_log_msg.push_str( &i8::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::I16 => { full_log_msg.push_str( &i16::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::I32 => { full_log_msg.push_str( &i32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::I64 => { full_log_msg.push_str( &i64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::Isize => { full_log_msg.push_str( &isize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::U8 => { full_log_msg.push_str( &u8::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::U16 => { full_log_msg.push_str( &u16::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::U32 => { full_log_msg.push_str( &u32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::U64 => { full_log_msg.push_str( &u64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::Usize => { full_log_msg.push_str( &usize::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::F32 => { full_log_msg.push_str( &f32::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::F64 => { full_log_msg.push_str( &f64::from_ne_bytes(attr.value.try_into().map_err(|_| ())?) .format(last_hint.take())?, ); } Argument::ArrU8Len6 => { let value: [u8; 6] = attr.value.try_into().map_err(|_| ())?; full_log_msg.push_str(&value.format(last_hint.take())?); } Argument::ArrU8Len16 => { let value: [u8; 16] = attr.value.try_into().map_err(|_| ())?; full_log_msg.push_str(&value.format(last_hint.take())?); } Argument::ArrU16Len8 => { let data: [u8; 16] = attr.value.try_into().map_err(|_| ())?; let mut value: [u16; 8] = Default::default(); for (i, s) in data.chunks_exact(2).enumerate() { value[i] = ((s[1] as u16) << 8) | s[0] as u16; } full_log_msg.push_str(&value.format(last_hint.take())?); } Argument::Str => match str::from_utf8(attr.value) { Ok(v) => { full_log_msg.push_str(v); } Err(e) => error!("received invalid utf8 string: {}", e), }, } buf = rest; } logger.log( &Record::builder() .args(format_args!("{full_log_msg}")) .target(target.ok_or(())?) .level(level) .module_path(module) .file(file) .line(line) .build(), ); logger.flush(); Ok(()) } struct TagLenValue<'a, T: Pod> { tag: T, value: &'a [u8], } impl<'a, T: Pod> TagLenValue<'a, T> { unsafe fn try_read(mut buf: &'a [u8]) -> Result<(TagLenValue<'a, T>, &'a [u8]), ()> { if buf.len() < mem::size_of::<T>() + mem::size_of::<usize>() { return Err(()); } let tag = ptr::read_unaligned(buf.as_ptr() as *const T); buf = &buf[mem::size_of::<T>()..]; let len = usize::from_ne_bytes(buf[..mem::size_of::<usize>()].try_into().unwrap()); buf = &buf[mem::size_of::<usize>()..]; if buf.len() < len { return Err(()); } Ok(( TagLenValue { tag, value: &buf[..len], }, &buf[len..], )) } } #[cfg(test)] mod test { use super::*; use aya_log_common::{write_record_header, WriteToBuf}; use log::logger; fn new_log(args: usize) -> Result<(usize, Vec<u8>), ()> { let mut buf = vec![0; 8192]; let len = write_record_header( &mut buf, "test", aya_log_common::Level::Info, "test", "test.rs", 123, args, )?; Ok((len, buf)) } #[test] fn test_str() { testing_logger::setup(); let (len, mut input) = new_log(1).unwrap(); "test" .write(&mut input[len..]) .expect("could not write to the buffer"); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "test"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_str_with_args() { testing_logger::setup(); let (mut len, mut input) = new_log(2).unwrap(); len += "hello " .write(&mut input[len..]) .expect("could not write to the buffer"); "test".write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "hello test"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_default() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "default hint: ".write(&mut input[len..]).unwrap(); len += DisplayHint::Default.write(&mut input[len..]).unwrap(); 14.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "default hint: 14"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_lower_hex() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "lower hex: ".write(&mut input[len..]).unwrap(); len += DisplayHint::LowerHex.write(&mut input[len..]).unwrap(); 200.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "lower hex: c8"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_upper_hex() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "upper hex: ".write(&mut input[len..]).unwrap(); len += DisplayHint::UpperHex.write(&mut input[len..]).unwrap(); 200.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "upper hex: C8"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_ipv4() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "ipv4: ".write(&mut input[len..]).unwrap(); len += DisplayHint::Ipv4.write(&mut input[len..]).unwrap(); // 10.0.0.1 as u32 167772161u32.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "ipv4: 10.0.0.1"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_ipv6_arr_u8_len_16() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "ipv6: ".write(&mut input[len..]).unwrap(); len += DisplayHint::Ipv6.write(&mut input[len..]).unwrap(); // 2001:db8::1:1 as byte array let ipv6_arr: [u8; 16] = [ 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, ]; ipv6_arr.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "ipv6: 2001:db8::1:1"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_ipv6_arr_u16_len_8() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "ipv6: ".write(&mut input[len..]).unwrap(); len += DisplayHint::Ipv6.write(&mut input[len..]).unwrap(); // 2001:db8::1:1 as u16 array let ipv6_arr: [u16; 8] = [ 0x2001, 0x0db8, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, ]; ipv6_arr.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "ipv6: 2001:db8::1:1"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_lower_mac() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "mac: ".write(&mut input[len..]).unwrap(); len += DisplayHint::LowerMac.write(&mut input[len..]).unwrap(); // 00:00:5e:00:53:af as byte array let mac_arr: [u8; 6] = [0x00, 0x00, 0x5e, 0x00, 0x53, 0xaf]; mac_arr.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "mac: 00:00:5e:00:53:af"); assert_eq!(captured_logs[0].level, Level::Info); }); } #[test] fn test_display_hint_upper_mac() { testing_logger::setup(); let (mut len, mut input) = new_log(3).unwrap(); len += "mac: ".write(&mut input[len..]).unwrap(); len += DisplayHint::UpperMac.write(&mut input[len..]).unwrap(); // 00:00:5E:00:53:AF as byte array let mac_arr: [u8; 6] = [0x00, 0x00, 0x5e, 0x00, 0x53, 0xaf]; mac_arr.write(&mut input[len..]).unwrap(); let logger = logger(); let _ = log_buf(&input, logger); testing_logger::validate(|captured_logs| { assert_eq!(captured_logs.len(), 1); assert_eq!(captured_logs[0].body, "mac: 00:00:5E:00:53:AF"); assert_eq!(captured_logs[0].level, Level::Info); }); } } <file_sep>/bpf/aya-bpf/src/maps/lpm_trie.rs use core::{cell::UnsafeCell, marker::PhantomData, mem, ptr::NonNull}; use aya_bpf_bindings::bindings::BPF_F_NO_PREALLOC; use aya_bpf_cty::{c_long, c_void}; use crate::{ bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_LPM_TRIE}, helpers::{bpf_map_delete_elem, bpf_map_lookup_elem, bpf_map_update_elem}, maps::PinningType, }; #[repr(transparent)] pub struct LpmTrie<K, V> { def: UnsafeCell<bpf_map_def>, _k: PhantomData<K>, _v: PhantomData<V>, } unsafe impl<K: Sync, V: Sync> Sync for LpmTrie<K, V> {} #[repr(packed)] pub struct Key<K> { /// Represents the number of bits matched against. pub prefix_len: u32, /// Represents arbitrary data stored in the LpmTrie. pub data: K, } impl<K> Key<K> { pub fn new(prefix_len: u32, data: K) -> Self { Self { prefix_len, data } } } impl<K, V> LpmTrie<K, V> { pub const fn with_max_entries(max_entries: u32, flags: u32) -> LpmTrie<K, V> { let flags = flags | BPF_F_NO_PREALLOC; LpmTrie { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LPM_TRIE, max_entries, flags, PinningType::None, )), _k: PhantomData, _v: PhantomData, } } pub const fn pinned(max_entries: u32, flags: u32) -> LpmTrie<K, V> { let flags = flags | BPF_F_NO_PREALLOC; LpmTrie { def: UnsafeCell::new(build_def::<K, V>( BPF_MAP_TYPE_LPM_TRIE, max_entries, flags, PinningType::ByName, )), _k: PhantomData, _v: PhantomData, } } #[inline] pub fn get(&self, key: &Key<K>) -> Option<&V> { unsafe { let value = bpf_map_lookup_elem(self.def.get() as *mut _, key as *const _ as *const c_void); // FIXME: alignment NonNull::new(value as *mut V).map(|p| p.as_ref()) } } #[inline] pub fn insert(&self, key: &Key<K>, value: &V, flags: u64) -> Result<(), c_long> { let ret = unsafe { bpf_map_update_elem( self.def.get() as *mut _, key as *const _ as *const _, value as *const _ as *const _, flags, ) }; (ret == 0).then_some(()).ok_or(ret) } #[inline] pub fn remove(&self, key: &Key<K>) -> Result<(), c_long> { let ret = unsafe { bpf_map_delete_elem(self.def.get() as *mut _, key as *const _ as *const c_void) }; (ret == 0).then_some(()).ok_or(ret) } } const fn build_def<K, V>(ty: u32, max_entries: u32, flags: u32, pin: PinningType) -> bpf_map_def { bpf_map_def { type_: ty, key_size: mem::size_of::<Key<K>>() as u32, value_size: mem::size_of::<V>() as u32, max_entries, map_flags: flags, id: 0, pinning: pin as u32, } } <file_sep>/test/integration-test/Cargo.toml [package] name = "integration-test" version = "0.1.0" edition = "2021" publish = false [dependencies] anyhow = "1" aya = { path = "../../aya" } clap = { version = "4", features = ["derive"] } env_logger = "0.10" inventory = "0.2" integration-test-macros = { path = "../integration-test-macros" } lazy_static = "1" libc = { version = "0.2.105" } log = "0.4" object = { version = "0.30", default-features = false, features = ["std", "read_core", "elf"] } regex = "1" <file_sep>/aya/src/obj/relocation.rs use std::{collections::HashMap, mem}; use log::debug; use object::{SectionIndex, SymbolKind}; use thiserror::Error; use crate::{ generated::{ bpf_insn, BPF_CALL, BPF_JMP, BPF_K, BPF_PSEUDO_CALL, BPF_PSEUDO_FUNC, BPF_PSEUDO_MAP_FD, BPF_PSEUDO_MAP_VALUE, }, maps::MapData, obj::{Function, Object, Program}, BpfError, }; pub(crate) const INS_SIZE: usize = mem::size_of::<bpf_insn>(); #[derive(Debug, Error)] enum RelocationError { #[error("unknown symbol, index `{index}`")] UnknownSymbol { index: usize }, #[error("section `{section_index}` not found, referenced by symbol `{}` #{symbol_index}", .symbol_name.clone().unwrap_or_default())] SectionNotFound { section_index: usize, symbol_index: usize, symbol_name: Option<String>, }, #[error("function {address:#x} not found while relocating `{caller_name}`")] UnknownFunction { address: u64, caller_name: String }, #[error("the map `{name}` at section `{section_index}` has not been created")] MapNotCreated { section_index: usize, name: String }, #[error("invalid offset `{offset}` applying relocation #{relocation_number}")] InvalidRelocationOffset { offset: u64, relocation_number: usize, }, } #[derive(Debug, Copy, Clone)] pub(crate) struct Relocation { // byte offset of the instruction to be relocated pub(crate) offset: u64, // index of the symbol to relocate to pub(crate) symbol_index: usize, } #[derive(Debug, Clone)] pub(crate) struct Symbol { pub(crate) index: usize, pub(crate) section_index: Option<usize>, pub(crate) name: Option<String>, pub(crate) address: u64, pub(crate) size: u64, pub(crate) is_definition: bool, pub(crate) kind: SymbolKind, } impl Object { pub fn relocate_maps(&mut self, maps: &HashMap<String, MapData>) -> Result<(), BpfError> { let maps_by_section = maps .iter() .map(|(name, map)| (map.obj.section_index(), (name.as_str(), map))) .collect::<HashMap<_, _>>(); let maps_by_symbol = maps .iter() .map(|(name, map)| (map.obj.symbol_index(), (name.as_str(), map))) .collect::<HashMap<_, _>>(); let functions = self .programs .values_mut() .map(|p| &mut p.function) .chain(self.functions.values_mut()); for function in functions { if let Some(relocations) = self.relocations.get(&function.section_index) { relocate_maps( function, relocations.values(), &maps_by_section, &maps_by_symbol, &self.symbols_by_index, self.text_section_index, ) .map_err(|error| BpfError::RelocationError { function: function.name.clone(), error: Box::new(error), })?; } } Ok(()) } pub fn relocate_calls(&mut self) -> Result<(), BpfError> { for (name, program) in self.programs.iter_mut() { let linker = FunctionLinker::new( self.text_section_index, &self.functions, &self.relocations, &self.symbols_by_index, ); linker .link(program) .map_err(|error| BpfError::RelocationError { function: name.clone(), error: Box::new(error), })?; } Ok(()) } } fn relocate_maps<'a, I: Iterator<Item = &'a Relocation>>( fun: &mut Function, relocations: I, maps_by_section: &HashMap<usize, (&str, &MapData)>, maps_by_symbol: &HashMap<usize, (&str, &MapData)>, symbol_table: &HashMap<usize, Symbol>, text_section_index: Option<usize>, ) -> Result<(), RelocationError> { let section_offset = fun.section_offset; let instructions = &mut fun.instructions; let function_size = instructions.len() * INS_SIZE; for (rel_n, rel) in relocations.enumerate() { let rel_offset = rel.offset as usize; if rel_offset < section_offset || rel_offset >= section_offset + function_size { // the relocation doesn't apply to this function continue; } // make sure that the relocation offset is properly aligned let ins_offset = rel_offset - section_offset; if ins_offset % INS_SIZE != 0 { return Err(RelocationError::InvalidRelocationOffset { offset: rel.offset, relocation_number: rel_n, }); } let ins_index = ins_offset / INS_SIZE; // a map relocation points to the ELF section that contains the map let sym = symbol_table .get(&rel.symbol_index) .ok_or(RelocationError::UnknownSymbol { index: rel.symbol_index, })?; let section_index = match sym.section_index { Some(index) => index, // this is not a map relocation None => continue, }; // calls and relocation to .text symbols are handled in a separate step if insn_is_call(&instructions[ins_index]) || sym.section_index == text_section_index { continue; } let (name, map) = if maps_by_symbol.contains_key(&rel.symbol_index) { maps_by_symbol .get(&rel.symbol_index) .ok_or(RelocationError::SectionNotFound { symbol_index: rel.symbol_index, symbol_name: sym.name.clone(), section_index, })? } else { maps_by_section .get(&section_index) .ok_or(RelocationError::SectionNotFound { symbol_index: rel.symbol_index, symbol_name: sym.name.clone(), section_index, })? }; let map_fd = map.fd.ok_or_else(|| RelocationError::MapNotCreated { name: (*name).into(), section_index, })?; if !map.obj.data().is_empty() { instructions[ins_index].set_src_reg(BPF_PSEUDO_MAP_VALUE as u8); instructions[ins_index + 1].imm = instructions[ins_index].imm + sym.address as i32; } else { instructions[ins_index].set_src_reg(BPF_PSEUDO_MAP_FD as u8); } instructions[ins_index].imm = map_fd; } Ok(()) } struct FunctionLinker<'a> { text_section_index: Option<usize>, functions: &'a HashMap<u64, Function>, linked_functions: HashMap<u64, usize>, relocations: &'a HashMap<SectionIndex, HashMap<u64, Relocation>>, symbol_table: &'a HashMap<usize, Symbol>, } impl<'a> FunctionLinker<'a> { fn new( text_section_index: Option<usize>, functions: &'a HashMap<u64, Function>, relocations: &'a HashMap<SectionIndex, HashMap<u64, Relocation>>, symbol_table: &'a HashMap<usize, Symbol>, ) -> FunctionLinker<'a> { FunctionLinker { text_section_index, functions, linked_functions: HashMap::new(), relocations, symbol_table, } } fn link(mut self, program: &mut Program) -> Result<(), RelocationError> { let mut fun = program.function.clone(); // relocate calls in the program's main function. As relocation happens, // it will trigger linking in all the callees. self.relocate(&mut fun, &program.function)?; // this now includes the program function plus all the other functions called during // execution program.function = fun; Ok(()) } fn link_function( &mut self, program: &mut Function, fun: &Function, ) -> Result<usize, RelocationError> { if let Some(fun_ins_index) = self.linked_functions.get(&fun.address) { return Ok(*fun_ins_index); }; // append fun.instructions to the program and record that `fun.address` has been inserted // at `start_ins`. We'll use `start_ins` to do pc-relative calls. let start_ins = program.instructions.len(); program.instructions.extend(&fun.instructions); // link func and line info into the main program // the offset needs to be adjusted self.link_func_and_line_info(program, fun, start_ins)?; self.linked_functions.insert(fun.address, start_ins); // relocate `fun`, recursively linking in all the callees self.relocate(program, fun)?; Ok(start_ins) } fn relocate(&mut self, program: &mut Function, fun: &Function) -> Result<(), RelocationError> { let relocations = self.relocations.get(&fun.section_index); debug!("relocating program {} function {}", program.name, fun.name); let n_instructions = fun.instructions.len(); let start_ins = program.instructions.len() - n_instructions; // process all the instructions. We can't only loop over relocations since we need to // patch pc-relative calls too. for ins_index in start_ins..start_ins + n_instructions { let ins = program.instructions[ins_index]; let is_call = insn_is_call(&ins); // only resolve relocations for calls or for instructions that // reference symbols in the .text section (eg let callback = // &some_fun) let rel = if let Some(relocations) = relocations { self.text_relocation_info( relocations, (fun.section_offset + (ins_index - start_ins) * INS_SIZE) as u64, )? // if not a call and not a .text reference, ignore the // relocation (see relocate_maps()) .and_then(|(_, sym)| { if is_call { return Some(sym.address); } match sym.kind { SymbolKind::Text => Some(sym.address), SymbolKind::Section if sym.section_index == self.text_section_index => { Some(sym.address + ins.imm as u64) } _ => None, } }) } else { None }; // some_fun() or let x = &some_fun trigger linking, everything else // can be ignored here if !is_call && rel.is_none() { continue; } let callee_address = if let Some(address) = rel { // We have a relocation entry for the instruction at `ins_index`, the address of // the callee is the address of the relocation's target symbol. address } else { // The caller and the callee are in the same ELF section and this is a pc-relative // call. Resolve the pc-relative imm to an absolute address. let ins_size = INS_SIZE as i64; (fun.section_offset as i64 + ((ins_index - start_ins) as i64) * ins_size + (ins.imm + 1) as i64 * ins_size) as u64 }; debug!( "relocating {} to callee address {} ({})", if is_call { "call" } else { "reference" }, callee_address, if rel.is_some() { "relocation" } else { "relative" }, ); // lookup and link the callee if it hasn't been linked already. `callee_ins_index` will // contain the instruction index of the callee inside the program. let callee = self.functions .get(&callee_address) .ok_or(RelocationError::UnknownFunction { address: callee_address, caller_name: fun.name.clone(), })?; debug!("callee is {}", callee.name); let callee_ins_index = self.link_function(program, callee)?; let mut ins = &mut program.instructions[ins_index]; ins.imm = if callee_ins_index < ins_index { -((ins_index - callee_ins_index + 1) as i32) } else { (callee_ins_index - ins_index - 1) as i32 }; if !is_call { ins.set_src_reg(BPF_PSEUDO_FUNC as u8); } } debug!( "finished relocating program {} function {}", program.name, fun.name ); Ok(()) } fn link_func_and_line_info( &mut self, program: &mut Function, fun: &Function, start: usize, ) -> Result<(), RelocationError> { let func_info = &fun.func_info.func_info; let func_info = func_info.iter().cloned().map(|mut info| { // `start` is the new instruction offset of `fun` within `program` info.insn_off = start as u32; info }); program.func_info.func_info.extend(func_info); program.func_info.num_info = program.func_info.func_info.len() as u32; let line_info = &fun.line_info.line_info; if !line_info.is_empty() { // this is the original offset let original_start_off = line_info[0].insn_off; let line_info = line_info.iter().cloned().map(|mut info| { // rebase offsets on top of start, which is the offset of the // function in the program being linked info.insn_off = start as u32 + (info.insn_off - original_start_off); info }); program.line_info.line_info.extend(line_info); program.line_info.num_info = program.func_info.func_info.len() as u32; } Ok(()) } fn text_relocation_info( &self, relocations: &HashMap<u64, Relocation>, offset: u64, ) -> Result<Option<(Relocation, Symbol)>, RelocationError> { if let Some(rel) = relocations.get(&offset) { let sym = self.symbol_table .get(&rel.symbol_index) .ok_or(RelocationError::UnknownSymbol { index: rel.symbol_index, })?; Ok(Some((*rel, sym.clone()))) } else { Ok(None) } } } fn insn_is_call(ins: &bpf_insn) -> bool { let klass = (ins.code & 0x07) as u32; let op = (ins.code & 0xF0) as u32; let src = (ins.code & 0x08) as u32; klass == BPF_JMP && op == BPF_CALL && src == BPF_K && ins.src_reg() as u32 == BPF_PSEUDO_CALL && ins.dst_reg() == 0 && ins.off == 0 } #[cfg(test)] mod test { use crate::{ bpf_map_def, maps::MapData, obj::{self, BtfMap, LegacyMap, MapKind}, BtfMapDef, }; use super::*; fn fake_sym(index: usize, section_index: usize, address: u64, name: &str, size: u64) -> Symbol { Symbol { index, section_index: Some(section_index), name: Some(name.to_string()), address, size, is_definition: false, kind: SymbolKind::Data, } } fn ins(bytes: &[u8]) -> bpf_insn { unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const _) } } fn fake_legacy_map(fd: i32, symbol_index: usize) -> MapData { MapData { obj: obj::Map::Legacy(LegacyMap { def: bpf_map_def { ..Default::default() }, section_index: 0, symbol_index, data: Vec::new(), kind: MapKind::Other, }), fd: Some(fd), btf_fd: None, pinned: false, } } fn fake_btf_map(fd: i32, symbol_index: usize) -> MapData { MapData { obj: obj::Map::Btf(BtfMap { def: BtfMapDef { ..Default::default() }, section_index: 0, symbol_index, data: Vec::new(), kind: MapKind::Other, }), fd: Some(fd), btf_fd: None, pinned: false, } } fn fake_func(name: &str, instructions: Vec<bpf_insn>) -> Function { Function { address: Default::default(), name: name.to_string(), section_index: SectionIndex(0), section_offset: Default::default(), instructions, func_info: Default::default(), line_info: Default::default(), func_info_rec_size: Default::default(), line_info_rec_size: Default::default(), } } #[test] fn test_single_legacy_map_relocation() { let mut fun = fake_func( "test", vec![ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ])], ); let symbol_table = HashMap::from([(1, fake_sym(1, 0, 0, "test_map", 0))]); let relocations = vec![Relocation { offset: 0x0, symbol_index: 1, }]; let maps_by_section = HashMap::new(); let map = fake_legacy_map(1, 1); let maps_by_symbol = HashMap::from([(1, ("test_map", &map))]); relocate_maps( &mut fun, relocations.iter(), &maps_by_section, &maps_by_symbol, &symbol_table, None, ) .unwrap(); assert_eq!(fun.instructions[0].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[0].imm, 1); mem::forget(map); } #[test] fn test_multiple_legacy_map_relocation() { let mut fun = fake_func( "test", vec![ ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), ], ); let symbol_table = HashMap::from([ (1, fake_sym(1, 0, 0, "test_map_1", 0)), (2, fake_sym(2, 0, 0, "test_map_2", 0)), ]); let relocations = vec![ Relocation { offset: 0x0, symbol_index: 1, }, Relocation { offset: mem::size_of::<bpf_insn>() as u64, symbol_index: 2, }, ]; let maps_by_section = HashMap::new(); let map_1 = fake_legacy_map(1, 1); let map_2 = fake_legacy_map(2, 2); let maps_by_symbol = HashMap::from([(1, ("test_map_1", &map_1)), (2, ("test_map_2", &map_2))]); relocate_maps( &mut fun, relocations.iter(), &maps_by_section, &maps_by_symbol, &symbol_table, None, ) .unwrap(); assert_eq!(fun.instructions[0].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[0].imm, 1); assert_eq!(fun.instructions[1].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[1].imm, 2); mem::forget(map_1); mem::forget(map_2); } #[test] fn test_single_btf_map_relocation() { let mut fun = fake_func( "test", vec![ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ])], ); let symbol_table = HashMap::from([(1, fake_sym(1, 0, 0, "test_map", 0))]); let relocations = vec![Relocation { offset: 0x0, symbol_index: 1, }]; let maps_by_section = HashMap::new(); let map = fake_btf_map(1, 1); let maps_by_symbol = HashMap::from([(1, ("test_map", &map))]); relocate_maps( &mut fun, relocations.iter(), &maps_by_section, &maps_by_symbol, &symbol_table, None, ) .unwrap(); assert_eq!(fun.instructions[0].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[0].imm, 1); mem::forget(map); } #[test] fn test_multiple_btf_map_relocation() { let mut fun = fake_func( "test", vec![ ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), ins(&[ 0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]), ], ); let symbol_table = HashMap::from([ (1, fake_sym(1, 0, 0, "test_map_1", 0)), (2, fake_sym(2, 0, 0, "test_map_2", 0)), ]); let relocations = vec![ Relocation { offset: 0x0, symbol_index: 1, }, Relocation { offset: mem::size_of::<bpf_insn>() as u64, symbol_index: 2, }, ]; let maps_by_section = HashMap::new(); let map_1 = fake_btf_map(1, 1); let map_2 = fake_btf_map(2, 2); let maps_by_symbol = HashMap::from([(1, ("test_map_1", &map_1)), (2, ("test_map_2", &map_2))]); relocate_maps( &mut fun, relocations.iter(), &maps_by_section, &maps_by_symbol, &symbol_table, None, ) .unwrap(); assert_eq!(fun.instructions[0].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[0].imm, 1); assert_eq!(fun.instructions[1].src_reg(), BPF_PSEUDO_MAP_FD as u8); assert_eq!(fun.instructions[1].imm, 2); mem::forget(map_1); mem::forget(map_2); } } <file_sep>/xtask/src/utils.rs use lazy_static::lazy_static; use serde_json::Value; use std::process::Command; lazy_static! { pub static ref WORKSPACE_ROOT: String = workspace_root(); } fn workspace_root() -> String { let output = Command::new("cargo").arg("metadata").output().unwrap(); if !output.status.success() { panic!("unable to run cargo metadata") } let stdout = String::from_utf8(output.stdout).unwrap(); let v: Value = serde_json::from_str(&stdout).unwrap(); v["workspace_root"].as_str().unwrap().to_string() } <file_sep>/netlify.toml [build] publish = "site" command = "rustup toolchain install nightly -c rust-src && cargo xtask docs" <file_sep>/aya/src/bpf.rs use std::{ borrow::Cow, collections::{HashMap, HashSet}, error::Error, ffi::CString, fs, io, os::{raw::c_int, unix::io::RawFd}, path::{Path, PathBuf}, }; use log::debug; use thiserror::Error; use crate::{ generated::{ bpf_map_type, bpf_map_type::*, AYA_PERF_EVENT_IOC_DISABLE, AYA_PERF_EVENT_IOC_ENABLE, AYA_PERF_EVENT_IOC_SET_BPF, }, maps::{Map, MapData, MapError}, obj::{ btf::{Btf, BtfError}, MapKind, Object, ParseError, ProgramSection, }, programs::{ BtfTracePoint, CgroupDevice, CgroupSkb, CgroupSkbAttachType, CgroupSock, CgroupSockAddr, CgroupSockopt, CgroupSysctl, Extension, FEntry, FExit, KProbe, LircMode2, Lsm, PerfEvent, ProbeKind, Program, ProgramData, ProgramError, RawTracePoint, SchedClassifier, SkLookup, SkMsg, SkSkb, SkSkbKind, SockOps, SocketFilter, TracePoint, UProbe, Xdp, }, sys::{ bpf_load_btf, bpf_map_freeze, bpf_map_update_elem_ptr, is_btf_datasec_supported, is_btf_decl_tag_supported, is_btf_float_supported, is_btf_func_global_supported, is_btf_func_supported, is_btf_supported, is_btf_type_tag_supported, is_prog_name_supported, retry_with_verifier_logs, }, util::{bytes_of, possible_cpus, VerifierLog, POSSIBLE_CPUS}, }; pub(crate) const BPF_OBJ_NAME_LEN: usize = 16; pub(crate) const PERF_EVENT_IOC_ENABLE: c_int = AYA_PERF_EVENT_IOC_ENABLE; pub(crate) const PERF_EVENT_IOC_DISABLE: c_int = AYA_PERF_EVENT_IOC_DISABLE; pub(crate) const PERF_EVENT_IOC_SET_BPF: c_int = AYA_PERF_EVENT_IOC_SET_BPF; /// Marker trait for types that can safely be converted to and from byte slices. pub unsafe trait Pod: Copy + 'static {} macro_rules! unsafe_impl_pod { ($($struct_name:ident),+ $(,)?) => { $( unsafe impl Pod for $struct_name { } )+ } } unsafe_impl_pod!(i8, u8, i16, u16, i32, u32, i64, u64, u128, i128); // It only makes sense that an array of POD types is itself POD unsafe impl<T: Pod, const N: usize> Pod for [T; N] {} #[allow(non_camel_case_types)] #[repr(C)] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct bpf_map_def { // minimum features required by old BPF programs pub(crate) map_type: u32, pub(crate) key_size: u32, pub(crate) value_size: u32, pub(crate) max_entries: u32, pub(crate) map_flags: u32, // optional features pub(crate) id: u32, pub(crate) pinning: PinningType, } #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct BtfMapDef { pub(crate) map_type: u32, pub(crate) key_size: u32, pub(crate) value_size: u32, pub(crate) max_entries: u32, pub(crate) map_flags: u32, pub(crate) pinning: PinningType, pub(crate) btf_key_type_id: u32, pub(crate) btf_value_type_id: u32, } #[repr(u32)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum PinningType { None = 0, ByName = 1, } #[derive(Debug, Error)] pub(crate) enum PinningError { #[error("unsupported pinning type")] Unsupported, } impl TryFrom<u32> for PinningType { type Error = PinningError; fn try_from(value: u32) -> Result<Self, Self::Error> { match value { 0 => Ok(PinningType::None), 1 => Ok(PinningType::ByName), _ => Err(PinningError::Unsupported), } } } impl Default for PinningType { fn default() -> Self { PinningType::None } } // Features implements BPF and BTF feature detection #[derive(Default, Debug)] pub(crate) struct Features { pub bpf_name: bool, pub btf: bool, pub btf_func: bool, pub btf_func_global: bool, pub btf_datasec: bool, pub btf_float: bool, pub btf_decl_tag: bool, pub btf_type_tag: bool, } impl Features { fn probe_features(&mut self) { self.bpf_name = is_prog_name_supported(); debug!("[FEAT PROBE] BPF program name support: {}", self.bpf_name); self.btf = is_btf_supported(); debug!("[FEAT PROBE] BTF support: {}", self.btf); if self.btf { self.btf_func = is_btf_func_supported(); debug!("[FEAT PROBE] BTF func support: {}", self.btf_func); self.btf_func_global = is_btf_func_global_supported(); debug!( "[FEAT PROBE] BTF global func support: {}", self.btf_func_global ); self.btf_datasec = is_btf_datasec_supported(); debug!( "[FEAT PROBE] BTF var and datasec support: {}", self.btf_datasec ); self.btf_float = is_btf_float_supported(); debug!("[FEAT PROBE] BTF float support: {}", self.btf_float); self.btf_decl_tag = is_btf_decl_tag_supported(); debug!("[FEAT PROBE] BTF decl_tag support: {}", self.btf_decl_tag); self.btf_type_tag = is_btf_type_tag_supported(); debug!("[FEAT PROBE] BTF type_tag support: {}", self.btf_type_tag); } } } /// Builder style API for advanced loading of eBPF programs. /// /// Loading eBPF code involves a few steps, including loading maps and applying /// relocations. You can use `BpfLoader` to customize some of the loading /// options. /// /// # Examples /// /// ```no_run /// use aya::{BpfLoader, Btf}; /// use std::fs; /// /// let bpf = BpfLoader::new() /// // load the BTF data from /sys/kernel/btf/vmlinux /// .btf(Btf::from_sys_fs().ok().as_ref()) /// // load pinned maps from /sys/fs/bpf/my-program /// .map_pin_path("/sys/fs/bpf/my-program") /// // finally load the code /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` #[derive(Debug)] pub struct BpfLoader<'a> { btf: Option<Cow<'a, Btf>>, map_pin_path: Option<PathBuf>, globals: HashMap<&'a str, &'a [u8]>, max_entries: HashMap<&'a str, u32>, features: Features, extensions: HashSet<&'a str>, verifier_log_level: VerifierLogLevel, } bitflags! { /// Used to set the verifier log level flags in [BpfLoader](BpfLoader::verifier_log_level()). pub struct VerifierLogLevel: u32 { /// Sets no verifier logging. const DISABLE = 0; /// Enables debug verifier logging. const DEBUG = 1; /// Enables verbose verifier logging. const VERBOSE = 2 | Self::DEBUG.bits; /// Enables verifier stats. const STATS = 4; } } impl Default for VerifierLogLevel { fn default() -> Self { Self { bits: Self::DEBUG.bits | Self::STATS.bits, } } } impl<'a> BpfLoader<'a> { /// Creates a new loader instance. pub fn new() -> BpfLoader<'a> { let mut features = Features::default(); features.probe_features(); BpfLoader { btf: Btf::from_sys_fs().ok().map(Cow::Owned), map_pin_path: None, globals: HashMap::new(), max_entries: HashMap::new(), features, extensions: HashSet::new(), verifier_log_level: VerifierLogLevel::default(), } } /// Sets the target [BTF](Btf) info. /// /// The loader defaults to loading `BTF` info using [Btf::from_sys_fs]. /// Use this method if you want to load `BTF` from a custom location or /// pass `None` to disable `BTF` relocations entirely. /// # Example /// /// ```no_run /// use aya::{BpfLoader, Btf, Endianness}; /// /// let bpf = BpfLoader::new() /// // load the BTF data from a custom location /// .btf(Btf::parse_file("/custom_btf_file", Endianness::default()).ok().as_ref()) /// .load_file("file.o")?; /// /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn btf(&mut self, btf: Option<&'a Btf>) -> &mut BpfLoader<'a> { self.btf = btf.map(Cow::Borrowed); self } /// Sets the base directory path for pinned maps. /// /// Pinned maps will be loaded from `path/MAP_NAME`. /// The caller is responsible for ensuring the directory exists. /// /// # Example /// /// ```no_run /// use aya::BpfLoader; /// /// let bpf = BpfLoader::new() /// .map_pin_path("/sys/fs/bpf/my-program") /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` /// pub fn map_pin_path<P: AsRef<Path>>(&mut self, path: P) -> &mut BpfLoader<'a> { self.map_pin_path = Some(path.as_ref().to_owned()); self } /// Sets the value of a global variable /// /// From Rust eBPF, a global variable would be constructed as follows: /// ```no_run /// #[no_mangle] /// static VERSION: i32 = 0; /// ``` /// Then it would be accessed with `core::ptr::read_volatile` inside /// functions: /// ```no_run /// # #[no_mangle] /// # static VERSION: i32 = 0; /// # unsafe fn try_test() { /// let version = core::ptr::read_volatile(&VERSION); /// # } /// ``` /// If using a struct, ensure that it is `#[repr(C)]` to ensure the size will /// match that of the corresponding ELF symbol. /// /// From C eBPF, you would annotate a variable as `volatile const` /// /// # Example /// /// ```no_run /// use aya::BpfLoader; /// /// let bpf = BpfLoader::new() /// .set_global("VERSION", &2) /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` /// pub fn set_global<V: Pod>(&mut self, name: &'a str, value: &'a V) -> &mut BpfLoader<'a> { // Safety: value is POD let data = unsafe { bytes_of(value) }; self.globals.insert(name, data); self } /// Set the max_entries for specified map. /// /// Overwrite the value of max_entries of the map that matches /// the provided name before the map is created. /// /// # Example /// /// ```no_run /// use aya::BpfLoader; /// /// let bpf = BpfLoader::new() /// .set_max_entries("map", 64) /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` /// pub fn set_max_entries(&mut self, name: &'a str, size: u32) -> &mut BpfLoader<'a> { self.max_entries.insert(name, size); self } /// Treat the provided program as an [`Extension`] /// /// When attempting to load the program with the provided `name` /// the program type is forced to be ] [`Extension`] and is not /// inferred from the ELF section name. /// /// # Example /// /// ```no_run /// use aya::BpfLoader; /// /// let bpf = BpfLoader::new() /// .extension("myfunc") /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` /// pub fn extension(&mut self, name: &'a str) -> &mut BpfLoader<'a> { self.extensions.insert(name); self } /// Sets BPF verifier log level. /// /// # Example /// /// ```no_run /// use aya::{BpfLoader, VerifierLogLevel}; /// /// let bpf = BpfLoader::new() /// .verifier_log_level(VerifierLogLevel::VERBOSE | VerifierLogLevel::STATS) /// .load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` /// pub fn verifier_log_level(&mut self, level: VerifierLogLevel) -> &mut BpfLoader<'a> { self.verifier_log_level = level; self } /// Loads eBPF bytecode from a file. /// /// # Examples /// /// ```no_run /// use aya::BpfLoader; /// /// let bpf = BpfLoader::new().load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> Result<Bpf, BpfError> { let path = path.as_ref(); self.load(&fs::read(path).map_err(|error| BpfError::FileError { path: path.to_owned(), error, })?) } /// Loads eBPF bytecode from a buffer. /// /// # Examples /// /// ```no_run /// use aya::BpfLoader; /// use std::fs; /// /// let data = fs::read("file.o").unwrap(); /// let bpf = BpfLoader::new().load(&data)?; /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn load(&mut self, data: &[u8]) -> Result<Bpf, BpfError> { let verifier_log_level = self.verifier_log_level.bits; let mut obj = Object::parse(data)?; obj.patch_map_data(self.globals.clone())?; let btf_fd = if self.features.btf { if let Some(ref mut obj_btf) = obj.btf { // fixup btf let section_data = obj.section_sizes.clone(); let symbol_offsets = obj.symbol_offset_by_name.clone(); obj_btf.fixup_and_sanitize(&section_data, &symbol_offsets, &self.features)?; // load btf to the kernel let raw_btf = obj_btf.to_bytes(); Some(load_btf(raw_btf)?) } else { None } } else { None }; if let Some(btf) = &self.btf { obj.relocate_btf(btf)?; } let mut maps = HashMap::new(); for (name, mut obj) in obj.maps.drain() { match self.max_entries.get(name.as_str()) { Some(size) => obj.set_max_entries(*size), None => { if obj.map_type() == BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32 && obj.max_entries() == 0 { obj.set_max_entries( possible_cpus() .map_err(|error| BpfError::FileError { path: PathBuf::from(POSSIBLE_CPUS), error, })? .len() as u32, ); } } } let mut map = MapData { obj, fd: None, pinned: false, btf_fd, }; let fd = match map.obj.pinning() { PinningType::ByName => { let path = match &self.map_pin_path { Some(p) => p, None => return Err(BpfError::NoPinPath), }; // try to open map in case it's already pinned match map.open_pinned(&name, path) { Ok(fd) => { map.pinned = true; fd as RawFd } Err(_) => { let fd = map.create(&name)?; map.pin(&name, path).map_err(|error| MapError::PinError { name: Some(name.to_string()), error, })?; fd } } } PinningType::None => map.create(&name)?, }; if !map.obj.data().is_empty() && map.obj.kind() != MapKind::Bss { bpf_map_update_elem_ptr(fd, &0 as *const _, map.obj.data_mut().as_mut_ptr(), 0) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, })?; } if map.obj.kind() == MapKind::Rodata { bpf_map_freeze(fd).map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_freeze".to_owned(), io_error, })?; } maps.insert(name, map); } obj.relocate_maps(&maps)?; obj.relocate_calls()?; let programs = obj .programs .drain() .map(|(name, obj)| { let prog_name = if self.features.bpf_name { Some(name.clone()) } else { None }; let section = obj.section.clone(); let program = if self.extensions.contains(name.as_str()) { Program::Extension(Extension { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } else { match &section { ProgramSection::KProbe { .. } => Program::KProbe(KProbe { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: ProbeKind::KProbe, }), ProgramSection::KRetProbe { .. } => Program::KProbe(KProbe { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: ProbeKind::KRetProbe, }), ProgramSection::UProbe { .. } => Program::UProbe(UProbe { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: ProbeKind::UProbe, }), ProgramSection::URetProbe { .. } => Program::UProbe(UProbe { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: ProbeKind::URetProbe, }), ProgramSection::TracePoint { .. } => Program::TracePoint(TracePoint { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::SocketFilter { .. } => { Program::SocketFilter(SocketFilter { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } ProgramSection::Xdp { .. } => Program::Xdp(Xdp { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::SkMsg { .. } => Program::SkMsg(SkMsg { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::CgroupSysctl { .. } => { Program::CgroupSysctl(CgroupSysctl { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } ProgramSection::CgroupSockopt { attach_type, .. } => { Program::CgroupSockopt(CgroupSockopt { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), attach_type: *attach_type, }) } ProgramSection::SkSkbStreamParser { .. } => Program::SkSkb(SkSkb { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: SkSkbKind::StreamParser, }), ProgramSection::SkSkbStreamVerdict { .. } => Program::SkSkb(SkSkb { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), kind: SkSkbKind::StreamVerdict, }), ProgramSection::SockOps { .. } => Program::SockOps(SockOps { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::SchedClassifier { .. } => { Program::SchedClassifier(SchedClassifier { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), name: unsafe { CString::from_vec_unchecked(Vec::from(name.clone())) .into_boxed_c_str() }, }) } ProgramSection::CgroupSkb { .. } => Program::CgroupSkb(CgroupSkb { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), expected_attach_type: None, }), ProgramSection::CgroupSkbIngress { .. } => Program::CgroupSkb(CgroupSkb { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), expected_attach_type: Some(CgroupSkbAttachType::Ingress), }), ProgramSection::CgroupSkbEgress { .. } => Program::CgroupSkb(CgroupSkb { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), expected_attach_type: Some(CgroupSkbAttachType::Egress), }), ProgramSection::CgroupSockAddr { attach_type, .. } => { Program::CgroupSockAddr(CgroupSockAddr { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), attach_type: *attach_type, }) } ProgramSection::LircMode2 { .. } => Program::LircMode2(LircMode2 { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::PerfEvent { .. } => Program::PerfEvent(PerfEvent { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::RawTracePoint { .. } => { Program::RawTracePoint(RawTracePoint { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } ProgramSection::Lsm { .. } => Program::Lsm(Lsm { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::BtfTracePoint { .. } => { Program::BtfTracePoint(BtfTracePoint { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } ProgramSection::FEntry { .. } => Program::FEntry(FEntry { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::FExit { .. } => Program::FExit(FExit { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::Extension { .. } => Program::Extension(Extension { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::SkLookup { .. } => Program::SkLookup(SkLookup { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }), ProgramSection::CgroupSock { attach_type, .. } => { Program::CgroupSock(CgroupSock { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), attach_type: *attach_type, }) } ProgramSection::CgroupDevice { .. } => { Program::CgroupDevice(CgroupDevice { data: ProgramData::new(prog_name, obj, btf_fd, verifier_log_level), }) } } }; (name, program) }) .collect(); let maps: Result<HashMap<String, Map>, BpfError> = maps.drain().map(parse_map).collect(); Ok(Bpf { maps: maps?, programs, }) } } fn parse_map(data: (String, MapData)) -> Result<(String, Map), BpfError> { let name = data.0; let map = data.1; let map_type = bpf_map_type::try_from(map.obj.map_type())?; let map = match map_type { BPF_MAP_TYPE_ARRAY => Ok(Map::Array(map)), BPF_MAP_TYPE_PERCPU_ARRAY => Ok(Map::PerCpuArray(map)), BPF_MAP_TYPE_PROG_ARRAY => Ok(Map::ProgramArray(map)), BPF_MAP_TYPE_HASH => Ok(Map::HashMap(map)), BPF_MAP_TYPE_PERCPU_HASH => Ok(Map::PerCpuHashMap(map)), BPF_MAP_TYPE_PERF_EVENT_ARRAY | BPF_MAP_TYPE_LRU_PERCPU_HASH => { Ok(Map::PerfEventArray(map)) } BPF_MAP_TYPE_SOCKHASH => Ok(Map::SockHash(map)), BPF_MAP_TYPE_SOCKMAP => Ok(Map::SockMap(map)), BPF_MAP_TYPE_BLOOM_FILTER => Ok(Map::BloomFilter(map)), BPF_MAP_TYPE_LPM_TRIE => Ok(Map::LpmTrie(map)), BPF_MAP_TYPE_STACK => Ok(Map::Stack(map)), BPF_MAP_TYPE_STACK_TRACE => Ok(Map::StackTraceMap(map)), BPF_MAP_TYPE_QUEUE => Ok(Map::Queue(map)), m => Err(BpfError::MapError(MapError::InvalidMapType { map_type: m as u32, })), }?; Ok((name, map)) } impl<'a> Default for BpfLoader<'a> { fn default() -> Self { BpfLoader::new() } } /// The main entry point into the library, used to work with eBPF programs and maps. #[derive(Debug)] pub struct Bpf { maps: HashMap<String, Map>, programs: HashMap<String, Program>, } impl Bpf { /// Loads eBPF bytecode from a file. /// /// Parses the given object code file and initializes the [maps](crate::maps) defined in it. If /// the kernel supports [BTF](Btf) debug info, it is automatically loaded from /// `/sys/kernel/btf/vmlinux`. /// /// For more loading options, see [BpfLoader]. /// /// # Examples /// /// ```no_run /// use aya::Bpf; /// /// let bpf = Bpf::load_file("file.o")?; /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn load_file<P: AsRef<Path>>(path: P) -> Result<Bpf, BpfError> { BpfLoader::new() .btf(Btf::from_sys_fs().ok().as_ref()) .load_file(path) } /// Loads eBPF bytecode from a buffer. /// /// Parses the object code contained in `data` and initializes the /// [maps](crate::maps) defined in it. If the kernel supports [BTF](Btf) /// debug info, it is automatically loaded from `/sys/kernel/btf/vmlinux`. /// /// For more loading options, see [BpfLoader]. /// /// # Examples /// /// ```no_run /// use aya::{Bpf, Btf}; /// use std::fs; /// /// let data = fs::read("file.o").unwrap(); /// // load the BTF data from /sys/kernel/btf/vmlinux /// let bpf = Bpf::load(&data)?; /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn load(data: &[u8]) -> Result<Bpf, BpfError> { BpfLoader::new() .btf(Btf::from_sys_fs().ok().as_ref()) .load(data) } /// Returns a reference to the map with the given name. /// /// The returned type is mostly opaque. In order to do anything useful with it you need to /// convert it to a [typed map](crate::maps). /// /// For more details and examples on maps and their usage, see the [maps module /// documentation][crate::maps]. pub fn map(&self, name: &str) -> Option<&Map> { self.maps.get(name) } /// Returns a mutable reference to the map with the given name. /// /// The returned type is mostly opaque. In order to do anything useful with it you need to /// convert it to a [typed map](crate::maps). /// /// For more details and examples on maps and their usage, see the [maps module /// documentation][crate::maps]. pub fn map_mut(&mut self, name: &str) -> Option<&mut Map> { self.maps.get_mut(name) } /// Takes ownership of a map with the given name. /// /// Use this when borrowing with [`map`](crate::Bpf::map) or [`map_mut`](crate::Bpf::map_mut) /// is not possible (eg when using the map from an async task). The returned /// map will be closed on `Drop`, therefore the caller is responsible for /// managing its lifetime. /// /// The returned type is mostly opaque. In order to do anything useful with it you need to /// convert it to a [typed map](crate::maps). /// /// For more details and examples on maps and their usage, see the [maps module /// documentation][crate::maps]. pub fn take_map(&mut self, name: &str) -> Option<Map> { self.maps.remove(name) } /// An iterator over all the maps. /// /// # Examples /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// for (name, map) in bpf.maps() { /// println!( /// "found map `{}`", /// name, /// ); /// } /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn maps(&self) -> impl Iterator<Item = (&str, &Map)> { self.maps.iter().map(|(name, map)| (name.as_str(), map)) } /// Returns a reference to the program with the given name. /// /// You can use this to inspect a program and its properties. To load and attach a program, use /// [program_mut](Self::program_mut) instead. /// /// For more details on programs and their usage, see the [programs module /// documentation](crate::programs). /// /// # Examples /// /// ```no_run /// # let bpf = aya::Bpf::load(&[])?; /// let program = bpf.program("SSL_read").unwrap(); /// println!("program SSL_read is of type {:?}", program.prog_type()); /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn program(&self, name: &str) -> Option<&Program> { self.programs.get(name) } /// Returns a mutable reference to the program with the given name. /// /// Used to get a program before loading and attaching it. For more details on programs and /// their usage, see the [programs module documentation](crate::programs). /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::programs::UProbe; /// /// let program: &mut UProbe = bpf.program_mut("SSL_read").unwrap().try_into()?; /// program.load()?; /// program.attach(Some("SSL_read"), 0, "libssl", None)?; /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn program_mut(&mut self, name: &str) -> Option<&mut Program> { self.programs.get_mut(name) } /// An iterator over all the programs. /// /// # Examples /// ```no_run /// # let bpf = aya::Bpf::load(&[])?; /// for (name, program) in bpf.programs() { /// println!( /// "found program `{}` of type `{:?}`", /// name, /// program.prog_type() /// ); /// } /// # Ok::<(), aya::BpfError>(()) /// ``` pub fn programs(&self) -> impl Iterator<Item = (&str, &Program)> { self.programs.iter().map(|(s, p)| (s.as_str(), p)) } /// An iterator mutably referencing all of the programs. /// /// # Examples /// ```no_run /// # use std::path::Path; /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # #[error(transparent)] /// # Pin(#[from] aya::pin::PinError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// # let pin_path = Path::new("/tmp/pin_path"); /// for (_, program) in bpf.programs_mut() { /// program.pin(pin_path)?; /// } /// # Ok::<(), Error>(()) /// ``` pub fn programs_mut(&mut self) -> impl Iterator<Item = (&str, &mut Program)> { self.programs.iter_mut().map(|(s, p)| (s.as_str(), p)) } } /// The error type returned by [`Bpf::load_file`] and [`Bpf::load`]. #[derive(Debug, Error)] pub enum BpfError { /// Error loading file #[error("error loading {path}")] FileError { /// The file path path: PathBuf, #[source] /// The original io::Error error: io::Error, }, /// Pinning requested but no path provided #[error("pinning requested but no path provided")] NoPinPath, /// Unexpected pinning type #[error("unexpected pinning type {name}")] UnexpectedPinningType { /// The value encountered name: u32, }, /// Invalid path #[error("invalid path `{error}`")] InvalidPath { /// The error message error: String, }, /// Error parsing BPF object #[error("error parsing BPF object")] ParseError(#[from] ParseError), /// Error parsing BTF object #[error("BTF error")] BtfError(#[from] BtfError), /// Error performing relocations #[error("error relocating `{function}`")] RelocationError { /// The function name function: String, #[source] /// The original error error: Box<dyn Error + Send + Sync>, }, /// No BTF parsed for object #[error("no BTF parsed for object")] NoBTF, #[error("map error")] /// A map error MapError(#[from] MapError), #[error("program error")] /// A program error ProgramError(#[from] ProgramError), } fn load_btf(raw_btf: Vec<u8>) -> Result<RawFd, BtfError> { let mut logger = VerifierLog::new(); let ret = retry_with_verifier_logs(10, &mut logger, |logger| { bpf_load_btf(raw_btf.as_slice(), logger) }); match ret { Ok(fd) => Ok(fd as RawFd), Err((_, io_error)) => { logger.truncate(); Err(BtfError::LoadError { io_error, verifier_log: logger .as_c_str() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "[none]".to_owned()), }) } } } <file_sep>/aya-tool/src/bindgen.rs use bindgen::{self, Builder, EnumVariation}; pub fn user_builder() -> Builder { bindgen::builder() .layout_tests(false) .generate_comments(false) .prepend_enum_name(false) .default_enum_style(EnumVariation::Rust { non_exhaustive: false, }) } pub fn bpf_builder() -> Builder { bindgen::builder() .use_core() .ctypes_prefix("::aya_bpf::cty") .layout_tests(false) .generate_comments(false) .clang_arg("-Wno-unknown-attributes") .default_enum_style(EnumVariation::ModuleConsts) .prepend_enum_name(false) // NOTE(vadorovsky): It's a workaround for the upstream bindgen issue: // https://github.com/rust-lang/rust-bindgen/issues/2083 // tl;dr: Rust nightly complains about #[repr(packed)] structs deriving // Debug without Copy. // It needs to be fixed properly upstream, but for now we have to // disable Debug derive here. .derive_debug(false) } <file_sep>/aya-log-common/src/lib.rs #![no_std] use core::{cmp, mem, ptr, slice}; use num_enum::IntoPrimitive; pub const LOG_BUF_CAPACITY: usize = 8192; pub const LOG_FIELDS: usize = 6; #[repr(usize)] #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum Level { /// The "error" level. /// /// Designates very serious errors. Error = 1, /// The "warn" level. /// /// Designates hazardous situations. Warn, /// The "info" level. /// /// Designates useful information. Info, /// The "debug" level. /// /// Designates lower priority information. Debug, /// The "trace" level. /// /// Designates very low priority, often extremely verbose, information. Trace, } #[repr(usize)] #[derive(Copy, Clone, Debug)] pub enum RecordField { Target = 1, Level, Module, File, Line, NumArgs, } /// Types which are supported by aya-log and can be safely sent from eBPF /// programs to userspace. #[repr(usize)] #[derive(Copy, Clone, Debug)] pub enum Argument { DisplayHint, I8, I16, I32, I64, Isize, U8, U16, U32, U64, Usize, F32, F64, /// `[u8; 6]` array which represents a MAC address. ArrU8Len6, /// `[u8; 16]` array which represents an IPv6 address. ArrU8Len16, /// `[u16; 8]` array which represents an IPv6 address. ArrU16Len8, Str, } /// All display hints #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq, Eq, IntoPrimitive)] pub enum DisplayHint { /// Default string representation. Default = 1, /// `:x` LowerHex, /// `:X` UpperHex, /// `:ipv4` Ipv4, /// `:ipv6` Ipv6, /// `:mac` LowerMac, /// `:MAC` UpperMac, } #[cfg(feature = "userspace")] mod userspace { use super::*; unsafe impl aya::Pod for RecordField {} unsafe impl aya::Pod for Argument {} unsafe impl aya::Pod for DisplayHint {} } struct TagLenValue<'a, T> { tag: T, value: &'a [u8], } impl<'a, T> TagLenValue<'a, T> where T: Copy, { #[inline(always)] pub(crate) fn new(tag: T, value: &'a [u8]) -> TagLenValue<'a, T> { TagLenValue { tag, value } } pub(crate) fn write(&self, mut buf: &mut [u8]) -> Result<usize, ()> { let size = mem::size_of::<T>() + mem::size_of::<usize>() + self.value.len(); let remaining = cmp::min(buf.len(), LOG_BUF_CAPACITY); // Check if the size doesn't exceed the buffer bounds. if size > remaining { return Err(()); } unsafe { ptr::write_unaligned(buf.as_mut_ptr() as *mut _, self.tag) }; buf = &mut buf[mem::size_of::<T>()..]; unsafe { ptr::write_unaligned(buf.as_mut_ptr() as *mut _, self.value.len()) }; buf = &mut buf[mem::size_of::<usize>()..]; let len = cmp::min(buf.len(), self.value.len()); // The verifier isn't happy with `len` being unbounded, so compare it // with `LOG_BUF_CAPACITY`. if len > LOG_BUF_CAPACITY { return Err(()); } buf[..len].copy_from_slice(&self.value[..len]); Ok(size) } } pub trait WriteToBuf { #[allow(clippy::result_unit_err)] fn write(&self, buf: &mut [u8]) -> Result<usize, ()>; } macro_rules! impl_write_to_buf { ($type:ident, $arg_type:expr) => { impl WriteToBuf for $type { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { TagLenValue::<Argument>::new($arg_type, &self.to_ne_bytes()).write(buf) } } }; } impl_write_to_buf!(i8, Argument::I8); impl_write_to_buf!(i16, Argument::I16); impl_write_to_buf!(i32, Argument::I32); impl_write_to_buf!(i64, Argument::I64); impl_write_to_buf!(isize, Argument::Isize); impl_write_to_buf!(u8, Argument::U8); impl_write_to_buf!(u16, Argument::U16); impl_write_to_buf!(u32, Argument::U32); impl_write_to_buf!(u64, Argument::U64); impl_write_to_buf!(usize, Argument::Usize); impl_write_to_buf!(f32, Argument::F32); impl_write_to_buf!(f64, Argument::F64); impl WriteToBuf for [u8; 16] { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { TagLenValue::<Argument>::new(Argument::ArrU8Len16, self).write(buf) } } impl WriteToBuf for [u16; 8] { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { let ptr = self.as_ptr().cast::<u8>(); let bytes = unsafe { slice::from_raw_parts(ptr, 16) }; TagLenValue::<Argument>::new(Argument::ArrU16Len8, bytes).write(buf) } } impl WriteToBuf for [u8; 6] { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { TagLenValue::<Argument>::new(Argument::ArrU8Len6, self).write(buf) } } impl WriteToBuf for str { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { TagLenValue::<Argument>::new(Argument::Str, self.as_bytes()).write(buf) } } impl WriteToBuf for DisplayHint { fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { let v: u8 = (*self).into(); TagLenValue::<Argument>::new(Argument::DisplayHint, &v.to_ne_bytes()).write(buf) } } #[allow(clippy::result_unit_err)] #[doc(hidden)] #[inline(always)] pub fn write_record_header( buf: &mut [u8], target: &str, level: Level, module: &str, file: &str, line: u32, num_args: usize, ) -> Result<usize, ()> { let mut size = 0; for attr in [ TagLenValue::<RecordField>::new(RecordField::Target, target.as_bytes()), TagLenValue::<RecordField>::new(RecordField::Level, &(level as usize).to_ne_bytes()), TagLenValue::<RecordField>::new(RecordField::Module, module.as_bytes()), TagLenValue::<RecordField>::new(RecordField::File, file.as_bytes()), TagLenValue::<RecordField>::new(RecordField::Line, &line.to_ne_bytes()), TagLenValue::<RecordField>::new(RecordField::NumArgs, &num_args.to_ne_bytes()), ] { size += attr.write(&mut buf[size..])?; } Ok(size) } <file_sep>/bpf/aya-bpf/Cargo.toml [package] name = "aya-bpf" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2021" [dependencies] aya-bpf-cty = { path = "../aya-bpf-cty" } aya-bpf-macros = { path = "../../aya-bpf-macros" } aya-bpf-bindings = { path = "../aya-bpf-bindings" } [build-dependencies] rustversion = "1.0" <file_sep>/bpf/aya-log-ebpf/src/lib.rs #![no_std] use aya_bpf::{ macros::map, maps::{PerCpuArray, PerfEventByteArray}, }; pub use aya_log_common::{write_record_header, Level, WriteToBuf, LOG_BUF_CAPACITY}; pub use aya_log_ebpf_macros::{debug, error, info, log, trace, warn}; #[doc(hidden)] #[repr(C)] pub struct LogBuf { pub buf: [u8; LOG_BUF_CAPACITY], } #[doc(hidden)] #[map] pub static mut AYA_LOG_BUF: PerCpuArray<LogBuf> = PerCpuArray::with_max_entries(1, 0); #[doc(hidden)] #[map] pub static mut AYA_LOGS: PerfEventByteArray = PerfEventByteArray::new(0); #[doc(hidden)] pub mod macro_support { pub use aya_log_common::{DisplayHint, Level, LOG_BUF_CAPACITY}; pub use aya_log_ebpf_macros::log; } <file_sep>/aya/src/maps/mod.rs //! Data structures used to setup and share data with eBPF programs. //! //! The eBPF platform provides data structures - maps in eBPF speak - that are //! used to setup and share data with eBPF programs. When you call //! [`Bpf::load_file`](crate::Bpf::load_file) or //! [`Bpf::load`](crate::Bpf::load), all the maps defined in the eBPF code get //! initialized and can then be accessed using [`Bpf::map`](crate::Bpf::map), //! [`Bpf::map_mut`](crate::Bpf::map_mut), or [`Bpf::take_map`](crate::Bpf::take_map). //! //! # Typed maps //! //! The eBPF API includes many map types each supporting different operations. //! [`Bpf::map`](crate::Bpf::map), [`Bpf::map_mut`](crate::Bpf::map_mut), and //! [`Bpf::take_map`](crate::Bpf::take_map) always return the //! opaque [`&Map`](crate::maps::Map), [`&mut Map`](crate::maps::Map), and [`Map`](crate::maps::Map) //! types respectively. Those three types can be converted to *typed maps* using //! the [`TryFrom`](std::convert::TryFrom) or [`TryInto`](std::convert::TryInto) //! trait. For example: //! //! ```no_run //! # let mut bpf = aya::Bpf::load(&[])?; //! use aya::maps::SockMap; //! use aya::programs::SkMsg; //! //! let intercept_egress = SockMap::try_from(bpf.map_mut("INTERCEPT_EGRESS").unwrap())?; //! let map_fd = intercept_egress.fd()?; //! let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; //! prog.load()?; //! prog.attach(map_fd)?; //! //! # Ok::<(), aya::BpfError>(()) //! ``` //! //! # Maps and `Pod` values //! //! Many map operations copy data from kernel space to user space and vice //! versa. Because of that, all map values must be plain old data and therefore //! implement the [Pod] trait. use std::{ convert::{AsMut, AsRef}, ffi::CString, fmt, io, marker::PhantomData, mem, ops::Deref, os::unix::{io::RawFd, prelude::AsRawFd}, path::Path, ptr, }; use libc::{getrlimit, rlimit, RLIMIT_MEMLOCK, RLIM_INFINITY}; use log::warn; use thiserror::Error; use crate::{ generated::bpf_map_type, obj::{self, parse_map_info}, pin::PinError, sys::{ bpf_create_map, bpf_get_object, bpf_map_get_info_by_fd, bpf_map_get_next_key, bpf_pin_object, kernel_version, }, util::nr_cpus, PinningType, Pod, }; pub mod array; pub mod bloom_filter; pub mod hash_map; pub mod lpm_trie; pub mod perf; pub mod queue; pub mod sock; pub mod stack; pub mod stack_trace; pub use array::{Array, PerCpuArray, ProgramArray}; pub use bloom_filter::BloomFilter; pub use hash_map::{HashMap, PerCpuHashMap}; pub use lpm_trie::LpmTrie; #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] pub use perf::AsyncPerfEventArray; pub use perf::PerfEventArray; pub use queue::Queue; pub use sock::{SockHash, SockMap}; pub use stack::Stack; pub use stack_trace::StackTraceMap; #[derive(Error, Debug)] /// Errors occuring from working with Maps pub enum MapError { /// Invalid map type encontered #[error("invalid map type {map_type}")] InvalidMapType { /// The map type map_type: u32, }, /// Invalid map name encountered #[error("invalid map name `{name}`")] InvalidName { /// The map name name: String, }, /// The map has not been created #[error("the map has not been created")] NotCreated, /// The map has already been created #[error("the map `{name}` has already been created")] AlreadyCreated { /// Map name name: String, }, /// Failed to create map #[error("failed to create map `{name}` with code {code}")] CreateError { /// Map name name: String, /// Error code code: libc::c_long, #[source] /// Original io::Error io_error: io::Error, }, /// Invalid key size #[error("invalid key size {size}, expected {expected}")] InvalidKeySize { /// Size encountered size: usize, /// Size expected expected: usize, }, /// Invalid value size #[error("invalid value size {size}, expected {expected}")] InvalidValueSize { /// Size encountered size: usize, /// Size expected expected: usize, }, /// Index is out of bounds #[error("the index is {index} but `max_entries` is {max_entries}")] OutOfBounds { /// Index accessed index: u32, /// Map size max_entries: u32, }, /// Key not found #[error("key not found")] KeyNotFound, /// Element not found #[error("element not found")] ElementNotFound, /// Progam Not Loaded #[error("the program is not loaded")] ProgramNotLoaded, /// Syscall failed #[error("the `{call}` syscall failed")] SyscallError { /// Syscall Name call: String, /// Original io::Error io_error: io::Error, }, /// Could not pin map by name #[error("map `{name:?}` requested pinning by name. pinning failed")] PinError { /// The map name name: Option<String>, /// The reason for the failure #[source] error: PinError, }, } /// A map file descriptor. pub struct MapFd(RawFd); impl AsRawFd for MapFd { fn as_raw_fd(&self) -> RawFd { self.0 } } #[derive(PartialEq, Eq, PartialOrd, Ord)] struct RlimitSize(usize); impl fmt::Display for RlimitSize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.0 < 1024 { write!(f, "{} bytes", self.0) } else if self.0 < 1024 * 1024 { write!(f, "{} KiB", self.0 / 1024) } else { write!(f, "{} MiB", self.0 / 1024 / 1024) } } } /// Raises a warning about rlimit. Should be used only if creating a map was not /// successful. fn maybe_warn_rlimit() { let mut limit = std::mem::MaybeUninit::<rlimit>::uninit(); let ret = unsafe { getrlimit(RLIMIT_MEMLOCK, limit.as_mut_ptr()) }; if ret == 0 { let limit = unsafe { limit.assume_init() }; let limit: RlimitSize = RlimitSize(limit.rlim_cur.try_into().unwrap()); if limit.0 == RLIM_INFINITY.try_into().unwrap() { return; } warn!( "RLIMIT_MEMLOCK value is {}, not RLIM_INFNITY; if experiencing problems with creating \ maps, try raising RMILIT_MEMLOCK either to RLIM_INFINITY or to a higher value sufficient \ for size of your maps", limit ); } } /// eBPF map types. #[derive(Debug)] pub enum Map { /// A [`Array`] map Array(MapData), /// A [`PerCpuArray`] map PerCpuArray(MapData), /// A [`ProgramArray`] map ProgramArray(MapData), /// A [`HashMap`] map HashMap(MapData), /// A [`PerCpuHashMap`] map PerCpuHashMap(MapData), /// A [`PerfEventArray`] map PerfEventArray(MapData), /// A [`SockMap`] map SockMap(MapData), /// A [`SockHash`] map SockHash(MapData), /// A [`BloomFilter`] map BloomFilter(MapData), /// A [`LpmTrie`] map LpmTrie(MapData), /// A [`Stack`] map Stack(MapData), /// A [`StackTraceMap`] map StackTraceMap(MapData), /// A [`Queue`] map Queue(MapData), } impl Map { /// Returns the low level map type. fn map_type(&self) -> u32 { match self { Map::Array(map) => map.obj.map_type(), Map::PerCpuArray(map) => map.obj.map_type(), Map::ProgramArray(map) => map.obj.map_type(), Map::HashMap(map) => map.obj.map_type(), Map::PerCpuHashMap(map) => map.obj.map_type(), Map::PerfEventArray(map) => map.obj.map_type(), Map::SockHash(map) => map.obj.map_type(), Map::SockMap(map) => map.obj.map_type(), Map::BloomFilter(map) => map.obj.map_type(), Map::LpmTrie(map) => map.obj.map_type(), Map::Stack(map) => map.obj.map_type(), Map::StackTraceMap(map) => map.obj.map_type(), Map::Queue(map) => map.obj.map_type(), } } } macro_rules! impl_try_from_map { ($($tx:ident from Map::$ty:ident),+ $(,)?) => { $( impl<'a> TryFrom<&'a Map> for $tx<&'a MapData> { type Error = MapError; fn try_from(map: &'a Map) -> Result<$tx<&'a MapData>, MapError> { match map { Map::$ty(m) => { $tx::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl<'a,> TryFrom<&'a mut Map> for $tx<&'a mut MapData> { type Error = MapError; fn try_from(map: &'a mut Map) -> Result<$tx<&'a mut MapData>, MapError> { match map { Map::$ty(m) => { $tx::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl TryFrom<Map> for $tx<MapData> { type Error = MapError; fn try_from(map: Map) -> Result<$tx<MapData>, MapError> { match map { Map::$ty(m) => { $tx::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } )+ } } impl_try_from_map!( ProgramArray from Map::ProgramArray, SockMap from Map::SockMap, PerfEventArray from Map::PerfEventArray, StackTraceMap from Map::StackTraceMap, ); #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] impl_try_from_map!( AsyncPerfEventArray from Map::PerfEventArray, ); macro_rules! impl_try_from_map_generic_key_or_value { ($($ty:ident),+ $(,)?) => { $( impl<'a, V:Pod> TryFrom<&'a Map> for $ty<&'a MapData, V> { type Error = MapError; fn try_from(map: &'a Map) -> Result<$ty<&'a MapData , V>, MapError> { match map { Map::$ty(m) => { $ty::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl<'a,V: Pod> TryFrom<&'a mut Map> for $ty<&'a mut MapData, V> { type Error = MapError; fn try_from(map: &'a mut Map) -> Result<$ty<&'a mut MapData, V>, MapError> { match map { Map::$ty(m) => { $ty::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl<V: Pod> TryFrom<Map> for $ty<MapData, V> { type Error = MapError; fn try_from(map: Map) -> Result<$ty<MapData, V>, MapError> { match map { Map::$ty(m) => { $ty::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } )+ } } impl_try_from_map_generic_key_or_value!(Array, PerCpuArray, SockHash, BloomFilter, Queue, Stack,); macro_rules! impl_try_from_map_generic_key_and_value { ($($ty:ident),+ $(,)?) => { $( impl<'a, V: Pod, K: Pod> TryFrom<&'a Map> for $ty<&'a MapData, V, K> { type Error = MapError; fn try_from(map: &'a Map) -> Result<$ty<&'a MapData,V,K>, MapError> { match map { Map::$ty(m) => { $ty::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl<'a,V: Pod,K: Pod> TryFrom<&'a mut Map> for $ty<&'a mut MapData, V, K> { type Error = MapError; fn try_from(map: &'a mut Map) -> Result<$ty<&'a mut MapData, V, K>, MapError> { match map { Map::$ty(m) => { $ty::new(m) }, _ => Err(MapError::InvalidMapType{ map_type: map.map_type()}), } } } impl<V: Pod, K: Pod> TryFrom<Map> for $ty<MapData, V, K> { type Error = MapError; fn try_from(map: Map) -> Result<$ty<MapData, V, K>, MapError> { match map { Map::$ty(m) => $ty::new(m), _ => Err(MapError::InvalidMapType { map_type: map.map_type() }), } } } )+ } } impl_try_from_map_generic_key_and_value!(HashMap, PerCpuHashMap, LpmTrie); pub(crate) fn check_bounds(map: &MapData, index: u32) -> Result<(), MapError> { let max_entries = map.obj.max_entries(); if index >= max_entries { Err(MapError::OutOfBounds { index, max_entries }) } else { Ok(()) } } pub(crate) fn check_kv_size<K, V>(map: &MapData) -> Result<(), MapError> { let size = mem::size_of::<K>(); let expected = map.obj.key_size() as usize; if size != expected { return Err(MapError::InvalidKeySize { size, expected }); } let size = mem::size_of::<V>(); let expected = map.obj.value_size() as usize; if size != expected { return Err(MapError::InvalidValueSize { size, expected }); }; Ok(()) } pub(crate) fn check_v_size<V>(map: &MapData) -> Result<(), MapError> { let size = mem::size_of::<V>(); let expected = map.obj.value_size() as usize; if size != expected { return Err(MapError::InvalidValueSize { size, expected }); }; Ok(()) } /// A generic handle to a BPF map. /// /// You should never need to use this unless you're implementing a new map type. #[derive(Debug)] pub struct MapData { pub(crate) obj: obj::Map, pub(crate) fd: Option<RawFd>, pub(crate) btf_fd: Option<RawFd>, /// Indicates if this map has been pinned to bpffs pub pinned: bool, } impl AsRef<MapData> for MapData { fn as_ref(&self) -> &MapData { self } } impl AsMut<MapData> for MapData { fn as_mut(&mut self) -> &mut MapData { self } } impl MapData { /// Creates a new map with the provided `name` pub fn create(&mut self, name: &str) -> Result<RawFd, MapError> { if self.fd.is_some() { return Err(MapError::AlreadyCreated { name: name.into() }); } let c_name = CString::new(name).map_err(|_| MapError::InvalidName { name: name.into() })?; let fd = bpf_create_map(&c_name, &self.obj, self.btf_fd).map_err(|(code, io_error)| { let k_ver = kernel_version().unwrap(); if k_ver < (5, 11, 0) { maybe_warn_rlimit(); } MapError::CreateError { name: name.into(), code, io_error, } })? as RawFd; self.fd = Some(fd); Ok(fd) } pub(crate) fn open_pinned<P: AsRef<Path>>( &mut self, name: &str, path: P, ) -> Result<RawFd, MapError> { if self.fd.is_some() { return Err(MapError::AlreadyCreated { name: name.into() }); } let map_path = path.as_ref().join(name); let path_string = CString::new(map_path.to_str().unwrap()).unwrap(); let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError { call: "BPF_OBJ_GET".to_string(), io_error, })? as RawFd; self.fd = Some(fd); Ok(fd) } /// Loads a map from a pinned path in bpffs. pub fn from_pin<P: AsRef<Path>>(path: P) -> Result<MapData, MapError> { let path_string = CString::new(path.as_ref().to_string_lossy().into_owned()).map_err(|e| { MapError::PinError { name: None, error: PinError::InvalidPinPath { error: e.to_string(), }, } })?; let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError { call: "BPF_OBJ_GET".to_owned(), io_error, })? as RawFd; let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError { call: "BPF_MAP_GET_INFO_BY_FD".to_owned(), io_error, })?; Ok(MapData { obj: parse_map_info(info, PinningType::ByName), fd: Some(fd), btf_fd: None, pinned: true, }) } /// Loads a map from a [`RawFd`]. /// /// If loading from a BPF Filesystem (bpffs) you should use [`Map::from_pin`](crate::maps::MapData::from_pin). /// This API is intended for cases where you have received a valid BPF FD from some other means. /// For example, you received an FD over Unix Domain Socket. pub fn from_fd(fd: RawFd) -> Result<MapData, MapError> { let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError { call: "BPF_OBJ_GET".to_owned(), io_error, })?; Ok(MapData { obj: parse_map_info(info, PinningType::None), fd: Some(fd), btf_fd: None, pinned: false, }) } pub(crate) fn fd_or_err(&self) -> Result<RawFd, MapError> { self.fd.ok_or(MapError::NotCreated) } pub(crate) fn pin<P: AsRef<Path>>(&mut self, name: &str, path: P) -> Result<(), PinError> { if self.pinned { return Err(PinError::AlreadyPinned { name: name.into() }); } let map_path = path.as_ref().join(name); let fd = self.fd.ok_or(PinError::NoFd { name: name.to_string(), })?; let path_string = CString::new(map_path.to_string_lossy().into_owned()).map_err(|e| { PinError::InvalidPinPath { error: e.to_string(), } })?; bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { name: "BPF_OBJ_PIN".to_string(), io_error, })?; self.pinned = true; Ok(()) } /// Returns the file descriptor of the map. /// /// Can be converted to [`RawFd`] using [`AsRawFd`]. pub fn fd(&self) -> Option<MapFd> { self.fd.map(MapFd) } } impl Drop for MapData { fn drop(&mut self) { // TODO: Replace this with an OwnedFd once that is stabilized. if let Some(fd) = self.fd.take() { unsafe { libc::close(fd) }; } } } impl Clone for MapData { fn clone(&self) -> MapData { MapData { obj: self.obj.clone(), fd: { if let Some(fd) = self.fd { unsafe { Some(libc::dup(fd)) }; } None }, btf_fd: self.btf_fd, pinned: self.pinned, } } } /// An iterable map pub trait IterableMap<K: Pod, V> { /// Get a generic map handle fn map(&self) -> &MapData; /// Get the value for the provided `key` fn get(&self, key: &K) -> Result<V, MapError>; } /// Iterator returned by `map.keys()`. pub struct MapKeys<'coll, K: Pod> { map: &'coll MapData, err: bool, key: Option<K>, } impl<'coll, K: Pod> MapKeys<'coll, K> { fn new(map: &'coll MapData) -> MapKeys<'coll, K> { MapKeys { map, err: false, key: None, } } } impl<K: Pod> Iterator for MapKeys<'_, K> { type Item = Result<K, MapError>; fn next(&mut self) -> Option<Result<K, MapError>> { if self.err { return None; } let fd = match self.map.fd_or_err() { Ok(fd) => fd, Err(e) => { self.err = true; return Some(Err(e)); } }; match bpf_map_get_next_key(fd, self.key.as_ref()) { Ok(Some(key)) => { self.key = Some(key); Some(Ok(key)) } Ok(None) => { self.key = None; None } Err((_, io_error)) => { self.err = true; Some(Err(MapError::SyscallError { call: "bpf_map_get_next_key".to_owned(), io_error, })) } } } } /// Iterator returned by `map.iter()`. pub struct MapIter<'coll, K: Pod, V, I: IterableMap<K, V>> { keys: MapKeys<'coll, K>, map: &'coll I, _v: PhantomData<V>, } impl<'coll, K: Pod, V, I: IterableMap<K, V>> MapIter<'coll, K, V, I> { fn new(map: &'coll I) -> MapIter<'coll, K, V, I> { MapIter { keys: MapKeys::new(map.map()), map, _v: PhantomData, } } } impl<K: Pod, V, I: IterableMap<K, V>> Iterator for MapIter<'_, K, V, I> { type Item = Result<(K, V), MapError>; fn next(&mut self) -> Option<Self::Item> { loop { match self.keys.next() { Some(Ok(key)) => match self.map.get(&key) { Ok(value) => return Some(Ok((key, value))), Err(MapError::KeyNotFound) => continue, Err(e) => return Some(Err(e)), }, Some(Err(e)) => return Some(Err(e)), None => return None, } } } } impl TryFrom<u32> for bpf_map_type { type Error = MapError; fn try_from(map_type: u32) -> Result<Self, Self::Error> { use bpf_map_type::*; Ok(match map_type { x if x == BPF_MAP_TYPE_UNSPEC as u32 => BPF_MAP_TYPE_UNSPEC, x if x == BPF_MAP_TYPE_HASH as u32 => BPF_MAP_TYPE_HASH, x if x == BPF_MAP_TYPE_ARRAY as u32 => BPF_MAP_TYPE_ARRAY, x if x == BPF_MAP_TYPE_PROG_ARRAY as u32 => BPF_MAP_TYPE_PROG_ARRAY, x if x == BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32 => BPF_MAP_TYPE_PERF_EVENT_ARRAY, x if x == BPF_MAP_TYPE_PERCPU_HASH as u32 => BPF_MAP_TYPE_PERCPU_HASH, x if x == BPF_MAP_TYPE_PERCPU_ARRAY as u32 => BPF_MAP_TYPE_PERCPU_ARRAY, x if x == BPF_MAP_TYPE_STACK_TRACE as u32 => BPF_MAP_TYPE_STACK_TRACE, x if x == BPF_MAP_TYPE_CGROUP_ARRAY as u32 => BPF_MAP_TYPE_CGROUP_ARRAY, x if x == BPF_MAP_TYPE_LRU_HASH as u32 => BPF_MAP_TYPE_LRU_HASH, x if x == BPF_MAP_TYPE_LRU_PERCPU_HASH as u32 => BPF_MAP_TYPE_LRU_PERCPU_HASH, x if x == BPF_MAP_TYPE_LPM_TRIE as u32 => BPF_MAP_TYPE_LPM_TRIE, x if x == BPF_MAP_TYPE_BLOOM_FILTER as u32 => BPF_MAP_TYPE_BLOOM_FILTER, x if x == BPF_MAP_TYPE_ARRAY_OF_MAPS as u32 => BPF_MAP_TYPE_ARRAY_OF_MAPS, x if x == BPF_MAP_TYPE_HASH_OF_MAPS as u32 => BPF_MAP_TYPE_HASH_OF_MAPS, x if x == BPF_MAP_TYPE_DEVMAP as u32 => BPF_MAP_TYPE_DEVMAP, x if x == BPF_MAP_TYPE_SOCKMAP as u32 => BPF_MAP_TYPE_SOCKMAP, x if x == BPF_MAP_TYPE_CPUMAP as u32 => BPF_MAP_TYPE_CPUMAP, x if x == BPF_MAP_TYPE_XSKMAP as u32 => BPF_MAP_TYPE_XSKMAP, x if x == BPF_MAP_TYPE_SOCKHASH as u32 => BPF_MAP_TYPE_SOCKHASH, x if x == BPF_MAP_TYPE_CGROUP_STORAGE as u32 => BPF_MAP_TYPE_CGROUP_STORAGE, x if x == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY as u32 => BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, x if x == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE as u32 => { BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE } x if x == BPF_MAP_TYPE_QUEUE as u32 => BPF_MAP_TYPE_QUEUE, x if x == BPF_MAP_TYPE_STACK as u32 => BPF_MAP_TYPE_STACK, x if x == BPF_MAP_TYPE_SK_STORAGE as u32 => BPF_MAP_TYPE_SK_STORAGE, x if x == BPF_MAP_TYPE_DEVMAP_HASH as u32 => BPF_MAP_TYPE_DEVMAP_HASH, x if x == BPF_MAP_TYPE_STRUCT_OPS as u32 => BPF_MAP_TYPE_STRUCT_OPS, x if x == BPF_MAP_TYPE_RINGBUF as u32 => BPF_MAP_TYPE_RINGBUF, x if x == BPF_MAP_TYPE_INODE_STORAGE as u32 => BPF_MAP_TYPE_INODE_STORAGE, x if x == BPF_MAP_TYPE_TASK_STORAGE as u32 => BPF_MAP_TYPE_TASK_STORAGE, _ => return Err(MapError::InvalidMapType { map_type }), }) } } pub(crate) struct PerCpuKernelMem { bytes: Vec<u8>, } impl PerCpuKernelMem { pub(crate) fn as_mut_ptr(&mut self) -> *mut u8 { self.bytes.as_mut_ptr() } } /// A slice of per-CPU values. /// /// Used by maps that implement per-CPU storage like [`PerCpuHashMap`]. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let bpf = aya::Bpf::load(&[])?; /// use aya::maps::PerCpuValues; /// use aya::util::nr_cpus; /// /// let values = PerCpuValues::try_from(vec![42u32; nr_cpus()?])?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] pub struct PerCpuValues<T: Pod> { values: Box<[T]>, } impl<T: Pod> TryFrom<Vec<T>> for PerCpuValues<T> { type Error = io::Error; fn try_from(values: Vec<T>) -> Result<Self, Self::Error> { let nr_cpus = nr_cpus()?; if values.len() != nr_cpus { return Err(io::Error::new( io::ErrorKind::InvalidInput, format!("not enough values ({}), nr_cpus: {}", values.len(), nr_cpus), )); } Ok(PerCpuValues { values: values.into_boxed_slice(), }) } } impl<T: Pod> PerCpuValues<T> { pub(crate) fn alloc_kernel_mem() -> Result<PerCpuKernelMem, io::Error> { let value_size = (mem::size_of::<T>() + 7) & !7; Ok(PerCpuKernelMem { bytes: vec![0u8; nr_cpus()? * value_size], }) } pub(crate) unsafe fn from_kernel_mem(mem: PerCpuKernelMem) -> PerCpuValues<T> { let mem_ptr = mem.bytes.as_ptr() as usize; let value_size = (mem::size_of::<T>() + 7) & !7; let mut values = Vec::new(); let mut offset = 0; while offset < mem.bytes.len() { values.push(ptr::read_unaligned((mem_ptr + offset) as *const _)); offset += value_size; } PerCpuValues { values: values.into_boxed_slice(), } } pub(crate) fn build_kernel_mem(&self) -> Result<PerCpuKernelMem, io::Error> { let mut mem = PerCpuValues::<T>::alloc_kernel_mem()?; let mem_ptr = mem.as_mut_ptr() as usize; let value_size = (mem::size_of::<T>() + 7) & !7; for i in 0..self.values.len() { unsafe { ptr::write_unaligned((mem_ptr + i * value_size) as *mut _, self.values[i]) }; } Ok(mem) } } impl<T: Pod> Deref for PerCpuValues<T> { type Target = Box<[T]>; fn deref(&self) -> &Self::Target { &self.values } } #[cfg(test)] mod tests { use libc::EFAULT; use crate::{ bpf_map_def, generated::{bpf_cmd, bpf_map_type::BPF_MAP_TYPE_HASH}, maps::MapData, obj::MapKind, sys::{override_syscall, Syscall}, }; use super::*; fn new_obj_map() -> obj::Map { obj::Map::Legacy(obj::LegacyMap { def: bpf_map_def { map_type: BPF_MAP_TYPE_HASH as u32, key_size: 4, value_size: 4, max_entries: 1024, ..Default::default() }, section_index: 0, symbol_index: 0, data: Vec::new(), kind: MapKind::Other, }) } fn new_map() -> MapData { MapData { obj: new_obj_map(), fd: None, pinned: false, btf_fd: None, } } #[test] fn test_create() { override_syscall(|call| match call { Syscall::Bpf { cmd: bpf_cmd::BPF_MAP_CREATE, .. } => Ok(42), _ => Err((-1, io::Error::from_raw_os_error(EFAULT))), }); let mut map = new_map(); assert!(matches!(map.create("foo"), Ok(42))); assert_eq!(map.fd, Some(42)); assert!(matches!( map.create("foo"), Err(MapError::AlreadyCreated { .. }) )); } #[test] fn test_create_failed() { override_syscall(|_| Err((-42, io::Error::from_raw_os_error(EFAULT)))); let mut map = new_map(); let ret = map.create("foo"); assert!(matches!(ret, Err(MapError::CreateError { .. }))); if let Err(MapError::CreateError { name, code, io_error, }) = ret { assert_eq!(name, "foo"); assert_eq!(code, -42); assert_eq!(io_error.raw_os_error(), Some(EFAULT)); } assert_eq!(map.fd, None); } } <file_sep>/aya/src/maps/array/program_array.rs //! An array of eBPF program file descriptors used as a jump table. use std::{ convert::{AsMut, AsRef}, os::unix::prelude::{AsRawFd, RawFd}, }; use crate::{ maps::{check_bounds, check_kv_size, MapData, MapError, MapKeys}, programs::ProgramFd, sys::{bpf_map_delete_elem, bpf_map_update_elem}, }; /// An array of eBPF program file descriptors used as a jump table. /// /// eBPF programs can jump to other programs calling `bpf_tail_call(ctx, /// prog_array, index)`. You can use [`ProgramArray`] to configure which /// programs correspond to which jump indexes. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.2. /// /// # Examples /// ```no_run /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::maps::ProgramArray; /// use aya::programs::CgroupSkb; /// /// let mut prog_array = ProgramArray::try_from(bpf.take_map("JUMP_TABLE").unwrap())?; /// let prog_0: &CgroupSkb = bpf.program("example_prog_0").unwrap().try_into()?; /// let prog_0_fd = prog_0.fd().unwrap(); /// let prog_1: &CgroupSkb = bpf.program("example_prog_1").unwrap().try_into()?; /// let prog_1_fd = prog_1.fd().unwrap(); /// let prog_2: &CgroupSkb = bpf.program("example_prog_2").unwrap().try_into()?; /// let prog_2_fd = prog_2.fd().unwrap(); /// let flags = 0; /// /// // bpf_tail_call(ctx, JUMP_TABLE, 0) will jump to prog_0 /// prog_array.set(0, prog_0_fd, flags); /// /// // bpf_tail_call(ctx, JUMP_TABLE, 1) will jump to prog_1 /// prog_array.set(1, prog_1_fd, flags); /// /// // bpf_tail_call(ctx, JUMP_TABLE, 2) will jump to prog_2 /// prog_array.set(2, prog_2_fd, flags); /// # Ok::<(), aya::BpfError>(()) /// ``` #[doc(alias = "BPF_MAP_TYPE_PROG_ARRAY")] pub struct ProgramArray<T> { inner: T, } impl<T: AsRef<MapData>> ProgramArray<T> { pub(crate) fn new(map: T) -> Result<ProgramArray<T>, MapError> { let data = map.as_ref(); check_kv_size::<u32, RawFd>(data)?; let _fd = data.fd_or_err()?; Ok(ProgramArray { inner: map }) } /// An iterator over the indices of the array that point to a program. The iterator item type /// is `Result<u32, MapError>`. pub fn indices(&self) -> MapKeys<'_, u32> { MapKeys::new(self.inner.as_ref()) } } impl<T: AsMut<MapData>> ProgramArray<T> { /// Sets the target program file descriptor for the given index in the jump table. /// /// When an eBPF program calls `bpf_tail_call(ctx, prog_array, index)`, control /// flow will jump to `program`. pub fn set(&mut self, index: u32, program: ProgramFd, flags: u64) -> Result<(), MapError> { let data = self.inner.as_mut(); check_bounds(data, index)?; let fd = data.fd_or_err()?; let prog_fd = program.as_raw_fd(); bpf_map_update_elem(fd, Some(&index), &prog_fd, flags).map_err(|(_, io_error)| { MapError::SyscallError { call: "bpf_map_update_elem".to_owned(), io_error, } })?; Ok(()) } /// Clears the value at index in the jump table. /// /// Calling `bpf_tail_call(ctx, prog_array, index)` on an index that has been cleared returns an /// error. pub fn clear_index(&mut self, index: &u32) -> Result<(), MapError> { let data = self.inner.as_mut(); check_bounds(data, *index)?; let fd = self.inner.as_mut().fd_or_err()?; bpf_map_delete_elem(fd, index) .map(|_| ()) .map_err(|(_, io_error)| MapError::SyscallError { call: "bpf_map_delete_elem".to_owned(), io_error, }) } } <file_sep>/test/integration-test/src/tests/elf.rs use super::{integration_test, IntegrationTest}; use aya::include_bytes_aligned; use object::{Object, ObjectSymbol}; #[integration_test] fn test_maps() { let bytes = include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/map_test"); let obj_file = object::File::parse(bytes).unwrap(); if obj_file.section_by_name("maps").is_none() { panic!("No 'maps' ELF section"); } let mut found = false; for sym in obj_file.symbols() { if let Ok(name) = sym.name() { if name == "BAR" { found = true; break; } } } if !found { panic!("No symbol 'BAR' in ELF file") } } <file_sep>/aya/src/programs/fentry.rs //! Fentry programs. use crate::{ generated::{bpf_attach_type::BPF_TRACE_FENTRY, bpf_prog_type::BPF_PROG_TYPE_TRACING}, obj::btf::{Btf, BtfKind}, programs::{ define_link_wrapper, load_program, utils::attach_raw_tracepoint, FdLink, FdLinkId, ProgramData, ProgramError, }, }; /// A program that can be attached to the entry point of (almost) any kernel /// function. /// /// [`FEntry`] programs are similar to [kprobes](crate::programs::KProbe), but /// the difference is that fentry has practically zero overhead to call before /// kernel function. Fentry programs can be also attached to other eBPF /// programs. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.5. /// /// # Examples /// /// ```no_run /// # #[derive(thiserror::Error, Debug)] /// # enum Error { /// # #[error(transparent)] /// # BtfError(#[from] aya::BtfError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError), /// # } /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::FEntry, BtfError, Btf}; /// /// let btf = Btf::from_sys_fs()?; /// let program: &mut FEntry = bpf.program_mut("filename_lookup").unwrap().try_into()?; /// program.load("filename_lookup", &btf)?; /// program.attach()?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_TRACE_FENTRY")] #[doc(alias = "BPF_PROG_TYPE_TRACING")] pub struct FEntry { pub(crate) data: ProgramData<FEntryLink>, } impl FEntry { /// Loads the program inside the kernel. /// /// Loads the program so it's executed when the kernel function `fn_name` /// is entered. The `btf` argument must contain the BTF info for the /// running kernel. pub fn load(&mut self, fn_name: &str, btf: &Btf) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(BPF_TRACE_FENTRY); self.data.attach_btf_id = Some(btf.id_by_type_name_kind(fn_name, BtfKind::Func)?); load_program(BPF_PROG_TYPE_TRACING, &mut self.data) } /// Attaches the program. /// /// The returned value can be used to detach, see [FEntry::detach]. pub fn attach(&mut self) -> Result<FEntryLinkId, ProgramError> { attach_raw_tracepoint(&mut self.data, None) } /// Detaches the program. /// /// See [FEntry::attach]. pub fn detach(&mut self, link_id: FEntryLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: FEntryLinkId) -> Result<FEntryLink, ProgramError> { self.data.take_link(link_id) } } define_link_wrapper!( /// The link used by [FEntry] programs. FEntryLink, /// The type returned by [FEntry::attach]. Can be passed to [FEntry::detach]. FEntryLinkId, FdLink, FdLinkId ); <file_sep>/bpf/aya-bpf/src/programs/xdp.rs use core::ffi::c_void; use crate::{bindings::xdp_md, BpfContext}; pub struct XdpContext { pub ctx: *mut xdp_md, } impl XdpContext { pub fn new(ctx: *mut xdp_md) -> XdpContext { XdpContext { ctx } } #[inline] pub fn data(&self) -> usize { unsafe { (*self.ctx).data as usize } } #[inline] pub fn data_end(&self) -> usize { unsafe { (*self.ctx).data_end as usize } } /// Return the raw address of the XdpContext metadata. #[inline(always)] pub fn metadata(&self) -> usize { unsafe { (*self.ctx).data_meta as usize } } /// Return the raw address immediately after the XdpContext's metadata. #[inline(always)] pub fn metadata_end(&self) -> usize { self.data() } } impl BpfContext for XdpContext { fn as_ptr(&self) -> *mut c_void { self.ctx as *mut _ } } <file_sep>/aya/Cargo.toml [package] name = "aya" version = "0.11.0" description = "An eBPF library with a focus on developer experience and operability." keywords = ["ebpf", "bpf", "linux", "kernel"] license = "MIT OR Apache-2.0" authors = ["The Aya Contributors"] repository = "https://github.com/aya-rs/aya" readme = "README.md" documentation = "https://docs.rs/aya" edition = "2021" [dependencies] libc = { version = "0.2.105" } thiserror = "1" object = { version = "0.30", default-features = false, features = ["std", "read_core", "elf"] } bitflags = "1.2.1" bytes = "1" lazy_static = "1" parking_lot = { version = "0.12.0", features = ["send_guard"] } tokio = { version = "1.2.0", features = ["macros", "rt", "rt-multi-thread", "net"], optional = true } async-io = { version = "1.3", optional = true } log = "0.4" [dev-dependencies] matches = "0.1.8" futures = { version = "0.3.12", default-features = false, features = ["std"] } [features] default = [] async = [] async_tokio = ["tokio", "async"] async_std = ["async-io", "async"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs","-D", "warnings"] <file_sep>/aya/src/obj/btf/mod.rs #[allow(clippy::module_inception)] mod btf; mod info; mod relocation; mod types; pub use btf::*; pub(crate) use info::*; pub use relocation::RelocationError; pub(crate) use types::*; <file_sep>/test/integration-ebpf/src/map_test.rs #![no_std] #![no_main] use aya_bpf::{ bindings::xdp_action, macros::{map, xdp}, maps::Array, programs::XdpContext, }; #[map] static FOO: Array<u32> = Array::<u32>::with_max_entries(10, 0); #[map(name = "BAR")] static BAZ: Array<u32> = Array::<u32>::with_max_entries(10, 0); #[xdp] pub fn pass(ctx: XdpContext) -> u32 { match unsafe { try_pass(ctx) } { Ok(ret) => ret, Err(_) => xdp_action::XDP_ABORTED, } } unsafe fn try_pass(_ctx: XdpContext) -> Result<u32, u32> { Ok(xdp_action::XDP_PASS) } #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachable_unchecked() } } <file_sep>/aya/src/programs/tc.rs //! Network traffic control programs. use thiserror::Error; use std::{ ffi::{CStr, CString}, io, }; use crate::{ generated::{ bpf_prog_type::BPF_PROG_TYPE_SCHED_CLS, TC_H_CLSACT, TC_H_MIN_EGRESS, TC_H_MIN_INGRESS, }, programs::{define_link_wrapper, load_program, Link, ProgramData, ProgramError}, sys::{ netlink_find_filter_with_name, netlink_qdisc_add_clsact, netlink_qdisc_attach, netlink_qdisc_detach, }, util::{ifindex_from_ifname, tc_handler_make}, }; /// Traffic control attach type. #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub enum TcAttachType { /// Attach to ingress. Ingress, /// Attach to egress. Egress, /// Attach to custom parent. Custom(u32), } /// A network traffic control classifier. /// /// [`SchedClassifier`] programs can be used to inspect, filter or redirect /// network packets in both ingress and egress. They are executed as part of the /// linux network traffic control system. See /// [https://man7.org/linux/man-pages/man8/tc-bpf.8.html](https://man7.org/linux/man-pages/man8/tc-bpf.8.html). /// /// # Examples /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.1. /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::programs::{tc, SchedClassifier, TcAttachType}; /// /// // the clsact qdisc needs to be added before SchedClassifier programs can be /// // attached /// tc::qdisc_add_clsact("eth0")?; /// /// let prog: &mut SchedClassifier = bpf.program_mut("redirect_ingress").unwrap().try_into()?; /// prog.load()?; /// prog.attach("eth0", TcAttachType::Ingress)?; /// /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SCHED_CLS")] pub struct SchedClassifier { pub(crate) data: ProgramData<SchedClassifierLink>, pub(crate) name: Box<CStr>, } /// Errors from TC programs #[derive(Debug, Error)] pub enum TcError { /// netlink error while attaching ebpf program #[error("netlink error while attaching ebpf program to tc")] NetlinkError { /// the [`io::Error`] from the netlink call #[source] io_error: io::Error, }, /// the clsact qdisc is already attached #[error("the clsact qdisc is already attached")] AlreadyAttached, } impl TcAttachType { pub(crate) fn parent(&self) -> u32 { match self { TcAttachType::Custom(parent) => *parent, TcAttachType::Ingress => tc_handler_make(TC_H_CLSACT, TC_H_MIN_INGRESS), TcAttachType::Egress => tc_handler_make(TC_H_CLSACT, TC_H_MIN_EGRESS), } } } /// Options for SchedClassifier attach #[derive(Default)] pub struct TcOptions { /// Priority assigned to tc program with lower number = higher priority. /// If set to default (0), the system chooses the next highest priority or 49152 if no filters exist yet pub priority: u16, /// Handle used to uniquely identify a program at a given priority level. /// If set to default (0), the system chooses a handle. pub handle: u32, } impl SchedClassifier { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SCHED_CLS, &mut self.data) } /// Attaches the program to the given `interface` using the default options. /// /// The returned value can be used to detach, see [SchedClassifier::detach]. /// /// # Errors /// /// [`TcError::NetlinkError`] is returned if attaching fails. A common cause /// of failure is not having added the `clsact` qdisc to the given /// interface, see [`qdisc_add_clsact`] /// pub fn attach( &mut self, interface: &str, attach_type: TcAttachType, ) -> Result<SchedClassifierLinkId, ProgramError> { self.attach_with_options(interface, attach_type, TcOptions::default()) } /// Attaches the program to the given `interface` with options defined in [`TcOptions`]. /// /// The returned value can be used to detach, see [SchedClassifier::detach]. /// /// # Errors /// /// [`TcError::NetlinkError`] is returned if attaching fails. A common cause /// of failure is not having added the `clsact` qdisc to the given /// interface, see [`qdisc_add_clsact`] /// pub fn attach_with_options( &mut self, interface: &str, attach_type: TcAttachType, options: TcOptions, ) -> Result<SchedClassifierLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let if_index = ifindex_from_ifname(interface) .map_err(|io_error| TcError::NetlinkError { io_error })?; let (priority, handle) = unsafe { netlink_qdisc_attach( if_index as i32, &attach_type, prog_fd, &self.name, options.priority, options.handle, ) } .map_err(|io_error| TcError::NetlinkError { io_error })?; self.data.links.insert(SchedClassifierLink::new(TcLink { if_index: if_index as i32, attach_type, priority, handle, })) } /// Detaches the program. /// /// See [SchedClassifier::attach]. pub fn detach(&mut self, link_id: SchedClassifierLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: SchedClassifierLinkId, ) -> Result<SchedClassifierLink, ProgramError> { self.data.take_link(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] pub(crate) struct TcLinkId(i32, TcAttachType, u16, u32); #[derive(Debug)] struct TcLink { if_index: i32, attach_type: TcAttachType, priority: u16, handle: u32, } impl Link for TcLink { type Id = TcLinkId; fn id(&self) -> Self::Id { TcLinkId(self.if_index, self.attach_type, self.priority, self.handle) } fn detach(self) -> Result<(), ProgramError> { unsafe { netlink_qdisc_detach(self.if_index, &self.attach_type, self.priority, self.handle) } .map_err(|io_error| TcError::NetlinkError { io_error })?; Ok(()) } } define_link_wrapper!( /// The link used by [SchedClassifier] programs. SchedClassifierLink, /// The type returned by [SchedClassifier::attach]. Can be passed to [SchedClassifier::detach]. SchedClassifierLinkId, TcLink, TcLinkId ); /// Add the `clasct` qdisc to the given interface. /// /// The `clsact` qdisc must be added to an interface before [`SchedClassifier`] /// programs can be attached. pub fn qdisc_add_clsact(if_name: &str) -> Result<(), io::Error> { let if_index = ifindex_from_ifname(if_name)?; unsafe { netlink_qdisc_add_clsact(if_index as i32) } } /// Detaches the programs with the given name. /// /// # Errors /// /// Returns [`io::ErrorKind::NotFound`] to indicate that no programs with the /// given name were found, so nothing was detached. Other error kinds indicate /// an actual failure while detaching a program. pub fn qdisc_detach_program( if_name: &str, attach_type: TcAttachType, name: &str, ) -> Result<(), io::Error> { let cstr = CString::new(name)?; qdisc_detach_program_fast(if_name, attach_type, &cstr) } /// Detaches the programs with the given name as a C string. /// Unlike qdisc_detach_program, this function does not allocate an additional /// CString to. /// /// # Errors /// /// Returns [`io::ErrorKind::NotFound`] to indicate that no programs with the /// given name were found, so nothing was detached. Other error kinds indicate /// an actual failure while detaching a program. fn qdisc_detach_program_fast( if_name: &str, attach_type: TcAttachType, name: &CStr, ) -> Result<(), io::Error> { let if_index = ifindex_from_ifname(if_name)? as i32; let filter_info = unsafe { netlink_find_filter_with_name(if_index, attach_type, name)? }; if filter_info.is_empty() { return Err(io::Error::new( io::ErrorKind::NotFound, name.to_string_lossy(), )); } for (prio, handle) in filter_info { unsafe { netlink_qdisc_detach(if_index, &attach_type, prio, handle)? }; } Ok(()) } <file_sep>/test/run.sh #!/bin/sh set -e # Temporary directory for tests to use. AYA_TMPDIR="$(pwd)/.tmp" # Directory for VM images AYA_IMGDIR=${AYA_TMPDIR} # Test Architecture if [ -z "${AYA_TEST_ARCH}" ]; then AYA_TEST_ARCH="$(uname -m)" fi # Test Image if [ -z "${AYA_TEST_IMAGE}" ]; then AYA_TEST_IMAGE="fedora36" fi case "${AYA_TEST_IMAGE}" in fedora*) AYA_SSH_USER="fedora";; centos*) AYA_SSH_USER="centos";; esac download_images() { mkdir -p "${AYA_IMGDIR}" case $1 in fedora36) if [ ! -f "${AYA_IMGDIR}/fedora36.${AYA_TEST_ARCH}.qcow2" ]; then IMAGE="Fedora-Cloud-Base-36-1.5.${AYA_TEST_ARCH}.qcow2" IMAGE_URL="https://download.fedoraproject.org/pub/fedora/linux/releases/36/Cloud/${AYA_TEST_ARCH}/images" echo "Downloading: ${IMAGE}, this may take a while..." curl -o "${AYA_IMGDIR}/fedora36.${AYA_TEST_ARCH}.qcow2" -sSL "${IMAGE_URL}/${IMAGE}" fi ;; centos8) if [ ! -f "${AYA_IMGDIR}/centos8.${AYA_TEST_ARCH}.qcow2" ]; then IMAGE="CentOS-8-GenericCloud-8.4.2105-20210603.0.${AYA_TEST_ARCH}.qcow2" IMAGE_URL="https://cloud.centos.org/centos/8/${AYA_TEST_ARCH}/images" echo "Downloading: ${IMAGE}, this may take a while..." curl -o "${AYA_IMGDIR}/centos8.${AYA_TEST_ARCH}.qcow2" -sSL "${IMAGE_URL}/${IMAGE}" fi ;; *) echo "$1 is not a recognized image name" return 1 ;; esac } start_vm() { download_images "${AYA_TEST_IMAGE}" # prepare config cat > "${AYA_TMPDIR}/metadata.yaml" <<EOF instance-id: iid-local01 local-hostname: test EOF if [ ! -f "${AYA_TMPDIR}/test_rsa" ]; then ssh-keygen -t rsa -b 4096 -f "${AYA_TMPDIR}/test_rsa" -N "" -C "" -q pub_key=$(cat "${AYA_TMPDIR}/test_rsa.pub") cat > "${AYA_TMPDIR}/user-data.yaml" <<EOF #cloud-config ssh_authorized_keys: - ${pub_key} EOF fi if [ ! -f "${AYA_TMPDIR}/ssh_config" ]; then cat > "${AYA_TMPDIR}/ssh_config" <<EOF StrictHostKeyChecking=no UserKnownHostsFile=/dev/null GlobalKnownHostsFile=/dev/null EOF fi cloud-localds "${AYA_TMPDIR}/seed.img" "${AYA_TMPDIR}/user-data.yaml" "${AYA_TMPDIR}/metadata.yaml" case "${AYA_TEST_ARCH}" in x86_64) QEMU=qemu-system-x86_64 machine="q35" cpu="qemu64" if [ "$(uname -m)" = "${AYA_TEST_ARCH}" ]; then if [ -c /dev/kvm ]; then machine="${machine},accel=kvm" cpu="host" elif [ "$(uname -s)" = "Darwin" ]; then machine="${machine},accel=hvf" cpu="host" fi fi ;; aarch64) QEMU=qemu-system-aarch64 machine="virt" cpu="cortex-a57" if [ "$(uname -m)" = "${AYA_TEST_ARCH}" ]; then if [ -c /dev/kvm ]; then machine="${machine},accel=kvm" cpu="host" elif [ "$(uname -s)" = "Darwin" ]; then machine="${machine},accel=hvf" cpu="host" fi fi ;; *) echo "${AYA_TEST_ARCH} is not supported" return 1 ;; esac qemu-img create -F qcow2 -f qcow2 -o backing_file="${AYA_IMGDIR}/${AYA_TEST_IMAGE}.${AYA_TEST_ARCH}.qcow2" "${AYA_TMPDIR}/vm.qcow2" || return 1 $QEMU \ -machine "${machine}" \ -cpu "${cpu}" \ -m 2G \ -display none \ -monitor none \ -daemonize \ -pidfile "${AYA_TMPDIR}/vm.pid" \ -device virtio-net-pci,netdev=net0 \ -netdev user,id=net0,hostfwd=tcp::2222-:22 \ -drive if=virtio,format=qcow2,file="${AYA_TMPDIR}/vm.qcow2" \ -drive if=virtio,format=raw,file="${AYA_TMPDIR}/seed.img" || return 1 trap cleanup_vm EXIT echo "Waiting for SSH on port 2222..." retry=0 max_retries=300 while ! ssh -q -F "${AYA_TMPDIR}/ssh_config" -o ConnectTimeout=1 -i "${AYA_TMPDIR}/test_rsa" ${AYA_SSH_USER}@localhost -p 2222 echo "Hello VM"; do retry=$((retry+1)) if [ ${retry} -gt ${max_retries} ]; then echo "Unable to connect to VM" return 1 fi sleep 1 done echo "VM launched, installing dependencies" exec_vm sudo dnf install -qy bpftool } scp_vm() { local=$1 remote=$(basename "$1") scp -q -F "${AYA_TMPDIR}/ssh_config" \ -i "${AYA_TMPDIR}/test_rsa" \ -P 2222 "${local}" \ "${AYA_SSH_USER}@localhost:${remote}" } exec_vm() { ssh -q -F "${AYA_TMPDIR}/ssh_config" \ -i "${AYA_TMPDIR}/test_rsa" \ -p 2222 \ ${AYA_SSH_USER}@localhost \ "$@" } stop_vm() { if [ -f "${AYA_TMPDIR}/vm.pid" ]; then echo "Stopping VM forcefully" kill -9 "$(cat "${AYA_TMPDIR}/vm.pid")" rm "${AYA_TMPDIR}/vm.pid" fi rm -f "${AYA_TMPDIR}/vm.qcow2" } cleanup_vm() { if [ "$?" != "0" ]; then stop_vm fi } if [ -z "$1" ]; then echo "path to libbpf required" exit 1 fi start_vm trap stop_vm EXIT cargo xtask build-integration-test --musl --libbpf-dir "$1" scp_vm ../target/x86_64-unknown-linux-musl/debug/integration-test exec_vm sudo ./integration-test <file_sep>/bpf/aya-bpf/src/maps/mod.rs #[repr(u32)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum PinningType { None = 0, ByName = 1, } pub mod array; pub mod bloom_filter; pub mod hash_map; pub mod lpm_trie; pub mod per_cpu_array; pub mod perf; pub mod program_array; pub mod queue; pub mod sock_hash; pub mod sock_map; pub mod stack; pub mod stack_trace; pub use array::Array; pub use bloom_filter::BloomFilter; pub use hash_map::{HashMap, LruHashMap, LruPerCpuHashMap, PerCpuHashMap}; pub use lpm_trie::LpmTrie; pub use per_cpu_array::PerCpuArray; pub use perf::{PerfEventArray, PerfEventByteArray}; pub use program_array::ProgramArray; pub use queue::Queue; pub use sock_hash::SockHash; pub use sock_map::SockMap; pub use stack::Stack; pub use stack_trace::StackTrace; <file_sep>/bpf/aya-bpf/src/programs/tc.rs use aya_bpf_cty::{c_long, c_void}; use crate::{bindings::__sk_buff, programs::sk_buff::SkBuff, BpfContext}; pub struct TcContext { pub skb: SkBuff, } impl TcContext { pub fn new(skb: *mut __sk_buff) -> TcContext { let skb = SkBuff { skb }; TcContext { skb } } #[allow(clippy::len_without_is_empty)] #[inline] pub fn len(&self) -> u32 { self.skb.len() } #[inline] pub fn data(&self) -> usize { self.skb.data() } #[inline] pub fn data_end(&self) -> usize { self.skb.data_end() } #[inline] pub fn set_mark(&mut self, mark: u32) { self.skb.set_mark(mark) } #[inline] pub fn cb(&self) -> &[u32] { self.skb.cb() } #[inline] pub fn cb_mut(&mut self) -> &mut [u32] { self.skb.cb_mut() } /// Returns the owner UID of the socket associated to the SKB context. #[inline] pub fn get_socket_uid(&self) -> u32 { self.skb.get_socket_uid() } #[inline] pub fn load<T>(&self, offset: usize) -> Result<T, c_long> { self.skb.load(offset) } /// Reads some bytes from the packet into the specified buffer, returning /// how many bytes were read. /// /// Starts reading at `offset` and reads at most `dst.len()` or /// `self.len() - offset` bytes, depending on which one is smaller. /// /// # Examples /// /// Read into a `PerCpuArray`. /// /// ```no_run /// use core::mem; /// /// use aya_bpf::{bindings::TC_ACT_PIPE, macros::map, maps::PerCpuArray, programs::TcContext}; /// # #[allow(non_camel_case_types)] /// # struct ethhdr {}; /// # #[allow(non_camel_case_types)] /// # struct iphdr {}; /// # #[allow(non_camel_case_types)] /// # struct tcphdr {}; /// /// const ETH_HDR_LEN: usize = mem::size_of::<ethhdr>(); /// const IP_HDR_LEN: usize = mem::size_of::<iphdr>(); /// const TCP_HDR_LEN: usize = mem::size_of::<tcphdr>(); /// /// #[repr(C)] /// pub struct Buf { /// pub buf: [u8; 1500], /// } /// /// #[map] /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0); /// /// fn try_classifier(ctx: TcContext) -> Result<i32, i32> { /// let buf = unsafe { /// let ptr = BUF.get_ptr_mut(0).ok_or(TC_ACT_PIPE)?; /// &mut *ptr /// }; /// let offset = ETH_HDR_LEN + IP_HDR_LEN + TCP_HDR_LEN; /// ctx.load_bytes(offset, &mut buf.buf).map_err(|_| TC_ACT_PIPE)?; /// /// // do something with `buf` /// /// Ok(TC_ACT_PIPE) /// } /// ``` #[inline(always)] pub fn load_bytes(&self, offset: usize, dst: &mut [u8]) -> Result<usize, c_long> { self.skb.load_bytes(offset, dst) } #[inline] pub fn store<T>(&mut self, offset: usize, v: &T, flags: u64) -> Result<(), c_long> { self.skb.store(offset, v, flags) } #[inline] pub fn l3_csum_replace( &self, offset: usize, from: u64, to: u64, size: u64, ) -> Result<(), c_long> { self.skb.l3_csum_replace(offset, from, to, size) } #[inline] pub fn l4_csum_replace( &self, offset: usize, from: u64, to: u64, flags: u64, ) -> Result<(), c_long> { self.skb.l4_csum_replace(offset, from, to, flags) } #[inline] pub fn adjust_room(&self, len_diff: i32, mode: u32, flags: u64) -> Result<(), c_long> { self.skb.adjust_room(len_diff, mode, flags) } #[inline] pub fn clone_redirect(&self, if_index: u32, flags: u64) -> Result<(), c_long> { self.skb.clone_redirect(if_index, flags) } #[inline] pub fn change_type(&self, ty: u32) -> Result<(), c_long> { self.skb.change_type(ty) } /// Pulls in non-linear data in case the skb is non-linear. /// /// Make len bytes from skb readable and writable. If a zero value is passed for /// `len`, then the whole length of the skb is pulled. This helper is only needed /// for reading and writing with direct packet access. /// /// # Examples /// /// ```no_run /// mod bindings; /// use bindings::{ethhdr, iphdr, udphdr}; /// /// const ETH_HLEN: usize = core::mem::size_of::<ethhdr>(); /// const IP_HLEN: usize = core::mem::size_of::<iphdr>(); /// const UDP_HLEN: usize = core::mem::size_of::<udphdr>(); /// /// fn try_classifier(ctx: TcContext) -> Result<i32, i32> { /// let len = ETH_HLEN + IP_HLEN + UDP_HLEN; /// match ctx.pull_data(len as u32) { /// Ok(_) => return Ok(0), /// Err(ret) => return Err(ret as i32), /// } /// } /// ``` #[inline(always)] pub fn pull_data(&self, len: u32) -> Result<(), c_long> { self.skb.pull_data(len) } } impl BpfContext for TcContext { fn as_ptr(&self) -> *mut c_void { self.skb.as_ptr() } } <file_sep>/aya-log-parser/src/lib.rs use std::str; use aya_log_common::DisplayHint; /// A parsed formatting parameter (contents of `{` `}` block). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Parameter { /// The display hint, e.g. ':ipv4', ':x'. pub hint: DisplayHint, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Fragment { /// A literal string (eg. `"literal "` in `"literal {}"`). Literal(String), /// A format parameter. Parameter(Parameter), } fn push_literal(frag: &mut Vec<Fragment>, unescaped_literal: &str) -> Result<(), String> { // Replace `{{` with `{` and `}}` with `}`. Single braces are errors. // Scan for single braces first. The rest is trivial. let mut last_open = false; let mut last_close = false; for c in unescaped_literal.chars() { match c { '{' => last_open = !last_open, '}' => last_close = !last_close, _ => { if last_open { return Err("unmatched `{` in format string".into()); } if last_close { return Err("unmatched `}` in format string".into()); } } } } // Handle trailing unescaped `{` or `}`. if last_open { return Err("unmatched `{` in format string".into()); } if last_close { return Err("unmatched `}` in format string".into()); } let literal = unescaped_literal.replace("{{", "{").replace("}}", "}"); frag.push(Fragment::Literal(literal)); Ok(()) } /// Parses the display hint (e.g. the `ipv4` in `{:ipv4}`). fn parse_display_hint(s: &str) -> Result<DisplayHint, String> { Ok(match s { "x" => DisplayHint::LowerHex, "X" => DisplayHint::UpperHex, "ipv4" => DisplayHint::Ipv4, "ipv6" => DisplayHint::Ipv6, "mac" => DisplayHint::LowerMac, "MAC" => DisplayHint::UpperMac, _ => return Err(format!("unknown display hint: {s:?}")), }) } /// Parse `Param` from the given `&str` which can specify an optional format /// like `:x` or `:ipv4` (without curly braces, which are parsed by the `parse` /// function). fn parse_param(mut input: &str) -> Result<Parameter, String> { const HINT_PREFIX: &str = ":"; // Then, optional hint let mut hint = DisplayHint::Default; if input.starts_with(HINT_PREFIX) { // skip the prefix input = &input[HINT_PREFIX.len()..]; if input.is_empty() { return Err("malformed format string (missing display hint after ':')".into()); } hint = parse_display_hint(input)?; } else if !input.is_empty() { return Err(format!("unexpected content {input:?} in format string")); } Ok(Parameter { hint }) } /// Parses the given format string into string literals and parameters specified /// by curly braces (with optional format hints like `:x` or `:ipv4`). pub fn parse(format_string: &str) -> Result<Vec<Fragment>, String> { let mut fragments = Vec::new(); // Index after the `}` of the last format specifier. let mut end_pos = 0; let mut chars = format_string.char_indices(); while let Some((brace_pos, ch)) = chars.next() { if ch != '{' { // Part of a literal fragment. continue; } // Peek at the next char. if chars.as_str().starts_with('{') { // Escaped `{{`, also part of a literal fragment. chars.next(); continue; } if brace_pos > end_pos { // There's a literal fragment with at least 1 character before this // parameter fragment. let unescaped_literal = &format_string[end_pos..brace_pos]; push_literal(&mut fragments, unescaped_literal)?; } // Else, this is a format specifier. It ends at the next `}`. let len = chars .as_str() .find('}') .ok_or("missing `}` in format string")?; end_pos = brace_pos + 1 + len + 1; // Parse the contents inside the braces. let param_str = &format_string[brace_pos + 1..][..len]; let param = parse_param(param_str)?; fragments.push(Fragment::Parameter(param)); } // Trailing literal. if end_pos != format_string.len() { push_literal(&mut fragments, &format_string[end_pos..])?; } Ok(fragments) } #[cfg(test)] mod test { use super::*; #[test] fn test_parse() { assert_eq!( parse("foo {} bar {:x} test {:X} ayy {:ipv4} lmao {:ipv6} {{}} {{something}}"), Ok(vec![ Fragment::Literal("foo ".into()), Fragment::Parameter(Parameter { hint: DisplayHint::Default }), Fragment::Literal(" bar ".into()), Fragment::Parameter(Parameter { hint: DisplayHint::LowerHex }), Fragment::Literal(" test ".into()), Fragment::Parameter(Parameter { hint: DisplayHint::UpperHex }), Fragment::Literal(" ayy ".into()), Fragment::Parameter(Parameter { hint: DisplayHint::Ipv4 }), Fragment::Literal(" lmao ".into()), Fragment::Parameter(Parameter { hint: DisplayHint::Ipv6 }), Fragment::Literal(" {{}} {{something}}".into()), ]) ); assert!(parse("foo {:}").is_err()); assert!(parse("foo { bar").is_err()); assert!(parse("foo } bar").is_err()); assert!(parse("foo { bar }").is_err()); } } <file_sep>/aya-tool/Cargo.toml [package] name = "aya-tool" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2021" [dependencies] bindgen = "0.63" clap = { version = "4", features = ["derive"] } anyhow = "1" thiserror = "1" tempfile = "3" <file_sep>/aya/src/programs/cgroup_device.rs //! Cgroup device programs. use std::os::unix::prelude::{AsRawFd, RawFd}; use crate::{ generated::{bpf_attach_type::BPF_CGROUP_DEVICE, bpf_prog_type::BPF_PROG_TYPE_CGROUP_DEVICE}, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, bpf_prog_attach, kernel_version}, }; /// A program used to watch or prevent device interaction from a cgroup. /// /// [`CgroupDevice`] programs can be attached to a cgroup and will be called every /// time a process inside that cgroup tries to access (e.g. read, write, mknod) /// a device (identified through its major and minor number). See /// [mknod](https://man7.org/linux/man-pages/man2/mknod.2.html) as a starting point. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is [4.15](https://github.com/torvalds/linux/commit/ebc614f687369f9df99828572b1d85a7c2de3d92). /// /// # Examples /// /// ```no_run /// # #[derive(Debug, thiserror::Error)] /// # enum Error { /// # #[error(transparent)] /// # IO(#[from] std::io::Error), /// # #[error(transparent)] /// # Map(#[from] aya::maps::MapError), /// # #[error(transparent)] /// # Program(#[from] aya::programs::ProgramError), /// # #[error(transparent)] /// # Bpf(#[from] aya::BpfError) /// # } /// # let mut bpf = aya::Bpf::load(&[])?; /// use aya::programs::CgroupDevice; /// /// let cgroup = std::fs::File::open("/sys/fs/cgroup/unified")?; /// let program: &mut CgroupDevice = bpf.program_mut("cgroup_dev").unwrap().try_into()?; /// program.load()?; /// program.attach(cgroup)?; /// # Ok::<(), Error>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_DEVICE")] pub struct CgroupDevice { pub(crate) data: ProgramData<CgroupDeviceLink>, } impl CgroupDevice { /// Loads the program inside the kernel pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_CGROUP_DEVICE, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupDevice::detach] pub fn attach<T: AsRawFd>(&mut self, cgroup: T) -> Result<CgroupDeviceLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let cgroup_fd = cgroup.as_raw_fd(); let k_ver = kernel_version().unwrap(); if k_ver >= (5, 7, 0) { let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, None, 0).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(CgroupDeviceLink::new(CgroupDeviceLinkInner::Fd( FdLink::new(link_fd), ))) } else { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_attach".to_owned(), io_error, } })?; self.data .links .insert(CgroupDeviceLink::new(CgroupDeviceLinkInner::ProgAttach( ProgAttachLink::new(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE), ))) } } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: CgroupDeviceLinkId, ) -> Result<CgroupDeviceLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program /// /// See [CgroupDevice::attach]. pub fn detach(&mut self, link_id: CgroupDeviceLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } } #[derive(Debug, Hash, Eq, PartialEq)] enum CgroupDeviceLinkIdInner { Fd(<FdLink as Link>::Id), ProgAttach(<ProgAttachLink as Link>::Id), } #[derive(Debug)] enum CgroupDeviceLinkInner { Fd(FdLink), ProgAttach(ProgAttachLink), } impl Link for CgroupDeviceLinkInner { type Id = CgroupDeviceLinkIdInner; fn id(&self) -> Self::Id { match self { CgroupDeviceLinkInner::Fd(fd) => CgroupDeviceLinkIdInner::Fd(fd.id()), CgroupDeviceLinkInner::ProgAttach(p) => CgroupDeviceLinkIdInner::ProgAttach(p.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { CgroupDeviceLinkInner::Fd(fd) => fd.detach(), CgroupDeviceLinkInner::ProgAttach(p) => p.detach(), } } } define_link_wrapper!( /// The link used by [CgroupDevice] programs. CgroupDeviceLink, /// The type returned by [CgroupDevice::attach]. Can be passed to [CgroupDevice::detach]. CgroupDeviceLinkId, CgroupDeviceLinkInner, CgroupDeviceLinkIdInner ); <file_sep>/aya-log-ebpf-macros/src/expand.rs use proc_macro2::TokenStream; use quote::quote; use syn::{ parse::{Parse, ParseStream}, parse_str, punctuated::Punctuated, Error, Expr, LitStr, Result, Token, }; use aya_log_common::DisplayHint; use aya_log_parser::{parse, Fragment}; pub(crate) struct LogArgs { pub(crate) ctx: Expr, pub(crate) target: Option<Expr>, pub(crate) level: Option<Expr>, pub(crate) format_string: LitStr, pub(crate) formatting_args: Option<Punctuated<Expr, Token![,]>>, } mod kw { syn::custom_keyword!(target); } impl Parse for LogArgs { fn parse(input: ParseStream) -> Result<Self> { let ctx: Expr = input.parse()?; input.parse::<Token![,]>()?; // Parse `target: &str`, which is an optional argument. let target: Option<Expr> = if input.peek(kw::target) { input.parse::<kw::target>()?; input.parse::<Token![:]>()?; let t: Expr = input.parse()?; input.parse::<Token![,]>()?; Some(t) } else { None }; // Check whether the next token is `format_string: &str` (which i // always provided) or `level` (which is an optional expression). // If `level` is provided, it comes before `format_string`. let (level, format_string): (Option<Expr>, LitStr) = if input.peek(LitStr) { // Only `format_string` is provided. (None, input.parse()?) } else { // Both `level` and `format_string` are provided. let level: Expr = input.parse()?; input.parse::<Token![,]>()?; let format_string: LitStr = input.parse()?; (Some(level), format_string) }; // Parse variadic arguments. let formatting_args: Option<Punctuated<Expr, Token![,]>> = if input.is_empty() { None } else { input.parse::<Token![,]>()?; Some(Punctuated::parse_terminated(input)?) }; Ok(Self { ctx, target, level, format_string, formatting_args, }) } } fn string_to_expr(s: String) -> Result<Expr> { parse_str(&format!("\"{s}\"")) } fn hint_to_expr(hint: DisplayHint) -> Result<Expr> { match hint { DisplayHint::Default => parse_str("::aya_log_ebpf::macro_support::DisplayHint::Default"), DisplayHint::LowerHex => parse_str("::aya_log_ebpf::macro_support::DisplayHint::LowerHex"), DisplayHint::UpperHex => parse_str("::aya_log_ebpf::macro_support::DisplayHint::UpperHex"), DisplayHint::Ipv4 => parse_str("::aya_log_ebpf::macro_support::DisplayHint::Ipv4"), DisplayHint::Ipv6 => parse_str("::aya_log_ebpf::macro_support::DisplayHint::Ipv6"), DisplayHint::LowerMac => parse_str("::aya_log_ebpf::macro_support::DisplayHint::LowerMac"), DisplayHint::UpperMac => parse_str("::aya_log_ebpf::macro_support::DisplayHint::UpperMac"), } } pub(crate) fn log(args: LogArgs, level: Option<TokenStream>) -> Result<TokenStream> { let ctx = args.ctx; let target = match args.target { Some(t) => quote! { #t }, None => quote! { module_path!() }, }; let lvl: TokenStream = if let Some(l) = level { l } else if let Some(l) = args.level { quote! { #l } } else { return Err(Error::new( args.format_string.span(), "missing `level` argument: try passing an `aya_log_ebpf::Level` value", )); }; let format_string = args.format_string; let format_string_val = format_string.value(); let fragments = parse(&format_string_val).map_err(|e| { Error::new( format_string.span(), format!("could not parse the format string: {e}"), ) })?; let mut arg_i = 0; let mut values = Vec::new(); for fragment in fragments { match fragment { Fragment::Literal(s) => { values.push(string_to_expr(s)?); } Fragment::Parameter(p) => { let arg = match args.formatting_args { Some(ref args) => args[arg_i].clone(), None => return Err(Error::new(format_string.span(), "no arguments provided")), }; values.push(hint_to_expr(p.hint)?); values.push(arg); arg_i += 1; } } } let num_args = values.len(); let values_iter = values.iter(); Ok(quote! { { if let Some(buf_ptr) = unsafe { ::aya_log_ebpf::AYA_LOG_BUF.get_ptr_mut(0) } { let buf = unsafe { &mut *buf_ptr }; if let Ok(header_len) = ::aya_log_ebpf::write_record_header( &mut buf.buf, #target, #lvl, module_path!(), file!(), line!(), #num_args, ) { let record_len = header_len; if let Ok(record_len) = { use ::aya_log_ebpf::WriteToBuf; Ok::<_, ()>(record_len) #( .and_then(|record_len| { if record_len >= buf.buf.len() { return Err(()); } { #values_iter }.write(&mut buf.buf[record_len..]).map(|len| record_len + len) }) )* } { unsafe { ::aya_log_ebpf::AYA_LOGS.output( #ctx, &buf.buf[..record_len], 0 )} } } } } }) } pub(crate) fn error(args: LogArgs) -> Result<TokenStream> { log( args, Some(quote! { ::aya_log_ebpf::macro_support::Level::Error }), ) } pub(crate) fn warn(args: LogArgs) -> Result<TokenStream> { log( args, Some(quote! { ::aya_log_ebpf::macro_support::Level::Warn }), ) } pub(crate) fn info(args: LogArgs) -> Result<TokenStream> { log( args, Some(quote! { ::aya_log_ebpf::macro_support::Level::Info }), ) } pub(crate) fn debug(args: LogArgs) -> Result<TokenStream> { log( args, Some(quote! { ::aya_log_ebpf::macro_support::Level::Debug }), ) } pub(crate) fn trace(args: LogArgs) -> Result<TokenStream> { log( args, Some(quote! { ::aya_log_ebpf::macro_support::Level::Trace }), ) } <file_sep>/bpf/aya-bpf/build.rs use std::env; fn main() { check_rust_version(); println!("cargo:rerun-if-env-changed=CARGO_CFG_BPF_TARGET_ARCH"); if let Ok(arch) = env::var("CARGO_CFG_BPF_TARGET_ARCH") { println!("cargo:rustc-cfg=bpf_target_arch=\"{arch}\""); } else { let arch = env::var("HOST").unwrap(); let arch = arch.split_once('-').map_or(&*arch, |x| x.0); println!("cargo:rustc-cfg=bpf_target_arch=\"{arch}\""); } } #[rustversion::nightly] fn check_rust_version() { println!("cargo:rustc-cfg=unstable"); } #[rustversion::not(nightly)] fn check_rust_version() {} <file_sep>/test/integration-ebpf/src/name_test.rs #![no_std] #![no_main] use aya_bpf::{bindings::xdp_action, macros::xdp, programs::XdpContext}; #[xdp(name = "ihaveaverylongname")] pub fn ihaveaverylongname(ctx: XdpContext) -> u32 { match unsafe { try_pass(ctx) } { Ok(ret) => ret, Err(_) => xdp_action::XDP_ABORTED, } } unsafe fn try_pass(_ctx: XdpContext) -> Result<u32, u32> { Ok(xdp_action::XDP_PASS) } #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachable_unchecked() } } <file_sep>/aya/src/maps/perf/mod.rs //! Ring buffer types used to receive events from eBPF programs using the linux `perf` API. //! //! See the [`PerfEventArray`](crate::maps::PerfEventArray) and [`AsyncPerfEventArray`](crate::maps::perf::AsyncPerfEventArray). #[cfg(any(feature = "async"))] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] mod async_perf_event_array; mod perf_buffer; mod perf_event_array; #[cfg(any(feature = "async"))] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] pub use async_perf_event_array::*; pub use perf_buffer::*; pub use perf_event_array::*; <file_sep>/aya/src/programs/xdp.rs //! eXpress Data Path (XDP) programs. use bitflags; use libc::if_nametoindex; use std::{convert::TryFrom, ffi::CString, hash::Hash, io, mem, os::unix::io::RawFd}; use thiserror::Error; use crate::{ generated::{ bpf_attach_type::{self, BPF_XDP}, bpf_link_type, bpf_prog_type::BPF_PROG_TYPE_XDP, XDP_FLAGS_DRV_MODE, XDP_FLAGS_HW_MODE, XDP_FLAGS_REPLACE, XDP_FLAGS_SKB_MODE, XDP_FLAGS_UPDATE_IF_NOEXIST, }, programs::{ define_link_wrapper, load_program, FdLink, Link, LinkError, ProgramData, ProgramError, }, sys::{ bpf_link_create, bpf_link_get_info_by_fd, bpf_link_update, kernel_version, netlink_set_xdp_fd, }, }; /// The type returned when attaching an [`Xdp`] program fails on kernels `< 5.9`. #[derive(Debug, Error)] pub enum XdpError { /// netlink error while attaching XDP program #[error("netlink error while attaching XDP program")] NetlinkError { /// the [`io::Error`] from the netlink call #[source] io_error: io::Error, }, } bitflags! { /// Flags passed to [`Xdp::attach()`]. #[derive(Default)] pub struct XdpFlags: u32 { /// Skb mode. const SKB_MODE = XDP_FLAGS_SKB_MODE; /// Driver mode. const DRV_MODE = XDP_FLAGS_DRV_MODE; /// Hardware mode. const HW_MODE = XDP_FLAGS_HW_MODE; /// Replace a previously attached XDP program. const REPLACE = XDP_FLAGS_REPLACE; /// Only attach if there isn't another XDP program already attached. const UPDATE_IF_NOEXIST = XDP_FLAGS_UPDATE_IF_NOEXIST; } } /// An XDP program. /// /// eXpress Data Path (XDP) programs can be attached to the very early stages of network /// processing, where they can apply custom packet processing logic. When supported by the /// underlying network driver, XDP programs can execute directly on network cards, greatly /// reducing CPU load. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.8. /// /// # Examples /// /// ```no_run /// # let mut bpf = Bpf::load_file("ebpf_programs.o")?; /// use aya::{Bpf, programs::{Xdp, XdpFlags}}; /// /// let program: &mut Xdp = bpf.program_mut("intercept_packets").unwrap().try_into()?; /// program.attach("eth0", XdpFlags::default())?; /// # Ok::<(), aya::BpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_XDP")] pub struct Xdp { pub(crate) data: ProgramData<XdpLink>, } impl Xdp { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = Some(bpf_attach_type::BPF_XDP); load_program(BPF_PROG_TYPE_XDP, &mut self.data) } /// Attaches the program to the given `interface`. /// /// The returned value can be used to detach, see [Xdp::detach]. /// /// # Errors /// /// If the given `interface` does not exist /// [`ProgramError::UnknownInterface`] is returned. /// /// When attaching fails, [`ProgramError::SyscallError`] is returned for /// kernels `>= 5.9.0`, and instead /// [`XdpError::NetlinkError`] is returned for older /// kernels. pub fn attach(&mut self, interface: &str, flags: XdpFlags) -> Result<XdpLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; let c_interface = CString::new(interface).unwrap(); let if_index = unsafe { if_nametoindex(c_interface.as_ptr()) } as RawFd; if if_index == 0 { return Err(ProgramError::UnknownInterface { name: interface.to_string(), }); } let k_ver = kernel_version().unwrap(); if k_ver >= (5, 9, 0) { let link_fd = bpf_link_create(prog_fd, if_index, BPF_XDP, None, flags.bits).map_err( |(_, io_error)| ProgramError::SyscallError { call: "bpf_link_create".to_owned(), io_error, }, )? as RawFd; self.data .links .insert(XdpLink::new(XdpLinkInner::FdLink(FdLink::new(link_fd)))) } else { unsafe { netlink_set_xdp_fd(if_index, prog_fd, None, flags.bits) } .map_err(|io_error| XdpError::NetlinkError { io_error })?; self.data .links .insert(XdpLink::new(XdpLinkInner::NlLink(NlLink { if_index, prog_fd, flags, }))) } } /// Detaches the program. /// /// See [Xdp::attach]. pub fn detach(&mut self, link_id: XdpLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link(&mut self, link_id: XdpLinkId) -> Result<XdpLink, ProgramError> { self.data.take_link(link_id) } /// Atomically replaces the program referenced by the provided link. /// /// Ownership of the link will transfer to this program. pub fn attach_to_link(&mut self, link: XdpLink) -> Result<XdpLinkId, ProgramError> { let prog_fd = self.data.fd_or_err()?; match link.inner() { XdpLinkInner::FdLink(fd_link) => { let link_fd = fd_link.fd; bpf_link_update(link_fd, prog_fd, None, 0).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_link_update".to_string(), io_error, } })?; // dispose of link and avoid detach on drop mem::forget(link); self.data .links .insert(XdpLink::new(XdpLinkInner::FdLink(FdLink::new(link_fd)))) } XdpLinkInner::NlLink(nl_link) => { let if_index = nl_link.if_index; let old_prog_fd = nl_link.prog_fd; let flags = nl_link.flags; let replace_flags = flags | XdpFlags::REPLACE; unsafe { netlink_set_xdp_fd(if_index, prog_fd, Some(old_prog_fd), replace_flags.bits()) .map_err(|io_error| XdpError::NetlinkError { io_error })?; } // dispose of link and avoid detach on drop mem::forget(link); self.data .links .insert(XdpLink::new(XdpLinkInner::NlLink(NlLink { if_index, prog_fd, flags, }))) } } } } #[derive(Debug)] pub(crate) struct NlLink { if_index: i32, prog_fd: RawFd, flags: XdpFlags, } impl Link for NlLink { type Id = (i32, RawFd); fn id(&self) -> Self::Id { (self.if_index, self.prog_fd) } fn detach(self) -> Result<(), ProgramError> { let k_ver = kernel_version().unwrap(); let flags = if k_ver >= (5, 7, 0) { self.flags.bits | XDP_FLAGS_REPLACE } else { self.flags.bits }; let _ = unsafe { netlink_set_xdp_fd(self.if_index, -1, Some(self.prog_fd), flags) }; Ok(()) } } #[derive(Debug, Hash, Eq, PartialEq)] pub(crate) enum XdpLinkIdInner { FdLinkId(<FdLink as Link>::Id), NlLinkId(<NlLink as Link>::Id), } #[derive(Debug)] pub(crate) enum XdpLinkInner { FdLink(FdLink), NlLink(NlLink), } impl Link for XdpLinkInner { type Id = XdpLinkIdInner; fn id(&self) -> Self::Id { match self { XdpLinkInner::FdLink(link) => XdpLinkIdInner::FdLinkId(link.id()), XdpLinkInner::NlLink(link) => XdpLinkIdInner::NlLinkId(link.id()), } } fn detach(self) -> Result<(), ProgramError> { match self { XdpLinkInner::FdLink(link) => link.detach(), XdpLinkInner::NlLink(link) => link.detach(), } } } impl TryFrom<XdpLink> for FdLink { type Error = LinkError; fn try_from(value: XdpLink) -> Result<Self, Self::Error> { if let XdpLinkInner::FdLink(fd) = value.into_inner() { Ok(fd) } else { Err(LinkError::InvalidLink) } } } impl TryFrom<FdLink> for XdpLink { type Error = LinkError; fn try_from(fd_link: FdLink) -> Result<Self, Self::Error> { // unwrap of fd_link.fd will not panic since it's only None when being dropped. let info = bpf_link_get_info_by_fd(fd_link.fd).map_err(|io_error| LinkError::SyscallError { call: "BPF_OBJ_GET_INFO_BY_FD".to_string(), code: 0, io_error, })?; if info.type_ == (bpf_link_type::BPF_LINK_TYPE_XDP as u32) { return Ok(XdpLink::new(XdpLinkInner::FdLink(fd_link))); } Err(LinkError::InvalidLink) } } define_link_wrapper!( /// The link used by [Xdp] programs. XdpLink, /// The type returned by [Xdp::attach]. Can be passed to [Xdp::detach]. XdpLinkId, XdpLinkInner, XdpLinkIdInner );
b89fd0b1d5c6c892789c5cf55c1a670143016532
[ "TOML", "Markdown", "Rust", "C", "Shell" ]
125
Rust
cmarincia/Aya
890e8c9340d46f931dbbaf43d884593e012ef9f9
00d5e493e501eef059317117a40d7c8f110f0847
refs/heads/master
<repo_name>rrozenv/swift-structL-lab-ios-0217<file_sep>/StructLove/PizzaDeliveryService.swift // // PizzaDeliveryService.swift // StructLove // // Created by <NAME> on 8/18/16. // Copyright © 2016 Flatiron School. All rights reserved. // import Foundation struct PizzaDeliveryService { let location: Coordinate var pizzasAvailable: Int init(location: Coordinate) { self.location = location self.pizzasAvailable = 10 } func isInRangeTo(to destination: Coordinate) -> Bool { var distanceInKilo: Double distanceInKilo = acos(sin(self.location.latitude.radians) * sin(destination.latitude.radians) + cos(self.location.latitude.radians) * cos(destination.latitude.radians) * cos(self.location.longitude.radians - destination.longitude.radians)) * 6371000 / 1000 guard distanceInKilo <= 5000 else { return false } return true } mutating func deliverPizza(to destination: Coordinate) -> Bool { let isInRange = self.isInRangeTo(to: destination) if pizzasAvailable == 0 { return false } guard isInRange else { return false } pizzasAvailable -= 1 return true } }
07269c2cb52bff6352f33d2eaf22fa36b88a4dc9
[ "Swift" ]
1
Swift
rrozenv/swift-structL-lab-ios-0217
04da179e111ae2ca5f5686b58195b97c00adb341
938a3a66dc266b8da78f29230648b4974a9600b4
refs/heads/master
<repo_name>JerSoh/mean-stack-app<file_sep>/src/app/recipes/recipes.service.ts import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Router } from '@angular/router'; import { Recipe } from './recipe.model'; @Injectable({ providedIn: 'root' }) export class RecipesService { private recipes: Recipe[] = []; private recipesUpdated = new Subject<Recipe[]>(); constructor(private http: HttpClient, private router: Router) {} getRecipes() { this.http .get<{ message: string, recipes: any }>( 'http://localhost:3000/api/recipes' ) .pipe(map((recipeData) => { return recipeData.recipes.map(recipe => { return { recipeName: recipe.recipeName, content: recipe.content, id: recipe._id, imagePath: recipe.imagePath, }; }); })) .subscribe(transformedRecipes => { this.recipes = transformedRecipes; this.recipesUpdated.next([...this.recipes]); }); } getRecipeUpdateListener() { return this.recipesUpdated.asObservable(); } getRecipe(id: string) { return this.http.get<{ _id: string, recipeName: string, content: string, imagePath: string }>( 'http://localhost:3000/api/recipes/' + id ); } addRecipe(recipeName: string, content: string, image: File) { const recipeData = new FormData(); recipeData.append('recipeName', recipeName); recipeData.append('content', content); recipeData.append('image', image, recipeName); this.http .post<{ message: string, recipe: Recipe }>( 'http://localhost:3000/api/recipes', recipeData ) .subscribe((responseData) => { const recipe: Recipe = { id: responseData.recipe.id, recipeName: recipeName, content: content, imagePath: responseData.recipe.imagePath, }; this.recipes.push(recipe); this.recipesUpdated.next([...this.recipes]); this.router.navigate(['/']); }); } updateRecipe(id: string, recipeName: string, content: string, image: File | string) { let recipeData: Recipe | FormData; if (typeof(image) === 'object') { recipeData = new FormData(); recipeData.append('id', id); recipeData.append('recipeName', recipeName); recipeData.append('content', content); recipeData.append('image', image, recipeName); } else { recipeData = { id: id, recipeName: recipeName, content: content, imagePath: image}; } this.http.put('http://localhost:3000/api/recipes/' + id, recipeData) .subscribe(response => { const updatedRecipes = [...this.recipes]; const oldRecipeIndex = updatedRecipes.findIndex(r => r.id === id); const recipe: Recipe = { id: id, recipeName: recipeName, content: content, imagePath: '', }; updatedRecipes[oldRecipeIndex] = recipe; this.recipes = updatedRecipes; this.recipesUpdated.next([...this.recipes]); console.log(response); this.router.navigate(['/']); }); } deleteRecipe(recipeId: string) { this.http.delete('http://localhost:3000/api/recipes/' + recipeId) .subscribe(() => { const updatedRecipes = this.recipes.filter(recipe => recipe.id !== recipeId); this.recipes = updatedRecipes; this.recipesUpdated.next([...this.recipes]); }); } } <file_sep>/src/app/recipes/recipe-create/recipe-create.component.ts import { Component, OnInit } from '@angular/core'; import { NgForm, FormGroup, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, ParamMap } from '@angular/router'; import { RecipesService } from '../recipes.service'; import { Recipe } from '../recipe.model'; import { mimeType } from './mime-type.validator'; @Component({ selector: 'app-recipe-create', templateUrl: './recipe-create.component.html', styleUrls: ['./recipe-create.component.css'] }) export class RecipeCreateComponent implements OnInit { recipe: Recipe; isLoading = false; form: FormGroup; imagePreview: string; private mode = 'create'; private recipeId: string; constructor( public recipesSvc: RecipesService, public route: ActivatedRoute) { } ngOnInit() { this.form = new FormGroup({ 'recipeName': new FormControl(null, { validators: [Validators.required] }), 'content': new FormControl(null, { validators: [Validators.required] }), 'image': new FormControl(null, { validators: [Validators.required], asyncValidators: [mimeType] }), }); this.route.paramMap.subscribe((paramMap: ParamMap) => { if (paramMap.has('recipeId')) { this.mode = 'edit'; this.recipeId = paramMap.get('recipeId'); this.isLoading = true; this.recipesSvc.getRecipe(this.recipeId).subscribe(recipeData => { this.isLoading = false; this.recipe = { id: recipeData._id, recipeName: recipeData.recipeName, content: recipeData.content, imagePath: recipeData.imagePath, }; this.form.setValue({ 'recipeName': this.recipe.recipeName, 'content': this.recipe.content, 'image': this.recipe.imagePath, }); }); } else { this.mode = 'create'; this.recipeId = null; } }); } onImagePicked(event: Event) { const file = (event.target as HTMLInputElement).files[0]; this.form.patchValue({image: file}); this.form.get('image').updateValueAndValidity(); const reader = new FileReader(); reader.onload = () => { this.imagePreview = reader.result as string; }; reader.readAsDataURL(file); } onSaveRecipe() { if (this.form.invalid) { return; } this.isLoading = true; if (this.mode === 'create') { this.recipesSvc.addRecipe( this.form.value.recipeName, this.form.value.content, this.form.value.image ); } else { this.recipesSvc.updateRecipe( this.recipeId, this.form.value.recipeName, this.form.value.content, this.form.value.image ); } this.form.reset(); } } <file_sep>/src/app/recipes/recipe.model.ts export interface Recipe { id: string; recipeName: string; content: string; imagePath: string; } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { FlexLayoutModule } from '@angular/flex-layout'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { RecipeCreateComponent } from './recipes/recipe-create/recipe-create.component'; import { RecipeListComponent } from './recipes/recipe-list/recipe-list.component'; import { RecipeListItemComponent } from './recipes/recipe-list/recipe-list-item/recipe-list-item.component'; import { MaterialModule } from './material.module'; import { AppRoutingModule } from './app-routing.module'; @NgModule({ declarations: [ AppComponent, HeaderComponent, RecipeCreateComponent, RecipeListComponent, RecipeListItemComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MaterialModule, FlexLayoutModule, ReactiveFormsModule, HttpClientModule, AppRoutingModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
13274d9eb9fa6be1bf14e91407813467736e0c45
[ "TypeScript" ]
4
TypeScript
JerSoh/mean-stack-app
8441ae457dc48766bc18d933aa08aa4ab089238d
2c3fdf9d585c0401a13176c4584ac6dbcaa7dfa1
refs/heads/master
<file_sep>#!/bin/sh [ -x /usr/sbin/nvme ] || exit PROC="$(basename "$0")[$$]" log() { FACILITY="kern.$1" shift logger -s -p "$FACILITY" -t "$PROC" "$@" } raw_ebs_alias() { /usr/sbin/nvme id-ctrl "/dev/$BASE" -b 2>/dev/null | dd bs=32 skip=96 count=1 2>/dev/null } case $ACTION in add|"") BASE=$(echo "$MDEV" | sed -re 's/^(nvme[0-9]+n[0-9]+).*/\1/') PART=$(echo "$MDEV" | sed -re 's/nvme[0-9]+n[0-9]+p?//g') MAXTRY=50 TRY=0 until [ -n "$EBS" ]; do EBS=$(raw_ebs_alias | sed -nre '/^(\/dev\/)?(s|xv)d[a-z]{1,2} /p' | tr -d ' ') [ -n "$EBS" ] && break TRY=$((TRY + 1)) if [ $TRY -eq $MAXTRY ]; then log err "Failed to get EBS volume alias for $MDEV after $MAXTRY attempts ($(raw_ebs_alias))" exit 1 fi sleep 0.1 done # remove any leading '/dev/', 'sd', or 'xvd', and append partition EBS=${EBS#/dev/} EBS=${EBS#sd} EBS=${EBS#xvd}$PART ln -sf "$MDEV" "sd$EBS" && log notice "Added sd$EBS symlink for $MDEV" ln -sf "$MDEV" "xvd$EBS" && log notice "Added xvd$EBS symlink for $MDEV" ;; remove) for TARGET in sd* xvd* do [ "$(readlink "$TARGET" 2>/dev/null)" = "$MDEV" ] && rm -f "$TARGET" && log notice "Removed $TARGET symlink for $MDEV" done ;; esac <file_sep># Alpine Linux EC2 AMI Builder These are the official Alpine AWS AMIs. For an index of images see the [Alpine Website](https://alpinelinux.org/cloud/). ## Pre-Built AMIs ***To get started with a pre-built minimalist AMIs, visit https://alpinelinux.org/cloud, or the [README](releases/README.md) in the [releases](releases) subdirectory of this repo.*** Alternately, with the right filters, you can query the EC2 API to programmatically find our most recent AMIs. For example, using the `aws` command line tool... ``` aws ec2 describe-images \ --output text \ --filters \ Name=owner-id,Values=538276064493 \ Name=name,Values='alpine-ami-*' \ Name=state,Values=available \ Name=tag:profile_build,Values=v3_10-x86_64 \ --query 'max_by(Images[], &CreationDate).ImageId' ``` ...will list the latest AMI id from our collection of 'v3_10-x86_64' builds. Refer to the AWS CLI Command Reference for [describe-images](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html) for more details. ## Custom AMIs Using the scripts and configuration in this project, you can build your own custom Alpine Linux AMIs. If you experience any problems building custom AMIs, please open an [issue](https://github.com/mcrute/alpine-ec2-ami/issues) and include as much detailed information as possible. ### Build Requirements * [Packer](https://packer.io) >= 1.4.1 * [Python 3.x](https://python.org) (3.7 is known to work) * an AWS account with an existing subnet in an AWS Virtual Private Cloud ### Profile Configuration Target profile config files reside in the [profiles](profiles) subdirectory, where you will also find the [config](profiles/alpine.conf) we use for our pre-built AMIs. Refer to the [README](profiles/README.md) in that subdirectory for more details and information about how AMI profile configs work. ### AWS Credentials These scripts use the `boto3` library to interact with AWS, enabling you to provide your AWS account credentials in a number of different ways. see the offical `boto3` documentation's section on [configuring credentials](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#guide-credentials) for more details. *Please note that these scripts do not implement the first two methods on the list.* ### Building AMIs To build all build targets in a target profile, simply... ``` ./scripts/builder.py amis <profile> ``` You can also build specfic build targets within a profile: ``` ./scripts/builder.py amis <profile> <build1> <build2> ... ``` Before each build, new Alpine Linux *releases* are detected and the version's core profile is updated. If there's already an AMI with the same name as the profile build's, that build will be skipped and the process moves on to build the other profile's build targets (if any). After each successful build, `releases/<profile>.yaml` is updated with the build's details, including (most importantly) the ids of the AMI artifacts that were built. Additional information about using your custom AMIs can be found in the [README](releases/README.md) in the [releases](releases) subdirectory. ### Pruning AMIs Every now and then, you may want to clean up old AMIs from your EC2 account and your profile's `releases/<profile>.yaml`. There are three different levels of pruning: * `revision` - keep only the latest revision for each release * `release` - keep only the latest release for each version * `end-of-life` - remove any end-of-life versions To prune a profile (or optionally one build target of a profile)... ``` ./scripts/builder.py prune-amis <profile> [<build>] ``` ### Updating the Release README This make target updates the [releases README](releases/README.md), primarily for updating the list of our pre-built AMIs. This may-or-may-not be useful for other target profiles. ``` ./scripts/builder.py gen-release-readme <profile> ``` ### Cleaning up the Build Environment The build process is careful to place all temporary files in the `build` subdirectory. Remove the temporary `build` subdirectory, which contains the resolved profile and Packer configs, the Python virtual environment, and other temporary build-related artifacts. ## Caveats * New Alpine Linux *versions* are currently not auto-detected and added as a core version profile; this process is, at the moment, still a manual task. <file_sep>#!/bin/sh # vim: set ts=4 et: set -e PROC="$(basename "$0")[$$]" DEBUG= log() { [ -z "$DEBUG" ] && [ "$1" = "debug" ] && return FACILITY="kern.$1" shift logger -s -p "$FACILITY" -t "$PROC" "$@" } if [ -z "$MDEV" ]; then log err "MDEV env not defined" exit 1 fi RTABLE="${MDEV#eth}" let RTABLE+=1000 IFACE_CFG=/etc/network/interfaces ip() { v=-4 if [ "$1" = '-4' ] || [ "$1" = '-6' ]; then v="$1" shift fi OP="$2" [ "$OP" = show ] && LEV=debug || LEV=info if /sbin/ip "$v" "$@" || [ -n "$FAIL_OK" ]; then log "$LEV" "OK: ip $v $*" else log err "FAIL: ip $v $*" fi } assemble_interfaces() { log info "Rebuilding $IFACE_CFG" /etc/network/assemble-interfaces } interface_up() { log info "Bringing up $MDEV" ifup "$MDEV" } cleanup_interface() { log info "Cleaning up $MDEV" # kill related udhcpc kill "$(cat "/run/udhcpc.$MDEV.pid")" # tidy up /run/ifstate, if it exists [ -f /run/ifstate ] && sed -i -e "/^$MDEV=/d" /run/ifstate # remove related rules for V in 4 6; do for P in $(ip -"$V" rule show table "$RTABLE" | cut -d: -f1); do ip -"$V" rule del pref "$P" done done } log info "STARTING: $ACTION $MDEV" if exec 200>>"$IFACE_CFG"; then if flock 200; then case $ACTION in add|"") assemble_interfaces interface_up ;; remove) assemble_interfaces cleanup_interface ;; *) log err "Unknown action '$ACTION'" exit 1 ;; esac else log err "Unable to flock $IFACE_CFG" exit 1 fi else log err "Unable to assign fd 200 to flock $IFACE_CFG" exit 1 fi log info "FINISHED: $ACTION $MDEV" <file_sep># AWS Identity Broker The identity broker is used to obtain short-lived and per-region credentials for an account. Opt-in regions require the use of a long-lived credential (e.g. IAM user), enabling global STS tokens, or an STS token sourced in that region. The identity broker holds long-term credentials and uses them to acquire short-term credentials in a given region. The broker also provides a list of opt-in regions and should be used to enumerate regions. For human-interactive users the identity broker performs OAUTH against GitHub to chain the user's GitHub identity to the tokens they are given from the broker. The broker also provides the user an API key to use when interacting with the broker programmatically. As of May 2020 the identity broker is not open sourced. If you want to provide your own identity broker, the rest of this document specifies the URLs endpoints and response formats to do so. # The API The identity broker API is a REST-ful service with an entry-point of `/api/account`. All further navigation through the API follows links within the hypertext. **Note:** Outside of the account entry-point, URI formats should be considered implementation details of the broker API and should never be templated. Beyond the account entry-point, nothing in this specification is normative with respect to URI paths and locations. ## Authentication All requests to the API must be authenticated with a broker-specific key. That key is provided to the broker in the `X-API-Key` header. When the broker determines that the key is either expired or invalid it must redirect the user to `/logout` to indicate that the user is logged out and must log-in again. API keys are bearer tokens and thus must only be exchanged over HTTPS. ## Status Codes `200 OK`: indicates that the request to the broker was successful. `302 Found`: indicates that the broker is providing a redirect. Users should check the redirect, if it is to the location `/logout` the user should consider themselves logged out and proceed to login. This condition should not be followed. Otherwise the user should follow all redirects. `400 Bad Request`: indicates that some part of the request is invalid as submitted. The hypertext MAY provide a description of this error and how to remedy it. `429 Rate Limit Exceeded`: indicates that the broker has rate-limited the user. A user should discontinue requests to the broker immediately and wait for at least 30 seconds before continuing their requests. The rate limit parameters are specific to the broker and not controlled by this spec. `500 Server Error`: indicates a server error condition that is not under the user's control. ## Account End-point The account end-point acts as a index of the rest of the API. It presents a list of accounts to which the user has access as well as links to navigate further into the API. The format of this document is: `short_name` (string): a url-safe name for the account, used as the primary account identifier within the broker. `account_number` (integer): the AWS account number `name` (string): a user-friendly name for the account `console_redirect_url` (uri): a URI that, when followed, leads to a resource that redirects the user to an authenticated console session. `get_console_url` (uri): a URI that, when followed, leads to a console URL resource. `credentials_url` (uri): a URI that, when followed, leads to a region list resource. `global_credential_url` (uri): a URI that, when followed, leads to a credential resource which provides a credential usable by all non-opt-in regions. The contents of this resource are a STS global credential which is not usable in opt-in regions. ``` [ { "short_name": "primary-account", "account_number": 123456789012, "name": "Primary AWS Account", "console_redirect_url": "https://broker/api/account/primary-account/console?redirect=1", "get_console_url": "https://broker/api/account/primary-account/console", "credentials_url": "https://broker/api/account/primary-account/credentials", "global_credential_url": "https://broker/api/account/primary-account/credentials/global" } ] ``` ## Console URL Resource **Note:** This resource is not used by the build scripts. The console URL resource provides a URL to the AWS console. This resource is designed for interactive use. When provided the query parameter `redirect` with a value of `1` this resource will not generate a body and will instead redirect to the URL that would have been returned for `console_url`. `console_url` (uri): a link to the AWS console with authentication credentials embedded. ``` { "console_url": "https://signin.aws.amazon.com/federation?..." } ``` ## Credential Resource The credential resource provides a set of credentials that can be used to configure AWS tools to access an account. `access_key` (string): the AWS access key ID `secret_key` (string): the AWS secret access key `session_token` (string): the AWS session token `expiration` (iso-formatted date): the date and time when the credential will expire ``` { "access_key": "<KEY>", "secret_key": "<KEY>", "session_token": "<KEY>...", "expiration": "2020-01-01T00:00:00Z" } ``` ## Region List Resource The region list resource provides a list of regions associated with the account both opted-in and not. For opted-in regions the resource includes a link to a credential resource for that region. `name` (string): AWS name for the region `enabled` (boolean): indicates if the region is enabled and opted-in for this account. `credentials_url` (uri): a URI that, when followed, leads to a credential resource containing a credential for access to that region. The credential provided will be usable against the region-local STS endpoint for the specified region. This also applies for classic regions, which typically use a global endpoint and credential. The returned credential is scoped to the acquiring region and may not be usable against the global endpoints or a different regional endpoint. ``` [ { "name": "af-south-1", "enabled": false }, { "name": "us-west-2", "enabled": true, "credentials_url": "https://broker/api/account/primary-account/credentials/us-west-2" } ] ``` <file_sep>#!/bin/sh # vim: set ts=4 et: # This script should be installed as symlinks in # /etc/udhcpc/<hook>/eth-eni-hook # <hook> :- # post-bound - after udhcpc binds an IP to the interface # post-renew - after udhcpc renews the lease for the IP # # udhcpc provides via ENV... # IFACE - eth0, etc. # mask - bits in IPv4 subnet mask set -e HOOK="$(basename "$(dirname "$0")")" DEBUG= log() { [ -z "$DEBUG" ] && [ "$1" = "debug" ] && return FACILITY="daemon.$1" shift logger -s -p "$FACILITY" -t "udhcpc/${HOOK}[$$]" -- "$@" } if [ -z "$IFACE" ] || [ -z "$mask" ]; then log err "Missing 'IFACE' or 'mask' ENV from udhcpc" exit 1 fi # route table number RTABLE="${IFACE#eth}" let RTABLE+=1000 IMDS=X-aws-ec2-metadata-token IMDS_IP=169.254.169.254 IMDS_MAC="http://$IMDS_IP/latest/meta-data/network/interfaces/macs/$( cat "/sys/class/net/$IFACE/address")" get_imds_token() { IMDS_TOKEN="$(echo -ne \ "PUT /latest/api/token HTTP/1.0\r\n$IMDS-ttl-seconds: 60\r\n\r\n" | nc "$IMDS_IP" 80 | tail -n 1)" } mac_meta() { wget -qO - --header "$IMDS: $IMDS_TOKEN" "$IMDS_MAC/$1" 2>/dev/null \ || true # when no ipv6s attached (yet), IMDS returns 404 error } ip() { FAIL_OK= if [ "$1" = '+F' ]; then FAIL_OK=1 shift fi v=-4 if [ "$1" = '-4' ] || [ "$1" = '-6' ]; then v="$1" shift fi OP="$2" [ "$OP" = show ] && LEV=debug || LEV=info if /sbin/ip "$v" "$@" || [ -n "$FAIL_OK" ]; then log "$LEV" "OK: ip $v $*" else log err "FAIL: ip $v $*" fi } iface_ip4s() { ip -4 addr show "$IFACE" secondary | sed -E -e '/inet /!d' -e 's/.*inet ([0-9.]+).*/\1/' } iface_ip6s() { ip -6 addr show "$IFACE" scope global | sed -E -e '/inet6/!d' -e 's/.*inet6 ([0-9a-f:]+).*/\1/' } ec2_ip4s() { get_imds_token # NOTE: metadata for ENI arrives later than hotplug events TRIES=60 while true; do IP4="$(mac_meta local-ipv4s)" [ -n "$IP4" ] && break let TRIES-- if [ "$TRIES" -eq 0 ]; then log err "Unable to get IPv4 addresses for $IFACE after 30s" exit 1 fi sleep 0.5 done IP4S="$(echo "$IP4" | tail +2)" # secondary IPs (udhcpc handles primary) # non-eth0 interfaces need custom route tables # if [ "$IFACE" != eth0 ] && [ -n "$IP4S" ] && [ -z "$(ip +F -4 route show table "$RTABLE")" ]; then IP4P="$(echo "$IP4" | head -1)" # primary IP IP4_CIDR="$(mac_meta subnet-ipv4-cidr-block)" IP4_GW="$(echo "$IP4_CIDR" | cut -d/ -f1 | awk -F. '{ print $1"."$2"."$3"."$4+1 }')" ip -4 route add default via "$IP4_GW" dev "$IFACE" table "$RTABLE" ip -4 route add "$IP4_CIDR" dev "$IFACE" proto kernel scope link \ src "$IP4P" table "$RTABLE" fi echo "$IP4S" } ec2_ip6s() { get_imds_token # NOTE: IPv6 metadata (if any) may arrive later than IPv4 metadata TRIES=60 while true; do IP6S="$(mac_meta ipv6s)" [ -n "$IP6S" ] && break let TRIES-- if [ "$TRIES" -eq 0 ]; then log warn "Unable to get IPv6 addresses for $IFACE after 30s" break fi sleep 0.5 done # non-eth0 interfaces need custom route tables # # NOTE: busybox iproute2 doesn't do 'route show table' properly for IPv6, # so iproute2-minimal package is required! # if [ "$IFACE" != eth0 ] && [ -n "$IP6S" ] && [ -z "$(ip +F -6 route show table "$RTABLE")" ]; then TRIES=20 while true; do GW="$(ip -6 route show dev "$IFACE" default | awk '{ print $3 }')" [ -n "$GW" ] && break let TRIES-- if [ "$TRIES" -eq 0 ]; then log warn "Unable to get IPv6 gateway RA after 10s" break fi sleep 0.5 done ip -6 route add default via "$GW" dev "$IFACE" table "$RTABLE" fi echo "$IP6S" } in_list() { echo "$2" | grep -q "^$1$" } # ip_addr {4|6} {add|del} <ip> ip_addr() { [ "$1" -eq 6 ] && MASK=128 || MASK="$mask" # IP6s are always /128 ip -"$1" addr "$2" "$3/$MASK" dev "$IFACE" [ "$IFACE" = eth0 ] && return # non-eth0 interfaces get rules associating IPs with route tables ip -"$1" rule "$2" from "$3" lookup "$RTABLE" } # sync_ips {4|6} "<ec2-ips>" "<iface-ips>" sync_ips() { # remove extra IPs for i in $3; do in_list "$i" "$2" || ip_addr "$1" del "$i" done # add missing IPs for i in $2; do in_list "$i" "$3" || ip_addr "$1" add "$i" done } log info "STARTING: $IFACE" if [ "$HOOK" != post-bound ] && [ "$HOOK" != post-renew ]; then log err "Unhandled udhcpc hook '$HOOK'" exit 1 fi sync_ips 4 "$(ec2_ip4s)" "$(iface_ip4s)" sync_ips 6 "$(ec2_ip6s)" "$(iface_ip6s)" log info "FINISHED: $IFACE" <file_sep>#!/usr/bin/env python3 # This bit has to stay at the very top of the script. It exists to ensure that # running this script all by itself uses the python virtual environment with # our dependencies installed. If will create that environment if it doesn't # exist. import os import sys import subprocess args = [os.path.join("build", "bin", "python3")] + sys.argv # Create the build root if it doesn't exist if not os.path.exists("build"): import venv print("Build environment does not exist, creating...", file=sys.stderr) venv.create("build", with_pip=True) subprocess.run(["build/bin/pip", "install", "-U", "pip", "pyhocon", "boto3", "python-dateutil", "PyYAML"]) print("Re-executing with builder python...", file=sys.stderr) os.execv(args[0], args) else: # If the build root python is not running this script re-execute it with # that python instead to ensure all of our dependencies exist. if os.path.join(os.getcwd(), args[0]) != sys.executable: print("Re-executing with builder python...", file=sys.stderr) os.execv(args[0], args) # Below here is the real script import io import os import re import sys import glob import json import time import shutil import logging import argparse import textwrap import subprocess import urllib.error import dateutil.parser from enum import Enum from collections import defaultdict from datetime import datetime, timedelta from distutils.version import StrictVersion from urllib.request import Request, urlopen import yaml import boto3 import pyhocon # allows us to set values deep within an object that might not be fully defined def dictfactory(): return defaultdict(dictfactory) # undo dictfactory() objects to normal objects def undictfactory(o): if isinstance(o, defaultdict): o = {k: undictfactory(v) for k, v in o.items()} return o # This is an ugly hack. We occasionally need the region name but it's not # attached to anything publicly exposed on the client objects. Hide this here. def region_from_client(client): return client._client_config.region_name # version sorting def sortable_version(x): v = x.split('_rc')[0] return StrictVersion("0.0" if v == "edge" else v) class EC2Architecture(Enum): I386 = "i386" X86_64 = "x86_64" ARM64 = "arm64" class AMIState(Enum): PENDING = "pending" AVAILABLE = "available" INVALID = "invalid" DEREGISTERED = "deregistered" TRANSIENT = "transient" FAILED = "failed" ERROR = "error" class EC2SnapshotState(Enum): PENDING = "pending" COMPLETED = "completed" ERROR = "error" class TaggedAWSObject: """Base class for AWS API models that support tagging """ EDGE = StrictVersion("0.0") missing_known_tags = None _identity = lambda x: x _known_tags = { "Name": _identity, "profile": _identity, "revision": _identity, "profile_build": _identity, "source_ami": _identity, "source_region": _identity, "arch": lambda x: EC2Architecture(x), "end_of_life": lambda x: datetime.fromisoformat(x), "release": lambda v: EDGE if v == "edge" else StrictVersion(v), "version": lambda v: EDGE if v == "edge" else StrictVersion(v), } def __repr__(self): attrs = [] for k, v in self.__dict__.items(): if isinstance(v, TaggedAWSObject): attrs.append(f"{k}=" + object.__repr__(v)) elif not k.startswith("_"): attrs.append(f"{k}={v!r}") attrs = ", ".join(attrs) return f"{self.__class__.__name__}({attrs})" __str__ = __repr__ @property def aws_tags(self): """Convert python tags to AWS API tags See AMI.aws_permissions for rationale. """ for key, values in self.tags.items(): for value in values: yield { "Key": key, "Value": value } @aws_tags.setter def aws_tags(self, values): """Convert AWS API tags to python tags See AMI.aws_permissions for rationale. """ if not getattr(self, "tags", None): self.tags = {} tags = defaultdict(list) for tag in values: tags[tag["Key"]].append(tag["Value"]) self.tags.update(tags) self._transform_known_tags() # XXX(mcrute): The second paragraph might be considered a bug and worth # fixing at some point. For now those are all read-only attributes though. def _transform_known_tags(self): """Convert well known tags into python attributes Some tags have special meanings for the model objects that they're attached to. This copies those tags, transforms them, then sets them in the model attributes. It doesn't touch the tag itself so if that attribute needs updated and re-saved the tag must be updated in addition to the model. """ self.missing_known_tags = [] for k, tf in self._known_tags.items(): v = self.tags.get(k, []) if not v: self.missing_known_tags.append(k) continue if len(v) > 1: raise Exception(f"multiple instances of tag {k}") setattr(self, k, v[0]) class AMI(TaggedAWSObject): @property def aws_permissions(self): """Convert python permissions to AWS API permissions The permissions model for the API makes more sense for a web service but is overly verbose for working with in Python. This and the setter allow transforming to/from the API syntax. The python code should consume the allowed_groups and allowed_users lists directly. """ perms = [] for g in self.allowed_groups: perms.append({"Group": g}) for i in self.allowed_users: perms.append({"UserId": i}) return perms @aws_permissions.setter def aws_permissions(self, perms): """Convert AWS API permissions to python permissions """ for perm in perms: group = perm.get("Group") if group: self.allowed_groups.append(group) user = perm.get("UserId") if user: self.allowed_users.append(user) @classmethod def from_aws_model(cls, ob, region): self = cls() self.linked_snapshot = None self.allowed_groups = [] self.allowed_users = [] self.region = region self.architecture = EC2Architecture(ob["Architecture"]) self.creation_date = ob["CreationDate"] self.description = ob.get("Description", None) self.image_id = ob["ImageId"] self.name = ob.get("Name") self.owner_id = int(ob["OwnerId"]) self.public = ob["Public"] self.state = AMIState(ob["State"]) self.virtualization_type = ob["VirtualizationType"] self.state_reason = ob.get("StateReason", {}).get("Message", None) self.aws_tags = ob.get("Tags", []) # XXX(mcrute): Assumes we only ever have one device mapping, which is # valid for Alpine AMIs but not a good general assumption. # # This should always resolve for AVAILABLE images but any part of the # data structure may not yet exist for images that are still in the # process of copying. if ob.get("BlockDeviceMappings"): self.snapshot_id = \ ob["BlockDeviceMappings"][0]["Ebs"].get("SnapshotId") return self class EC2Snapshot(TaggedAWSObject): @classmethod def from_aws_model(cls, ob, region): self = cls() self.linked_ami = None self.region = region self.snapshot_id = ob["SnapshotId"] self.description = ob.get("Description", None) self.owner_id = int(ob["OwnerId"]) self.progress = int(ob["Progress"].rstrip("%")) / 100 self.start_time = ob["StartTime"] self.state = EC2SnapshotState(ob["State"]) self.volume_size = ob["VolumeSize"] self.aws_tags = ob.get("Tags", []) return self class ColoredFormatter(logging.Formatter): """Log formatter that colors output based on level """ _colors = { "red": "31", "green": "32", "yellow": "33", "blue": "34", "magenta": "35", "cyan": "36", "white": "37", } def _color_wrap(self, text, color, bold=False): code = self._colors[color] if bold: code = "1;{}".format(code) return "\033[{}m{}\033[0m".format(code, text) def format(self, record): msg = super().format(record) # Levels: CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET if record.levelno in {logging.ERROR, logging.CRITICAL}: return self._color_wrap(msg, "red") elif record.levelno == logging.WARNING: return self._color_wrap(msg, "yellow") else: return self._color_wrap(msg, "green") class IdentityBrokerClient: """Client for identity broker Export IDENTITY_BROKER_ENDPOINT to override the default broker endpoint. Export IDENTITY_BROKER_API_KEY to specify an API key for the broker. See README_BROKER.md for more information and a spec. """ _DEFAULT_ENDPOINT = "https://aws-access.crute.us/api/account" _DEFAULT_ACCOUNT = "alpine-amis-user" def __init__(self, endpoint=None, key=None, account=None): self.endpoint = endpoint or self._DEFAULT_ENDPOINT self.account = account or self._DEFAULT_ACCOUNT self.key = key self._logger = logging.getLogger() override_endpoint = os.environ.get("IDENTITY_BROKER_ENDPOINT") if override_endpoint: self.endpoint = override_endpoint if not self.key: self.key = os.environ.get("IDENTITY_BROKER_API_KEY") if not self.key: raise Exception("No identity broker key found") def _get(self, path): while True: # to handle rate limits try: res = urlopen(Request(path, headers={"X-API-Key": self.key})) except urllib.error.HTTPError as ex: if ex.headers.get("Location") == "/logout": raise Exception("Identity broker token is expired") if ex.status == 429: self._logger.warning( "Rate-limited by identity broker, sleeping 30 seconds") time.sleep(30) continue raise ex if res.status not in {200, 429}: raise Exception(res.reason) return json.load(res) def get_credentials_url(self): for account in self._get(self.endpoint): if account["short_name"] == self.account: return account["credentials_url"] raise Exception("No account found") def get_regions(self): out = {} for region in self._get(self.get_credentials_url()): if region["enabled"]: out[region["name"]] = region["credentials_url"] return out def get_credentials(self, region): return self._get(self.get_regions()[region]) def _boto3_session_from_creds(self, creds, region): return boto3.session.Session( aws_access_key_id=creds["access_key"], aws_secret_access_key=creds["secret_key"], aws_session_token=creds["session_token"], region_name=region) def boto3_session_for_region(self, region): return self._boto3_session_from_creds( self.get_credentials(region), region) def iter_regions(self): for region, cred_url in self.get_regions().items(): yield self._boto3_session_from_creds(self._get(cred_url), region) class ConfigBuilder: now = datetime.utcnow() tomorrow = now + timedelta(days=1) @staticmethod def unquote(x): return x.strip('"') @staticmethod def force_iso_date(input): return datetime.fromisoformat(input).isoformat(timespec="seconds") @classmethod def resolve_release(cls, input, cfg): if input: # release is explicitly defined, run with it return input if cfg['version'] == 'edge': return 'edge' # hack to determine release value from version's alpine-base APK pkgs_url = f"https://dl-cdn.alpinelinux.org/alpine/v{cfg['version']}/main/{cfg['arch']}/" try: res = urlopen(pkgs_url) except urllib.error.HTTPError as ex: print(f"Unable to urlopen {pkgs_url} - {ex}", file=sys.stderr) exit(1) line = res.readline().decode('utf-8') while line: if line.startswith('<a href="'): pkg = line.split('"')[1] if pkg.startswith('alpine-base-'): # we got it, use package version as the revision value return pkg.split('-')[2] line = res.readline().decode('utf-8') # didn't find it? raise RuntimeError(f"Unable to parse 'alpine-base' APK from {pkgs_url}") @classmethod def resolve_now(cls): return cls.now.strftime("%Y%m%d%H%M%S") @classmethod def resolve_revision(cls, input, cfg): if input is None or input == "": return cls.resolve_now() return input @classmethod def resolve_tomorrow(cls): return cls.tomorrow.isoformat(timespec="seconds") @classmethod def resolve_end_of_life(cls, input, cfg): if input is None or input == "": return cls.resolve_tomorrow() return input @classmethod def fold_comma(cls, input, cfg): return ",".join([cls.unquote(k) for k in input.keys()]) @classmethod def fold_space(cls, input, cfg): return " ".join([cls.unquote(k) for k in input.keys()]) @classmethod def fold_repos(cls, input, cfg): return "\n".join( f"@{v} {cls.unquote(k)}" if isinstance(v, str) else cls.unquote(k) for k, v in input.items()) @staticmethod def fold_packages(input, cfg): return " ".join( f"{k}@{v}" if isinstance(v, str) else k for k, v in input.items()) @staticmethod def fold_services(input, cfg): return " ".join( "{}={}".format(k, ",".join(v.keys())) for k, v in input.items()) def __init__(self, config_path, out_dir): self.config_path = config_path self.out_dir = out_dir self._keys_to_transform = { "kernel_modules" : self.fold_comma, "kernel_options" : self.fold_space, "initfs_features" : self.fold_space, "repos" : self.fold_repos, "pkgs" : self.fold_packages, "svcs" : self.fold_services, "release" : self.resolve_release, "revision" : self.resolve_revision, "end_of_life" : lambda x, y: \ self.force_iso_date(self.resolve_end_of_life(x, y)), } def build_all(self): for file in glob.glob(os.path.join(self.config_path, "*.conf")): profile = os.path.splitext(os.path.split(file)[-1])[0] self.build_profile(profile) def rel_symlink(self, src_path, dest_dir, dest): os.symlink( os.path.relpath(src_path, dest_dir), os.path.join(dest_dir, dest)) def build_profile(self, profile): build_config = pyhocon.ConfigFactory.parse_file( os.path.join(self.config_path, f"{profile}.conf")) for build, cfg in build_config["BUILDS"].items(): build_dir = os.path.join(self.out_dir, profile, build) setup_dir = os.path.join(build_dir, "setup-ami.d") # Always start fresh shutil.rmtree(build_dir, ignore_errors=True) os.makedirs(setup_dir) # symlink everything in scripts/setup-ami.d for item in os.listdir("scripts/setup-ami.d"): self.rel_symlink(os.path.join("scripts/setup-ami.d", item), setup_dir, item) # symlink additional setup_script if "setup_script" in cfg.keys() and cfg["setup_script"] is not None: self.rel_symlink(cfg["setup_script"], setup_dir, "setup_script") del cfg["setup_script"] if "setup_copy" in cfg.keys() and cfg["setup_copy"] is not None: for dst, src in cfg["setup_copy"].items(): self.rel_symlink(src, setup_dir, dst) del cfg["setup_copy"] cfg["profile"] = profile cfg["profile_build"] = build # Order of operations is important here for k, v in cfg.items(): transform = self._keys_to_transform.get(k) if transform: cfg[k] = transform(v, cfg) if isinstance(v, str) and "{var." in v: cfg[k] = v.format(var=cfg) with open(os.path.join(build_dir, "vars.json"), "w") as out: json.dump(cfg, out, indent=4, separators=(",", ": ")) class BuildAMIs: """Build all AMIs for profile, or specific builds within a profile """ command_name = "amis" @staticmethod def add_args(parser): # NOTE: --use-broker and --region are not mutually exclusive here! parser.add_argument("--use-broker", action="store_true", help="use identity broker to obtain region credentials") parser.add_argument("--region", "-r", default="us-west-2", help="region to use for build") parser.add_argument("profile", metavar="PROFILE", help="name of profile to build") parser.add_argument("builds", metavar="BUILD", nargs="*", help="name of build within a profile (multiple OK)") @staticmethod def get_artifact_id(root, profile, build): manifest_json = os.path.join( root, "build", "profile", profile, build, "manifest.json") with open(manifest_json, "r") as data: manifest = json.load(data) return manifest['builds'][0]['artifact_id'].split(':')[1] def make_amis(self, args, root, log): os.chdir(os.path.join(root, "build")) builds = args.builds or os.listdir( os.path.join("profile", args.profile)) artifacts = [] for build in builds: log.info("\n*** Building %s/%s ***\n\n", args.profile, build) build_dir = os.path.join("profile", args.profile, build) if not os.path.exists(build_dir): log.info("Build dir '%s' does not exist", build_dir) break env = None if args.use_broker: creds = IdentityBrokerClient().get_credentials(args.region) env = { "PATH": os.environ.get("PATH"), "AWS_ACCESS_KEY_ID": creds["access_key"], "AWS_SECRET_ACCESS_KEY": creds["secret_key"], "AWS_SESSION_TOKEN": creds["session_token"], "AWS_DEFAULT_REGION": args.region, } out = io.StringIO() res = subprocess.Popen([ os.environ.get("PACKER", "packer"), "build", f"-var-file={build_dir}/vars.json", "packer.json" ], stdout=subprocess.PIPE, encoding="utf-8", env=env) while res.poll() is None: text = res.stdout.readline() out.write(text) print(text, end="") # input is already colorized if res.returncode == 0: artifacts.append(self.get_artifact_id(root, args.profile, build)) else: if "is used by an existing AMI" in out.getvalue(): continue else: sys.exit(res.returncode) return artifacts def run(self, args, root, log): log.info("Converting packer.conf to JSON...") source = os.path.join(root, "packer.conf") dest = os.path.join(root, "build", "packer.json") pyhocon.converter.HOCONConverter.convert_from_file( source, dest, "json", 2, False) log.info("Resolving profile...") builder = ConfigBuilder( os.path.join(root, "profiles"), os.path.join(root, "build", "profile")) builder.build_profile(args.profile) log.info("Running packer...") amis = self.make_amis(args, root, log) log.info("\n=== DONE ===\n\nNew: " + ' '.join(amis) + "\n") # These are general-purpose methods # iterate over EC2 region clients, whether we're using the broker or not def iter_regions(use_broker, regions): if use_broker: for region in IdentityBrokerClient().iter_regions(): yield region.client('ec2') else: for region in regions: yield boto3.session.Session(region_name=region).client('ec2') def get_image(client, image_id): images = client.describe_images(ImageIds=[image_id], Owners=["self"]) perms = client.describe_image_attribute( Attribute="launchPermission", ImageId=image_id) ami = AMI.from_aws_model(images["Images"][0], region_from_client(client)) ami.aws_permissions = perms["LaunchPermissions"] return ami def get_images_with_tags(client, **tags): images = [] res = client.describe_images(Owners=["self"], Filters=[ {"Name": f"tag:{k}", "Values": [v]} for k, v in tags.items()]) for image in res["Images"]: ami = AMI.from_aws_model(image, region_from_client(client)) perms = client.describe_image_attribute( Attribute="launchPermission", ImageId=ami.image_id) ami.aws_permissions = perms["LaunchPermissions"] images.append(ami) return images def get_image_with_tags(client, **tags): images = get_images_with_tags(client, **tags) if len(images) > 1: raise Exception(f"Too many images for query {tags!r}") elif len(images) == 0: return None else: return images[0] def get_all_images(client): return get_images_with_tags(client) class ReleaseAMIs: """Copy one or more AMIs to other regions and/or set AMI permissions. By default, source AMI permissions are applied to their copies, unless --public, --private, or --allow-account options are specified. If the source AMI's permissions are different than the options provided, its permissions will be updated to match. """ command_name = "release" @staticmethod def add_args(parser): parser.add_argument("--source-region", default="us-west-2", metavar="REGION", help="region of source AMI(s)") rgroup = parser.add_mutually_exclusive_group(required=True) rgroup.add_argument("--use-broker", action="store_true", help="identity broker provides destination regions and credentials") rgroup.add_argument("--region", "-r", action="append", dest="regions", metavar="REGION", help="destination region (multiple OK)") pgroup = parser.add_mutually_exclusive_group() pgroup.add_argument("--public", action="store_true", default=None, help="make source and copied AMIs public") pgroup.add_argument("--private", dest="public", action="store_false", help="make source and copied AMIs private") pgroup.add_argument("--allow-account", dest="allow_accounts", action="append", metavar="ID", help="make source and copied AMIs " "accessible by AWS account id (multiple OK)") parser.add_argument("amis", metavar="AMI", nargs="+", help="AMI id(s) to copy") def get_source_region_client(self, use_broker, source_region): if use_broker: return IdentityBrokerClient().boto3_session_for_region( source_region).client("ec2") else: return boto3.session.Session(region_name=source_region).client( "ec2") def copy_image(self, from_client, to_client, image_id): source = get_image(from_client, image_id) res = to_client.copy_image( Name=source.name, Description=source.description, SourceImageId=source.image_id, SourceRegion=source.region) tags = [ { "Key": "source_ami", "Value": source.image_id, }, { "Key": "source_region", "Value": source.region, } ] tags.extend(source.aws_tags) to_client.create_tags(Resources=[res["ImageId"]], Tags=tags) return get_image(to_client, res["ImageId"]) def has_incorrect_perms(self, image, perms): if (set(image.allowed_groups) != set(perms['groups']) or set(image.allowed_users) != set(perms['users'])): return True def update_image_permissions(self, client, image): client.reset_image_attribute( Attribute="launchPermission", ImageId=image.image_id) client.modify_image_attribute( Attribute="launchPermission", ImageId=image.image_id, LaunchPermission={"Add": image.aws_permissions}) def run(self, args, root, log): source_perms = {} pending_copy = [] pending_perms = [] source_region = args.source_region log.info(f"Source region {source_region}") source_client = self.get_source_region_client( args.use_broker, source_region) # resolve source ami perms, queue for fixing if necessary for ami in args.amis: image = get_image(source_client, ami) if args.public is True: source_perms[ami] = { 'groups': ['all'], 'users': [] } elif args.public is False: source_perms[ami] = { 'groups': [], 'users': [] } elif args.allow_accounts: source_perms[ami] = { 'groups': [], 'users': args.allow_accounts } else: log.warning(f"Will apply {source_region} {ami} permissions to its copies") source_perms[ami] = { 'groups': image.allowed_groups, 'users': image.allowed_users } if self.has_incorrect_perms(image, source_perms[ami]): log.warning(f"Will update source {source_region} {ami} permissions") pending_perms.append((source_client, ami, source_perms[ami])) # Copy image to regions where it's missing, queue images that need # permission fixes log.info('') for client in iter_regions(args.use_broker, args.regions): region_name = region_from_client(client) # For logging # Don't bother copying to source region if region_name == args.source_region: continue log.info(f"Destination region {region_name}...") for ami in args.amis: src_log = f"* source {ami}" image = get_image_with_tags(client, source_ami=ami, source_region=args.source_region) if not image: log.info(f"{src_log} - copying to {region_name}") ami_copy = self.copy_image(source_client, client, ami) pending_copy.append( (client, ami_copy.image_id, source_perms[ami])) elif self.has_incorrect_perms(image, source_perms[ami]): log.info(f"{src_log} - will update {image.image_id} perms") pending_perms.append( (client, image.image_id, source_perms[ami])) else: log.info(f"{src_log} - verified {image.image_id}") log.info('') if pending_copy: # seems to take at least 3m pending_copy.append(('sleep', 180, '')) # Wait for images to copy while pending_copy: client, id, perms = pending_copy.pop(0) # emulate a FIFO queue if client == 'sleep': if not pending_copy: continue log.info(f"Sleeping {id}s...") time.sleep(id) # recheck every 30s pending_copy.append(('sleep', 30, '')) continue region_name = region_from_client(client) # For logging image = get_image(client, id) if image.state != AMIState.AVAILABLE: log.info(f"- copying: {id} ({region_name})") pending_copy.append((client, id, perms)) else: done_log = f"+ completed: {id} ({region_name})" if self.has_incorrect_perms(image, perms): log.info(f"{done_log} - will update perms") pending_perms.append((client, id, perms)) else: log.info(f"{done_log} - verified perms") # Update all permissions for client, id, perms in pending_perms: region_name = region_from_client(client) # For logging log.info(f"% updating perms: {id} ({region_name})") image = get_image(client, id) image.allowed_groups = perms['groups'] image.allowed_users = perms['users'] self.update_image_permissions(client, image) if pending_perms: log.info('') log.info('Release Completed') class Releases: RELEASE_FIELDS = [ 'description', 'profile', 'profile_build', 'version', 'release', 'arch', 'revision', 'creation_date', 'end_of_life' ] def __init__(self, profile=None, use_broker=None, regions=None): self.profile = profile self.tags = { 'profile': profile } self.use_broker = use_broker self.regions = regions self.clients = {} self.reset_images() self.reset_releases() def reset_images(self): self.images = defaultdict(list) def reset_releases(self): self.releases = dictfactory() # TODO: separate Clients class? def iter_clients(self): if not self.clients: for client in iter_regions(self.use_broker, self.regions): region = region_from_client(client) self.clients[region] = client yield (region, client) else: for region, client in self.clients.items(): yield (region, client) # when we're just interested in the profile's images def load_profile_images(self, log=None): for region, client in self.iter_clients(): if log: log.info(f"Loading '{self.profile}' profile images from {region}...") self.images[region] = get_images_with_tags(client, **self.tags) # not belonging to any profile def load_unknown_images(self, log=None): for region, client in self.iter_clients(): if log: log.info(f"Loading unknown images from {region}...") for image in get_all_images(client): if 'profile' not in image.tags: self.images[region].append(image) # build profile releases object based on loaded self.images def build_releases(self, log=None, trim=None): now = datetime.utcnow() versions = dictfactory() for region, amis in self.images.items(): if log: log.info(f"{region}") for ami in amis: eol = datetime.fromisoformat(ami.end_of_life) # if we're trimming, we're not interested in EOL images if trim and eol < now: continue version = ami.version release = ami.release build = ami.profile_build name = ami.name id = ami.image_id build_time = int(dateutil.parser.parse(ami.creation_date).strftime('%s')) if log: log.info(f" * {ami.image_id} {ami.name}") version_obj = versions[version][release][build][name] for field in self.RELEASE_FIELDS: if field not in version_obj: version_obj[field] = getattr(ami, field) # ensure earliest build_time is used if ('build_time' not in version_obj or build_time < version_obj['build_time']): version_obj['build_time'] = build_time version_obj['creation_date'] = ami.creation_date version_obj['artifacts'][region] = id for version, releases in versions.items(): for release, builds in sorted(releases.items(), reverse=True, key=lambda x: sortable_version(x[0])): for build, revisions in builds.items(): for revision, info in sorted(revisions.items(), reverse=True, key=lambda x: x[1]['build_time']): self.releases[release][build][revision] = info # if we are trimming, we want only the most recent revisions if trim: break # if we are trimming releases, we want only the most recent release if trim == 'release': break class ReleasesYAML: """Update releases/<profile>.yaml with profile's currently existing AMIs """ command_name = "release-yaml" @staticmethod def add_args(parser): TRIM_HELP=""" revision = keep last x.y.z-r# of non-EOL releases, release = keep last x.y.# of non-EOL versions """ rgroup = parser.add_mutually_exclusive_group(required=True) rgroup.add_argument("--use-broker", action="store_true", help="identity broker provides destination regions and credentials") rgroup.add_argument("--region", "-r", action="append", dest="regions", metavar="REGION", help="destination region (multiple OK)") parser.add_argument("--trim", "-t", choices=['revision','release'], help=TRIM_HELP) parser.add_argument("profile", metavar="PROFILE", help="profile name") def run(self, args, root, log): release_dir = os.path.join(root, 'releases') if not os.path.exists(release_dir): os.makedirs(release_dir) release_yaml = os.path.join(release_dir, f"{args.profile}.yaml") r = Releases( profile = args.profile, use_broker = args.use_broker, regions = args.regions) r.load_profile_images(log) r.build_releases(trim=args.trim) log.info(f"Writing new {release_yaml}") with open(release_yaml, 'w') as data: yaml.dump(undictfactory(r.releases), data, sort_keys=False) class ReleasesReadme: """Build releases/README_<profile>.md from releases/<profile>.yaml """ command_name = "release-readme" SECTION_TPL = textwrap.dedent(""" ### Alpine Linux {release} ({date}) <details><summary><i>click to show/hide</i></summary><p> {rows} </p></details> """) AMI_TPL = ( " [{id}](https://{r}.console.aws.amazon.com/ec2/home" "#Images:visibility=public-images;imageId={id}) " "([launch](https://{r}.console.aws.amazon.com/ec2/home" "#launchAmi={id})) |" ) @staticmethod def add_args(parser): parser.add_argument("profile", metavar="PROFILE", help="profile name") @staticmethod def extract_ver(x): return sortable_version(x['release']) def resolve_sections(self, release_data, log): sects = dictfactory() for release, builds in sorted(release_data.items(), reverse=True): version = '.'.join(release.split('.')[0:2]) if version in sects: continue for build, revisions in builds.items(): ver = sects[version] ver['release'] = release name, info = sorted( revisions.items(), key=lambda x: x[1]['build_time'], reverse=True)[0] if name in ver['builds']: log.warning( f"Duplicate AMI '{name}' in builds " f"'{info['profile_build']} and " f"'{ver['builds'][name]['build']}") ver['builds'][name] = { 'build': info['profile_build'], 'built': int(info['build_time']), 'amis': info['artifacts'] } self.sections = sorted( undictfactory(sects).values(), key=self.extract_ver, reverse=True) def get_ami_markdown(self): ami_list = "## AMIs\n" for section in self.sections: built = 0 regions = [] rows = ["| Region |", "| ------ |"] for name, info in sorted(section['builds'].items()): rows[0] += f" {name} |" rows[1] += " --- |" regions = set(regions) | set(info['amis'].keys()) built = max(built, info['built']) for region in sorted(regions): row = f"| {region} |" for name, info in sorted(section['builds'].items()): amis = info['amis'] if region in amis: row += self.AMI_TPL.format(r=region, id=amis[region]) else: row += ' |' rows.append(row) ami_list += self.SECTION_TPL.format( release=section['release'].capitalize(), date=datetime.utcfromtimestamp(built).date(), rows="\n".join(rows)) return ami_list def run(self, args, root, log): profile = args.profile release_dir = os.path.join(root, "releases") profile_file = os.path.join(release_dir, f"{profile}.yaml") with open(profile_file, "r") as data: self.resolve_sections(yaml.safe_load(data), log) ami_markdown = self.get_ami_markdown() readme = "" readme_md = os.path.join(release_dir, f"README_{profile}.md") action = "Updated" if os.path.exists(readme_md): with open(readme_md, "r") as file: readme = file.read() else: action = "Created" re_images = re.compile(r"## AMIs.*\Z", flags=re.DOTALL) if re_images.search(readme): readme = re_images.sub(ami_markdown, readme) else: log.warning("appending") readme += "\n" + ami_markdown with open(readme_md, "w") as file: file.write(readme) log.info(f"{action} {readme_md}") class PruneAMIs: """Prune Released AMIs """ command_name = "prune" @staticmethod def add_args(parser): LEVEL_HELP = """ revision = x.y.z-r#, release = x.y.#, end-of-life = EOL versions (#.#), UNKNOWN = AMIs with no profile tag """ parser.add_argument("level", choices=["revision", "release", "end-of-life", "UNKNOWN"], help=LEVEL_HELP) rgroup = parser.add_mutually_exclusive_group(required=True) rgroup.add_argument("--use-broker", action="store_true", help="use identity broker to obtain per-region credentials") rgroup.add_argument("--region", "-r", metavar='REGION', dest='regions', action="append", help="regions to prune, may be specified multiple times") parser.add_argument("profile", metavar='PROFILE', help="profile to prune") parser.add_argument("builds", metavar='BUILD', nargs="*", help="build(s) within profile to prune") agroup = parser.add_mutually_exclusive_group() agroup.add_argument( '--keep', metavar='NUM', type=int, default=0, help='keep NUM most-recent additional otherwise-pruneable per LEVEL') agroup.add_argument('--defer-eol', metavar='DAYS', type=int, default=0, help='defer end-of-life pruning for additional days') parser.add_argument( '--no-pretend', action='store_true', help='actually prune images') @staticmethod def check_args(args): if args.level != 'end-of-life' and args.defer_eol != 0: return ["--defer-eol may only be used with 'end-of-life' pruning."] if args.keep < 0: return ["Only non-negative integers are valid for --keep."] def __init__(self): self.pruneable = dictfactory() def find_pruneable(self, r, args, log): level = args.level builds = args.builds keep = args.keep defer_eol = args.defer_eol now = datetime.utcnow() - timedelta(days=args.defer_eol) # build releases from profile images r.load_profile_images(log) r.build_releases() # scan for pruning criteria criteria = dictfactory() for release, rdata in r.releases.items(): for build, bdata in rdata.items(): if builds and build not in builds: continue for ami_name, info in bdata.items(): version = info['version'] built = info['build_time'] eol = datetime.fromisoformat(info['end_of_life']) # default: level == 'release' basis = version if level == 'revision': basis = release elif level == 'end-of-life': # not enough in common with revision/release if build not in criteria[version]: criteria[version][build] = [now] if eol < now and eol not in criteria[version][build]: criteria[version][build].append(eol) criteria[version][build].sort(reverse=True) continue # revsion/release have enough commonality if build not in criteria[basis]: criteria[basis][build] = [built] elif built not in criteria[basis][build]: criteria[basis][build].append(built) criteria[basis][build].sort(reverse=True) # scan again to determine what doesn't make the cut for release, rdata in r.releases.items(): for build, bdata in rdata.items(): if builds and build not in builds: continue for ami_name, info in bdata.items(): version = info['version'] built = info['build_time'] eol = datetime.fromisoformat(info['end_of_life']) # default: level == 'release' basis = version value = built if level == 'revision': basis = release elif level == 'end-of-life': value = eol c = criteria[basis][build] if keep < len(c) and value < c[keep]: for region, ami in info['artifacts'].items(): self.pruneable[region][ami] = { 'name': ami_name, } # populate AMI creation_date and snapshot_id from Release().images for region, images in r.images.items(): for image in images: if image.image_id in self.pruneable[region]: p = self.pruneable[region][image.image_id] p['name'] = image.name p['creation_date'] = dateutil.parser.parse( image.creation_date).strftime('%Y-%m-%d') p['snapshot_id'] = image.snapshot_id def all_unknown_pruneable(self, r, log): r.load_unknown_images(log) for region, images in r.images.items(): for image in images: self.pruneable[region][image.image_id] = { 'name': image.name, 'creation_date': dateutil.parser.parse( image.creation_date).strftime('%Y-%m-%d'), 'snapshot_id': image.snapshot_id } def run(self, args, root, log): # instantiate Releases object r = Releases( profile=args.profile, use_broker=args.use_broker, regions=args.regions) if args.level == 'UNKNOWN': self.all_unknown_pruneable(r, log) else: self.find_pruneable(r, args, log) for region, amis in sorted(self.pruneable.items()): r_str = f"{args.level} AMIs in {region}" if not amis: log.info(f"No pruneable {r_str}.") continue if args.no_pretend: log.error(f"REMOVING {r_str}:") else: log.warning(f"Removable {r_str}:") for ami, info in sorted(amis.items(), key=lambda x: x[1]['creation_date']): a_str = f" * {ami} ({info['creation_date']}) {info['name']}" if args.no_pretend: log.warning(a_str) r.clients[region].deregister_image(ImageId=ami) r.clients[region].delete_snapshot(SnapshotId=info['snapshot_id']) else: log.info(a_str) def find_repo_root(): """Find the root of the repo, which contains a .git folder """ path = os.getcwd() while ".git" not in set(os.listdir(path)) and path != "/": path = os.path.dirname(path) if path == "/": raise Exception("No repo found, stopping at /") return path def main(): """An introspective main method Just some silly metaprogramming to make commands really easy to write and to avoid needing to hand register them. Commands have a specific interface, per below, but should be really easy to create and will be auto discovered. Commands are objects that have the following attributes: __doc__ (python docstring) used as help text in the CLI command_name (string) name of the command as invoked by the cli add_args(parser) (class or static method) passed an argparse subparser at setup time that will ultimately handle the arguments for the command at runtime. Should add any configuration necessary for the command to use later. Must not rely on object state as it is not invoked with an instance of the object. check_args(self, args) (class method, optional) passed the set of arguments that were parsed before the command was invoked. This function should return a list of errors or None. Non-empty lists will cause the command to not be executed and help being printed. run(self, args, root, log) (instance method) passed the arguments object as parsed by argparse as well as a string indicating the root of the repository (the folder containing the .git folder) and an instance of a stanard libary logger for output. Should throw exceptions on error and return when completed. Should *not* execute sys.exit """ dispatch = {} parser = argparse.ArgumentParser() subs = parser.add_subparsers(dest="command_name", required=True) # Configure logger logger = logging.getLogger() handler = logging.StreamHandler() handler.setFormatter(ColoredFormatter(fmt="%(message)s")) logger.addHandler(handler) logger.setLevel(logging.INFO) for command in sys.modules[__name__].__dict__.values(): if not hasattr(command, "command_name"): continue dispatch[command.command_name] = command() doc = getattr(command, "__doc__", "") subparser = subs.add_parser( command.command_name, help=doc, description=doc) add_args = getattr(command, "add_args", None) if add_args: command.add_args(subparser) args = parser.parse_args() command = dispatch[args.command_name] errors = getattr(command, "check_args", lambda x: [])(args) if errors: logger.error("\n".join(errors)) # Ugly hack, gets the help for the subcommand, no public API for this parser._actions[1]._name_parser_map[args.command_name].print_help() else: command.run(args, find_repo_root(), logger) if __name__ == "__main__": main() <file_sep>#!/bin/sh # vim: set ts=4 et: set -eu DEVICE=/dev/xvdf TARGET=/mnt/target SETUP=/tmp/setup-ami.d [ "$VERSION" = 'edge' ] && V= || V=v MAIN_REPO="https://dl-cdn.alpinelinux.org/alpine/$V$VERSION/main/$ARCH" die() { printf '\033[1;31mERROR:\033[0m %s\n' "$@" >&2 # bold red exit 1 } einfo() { printf '\n\033[1;36m> %s\033[0m\n' "$@" >&2 # bold cyan } rc_add() { runlevel="$1"; shift # runlevel name services="$*" # names of services for svc in $services; do mkdir -p "$TARGET/etc/runlevels/$runlevel" ln -s "/etc/init.d/$svc" "$TARGET/etc/runlevels/$runlevel/$svc" echo " * service $svc added to runlevel $runlevel" done } validate_block_device() { lsblk -P --fs "$DEVICE" >/dev/null 2>&1 || \ die "'$DEVICE' is not a valid block device" if lsblk -P --fs "$DEVICE" | grep -vq 'FSTYPE=""'; then die "Block device '$DEVICE' is not blank" fi } main_repo_pkgs() { wget -T 10 -q -O - "$MAIN_REPO/" | grep '^<a href=' | cut -d\" -f2 } fetch_apk_tools() { store="$(mktemp -d)" tarball="$(main_repo_pkgs | grep ^apk-tools-static- | sort -V | tail -n 1)" wget -T 10 -q -O "$store/$tarball" "$MAIN_REPO/$tarball" tar -C "$store" --warning=no-unknown-keyword -xf "$store/$tarball" find "$store" -name apk.static } # mostly from Alpine's /sbin/setup-disk setup_partitions() { start=2M # Needed to align EBS partitions line= # create new partitions ( for line in "$@"; do case "$line" in 0M*) ;; *) echo "$start,$line"; start= ;; esac done ) | sfdisk --quiet --label gpt "$DEVICE" # we assume that the build host will create the new devices within 5s tries=5 while [ ! -e "${DEVICE}1" ]; do [ $tries -eq 0 ] && break sleep 1 tries=$(( tries - 1 )) done [ -e "${DEVICE}1" ] || die "Expected new device ${DEVICE}1 not created" } make_filesystem() { root_dev="$DEVICE" if [ "$BOOTLOADER" = grub-efi ] || [ "$BOOTLOADER" = EFI_STUB ]; then # create a small EFI partition (remainder for root) if [ "$BOOTLOADER" = EFI_STUB ]; then setup_partitions '11M,U,*' ',L' # kernel + initfs else setup_partitions '512K,U,*' ',L' # currently 278K used fi root_dev="${DEVICE}2" mkfs.vfat -n EFI "${DEVICE}1" fi mkfs.ext4 -O ^64bit -L / "$root_dev" mount "$root_dev" "$TARGET" if [ "$BOOTLOADER" = grub-efi ] || [ "$BOOTLOADER" = EFI_STUB ]; then # mount small EFI partition mkdir -p "$TARGET/boot/efi" mount -t vfat "${DEVICE}1" "$TARGET/boot/efi" fi } setup_repositories() { mkdir -p "$TARGET/etc/apk/keys" echo "$REPOS" > "$TARGET/etc/apk/repositories" } fetch_keys() { tmp="$(mktemp -d)" tarball="$(main_repo_pkgs | grep ^alpine-keys- | sort -V | tail -n 1)" wget -T 10 -q -O "$tmp/$tarball" "$MAIN_REPO/$tarball" tar -C "$TARGET" --warning=no-unknown-keyword -xvf "$tmp/$tarball" etc/apk/keys rm -rf "$tmp" } install_base() { $apk add --root "$TARGET" --no-cache --initdb alpine-base # verify release matches if [ "$VERSION" != edge ]; then ALPINE_RELEASE=$(cat "$TARGET/etc/alpine-release") [ "$RELEASE" = "$ALPINE_RELEASE" ] || \ die "Release '$RELEASE' does not match /etc/alpine-release: $ALPINE_RELEASE" fi } setup_chroot() { mount -t proc none "$TARGET/proc" mount --bind /dev "$TARGET/dev" mount --bind /sys "$TARGET/sys" # Needed for bootstrap, will be removed in the cleanup stage. install -Dm644 /etc/resolv.conf "$TARGET/etc/resolv.conf" } install_core_packages() { chroot "$TARGET" apk --no-cache add $PKGS # EFI_STUB requires no bootloader [ "$BOOTLOADER" = EFI_STUB ] || \ chroot "$TARGET" apk --no-cache add --no-scripts "$BOOTLOADER" # Disable starting getty for physical ttys because they're all inaccessible # anyhow. With this configuration boot messages will still display in the # EC2 console. sed -Ei '/^tty[0-9]/s/^/#/' "$TARGET/etc/inittab" # Enable the getty for the serial terminal. This will show the login prompt # in the get-console-output API that's accessible by the CLI and the web # console. sed -Ei '/^#ttyS0:/s/^#//' "$TARGET/etc/inittab" # Make it a little more obvious who is logged in by adding username to the # prompt sed -i "s/^export PS1='/&\\\\u@/" "$TARGET/etc/profile" } setup_mdev() { install -o root -g root -Dm755 -t "$TARGET/lib/mdev" \ "$SETUP/nvme-ebs-links" \ "$SETUP/eth-eni-hotplug" # insert nvme ebs mdev configs just above "# fallback" comment sed -n -i \ -e "/# fallback/r $SETUP/etc/mdev-ec2.conf" \ -e 1x -e '2,${x;p}' -e '${x;p}' \ "$TARGET/etc/mdev.conf" } create_initfs() { sed -Ei "s/^features=\"([^\"]+)\"/features=\"\1 $INITFS_FEATURES\"/" \ "$TARGET/etc/mkinitfs/mkinitfs.conf" chroot "$TARGET" /sbin/mkinitfs $(basename $(find "$TARGET/lib/modules/"* -maxdepth 0)) } install_bootloader() { case "$BOOTLOADER" in syslinux) install_extlinux ;; grub-efi) install_grub_efi ;; EFI_STUB) install_EFI_STUB ;; *) die "unknown bootloader '$BOOTLOADER'" ;; esac } install_extlinux() { # Must use disk labels instead of UUID or devices paths so that this works # across instance familes. UUID works for many instances but breaks on the # NVME ones because EBS volumes are hidden behind NVME devices. # # Enable ext4 because the root device is formatted ext4 # # Shorten timeout (1/10s) as EC2 has no way to interact with instance console # # ttyS0 is the target for EC2s "Get System Log" feature whereas tty0 is the # target for EC2s "Get Instance Screenshot" feature. Enabling the serial # port early in extlinux gives the most complete output in the system log. sed -Ei -e "s|^[# ]*(root)=.*|\1=LABEL=/|" \ -e "s|^[# ]*(default_kernel_opts)=.*|\1=\"$KERNEL_OPTS\"|" \ -e "s|^[# ]*(serial_port)=.*|\1=ttyS0|" \ -e "s|^[# ]*(modules)=.*|\1=$KERNEL_MODS|" \ -e "s|^[# ]*(default)=.*|\1=virt|" \ -e "s|^[# ]*(timeout)=.*|\1=1|" \ "$TARGET/etc/update-extlinux.conf" chroot "$TARGET" /sbin/extlinux --install /boot chroot "$TARGET" /sbin/update-extlinux --warn-only } install_grub_efi() { [ -d "/sys/firmware/efi" ] || die "/sys/firmware/efi does not exist" case "$ARCH" in x86_64) grub_target=x86_64-efi ; fwa=x64 ;; aarch64) grub_target=arm64-efi ; fwa=aa64 ;; *) die "ARCH=$ARCH is currently unsupported" ;; esac # disable nvram so grub doesn't call efibootmgr chroot "$TARGET" /usr/sbin/grub-install --target="$grub_target" --efi-directory=/boot/efi \ --bootloader-id=alpine --boot-directory=/boot --no-nvram # fallback mode install -D "$TARGET/boot/efi/EFI/alpine/grub$fwa.efi" "$TARGET/boot/efi/EFI/boot/boot$fwa.efi" # install default grub config install -o root -g root -Dm644 -t "$TARGET/etc/default" \ "$SETUP/etc/grub" # generate/install new config chroot "$TARGET" grub-mkconfig -o /boot/grub/grub.cfg } install_EFI_STUB() { [ -d "/sys/firmware/efi" ] || die "/sys/firmware/efi does not exist" case "$ARCH" in x86_64) fwa=x64 ;; aarch64) fwa=aa64 ;; *) die "ARCH=$ARCH is currently unsupported" ;; esac # TODO: kernel modules/options? # TODO: will also need initfs in here too # TODO: make it work # install kernel as UEFI fallback install -o root -g root -Dm644 "$TARGET/boot/vmlinuz-virt" \ "$TARGET/boot/efi/EFI/boot/boot$fwa.efi" # replace original with a symlink rm "$TARGET/boot/vmlinuz-virt" ln -s "efi/EFI/boot/boot$fwa.efi" "$TARGET/boot/vmlinuz-virt" } setup_fstab() { install -o root -g root -Dm644 -t "$TARGET/etc" \ "$SETUP/etc/fstab" # if we're using an EFI bootloader, add extra line for EFI partition if [ "$BOOTLOADER" = grub-efi ] || [ "$BOOTLOADER" = EFI_STUB ]; then cat "$SETUP/etc/fstab.grub-efi" >> "$TARGET/etc/fstab" fi } setup_networking() { # configure standard interfaces IFACE_CFG="$TARGET/etc/network/interfaces" install -o root -g root -Dm755 -d "$SETUP/etc/interfaces.d" "$IFACE_CFG.d" install -o root -g root -Dm644 -t "$IFACE_CFG.d" \ "$SETUP/etc/interfaces.d/"* cat "$IFACE_CFG.d/lo" "$IFACE_CFG.d/eth0" > "$IFACE_CFG" install -o root -g root -Dm755 -t "$TARGET/etc/network" \ "$SETUP/assemble-interfaces" # install ucdhcp hooks for EC2 ENI IPv6 and secondary IPv4 install -o root -g root -Dm755 -t "$TARGET/usr/share/udhcpc" \ "$SETUP/eth-eni-hook" for i in post-bound post-renew; do mkdir -p "$TARGET/etc/udhcpc/$i" ln -sf /usr/share/udhcpc/eth-eni-hook \ "$TARGET/etc/udhcpc/$i" done # install ENI interface setup init script install -o root -g root -Dm755 -t "$TARGET/etc/init.d" \ "$SETUP/eth-eni-setup" } enable_services() { for lvl_svcs in $SVCS; do rc_add $(echo "$lvl_svcs" | tr '=,' ' ') done } create_alpine_user() { # Allow members of the wheel group to sudo without a password. By default # this will only be the alpine user. This allows us to ship an AMI that is # accessible via SSH using the user's configured SSH keys (thanks to # tiny-ec2-bootstrap) but does not allow remote root access which is the # best-practice. sed -i '/%wheel .* NOPASSWD: .*/s/^# //' "$TARGET/etc/sudoers" # explicitly lock the root account chroot "$TARGET" /usr/bin/passwd -l root # There is no real standard ec2 username across AMIs, Amazon uses ec2-user # for their Amazon Linux AMIs but Ubuntu uses ubuntu, Fedora uses fedora, # etc... (see: https://alestic.com/2014/01/ec2-ssh-username/). So our user # and group, by default, are alpine because this is Alpine Linux. user="${EC2_USER:-alpine}" chroot "$TARGET" /usr/sbin/addgroup "$user" chroot "$TARGET" /usr/sbin/adduser -h "/home/$user" -s /bin/sh -G "$user" -D "$user" chroot "$TARGET" /usr/sbin/addgroup "$user" wheel chroot "$TARGET" /usr/bin/passwd -u "$user" # Let tiny-ec2-bootstrap know what the EC2 user of the AMI is echo "EC2_USER=$user" > "$TARGET/etc/conf.d/tiny-ec2-bootstrap" } configure_ntp() { # EC2 provides an instance-local NTP service syncronized with GPS and # atomic clocks in-region. Prefer this over external NTP hosts when running # in EC2. # # See: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html sed -e 's/^pool /server /' \ -e 's/pool.ntp.org/169.254.169.123/g' \ -i "$TARGET/etc/chrony/chrony.conf" } setup_script() { if [ -f "$SETUP/setup_script" ]; then einfo "Executing additional setup script" ( cd "$SETUP" chmod u+x ./setup_script TARGET="$TARGET" ./setup_script ) else einfo "No additional setup script" fi } cleanup() { # Sweep cruft out of the image that doesn't need to ship or will be # re-generated when the image boots rm -f \ "$TARGET/var/cache/apk/"* \ "$TARGET/etc/resolv.conf" \ "$TARGET/root/.ash_history" \ "$TARGET/etc/"*- # unmount extra EFI mount if [ "$BOOTLOADER" = grub-efi ] || [ "$BOOTLOADER" = EFI_STUB ]; then umount "$TARGET/boot/efi" fi umount \ "$TARGET/dev" \ "$TARGET/proc" \ "$TARGET/sys" umount "$TARGET" } main() { validate_block_device [ -d "$TARGET" ] || mkdir "$TARGET" einfo "Fetching static APK tools" apk="$(fetch_apk_tools)" einfo "Creating root filesystem" make_filesystem einfo "Configuring Alpine repositories" setup_repositories einfo "Fetching Alpine signing keys" fetch_keys einfo "Installing base system" install_base setup_chroot einfo "Installing core packages" install_core_packages einfo "Configuring and enabling '$BOOTLOADER' boot loader" create_initfs install_bootloader einfo "Configuring system" setup_mdev setup_fstab setup_networking enable_services create_alpine_user configure_ntp setup_script einfo "All done, cleaning up" cleanup } main "$@" <file_sep># Profiles Profiles are collections of related build definitions, which are used to generate the `vars.json` files that [Packer](https://packer.io) consumes when building AMIs. Profiles use [HOCON](https://github.com/lightbend/config/blob/master/HOCON.md) (Human-Optimized Config Object Notation) which allows importing common configs from other files, simple variable interpolation, and easy merging of objects. This flexibility helps keep configuration for related build targets [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). ## Core Profiles Core profile configurations are found in the `base`, `version`, and `arch` subdirectories. Core profiles do not have a `.conf` suffix because they're not meant to be directly used like target profiles with the `builder.py` script. Base core profiles define all build vars with default values -- those left empty or null are usually set in version, arch, or target profile configs. Base profiles are included in version profiles, and do not need to be included in target profiles. Version core profiles expand on the base profile they include, and set the `version`, `release`, `end_of_life` (if known), and the associated Alpine Linux `repos`. Arch core profiles further define architecture-specific variables, such as which `apk-tools` and `alpine-keys` to use (and their SHA256 checksums). ## Target Profiles Target profiles, defined in this directory, are the top-level configuration used with `./scripts/builder.py`; they must have a `.conf` suffix. Several configuration objects are defined and later merged within the `BUILDS` object, ultimately defining each individual build. Simple profiles have an object that loads a "version" core profile and another that loads an "arch" core profile. A more complicated version-arch matrix profile would have an object for each version and arch. Additionally, there are one or more objects that define profile-specific settings. The `BUILDS` object's elements merge core and profile configs (with optional inline build settings) into named build definitions; these build names can be used to specify a subset of a profile's builds, for example: `./scripts/builder.py amis <profile> <build1> <build2> ...` **Please note that merge order matters!** The merge sequence is version --> architecture --> profile --> build. ## Customization If the AWS configuration you're using does not specify a default region, your custom profile will need to specify `build_region`. If the build region does not have a default VPC, you'll need to specify `build_subnet`. `version` and `release` are meant to match Alpine; however, `revision` is used used to track changes to the profile, additions of new [alpine-ec2-ami](https://github.com/mcrute/alpine-ec2-ami) features, or other situations where the AMIs needs to be rebuilt. The "edge" core version profile sets `revision` to null, which translates into the current datetime. Otherwise, the default set in the base profile is `r0`. You will probably want to personalize the name and description of your AMI. Set `ami_name_prefix` and `ami_name_suffix`; setting `ami_desc_suffix` and `ami_desc_suffix` is optional. Set `build_instance_type` if you want/need to use a different instance type to build the image; the default is `t3.nano`. If 1 GiB is not enough to install the packages in your base AMI, you can set the `ami_volume_size` to the number of GiB you need. Note, however, that the [tiny-ec2-bootstrap](https://github.com/mcrute/tiny-ec2-bootstrap) init script will expand the root partition to use the instance's entire EBS root volume during the first boot, so you shouldn't need to make space for anything other than installed packages. Set `ami_encrypt` to "true" to create an encrypted AMI image. Launching images from an encrypted AMI results in an encrypted EBS root volume. Please note that if your AMI is encrypted, only the owning account will be able to use it. _*NOTE*: The following funcitonality that is currently not operational -- it is pending completion and integration of a new release tool. In the meantime, you will have to manually copy AMIs from the build region to other regions._ To copy newly built AMIs to regions other than the `build_region` region, set `ami_regions`. This variable is a *hash*, which allows for finer control over inherited values when merging configs. Region identifiers are the keys, a value of `true` means the AMI should be copied to that region; `null` or `false` indicate that it shouldn't be copied to that region. If you want to ensure that the `ami_regions` hash does not inherit any values, set it to `null` before configuring your regions. For example: ``` ami_regions = null # don't inherit any previous values ami_regions { us-west-2 = true eu-north-1 = true } ``` By default, the AMIs built are accessible only by the owning account. To make your AMIs publicly available, set the `ami_access` hash variable: ``` ami_access { all = true } ``` Controlling what packages are installed and enabled in the AMI is the number one reason for creating custom profile. The `repos`, `pkgs`, and `svcs` hash variables serve precisely that purpose. With some exceptions (noted below), they work the same as the `ami_regions` hash: `true` values enable, `false` and `null` values disable, and inherited values can be cleared by first setting the variable itself to `null`. With `repos`, the keys are double-quoted URLs to the `apk` repos that you want set up; these are initially set in the "version" core profiles. In addition to the `true`, `false`, and `null` values, you can also use a "repo alias" string value, allowing you to pin packages to be sourced from that particular repo. For example, with a profile based from a non-edge core profile, you may want to be able to pull packages from the edge testing repo: ``` repos { "http://dl-cdn.alpinelinux.org/alpine/edge/testing" = "edge-testing" } ``` The `pkgs` hash's default is set in the base core profile; its keys are simply the Alpine package to install (or not install, if the value is `false` or `null`). A `true` value installs the package from the default repos; if the value is a repo alias string, the package will be pinned to explicitly install from that repo. For example: ``` pkgs { # install docker-compose from edge-testing repo docker-compose = "edge-testing" } ``` To control when (or whether) a system service starts, use the `svcs` hash variable. Its first-level keys are names of runlevels (`sysinit`, `boot`, `default`, and `shutown`), and the second-level keys are the services, as they appear in `/etc/init.d`. Like the other profile hash variables, setting `false` or `null` disable the service in the runlevel, `true` will enable the service. Further customization can be done by specifying your own setup script with the `setup_script` profile variable. This will be copied to the build instance at `/tmp/setup-ami.d/setup_script`, and executed by the `setup-ami` script just before the final cleanup phase. If there are additional data or scripts that your setup script uses, use the `setup_copy` hash variable -- the key is the destination path under the build instance's `/tmp/setup-ami.d` directory, and the value is the local path to the source file or directory. No data is automatically installed in the AMI, and no additional scripts are executed -- you must explicitly install/execute via the `setup_script` script. The AMI's default login user is `alpine`. If you want to specify a alternate login, set it with the `ami_user` profile variable. This setting is saved in `/etc/conf.d/tiny-ec2-bootstrap` as `EC2_USER` and [tiny-ec2-bootstrap](https://github.com/mcrute/tiny-ec2-bootstrap) will use that valie instead of `alpine`. ## Limitations and Caveats * Hash variables that are reset to clear inherited values *must* be re-defined as a hash, even if it is to remain empty: ``` hash_var = null # drops inherited values hash_var {} # re-defines as an empty hash ``` <file_sep># Alpine Linux EC2 AMIs These are the official Alpine AWS AMIs. For an index of images see the [Alpine Website](https://alpinelinux.org/cloud/). These AMIs should work with most EC2 features -- such as ENIs (Elastic Network Interfaces) and NVMe EBS (Elastic Block Storage) volumes. If you find any problems launching these AMIs on current generation instances, please open an [issue](https://github.com/mcrute/alpine-ec2-ami/issues) and include as much detailed information as possible. All AMIs built after 2020-09-15 include support for hot-pluggable ENIs, and will sync all associated IPv6 and secondary IPv4 addresses during `udhcpc` post-bound and post-renew events. Starting with Alpine release 3.12.1, IMDSv2 (Instance MetaData Service v2) is fully supported, and `aarch64` AMIs are provided for EC2 ARM-based instances. During the *first boot* of instances created with these AMIs, the lightweight [tiny-ec2-bootstrap](https://github.com/mcrute/tiny-ec2-bootstrap) init script... - sets the instance's hostname, - installs the SSH authorized_keys for the AMI user (default 'alpine'), - disables 'root' and AMI user (default 'alpine') passwords, - expands the root partition to use all available EBS volume space, - and executes a "user data" script (must be a shell script that starts with `#!`) If you launch these AMIs to build other images (via [Packer](https://packer.io), etc.), don't forget to remove `/var/lib/cloud/.bootstrap-complete` -- otherwise instances launched from those second-generation AMIs will not run `tiny-ec2-bootstrap` on their first boot. The more popular [cloud-init](https://cloudinit.readthedocs.io/en/latest/) is currently not supported on Alpine Linux. If `cloud-init` support is important to you, please open an [issue](https://github.com/mcrute/alpine-ec2-ami/issues). ***These AMIs are also available by visiting https://alpinelinux.org/cloud*** ## AMIs ### Alpine Linux 3.13.5 (2021-04-15) <details><summary><i>click to show/hide</i></summary><p> | Region | alpine-ami-3.13.5-aarch64-r0 | alpine-ami-3.13.5-x86_64-r0 | | ------ | --- | --- | | af-south-1 | [ami-030d3dc1fe244dd57](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-030d3dc1fe244dd57) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-030d3dc1fe244dd57)) | [ami-0441b82fd3fb48433](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0441b82fd3fb48433) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0441b82fd3fb48433)) | | ap-east-1 | [ami-06a456f57c8505d62](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06a456f57c8505d62) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-06a456f57c8505d62)) | [ami-0e2d8dfaf125a7631](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e2d8dfaf125a7631) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0e2d8dfaf125a7631)) | | ap-northeast-1 | [ami-0c59fa324a698444e](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c59fa324a698444e) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0c59fa324a698444e)) | [ami-02fb62943caac3c71](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02fb62943caac3c71) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-02fb62943caac3c71)) | | ap-northeast-2 | [ami-01ca3b67a65eb6919](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-01ca3b67a65eb6919) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-01ca3b67a65eb6919)) | [ami-038fc3b2d886b83ce](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-038fc3b2d886b83ce) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-038fc3b2d886b83ce)) | | ap-northeast-3 | [ami-067123573f7c9d51a](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-067123573f7c9d51a) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-067123573f7c9d51a)) | [ami-0678e9272dbb276a1](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0678e9272dbb276a1) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0678e9272dbb276a1)) | | ap-south-1 | [ami-0162c60e22df30210](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0162c60e22df30210) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0162c60e22df30210)) | [ami-0c0073e10ee3a5b66](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c0073e10ee3a5b66) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0c0073e10ee3a5b66)) | | ap-southeast-1 | [ami-0dcbd800f660da8f7](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0dcbd800f660da8f7) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0dcbd800f660da8f7)) | [ami-07c71c29e8cfef967](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-07c71c29e8cfef967) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-07c71c29e8cfef967)) | | ap-southeast-2 | [ami-04710a38d0268afa2](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-04710a38d0268afa2) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-04710a38d0268afa2)) | [ami-039c2e2595e9da7fc](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-039c2e2595e9da7fc) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-039c2e2595e9da7fc)) | | ca-central-1 | [ami-0371786a6b356af22](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0371786a6b356af22) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0371786a6b356af22)) | [ami-0a464816128999904](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a464816128999904) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a464816128999904)) | | eu-central-1 | [ami-0be980c74d002c93d](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0be980c74d002c93d) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0be980c74d002c93d)) | [ami-0d6ad9b3597da40c4](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d6ad9b3597da40c4) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0d6ad9b3597da40c4)) | | eu-north-1 | [ami-0b356504ff165dd60](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b356504ff165dd60) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b356504ff165dd60)) | [ami-03cb5b21303291be4](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-03cb5b21303291be4) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-03cb5b21303291be4)) | | eu-south-1 | [ami-04f8023beeed567c5](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-04f8023beeed567c5) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-04f8023beeed567c5)) | [ami-02bd65e399a33d2c0](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02bd65e399a33d2c0) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-02bd65e399a33d2c0)) | | eu-west-1 | [ami-0d0b74b7120bb9716](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d0b74b7120bb9716) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0d0b74b7120bb9716)) | [ami-097ec49079a5d612f](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-097ec49079a5d612f) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-097ec49079a5d612f)) | | eu-west-2 | [ami-0aa557fc3c91bf915](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0aa557fc3c91bf915) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0aa557fc3c91bf915)) | [ami-0360a9a8fec665753](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0360a9a8fec665753) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0360a9a8fec665753)) | | eu-west-3 | [ami-0318f83b86ad7ac88](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0318f83b86ad7ac88) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0318f83b86ad7ac88)) | [ami-0adda5d20f341ae82](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0adda5d20f341ae82) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0adda5d20f341ae82)) | | me-south-1 | [ami-02acb0b55419c47a9](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02acb0b55419c47a9) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-02acb0b55419c47a9)) | [ami-0cd56b96bf4e83dcf](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0cd56b96bf4e83dcf) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0cd56b96bf4e83dcf)) | | sa-east-1 | [ami-03cdc3d22923fdf90](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-03cdc3d22923fdf90) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-03cdc3d22923fdf90)) | [ami-08370ac3635a06147](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-08370ac3635a06147) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-08370ac3635a06147)) | | us-east-1 | [ami-0056ccb36f3fb6235](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0056ccb36f3fb6235) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0056ccb36f3fb6235)) | [ami-068216a0f0800db09](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-068216a0f0800db09) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-068216a0f0800db09)) | | us-east-2 | [ami-074945fa4d4a6f94e](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-074945fa4d4a6f94e) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-074945fa4d4a6f94e)) | [ami-06c24203121c5baa9](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06c24203121c5baa9) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-06c24203121c5baa9)) | | us-west-1 | [ami-0c472aada49c5ce17](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c472aada49c5ce17) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0c472aada49c5ce17)) | [ami-03815baf7396cc308](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-03815baf7396cc308) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-03815baf7396cc308)) | | us-west-2 | [ami-02b50aee474e34b6d](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02b50aee474e34b6d) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-02b50aee474e34b6d)) | [ami-0ccbd58d6e42a3f64](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ccbd58d6e42a3f64) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0ccbd58d6e42a3f64)) | </p></details> ### Alpine Linux 3.12.7 (2021-04-15) <details><summary><i>click to show/hide</i></summary><p> | Region | alpine-ami-3.12.7-aarch64-r0 | alpine-ami-3.12.7-x86_64-r0 | | ------ | --- | --- | | af-south-1 | [ami-06a70fc94c1b79103](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06a70fc94c1b79103) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-06a70fc94c1b79103)) | [ami-0ef71998139e39742](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ef71998139e39742) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0ef71998139e39742)) | | ap-east-1 | [ami-08543ebcf60f9408c](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-08543ebcf60f9408c) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-08543ebcf60f9408c)) | [ami-0628f9a686336d658](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0628f9a686336d658) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0628f9a686336d658)) | | ap-northeast-1 | [ami-0de5d5c864ff290c9](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0de5d5c864ff290c9) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0de5d5c864ff290c9)) | [ami-0b34d9cbb63106e61](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b34d9cbb63106e61) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b34d9cbb63106e61)) | | ap-northeast-2 | [ami-0c75288f31f0cb7b9](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c75288f31f0cb7b9) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0c75288f31f0cb7b9)) | [ami-080b50f812df717ea](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-080b50f812df717ea) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-080b50f812df717ea)) | | ap-northeast-3 | [ami-0914593958f896d39](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0914593958f896d39) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0914593958f896d39)) | [ami-01ddf8610921c1f5b](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-01ddf8610921c1f5b) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-01ddf8610921c1f5b)) | | ap-south-1 | [ami-064cb45377af025fd](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-064cb45377af025fd) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-064cb45377af025fd)) | [ami-0f8f786ca89d0968c](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f8f786ca89d0968c) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0f8f786ca89d0968c)) | | ap-southeast-1 | [ami-0029ccf596b04ede9](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0029ccf596b04ede9) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0029ccf596b04ede9)) | [ami-079d7c6b97cac3237](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-079d7c6b97cac3237) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-079d7c6b97cac3237)) | | ap-southeast-2 | [ami-03329a79c26b708ac](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-03329a79c26b708ac) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-03329a79c26b708ac)) | [ami-0d2e1217ececc880d](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d2e1217ececc880d) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0d2e1217ececc880d)) | | ca-central-1 | [ami-0db89bf48ad1abe72](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0db89bf48ad1abe72) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0db89bf48ad1abe72)) | [ami-094e7437e91419deb](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-094e7437e91419deb) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-094e7437e91419deb)) | | eu-central-1 | [ami-032fc9bc108559f48](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-032fc9bc108559f48) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-032fc9bc108559f48)) | [ami-09eec438ca839ca58](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-09eec438ca839ca58) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-09eec438ca839ca58)) | | eu-north-1 | [ami-05646b55b5ae08b43](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-05646b55b5ae08b43) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-05646b55b5ae08b43)) | [ami-09447e487e10b7655](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-09447e487e10b7655) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-09447e487e10b7655)) | | eu-south-1 | [ami-094cd39ae22bd4939](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-094cd39ae22bd4939) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-094cd39ae22bd4939)) | [ami-04d393060a61a1eca](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-04d393060a61a1eca) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-04d393060a61a1eca)) | | eu-west-1 | [ami-085ac63da43317dd5](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-085ac63da43317dd5) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-085ac63da43317dd5)) | [ami-095c3d5967fd9c885](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-095c3d5967fd9c885) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-095c3d5967fd9c885)) | | eu-west-2 | [ami-0f7d892cc36618710](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f7d892cc36618710) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0f7d892cc36618710)) | [ami-005a2f89daaf77547](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-005a2f89daaf77547) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-005a2f89daaf77547)) | | eu-west-3 | [ami-0936121449608b6c5](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0936121449608b6c5) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0936121449608b6c5)) | [ami-0700c55763af6a1bb](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0700c55763af6a1bb) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0700c55763af6a1bb)) | | me-south-1 | [ami-0f7ec8223dabb5b0e](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f7ec8223dabb5b0e) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0f7ec8223dabb5b0e)) | [ami-039b1ff0cfd4c9e1c](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-039b1ff0cfd4c9e1c) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-039b1ff0cfd4c9e1c)) | | sa-east-1 | [ami-0ac0c553d8d12be19](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ac0c553d8d12be19) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0ac0c553d8d12be19)) | [ami-0d364d95ef0e3ed08](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d364d95ef0e3ed08) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0d364d95ef0e3ed08)) | | us-east-1 | [ami-0f2ae298a58efa981](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f2ae298a58efa981) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0f2ae298a58efa981)) | [ami-08a8e1cd5cfe6fc40](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-08a8e1cd5cfe6fc40) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-08a8e1cd5cfe6fc40)) | | us-east-2 | [ami-0bafced8fbca21718](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0bafced8fbca21718) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0bafced8fbca21718)) | [ami-0f213093a04cde948](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f213093a04cde948) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0f213093a04cde948)) | | us-west-1 | [ami-0a241d0061f878274](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a241d0061f878274) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a241d0061f878274)) | [ami-0a5fc9a6a5351641e](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a5fc9a6a5351641e) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a5fc9a6a5351641e)) | | us-west-2 | [ami-06c17e9baaa7fc2a8](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06c17e9baaa7fc2a8) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-06c17e9baaa7fc2a8)) | [ami-06b1887a7bc6eb122](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06b1887a7bc6eb122) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-06b1887a7bc6eb122)) | </p></details> ### Alpine Linux 3.11.11 (2021-04-15) <details><summary><i>click to show/hide</i></summary><p> | Region | alpine-ami-3.11.11-x86_64-r0 | | ------ | --- | | af-south-1 | [ami-0a5bccfa2bc184bb1](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a5bccfa2bc184bb1) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a5bccfa2bc184bb1)) | | ap-east-1 | [ami-057fe5fb6dbaeaabe](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-057fe5fb6dbaeaabe) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-057fe5fb6dbaeaabe)) | | ap-northeast-1 | [ami-0ce72c30606d58e2a](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ce72c30606d58e2a) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0ce72c30606d58e2a)) | | ap-northeast-2 | [ami-075d81ae6bd805c9a](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-075d81ae6bd805c9a) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-075d81ae6bd805c9a)) | | ap-northeast-3 | [ami-048b8b812a37a6e9d](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-048b8b812a37a6e9d) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-048b8b812a37a6e9d)) | | ap-south-1 | [ami-0a09ced4a0968561a](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a09ced4a0968561a) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a09ced4a0968561a)) | | ap-southeast-1 | [ami-0c3268d224a7be79f](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c3268d224a7be79f) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0c3268d224a7be79f)) | | ap-southeast-2 | [ami-0fe81386105b2c320](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fe81386105b2c320) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0fe81386105b2c320)) | | ca-central-1 | [ami-02351d48ae19b5153](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02351d48ae19b5153) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-02351d48ae19b5153)) | | eu-central-1 | [ami-082d5ae92b013cf0c](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-082d5ae92b013cf0c) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-082d5ae92b013cf0c)) | | eu-north-1 | [ami-0a67df0ddb737bca0](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a67df0ddb737bca0) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a67df0ddb737bca0)) | | eu-south-1 | [ami-0b9e1df4e1ea3f09a](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b9e1df4e1ea3f09a) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b9e1df4e1ea3f09a)) | | eu-west-1 | [ami-06318efc075e9c192](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06318efc075e9c192) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-06318efc075e9c192)) | | eu-west-2 | [ami-0a68f325601d8968f](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a68f325601d8968f) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0a68f325601d8968f)) | | eu-west-3 | [ami-06d6b6f3eb35b4988](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06d6b6f3eb35b4988) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-06d6b6f3eb35b4988)) | | me-south-1 | [ami-0fee76fd32b0acb09](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fee76fd32b0acb09) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0fee76fd32b0acb09)) | | sa-east-1 | [ami-0e3921332d634a1bc](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e3921332d634a1bc) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0e3921332d634a1bc)) | | us-east-1 | [ami-09a785c1dd12aa464](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-09a785c1dd12aa464) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-09a785c1dd12aa464)) | | us-east-2 | [ami-0f27d5f504d774c42](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f27d5f504d774c42) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0f27d5f504d774c42)) | | us-west-1 | [ami-0e1759b0e8c3b8fde](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e1759b0e8c3b8fde) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0e1759b0e8c3b8fde)) | | us-west-2 | [ami-038d4cc13841ec79f](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-038d4cc13841ec79f) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-038d4cc13841ec79f)) | </p></details> ### Alpine Linux 3.10.9 (2021-04-15) <details><summary><i>click to show/hide</i></summary><p> | Region | alpine-ami-3.10.9-x86_64-r1 | | ------ | --- | | af-south-1 | [ami-05a0f52ef9b362d15](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-05a0f52ef9b362d15) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-05a0f52ef9b362d15)) | | ap-east-1 | [ami-0b3f9948309f675f4](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b3f9948309f675f4) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b3f9948309f675f4)) | | ap-northeast-1 | [ami-0fea317d2df3cce69](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fea317d2df3cce69) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0fea317d2df3cce69)) | | ap-northeast-2 | [ami-0d0575f67befe4c8f](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d0575f67befe4c8f) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0d0575f67befe4c8f)) | | ap-northeast-3 | [ami-011d0cf2c117c1e56](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-011d0cf2c117c1e56) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-011d0cf2c117c1e56)) | | ap-south-1 | [ami-0fc4c8a903643a419](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fc4c8a903643a419) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0fc4c8a903643a419)) | | ap-southeast-1 | [ami-034b1643c7a1f6ad3](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-034b1643c7a1f6ad3) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-034b1643c7a1f6ad3)) | | ap-southeast-2 | [ami-0a7b4fc41269a89dc](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a7b4fc41269a89dc) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0a7b4fc41269a89dc)) | | ca-central-1 | [ami-019f7a425e4f03324](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-019f7a425e4f03324) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-019f7a425e4f03324)) | | eu-central-1 | [ami-093bd61857bedc054](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-093bd61857bedc054) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-093bd61857bedc054)) | | eu-north-1 | [ami-0bfb77538faaff8cd](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0bfb77538faaff8cd) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0bfb77538faaff8cd)) | | eu-south-1 | [ami-0b8733c89a66b970e](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b8733c89a66b970e) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b8733c89a66b970e)) | | eu-west-1 | [ami-0e82733ed8463266f](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e82733ed8463266f) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0e82733ed8463266f)) | | eu-west-2 | [ami-051ecb0c23f497417](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-051ecb0c23f497417) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-051ecb0c23f497417)) | | eu-west-3 | [ami-0626be1c660c6a49d](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0626be1c660c6a49d) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0626be1c660c6a49d)) | | me-south-1 | [ami-08c67a11120a80177](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-08c67a11120a80177) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-08c67a11120a80177)) | | sa-east-1 | [ami-0cc2b92d5645ca1e8](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0cc2b92d5645ca1e8) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0cc2b92d5645ca1e8)) | | us-east-1 | [ami-0b1bd4876203c2b8c](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b1bd4876203c2b8c) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b1bd4876203c2b8c)) | | us-east-2 | [ami-00123a738deb3a8e4](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-00123a738deb3a8e4) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-00123a738deb3a8e4)) | | us-west-1 | [ami-0734555c891e8da78](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0734555c891e8da78) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0734555c891e8da78)) | | us-west-2 | [ami-0cea541629d472655](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0cea541629d472655) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0cea541629d472655)) | </p></details> ### Alpine Linux Edge (2021-04-15) <details><summary><i>click to show/hide</i></summary><p> | Region | alpine-ami-edge-aarch64-20210415004934 | alpine-ami-edge-x86_64-20210415004934 | | ------ | --- | --- | | af-south-1 | [ami-05323d7ccfeef338d](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-05323d7ccfeef338d) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-05323d7ccfeef338d)) | [ami-0b2a5bd82f5c19450](https://af-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b2a5bd82f5c19450) ([launch](https://af-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b2a5bd82f5c19450)) | | ap-east-1 | [ami-0a205de4599a46b73](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a205de4599a46b73) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a205de4599a46b73)) | [ami-0b4af1fbe3d316c7c](https://ap-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b4af1fbe3d316c7c) ([launch](https://ap-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b4af1fbe3d316c7c)) | | ap-northeast-1 | [ami-0bed76a1c41508f7a](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0bed76a1c41508f7a) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0bed76a1c41508f7a)) | [ami-0a7db21efc6e29878](https://ap-northeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a7db21efc6e29878) ([launch](https://ap-northeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a7db21efc6e29878)) | | ap-northeast-2 | [ami-0459895d7d22cd6d2](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0459895d7d22cd6d2) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0459895d7d22cd6d2)) | [ami-05818d04f9ca5ae0c](https://ap-northeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-05818d04f9ca5ae0c) ([launch](https://ap-northeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-05818d04f9ca5ae0c)) | | ap-northeast-3 | [ami-0f6abafa7355f5498](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f6abafa7355f5498) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-0f6abafa7355f5498)) | [ami-092966b779e986ea9](https://ap-northeast-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-092966b779e986ea9) ([launch](https://ap-northeast-3.console.aws.amazon.com/ec2/home#launchAmi=ami-092966b779e986ea9)) | | ap-south-1 | [ami-0a424f47b2e6e98f1](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a424f47b2e6e98f1) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0a424f47b2e6e98f1)) | [ami-0f1c17fbeca6684f0](https://ap-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0f1c17fbeca6684f0) ([launch](https://ap-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0f1c17fbeca6684f0)) | | ap-southeast-1 | [ami-0ddd8b5bf6ce262a7](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ddd8b5bf6ce262a7) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0ddd8b5bf6ce262a7)) | [ami-0fe9948c390424705](https://ap-southeast-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fe9948c390424705) ([launch](https://ap-southeast-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0fe9948c390424705)) | | ap-southeast-2 | [ami-06d87bbcb96a8f826](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06d87bbcb96a8f826) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-06d87bbcb96a8f826)) | [ami-0862d60e3aad763fd](https://ap-southeast-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0862d60e3aad763fd) ([launch](https://ap-southeast-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0862d60e3aad763fd)) | | ca-central-1 | [ami-01e7f633089983fb3](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-01e7f633089983fb3) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-01e7f633089983fb3)) | [ami-0bc9abfc42e208ab3](https://ca-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0bc9abfc42e208ab3) ([launch](https://ca-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0bc9abfc42e208ab3)) | | eu-central-1 | [ami-0b026a13578b0881c](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0b026a13578b0881c) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0b026a13578b0881c)) | [ami-09b8a9cd743ea4aeb](https://eu-central-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-09b8a9cd743ea4aeb) ([launch](https://eu-central-1.console.aws.amazon.com/ec2/home#launchAmi=ami-09b8a9cd743ea4aeb)) | | eu-north-1 | [ami-0625ddde0e3703657](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0625ddde0e3703657) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0625ddde0e3703657)) | [ami-0827247eeafc299c7](https://eu-north-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0827247eeafc299c7) ([launch](https://eu-north-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0827247eeafc299c7)) | | eu-south-1 | [ami-0fa6bc7832c89cc88](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0fa6bc7832c89cc88) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0fa6bc7832c89cc88)) | [ami-007cd9a3750268568](https://eu-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-007cd9a3750268568) ([launch](https://eu-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-007cd9a3750268568)) | | eu-west-1 | [ami-0db2720148e1ee7c9](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0db2720148e1ee7c9) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0db2720148e1ee7c9)) | [ami-02f5d396ef0d0cd4e](https://eu-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-02f5d396ef0d0cd4e) ([launch](https://eu-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-02f5d396ef0d0cd4e)) | | eu-west-2 | [ami-0e28797e7ca6aa52e](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e28797e7ca6aa52e) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0e28797e7ca6aa52e)) | [ami-0a3846ca0a16d70cc](https://eu-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0a3846ca0a16d70cc) ([launch](https://eu-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0a3846ca0a16d70cc)) | | eu-west-3 | [ami-04b6003dc6d833b93](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-04b6003dc6d833b93) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-04b6003dc6d833b93)) | [ami-001c0eab9d67f6718](https://eu-west-3.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-001c0eab9d67f6718) ([launch](https://eu-west-3.console.aws.amazon.com/ec2/home#launchAmi=ami-001c0eab9d67f6718)) | | me-south-1 | [ami-0d40a784a21287887](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d40a784a21287887) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0d40a784a21287887)) | [ami-035a951e8bcea8167](https://me-south-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-035a951e8bcea8167) ([launch](https://me-south-1.console.aws.amazon.com/ec2/home#launchAmi=ami-035a951e8bcea8167)) | | sa-east-1 | [ami-0d21274dd1ffbf9b3](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0d21274dd1ffbf9b3) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0d21274dd1ffbf9b3)) | [ami-06ecc174e406c8af1](https://sa-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-06ecc174e406c8af1) ([launch](https://sa-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-06ecc174e406c8af1)) | | us-east-1 | [ami-0ce76b18bd6aedcf4](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0ce76b18bd6aedcf4) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0ce76b18bd6aedcf4)) | [ami-0296efb204b82eb67](https://us-east-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0296efb204b82eb67) ([launch](https://us-east-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0296efb204b82eb67)) | | us-east-2 | [ami-0e3a658b7337d7c80](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0e3a658b7337d7c80) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0e3a658b7337d7c80)) | [ami-0c21f3fdbb360887e](https://us-east-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0c21f3fdbb360887e) ([launch](https://us-east-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0c21f3fdbb360887e)) | | us-west-1 | [ami-0136fdf84a68f211b](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0136fdf84a68f211b) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0136fdf84a68f211b)) | [ami-0244d7eadf1f89420](https://us-west-1.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0244d7eadf1f89420) ([launch](https://us-west-1.console.aws.amazon.com/ec2/home#launchAmi=ami-0244d7eadf1f89420)) | | us-west-2 | [ami-051019494417c7234](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-051019494417c7234) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-051019494417c7234)) | [ami-0589edf1630de358f](https://us-west-2.console.aws.amazon.com/ec2/home#Images:visibility=public-images;imageId=ami-0589edf1630de358f) ([launch](https://us-west-2.console.aws.amazon.com/ec2/home#launchAmi=ami-0589edf1630de358f)) | </p></details> <file_sep>#!/bin/sh # vim: set ts=4 et: set -e IFACE_CFG=/etc/network/interfaces IFACE_DIR="${IFACE_CFG}.d" cd "$IFACE_DIR" cat > "$IFACE_CFG.new" <<EOT # NOTE: /etc/network/assemble-interfaces rewrites this file. Edit files in # /etc/network/interfaces.d/ to persist any customizations. EOT # loopback first cat lo >> "$IFACE_CFG.new" # existing eths for i in /sys/class/net/eth*; do IFACE="$(basename "$i")" [ ! -f "$IFACE" ] && sed -e "s/%%/$IFACE/g" DEFAULT > "$IFACE" cat "$IFACE" >> "$IFACE_CFG.new" done # all the rest for i in "$IFACE_DIR"/*; do IFACE="$(basename "$i")" case $IFACE in DEFAULT|lo|eth*) continue ;; *) cat "$IFACE" >> "$IFACE_CFG.new" ;; esac done # install new interfaces config cp -a "$IFACE_CFG" "$IFACE_CFG.bak" mv "$IFACE_CFG.new" "$IFACE_CFG" <file_sep>#!/usr/bin/env sh set -ex # copy a directory into place cp -a ./base "$TARGET/home/$EC2_USER/test" # process a file and put it into place tac ./aarch64 | rev > "$TARGET/home/$EC2_USER/test/46hcraa" # set ownership of installed things chroot "$TARGET" chown -R "$EC2_USER:$EC2_USER" "/home/$EC2_USER/test"
39bb19244989a9c23a864ff876265c35ea658ea4
[ "Markdown", "Python", "Shell" ]
11
Shell
denzuko-forked/alpine-ec2-ami
b578a39eb7054b93993488f10cfdc41d324540f7
b12758cd20331c39072302f88025b9c3269c4fe1
refs/heads/master
<repo_name>fariborz89/mytomorrows<file_sep>/models/price.py class Price: def __init__(self, min, max, avg): self.min = min self.max = max self.avg = round(avg, 1) class CityPrice(Price): def __init__(self, min, max, avg, city): Price.__init__(self, min, max, avg) self.city = city class SizePrice(Price): def __init__(self, min, max, avg, size): Price.__init__(self, min, max, avg) self.size = size class TypePrice(Price): def __init__(self, min, max, avg, type): Price.__init__(self, min, max, avg) self.type = type<file_sep>/server.py from flask import Flask from flask_restful import Api from utils.config import SERVER_PORT from api.api_services import NewSales, AggregatedData, FilteredAggregatedData from db.services import * app = Flask(__name__) api = Api(app) api.add_resource(NewSales, '/v1/buildings/sale') # Route_1 api.add_resource(AggregatedData, '/v1/buildings/sale/aggregated/<aggregation_type>/<from_date>/<to_date>') # Route_2 api.add_resource(FilteredAggregatedData, '/v1/buildings/sale/aggregated/filter/<aggregation_type>/<from_date>/<to_date>') # Route_3 if __name__ == '__main__': DbServices.create_sales_table() app.run(port=SERVER_PORT) <file_sep>/requirements.txt aniso8601==6.0.0 asn1crypto==0.24.0 certifi==2019.3.9 cffi==1.12.3 chardet==3.0.4 Click==7.0 cryptography==2.6.1 enum34==1.1.6 Flask==1.0.2 Flask-Jsonpify==1.5.0 Flask-RESTful==0.3.7 Flask-SQLAlchemy==2.4.0 idna==2.8 ipaddress==1.0.22 itsdangerous==1.1.0 Jinja2==2.10.1 MarkupSafe==1.1.1 pycparser==2.19 PyJWT==1.7.1 pyOpenSSL==19.0.0 pytz==2019.1 requests==2.21.0 six==1.12.0 SQLAlchemy==1.3.3 twilio==6.26.2 urllib3==1.24.2 Werkzeug==0.15.2 <file_sep>/api/api_services.py from flask import request from flask_restful import Resource from datetime import datetime from utils.base import create_final_dict from db.services import DbServices class NewSales(Resource): def post(self): """ Converting the csv file to the database objects and insert in database if the file doesn't have the correct format it will not add any entity to the db :return: http status code and the message. """ f = request.files['file'] # check the correctness of file correct_file, issue = self.check_input_file(f) if not correct_file: return issue, 400 # go back to the begin of the file f.seek(0) line = f.readline() first_line = True while line != '': if first_line: first_line = False line = f.readline() continue words = line.split(',') # sale_date of the building has this format Wed May 21 00:00:00 EDT 2008, in the next lines # some redundant info will be removed. We just need the date 2008-05-15| list_time = words[8].split(' ') sale_date_string = ' '.join(list_time[1: 4]) + ' ' + list_time[5] sale_date = datetime.strptime(sale_date_string, "%b %d %H:%M:%S %Y") dict = { 'street': words[0], 'city': words[1].lower(), 'zip': int(words[2]), 'state': words[3], 'beds': int(words[4]), 'baths': int(words[5]), 'size': int(words[6]), 'type': words[7], 'sale_date': sale_date, 'price': int(words[9]), 'latitude': float(words[10]), 'longitude': float(words[11])} try: DbServices.insert_data(dict) except: return 'Something went wrong with this line: ' + line + ' BUT THE PREVIOUS LINES ARE SAVED.', 500 line = f.readline() return 'File uploaded successfully', 201 def check_input_file(self, f): """ Checking the correct style and information of the input file The first line must be in order and other line must have the information of city, sale_date, price and size :param f: the csv file :return: The http status code and the message """ line = f.readline() # checking the first line order is_allowed, issue = self.check_first_line(line) if not is_allowed: return False, issue first_line = True # checking all sales to be sure they have city, size, price and sale_date while line != '': if first_line: first_line = False line = f.readline() continue words = line.split(',') if words[1] == '' or words[6] == '' or words[7] == '' or words[8] == '': return False, "This sale does not have enough information: " + line line = f.readline() return True, 'ok' def check_first_line(self, line): """ Checks the correct format of the first line of csv file :param line: the first line of csv file :return: is it ok and the message """ if line.lower().strip() == 'street,city,zip,state,beds,baths,sq__ft,type,sale_date,price,latitude,longitude': return True, 'ok' return False, "First line is not in order." class AggregatedData(Resource): def get(self, aggregation_type, from_date, to_date): """ This function will aggregate the sales data in an interval by city or size or type It will provide the avg, min and max of the prices :param aggregation_type: We provide three kind of aggregation --> city, type, size :param from_date: The processing will be done on an interval of time, this is the beginning of interval :param to_date: The processing will be done on an interval of time, this is the end of interval :return: http status code and the dictionary (json) of the result which contains min, max, avg of aggregation """ if not check_aggregation_type(aggregation_type): return "No valid aggregation type: " + aggregation_type, 400 from_date = datetime.strptime(from_date, "%Y-%m-%d").date() to_date = datetime.strptime(to_date, "%Y-%m-%d").date() command = 'select min(price), max(price), avg(price), {0} from sales where sale_date ' \ 'between \'{1}\' and \'{2}\' group by {0};'.format(aggregation_type, from_date, to_date) try: query = DbServices.query_execute(command) except: return "Something went wrong!", 500 final_dict = create_final_dict(aggregation_type, query) return final_dict, 200 class FilteredAggregatedData(Resource): def get(self, aggregation_type, from_date, to_date): """ This function will aggregate the sales data in an interval by city or size or type AND will do a filter by city or size or type It will provide the avg, min and max of the prices For example we want the aggregated data of Berlin city by type of buildings in Januray Filter will be as query parameter :param aggregation_type: We provide three kind of aggregation --> city, type, size :param from_date: The processing will be done on an interval of time, this is the beginning of interval :param to_date: The processing will be done on an interval of time, this is the end of interval :return: http status code and the dictionary (json) of the result which contains min, max, avg of aggregation """ if not check_aggregation_type(aggregation_type): return "No valid aggregation type: " + aggregation_type, 400 city_condition = '' size_condition = '' type_condition = '' first_and = False second_and = False first_and_char = '' second_and_char = '' # In the next three if, we are creating the where clause of aggregation query if 'city' in request.args: city = request.args['city'] city_condition = 'city=\'' + city.lower() + '\'' first_and = True if 'size' in request.args: size = request.args['size'] if first_and: first_and_char = 'And ' size_condition = first_and_char + 'size=' + size second_and = True if 'type' in request.args: type = request.args['type'] if first_and or second_and: second_and_char = 'And ' type_condition = second_and_char + 'type=\'' + type + '\'' from_date = datetime.strptime(from_date, "%Y-%m-%d").date() to_date = datetime.strptime(to_date, "%Y-%m-%d").date() command = 'select min(price), max(price), avg(price), {0} from sales where sale_date ' \ 'between \'{1}\' and \'{2}\' And {3} {4} {5} group by {0};'.format \ (aggregation_type, from_date, to_date, city_condition, size_condition, type_condition) try: query = DbServices.query_execute(command) except: return "Something went wrong!", 500 return create_final_dict(aggregation_type, query), 200 def check_aggregation_type(aggregation_type): if aggregation_type != 'city' and aggregation_type != 'size' and aggregation_type != 'type': return False return True <file_sep>/utils/config.py import logging LOG_LEVEL = logging.DEBUG SERVER_PORT = 8080 DB = "test1.db" <file_sep>/db/services.py from sqlalchemy import create_engine, Table, Column, Integer, Date, Float, String, MetaData, ForeignKey from utils.config import DB metadata = MetaData() sales = Table('sales', metadata, Column('id', Integer, primary_key=True), Column('street', String), Column('city', String, nullable=False), Column('zip', Integer), Column('state', String), Column('beds', Integer), Column('baths', Integer), Column('size', Integer, nullable=False), Column('type', String), Column('sale_date', Date, nullable=False), Column('price', Integer, nullable=False), Column('latitude', Float), Column('longitude', Float), ) class DbServices: engine = create_engine('sqlite:///' + DB) @staticmethod def query_execute(command): """ Will execute the sql command :param command: the command to execute :return: The result of the db execution of command """ conn = DbServices.engine.connect() return conn.execute(command) @staticmethod def insert_data(dict): """ This function will insert new entities to the db :param dict: the dictionary of the entity :return: The result of db insert """ ins = sales.insert().values( street=dict['street'], city=dict['city'], zip=dict['zip'], state=dict['state'], beds=dict['beds'], baths=dict['baths'], size=dict['size'], type=dict['type'], sale_date=dict['sale_date'], price=dict['price'], latitude=dict['latitude'], longitude=dict['longitude']) result = DbServices.engine.execute(ins) return result @staticmethod def create_sales_table(): """ This function will create the sales table if doesn't exist :return: """ metadata.create_all(DbServices.engine) return <file_sep>/README.md # mytomorrows assignment This is a project to aggregate the sales data of RealEstate company. This project is based on python 2.7 and flask. To run the project, the entry point is server.py. Before running you need to install required packages: **pip install -r requirements.txt** Also you need to define server port and db address. You can change them in utils/conf.py. You must also **create the db** before running the project. To run the project you just need to do: **python server.py** _There is also a postman collection to get more familiar with the APIs._ <file_sep>/utils/base.py from models.price import CityPrice, SizePrice, TypePrice def create_final_dict(aggregation_type, query): """ :param aggregation_type: Is the aggregation based on city, size or type :param query: The result of database execution command, this input has the list of response. :return: dictionary of the aggregated data which can be shown as json """ final_list = [] if aggregation_type == 'city': for r in query.cursor.fetchall(): obj = CityPrice(r[0], r[1], r[2], r[3]) final_list.append(obj) if aggregation_type == 'size': for r in query.cursor.fetchall(): obj = SizePrice(r[0], r[1], r[2], r[3]) final_list.append(obj) if aggregation_type == 'type': for r in query.cursor.fetchall(): obj = TypePrice(r[0], r[1], r[2], r[3]) final_list.append(obj) final_dict = [obj.__dict__ for obj in final_list] return final_dict
42e24cb6bda88f4a73b1fecef1639180e5784dbc
[ "Markdown", "Python", "Text" ]
8
Python
fariborz89/mytomorrows
1a6b098040bf26df413dbabfb334dbba817f7334
fb2c1d3a17ec8be005ea1eef3dbda13dd111f526
refs/heads/master
<repo_name>chris510/Poke<file_sep>/src/app/services/data-storage-service.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { PokemonService } from './pokemon.service'; import { tap } from 'rxjs/operators'; import { Pokemon } from '../pokemon.model'; @Injectable({ providedIn: 'root' }) export class DataStorageServiceService { constructor( private http: HttpClient, private pokemonService: PokemonService ) { } storePokemon() { const pokemonList = this.pokemonService.getPokemonList(); this.http.put('https://pokemons-a3b54.firebaseio.com/post.json', pokemonList) .subscribe( pokemonList => console.log(pokemonList) ) } fetchPokemon() { return this.http.get<Pokemon[]>('https://pokemons-a3b54.firebaseio.com/post.json') .pipe( tap(pokemonList => { this.pokemonService.setPokemon(pokemonList) }) ) } } <file_sep>/src/app/pokemon-item/pokemon-item.component.ts import { Component, OnInit, Input } from '@angular/core'; import { types } from '../pokemon.types'; import { Router, ActivatedRoute } from '@angular/router'; import { PokemonService } from '../services/pokemon.service'; import { Pokemon } from '../pokemon.model'; @Component({ selector: 'app-pokemon-item', templateUrl: './pokemon-item.component.html', styleUrls: ['./pokemon-item.component.scss'] }) export class PokemonItemComponent implements OnInit { @Input() pokemon: Pokemon; @Input() index: number; toggleImg = true; types = types; constructor( private router: Router, private route: ActivatedRoute, private pokemonService: PokemonService ) { } ngOnInit(): void { } onToggleImg() { this.toggleImg = !this.toggleImg; } onPokemonDetail() { console.log('navgiated') this.router.navigate(['name'], {relativeTo: this.route }) } onAddToTeam() { this.pokemonService.addPokemonToTeam(this.pokemon); } onDeletePokemon() { console.log('Pokemon Has been Deleted'); this.pokemonService.deletePokemon(this.index); // console.log(this.pokemon.id); } } <file_sep>/src/app/pokemon.model.ts export class Pokemon { constructor( public id: string, public name: string, public type: string, public frontImg: string, public move1: string, public move2: string, public move3: string, public move4?: string, public backImg?: string, ) { } }<file_sep>/src/app/services/pokemon.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Subject } from 'rxjs'; import { Pokemon } from '../pokemon.model'; import { MyTeamService } from '../my-team.service'; @Injectable({ providedIn: 'root' }) export class PokemonService { // pokemon = new Subject<any>(); pokemonListChanged = new Subject<Pokemon[]>(); private pokemonList = []; constructor( private http: HttpClient, private myTeam: MyTeamService ) { } getPokemonList() { return this.pokemonList.slice(); } notifyPokemonListChange() { this.pokemonListChanged.next(this.pokemonList.slice()) } addPokemonToTeam(pokemon: Pokemon) { this.myTeam.addToTeam(pokemon); } addPokemon(pokemon: Pokemon) { this.pokemonList.push(pokemon); this.notifyPokemonListChange(); } setPokemon(pokemonList: Pokemon[]) { this.pokemonList = pokemonList; this.notifyPokemonListChange(); } deletePokemon(index: number) { this.pokemonList.splice(index, 1); this.notifyPokemonListChange(); } getAllPokemon() { // const promises = []; for (let i = 1; i <= 151; i++) { this.http.get(`https://pokeapi.co/api/v2/pokemon/${i}/`).subscribe( pokemonData => { this.createPokemon(pokemonData); } ) } // this.pokemonListChanged.next(this.pokemonList.slice()); // Promise.all(promises).then(allData => { // allData.map(pokemonData => { // pokemonData.subscribe(pokemon => { // this.createPokemon(pokemon); // }) // }) // }) } getPokemon(pokemonName: string) { return this.http.get(` https://pokeapi.co/api/v2/pokemon/${pokemonName}/ `) // .subscribe( // pokemonData => { // console.log(pokemonData); // this.createPokemon(pokemonData); // } // ) } createPokemon(pokemonData: object) { let chosenType = pokemonData['types'][1] ? pokemonData['types'][1]['type']['name'] : pokemonData['types'][0]['type']['name'] let newPokemon = new Pokemon( pokemonData['id'], pokemonData['name'], chosenType, pokemonData['sprites']['front_default'], pokemonData['moves'][0]['move']['name'], pokemonData['moves'][1]['move']['name'], pokemonData['moves'][2]['move']['name'], pokemonData['moves'][3]['move']['name'], pokemonData['sprites']['back_default'] ) this.addPokemon(newPokemon); } } <file_sep>/src/app/pokedex-list/pokedex-list.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { PokemonService } from '../services/pokemon.service'; import { Subscription } from 'rxjs'; import { Pokemon } from '../pokemon.model'; import { DataStorageServiceService } from '../services/data-storage-service.service'; @Component({ selector: 'app-pokedex-list', templateUrl: './pokedex-list.component.html', styleUrls: ['./pokedex-list.component.scss'] }) export class PokedexListComponent implements OnInit, OnDestroy { pokemonList = []; newPokemonSub: Subscription; storage: Subscription; searchPokeSub: Subscription; currPokeName = ''; error: string = ''; holdBtnMessage: string = ''; constructor( private pokemonService: PokemonService, ) { } ngOnInit(): void { // this.storage = this.dataStorageService.fetchPokemon().pipe(take(1)).subscribe( // (pokemonList: Pokemon[]) => { // this.pokemonList = pokemonList; // } // ) // this.pokemonService.getAllPokemon() // console.log(this.pokemonList.length) // if (this.pokemonList.length === 0) { // this.dataStorageService.fetchPokemon().subscribe(); // } // this.pokemonList.length === 0 ? this.dataStorageService.fetchPokemon() : null; this.newPokemonSub = this.pokemonService.pokemonListChanged.subscribe( (pokemonList: Pokemon[]) => { this.pokemonList = pokemonList; console.log(pokemonList, 'hello'); } ) this.pokemonList = this.pokemonService.getPokemonList(); } onSearchSubmit() { console.log('This function does not do anything'); // this.searchPokeSub = this.pokemonService.getPokemon(this.currPokeName.toLowerCase()).subscribe( // pokemonData => { // this.pokemonService.createPokemon(pokemonData); // }, error => { // this.error = 'Pokemon Not Found!' // } // ); } onHandleKeyEnter() { this.searchPokeSub = this.pokemonService.getPokemon(this.currPokeName.toLowerCase()).subscribe( pokemonData => { this.pokemonService.createPokemon(pokemonData); }, error => { this.error = 'Pokemon Not Found!' }, () => { console.log('this is completed'); } ); } onHandleError() { (this.error) ? this.error = null : null; (this.holdBtnMessage) ? this.holdBtnMessage = null : null; } holdHandler(msg: string) { console.log(msg); this.holdBtnMessage = msg; } ngOnDestroy() { this.searchPokeSub ? this.searchPokeSub.unsubscribe() : null; // this.newPokemonSub.unsubscribe(); // this.storage.unsubscribe(); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms' import { HttpClientModule} from '@angular/common/http' import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NavComponent } from './nav/nav.component'; import { PokedexListComponent } from './pokedex-list/pokedex-list.component'; import { PokemonItemComponent } from './pokemon-item/pokemon-item.component'; import { TeamComponent } from './team/team.component'; import { PokemonDetailComponent } from './pokemon-detail/pokemon-detail.component'; import { AlertComponent } from './alert/alert.component'; import { HoldableDirective } from './holdable.directive'; @NgModule({ declarations: [ AppComponent, NavComponent, PokedexListComponent, PokemonItemComponent, TeamComponent, PokemonDetailComponent, AlertComponent, HoldableDirective ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/nav/nav.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { DataStorageServiceService } from '../services/data-storage-service.service'; @Component({ selector: 'app-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.scss'] }) export class NavComponent implements OnInit, OnDestroy { fetchSub: Subscription constructor( private dataStorageService: DataStorageServiceService ) { } ngOnInit(): void { } onSaveData() { this.dataStorageService.storePokemon(); } onFetchData() { this.fetchSub = this.dataStorageService.fetchPokemon().subscribe(); } ngOnDestroy() { this.fetchSub.unsubscribe(); } } <file_sep>/src/app/team/team.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { MyTeamService } from '../my-team.service'; import { Pokemon } from '../pokemon.model'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-team', templateUrl: './team.component.html', styleUrls: ['./team.component.scss'] }) export class TeamComponent implements OnInit, OnDestroy { myTeam: Pokemon[] = []; myTeamSub: Subscription; constructor( private pokemonTeam: MyTeamService ) { } ngOnInit(): void { this.myTeam = this.pokemonTeam.getTeam(); // this.myTeamSub = this.pokemonTeam.myTeamChanged.subscribe( // (myPokemonTeam: Pokemon[]) => { // console.log(myPokemonTeam); // this.myTeam = myPokemonTeam; // } // ) } ngOnDestroy() { } }
f4b32e0a1fd054f53eea2abd4503ec659314cf0a
[ "TypeScript" ]
8
TypeScript
chris510/Poke
13888becf51134774d438f9feeb8a7c8ccee0f06
23db9393114838e8eee4bc7e422530100e55bdbc
refs/heads/master
<repo_name>arscrift/web<file_sep>/src/app/navegacao/navegacao.component.ts import { Component, OnInit } from '@angular/core'; import { Categoria } from './navegacao.model'; import { NavegacaoService } from './navegacao.service'; @Component({ selector: 'navegacao', templateUrl: './navegacao.component.html', styleUrls: ['./navegacao.component.css'] }) export class NavegacaoComponent implements OnInit { public categorias: Categoria[]; constructor(private navegacaoService: NavegacaoService) { } ngOnInit() { this.navegacaoService.listarCategorias().subscribe(res => { this.categorias = res; }); } }<file_sep>/src/app/principal/evento/inscrever/inscrever.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'inscrever', templateUrl: './inscrever.component.html', styleUrls: ['./inscrever.component.css'] }) export class InscreverComponent implements OnInit { public passoAtivo: object = {um: true, dois: false, tres: false}; constructor() { } ngOnInit() { } setPasso(passo: number){ switch(passo){ case 1: this.passoAtivo = {um: true, dois: false, tres: false}; break; case 2: this.passoAtivo = {um: false, dois: true, tres: false}; break; case 3: this.passoAtivo = {um: false, dois: false, tres: true}; break; default: this.passoAtivo = {um: true, dois: false, tres: false}; } } }<file_sep>/Dockerfile FROM node:10-alpine as builder WORKDIR /app COPY package*.json /app/ RUN npm install -g @angular/cli RUN npm install COPY ./ /app/ RUN ng build --output-path=dist FROM nginx:alpine RUN rm -rf /usr/share/nginx/html/* COPY default /etc/nginx/sites-available/ COPY nginx.conf /etc/nginx/ COPY --from=builder /app/dist/ /usr/share/nginx/html EXPOSE 82 CMD ["nginx", "-g", "daemon off;"]<file_sep>/src/app/principal/evento/patrocinador/patrocinador.component.ts import { Component, OnInit, Input } from '@angular/core'; import { PatrocinadorModel } from '../models/patrocinador.model'; @Component({ selector: 'patrocinador', templateUrl: './patrocinador.component.html', styleUrls: ['./patrocinador.component.css'] }) export class PatrocinadorComponent implements OnInit { @Input() patrocinador: PatrocinadorModel; constructor() { } ngOnInit() { } }<file_sep>/src/app/principal/evento/evento.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { CatalogoService } from '../catalogo/catalogo.service'; import { EventoModel } from './models/evento.model'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'evento', templateUrl: './evento.component.html', styleUrls: ['./evento.component.css'] }) export class EventoComponent implements OnInit { public evento: EventoModel; constructor( private route: ActivatedRoute, private catalogoService: CatalogoService, public sanitizer: DomSanitizer ) { } ngOnInit() { this.route.params.subscribe(params => { this.buscarEvento(parseInt(params['id'])); //console.log(this.evento) }); } buscarEvento(id: number) { this.catalogoService.consultarEvento(id).subscribe(res => { this.evento = res; }); } }<file_sep>/README.md # Web To start the web, run the command: ``` docker run -itd --rm --name web -p 80:82 strund3r/arscrift-web ``` <file_sep>/src/app/cabecalho/cabecalho.component.ts import { Component, OnInit, ElementRef, HostListener } from '@angular/core'; @Component({ selector: 'cabecalho', templateUrl: './cabecalho.component.html', styleUrls: ['./cabecalho.component.css'] }) export class CabecalhoComponent implements OnInit { constructor(private element: ElementRef) { } ngOnInit() { } @HostListener('window:scroll', ['$event']) onScroll(): void{ let parallax = this.element.nativeElement; if(window.scrollY < parallax.offsetHeight){ let suave = window.scrollY * 70 / 100; //console.log(parallax.offsetHeight, window.scrollY); parallax.style.backgroundPosition = `center top ${suave}px`; }else{parallax.removeAttribute('style');} let menu = this.element.nativeElement.querySelector('#menu'); if(window.scrollY >= (parallax.scrollHeight - menu.scrollHeight)){ menu.classList.add('fixo'); }else{ menu.classList.remove('fixo'); } } mostrarCategorias(): void{ document.querySelector('#navegacao').classList.toggle('menu-aberto'); } }<file_sep>/src/app/principal/evento/models/patrocinador.model.ts export class PatrocinadorModel { idPatrocinador: number; idEvento: number; nome: string; descricao: string; caminhoDaImagem: string; }<file_sep>/src/app/utilitarios/lazy-loading-img.directive.ts import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[LazyLoadingIMG]' }) export class LazyLoadingIMGDirective { @Input() caminhoDaImagem: string; private intersectionObserver? : IntersectionObserver; constructor(private element: ElementRef) { this.intersectionObserver = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { let image = this.element.nativeElement; image.src = `${this.caminhoDaImagem}`; setTimeout(()=>{ image.classList.remove("lazy"); image.removeAttribute('LazyLoadingIMG'); }, 300); //console.log(entry.target) this.intersectionObserver.unobserve(image); } }); }); this.intersectionObserver.observe(this.element.nativeElement); } }<file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CatalogoComponent } from './principal/catalogo/catalogo.component'; import { ApresentacaoComponent } from './principal/apresentacao/apresentacao.component'; import { PrincipalComponent } from './principal/principal.component'; import { EventoComponent } from './principal/evento/evento.component'; const ROUTES: Routes = [ { path: '', component: PrincipalComponent, children: [ {path: '', component: ApresentacaoComponent}, {path: 'categoria/:id', component: CatalogoComponent}, {path: 'evento/:id', component: EventoComponent} ] }, {path: 'home', component: ApresentacaoComponent} ]; @NgModule({ imports: [RouterModule.forRoot(ROUTES)], exports: [RouterModule] }) export class AppRoutingModule { }<file_sep>/src/app/principal/catalogo/catalogo.component.ts import { Component, OnInit} from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { CatalogoService } from './catalogo.service'; import { EventoModel } from '../evento/models/evento.model'; import { Categoria } from 'src/app/navegacao/navegacao.model'; @Component({ selector: 'catalogo', templateUrl: './catalogo.component.html', styleUrls: ['./catalogo.component.css'] }) export class CatalogoComponent implements OnInit { public eventos: EventoModel[]; constructor( private route: ActivatedRoute, private catalogoService: CatalogoService ) { } ngOnInit() { this.route.params.subscribe(params => { this.listarCatalogo(parseInt(params['id'])); }); } listarCatalogo(id: number) { this.catalogoService.listarEventosPorCategoria(id).subscribe(res => { this.eventos = res; }); } }<file_sep>/src/app/principal/catalogo/catalogo.service.ts import { Injectable } from '@angular/core'; import { EventoModel } from '../evento/models/evento.model'; import { PatrocinadorModel } from '../evento/models/patrocinador.model'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CatalogoService { private eventos: EventoModel[] = []; constructor(private httpClient: HttpClient){} listarCategorias(): Observable<PatrocinadorModel[]>{ return this.httpClient.get<PatrocinadorModel[]>(`https://api.arscrift.digital/restrito/patrocinador/listar`); } listarEventos(): Observable<EventoModel[]> { return this.httpClient.get<EventoModel[]>(`https://api.arscrift.digital/restrito/evento/listar`); } listarEventosPorCategoria(id: number): Observable<EventoModel[]> { return this.httpClient.get<EventoModel[]>(`https://api.arscrift.digital/restrito/evento/listarEventosPorCategoria/${id}`); } consultarEvento(id: number): Observable<EventoModel> { return this.httpClient.get<EventoModel>(`https://api.arscrift.digital/restrito/evento/buscar/${id}`); } }<file_sep>/src/app/principal/evento/models/evento.model.ts import { PatrocinadorModel } from './patrocinador.model'; export class EventoModel { idEvento: number; idCategoria: number; titulo: string; breveDescricao: string; descricao: string; imagemPrincipal: string; temPatrocinio: boolean; urlDoGoogleMaps: string; patrocinadores?: PatrocinadorModel[]; }<file_sep>/src/app/principal/evento/inscrever/form-usuario/form-usuario.component.ts import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { Observable } from 'rxjs'; @Component({ selector: 'form-usuario', templateUrl: './form-usuario.component.html', styleUrls: ['./form-usuario.component.css'] }) export class FormUsuarioComponent implements OnInit { @Output() proximoPasso: any = new EventEmitter(); constructor() { } ngOnInit() { } proximo(): Observable<number> { return this.proximoPasso.emit(2); } }<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CabecalhoComponent } from './cabecalho/cabecalho.component'; import { NavegacaoComponent } from './navegacao/navegacao.component'; import { PrincipalComponent } from './principal/principal.component'; import { RodapeComponent } from './rodape/rodape.component'; import { NavegacaoService } from './navegacao/navegacao.service'; import { CatalogoComponent } from './principal/catalogo/catalogo.component'; import { EventoComponent } from './principal/evento/evento.component'; import { ApresentacaoComponent } from './principal/apresentacao/apresentacao.component'; import { LazyLoadingIMGDirective } from './utilitarios/lazy-loading-img.directive'; import { CatalogoService } from './principal/catalogo/catalogo.service'; import { CartaoComponent } from './principal/catalogo/cartao/cartao.component'; import { PatrocinadorComponent } from './principal/evento/patrocinador/patrocinador.component'; import { InscreverComponent } from './principal/evento/inscrever/inscrever.component'; import { FormUsuarioComponent } from './principal/evento/inscrever/form-usuario/form-usuario.component'; import { FormEnderecoComponent } from './principal/evento/inscrever/form-endereco/form-endereco.component'; import { FormPagamentoComponent } from './principal/evento/inscrever/form-pagamento/form-pagamento.component'; import { FormLoginComponent } from './principal/evento/inscrever/form-login/form-login.component'; import { HttpClientModule } from '@angular/common/http'; import { Interceptor } from './https-request-interceptor'; @NgModule({ declarations: [ AppComponent, CabecalhoComponent, NavegacaoComponent, PrincipalComponent, RodapeComponent, CatalogoComponent, EventoComponent, ApresentacaoComponent, LazyLoadingIMGDirective, CartaoComponent, PatrocinadorComponent, InscreverComponent, FormUsuarioComponent, FormEnderecoComponent, FormPagamentoComponent, FormLoginComponent ], imports: [ BrowserModule, AppRoutingModule, Interceptor, HttpClientModule ], providers: [NavegacaoService, CatalogoService], bootstrap: [AppComponent] }) export class AppModule { }<file_sep>/src/app/principal/evento/inscrever/form-endereco/form-endereco.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'form-endereco', templateUrl: './form-endereco.component.html', styleUrls: ['./form-endereco.component.css'] }) export class FormEnderecoComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/deploy.sh #!/bin/bash set -eo pipefail ############################ VARIABLES ############################ # ssh key's location # ssh_key="/home/circleci/arscrift/arscrift.pem" # # ############################ VARIABLES ############################ echo -e " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @ CONFIGURING AWS @ @ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" # CONFIGURE AWS_CLI aws --version aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY aws configure set default.region us-east-1 aws configure set default.output json echo -e " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @ DEPLOYING SERVICES TO AWS @ @ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" export _sshconfig=$(mktemp -u) export _ssh_ctrl_socket=$(mktemp -u) cfn_stack_name=arscrift jqScript=".AutoScalingGroups[] | select(.Tags[].Value == \"${cfn_stack_name}-Manager\").Instances[] | select(.HealthStatus == \"Healthy\").InstanceId" manager_id=$(aws autoscaling describe-auto-scaling-groups | jq -r "${jqScript}" | head -n1) manager=$(aws ec2 describe-instances --instance-ids ${manager_id} | jq -r '.Reservations[].Instances[].PublicDnsName') cat <<EOF > ${_sshconfig} User docker LogLevel error StrictHostKeyChecking no UserKnownHostsFile=/dev/null IdentityFile ${ssh_key} ControlPath ${_ssh_ctrl_socket} EOF chmod 400 ${ssh_key} echo $manager # Set up an SSH control socket for tunneling, so that we can cleanly close it when we're done ssh -M -F ${_sshconfig} -fnNT -L localhost:2374:/var/run/docker.sock ${manager} # configure all `docker` commands to communicate through the SSH tunnel instead of any local docker engine export DOCKER_HOST=localhost:2374 # now run `docker` commands as normal: docker stack deploy -c /home/circleci/arscrift/docker-compose.yml arscrift # Close the tunnel ssh -F ${_sshconfig} -O exit - # remove the temporary SSH-related files rm -f ${_ssh_ctrl_socket} unset DOCKER_HOST<file_sep>/src/app/principal/catalogo/cartao/cartao.component.ts import { Component, OnInit, Input } from '@angular/core'; import { EventoModel } from '../../evento/models/evento.model'; @Component({ selector: 'cartao', templateUrl: './cartao.component.html', styleUrls: ['./cartao.component.css'] }) export class CartaoComponent implements OnInit { @Input() evento: EventoModel; constructor() { } ngOnInit() { } }<file_sep>/docker-compose.yml version: '3.7' services: web: image: strund3r/arscrift-web:latest networks: - traefik-public - default deploy: replicas: 3 update_config: parallelism: 2 delay: 10s monitor: 2m failure_action: rollback rollback_config: parallelism: 2 delay: 10s monitor: 2m restart_policy: condition: on-failure placement: constraints: - node.role == worker labels: - "traefik.http.routers.web.rule=Host(`arscrift.digital`)" - "traefik.http.routers.web.service=web" - "traefik.http.services.web.loadbalancer.server.port=82" - "traefik.http.routers.web.tls.certresolver=leresolver" - "traefik.http.routers.web.entrypoints=websecure" dashboard: image: strund3r/arscrift-dashboard:latest networks: - traefik-public - default deploy: replicas: 3 update_config: parallelism: 2 delay: 10s monitor: 2m failure_action: rollback rollback_config: parallelism: 2 delay: 10s monitor: 2m restart_policy: condition: on-failure placement: constraints: - node.role == worker labels: - "traefik.http.routers.dashboard.rule=Host(`dashboard.arscrift.digital`)" - "traefik.http.routers.dashboard.service=dashboard" - "traefik.http.services.dashboard.loadbalancer.server.port=81" - "traefik.http.routers.dashboard.tls.certresolver=leresolver" - "traefik.http.routers.dashboard.entrypoints=websecure" dashboard-new: image: strund3r/arscrift-dashboard-new:latest networks: - traefik-public - default deploy: replicas: 3 update_config: parallelism: 2 delay: 10s monitor: 2m failure_action: rollback rollback_config: parallelism: 2 delay: 10s monitor: 2m restart_policy: condition: on-failure placement: constraints: - node.role == worker labels: - "traefik.http.routers.dashboard-new.rule=Host(`dashboard-new.arscrift.digital`)" - "traefik.http.routers.dashboard-new.service=dashboard-new" - "traefik.http.services.dashboard-new.loadbalancer.server.port=83" - "traefik.http.routers.dashboard-new.tls.certresolver=leresolver" - "traefik.http.routers.dashboard-new.entrypoints=websecure" api: image: strund3r/arscrift-api:latest networks: - traefik-public - default deploy: replicas: 3 update_config: parallelism: 2 delay: 10s monitor: 2m failure_action: rollback rollback_config: parallelism: 2 delay: 10s monitor: 2m restart_policy: condition: on-failure placement: constraints: - node.role == worker labels: - "traefik.http.routers.api.rule=Host(`api.arscrift.digital`)" - "traefik.http.routers.api.service=api" - "traefik.http.services.api.loadbalancer.server.port=8393" - "traefik.http.routers.api.tls.certresolver=leresolver" - "traefik.http.routers.api.entrypoints=websecure" networks: traefik-public: external: true default: external: false
19865e59d79a06a5d95c42d35a4758be2b3a085f
[ "YAML", "Markdown", "TypeScript", "Dockerfile", "Shell" ]
19
TypeScript
arscrift/web
e2fb04ae594255949bca6fdbcd5a10fce2c41cee
b642eac4c942ee552d7a7d2b421f8eab0f4a6a0e
refs/heads/master
<file_sep>package flags import "github.com/clipperhouse/typewriter" var flags = &typewriter.Template{ Name: "flags", Text: ` // {{.SliceName}} is a slice of {{.Type}}. type {{.SliceName}} []{{.Type}} // ErrMutex says that a result had more than one mutually exclusive bit set. var ErrMutex = errors.New("attempt to set mutually exclusive {{.Type}}") // ErrUnrecognized says that a string does not map to a value var ErrUnrecognized = errors.New("unrecognized string") // Punch turns a particular bit or set of {{.Type}} on. // If a bit that is part of a mutually exclusive set is // turned on, all of the other bits in that set will be // turned off. If multiple bits in the mutually exclusive // set are turned on, only the highest bit will remain on. func (f *{{.Type}}) Punch(v {{.Type}}) {{.Type}} { var x {{.Type}} s := v.Unpack() for _, b := range s { x = *f | b y := x & MutuallyExclusive if !y.IsEmpty() && !(y & (y - 1)).IsEmpty() { z := x &^ MutuallyExclusive x = z | b } } *f = x return x } // Set turns a particular bit or set of {{.Type}} on, and // returns ErrMutex if an attempt is made to turn mutually exclusive // bits on at the same time. func (f *{{.Type}}) Set(v {{.Type}}) ({{.Type}}, error) { x := *f | v y := x & MutuallyExclusive if !y.IsEmpty() && !(y & (y - 1)).IsEmpty() { return *f, ErrMutex } *f = x return x, nil } // Unset turns a particular bit or set of {{.Type}} off. func (f *{{.Type}}) Unset(v {{.Type}}) ({{.Type}}, error) { x := *f &^ v *f = x return x, nil } // IsEmpty is true if no {{.Type}} are on. func (f {{.Type}}) IsEmpty() bool { return f == 0 } // IsSet determines if a Flags has a particular bit or set of {{.Type}} on. func (f {{.Type}}) IsSet(v {{.Type}}) bool { return f&v != 0 } // Unpack creates a {{.SliceName}} from a single {{.Type}}, with each item in the list // having only a single bit on. func (f {{.Type}}) Unpack() {{.SliceName}} { var v {{.Type}} fl := {{.SliceName}}{} for v = 1; v <= 1<<31; v <<= 1 { if f.IsSet(v) { fl = append(fl, v) } if v == 1<<31 { break } } return fl } // Pack packs a {{.SliceName}} into a single {{.Type}} value. func (fl {{.SliceName}}) Pack() ({{.Type}}, error) { var f {{.Type}} var err error for _, v := range fl { f, err = f.Set(v) if err != nil { return 0, err } } return f, nil } // Unstring turns the string representation of a Flags into a Flags value. // This is meant to be used with constants that have had String() and // JSON Marshal/Unmarshal routines generated with stringer and jsonenums. func Unstring(s string) ({{.Type}}, error) { var f {{.Type}} var ok bool if f, ok = _{{.Type}}NameToValue[s]; !ok { return 0, ErrUnrecognized } return f, nil } // PackStrings takes a slice of string representations of {{.Type}} and packs // them into a single Flags value. func PackStrings(fs []string) ({{.Type}}, error) { var f, v {{.Type}} var err error for _, s := range fs { v, err = Unstring(s) if err != nil { return 0, err } f, err = f.Set(v) if err != nil { return 0, err } } return f, nil } `, } <file_sep>// Generated by: main // TypeWriter: flags // Directive: +gen on Bits package example import "errors" // BitsSlice is a slice of Bits. type BitsSlice []Bits // ErrMutex says that a result had more than one mutually exclusive bit set. var ErrMutex = errors.New("attempt to set mutually exclusive Bits") // ErrUnrecognized says that a string does not map to a value var ErrUnrecognized = errors.New("unrecognized string") // Punch turns a particular bit or set of Bits on. // If a bit that is part of a mutually exclusive set is // turned on, all of the other bits in that set will be // turned off. If multiple bits in the mutually exclusive // set are turned on, only the highest bit will remain on. func (f *Bits) Punch(v Bits) Bits { var x Bits s := v.Unpack() for _, b := range s { x = *f | b y := x & MutuallyExclusive if !y.IsEmpty() && !(y & (y - 1)).IsEmpty() { z := x &^ MutuallyExclusive x = z | b } } *f = x return x } // Set turns a particular bit or set of Bits on, and // returns ErrMutex if an attempt is made to turn mutually exclusive // bits on at the same time. func (f *Bits) Set(v Bits) (Bits, error) { x := *f | v y := x & MutuallyExclusive if !y.IsEmpty() && !(y & (y - 1)).IsEmpty() { return *f, ErrMutex } *f = x return x, nil } // Unset turns a particular bit or set of Bits off. func (f *Bits) Unset(v Bits) (Bits, error) { x := *f &^ v *f = x return x, nil } // IsEmpty is true if no Bits are on. func (f Bits) IsEmpty() bool { return f == 0 } // IsSet determines if a Flags has a particular bit or set of Bits on. func (f Bits) IsSet(v Bits) bool { return f&v != 0 } // Unpack creates a BitsSlice from a single Bits, with each item in the list // having only a single bit on. func (f Bits) Unpack() BitsSlice { var v Bits fl := BitsSlice{} for v = 1; v <= 1<<31; v <<= 1 { if f.IsSet(v) { fl = append(fl, v) } if v == 1<<31 { break } } return fl } // Pack packs a BitsSlice into a single Bits value. func (fl BitsSlice) Pack() (Bits, error) { var f Bits var err error for _, v := range fl { f, err = f.Set(v) if err != nil { return 0, err } } return f, nil } // Unstring turns the string representation of a Flags into a Flags value. // This is meant to be used with constants that have had String() and // JSON Marshal/Unmarshal routines generated with stringer and jsonenums. func Unstring(s string) (Bits, error) { var f Bits var ok bool if f, ok = _BitsNameToValue[s]; !ok { return 0, ErrUnrecognized } return f, nil } // PackStrings takes a slice of string representations of Bits and packs // them into a single Flags value. func PackStrings(fs []string) (Bits, error) { var f, v Bits var err error for _, s := range fs { v, err = Unstring(s) if err != nil { return 0, err } f, err = f.Set(v) if err != nil { return 0, err } } return f, nil } <file_sep>// generated by jsonenums -type=Bits; DO NOT EDIT package example import ( "encoding/json" "fmt" ) var ( _BitsNameToValue = map[string]Bits{ "Bit01": Bit01, "Bit02": Bit02, "Bit03": Bit03, "Bit04": Bit04, "Bit05": Bit05, "Bit06": Bit06, "Bit07": Bit07, "Bit08": Bit08, "Bit09": Bit09, "Bit10": Bit10, "Bit11": Bit11, "Bit12": Bit12, "Bit13": Bit13, "Bit14": Bit14, "Bit15": Bit15, "Bit16": Bit16, "Bit17": Bit17, "Bit18": Bit18, "Bit19": Bit19, "Bit20": Bit20, "Bit21": Bit21, "Bit22": Bit22, "Bit23": Bit23, "Bit24": Bit24, "Bit25": Bit25, "Bit26": Bit26, "Bit27": Bit27, "Bit28": Bit28, "Bit29": Bit29, "Bit30": Bit30, "Bit31": Bit31, "Bit32": Bit32, "AnyEven": AnyEven, "AnyOdd": AnyOdd, "MutuallyExclusive": MutuallyExclusive, } _BitsValueToName = map[Bits]string{ Bit01: "Bit01", Bit02: "Bit02", Bit03: "Bit03", Bit04: "Bit04", Bit05: "Bit05", Bit06: "Bit06", Bit07: "Bit07", Bit08: "Bit08", Bit09: "Bit09", Bit10: "Bit10", Bit11: "Bit11", Bit12: "Bit12", Bit13: "Bit13", Bit14: "Bit14", Bit15: "Bit15", Bit16: "Bit16", Bit17: "Bit17", Bit18: "Bit18", Bit19: "Bit19", Bit20: "Bit20", Bit21: "Bit21", Bit22: "Bit22", Bit23: "Bit23", Bit24: "Bit24", Bit25: "Bit25", Bit26: "Bit26", Bit27: "Bit27", Bit28: "Bit28", Bit29: "Bit29", Bit30: "Bit30", Bit31: "Bit31", Bit32: "Bit32", AnyEven: "AnyEven", AnyOdd: "AnyOdd", MutuallyExclusive: "MutuallyExclusive", } ) func init() { var v Bits if _, ok := interface{}(v).(fmt.Stringer); ok { _BitsNameToValue = map[string]Bits{ interface{}(Bit01).(fmt.Stringer).String(): Bit01, interface{}(Bit02).(fmt.Stringer).String(): Bit02, interface{}(Bit03).(fmt.Stringer).String(): Bit03, interface{}(Bit04).(fmt.Stringer).String(): Bit04, interface{}(Bit05).(fmt.Stringer).String(): Bit05, interface{}(Bit06).(fmt.Stringer).String(): Bit06, interface{}(Bit07).(fmt.Stringer).String(): Bit07, interface{}(Bit08).(fmt.Stringer).String(): Bit08, interface{}(Bit09).(fmt.Stringer).String(): Bit09, interface{}(Bit10).(fmt.Stringer).String(): Bit10, interface{}(Bit11).(fmt.Stringer).String(): Bit11, interface{}(Bit12).(fmt.Stringer).String(): Bit12, interface{}(Bit13).(fmt.Stringer).String(): Bit13, interface{}(Bit14).(fmt.Stringer).String(): Bit14, interface{}(Bit15).(fmt.Stringer).String(): Bit15, interface{}(Bit16).(fmt.Stringer).String(): Bit16, interface{}(Bit17).(fmt.Stringer).String(): Bit17, interface{}(Bit18).(fmt.Stringer).String(): Bit18, interface{}(Bit19).(fmt.Stringer).String(): Bit19, interface{}(Bit20).(fmt.Stringer).String(): Bit20, interface{}(Bit21).(fmt.Stringer).String(): Bit21, interface{}(Bit22).(fmt.Stringer).String(): Bit22, interface{}(Bit23).(fmt.Stringer).String(): Bit23, interface{}(Bit24).(fmt.Stringer).String(): Bit24, interface{}(Bit25).(fmt.Stringer).String(): Bit25, interface{}(Bit26).(fmt.Stringer).String(): Bit26, interface{}(Bit27).(fmt.Stringer).String(): Bit27, interface{}(Bit28).(fmt.Stringer).String(): Bit28, interface{}(Bit29).(fmt.Stringer).String(): Bit29, interface{}(Bit30).(fmt.Stringer).String(): Bit30, interface{}(Bit31).(fmt.Stringer).String(): Bit31, interface{}(Bit32).(fmt.Stringer).String(): Bit32, interface{}(AnyEven).(fmt.Stringer).String(): AnyEven, interface{}(AnyOdd).(fmt.Stringer).String(): AnyOdd, interface{}(MutuallyExclusive).(fmt.Stringer).String(): MutuallyExclusive, } } } // MarshalJSON is generated so Bits satisfies json.Marshaler. func (r Bits) MarshalJSON() ([]byte, error) { if s, ok := interface{}(r).(fmt.Stringer); ok { return json.Marshal(s.String()) } s, ok := _BitsValueToName[r] if !ok { return nil, fmt.Errorf("invalid Bits: %d", r) } return json.Marshal(s) } // UnmarshalJSON is generated so Bits satisfies json.Unmarshaler. func (r *Bits) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("Bits should be a string, got %s", data) } v, ok := _BitsNameToValue[s] if !ok { return fmt.Errorf("invalid Bits %q", s) } *r = v return nil } <file_sep>package example import ( "encoding/json" "testing" . "github.com/smartystreets/goconvey/convey" ) func TestEmpty(t *testing.T) { var m Bits Convey("New Bits should be empty.", t, func() { So(m, ShouldEqual, 0) }) } func TestSetSingle(t *testing.T) { var m Bits m.Set(Bit01) Convey("Bits should be 1.", t, func() { So(m, ShouldEqual, 1) }) Convey("Bits should have SystemAdmin flag set.", t, func() { So(m.IsSet(Bit01), ShouldEqual, true) }) } func TestSetMultiple(t *testing.T) { var m Bits m.Set(Bit01 | Bit32) Convey("Bits should have Bit01 & Bit32 flag set.", t, func() { So(m.IsSet(Bit01|Bit32), ShouldEqual, true) }) Convey("Bits should have Bit01 flag set.", t, func() { So(m.IsSet(Bit01), ShouldEqual, true) }) Convey("Bits should not have Bit31 set.", t, func() { So(m.IsSet(Bit31), ShouldEqual, false) }) } func TestUnsetSingle(t *testing.T) { var m Bits m.Set(Bit01) Convey("Bits should have Bit01 flag set.", t, func() { So(m.IsSet(Bit01), ShouldEqual, true) }) m.Unset(Bit01) Convey("Bits should not have Bit01 flag set.", t, func() { So(m.IsSet(Bit01), ShouldEqual, false) }) Convey("Bits should be empty.", t, func() { So(m.IsEmpty(), ShouldEqual, true) }) } func TestUnsetMultple(t *testing.T) { var m Bits m.Set(Bit01 | Bit32) Convey("Bits should have Bit01 & Bit32 flag set.", t, func() { So(m.IsSet(Bit01|Bit32), ShouldEqual, true) }) m.Unset(Bit32) Convey("Bits should have Bit01 flag set.", t, func() { So(m.IsSet(Bit01), ShouldEqual, true) }) Convey("Bits should not have Bit32 flag set.", t, func() { So(m.IsSet(Bit32), ShouldEqual, false) }) } func TestStringer(t *testing.T) { Convey("Bits stringer names are generated.", t, func() { So(Bit01.String(), ShouldEqual, "Bit01") }) } func TestJSONEnumsMarshal(t *testing.T) { j, _ := json.Marshal(Bit01) Convey("Bits jsonenum marshal works.", t, func() { So(j, ShouldResemble, []byte("\"Bit01\"")) }) } func TestJSONEnumsUnmarshal(t *testing.T) { var m Bits json.Unmarshal([]byte("\"Bit01\""), &m) Convey("Bits jsonenum unmarshal works.", t, func() { So(m, ShouldEqual, Bit01) }) } func TestUnstring(t *testing.T) { f, _ := Unstring("Bit01") Convey("Bits unstring works.", t, func() { So(f, ShouldEqual, Bit01) }) } func TestMutex(t *testing.T) { var m Bits m, err := m.Set(MutuallyExclusive) Convey("Bits mutex works.", t, func() { So(err, ShouldEqual, ErrMutex) }) } func TestPunch(t *testing.T) { var m Bits m.Set(Bit01) m = m.Punch(Bit02 | Bit03) Convey("Bits toggle works.", t, func() { So(m, ShouldEqual, Bit03) }) } <file_sep>// Generated by: main // TypeWriter: stringer // Directive: +gen on Bits package example import ( "fmt" ) const _Bits_name = "Bit01Bit02Bit03MutuallyExclusiveBit04Bit05Bit06Bit07Bit08Bit09Bit10Bit11Bit12Bit13Bit14Bit15Bit16Bit17Bit18Bit19Bit20Bit21Bit22Bit23Bit24Bit25Bit26Bit27Bit28Bit29Bit30Bit31AnyOddBit32AnyEven" var _Bits_map = map[Bits]string{ 1: _Bits_name[0:5], 2: _Bits_name[5:10], 4: _Bits_name[10:15], 7: _Bits_name[15:32], 8: _Bits_name[32:37], 16: _Bits_name[37:42], 32: _Bits_name[42:47], 64: _Bits_name[47:52], 128: _Bits_name[52:57], 256: _Bits_name[57:62], 512: _Bits_name[62:67], 1024: _Bits_name[67:72], 2048: _Bits_name[72:77], 4096: _Bits_name[77:82], 8192: _Bits_name[82:87], 16384: _Bits_name[87:92], 32768: _Bits_name[92:97], 65536: _Bits_name[97:102], 131072: _Bits_name[102:107], 262144: _Bits_name[107:112], 524288: _Bits_name[112:117], 1048576: _Bits_name[117:122], 2097152: _Bits_name[122:127], 4194304: _Bits_name[127:132], 8388608: _Bits_name[132:137], 16777216: _Bits_name[137:142], 33554432: _Bits_name[142:147], 67108864: _Bits_name[147:152], 134217728: _Bits_name[152:157], 268435456: _Bits_name[157:162], 536870912: _Bits_name[162:167], 1073741824: _Bits_name[167:172], 1431655765: _Bits_name[172:178], 2147483648: _Bits_name[178:183], 2863311530: _Bits_name[183:190], } func (i Bits) String() string { if str, ok := _Bits_map[i]; ok { return str } return fmt.Sprintf("Bits(%d)", i) } <file_sep>package flags import ( "io" "github.com/clipperhouse/typewriter" ) type model struct { Type typewriter.Type SliceName string TypeParameter typewriter.Type typewriter.TagValue } var templates = typewriter.TemplateSlice{ flags, } func init() { err := typewriter.Register(NewWriter()) if err != nil { panic(err) } } func NewWriter() *Writer { return &Writer{} } func SliceName(typ typewriter.Type) string { return typ.Name + "Slice" } type Writer struct{} func (fw *Writer) Name() string { return "flags" } func (fw *Writer) Imports(typ typewriter.Type) (result []typewriter.ImportSpec) { return []typewriter.ImportSpec{ {Path: "encoding/json"}, {Path: "errors"}, } } func (fw *Writer) Write(w io.Writer, typ typewriter.Type) error { tag, found := typ.FindTag(fw) if !found { return nil } tmpl, err := templates.ByTag(typ, tag) if err != nil { return err } m := model{ Type: typ, SliceName: SliceName(typ), } if err := tmpl.Execute(w, m); err != nil { return err } return nil } <file_sep>package example //go:generate jsonenums -type=Bits //go:generate gen // +gen stringer flags type Bits uint32 const ( Bit01 Bits = 1 << iota Bit02 Bit03 Bit04 Bit05 Bit06 Bit07 Bit08 Bit09 Bit10 Bit11 Bit12 Bit13 Bit14 Bit15 Bit16 Bit17 Bit18 Bit19 Bit20 Bit21 Bit22 Bit23 Bit24 Bit25 Bit26 Bit27 Bit28 Bit29 Bit30 Bit31 Bit32 ) const ( AnyEven Bits = Bit02 | Bit04 | Bit06 | Bit08 | Bit10 | Bit12 | Bit14 | Bit16 | Bit18 | Bit20 | Bit22 | Bit24 | Bit26 | Bit28 | Bit30 | Bit32 AnyOdd Bits = Bit01 | Bit03 | Bit05 | Bit07 | Bit09 | Bit11 | Bit13 | Bit15 | Bit17 | Bit19 | Bit21 | Bit23 | Bit25 | Bit27 | Bit29 | Bit31 ) const MutuallyExclusive Bits = Bit01 | Bit02 | Bit03 <file_sep>## flags Typewriter This is a [gen](http://clipperhouse.github.io/gen/) typewriter for creating bit flag types. <file_sep>rm bits_*.go mv example_test.go example_test go generate mv example_test example_test.go go test
6dc6b0b447ba997c821b0232d114f58da64637df
[ "Markdown", "Go", "Shell" ]
9
Go
msmprojects/flags
b979f69f750e9f4f7a03fa60d6c58158803c70a0
5eeda8a9c35f6fd404d4c1cae5b704fc11d63f3c
refs/heads/master
<repo_name>mtjarrett/fancy-index<file_sep>/README.md # Fancy Index `This fork allows for icons to be replaced with thumbnails of image and pdf files. It also includes a thumbnailer to use when dealing with larger images as well as a number of smaller features to improve UI such as grid/list view.` A responsive Apache index page. I was tired of seeing the ugly apache-generated index page, so I decided to do something about it. Inspired by [Seti UI](https://github.com/jesseweed/seti-ui) and [atom file-icons](https://github.com/file-icons/atom), this project adds an `.htaccess` file which tells apache to use a table, among other things, instead of `<pre>`. ### Before Fancy Index: ![before fancy index](before.png) ### After Fancy Index ![after fancy index](after.png) ## Setup 1. Clone `fancy-index` repo into /var/www/html or sub directory as desired (instructions will assume this directory). 2. Move `images`, `thumbnailer.py`, and `.htaccess` up one level (/var/www/html). 3. Edit /etc/httpd/conf.d/welcome.conf so that every line is commented out. 4. Edit /etc/httpd/conf.d/userdir.conf so that the final lines read: `<Directory "/var/www/html"> AllowOverride All Options MultiViews Indexes FollowSymLinks Require all granted </Directory>` Note: If security is an issue and you would rather not use .htaccess files, the contents of the included .htaccess file can be transfered to `httpd.conf`. If you do this, skip step 4. 5. Restart httpd 6. Run `thumbnailer.py` so that thumbnails in `images` will appear. -Thumbnailer uses imagemagick. Ensure this is installed on your system. -Thumbnailer requires an argument specifying the root directory for images to convert. ex:`python thumbnailer.py /var/www/html/images` 7a. Create cron job to run `thumbnailer.py`. ex. `* 16 * * * /usr/bin/python /var/www/html/thumbnailer.py <path>` 7b. Manually run `thumbnailer.py` after each change to `images` directory. 8. Drink all the beer! ## Mobile Comparison Now you don't have to zoom in or be a sniper with your finger! | Default | Fancy | |:--------:|:------:| |![before fancy index (mobile)](before_mobile.png) | ![after fancy index (mobile)](after_mobile.png)| ## Customizing hidden files and directories If you want to hide some files or directories, for example the `fancy-index` directory, there is a `IndexIgnore` directive in `.htaccess` file. 1. Edit `.htaccess` file in root directory. 2. Look for the "IGNORE THESE FILES" section. 3. Update the `IndexIgnore` directive with the path of files and directories to hide, separated by spaces. * For example: `IndexIgnore .ftpquota .DS_Store .git /fancy-index` 4. Save the changes. 5. Reload the index page. <file_sep>/script.js function fixTable() { const table = document.querySelector('table'); // Remove <hr>s Array.from(table.querySelectorAll('hr')).forEach(({ parentNode }) => { const row = parentNode.parentNode; row.parentNode.removeChild(row); }); // Make a table head. const thead = document.createElement('thead'); const firstRow = table.querySelector('tr'); firstRow.parentNode.removeChild(firstRow); thead.appendChild(firstRow); table.insertBefore(thead, table.firstElementChild); // Remove the first column and put the image in the next. const rows = Array.from(table.querySelectorAll('tr')); rows.forEach((row) => { const iconColumn = row.children[0]; const fileColumn = row.children[1]; // Remove icon column. row.removeChild(iconColumn); //back.svg icon for Parent Directory doesn't appear in grid, the following changes the file type to jpg if(document.getElementsByTagName("img")[0].getAttribute("alt") == "[PARENTDIR]"){ document.getElementsByTagName("img")[0].setAttribute("src","/fancy-index/icons/back.jpg"); } //replaces default img icons with thumbnails const thumbnail = fileColumn.firstElementChild.href; //list of image types that will be changed var thumb = thumbnail.split('.').pop(); if (thumb=='jpg' || thumb=='JPG' || thumb=='png' || thumb=='svg' || thumb=='jpeg' || thumb=='gif' || thumb=='tiff' || thumb=='tif' || thumb=='bmp' || thumb=='pdf') { //if image is in the file defined by the thumbnailer or deeper, then it will use the image from '.thumbnails' as its thumbnail var image = document.createElement("img"); image.setAttribute("src",".thumbnails/thumb." + thumbnail.split("/").pop().replace(/\.[^/.]+$/, "") + ".jpg"); image.setAttribute("onerror","this.src = '/fancy-index/icons/file-media.svg'"); //all file types that are not defined above will use themselves as a thumbnail }else { var image = iconColumn.firstElementChild; } //if all else fails, return anyway if (!image) { return; } // Wrap icon in a div.img-wrap. const div = document.createElement('div'); div.className = 'img-wrap'; div.appendChild(image); // Insert icon before filename. fileColumn.insertBefore(div, fileColumn.firstElementChild); }); } // add link to images function imageLinks(){ var thumbnailImage = document.querySelectorAll('tbody .img-wrap img'); var thumbnailLink = document.querySelectorAll('tbody .indexcolname a'); for(var i=0; i<thumbnailImage.length; i++){ $(thumbnailImage[i]).wrap("<a href=" + thumbnailLink[i].href + "></a>"); } } // Underscore string's titleize. function titleize(str) { return decodeURI(str).toLowerCase().replace(/(?:^|\s|-)\S/g, c => c.toUpperCase()); } function addTitle() { let path = window.location.pathname.replace(/\/$/g, ''); let titleText; //create 'parent directory' button var parentImage = document.createElement("img"); parentImage.setAttribute("src", "/fancy-index/icons/back.jpg"); parentImage.setAttribute("height", "48px"); parentImage.setAttribute("id", "parentImage"); if (path) { const parts = path.split('/'); path = parts[parts.length - 1]; titleText = titleize(path).replace(/-|_/g, ' '); } else { titleText = window.location.host; } titleText = `${titleText}`; const container = document.createElement('div'); container.id = 'page-header'; const h1 = document.createElement('h1'); h1.appendChild(document.createTextNode(titleText)); container.appendChild(parentImage); container.appendChild(h1); document.body.insertBefore(container, document.body.firstChild); document.title = titleText; //adds link for parent directory image $('#parentImage').wrap('<a href="../"></a>'); } function getTimeSince(seconds) { let intervalType; let interval = Math.floor(seconds / 31536000); if (interval >= 1) { intervalType = 'year'; } else { interval = Math.floor(seconds / 2592000); if (interval >= 1) { intervalType = 'month'; } else { interval = Math.floor(seconds / 86400); if (interval >= 1) { intervalType = 'day'; } else { interval = Math.floor(seconds / 3600); if (interval >= 1) { intervalType = 'hour'; } else { interval = Math.floor(seconds / 60); if (interval >= 1) { intervalType = 'minute'; } else { interval = seconds; intervalType = 'second'; } } } } } if (interval > 1 || interval === 0) { intervalType += 's'; } return `${interval} ${intervalType}`; } function fixTime() { const dates = Array.from(document.querySelectorAll('.indexcollastmod')); const now = new Date(); dates.forEach((date, i) => { const stamp = date.textContent.trim(); if (!stamp || i === 0) return; // 2014-12-09 10:43 -> 2014, 11, 09, 10, 43, 0. const parts = stamp.split(' '); const day = parts[0].split('-'); const timeOfDay = parts[1].split(':'); const year = parseInt(day[0], 10); const month = parseInt(day[1], 10) - 1; const _day = parseInt(day[2], 10); const hour = parseInt(timeOfDay[0], 10); const minutes = parseInt(timeOfDay[1], 10); const time = new Date(year, month, _day, hour, minutes, 0); const difference = Math.round((now.getTime() - time.getTime()) / 1000); date.textContent = `${getTimeSince(difference)} ago`; }); } function addFilter() { const input = document.createElement('input'); input.type = 'filter'; input.id = 'filter'; input.setAttribute('placeholder', 'Filter'); document.getElementById('page-header').appendChild(input); const sortColumns = Array.from(document.querySelectorAll('thead a')); const nameColumns = Array.from(document.querySelectorAll('tbody .indexcolname')); const rows = nameColumns.map(({ parentNode }) => parentNode); const fileNames = nameColumns.map(({ textContent }) => textContent); function filter(value) { // Allow tabbing out of the filter input and skipping the sort links // when there is a filter value. sortColumns.forEach((link) => { if (value) { link.tabIndex = -1; } else { link.removeAttribute('tabIndex'); } }); // Test the input against the file/folder name. let even = false; fileNames.forEach((name, i) => { if (!value || name.toLowerCase().includes(value.toLowerCase())) { const className = even ? 'even' : ''; rows[i].className = className; even = !even; } else { rows[i].className = 'hidden'; } }); } document.getElementById('filter').addEventListener('input', ({ target }) => { filter(target.value); }); filter(''); } //used to add grid and list buttons function addButton(buttonImg, toggle) { const viewButton = document.createElement("button"); viewButton.setAttribute("type","button"); viewButton.setAttribute("background-image",buttonImg); var buttonImage = document.createElement("img"); buttonImage.setAttribute("src", buttonImg); buttonImage.setAttribute("width","35px"); viewButton.appendChild(buttonImage); document.getElementById('page-header').appendChild(viewButton); viewButton.onclick = function(){setCookie(toggle)}; } function buttonFunction(headDisplay,bodyDisplay,bodyWrap,fileDisplay,imgSize,imgDisplay,elemColor) { var elem = document.querySelectorAll('tbody .img-wrap'); var elemBackground = document.querySelectorAll('tbody .even'); var fileDataHidden = document.querySelectorAll('tbody tr td'); var tableHead = document.querySelector('thead'); var tableBody = document.querySelector('tbody'); tableHead.style.display = headDisplay; tableBody.style.display = bodyDisplay; tableBody.style['flex-wrap'] = bodyWrap; for (var i=0; i<fileDataHidden.length; i++) { if(fileDataHidden[i].className != "indexcolname") fileDataHidden[i].style.display = fileDisplay; } for (var i=0; i<elem.length; i++) { elem[i].style.height = imgSize; elem[i].style.width = imgSize; elem[i].style.display = imgDisplay; } for (var i=0; i<elemBackground.length; i++) { elemBackground[i].style.backgroundColor = elemColor; } } function addSlider() { const sliderBar = document.createElement("input"); //sliderBar.setAttribute("type","range"); sliderBar.setAttribute("id", "slider1"); sliderBar.setAttribute("type","range"); sliderBar.setAttribute("min","1"); sliderBar.setAttribute("max","7"); if(document.cookie.split("state=").pop() == 0){ sliderBar.setAttribute("value","1"); }else{ sliderBar.setAttribute("value",document.cookie.split("state=").pop()); } sliderBar.setAttribute("oninput","sliderFunction(this.value)"); document.getElementById('page-header').appendChild(sliderBar); //cookie needs to switch from toggle to a range //32 64 128 192 256 //sliderBar.onclick = function(){setCookie(toggle)}; } function sliderFunction(value){ setCookie(value); } function setCookie(toggle){ document.cookie ='grid_state=' + toggle + '; path=/'; readCookie(toggle); console.log("toggle: " + toggle); document.getElementById("slider1").value = toggle; } //0=list; 1-7=grid sizes function readCookie(state){ var sliderSet = document.getElementById('slider1'); sliderSet.setAttribute('value',state); if(state == 7){ buttonFunction("none","flex","wrap","none","256px","flex","white"); } else if(state == 6){ buttonFunction("none","flex","wrap","none","224px","flex","white"); } else if(state == 5){ buttonFunction("none","flex","wrap","none","192px","flex","white"); } else if(state == 4){ buttonFunction("none","flex","wrap","none","160px","flex","white"); } else if(state == 3){ buttonFunction("none","flex","wrap","none","128px","flex","white"); } else if(state == 2){ buttonFunction("none","flex","wrap","none","96px","flex","white"); } else if(state == 1){ buttonFunction("none","flex","wrap","none","64px","flex","white"); } else { buttonFunction("","","","","48px","",""); sliderSet.setAttribute('value','1'); } console.log("state: " + state); console.log(document.getElementById('slider1').value); } //Add parent directory image at top left function addParentImage(){ var parentImage = document.createElement("img"); parentImage.setAttribute("src", "/fancy-index/icons/back.jpg"); document.getElementById('page-header').appendChild(parentImage); } //order of elements at load fixTable(); addTitle(); fixTime(); addButton("/fancy-index/icons/list.png", 0); addButton("/fancy-index/icons/grid.png", 7); addSlider(); addFilter(); imageLinks(); readCookie(document.cookie.split("state=").pop()); <file_sep>/thumbnailer.py #!/usr/bin/python import os import sys import re rootDir = "/var/www/html/image/" #rootDir = sys.argv[1] #Recursive walkthrough from "rootDir" for dirName, subdirList, fileList in os.walk(rootDir): #print ("Checking for changes in directory: \'%s\'" % (dirName)) #ignore hidden folders (starting with ".") subdirList[:] = [d for d in subdirList if not d[0] == '.'] #check and/or create hidden thumbnail directory if (os.path.isdir("%s/.thumbnails/" % (dirName)) == False): os.system("mkdir \'%s\'/.thumbnails" % (dirName)) #cycle through file and add thumbnails to thumbnail directory for filename in os.listdir('%s' % (dirName)): #image thumbnailer if (filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".svg") or filename.endswith(".jpeg") or filename.endswith(".JPG") or filename.endswith(".gif") or filename.endswith(".tiff") or filename.endswith(".tif") or filename.endswith(".bmp")): fileTime = float(os.path.getctime("%s/%s" % (dirName, filename))) stripFile = os.path.splitext(os.path.basename(filename))[0] filename = filename.replace('*','\*') stripFile2 = stripFile.replace('*','\*') if(os.path.isfile("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))): thumbTime = float(os.path.getctime("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))) else: thumbTime = 0.0 if ((fileTime) > thumbTime): #print("Thumbnailing: \'%s\'/\'%s\'" % (dirName, filename)) os.system("convert -thumbnail 256x256 \'%s\'/\'%s\' \'%s\'/.thumbnails/thumb.\'%s\'.jpg" % (dirName, filename, dirName, stripFile2)) if '\*' in stripFile2: os.system("mv \"%s/.thumbnails/thumb.%s.jpg\" \"%s/.thumbnails/thumb.%s.jpg\"" % (dirName, stripFile2, dirName, stripFile)) #pdf thumbnailer elif (filename.endswith(".pdf")): stripFile = os.path.splitext(os.path.basename(filename))[0] filename = filename.replace('*','\*') stripFile2 = stripFile.replace('*','\*') if(os.path.isfile("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))): thumbTime = float(os.path.getctime("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))) else: thumbTime = 0.0 if ((fileTime) > thumbTime): os.system("convert -colorspace sRGB \'%s\'/\'%s\'[0] -scale 256x256 -background white -flatten \'%s\'/.thumbnails/thumb.\'%s\'.jpg" % (dirName, filename, dirName, stripFile2)) if '\*' in stripFile2: os.system("mv \"%s/.thumbnails/thumb.%s.jpg\" \"%s/.thumbnails/thumb.%s.jpg\"" % (dirName, stripFile2, dirName, stripFile)) #video thumbnailer elif (filename.endswith(".mp4")): stripFile = os.path.splitext(os.path.basename(filename))[0] filename = filename.replace('*','\*') stripFile2 = stripFile.replace('*','\*') if(os.path.isfile("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))): thumbTime = float(os.path.getctime("%s/.thumbnails/thumb.%s.jpg" % (dirName, stripFile))) else: thumbTime = 0.0 if ((fileTime) > thumbTime): os.system("convert \'%s\'/\'%s\'[100] \'%s\'/.thumbnails/thumb.\'%s\'.png" % (dirName, filename, dirName, stripFile2)) if '\*' in stripFile2: os.system("mv \"%s/.thumbnails/thumb.%s.jpg\" \"%s/.thumbnails/thumb.%s.jpg\"" % (dirName, stripFile2, dirName, stripFile))
95c8ea904988e303a5ad57932e747a1f5c6bd297
[ "Markdown", "Python", "JavaScript" ]
3
Markdown
mtjarrett/fancy-index
d6df74ea415c830391c3b2261fcc18f05ecac1fe
d4ce4d1096f310af50b6175b2cddaea3d28c3208
refs/heads/master
<file_sep>function Node(uID, x ,y){ this.id = uID; this.vertex=new Vertex(x,y); } Node.prototype.position = function() { return this.vertex; } Node.prototype.equals = function(node) { var rv = false; if (this.id == node.id) { rv = true; } return rv; } <file_sep>function MapGenerator(difficulty){ //returns a map object var mapGraph= new Graph(); var structureList= {}; } generateMapGraph(){} toNearestStation(){} //returns a fraction to indicate how much gas it would take to get to nearest station toNearestStructure(){} //same as previous but for non-gas stations denominatorPool(difficulty){} //rng the underlying map denominator from a pool of values based on difficulty validateMap(){} //make sure the map isn't impossible <file_sep>var xmldoc=loadXML("map.xml"); var map1= new Map(xmldoc); //console.log(map1);<file_sep>// This file describes the function prototypes for the Vertex JavaScript class function Vertex(xIn, yIn) function distance(pt1, pt2) Vertex.prototype.clone = function() Vertex.prototype.equals = function(vertex) Vertex.prototype.slope = function(vertex) Vertex.prototype.inverse = function() Vertex.prototype.applyRotation = function(angle) Vertex.prototype.move = function(offset) Vertex.prototype.scale = function(factor) <file_sep>function Structure(nodeID, StructType, StructCaption, Points) { this.nodeID=nodeID; this.StructType=StructType; this.StructCaption=StructCaption; this.Points=Points; this.visited=false; } Structure.prototype.position = function() { return this.nodeID; } Structure.prototype.getType = function() { return this.StructType; } Structure.prototype.getCaption = function(){ return this.StructCaption; } Structure.prototype.pointsString = function(){ return this.Points.toString(); } Structure.prototype.equals = function(struct){ var rv=false; if (this.nodeID==struct.nodeID) rv=true; return rv; }<file_sep>function Map(){ var mapGraph; var structureList; } getEdgeMatrix(){} importXML(){} exportXML(){} <file_sep>// This file describes the function prototypes for the Graph JavaScript class function Graph() Graph.prototype.addNode = function(node, connectionIdList) Graph.prototype.clearGraph = function() Graph.prototype.addConnection = function(nodeID, nodeToConnect) Graph.prototype.findNodeArray = function(nodeID) Graph.prototype.areNodesConnected = function(nodeID, nodeIDMatch) <file_sep>// This file describes the function prototypes for the Node JavaScript class function Node(uID,x,y) Node.prototype.position = function() Node.prototype.equals = function(node)<file_sep>function Structure(nodeID, StructType, StructCaption, Points){ this.visited=false; } Structure.prototype.position=function(){} //returns the nodeID Structure.prototype.getType=function(){} //StructType will correspond with the filename for the icon Structure.prototype.getCaption=function(){} //StructCaption is the name of the individual structure Structure.prototype.pointsString=function(){} //returns Points as a string //the get functions may be removed or modified since all variables are public
f601a02999f4008d5b82d3a506ebb01c4be773e0
[ "JavaScript", "C" ]
9
JavaScript
Callaghan/thecollectors
e140b6af45d14a600c01e66c1f66ba55d21f9194
0e4194aab75cb24ba98876b9b6a7f27b78c858ef
refs/heads/master
<file_sep>import {initializePhraseAppEditor} from '../src/functions'; beforeEach(() => { const scripts = document.getElementsByTagName('script'); for(let i =0; i< scripts.length; i++) { scripts[i].remove(); } }) test('with old ICE: translation should be rendered by default', () => { let config = {phraseEnabled: true, useOldICE: true, forceInitialize: true}; initializePhraseAppEditor(config); expect(document.getElementsByTagName('script')[0].src) .toMatch(/https:\/\/app.phrase.com\/assets\/in-context-editor\/2.0\/app.js\?[\d]/); }); test('translation should be rendered by default', () => { let config = {phraseEnabled: true, useOldICE: false, forceInitialize: true}; initializePhraseAppEditor(config); expect(document.getElementsByTagName('script')[0].src) .toMatch('https://d2bgdldl6xit7z.cloudfront.net/latest/ice/index.js'); }); <file_sep>export { initializePhraseAppEditor } from './functions'; export { injectIntl } from './injectIntl'; export { FormattedMessage } from './FormattedMessage'; export { useIntl } from './useIntl'; export { WrappedComponentProps } from './WrappedComponentProps'; <file_sep># react-intl-phraseapp ![Build status](https://github.com/phrase/react-intl-phraseapp/workflows/Test/badge.svg) **react-intl-phraseapp** is the official library for integrating [Phrase Strings In-Context Editor](https://support.phrase.com/hc/en-us/articles/5784095916188-In-Context-Editor-Strings) with [react-intl](https://github.com/yahoo/react-intl) in your React application. ## :scroll: Documentation ### Prerequisites To use react-intl-phraseapp with your application you have to: * Sign up for a Phrase account: [https://app.phrase.com/signup](https://app.phrase.com/signup) * Use the excellent [react-intl](https://github.com/yahoo/react-intl) module by yahoo for localization in your react app ### Demo You can find a demo project in the `examples/demo` folder, just run `yarn && yarn start` ### Installation #### via NPM ```bash npm install react-intl-phraseapp ``` #### via Yarn ```bash yarn add react-intl-phraseapp ``` #### Build from source You can also build it directly from source to get the latest and greatest: ```bash yarn dist ``` ### Development ```bash # install deps yarn install ``` #### Configure Add the following JavaScript snippet to your react app. ```js import {initializePhraseAppEditor} from 'react-intl-phraseapp' let config = { projectId: '<YOUR_PROJECT_ID>', accountId: '<YOUR_ACCOUNT_ID>', phraseEnabled: true, prefix: "[[__", suffix: "__]]", fullReparse: true }; initializePhraseAppEditor(config); ``` You can find the Project-ID in the Project overview in the PhraseApp Translation Center. You can find the Account-ID in the Organization page in the PhraseApp Translation Center. If this does not work for you, you can also integrate the [JavaScript snippet manually](https://help.phrase.com/help/integrate-in-context-editor-into-any-web-framework). To use the old version of ICE, use option `useOldICE: true` in your PHRASEAPP_CONFIG or integration options ```js let config = { projectId: '<YOUR_PROJECT_ID>', phraseEnabled: true, useOldICE: true, }; initializePhraseAppEditor(config); ``` #### Using the US Datacenter with ICE In addition to the settings in your config, set the US datacenter to enable it working with the US endpoints. ```js datacenter: 'us', ``` #### Import from react-intl-phraseapp rather than from react-intl Find all available imports for `react-intl` by changing the source from `react-intl` to `react-intl-phraseapp`, such as `FormattedMessage`, `useIntl`, `WrappedComponentProps`, and `injectIntl`. `import { FormattedMessage } from 'react-intl-phraseapp'` `import { useIntl, WrappedComponentProps } from 'react-intl-phraseapp'` `import { injectIntl, WrappedComponentProps } from 'react-intl-phraseapp'` ### Browser support This library might not work out of the box for some older browser or IE11. We recommend to add [Babel](https://github.com/babel/babel) to the build pipeline if those browser need to be supported. ### How does it work The library inherits common components of the react-intl packages. In case you enabled Phrase by calling `initializePhraseAppEditor` the behaviour of the components will be changed. ### Test Run unit tests using jest: ```bash npm test ``` ## :white_check_mark: Commits & Pull Requests We welcome anyone who wants to contribute to our codebase, so if you notice something, feel free to open a Pull Request! However, we ask that you please use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification for your commit messages and titles when opening a Pull Request. Example: `chore: Update README` ## :question: Issues, Questions, Support Please use [GitHub issues](https://github.com/phrase/react-intl-phraseapp/issues) to share your problem, and we will do our best to answer any questions or to support you in finding a solution. ## :memo: Changelog Detailed changes for each release are documented in the [changelog](https://github.com/phrase/react-intl-phraseapp/releases). <file_sep>import { WrappedComponentProps as ReactIntlWrappedComponentProps } from 'react-intl'; export type WrappedComponentProps = ReactIntlWrappedComponentProps; <file_sep># react-intl-phraseapp Demo This demo project shows how to integrate the [PhraseApp In-Context Editor](https://phraseapp.com/) into a React app using [react-intl](https://github.com/yahoo/react-intl) for localization via the [react-intl-phraseapp](https://github.com/phrase/react-intl-phraseapp) plugin. ## Install yarn install ## Configure In order to run the demo you need to provide your phrase project ID and account ID. To do so: - register at [phrase.com](https://phrase.com), - create & setup new project (or use existing if you got one), - go to "Project Settings", - from the left hand side menu, select "API" tab, - copy the project ID, - you can find the account ID in your organizations page - inside `index.tsx` file find & replace `projectId` and `accountId` with your own IDs ## Run Start the server: yarn && yarn start and then open the app at: [http://localhost:3000](http://localhost:3000/) ## Get help / support Please contact [<EMAIL>](mailto:<EMAIL>?subject=[GitHub]%20) and we can take more direct action toward finding a solution. <file_sep>module.exports = { resolve: { extensions: ['.js', '.ts', '.tsx'] }, module: { rules: [ { test: /\.tsx?$/, use: [ "ts-loader" ] }, { test: /examples\/demo.*/, include() { return false } }, ] }, externals: { "react-intl": { root: 'ReactIntl', commonjs2: 'react-intl', commonjs: 'react-intl', amd: 'react-intl' }, "react": { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, entry: [ './src/index.ts' ], output: { path: __dirname + '/dist', filename: 'index.js', libraryTarget: "umd", library: 'react-intl-phraseapp' } }; <file_sep># Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [3.0.2](https://github.com/phrase/react-intl-phraseapp/compare/v3.0.1...v3.0.2) (2022-06-21) ### Feat * support react-intl >= 5.0.0. ([#69](https://github.com/phrase/react-intl-phraseapp/pull/69)) ## [3.0.1](https://github.com/phrase/react-intl-phraseapp/compare/v3.0.0...v3.0.1) (2021-06-08) ### Fixes * properly map `react` and `react-intl` dependencies in UMD build. ([#60](https://github.com/phrase/react-intl-phraseapp/pull/60)) ## [3.0.0](https://github.com/phrase/react-intl-phraseapp/compare/v2.0.1...v3.0.0) (2020-06-24) ### ⚠ BREAKING CHANGES * add support for `react-intl@>=4.0.0`! Please follow [upgrade guide](https://formatjs.io/docs/react-intl/upgrade-guide-4x) to make your app compatible (especially the ["Breaking API Changes" section](https://formatjs.io/docs/react-intl/upgrade-guide-4x#breaking-api-changes)) ([#49](https://github.com/phrase/react-intl-phraseapp/pull/49)) * remove deprecated `FormattedHTMLMessage` component. Please refer to `react-intl` upgrade guide mentioned above for more informations about this change. ([#49](https://github.com/phrase/react-intl-phraseapp/pull/49)) ## [2.1.0](https://github.com/phrase/react-intl-phraseapp/compare/v1.0.0...v2.1.0) (2020-02-20) ### Features * add back binding for functions within injectIntl ([c50d009](https://github.com/phrase/react-intl-phraseapp/commit/c50d0093441472ad9d037198f22ac4ac589c382d)) ## [2.0.0](https://github.com/phrase/react-intl-phraseapp/compare/v1.0.0...v2.0.0) (2020-02-13) ### ⚠ BREAKING CHANGES * remove unnecessary `state` property and `error` prop ([#39](https://github.com/phrase/react-intl-phraseapp/pull/39)) ([2c03b1b](https://github.com/phrase/react-intl-phraseapp/commit/2c03b1b041e398775e52d57378546557e38a4f81)) * add support for `react-intl@>=3.0.0`! Please follow [upgrade guide](https://formatjs.io/docs/react-intl/upgrade-guide-3x) to make your app compatible (especially the ["Breaking API Changes" section](https://formatjs.io/docs/react-intl/upgrade-guide-3x#breaking-api-changes)) ([#36](https://github.com/phrase/react-intl-phraseapp/pull/36)) ([3fb9c26](https://github.com/phrase/react-intl-phraseapp/commit/3fb9c2612ba164824144bcc08cb4809aae1039a1)) <file_sep>let phraseAppEditor = false; function sanitizeConfig(config: any) : any { config.prefix = config.prefix ? config.prefix : '{{__'; config.suffix = config.suffix ? config.suffix : '__}}'; return config; } export function initializePhraseAppEditor (config: any) { if (phraseAppEditor && !config.forceInitialize) return; phraseAppEditor = true; (<any>window).PHRASEAPP_ENABLED = config.phraseEnabled; (<any>window).PHRASEAPP_CONFIG = sanitizeConfig(config); if (config.phraseEnabled) { const phraseapp = document.createElement('script'); if (config.useOldICE) { phraseapp.type = 'text/javascript'; phraseapp.src = ['https://', 'app.phrase.com/assets/in-context-editor/2.0/app.js?', new Date().getTime()].join(''); } else { phraseapp.type = 'module'; phraseapp.src = 'https://d2bgdldl6xit7z.cloudfront.net/latest/ice/index.js' } phraseapp.async = true; var s = document.getElementsByTagName('script')[0]; if (s !== undefined) { s.parentNode.insertBefore(phraseapp, s); } else { document.body.appendChild(phraseapp); } } } export function isPhraseEnabled() : boolean { return (<any>window).PHRASEAPP_ENABLED } export function escapeId (id : string | number) : string { let config = (<any>window).PHRASEAPP_CONFIG; return config.prefix + 'phrase_' + id + config.suffix; }
534ba04d18fc9ca054032ee90cf49569ef22bdb1
[ "Markdown", "TypeScript", "JavaScript" ]
8
TypeScript
phrase/react-intl-phraseapp
34af11414209bcd1eb005c742ebdd8a188a221b2
fe7b017e61655f578de3a1938fa512621a4d9215
refs/heads/master
<repo_name>ebtenorio/Password-Encryptor-Decryptor<file_sep>/EncryptDecryptApp/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using PTI.Security; using System.Diagnostics; namespace EncryptDecryptApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void encryptButton_Click(object sender, EventArgs e) { if (this.hsnRadioButton.Checked) { this.targetStringTextBox.Text = this.HSNEncrypt(this.sourceStringTextBox.Text); } else if (this.edi2WebRadioButton.Checked) { this.targetStringTextBox.Text = this.EDI2WebEncrypt(this.sourceStringTextBox.Text); } else { MessageBox.Show("Please select method."); } } private void decryptButton_Click(object sender, EventArgs e) { if (this.hsnRadioButton.Checked) { this.targetStringTextBox.Text = this.HSNDecrypt(this.sourceStringTextBox.Text); } else if (this.edi2WebRadioButton.Checked) { this.targetStringTextBox.Text = this.EDI2WebDecrypt(this.sourceStringTextBox.Text); } else { MessageBox.Show("Please select method."); } } private void clearButton_Click(object sender, EventArgs e) { this.sourceStringTextBox.Clear(); this.targetStringTextBox.Clear(); this.edi2WebRadioButton.Checked = false; this.hsnRadioButton.Checked = false; } private string EDI2WebEncrypt(string sourceString) { SecuritySVC _securityService = new SecuritySVC(); return _securityService.StringEncrypt(sourceString); } private string EDI2WebDecrypt(string sourceString) { SecuritySVC _securityService = new SecuritySVC(); return _securityService.StringDecrypt(sourceString); } private string HSNEncrypt(string sourceString) { PTI.Crypt _securityService = new PTI.Crypt(); return _securityService.Encrypt(sourceString); } private string HSNDecrypt(string sourceString) { PTI.Crypt _securityService = new PTI.Crypt(); return _securityService.Decrypt(sourceString); } private void button1_Click(object sender, EventArgs e) { this.WriteToEventLog(this.newEventLogTextField.Text.Trim(), "Application", EventLogEntryType.Information, "THIS IS AN APPEVENT MESSAGE" + DateTime.Now); } private void WriteToEventLog(string AppEventSource, string AppEventLog, EventLogEntryType AppEventType, string AppEventMessage) { try { if (!(EventLog.SourceExists(AppEventSource))) { EventLog.CreateEventSource(AppEventSource, AppEventLog); } EventLog.WriteEntry(AppEventSource, AppEventMessage, AppEventType); MessageBox.Show("Done"); this.newEventLogTextField.Text = ""; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
7a5642789a1ac186a9580a42f3b0af4066baef6b
[ "C#" ]
1
C#
ebtenorio/Password-Encryptor-Decryptor
a963aa5391849dbe2d1bcce38fed24191f2ed894
05a546c807b803a766bcdffc1efd4ecd923cb91c
refs/heads/master
<file_sep>package test.java; import java.time.Duration; import org.junit.*; import static org.junit.Assert.assertEquals; import main.java.Song; public class SongTest { @Test public void getPrettyDurationTest() { Song mySong = new Song("Title","Artist",Duration.ofSeconds(205)); String prettyResult = mySong.getDurationPretty(); String expectedResult = String.format("%d:%02d:%02d", 0,3,25); assertEquals("getDurationPretty should convert a song's duration in seconds into the format mm:ss",prettyResult,expectedResult); } } <file_sep>package test.java; import static org.junit.Assert.assertEquals; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.*; import main.java.Playlist; import main.java.Song; public class PlaylistTest { Playlist myPlaylist; List<Song> songs = new ArrayList<Song>(Arrays.asList( new Song("<NAME>","<NAME>",Duration.ofSeconds(210)), new Song("I Would Do Anything for Love","Meatloaf",Duration.ofSeconds(756)), new Song("Closer","The Chainsmokers",Duration.ofSeconds(244)))); public void addSongs() { myPlaylist.addSong(songs.get(0)); myPlaylist.addSong(songs.get(1)); myPlaylist.addSong(songs.get(2)); } @Before public void testSetup() { myPlaylist = new Playlist(); } @Test public void newPlaylistEmptyTest() { int expectedSize = 0; int actualSize = myPlaylist.getSonglist().size(); assertEquals("A new songlist should be empty",expectedSize,actualSize); } @Test public void addSongToPlaylistTest() { myPlaylist.addSong(songs.get(0)); int expectedSize = 1; int actualSize = myPlaylist.getSonglist().size(); assertEquals("Adding a song to the playlist should increase its size by 1",expectedSize,actualSize); } @Test public void removeSongFromPlaylistTest() { addSongs(); myPlaylist.removeSong(songs.get(1)); assertEquals("Removing a song from a playlist should shorten the songlist by 1",2,myPlaylist.getSonglist().size()); assertEquals("Removing a song from a playlist should remove only that song","<NAME>",myPlaylist.getSonglist().get(0).getTitle()); assertEquals("Removing a song from a playlist should remove only that song","Closer",myPlaylist.getSonglist().get(1).getTitle()); } @Test public void moveSongTest() { addSongs(); myPlaylist.moveSong(2,0); String song0Title = myPlaylist.getSonglist().get(0).getTitle(); String song1Title = myPlaylist.getSonglist().get(1).getTitle(); String song2Title = myPlaylist.getSonglist().get(2).getTitle(); assertEquals("First song is correct","Closer",song0Title); assertEquals("Second song is correct","<NAME>",song1Title); assertEquals("Third song is correct","I Would Do Anything for Love",song2Title); } @Test public void getPlaylistDurationTest() { addSongs(); long expectedDurationSeconds = 1210; long actualDurationSeconds = myPlaylist.getPlaylistDuration().getSeconds(); assertEquals("Total Duration of playist is equal to sum of song durations",expectedDurationSeconds,actualDurationSeconds); } @Test public void showPlaylistTest() { addSongs(); String expectedPlaylist = songs.get(0).getTitle()+" - "+ songs.get(0).getArtist()+" "+songs.get(0).getDurationPretty()+"\n"+ songs.get(1).getTitle()+" - "+ songs.get(1).getArtist()+" "+songs.get(1).getDurationPretty()+"\n"+ songs.get(2).getTitle()+" - "+ songs.get(2).getArtist()+" "+songs.get(2).getDurationPretty()+"\n"; System.out.println(myPlaylist.getPrettyPlaylist()); assertEquals("The showPlaylist method should produce a pretty list",expectedPlaylist,myPlaylist.getPrettyPlaylist()); } }
7e061bc70e32b4c3b34c12bf15d3116057ad0a4d
[ "Java" ]
2
Java
playbball212/TDD-Java-Music-Playlist-Completed
3124d4cd87356dd10525f344c5d890c03e89d02b
f8c6821d5a42743ad0b67ac2b71896503e6fb686
refs/heads/master
<file_sep><?php class Basetut_Createorder_IndexController extends Mage_Core_Controller_Front_Action { protected function _getOrderCreateModel() { return Mage::getSingleton('adminhtml/sales_order_create'); } /** * index action */ public function indexAction() { /** @var Mage_Adminhtml_Model_Sales_Order_Create $create */ //$create = $this->_getOrderCreateModel(); //kkk /** * @var Mage_Sales_Model_Quote */ if (isset($_POST["customer_id"])) { $customerId = $_POST["customer_id"]; $quote = Mage::getModel('sales/quote'); $customerData = Mage::getModel('customer/customer')->load($customerId); $quote->assignCustomer($customerData); if (isset($_POST["storedId"])) { $storeId = $_POST["storedId"]; $quote->setStoreId($storeId); if (isset($_POST["arrIdProduct"]) && isset($_POST["quantity"])) { $arrproductId = $_POST["arrIdProduct"]; $quantity = $_POST["quantity"]; foreach ($arrproductId as $arrproduct) { $product = Mage::getModel('catalog/product')->load($arrproduct); $buyInfo = ['qty' => $quantity]; $quote->addProduct($product, new Varien_Object($buyInfo)); } $quote->getBillingAddress() ->addData($customerData->getDefaultBillingAddress()->getData()); if (isset($_POST["paymentMethod"])) { $paymentMethod = $_POST["paymentMethod"]; $quote->getPayment()->setMethod($paymentMethod); $quote->getPayment()->importData(['method' => $paymentMethod]); } $result = null; if (isset($_POST["shippingMethod"])) { if ($_POST['shippingMethod'] == 1) { $quote->getShippingAddress() ->setRecollect(true) ->addData($customerData->getDefaultShippingAddress()->getData()) ->setCollectShippingRates(true) ->collectShippingRates(); $rates = []; foreach ($quote->getShippingAddress()->getAllShippingRates() as $allShippingRate) { $rates[] = $allShippingRate->getData(); } $result = $rates; } else { $shippingMethod = $_POST["shippingMethod"]; $quote->getShippingAddress() ->setShippingMethod($shippingMethod) ->setRecollect(true) ->addData($customerData->getDefaultShippingAddress()->getData()) ->setCollectShippingRates(true) ->collectShippingRates(); } } if (isset($_POST['creatorder'])) { $quote->collectTotals(); $quote->save(); $service = Mage::getModel('sales/service_quote', $quote); $order = $service->submit(); } } } return $this->getResponse() ->setHeader('Content-type', 'application/json')//sends the http json header to the browser ->setHeader('Access-Control-Allow-Origin', '*')// Allow other page to get data ->setBody(json_encode($result)); } } }<file_sep><?php class Basetut_Helloworld_IndexController extends Mage_Core_Controller_Front_Action { /** * index action */ public function customerAction() { $data = Mage::getModel('helloworld/dataManager')->getCustomerData(); //getModel gọi đến class helloworld-model-dataManager-> hàm getCustomer. return $this->getResponse() ->setHeader('Content-type', 'application/json') ->setBody(json_encode($data));//chuyển data về chuỗi json. } public function productAction() { // die('dsfsd'); $data = Mage::getModel('helloworld/dataManager')->getProductData(); return $this->getResponse() ->setHeader('Content-type', 'application/json') ->setBody(json_encode($data)); } public function paymentAction() { $data =Mage::getModel('helloworld/dataManager') ->getActivePaymentMethods(); return $this->getResponse() ->setBody(json_encode($data)) ->setHeader('Content-type', 'application/json'); } public function shippingAction() { $data =Mage::getModel('helloworld/dataManager') ->getShippingOptionArray(); return $this->getResponse() ->setBody(json_encode($data)) ->setHeader('Content-type', 'application/json'); } }<file_sep><?php class Basetut_Createorder_Block_Createorder extends Mage_Core_Block_Template { protected function _getOrderCreateModel() { return Mage::getSingleton('adminhtml/sales_order_create'); } public function methodOrder() { } }<file_sep><?php class Basetut_Helloworld_Model_DataManager extends Mage_Catalog_Model_Abstract{ public function getCustomerData(){ $customer = Mage::getModel('customer/customer')->getCollection()//getmoodel -> den class customer //get getcollection. ham getcolloction de tao cau query ->addAttributeToSelect('*') ->setOrder('entity_id', 'ASC') ->setPageSize(100) //get default bill setting ->joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left') ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left') ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left') ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left') ->joinAttribute('billing_fax', 'customer_address/fax', 'default_billing', null, 'left') ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left') ->joinAttribute('billing_country_code', 'customer_address/country_id', 'default_billing', null, 'left') //get default ship setting ->joinAttribute('shipping_street', 'customer_address/street', 'default_shipping', null, 'left') ->joinAttribute('shipping_postcode', 'customer_address/postcode', 'default_shipping', null, 'left') ->joinAttribute('shipping_city', 'customer_address/city', 'default_shipping', null, 'left') ->joinAttribute('shipping_telephone', 'customer_address/telephone', 'default_shipping', null, 'left') ->joinAttribute('shipping_fax', 'customer_address/fax', 'default_shipping', null, 'left') ->joinAttribute('shipping_region', 'customer_address/region', 'default_shipping', null, 'left') ->joinAttribute('shipping_country_code', 'customer_address/country_id', 'default_shipping', null, 'left') ->joinAttribute('taxvat', 'customer/taxvat', 'entity_id', null, 'left'); foreach ($customer as $custome) { // var_dump($custome->getData());die; $arr_customer[] = $custome->toArray(array('entity_id', 'firstname' ,'lastname', 'email', 'group_id', 'shipping_street','billing_city')); } return $arr_customer; } public function getProductData(){ // die('tuananaana'); $product = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('*') ->setOrder('entity_id', 'DESC') ->setPageSize(100); foreach ($product as $pro) { // var_dump($pro->getData()); $arr_products[] = $pro->toArray(array('entity_id','type_id','name', 'sku', 'price')); } // die; return $arr_products; } public function getActivePaymentMethods() { $payments = Mage::getSingleton('payment/config')->getActiveMethods(); // chưa hiểu getsingleton là gì? $methods = array(array('value'=>'', 'label'=>Mage::helper('adminhtml')->__('--Please Select--'))); foreach ($payments as $paymentCode=>$paymentModel) { $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title'); $methods[] = array( 'label' => $paymentTitle, 'value' => $paymentCode, ); } return $methods; } public function getShippingOptionArray($isMultiSelect = false) { $methods = Mage::getSingleton('shipping/config')->getActiveCarriers(); // chưa hiểu getsingleton là gì. $options = array(); foreach($methods as $_code => $_method) { if(!$_title = Mage::getStoreConfig("carriers/$_code/title")) $_title = $_code; $options[] = array('value' => $_code, 'label' => $_title . " ($_code)"); } if($isMultiSelect) { array_unshift($options, array('value'=>'', 'label'=> Mage::helper('adminhtml')->__('--Please Select--'))); } return $options; } }<file_sep><?php class Basetut_Createorder_Model_CreateOrder extends Mage_Catalog_Model_Abstract{ }
a0d0ccf5d060fd2b28a2309c5b8224f53ab096be
[ "PHP" ]
5
PHP
tuandvsmartosc/magento1
15255b767d00c6cd0d4e6c68ae777fa5acc3a496
0d1624460a262f433eb0d84bb72555f9ff587d01
refs/heads/master
<repo_name>OmarMAmin/Snake-Game-Tutorial<file_sep>/Snake/Snake/Main.cpp #include <iostream> #include <conio.h> #include <math.h> #include <thread> #include <future> #include <stdlib.h> #include <chrono> #include <thread> using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; using namespace std; #define dim 20 enum Direction { left = 0, right = 1,up = 2,down = 3 }; #define LEFT Direction::left #define RIGHT Direction::right #define UP Direction::up #define DOWN Direction::down struct Node { int x; int y; Direction dir; }; struct Snake { Node nodes[400]; int size; }; struct Food { int x; int y; int timelefttodisappear; }; struct World { Snake snake; Food food[5]; int foodcount; int score; bool gameover; char world[dim][dim]; }; void InitializeSnake(Snake & snk); void SnakeDraw(); void InitializeWorldOfSnake(World & wofsnk); void AddSnakeToTheWorld(World & wofsnk); bool GeneratedOnSnake(Snake sn, int x, int y); void InitializeWorld(char world[dim][dim]); void DrawWorld(World w); void MoveSnakeToTheRight(Snake & snake); bool MoveSnake(Snake & snake,Direction direction); void MoveNode(Node & node, Direction dir); bool AreThereAnyCollisions(Snake snake); void AddFoodToTheWorld(World & w); Direction GetDirection(char choice) { if (choice == 'a') return LEFT; else if(choice == 's') return DOWN; else if (choice == 'd') return RIGHT; else if (choice == 'w') return UP; } void MoveNodeNormally(Node & node); void InitializeFood(World &w); bool SnakeEatFood(World &w); void delay() { for(int i =0;i<10000;i++) { for(int j =0;j<20000;j++) ; } } void GetDirectionThread(char * c) { *c = _getch(); char choice = *c; while (choice != 'a' && choice != 's' && choice != 'w' && choice != 'd') { cout << endl << "Not Valid Direction, Please Enter a,s,d,w only" << endl; } } int main() { World w; char choice ='d'; InitializeSnake(w.snake); InitializeFood(w); bool gameover = false; while (!gameover) { system("cls"); InitializeWorldOfSnake(w); DrawWorld(w); cout << endl << endl << "Enter a,s,d,w to move left,down,right,up respectively"<<endl; char j = choice; thread x(GetDirectionThread, &choice); sleep_for(400ms); x.detach(); gameover = MoveSnake(w.snake,GetDirection(choice)); if (SnakeEatFood(w)) w.snake.size++; } system("pause"); return 0; } bool SnakeEatFood(World &w) { int headx = w.snake.nodes[0].x; int heady = w.snake.nodes[0].y; for (int i = 0; i < w.foodcount; i++) { if (headx == w.food[i].x && heady == w.food[i].y) { w.food[i].timelefttodisappear = 1; w.score += 100; return true; } } return false; } void InitializeFood(World & w) { w.foodcount = 0; w.score = 0; } void MoveNode(Node & node, Direction dir) { node.dir = dir; MoveNodeNormally(node); } void MoveNodeNormally(Node & node) { Direction dir = node.dir; if (dir == UP) node.x--; else if (dir == DOWN) node.x++; else if (dir == RIGHT) node.y++; else if (dir == LEFT) node.y--; // adjust node coordinates if it's on the wall if (node.x == 0) node.x = dim - 2; else if (node.x == dim - 1) node.x = 1; if (node.y == 0) node.y = dim - 2; else if (node.y == dim - 1) node.y = 1; } bool IsMovingInItsDirection(Direction input, Direction state) { if (input == state || input == UP && state == DOWN || input == DOWN && state == UP || input == RIGHT && state == LEFT || input == LEFT && state == RIGHT) return true; else return false; } bool MoveSnake(Snake & snake, Direction direction) { Direction HeadDirection = snake.nodes[0].dir; bool ShouldMoveNormally = IsMovingInItsDirection(direction, HeadDirection); int snakesize = snake.size; for (int i = snakesize;i > 0 ;i--) { // snake was : ***> // snake will be : ***> // moving each node from the tail to the node next to it in the snake snake.nodes[i].x = snake.nodes[i - 1].x; snake.nodes[i].y = snake.nodes[i - 1].y; snake.nodes[i].dir = snake.nodes[i - 1].dir; } if (ShouldMoveNormally) { // the head node will continue to move in its original direction MoveNodeNormally(snake.nodes[0]); } else { MoveNode(snake.nodes[0],direction); } return AreThereAnyCollisions(snake); } bool AreThereAnyCollisions(Snake snake) { // collision happens only when the head hits anyother node int snakeheadX = snake.nodes[0].x; int snakeheady = snake.nodes[0].y; for (size_t i = 1; i < snake.size; i++) { if (snake.nodes[i].x == snakeheadX && snake.nodes[i].y == snakeheady) return true; } // if no node collided with the snake head // then there're no collisions return false; } void MoveSnakeToTheRight(Snake & snake) { for (size_t i = 0; i < snake.size; i++) { snake.nodes[i].y++; // if snake moved to the right wall if (snake.nodes[i].y == dim - 1) // make it the first snake.nodes[i].y = 1; } } void AdjustFoodTime(World &w) { // just simpler name int count = w.foodcount; for (int i = 0; i < count; i++) { w.food[i].timelefttodisappear--; if (w.food[i].timelefttodisappear == 0) { // remove it for (int j = i;j < count;j++) { // move the rest backword one step starting from i to the end; w.food[j].x = w.food[j + 1].x; w.food[j].y = w.food[j + 1].y; w.food[j].timelefttodisappear = w.food[j + 1].timelefttodisappear; } // you've deleted one item, so update the counters count--; // go back one food item as afte the iteration i++ will be executed and you don't want // to skip any items i--; } } w.foodcount = count; } void InitializeWorldOfSnake(World & wofsnk) { InitializeWorld(wofsnk.world); AdjustFoodTime(wofsnk); AddSnakeToTheWorld(wofsnk); AddFoodToTheWorld(wofsnk); } void AddSnakeToTheWorld(World & wofsnk) { int size = wofsnk.snake.size; for (int i = 0; i < size; i++) { int x = wofsnk.snake.nodes[i].x; int y = wofsnk.snake.nodes[i].y; wofsnk.world[x][y] = '*'; } } void DrawWorld(World w) { for (size_t i = 0; i < dim; i++) { for (size_t j = 0; j < dim; j++) { cout << w.world[i][j]; } cout << endl; } cout << endl; cout << "\t\t\t Score : " << w.score; } void InitializeWorld(char world[dim][dim]) { for (int i = 0;i < dim;i++) { for (int j = 0; j < dim; j++) { // when to draw boundary if (i == 0 || i == dim - 1 || j == 0 || j == dim - 1) world[i][j] = '#'; // when to draw space else world[i][j] = ' '; } } } void InitializeSnake(Snake & snk) { snk.size = 3; int initial_y = 10; for (size_t i = 0; i < snk.size; i++) { snk.nodes[i].x = 9; snk.nodes[i].y = initial_y--; snk.nodes[i].dir = RIGHT; } } void SnakeDraw() { for (int i = 0;i < dim;i++) { for (int j = 0; j < dim; j++) { // when to draw boundary if (i == 0 || i == dim - 1 || j == 0 || j == dim - 1) cout << "#"; // when to draw snake else if (i == 9 && j == 8 || i == 9 && j == 9 || i == 9 && j == 10) cout << "*"; // when to draw empty else cout << " "; } cout << endl; } } bool GeneratedOnSnake(Snake sn, int x, int y) { for (size_t i = 0; i < sn.size; i++) { if (sn.nodes[i].x == x && sn.nodes[i].y == y) { return true; } } return false; } void AddFoodToTheWorld(World &w) { // Do we need to generate food ? int foodcount = w.foodcount; if (foodcount == 4) return; bool Generate = ((4 - foodcount) * (rand() % 10)) > 26; if(Generate) { // rand() % (dim - 2) + 1 ==== random number between 1 and dim-1 (inside the world) int x = rand() % (dim - 2) + 1; int y = rand() % (dim - 2) + 1; // check if the generated food isn't part of the snake while (GeneratedOnSnake(w.snake, x, y)) { x = rand() % (dim - 2) + 1; y = rand() % (dim - 2) + 1; } int headx = w.snake.nodes[0].x; // getting head x position int heady = w.snake.nodes[0].y; // getting head y position int distance = abs(headx-x) + abs(heady-y); int timetodisappear = distance + 1 + rand() % 5; // rand()%5 to give space for any mistake on the way // accumelate on other food objects w.food[foodcount].x = x; w.food[foodcount].y = y; w.food[foodcount].timelefttodisappear = timetodisappear; w.foodcount++; } for (size_t i = 0; i < w.foodcount; i++) { int x = w.food[i].x; int y = w.food[i].y; w.world[x][y] = '$'; } }
1332b906ff5470ffd8212bbee4bd9a6b9832eb0b
[ "C++" ]
1
C++
OmarMAmin/Snake-Game-Tutorial
36e42fba5fa0e936758a44c42f27bf69d5ba57fe
62497c13f5cb4d7b22a1397b647d172794328384
refs/heads/master
<repo_name>sagarpaliwal111/Messaging_App<file_sep>/settings.gradle rootProject.name = "Messaging App" include ':app' <file_sep>/app/src/main/java/com/example/messagingapp/CreatePostActivity.kt package com.example.messagingapp import android.content.Intent import android.os.Bundle import android.view.Window import android.view.WindowManager import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.example.messagingapp.Dao.PostDao class CreatePostActivity : AppCompatActivity() { private lateinit var postDao: PostDao override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_create_post) postDao = PostDao() findViewById<Button>(R.id.postButton).setOnClickListener { val input = findViewById<EditText>(R.id.inputText).text.toString().trim() if (input.isNotEmpty()) { postDao.addPost(input) val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } } } <file_sep>/app/src/main/java/com/example/messagingapp/MainActivity.kt package com.example.messagingapp import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.messagingapp.Adapter.IPostAdapter import com.example.messagingapp.Adapter.PostAdapter import com.example.messagingapp.Dao.PostDao import com.example.messagingapp.models.Post import com.firebase.ui.firestore.FirestoreRecyclerOptions import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.Query import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : AppCompatActivity(), IPostAdapter { private lateinit var postDao: PostDao private lateinit var adapter: PostAdapter lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) firebaseAuth = FirebaseAuth.getInstance() AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { val intent = Intent(this, CreatePostActivity::class.java) startActivity(intent) } setUpRecyclerView() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.option_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { super.onOptionsItemSelected(item) when (item.itemId) { R.id.logoutoption -> { GlobalScope.launch { FirebaseAuth.getInstance().signOut() } val intent = Intent(this, SignIn::class.java) startActivity(intent) finish() } } return true } private fun setUpRecyclerView() { postDao = PostDao() val postsCollections = postDao.postCollection val query = postsCollections.orderBy("createdAt", Query.Direction.DESCENDING) val recyclerViewOptions = FirestoreRecyclerOptions.Builder<Post>().setQuery(query, Post::class.java).build() adapter = PostAdapter(recyclerViewOptions, this) findViewById<RecyclerView>(R.id.recyclerView).adapter = adapter findViewById<RecyclerView>(R.id.recyclerView).layoutManager = LinearLayoutManager(this) } override fun onStart() { super.onStart() adapter.startListening() } override fun onStop() { super.onStop() adapter.stopListening() } override fun onLikesClicked(postId: String) { postDao.updateLikes(postId) } }
43f1e66f307697a1949da34be8e3305cc9d0d40d
[ "Kotlin", "Gradle" ]
3
Gradle
sagarpaliwal111/Messaging_App
0482e33f587a2869bb509af80b3dc994790b7635
2c8085246deaeba07eb674c4c4da133be26ed302
refs/heads/master
<repo_name>datalyticsllc/hci-solver<file_sep>/Solver/Models/Driver.cs using System; using System.Collections.Generic; namespace Solver { public class Driver { public long id { get; set; } public string name { get; set; } public Location location { get; set; } public int maxStops { get; set; } public int maxWorkTime { get; set; } public TimeWindow timeWindow { get; set; } public List<string> tags { get; set; } public List<string> services { get; set; } public List<Pref> prefs { get; set; } } } <file_sep>/Solver/EvoStrat.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Optimization; using HeuristicLab.Problems.TravelingSalesman; using HeuristicLab.Problems.VehicleRouting.Datalytics; using HeuristicLab.Algorithms.EvolutionStrategy; namespace Solver { public class EvoStrat { // Configuration private StrategyState _strategyState = StrategyState.Stopped; private double _elapsedTime = 0; // elapsed time tracking (may not need if host handles database calls) public class StatusUpdateEventArgs : EventArgs { public OptimizationRun Run { get; set; } public StrategyState State { get; set; } public DateTime UpdateTime { get; set; } public string Message { get; set; } } public enum StrategyState { Stopped, Running, Paused, Completed } // Problem private List<int> _stopIds = new List<int>(); // stores the visit IDs private List<int> _driverIds = new List<int>(); // stores the staff IDs private List<RouteOrder> _orders = new List<RouteOrder>(); private List<RouteDriver> _drivers = new List<RouteDriver>(); private DoubleMatrix _coordinates = new DoubleMatrix(); private IntArray _vehicleAssignment = new IntArray(); private List<RouteEntity> _routeEntities = new List<RouteEntity>(); private List<RouteLeg> _routeLegs = new List<RouteLeg>(); private List<RouteOrderMultiplier> _mutipliers = new List<RouteOrderMultiplier>(); // cost-optimization stuff private bool _costOptimization = false; private double _distanceCostRatio = 0.0; private double _avgLegLength = 0.0; private double _maxLegLength = 0.0; private double _avgLegPenalty = 0.0; private double _maxLegPenalty = 0.0; private double _capacity = 0.0; private double _demand = 0.0; // Run vars HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy algorithm; private OptimizationRun _run = new OptimizationRun(); // External Events public event EventHandler StatusUpdate; protected virtual void OnStatusUpdate(StatusUpdateEventArgs e) { EventHandler handler = StatusUpdate; if (handler != null) { handler(this, e); } } public EvoStrat(OptimizationRun run, ICollection<RouteDriver> drivers, ICollection<RouteOrder> orders, ICollection<RouteLeg> routeLegs, ICollection<RouteOrderMultiplier> routeMutipliers, bool costOptimization, double distanceCostRatio, double avgLegLength, double maxLegLength, double avgLegPenalty, double maxLegPenalty, double demand, double capacity) { _run = run; _drivers = drivers.ToList(); _orders = orders.ToList(); _routeLegs = routeLegs.ToList(); _mutipliers = routeMutipliers.ToList(); _costOptimization = costOptimization; _distanceCostRatio = distanceCostRatio; _avgLegLength = avgLegLength; _avgLegPenalty = avgLegPenalty; _maxLegLength = maxLegLength; _maxLegPenalty = maxLegPenalty; _demand = demand; _capacity = capacity; } public void StartOptimization() { UpdateRun("Starting Optimization", StrategyState.Running); // setup the Entity List _routeEntities.AddRange(RouteEntity.Convert(_drivers)); // add an entity for each visit, but we add the patient id, so our distance matrix will work. // we do this the handle multiple orders (visits) to the same stop (patient) foreach (var o in _orders) { // _routeEntities.Add(new Data.Models.RouteEntity { TypeID = 1, ID = o.StopID, GeoLat = o.GeoLat, GeoLon = o.GeoLon }); } _driverIds = (from s in _drivers select s.ID).ToList (); _stopIds = (from s in _orders select s.ID).ToList (); //TODO: We need to change where the algorithms are stored. Ideally, we'd have them // in a folder in the project directory string algorithmPath = @"C:\Algorithms\ES_MDVRPTW_v3.hl"; //ContentManager.Initialize(new PersistenceContentManager()); var content = ContentManager.Load(algorithmPath); LoadingCompleted(content); } public void StopJob() { algorithm.Stop(); } private void LoadingCompleted(IStorableContent content) { //if (error != null) throw error; UpdateRun("Algorithm loading complete", StrategyState.Running); if (content is HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy) { algorithm = content as HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy; VehicleRoutingProblem problem = algorithm.Problem as VehicleRoutingProblem; if (problem == null) { Console.WriteLine("Unsupported problem type detected."); return; } SetProblemInstance(problem); ParameterizeProblem(problem); ParameterizeAlgorithm(algorithm); RegisterAlgorithmEventHandlers(algorithm); try { algorithm.Start(); } catch (Exception exc) { Console.WriteLine("Error Loading: " + exc.Message); } } else { // TODO: update the run status to error... //_strategyState = StrategyState.Stopped; } } private void SetProblemInstance(VehicleRoutingProblem problem) { //var pi = problem.ProblemInstance.Clone() as HeuristicLab.Problems.VehicleRouting.ProblemInstances.MDCVRPTWProblemInstance; HeuristicLab.Problems.VehicleRouting.Datalytics.ProblemInstances.MDCVRPTWProblemInstance pi = new HeuristicLab.Problems.VehicleRouting.Datalytics.ProblemInstances.MDCVRPTWProblemInstance(); pi.Cities.Value = _orders.Count; pi.Depots.Value = _drivers.Count; pi.Vehicles.Value = _drivers.Count; // only allow 1 vehicle per depot pi.DistanceFactor.Value = 1.0; pi.FleetUsageFactor.Value = 0.0; pi.UseDistanceMatrix.Value = true; pi.Capacity = new DoubleArray(GetCapacity(_drivers.Count)); pi.Coordinates = new DoubleMatrix(GetCoordinates()); _coordinates = pi.Coordinates; //string patientList = string.Join(",", _stopIds); //string staffList = string.Join(",", _driverIds); UpdateRun("Calculating Distance Matrix", StrategyState.Running); //Routing.Routing routing = new Routing.Routing(); //_routeLegs = routing.GetRouteLegs(patientList, staffList, "Distance"); pi.DistanceMatrix = CreateDistanceMatrix(); pi.TimeMatrix = CreateTimeMatrix(); pi.QualityMatrix = CreateQualityMatrix(); // cost-based functionality pi.CostOptimization.Value = _costOptimization; pi.DistanceToCostRatio.Value = _distanceCostRatio; pi.PerStopCost = CreatePerVisitCostArray(); pi.PerMileCost = CreatePerMileCostArray(); pi.AvgLegLength.Value = _avgLegLength; pi.AvgLegPenality.Value = _avgLegPenalty; pi.MaxLegLength.Value = _maxLegLength; pi.MaxLegPenality.Value = _maxLegPenalty; UpdateRun("Distance Matrix Loaded", StrategyState.Running); pi.Demand = new DoubleArray(GetDemand(_orders.Count)); double dueTime = 1.7976931348623157E308; // Max double, we need this for some reason, 0 didn't work pi.DueTime = new DoubleArray(GetDueTime(_orders.Count + _drivers.Count, dueTime)); pi.ServiceTime = new DoubleArray(GetServiceTime(_orders.Count)); pi.ReadyTime = new DoubleArray(GetReadyTime(_orders.Count + _drivers.Count)); pi.VehicleDepotAssignment = new IntArray(SetVehicleDepotAssignment(_drivers.Count)); // set the vehicle assigment array _vehicleAssignment = pi.VehicleDepotAssignment; problem.SetProblemInstance(pi); UpdateRun("Problem Instance Set", StrategyState.Running); } private void ParameterizeAlgorithm(HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy algorithm) { //set all parameters of the algorithm, e.g. algorithm.MaximumGenerations = new IntValue(_run.GenerationsToRun); } private void ParameterizeProblem(VehicleRoutingProblem problem) { //set all parameters of the problem, e.g. //problem.MaximizationParameter = false; } private double[,] GetCoordinates() { // depot (staff) coords are loaded in the first n slots, the patients afterwards double[,] coords = new double[_drivers.Count + _orders.Count, 2]; // add the driver coords first int i = 0; foreach (RouteDriver d in _drivers) { //_driverIds.Add(d.ID); coords[i, 0] = Convert.ToDouble(d.GeoLat); coords[i, 1] = Convert.ToDouble(d.GeoLon); i++; } // now add the stop coords foreach (RouteOrder s in _orders) { // _stopIds.Add(s.ID); coords[i, 0] = Convert.ToDouble(s.GeoLat); coords[i, 1] = Convert.ToDouble(s.GeoLon); i++; } return coords; } private DoubleMatrix CreateDistanceMatrix() { DoubleMatrix distanceMatrix = new DoubleMatrix(_routeEntities.Count, _routeEntities.Count); for (int i = 0; i < distanceMatrix.Rows; i++) { for (int j = 0; j < distanceMatrix.Columns; j++) { var start = _routeEntities[i]; var end = _routeEntities[j]; RouteLeg leg = _routeLegs.Where(x => x.FromID == start.ID && x.FromTypeID == start.TypeID && x.ToID == end.ID && x.ToTypeID == end.TypeID).FirstOrDefault(); distanceMatrix[i, j] = Convert.ToDouble(leg.DrivingDistance); } } return distanceMatrix; } private DoubleMatrix CreateTimeMatrix() { DoubleMatrix timeMatrix = new DoubleMatrix(_routeEntities.Count, _routeEntities.Count); for (int i = 0; i < timeMatrix.Rows; i++) { for (int j = 0; j < timeMatrix.Columns; j++) { var start = _routeEntities[i]; var end = _routeEntities[j]; RouteLeg leg = _routeLegs.Where(x => x.FromID == start.ID && x.FromTypeID == start.TypeID && x.ToID == end.ID && x.ToTypeID == end.TypeID).FirstOrDefault(); timeMatrix[i, j] = Convert.ToDouble(leg.DrivingTime / 60); } } return timeMatrix; } private DoubleMatrix CreateQualityMatrix() { DoubleMatrix qualityMatrix = new DoubleMatrix(_driverIds.Count, _stopIds.Count); for (int i = 0; i < qualityMatrix.Rows; i++) { for (int j = 0; j < qualityMatrix.Columns; j++) { var start = _driverIds[i]; var end = _stopIds[j]; // replace with the new RouteLegMultiplier RouteOrderMultiplier mutiplier = _mutipliers.Where(x => x.RouteDriverID == start && x.RouteOrderID == end).FirstOrDefault(); qualityMatrix[i, j] = Convert.ToDouble(mutiplier.AdjustmentMultiplier); } } return qualityMatrix; } private DoubleArray CreatePerVisitCostArray() { DoubleArray perVisitCostArray = new DoubleArray(_driverIds.Count); for (int i = 0; i < perVisitCostArray.Length; i++) { perVisitCostArray[i] = Convert.ToDouble(_drivers[i].PerVisitCost); } return perVisitCostArray; } private DoubleArray CreatePerMileCostArray() { DoubleArray perMileCostArray = new DoubleArray(_driverIds.Count); for (int i = 0; i < perMileCostArray.Length; i++) { perMileCostArray[i] = Convert.ToDouble(_drivers[i].PerMileCost); } return perMileCostArray; } private int[] SetVehicleDepotAssignment(int staff) { int[] depots = new int[staff]; for (int i = 0; i < staff; i++) { depots[i] = i; } return depots; } private double[] GetCapacity(int staff) { double[] capacity = new double[staff]; for (int i = 0; i < staff; i++) { capacity[i] = _capacity; } return capacity; } private double[] GetDueTime(int count, double dueTimeVal) { double[] dueTime = new double[count]; for (int i = 0; i < count; i++) { if (i < _drivers.Count) { dueTime[i] = Convert.ToDouble(_drivers[i].Availability); } else { dueTime[i] = dueTimeVal; } } return dueTime; } private double[] GetServiceTime(int count) { double[] serviceTime = new double[count]; for (int i = 0; i < count; i++) { serviceTime[i] = Convert.ToDouble(_orders[i].ServiceTime); } return serviceTime; } private double[] GetReadyTime(int count) { double[] readyTime = new double[count]; for (int i = 0; i < count; i++) { readyTime[i] = 0; } return readyTime; } private double[] GetDemand(int patients) { double[] demand = new double[patients]; for (int i = 0; i < patients; i++) { demand[i] = _demand; } return demand; } private void RegisterAlgorithmEventHandlers(EngineAlgorithm alg) { //alg.ExecutionStateChanged += new EventHandler(ExecutionStateChanged); alg.ExecutionTimeChanged += new EventHandler(ExecutionTimeChanged); alg.Stopped += new EventHandler(Stopped); //alg.Started += new EventHandler(Started); alg.Paused += new EventHandler(Paused); } private void DeregisterAlgorithmEventHandlers(EngineAlgorithm alg) { //alg.ExecutionStateChanged -= new EventHandler(ExecutionStateChanged); alg.ExecutionTimeChanged -= new EventHandler(ExecutionTimeChanged); alg.Stopped -= new EventHandler(Stopped); //alg.Started += new EventHandler(Started); alg.Paused += new EventHandler(Paused); } private void ExecutionTimeChanged(object sender, EventArgs e) { // maybe we should check to see if the execution time has been longer than say 5 secs? EngineAlgorithm alg = sender as EngineAlgorithm; // only update on certain intervals, so we don't tax the db unnecessarily var results = alg.Results.Clone() as ResultCollection; try { foreach (var s in results) { if (s.Name == "BestQuality") { // debug //var test = _pi.QualityMatrix; // get algorithm output string bestQuality = results["BestQuality"].Value.ToString(); string generations = results["Generations"].Value.ToString(); string bestSolution = GetBestSolution(results); string currentResults = GetCurrentResults(results); _run.Generations = Convert.ToInt32(generations); _run.BestQuality = bestQuality; _run.BestSolution = bestSolution; _run.CurrentResults = currentResults; //Console.WriteLine("Thread1 -> Time: " + alg.ExecutionTime + ", Quality: " + alg.Results["BestQuality"].Value.ToString()); UpdateRun("Quality: " + alg.Results["BestQuality"].Value.ToString(), StrategyState.Running); } } } catch (Exception exc) { bool ignore = true; } } private void Paused(object sender, EventArgs e) { EngineAlgorithm alg = sender as EngineAlgorithm; Console.WriteLine("Execution paused"); alg.Stop(); } private void Stopped(object sender, EventArgs e) { EngineAlgorithm alg = sender as EngineAlgorithm; // only update on certain intervals, so we don't tax the db unnecessarily var results = alg.Results.Clone() as ResultCollection; foreach (var s in results) { if (s.Name == "BestQuality") { // get algorithm output string bestQuality = results["BestQuality"].Value.ToString(); string generations = results["Generations"].Value.ToString(); string bestSolution = GetBestSolution(results); string currentResults = GetCurrentResults(results); _run.Generations = Convert.ToInt32(generations); _run.BestQuality = bestQuality; _run.BestSolution = bestSolution; _run.CurrentResults = currentResults; //Console.WriteLine("Thread1 -> Time: " + alg.ExecutionTime + ", Quality: " + alg.Results["BestQuality"].Value.ToString()); UpdateRun("Optimization Completed", StrategyState.Stopped); } } DeregisterAlgorithmEventHandlers(alg); //UpdateRun("Optimization completed", StrategyState.Stopped); } private string GetBestSolution(ResultCollection results) { string result = string.Empty; try { if (results["Best VRP Solution"] == null) return null; // otherwise we have a valid solution, so update the database VRPSolution solution = results["Best VRP Solution"].Value as VRPSolution; var tours = solution.Solution.GetTours(); bool firstDriver = true; for (int i = 0; i < tours.Count; i++) { if (firstDriver) { firstDriver = false; } else { result += "|"; } int tourIndex = solution.Solution.GetTourIndex(tours[i]); int vehicle = solution.Solution.GetVehicleAssignment(tourIndex); int depot = _vehicleAssignment[vehicle]; result += _driverIds[depot].ToString() + ":"; var stops = string.Empty; bool first = true; foreach (var s in tours[i].Stops) { if (first) first = false; else { stops += ","; } stops += _stopIds[s - 1].ToString(); } result += stops; } } catch (Exception exc) { //alg.Stop(); _strategyState = StrategyState.Stopped; return null; } return result; } private string GetCurrentResults(ResultCollection results) { string currentResults = string.Empty; bool first = true; foreach (var s in results) { if (s.Name != "Overloads" && s.Name != "TardinessValues" && s.Name != "TravelTimes" && s.Name != "Distances" && s.Name != "VehiclesUtilizedValues" && s.Name != "Best VRP Solution") { if (first) { first = false; } else { currentResults += "|"; } currentResults += s.Name + ":" + s.Value; } } return currentResults; } private void UpdateRun(string message, StrategyState state) { try { _strategyState = state; // Trigger update event StatusUpdate(this, new StatusUpdateEventArgs() { Run = _run, Message = message, State = this._strategyState, UpdateTime = DateTime.Now }); } catch (Exception exc) { _strategyState = StrategyState.Stopped; var error = exc.ToString(); } } } } <file_sep>/Solver/bin/Release/deploy #!/bin/bash #FILES="/Users/ericodom/projects/Solver/Solver/bin/release" #for f in $FILES #do # echo "Processing $f" #done for file in $* do # do something on $file echo $file # gcutil --zone="us-central2-a" --project="smart-amplifier-286" push "test1" "$file" /etc/solver done <file_sep>/Solver/Models/OptimizationRun.cs using System; namespace Solver { public class OptimizationRun { // Job tracking public int ID { get; set; } public int CustomerID { get; set; } public string Algorithm { get; set; } public DateTime ServiceDate { get; set; } public string Drivers { get; set; } public string Orders { get; set; } public string Tags { get; set; } public int GenerationsToRun { get; set; } public int Generations { get; set; } public string BestQuality { get; set; } public string BestSolution { get; set; } public string CurrentResults { get; set; } public DateTime CreateDate { get; set; } public int RunLock { get; set; } public int KillRun { get; set; } // cost-based optimization stuff public bool CostOptimization { get; set; } public decimal DistanceCostRatio { get; set; } public int AvgLegLength { get; set; } public int MaxLegLength { get; set; } public decimal AvgLegPenalty { get; set; } public decimal MaxLegPenalty { get; set; } public int MaxCapacity { get; set; } public string Message { get; set; } public bool Demo { get; set; } } } <file_sep>/Solver/Optimization/EvoStrat.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Optimization; using HeuristicLab.Problems.TravelingSalesman; using HeuristicLab.Problems.VehicleRouting.Datalytics; using HeuristicLab.Algorithms.EvolutionStrategy; using System.IO; namespace Solver { public class EvoStrat { // Configuration private StrategyState _strategyState = StrategyState.Stopped; //private double _elapsedTime = 0; // elapsed time tracking (may not need if host handles database calls) public class StatusUpdateEventArgs : EventArgs { public OptimizationRun Run { get; set; } public StrategyState State { get; set; } public DateTime UpdateTime { get; set; } public string Message { get; set; } } public enum StrategyState { Stopped, Running, Paused, Completed } // Problem private List<long> _stopIds = new List<long>(); // stores the visit IDs private List<long> _driverIds = new List<long>(); // stores the staff IDs //private DoubleMatrix _coordinates = new DoubleMatrix(); private IntArray _vehicleAssignment = new IntArray(); private List<Driver> _drivers = new List<Driver> (); private List<Task> _tasks = new List<Task> (); private List<Entity> _routeEntities = new List<Entity>(); private List<RouteLeg> _routeLegs = new List<RouteLeg>(); private List<DriverTaskMultiplier> _mutipliers = new List<DriverTaskMultiplier>(); // cost-optimization stuff private bool _costOptimization = false; private double _distanceCostRatio = 0.0; private double _avgLegLength = 0.0; private double _maxLegLength = 0.0; private double _avgLegPenalty = 0.0; private double _maxLegPenalty = 0.0; private double _capacity = 0.0; private double _demand = 0.0; // Run vars HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy algorithm; private OptimizationRun _run = new OptimizationRun(); // External Events public event EventHandler StatusUpdate; protected virtual void OnStatusUpdate(StatusUpdateEventArgs e) { EventHandler handler = StatusUpdate; if (handler != null) { handler(this, e); } } public EvoStrat( OptimizationRun run, ICollection<long> driverIds, ICollection<long> taskIds, ICollection<Entity> entities, ICollection<Driver> drivers, ICollection<Task> tasks, ICollection<RouteLeg> routeLegs, ICollection<DriverTaskMultiplier> routeMutipliers, bool costOptimization, double distanceCostRatio, double avgLegLength, double maxLegLength, double avgLegPenalty, double maxLegPenalty, double demand){ _run = run; _driverIds = driverIds.ToList(); _stopIds = taskIds.ToList(); _routeEntities = entities.ToList(); _drivers = drivers.ToList(); _tasks = tasks.ToList(); _routeLegs = routeLegs.ToList(); _mutipliers = routeMutipliers.ToList(); _costOptimization = costOptimization; _distanceCostRatio = distanceCostRatio; _avgLegLength = avgLegLength; _avgLegPenalty = avgLegPenalty; _maxLegLength = maxLegLength; _maxLegPenalty = maxLegPenalty; _demand = demand; } public void StartOptimization() { UpdateRun("Starting Optimization", StrategyState.Running); string algorithmPath = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "Algorithms"), _run.Algorithm); Console.WriteLine("Loading algorithm: " + algorithmPath); //ContentManager.Initialize(new PersistenceContentManager()); var content = ContentManager.Load(algorithmPath); LoadingCompleted(content); } public void StopJob() { algorithm.Stop(); } private void LoadingCompleted(IStorableContent content) { //if (error != null) throw error; UpdateRun("Algorithm loading complete", StrategyState.Running); if (content is HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy) { algorithm = content as HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy; VehicleRoutingProblem problem = algorithm.Problem as VehicleRoutingProblem; if (problem == null) { Console.WriteLine("Unsupported problem type detected."); return; } SetProblemInstance(problem); ParameterizeProblem(problem); ParameterizeAlgorithm(algorithm); RegisterAlgorithmEventHandlers(algorithm); try { algorithm.Start(); } catch (Exception exc) { Console.WriteLine("Error Loading: " + exc.Message); } } else { // TODO: update the run status to error... //_strategyState = StrategyState.Stopped; } } private void SetProblemInstance(VehicleRoutingProblem problem) { //var pi = problem.ProblemInstance.Clone() as HeuristicLab.Problems.VehicleRouting.ProblemInstances.MDCVRPTWProblemInstance; HeuristicLab.Problems.VehicleRouting.Datalytics.ProblemInstances.MDCVRPTWProblemInstance pi = new HeuristicLab.Problems.VehicleRouting.Datalytics.ProblemInstances.MDCVRPTWProblemInstance(); pi.Cities.Value = _tasks.Count; pi.Depots.Value = _drivers.Count; pi.Vehicles.Value = _drivers.Count; // only allow 1 vehicle per depot pi.DistanceFactor.Value = 1.0; pi.FleetUsageFactor.Value = 0.0; pi.UseDistanceMatrix.Value = true; pi.Capacity = new DoubleArray(GetCapacity()); pi.Coordinates = new DoubleMatrix(GetCoordinates()); //_coordinates = pi.Coordinates; //string patientList = string.Join(",", _stopIds); //string staffList = string.Join(",", _driverIds); UpdateRun("Calculating Distance Matrix", StrategyState.Running); //Routing.Routing routing = new Routing.Routing(); //_routeLegs = routing.GetRouteLegs(patientList, staffList, "Distance"); pi.DistanceMatrix = CreateDistanceMatrix(); pi.TimeMatrix = CreateTimeMatrix(); pi.QualityMatrix = CreateQualityMatrix(); // cost-based functionality pi.CostOptimization.Value = _costOptimization; pi.DistanceToCostRatio.Value = _distanceCostRatio; pi.PerStopCost = CreatePerVisitCostArray(); pi.PerMileCost = CreatePerMileCostArray(); pi.AvgLegLength.Value = _avgLegLength; pi.AvgLegPenality.Value = _avgLegPenalty; pi.MaxLegLength.Value = _maxLegLength; pi.MaxLegPenality.Value = _maxLegPenalty; UpdateRun("Distance Matrix Loaded", StrategyState.Running); pi.Demand = new DoubleArray(GetDemand(_tasks.Count)); double dueTime = 1.7976931348623157E308; // Max double, we need this for some reason, 0 didn't work pi.DueTime = new DoubleArray(GetDueTime(_tasks.Count + _drivers.Count, dueTime)); pi.ServiceTime = new DoubleArray(GetServiceTime(_tasks.Count)); pi.ReadyTime = new DoubleArray(GetReadyTime(_tasks.Count + _drivers.Count)); pi.VehicleDepotAssignment = new IntArray(SetVehicleDepotAssignment(_drivers.Count)); // set the vehicle assigment array _vehicleAssignment = pi.VehicleDepotAssignment; problem.SetProblemInstance(pi); UpdateRun("Problem Instance Set", StrategyState.Running); } private void ParameterizeAlgorithm(HeuristicLab.Algorithms.EvolutionStrategy.EvolutionStrategy algorithm) { //set all parameters of the algorithm, e.g. algorithm.MaximumGenerations = new IntValue(_run.GenerationsToRun); } private void ParameterizeProblem(VehicleRoutingProblem problem) { //set all parameters of the problem, e.g. //problem.MaximizationParameter = false; } private double[,] GetCoordinates() { // depot (driver) coords are loaded in the first n slots, the stops afterwards double[,] coords = new double[_drivers.Count + _tasks.Count, 2]; // add the driver coords first int i = 0; foreach (Driver d in _drivers) { coords[i, 0] = Convert.ToDouble(d.location.latitude); coords[i, 1] = Convert.ToDouble(d.location.longitude); i++; } // now add the stop coords foreach (Task s in _tasks) { coords[i, 0] = Convert.ToDouble(s.stop.location.latitude); coords[i, 1] = Convert.ToDouble(s.stop.location.longitude); i++; } return coords; } private DoubleMatrix CreateDistanceMatrix() { DoubleMatrix distanceMatrix = new DoubleMatrix(_routeEntities.Count, _routeEntities.Count); for (int i = 0; i < distanceMatrix.Rows; i++) { for (int j = 0; j < distanceMatrix.Columns; j++) { var start = _routeEntities[i]; var end = _routeEntities[j]; RouteLeg leg = _routeLegs.Where(x => x.FromID == start.id && x.ToID == end.id).FirstOrDefault(); distanceMatrix[i, j] = Convert.ToDouble(leg.DrivingDistance); } } return distanceMatrix; } private DoubleMatrix CreateTimeMatrix() { DoubleMatrix timeMatrix = new DoubleMatrix(_routeEntities.Count, _routeEntities.Count); for (int i = 0; i < timeMatrix.Rows; i++) { for (int j = 0; j < timeMatrix.Columns; j++) { var start = _routeEntities[i]; var end = _routeEntities[j]; RouteLeg leg = _routeLegs.Where(x => x.FromID == start.id && x.ToID == end.id).FirstOrDefault(); timeMatrix[i, j] = Convert.ToDouble(leg.DrivingTime / 60); } } return timeMatrix; } private DoubleMatrix CreateQualityMatrix() { DoubleMatrix qualityMatrix = new DoubleMatrix(_drivers.Count, _tasks.Count); for (int i = 0; i < qualityMatrix.Rows; i++) { for (int j = 0; j < qualityMatrix.Columns; j++) { var start = _drivers[i].name; var end = _tasks [j].name; // TODO: Calculate the DriverTaskMultiplier fro Pref and Tags DriverTaskMultiplier multiplier = _mutipliers.Where(x => x.DriverName == start && x.TaskName == end).FirstOrDefault(); qualityMatrix[i, j] = multiplier.AdjustmentMultiplier; // Convert.ToDouble(mutiplier.AdjustmentMultiplier); } } return qualityMatrix; } private DoubleArray CreatePerVisitCostArray() { DoubleArray perVisitCostArray = new DoubleArray(_driverIds.Count); for (int i = 0; i < perVisitCostArray.Length; i++) { perVisitCostArray [i] = 0; //Convert.ToDouble(_drivers[i].PerVisitCost); } return perVisitCostArray; } private DoubleArray CreatePerMileCostArray() { DoubleArray perMileCostArray = new DoubleArray(_driverIds.Count); for (int i = 0; i < perMileCostArray.Length; i++) { perMileCostArray [i] = 0; //Convert.ToDouble(_drivers[i].PerMileCost); } return perMileCostArray; } // This set each driver starting point to their house private int[] SetVehicleDepotAssignment(int drivers) { int[] depots = new int[drivers]; for (int i = 0; i < drivers; i++) { depots[i] = i; } return depots; } private double[] GetCapacity() { double[] capacity = new double[_drivers.Count]; for (int i = 0; i < _drivers.Count; i++) { capacity[i] = Convert.ToDouble(_drivers[i].maxStops); } return capacity; } private double[] GetDueTime(int count, double dueTimeVal) { double[] dueTime = new double[count]; for (int i = 0; i < count; i++) { if (i < _drivers.Count) { dueTime [i] = Convert.ToDouble(_drivers[i].maxWorkTime / 60); } else { dueTime[i] = dueTimeVal; } } return dueTime; } private double[] GetServiceTime(int count) { double[] serviceTime = new double[count]; for (int i = 0; i < count; i++) { serviceTime [i] = Convert.ToDouble(_tasks[i].service.duration); } return serviceTime; } private double[] GetReadyTime(int count) { double[] readyTime = new double[count]; for (int i = 0; i < count; i++) { readyTime[i] = 0; } return readyTime; } private double[] GetDemand(int patients) { double[] demand = new double[patients]; for (int i = 0; i < patients; i++) { demand[i] = _demand; } return demand; } private void RegisterAlgorithmEventHandlers(EngineAlgorithm alg) { //alg.ExecutionStateChanged += new EventHandler(ExecutionStateChanged); alg.ExecutionTimeChanged += new EventHandler(ExecutionTimeChanged); alg.Stopped += new EventHandler(Stopped); //alg.Started += new EventHandler(Started); alg.Paused += new EventHandler(Paused); } private void DeregisterAlgorithmEventHandlers(EngineAlgorithm alg) { //alg.ExecutionStateChanged -= new EventHandler(ExecutionStateChanged); alg.ExecutionTimeChanged -= new EventHandler(ExecutionTimeChanged); alg.Stopped -= new EventHandler(Stopped); //alg.Started += new EventHandler(Started); alg.Paused += new EventHandler(Paused); } private void ExecutionTimeChanged(object sender, EventArgs e) { // maybe we should check to see if the execution time has been longer than say 5 secs? EngineAlgorithm alg = sender as EngineAlgorithm; // only update on certain intervals, so we don't tax the db unnecessarily var results = alg.Results.Clone() as ResultCollection; try { foreach (var s in results) { if (s.Name == "BestQuality") { // debug //var test = _pi.QualityMatrix; // get algorithm output string bestQuality = results["BestQuality"].Value.ToString(); string generations = results["Generations"].Value.ToString(); string bestSolution = GetBestSolution(results); string currentResults = GetCurrentResults(results); // only call the database on the last update //if(_run.GenerationsToRun == Convert.ToInt32(generations)) //{ _run.Generations = Convert.ToInt32(generations); _run.BestQuality = bestQuality; _run.BestSolution = bestSolution; _run.CurrentResults = currentResults; //Console.WriteLine("Thread1 -> Time: " + alg.ExecutionTime + ", Quality: " + alg.Results["BestQuality"].Value.ToString()); UpdateRun("Quality: " + alg.Results["BestQuality"].Value.ToString(), StrategyState.Running); //} } } } catch { //bool ignore = true; } } private void Paused(object sender, EventArgs e) { EngineAlgorithm alg = sender as EngineAlgorithm; Console.WriteLine("Execution paused"); alg.Stop(); } private void Stopped(object sender, EventArgs e) { EngineAlgorithm alg = sender as EngineAlgorithm; // only update on certain intervals, so we don't tax the db unnecessarily var results = alg.Results.Clone() as ResultCollection; foreach (var s in results) { if (s.Name == "BestQuality") { // get algorithm output string bestQuality = results["BestQuality"].Value.ToString(); string generations = results["Generations"].Value.ToString(); string bestSolution = GetBestSolution(results); string currentResults = GetCurrentResults(results); _run.Generations = Convert.ToInt32(generations); _run.BestQuality = bestQuality; _run.BestSolution = bestSolution; _run.CurrentResults = currentResults; //Console.WriteLine("Thread1 -> Time: " + alg.ExecutionTime + ", Quality: " + alg.Results["BestQuality"].Value.ToString()); UpdateRun("Optimization Completed", StrategyState.Stopped); } } DeregisterAlgorithmEventHandlers(alg); //UpdateRun("Optimization completed", StrategyState.Stopped); } private string GetBestSolution(ResultCollection results) { string result = string.Empty; try { if (results["Best VRP Solution"] == null) return null; // otherwise we have a valid solution, so update the database VRPSolution solution = results["Best VRP Solution"].Value as VRPSolution; var tours = solution.Solution.GetTours(); bool firstDriver = true; for (int i = 0; i < tours.Count; i++) { if (firstDriver) { firstDriver = false; } else { result += "|"; } int tourIndex = solution.Solution.GetTourIndex(tours[i]); int vehicle = solution.Solution.GetVehicleAssignment(tourIndex); int depot = _vehicleAssignment[vehicle]; //result += _driverIds[depot].ToString() + ":"; result += _drivers[depot].name + ":"; var stops = string.Empty; bool first = true; foreach (var s in tours[i].Stops) { if (first) first = false; else { stops += ","; } //stops += _stopIds[s - 1].ToString(); stops += _tasks[s - 1].name; var penalty = _mutipliers.Where(x => x.DriverName == _drivers[depot].name && x.TaskName == _tasks[s - 1].name).FirstOrDefault(); if(penalty.AdjustmentMultiplier >= 1000){ stops += "~2"; } else if(penalty.AdjustmentMultiplier > 1){ stops += "~1"; } else{ stops += "~0"; } if(_drivers[depot].name == "2" && _tasks[s - 1].stop.name == "100"){ var debug = true; } } result += stops; } } catch { //alg.Stop(); _strategyState = StrategyState.Stopped; return null; } return result; } private string GetCurrentResults(ResultCollection results) { string currentResults = string.Empty; bool first = true; foreach (var s in results) { if (s.Name != "Overloads" && s.Name != "TardinessValues" && s.Name != "TravelTimes" && s.Name != "Distances" && s.Name != "VehiclesUtilizedValues" && s.Name != "Best VRP Solution") { if (first) { first = false; } else { currentResults += "|"; } currentResults += s.Name + ":" + s.Value; } } return currentResults; } private void UpdateRun(string message, StrategyState state) { try { _strategyState = state; // Trigger update event StatusUpdate(this, new StatusUpdateEventArgs() { Run = _run, Message = message, State = this._strategyState, UpdateTime = DateTime.Now }); } catch { _strategyState = StrategyState.Stopped; //var error = exc.ToString(); } } } } <file_sep>/Solver/Models/Service.cs using System; using System.Collections.Generic; namespace Solver { public class Service { public string name { get; set; } public string driver { get; set; } public int duration { get; set; } public List<Pref> prefs { get; set; } } } <file_sep>/Solver/Models/DriverTaskMultiplier.cs using System; namespace Solver { public class DriverTaskMultiplier { public string TaskName { get; set; } public string DriverName { get; set; } public double AdjustmentMultiplier { get; set; } } } <file_sep>/solver-master-gc/OpsMaster/Models/RouteJobsResponse.cs using System; using System.Collections; using System.Collections.Generic; namespace Solver { public class RouteJobsResponse { public RouteJobsResponse() { this.RouteJobs = new List<OptimizationRun>(); } public List<OptimizationRun> RouteJobs { get; set; } } } <file_sep>/Solver/Models/ResponseDto/RouteResponse.cs using System; using System.Collections; using System.Collections.Generic; namespace Solver { public class RouteResponse { public int routeId { get; set; } public int customerId { get; set; } public int generations { get; set; } public List<Pref> prefs { get; set; } public List<Driver> drivers { get; set; } public List<Task> tasks { get; set; } } } <file_sep>/solver-master-gc/OpsMaster/bin/Release/startup.sh #! /bin/bash cd /etc/solver exec mono Solver.exe <file_sep>/solver-master-gc/OpsMaster/bin/Release/startupmaster.sh #! /bin/bash cd /etc/solver-master exec mono OpsMaster.exe <file_sep>/Solver/Models/RouteEntity.cs using System; using System.Collections.Generic; namespace Solver { public class RouteEntity { public int ID { get; set; } public int TypeID { get; set; } // geo-location public double? GeoLat { get; set; } public double? GeoLon { get; set; } // address public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } public static RouteEntity Convert(RouteStop incoming) { return new RouteEntity() { ID = incoming.ID, TypeID = 1, // Stops are type 1 GeoLat = incoming.GeoLat, GeoLon = incoming.GeoLon, Address = incoming.Address, City = incoming.City, State = incoming.State, Zip = incoming.Zip }; } public static IEnumerable<RouteEntity> Convert(IEnumerable<RouteStop> incoming) { List<RouteEntity> result = new List<RouteEntity>(); foreach (RouteStop stop in incoming) { result.Add(new RouteEntity() { ID = stop.ID, TypeID = 1, // Stops are type 1 GeoLat = stop.GeoLat, GeoLon = stop.GeoLon, Address = stop.Address, City = stop.City, State = stop.State, Zip = stop.Zip }); } return result; } public static RouteEntity Convert(RouteDriver incoming) { return new RouteEntity() { ID = incoming.ID, TypeID = 2, // Drivers are type 2 GeoLat = incoming.GeoLat, GeoLon = incoming.GeoLon, Address = incoming.Address, City = incoming.City, State = incoming.State, Zip = incoming.Zip }; } public static IEnumerable<RouteEntity> Convert(IEnumerable<RouteDriver> incoming) { List<RouteEntity> result = new List<RouteEntity>(); foreach (RouteDriver driver in incoming) { result.Add(new RouteEntity() { ID = driver.ID, TypeID = 2, // Drivers are type 2 GeoLat = driver.GeoLat, GeoLon = driver.GeoLon, Address = driver.Address, City = driver.City, State = driver.State, Zip = driver.Zip }); } return result; } } } <file_sep>/Solver/Models/TimeWindow.cs using System; using System.Collections.Generic; namespace Solver { public class TimeWindow { public int startTime { get; set; } public int stopTime { get; set; } } } <file_sep>/Solver/Models/OptimizationTag.cs using System; namespace Solver { public class OptimizationTag { public string Name { get; set; } public float Multiplier { get; set; } public bool IsExclusive { get; set; } } } <file_sep>/Solver/Optimization/OptimizationTagParser.cs using System; using System.Collections; using System.Collections.Generic; namespace Solver { public class OptimizationTagParser { public static IEnumerable<OptimizationTag> Parse(string Tags) { List<OptimizationTag> result = new List<OptimizationTag>(); foreach (string tag in Tags.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)) { if (tag.Contains("+")) { result.Add(new OptimizationTag() { IsExclusive = false, Name = tag.Substring(0, tag.IndexOf("+")), Multiplier = float.Parse(tag.Substring(tag.IndexOf("+") + 1)) }); } else { result.Add(new OptimizationTag() { IsExclusive = true, Name = tag.Substring(0, tag.IndexOf("-")), Multiplier = float.Parse(tag.Substring(tag.IndexOf("-") + 1)) }); } } return result; } } } <file_sep>/Solver/Models/Entity.cs using System; using System.Collections.Generic; namespace Solver { public class Entity { public long id { get; set; } public string externalId { get; set; } public float geoLat { get; set; } public float geoLon { get; set; } } } <file_sep>/Solver/Models/Stop.cs using System; using System.Collections.Generic; namespace Solver { public class Stop { public string name { get; set; } public Location location { get; set; } public TimeWindow timeWindow { get; set; } public List<string> tags { get; set; } public List<Pref> prefs { get; set; } } } <file_sep>/Solver/Program.cs using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using System.Net; using System.Data.SqlClient; using System.Data; namespace Solver { class Program { private static int _sleepDuration = 5000; private static Thread[] _threadArray; private const int NUMBER_OF_THREADS = 1; private static bool _alive = true; static void Main(string[] args) { Console.WriteLine("*** Control-C To Quit v2.0 ***"); Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPress_EventHandler); // create a single instance of the ContentManager... ContentManager.Initialize(new PersistenceContentManager()); _threadArray = new Thread[NUMBER_OF_THREADS]; for (int index = 1; index <= NUMBER_OF_THREADS; index++) { OptimizationJob oj = new OptimizationJob(index, _sleepDuration); _threadArray[index - 1] = new Thread(new ThreadStart(oj.StartOptimization)); _threadArray[index - 1].Start(); } // keep the console open...praise be to Scotty while (_alive) { Console.ReadKey(); } } protected static void CancelKeyPress_EventHandler(object sender, ConsoleCancelEventArgs args) { Console.WriteLine("*** QUIT COMMAND RECEIVED ***"); _alive = false; Environment.Exit(0); } } } <file_sep>/Solver/Routing.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Solver { public class Routing { private const string BING_API_KEY = "<KEY>"; // Signals the routing engine what trip "cost" factor to optimize on. Examples are: distance, time, environmental, maintenance, etc. public enum CostType { Distance, Time // not yet used } /* // This method will attempt to geocode and drivers or stops with missing coordinates and will filter out those that were not able to be geocoded. public void GeocodeRouteEntities(ref ICollection<RouteStop> Stops, ref ICollection<RouteDriver> Drivers, ref ICollection<RouteOrder> Orders, int CustomerID) { BingServices bing = new BingServices(BING_API_KEY); // get the connection string for the customer, so we can query the RouteLeg table with their drivers and stops CentralUnitOfWork centralUnitOfWork = new CentralUnitOfWork("data source=coordcare.com;Initial Catalog=CoordCareCentral;User Id=CoordCareWeb;Password=<PASSWORD>;Persist Security Info=True"); using (RoutingUnitOfWork unitOfWork = new RoutingUnitOfWork(centralUnitOfWork.ScheduleCustomerRepository.GetByID(CustomerID).ConnectionString)) { // Get drivers and geolocate any missing List<RouteDriver> drivers = unitOfWork.GetRouteDrivers(string.Join(",", from u in Drivers select u.ID.ToString())).ToList(); foreach (RouteDriver driver in drivers) { if (!driver.GeoLat.HasValue || !driver.GeoLon.HasValue) { // geo-locate this driver double lat; double lon; RouteDriver updater = unitOfWork.RouteDriverRepository.GetByID(driver.ID); if (bing.GeocodeAddress(driver.Address, driver.City, driver.State, driver.Zip, out lat, out lon, BingServices.GeocodeConfidence.Medium) != BingServices.GeocodeConfidence.Zero) { // update the ref driver, we we'll have the geocode for the GetRouteLegs step var dToUpdate = Drivers.Where(x => x.ID == driver.ID); foreach(var d in dToUpdate) { d.GeoLat = lat; d.GeoLon = lon; } updater.GeoLat = lat; updater.GeoLon = lon; unitOfWork.Save(); } else { // unable to geocode, remove this driver from the list Drivers.Remove((from d in Drivers where d.ID == driver.ID select d).FirstOrDefault()); } } } // Get patients and geolocate any missing List<RouteStop> stops = unitOfWork.GetRouteStops(string.Join(",", from u in Stops select u.ID.ToString())).ToList(); foreach (RouteStop stop in stops) { if (!stop.GeoLat.HasValue || !stop.GeoLon.HasValue) { // geo-locate this stop double lat; double lon; RouteStop updater = unitOfWork.RouteStopRepository.GetByID(stop.ID); if (bing.GeocodeAddress(stop.Address, stop.City, stop.State, stop.Zip, out lat, out lon, BingServices.GeocodeConfidence.Medium) != BingServices.GeocodeConfidence.Zero) { // update the ref stop, we we'll have the geocode for the GetRouteLegs step var sToUpdate = Stops.Where(x => x.ID == stop.ID); foreach (var s in sToUpdate) { s.GeoLat = lat; s.GeoLon = lon; } updater.GeoLat = lat; updater.GeoLon = lon; unitOfWork.Save(); } else { // unable to geocode, remove this stop from the list Stops.Remove((from s in Stops where s.ID == stop.ID select s).FirstOrDefault()); // need to remove the order associated with the stop that was removed Orders.Remove((from o in Orders where o.StopID == stop.ID select o).FirstOrDefault()); } } } } } // Get distance for every possible combination of driver/stop public ICollection<RouteLeg> GetRouteLegs(ICollection<RouteStop> Stops, ICollection<RouteDriver> Drivers, int CustomerID, CostType CostType) { BingServices bing = new BingServices(BING_API_KEY); // get the connection string for the customer, so we can query the RouteLeg table with their drivers and stops CentralUnitOfWork centralUnitOfWork = new CentralUnitOfWork("data source=coordcare.com;Initial Catalog=CoordCareCentral;User Id=CoordCareWeb;Password=<PASSWORD>;Persist Security Info=True"); using (RoutingUnitOfWork unitOfWork = new RoutingUnitOfWork(centralUnitOfWork.ScheduleCustomerRepository.GetByID(CustomerID).ConnectionString)) { // get existing driving distances and times from database ICollection<RouteLeg> result = unitOfWork.CalculateDrivingMatrix( string.Join(",", from p in Stops select p.ID.ToString()), string.Join(",", from u in Drivers select u.ID.ToString())); //var test = result.Where(x => x.FromID == 27 && x.FromTypeID == 27).ToList(); // find any gaps in calculations, marked with -1 distance calc if (result.Where(x => x.DrivingDistance == -1).Count() > 0) { // fill in the gaps foreach (RouteLeg calc in result.Where(x => x.DrivingDistance == -1)) { // check if the from and to resources are the same resource if (!(calc.FromID == calc.ToID && calc.FromTypeID == calc.ToTypeID)) { // get the patient or user involved if (calc.FromTypeID == 1 && calc.ToTypeID == 1) { RouteStop fromPatient = Stops.Where(x => x.ID == calc.FromID).FirstOrDefault(); RouteStop toPatient = Stops.Where(x => x.ID == calc.ToID).FirstOrDefault(); // Ensure that entities involved are routable EnsureEntityIsRoutable(fromPatient); EnsureEntityIsRoutable(toPatient); // get distance and time double[] bingResult = bing.GetDrivingDistanceAndTimeBetween2Points( Convert.ToDouble(fromPatient.GeoLat), Convert.ToDouble(fromPatient.GeoLon), Convert.ToDouble(toPatient.GeoLat), Convert.ToDouble(toPatient.GeoLon)); // store result unitOfWork.RouteLegRepository.Insert(new RouteLeg() { DrivingDistance = Convert.ToDecimal(bingResult[0]), DrivingTime = Convert.ToDecimal(bingResult[1]), FromID = calc.FromID, FromTypeID = 1, // patient ToID = calc.ToID, ToTypeID = 1 // patient // LastModifiedDate = DateTime.Now }); unitOfWork.Save(); // update result list calc.DrivingDistance = Convert.ToDecimal(bingResult[0]); calc.DrivingTime = Convert.ToDecimal(bingResult[1]); } else if (calc.FromTypeID == 1 && calc.ToTypeID == 2) { RouteStop fromPatient = Stops.Where(x => x.ID == calc.FromID).FirstOrDefault(); RouteDriver toUserAccount = Drivers.Where(x => x.ID == calc.ToID).FirstOrDefault(); // Ensure that entities involved are routable EnsureEntityIsRoutable(fromPatient); EnsureEntityIsRoutable(toUserAccount); // get distance and time double[] bingResult = bing.GetDrivingDistanceAndTimeBetween2Points( Convert.ToDouble(fromPatient.GeoLat), Convert.ToDouble(fromPatient.GeoLon), Convert.ToDouble(toUserAccount.GeoLat), Convert.ToDouble(toUserAccount.GeoLon)); // store result unitOfWork.RouteLegRepository.Insert(new RouteLeg() { DrivingDistance = Convert.ToDecimal(bingResult[0]), DrivingTime = Convert.ToDecimal(bingResult[1]), FromID = calc.FromID, FromTypeID = 1, // patient ToID = calc.ToID, ToTypeID = 2 // user //LastModifiedDate = DateTime.Now }); unitOfWork.Save(); // update result list calc.DrivingDistance = Convert.ToDecimal(bingResult[0]); calc.DrivingTime = Convert.ToDecimal(bingResult[1]); } else if (calc.FromTypeID == 2 && calc.ToTypeID == 2) { RouteDriver fromUserAccount = Drivers.Where(x => x.ID == calc.FromID).FirstOrDefault(); RouteDriver toUserAccount = Drivers.Where(x => x.ID == calc.ToID).FirstOrDefault(); // Ensure that entities involved are routable EnsureEntityIsRoutable(fromUserAccount); EnsureEntityIsRoutable(toUserAccount); // get distance and time double[] bingResult = bing.GetDrivingDistanceAndTimeBetween2Points( Convert.ToDouble(fromUserAccount.GeoLat), Convert.ToDouble(fromUserAccount.GeoLon), Convert.ToDouble(toUserAccount.GeoLat), Convert.ToDouble(toUserAccount.GeoLon)); // store result unitOfWork.RouteLegRepository.Insert(new RouteLeg() { DrivingDistance = Convert.ToDecimal(bingResult[0]), DrivingTime = Convert.ToDecimal(bingResult[1]), FromID = calc.FromID, FromTypeID = 2, // user ToID = calc.ToID, ToTypeID = 2 // user //LastModifiedDate = DateTime.Now }); unitOfWork.Save(); // update result list calc.DrivingDistance = Convert.ToDecimal(bingResult[0]); calc.DrivingTime = Convert.ToDecimal(bingResult[1]); } else// if((calc.FromResourceID.Contains("u") && calc.ToResourceID.Contains("p")) { RouteDriver fromUserAccount = Drivers.Where(x => x.ID == calc.FromID).FirstOrDefault(); RouteStop toPatient = Stops.Where(x => x.ID == calc.ToID).FirstOrDefault(); // Ensure that entities involved are routable EnsureEntityIsRoutable(fromUserAccount); EnsureEntityIsRoutable(toPatient); // get distance and time double[] bingResult = bing.GetDrivingDistanceAndTimeBetween2Points( Convert.ToDouble(fromUserAccount.GeoLat), Convert.ToDouble(fromUserAccount.GeoLon), Convert.ToDouble(toPatient.GeoLat), Convert.ToDouble(toPatient.GeoLon)); // store result unitOfWork.RouteLegRepository.Insert(new RouteLeg() { DrivingDistance = Convert.ToDecimal(bingResult[0]), DrivingTime = Convert.ToDecimal(bingResult[1]), FromID = calc.FromID, FromTypeID = 2, // user ToID = calc.ToID, ToTypeID = 1 // patient //LastModifiedDate = DateTime.Now }); unitOfWork.Save(); // update result list calc.DrivingDistance = Convert.ToDecimal(bingResult[0]); calc.DrivingTime = Convert.ToDecimal(bingResult[1]); } } } } List<RouteLeg> legs = new List<RouteLeg>(); foreach (RouteLeg c in result) { legs.Add(new RouteLeg { FromID = c.FromID, FromTypeID = c.FromTypeID, ToID = c.ToID, ToTypeID = c.ToTypeID, DrivingDistance = c.DrivingDistance, DrivingTime = c.DrivingTime }); } return legs; } } */ public ICollection<RouteOrderMultiplier> GetRouteMultipliers(ICollection<RouteOrder> Orders, ICollection<RouteDriver> Drivers, IEnumerable<OptimizationTag> Multipliers) { List<RouteOrderMultiplier> result = new List<RouteOrderMultiplier>(); // Set all driver multipliers (globally applied to any of a driver's possible visits) Dictionary<int, float> driverMultipliers = new Dictionary<int, float>(); foreach (RouteDriver driver in Drivers) { // Add multiplier to lookup driverMultipliers.Add(driver.ID, CalculateDriverMultiplier(driver, Multipliers)); } // Set route order multipliers (drivers and stops) foreach (RouteOrder order in Orders) { // Create multiplier record for every driver for this order foreach(RouteDriver driver in Drivers) { result.Add(new RouteOrderMultiplier() { RouteOrderID = order.ID, RouteDriverID = driver.ID, AdjustmentMultiplier = CalculateDriverOrderMultiplier(driver, order, Multipliers) + (driverMultipliers[driver.ID] - 1.0f) }); } } return result; } private float CalculateDriverMultiplier(RouteDriver Driver, IEnumerable<OptimizationTag> Multipliers) { float result = 1.0f; string[] driverTags = Driver.Tags.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); foreach (string tag in driverTags) { OptimizationTag optimizationTag = (from m in Multipliers where m.Name == tag && !m.IsExclusive select m).FirstOrDefault(); if (optimizationTag != null) { result += (optimizationTag.Multiplier - 1.0f); // multiplier is additive, not compounding } } return result; } private float CalculateDriverOrderMultiplier(RouteDriver Driver, RouteOrder Order, IEnumerable<OptimizationTag> Multipliers) { float result = 1.0f; string[] orderTags = Order.Tags.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); foreach (string tag in orderTags) { OptimizationTag optimizationTag = (from m in Multipliers where (m.Name == tag) || (m.Name.Contains("*") && tag.StartsWith(m.Name.Substring(0, m.Name.IndexOf("*")))) // handle wildcards && m.IsExclusive select m) .FirstOrDefault(); if (optimizationTag != null && !Driver.Tags.Contains(tag)) { // If optimization tag is not found for the driver, apply multiplier result += (optimizationTag.Multiplier - 1.0f); // multiplier is additive, not compounding } } return result; } private static void EnsureEntityIsRoutable(RouteDriver entity) { if(!entity.GeoLat.HasValue || !entity.GeoLon.HasValue) throw new RoutingEntityException("Driver missing geocoding coordinates.", entity.ID); } private static void EnsureEntityIsRoutable(RouteStop entity) { if (!entity.GeoLat.HasValue || !entity.GeoLon.HasValue) throw new RoutingEntityException("Stop missing geocoding coordinates.", entity.ID); } } } <file_sep>/Solver/Optimization/OptimizationJob.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Xml; using System.Threading; using System.Configuration; using ServiceStack.ServiceClient.Web; using PubNubMessaging.Core; using System.IO; using System.Net; using System.Diagnostics; using Npgsql; using NpgsqlTypes; using Newtonsoft.Json; namespace Solver { public class OptimizationJob { static public Pubnub pubnub; static public bool deliveryStatus = false; static public string channel = "routing"; private int _sleepDuration = 5000; private int _threadID = 0; private int _generation = 0; private int _runID = 0; private EvoStrat _evoStrat; // thread status private bool _running = false; private bool _ready = false; public OptimizationJob(int ThreadID, int? SleepDuration) { _threadID = ThreadID; if (SleepDuration.HasValue) _sleepDuration = SleepDuration.Value; InitializeMessaging (); } public void InitializeMessaging() { pubnub = new Pubnub("pub-c-efa16124-0af8-46ae-b518-3ce6d735c9db", "sub-c-05ff316c-f560-11e2-a11a-02ee2ddab7fe"); } public void SendMessage(string message) { pubnub.Publish<string>(channel + _runID.ToString(), message, DisplayReturnMessage); } static void DisplayReturnMessage(string result) { //Console.WriteLine(result); } private void PublishVrpRunMessage(int runId, int generations, string bestQuality, string bestSolution, string currentResults, string message) { string pMessage = ""; pMessage = "ID=" + runId + "^Generations=" + generations.ToString () + "^BestQuality=" + bestQuality + "^BestSolution=" + bestSolution + "^Message=" + message; SendMessage (pMessage); } public void Stop() { _running = false; _ready = false; } public void StartOptimization() { _running = true; _ready = true; while (_running && _ready) { OptimizationRun run = new OptimizationRun(); RouteResponse response = null; List<Entity> routeEntities = new List<Entity> (); List<RouteLeg> routeLegs = new List<RouteLeg>(); try{ // First, let's check to see if there's any jobs to process response = GetNextJobToProcess(); if (response != null) { // we've got a job! run.ID = response.routeId; _runID = response.routeId; _ready = false; Console.WriteLine ("Set RunID = " + run.ID); List<Int64> driverList = new List<Int64>(); List<Int64> stopList = new List<Int64>(); Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started."); NpgsqlConnection conn = new NpgsqlConnection("Server=hci.cvwcpfnur8ep.us-east-1.rds.amazonaws.com;Port=5432;User Id=hci_user;Password=<PASSWORD>;Database=route;"); conn.Open(); try { // Update the driver entities foreach(Driver d in response.drivers){ NpgsqlCommand command = new NpgsqlCommand( "SELECT * FROM update_entity(" + response.customerId.ToString() + "::bigint, " + d.name + "::varchar, " + d.location.latitude.ToString() + "::float8, " + d.location.longitude.ToString() + "::float8, " + "2::int2)", conn); command.CommandType = CommandType.Text; Object result = command.ExecuteScalar(); // set the driver system id d.id = Convert.ToInt64(result); driverList.Add(Convert.ToInt64(result)); // now add the driver to the entity list routeEntities.Add(new Entity{ id = Convert.ToInt64(result), geoLat = d.location.latitude, geoLon = d.location.longitude }); } Console.WriteLine("Drivers: " + string.Join<Int64>(",", driverList)); // update the stop entities foreach(Task t in response.tasks){ NpgsqlCommand command = new NpgsqlCommand( "SELECT * FROM update_entity(" + response.customerId.ToString() + "::bigint, " + t.stop.name + "::varchar, " + t.stop.location.latitude.ToString() + "::float8, " + t.stop.location.longitude.ToString() + "::float8, " + "1::int2)", conn); command.CommandType = CommandType.Text; Object result = command.ExecuteScalar(); // set's the id to the stop ID, to lookup during the routeleg calculation t.id = Convert.ToInt64(result); stopList.Add(Convert.ToInt64(result)); // now add the stop to the entity list routeEntities.Add(new Entity{ id = Convert.ToInt64(result), geoLat = t.stop.location.latitude, geoLon = t.stop.location.longitude }); } Console.WriteLine("Stops: " + string.Join<Int64>(",", stopList)); // now get a list of route legs string drivers = string.Join<Int64>(",", driverList); string stops = string.Join<Int64>(",", stopList); NpgsqlCommand legCommand = new NpgsqlCommand("SELECT * FROM calc_entity_matrix('" + drivers + "','" + stops + "')", conn); NpgsqlDataReader dr = legCommand.ExecuteReader(); while(dr.Read()) { routeLegs.Add(new RouteLeg{ FromID = Convert.ToInt32(dr.GetValue(0)), ToID = Convert.ToInt32(dr.GetValue(1)), DrivingDistance = Convert.ToDecimal(dr.GetValue(2)), DrivingTime = Convert.ToDecimal(dr.GetValue(3)) }); } } finally { conn.Close(); } // Now calculate the route leg stuff Routing routing = new Routing(); ICollection<RouteLeg> legs = routing.GetRouteLegs(routeEntities, routeLegs, 1, Routing.CostType.Distance); ICollection<DriverTaskMultiplier> legMultipliers = routing.GetRoutePenalties(response.drivers, response.tasks); int demand = 1; // set the alogorithm manually for demo run.GenerationsToRun = response.generations; run.Algorithm = "ES_MDVRPTW_v3.hl"; run.CostOptimization = false; run.DistanceCostRatio = 1.0m; run.AvgLegLength = 20; run.AvgLegPenalty = 0; run.MaxLegLength = 30; run.MaxLegPenalty = 0; _evoStrat = new EvoStrat( run, driverList, stopList, routeEntities, response.drivers, response.tasks, legs, legMultipliers, run.CostOptimization, Convert.ToDouble(run.DistanceCostRatio), Convert.ToDouble(run.AvgLegLength), Convert.ToDouble(run.MaxLegLength), Convert.ToDouble(run.AvgLegPenalty), Convert.ToDouble(run.MaxLegPenalty), demand); _evoStrat.StatusUpdate += new EventHandler(Routing_StatusUpdate); _evoStrat.StartOptimization(); } else { //Stop (); // No jobs, so terminate instance! Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": No job to process..."); //Process shutdown = new Process(); //shutdown.StartInfo.FileName = "shutdown.sh"; //shutdown.Start(); Thread.Sleep(_sleepDuration); } } catch(Exception exc){ // ignore error Thread.Sleep(_sleepDuration); var error = exc; } } // loop until it gets a job } private RouteResponse GetNextJobToProcess(){ RouteResponse result = null; NpgsqlConnection conn = new NpgsqlConnection("Server=hci.cvwcpfnur8ep.us-east-1.rds.amazonaws.com;Port=5432;User Id=hci_user;Password=<PASSWORD>;Database=route;"); conn.Open(); try { NpgsqlCommand legCommand = new NpgsqlCommand("SELECT * FROM get_next_route()", conn); NpgsqlDataReader dr = legCommand.ExecuteReader(); while(dr.Read()) { var jsonObject = dr.GetValue(1).ToString(); result = JsonConvert.DeserializeObject<RouteResponse>(jsonObject); result.routeId = Convert.ToInt32(dr.GetValue(0)); } } catch(Exception exc){ var error = exc; } finally { conn.Close (); } return result; } private void Routing_StatusUpdate(object sender, EventArgs e) { EvoStrat.StatusUpdateEventArgs evt = (EvoStrat.StatusUpdateEventArgs)e; // Note: Both methods below work, we just need to determine which we want to use // Update: looks like the EF version isn't as stable, since it's holding on to contexts and such, use SP version. try { // Stored ProcVersion if(evt.State == EvoStrat.StrategyState.Completed || evt.State == EvoStrat.StrategyState.Stopped) { //UpdateVrpRun(evt.Run.ID, evt.Run.Generations, evt.Run.BestQuality, evt.Run.BestSolution, evt.Run.CurrentResults, evt.Message); PublishVrpRunMessage(evt.Run.ID, evt.Run.Generations, evt.Run.BestQuality, evt.Run.BestSolution, evt.Run.CurrentResults, evt.Message); // now restart the listener if(evt.State == EvoStrat.StrategyState.Stopped) { StartOptimization(); } } else if(evt.Run.Generations != _generation) // only update status once per generation { _generation = evt.Run.Generations; //UpdateVrpRun(evt.Run.ID, evt.Run.Generations, evt.Run.BestQuality, evt.Run.BestSolution, evt.Run.CurrentResults, evt.Message); PublishVrpRunMessage(evt.Run.ID, evt.Run.Generations, evt.Run.BestQuality, evt.Run.BestSolution, evt.Run.CurrentResults, evt.Message); switch (evt.State) { case EvoStrat.StrategyState.Completed: _ready = true; Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + " completed. (" + evt.Run.Generations + ")"); break; case EvoStrat.StrategyState.Paused: Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + " paused. (" + evt.Run.Generations + ")"); break; case EvoStrat.StrategyState.Running: Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + ": " + evt.Message + " (" + evt.Run.Generations + ")"); break; case EvoStrat.StrategyState.Stopped: _ready = true; Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + ": Optimization job " + evt.Run.ID + " completed. (" + evt.Run.Generations + ")"); break; } } } catch { //var ignore = true; } } } } <file_sep>/Solver/Routing/RoutingEntityException.cs using System; namespace Solver { [Serializable] public class RoutingEntityException : ApplicationException { public int EntityID { get; set; } public int EntityTypeID { get; set; } public RoutingEntityException(string message, Exception innerException) : base(message, innerException) { } public RoutingEntityException(string message) : base(message) { } public RoutingEntityException(string message, int entityID) : base(message) { this.EntityID = entityID; } public RoutingEntityException(string message, int entityID, int entityTypeID) : base(message) { this.EntityID = entityID; this.EntityTypeID = entityTypeID; } } } <file_sep>/solver-master-gc/OpsMaster/Program.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Data.SqlClient; using System.Data; using System.Threading; //using Google.Apis; //using Google.Apis.Compute.v1beta15; //using Google.Apis.Compute.v1beta15.Data; using System.Diagnostics; namespace OpsMaster { class MainClass { private static int _sleepDuration = 5000; private static bool _alive = true; public static void Main (string[] args) { Console.WriteLine ("*** Optimization Master Service Started ***"); Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPress_EventHandler); Master m = new Master(_sleepDuration); Thread master = new Thread(new ThreadStart(m.StartMaster)); master.Start(); // keep the console open...praise be to Scotty while (_alive) { Console.ReadKey(); } } protected static void CancelKeyPress_EventHandler(object sender, ConsoleCancelEventArgs args) { Console.WriteLine("*** QUIT COMMAND RECEIVED ***"); _alive = false; Environment.Exit(0); } } } <file_sep>/Solver/Models/Task.cs using System; using System.Collections.Generic; namespace Solver { public class Task { public long id { get; set; } public string name { get; set; } public Stop stop { get; set; } public Service service { get; set; } } } <file_sep>/solver-master-gc/OpsMaster/Master.cs using System; using System.Threading; using ServiceStack.ServiceClient.Web; using Solver; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Diagnostics; namespace OpsMaster { public class Master { private int _sleepDuration = 5000; // thread status private bool _running = false; private bool _ready = false; public Master (int? SleepDuration) { if (SleepDuration.HasValue) _sleepDuration = SleepDuration.Value; } public void StartMaster() { _running = true; _ready = true; while (_running && _ready) { List<OptimizationRun> pendingJobs = new List<OptimizationRun> (); using (JsonServiceClient client = new JsonServiceClient()) { RouteJobsResponse response = client.Get<RouteJobsResponse>("http://api.datalyticsllc.com/routing/routejobs/"); if(response.RouteJobs.Count > 0) { pendingJobs = response.RouteJobs; Console.WriteLine (pendingJobs.Count.ToString() + " pending jobs found...starting optimization slaves."); } }; if (pendingJobs.Count > 0) { foreach (OptimizationRun job in pendingJobs) { long serverId = DateTime.Now.Ticks; Console.WriteLine ("*** Attempting to start Google Instance: slave-" + serverId.ToString() + " ***"); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "createinstance.sh", Arguments = "slave-" + serverId.ToString(), UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start (); while (!proc.StandardOutput.EndOfStream) { string line = proc.StandardOutput.ReadLine(); // do something with line } } // now sleep the timer for 30 seconds to give the machines time to come back up Thread.Sleep(60000); } else { Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] : No job to process."); Thread.Sleep(_sleepDuration); } } } } } <file_sep>/Solver/Routing/BingServices.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Solver { public class BingServices { private BingRouteService.Credentials _credentials; // e.g. "<KEY>" private BingGeocodeService.Credentials _geoCredentials; public enum GeocodeConfidence { Zero, Low, Medium, High } public BingServices(string BingAppID) { _credentials = new BingRouteService.Credentials(); _credentials.ApplicationId = BingAppID; _geoCredentials = new BingGeocodeService.Credentials(); _geoCredentials.ApplicationId = BingAppID; } public double GetDrivingDistanceBetween2Points(double lat1, double lon1, double lat2, double lon2) { BingRouteService.RouteService routing = new BingRouteService.RouteService(); BingRouteService.RouteRequest routeRequest = new BingRouteService.RouteRequest(); routeRequest.Credentials = _credentials; routeRequest.UserProfile = new BingRouteService.UserProfile { DistanceUnit = BingRouteService.DistanceUnit.Mile }; BingRouteService.RouteOptions routeOptions = new BingRouteService.RouteOptions(); routeOptions.Optimization = BingRouteService.RouteOptimization.MinimizeTime; routeOptions.TrafficUsage = BingRouteService.TrafficUsage.None; routeOptions.Mode = BingRouteService.TravelMode.Driving; routeRequest.Options = routeOptions; routeRequest.Waypoints = new BingRouteService.Waypoint[2]; BingRouteService.Waypoint wp1 = new BingRouteService.Waypoint { Location = new BingRouteService.Location { Latitude = lat1, Longitude = lon1, LatitudeSpecified = true, LongitudeSpecified = true } }; routeRequest.Waypoints[0] = wp1; BingRouteService.Waypoint wp2 = new BingRouteService.Waypoint { Location = new BingRouteService.Location { Latitude = lat2, Longitude = lon2, LatitudeSpecified = true, LongitudeSpecified = true } }; routeRequest.Waypoints[1] = wp2; BingRouteService.RouteResponse routeResponse = routing.CalculateRoute(routeRequest); return routeResponse.Result.Summary.Distance; } // Gets the distance (in miles) and time (in seconds) and returns them in an array of double public double[] GetDrivingDistanceAndTimeBetween2Points(double lat1, double lon1, double lat2, double lon2) { BingRouteService.RouteService routing = new BingRouteService.RouteService(); BingRouteService.RouteRequest routeRequest = new BingRouteService.RouteRequest(); routeRequest.Credentials = _credentials; routeRequest.UserProfile = new BingRouteService.UserProfile { DistanceUnit = BingRouteService.DistanceUnit.Mile }; BingRouteService.RouteOptions routeOptions = new BingRouteService.RouteOptions(); routeOptions.Optimization = BingRouteService.RouteOptimization.MinimizeTime; routeOptions.TrafficUsage = BingRouteService.TrafficUsage.None; routeOptions.Mode = BingRouteService.TravelMode.Driving; routeRequest.Options = routeOptions; routeRequest.Waypoints = new BingRouteService.Waypoint[2]; BingRouteService.Waypoint wp1 = new BingRouteService.Waypoint { Location = new BingRouteService.Location { Latitude = lat1, Longitude = lon1, LatitudeSpecified = true, LongitudeSpecified = true } }; routeRequest.Waypoints[0] = wp1; BingRouteService.Waypoint wp2 = new BingRouteService.Waypoint { Location = new BingRouteService.Location { Latitude = lat2, Longitude = lon2, LatitudeSpecified = true, LongitudeSpecified = true } }; routeRequest.Waypoints[1] = wp2; BingRouteService.RouteResponse routeResponse = routing.CalculateRoute(routeRequest); return new double[] { routeResponse.Result.Summary.Distance, routeResponse.Result.Summary.TimeInSeconds }; } // Geocodes the given address and returns the confidence level public GeocodeConfidence GeocodeAddress(string address, string city, string state, string zip, out double lat, out double lon, GeocodeConfidence minConfidence) { if(string.IsNullOrEmpty(address)) throw new ArgumentException("Missing 'address' parameter."); if(string.IsNullOrEmpty(city)) throw new ArgumentException("Missing 'city' parameter."); if(string.IsNullOrEmpty(state)) throw new ArgumentException("Missing 'state' parameter."); if(string.IsNullOrEmpty(zip)) throw new ArgumentException("Missing 'zip' parameter."); // Reference geocode client BingGeocodeService.GeocodeService client = new BingGeocodeService.GeocodeService (); // Set the options to only return high confidence results BingGeocodeService.ConfidenceFilter[] filters = new BingGeocodeService.ConfidenceFilter[1]; filters[0] = new BingGeocodeService.ConfidenceFilter(); filters[0].MinimumConfidence = TranslateGeocodeConfidence(minConfidence); // Build geocode request BingGeocodeService.GeocodeRequest request = new BingGeocodeService.GeocodeRequest(); request.Query = address + ", " + city + ", " + state + ", " + zip; request.Credentials = _geoCredentials; // Issue request BingGeocodeService.GeocodeResponse response = client.Geocode(request); // Set out params if (response.Results.Length > 0) { lat = response.Results[0].Locations[0].Latitude; lon = response.Results[0].Locations[0].Longitude; return TranslateBingConfidence(response.Results[0].Confidence); } else { lat = 0; lon = 0; return 0; // no confidence, bad result } } private static GeocodeConfidence TranslateBingConfidence(BingGeocodeService.Confidence confidence) { GeocodeConfidence result = GeocodeConfidence.Zero; switch (confidence) { case BingGeocodeService.Confidence.High: result = GeocodeConfidence.High; break; case BingGeocodeService.Confidence.Medium: result = GeocodeConfidence.Medium; break; case BingGeocodeService.Confidence.Low: result = GeocodeConfidence.Low; break; } return result; } private static BingGeocodeService.Confidence TranslateGeocodeConfidence(GeocodeConfidence confidence) { BingGeocodeService.Confidence result = BingGeocodeService.Confidence.Low; switch (confidence) { case GeocodeConfidence.High: result = BingGeocodeService.Confidence.High; break; case GeocodeConfidence.Medium: result = BingGeocodeService.Confidence.Medium; break; } return result; } } } <file_sep>/Solver/Models/RouteLeg.cs using System; namespace Solver { public class RouteLeg { public int FromID { get; set; } public int FromTypeID { get; set; } public int ToID { get; set; } public int ToTypeID { get; set; } public decimal DrivingDistance { get; set; } public decimal DrivingTime { get; set; } } } <file_sep>/Solver/Models/Pref.cs using System; using System.Collections.Generic; namespace Solver { public class Pref { public string tag { get; set; } public int multiplier { get; set; } public bool required { get; set; } public bool exclude { get; set; } public int penalty { get; set; } } } <file_sep>/Solver/OptimizationJob.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Xml; using System.Threading; using System.Configuration; using ServiceStack.ServiceClient.Web; namespace Solver { public class OptimizationJob { private int _sleepDuration = 5000; private string _connectionString; private int _threadID = 0; private EvoStrat _evoStrat; // thread status private bool _running = false; private bool _ready = false; public OptimizationJob(int ThreadID, string ConnectionString, int? SleepDuration) { if (string.IsNullOrEmpty(ConnectionString)) throw new ArgumentException("OptimizationJob: ConnectionString parameter missing."); else _connectionString = ConnectionString; _threadID = ThreadID; if (SleepDuration.HasValue) _sleepDuration = SleepDuration.Value; } public void Stop() { _running = false; _ready = false; } public void StartOptimization() { _running = true; _ready = true; while (_running && _ready) { // first get the next Optimization Run to solve //OptimizationRun run = GetNextOptimizationJob(); OptimizationRun run = null; using (JsonServiceClient client = new JsonServiceClient()) { RouteJobsResponse response = client.Get<RouteJobsResponse>("http://api.datalyticsllc.com/routing/routejobs/-1"); if(response.RouteJobs.Count > 0) { run = response.RouteJobs [0]; } }; if (run != null) { //Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started."); /* // get the connection string for the customer who posted the optimization job ScheduleCustomer customer = centralUnitOfWork.ScheduleCustomerRepository.GetByID(run.CustomerID); RoutingUnitOfWork unitOfWork = new RoutingUnitOfWork(customer.ConnectionString); */ // we've got a job! don't get the next job off this thread...we're done. _ready = false; Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started."); /* // need to dynamically switch to the customer database to get the list of drivers and orders ICollection<RouteDriver> drivers = unitOfWork.GetRouteDriversWithAvailability(run.Drivers, run.ServiceDate).ToList(); ICollection<RouteOrder> orders = unitOfWork.GetRouteOrders(run.Orders).ToList(); // get a list of stops from the orders (ie. patients from the visits). Used for RouteLeg lookup ICollection<RouteStop> stops = orders.Select(x => new RouteStop() { ID = x.StopID, GeoLat = x.GeoLat, GeoLon = x.GeoLon, Address = x.Address, City = x.City, State = x.State, Zip = x.Zip }).Distinct().ToList(); // So we pass the route legs when we call the optimizer, or calculate here? Routing.Routing routing = new Routing.Routing(); ICollection<RouteLeg> routeLegs = routing.GetRouteLegs(stops, drivers, run.CustomerID, Routing.Routing.CostType.Distance); Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Parsing optimization tags - '" + run.OptimizationTags + "'."); IEnumerable<OptimizationTag> optimizationTags = OptimizationTagParser.Parse(run.OptimizationTags); ICollection<RouteOrderMultiplier> legMultipliers = routing.GetRouteMultipliers(orders, drivers, optimizationTags); int demand = run.MaxCapacity > 0 ? 1 : 0; _evoStrat = new EvoStrat( run, drivers, orders, routeLegs, legMultipliers, run.CostOptimization, Convert.ToDouble(run.DistanceCostRatio), Convert.ToDouble(run.AvgLegLength), Convert.ToDouble(run.MaxLegLength), Convert.ToDouble(run.AvgLegPenalty), Convert.ToDouble(run.MaxLegPenalty), demand, run.MaxCapacity); _evoStrat.StatusUpdate += new EventHandler(Routing_StatusUpdate); _evoStrat.StartOptimization(); */ } else { Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": No job to process."); Thread.Sleep(_sleepDuration); } } // loop until it gets a job } private void Routing_StatusUpdate(object sender, EventArgs e) { EvoStrat.StatusUpdateEventArgs evt = (EvoStrat.StatusUpdateEventArgs)e; // Note: Both methods below work, we just need to determine which we want to use // Update: looks like the EF version isn't as stable, since it's holding on to contexts and such, use SP version. try { // Entity Framework version //_routingUnitOfWork.OptimizationRunRepository.Update(evt.Run); // _routingUnitOfWork.Save(); // Stored ProcVersion UpdateVrpRun(evt.Run.ID, evt.Run.Generations, evt.Run.BestQuality, evt.Run.BestSolution, evt.Run.CurrentResults, evt.Message); switch (evt.State) { case EvoStrat.StrategyState.Completed: _ready = true; Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + " completed."); break; case EvoStrat.StrategyState.Paused: Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + " paused."); break; case EvoStrat.StrategyState.Running: Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + ": " + evt.Message); break; case EvoStrat.StrategyState.Stopped: _ready = true; Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", evt.UpdateTime) + "] Thread " + _threadID + ": Optimization job " + evt.Run.ID + " completed."); StartOptimization(); break; } } catch (Exception exc) { var ignore = true; } //TODO: Add switch() statement to handle all StrategyState states } // Thread-safe method to get the next optimization job to run private OptimizationRun GetNextOptimizationJob() { OptimizationRun run = null; SqlConnection conn = new SqlConnection("Data Source=CoordCare.com;Initial Catalog=Optimization;Integrated Security=False;User ID=sa;Password=<PASSWORD>"); SqlCommand cmd; SqlDataAdapter sda; DataSet tables = new DataSet(); conn.Open(); // get the next cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "GetNextOptimizationRun"; tables = new DataSet(); sda = new SqlDataAdapter(cmd); sda.Fill(tables); if (tables.Tables[0].Rows.Count == 0) { conn.Close(); return null; } else { foreach (DataRow r in tables.Tables[0].Rows) { try { run = new OptimizationRun(); run.ID = Convert.ToInt32(r["ID"].ToString()); run.CustomerID = Convert.ToInt32(r["CustomerID"].ToString()); run.GenerationsToRun = Convert.ToInt32(r["GenerationsToRun"].ToString()); run.ServiceDate = Convert.ToDateTime(r["ServiceDate"].ToString()); run.Drivers = r["Drivers"].ToString(); run.Orders = r["Orders"].ToString(); run.Algorithm = r["Algorithm"].ToString(); run.Demo = r["Demo"] == null ? false : Convert.ToInt32(r["Demo"]) == 1; run.OptimizationTags = r["Tags"].ToString(); run.CostOptimization = Convert.ToBoolean(r["CostOptimization"].ToString()); run.DistanceCostRatio = Convert.ToDecimal(r["DistanceCostRatio"].ToString()); run.AvgLegLength = Convert.ToInt32(r["AvgLegLength"].ToString()); run.MaxLegLength = Convert.ToInt32(r["MaxLegLength"].ToString()); run.AvgLegPenalty = Convert.ToDecimal(r["AvgLegPenalty"].ToString()); run.MaxLegPenalty = Convert.ToDecimal(r["MaxLegPenalty"].ToString()); run.MaxCapacity = Convert.ToInt32(r["MaxCapacity"].ToString()); } catch (Exception exc) { Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Error -- " + exc.ToString()); } } conn.Close(); } return run; } // Thread-save method to update an optimization job private void UpdateVrpRun(int runId, int generations, string bestQuality, string bestSolution, string currentResults, string message) { SqlCommand cmd; DataSet tables = new DataSet(); try { SqlConnection conn = new SqlConnection("Data Source=CoordCare.com;Initial Catalog=Optimization;Integrated Security=False;User ID=sa;Password=<PASSWORD>"); conn.Open(); cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "UpdateOptimizationRun"; cmd.Parameters.AddWithValue("@ID", runId); cmd.Parameters.AddWithValue("@BestQuality", bestQuality == null ? "" : bestQuality); cmd.Parameters.AddWithValue("@Generations", generations); cmd.Parameters.AddWithValue("@BestSolution", bestSolution == null ? "" : bestSolution); cmd.Parameters.AddWithValue("@CurrentResults", currentResults == null ? "" : currentResults); cmd.Parameters.AddWithValue("@Status", message); var killRun = cmd.ExecuteScalar(); if (Convert.ToInt32(killRun) == 1) { _evoStrat.StopJob(); } } catch (Exception exc) { var error = exc.ToString(); } } } } <file_sep>/Solver/bin/Release/shutdown.sh #! /bin/bash # Get the instance name INSTANCE_ID=$(curl http://metadata/computeMetadata/v1beta1/instance/attributes/serverId) # Now shut down the server gcutil --project="smart-amplifier-286" deleteinstance $INSTANCE_ID --force <file_sep>/Solver/Routing/Routing.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using ServiceStack.ServiceClient.Web; using System.Data; using Npgsql; namespace Solver { public class Routing { private const string BING_API_KEY = "<KEY>"; // Signals the routing engine what trip "cost" factor to optimize on. Examples are: distance, time, environmental, maintenance, etc. public enum CostType { Distance, Time // not yet used } // Get distance for every possible combination of driver/stop public ICollection<RouteLeg> GetRouteLegs(ICollection<Entity> Entities, List<RouteLeg> RouteLegs, int CustomerID, CostType CostType) { BingServices bing = new BingServices(BING_API_KEY); // find any gaps in calculations, marked with -1 distance calc if (RouteLegs.Where (x => x.DrivingDistance == -1).Count () > 0) { // fill in the gaps foreach (RouteLeg calc in RouteLegs.Where(x => x.DrivingDistance == -1)) { // check if the from and to resources are the same resource // also, distance = 0 if they are the same ID, -1 if missing the record // don't need to calculate the distances between the drivers if (!(calc.FromID == calc.ToID) && !(calc.FromTypeID == 2) && !(calc.ToTypeID == 2)) { Entity fromEntity = Entities.Where (x => x.id == calc.FromID).FirstOrDefault (); Entity toEntity = Entities.Where (x => x.id == calc.ToID).FirstOrDefault (); // get distance and time double[] bingResult = bing.GetDrivingDistanceAndTimeBetween2Points ( Convert.ToDouble (fromEntity.geoLat), Convert.ToDouble (fromEntity.geoLon), Convert.ToDouble (toEntity.geoLat), Convert.ToDouble (toEntity.geoLon)); InsertRouteLeg (calc.FromID, calc.ToID, Convert.ToDecimal (bingResult [0]), Convert.ToDecimal (bingResult [1])); // update result list calc.DrivingDistance = Convert.ToDecimal (bingResult [0]); calc.DrivingTime = Convert.ToDecimal (bingResult [1]); } } } List<RouteLeg> legs = new List<RouteLeg>(); foreach (RouteLeg c in RouteLegs) { legs.Add(new RouteLeg{ FromID = c.FromID, FromTypeID = c.FromTypeID, ToID = c.ToID, ToTypeID = c.ToTypeID, DrivingDistance = c.DrivingDistance, DrivingTime = c.DrivingTime }); } return legs; } public void InsertRouteLeg(Int64 FromId, Int64 ToId, Decimal Distance, Decimal Duration) { NpgsqlConnection conn = new NpgsqlConnection("Server=hci.cvwcpfnur8ep.us-east-1.rds.amazonaws.com;Port=5432;User Id=hci_user;Password=<PASSWORD>;Database=route;"); conn.Open(); try { NpgsqlCommand command = new NpgsqlCommand( "INSERT INTO entity_leg(from_id, to_id, distance, duration) " + "VALUES(" + FromId + ", " + ToId + ", " + Distance + ", " + Duration + ")", conn); command.CommandType = CommandType.Text; command.ExecuteScalar(); } finally { conn.Close (); } } public ICollection<DriverTaskMultiplier> GetRoutePenalties(ICollection<Driver> Drivers, ICollection<Task> Tasks) { List<DriverTaskMultiplier> result = new List<DriverTaskMultiplier>(); // Set route order multipliers (drivers and stops) foreach (Task task in Tasks) { // Create multiplier record for every driver for this order foreach(Driver driver in Drivers) { result.Add(new DriverTaskMultiplier(){ TaskName = task.name, DriverName = driver.name, AdjustmentMultiplier = CalculateDriverTaskMultiplier(driver, task) }); } } return result; } private double CalculateDriverMultiplier(Driver Driver, IEnumerable<OptimizationTag> Multipliers) { double result = 1.0; // TODO: This is for "global" preferences applied to all visits for the driver, ie: paytype, iniation costs, etc // string[] driverTags = Driver.Tags.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); // foreach (string tag in driverTags) // { // OptimizationTag optimizationTag = (from m in Multipliers where m.Name == tag && !m.IsExclusive select m).FirstOrDefault(); // if (optimizationTag != null) // { // result += (optimizationTag.Multiplier - 1.0f); // multiplier is additive, not compounding // } // } return result; } private double CalculateDriverTaskMultiplier(Driver Driver, Task Task) { double result = 1.0; // check the tag preferences foreach (Pref pref in Task.stop.prefs) { if (pref.exclude) { // don't want this tag if(Driver.tags.Contains(pref.tag)) { if (pref.required) { // oops, this is a bad one, basically put it out of range return 1000; // we're done, just send back 1000 } else { result += pref.penalty / 100.0 * pref.multiplier; // convert to % of multiplier } } } else { // want this tag if(!Driver.tags.Contains(pref.tag)) { if (pref.required) { // oops, this is a bad one return 1000; // we're done, just send back 1000 } else { result += pref.penalty / 100.0 * pref.multiplier; // convert to % of multiplier } } } } // now check to make sure the driver can perform the service if (!Driver.services.Contains (Task.service.name) && Task.service.name != "Ignore") { // can't perform the service, so penalize return 1000; // we're done, just send back 1000 } // if (Task.stop.name == "124") { // // Console.WriteLine (Driver.name + ": " + result); // } return result; // only soft constraint penalties were found } } }
01c8ead1769b3e2ad9060d31cfe36308d97d9702
[ "C#", "Shell" ]
30
C#
datalyticsllc/hci-solver
5d63e740d12d7036a10b2b57f5b20e1eacdbbb8a
b6e5da773af2bb899a686c9b248734db2df52adf
refs/heads/main
<repo_name>sonusagar98/Covid-Analysis-and-Tic-Tac-Toe<file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/ICheckHeader.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { /// <summary> /// for checking if header present in importedd file is valid or not /// </summary> public interface ICheckHeader { bool IsHeaderValid(string[] Header,string fileHeader); } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/ViewModels/AllocateArea.cs using CovidAnalysisAssignment.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.ViewModels { /// <summary> /// Storing area of all the states and UT in a dictionary /// </summary> public class AllocateArea : IAllocateArea { /// <returns> Dictionary<"State Name", Area> containing area </returns> public Dictionary<string, int> AllocateStateArea() { Dictionary<string, int> area = new Dictionary<string, int>(); string filename = "State Area"; string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(filename, ".csv")); for (int i = 1; i < lines.Length; i++) { string[] data = lines[i].Split(','); area.Add(data[0], Convert.ToInt32(data[1])); } return area; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/ViewModels/CheckHeader.cs using CovidAnalysisAssignment.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace CovidAnalysisAssignment.ViewModels { public class CheckHeader : ICheckHeader { public bool IsHeaderValid(string[] Header, string fileHeader) { string[] data = fileHeader.Split(','); int i = 0; for (i = 0; i < Header.Length; i++) { if (Header[i] != data[i]) { MessageBox.Show("Header is not correct", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); return false; } } return true; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/IAllocateArea.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { /// <summary> /// for allocating area to states /// </summary> public interface IAllocateArea { Dictionary<String, int> AllocateStateArea(); } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/ViewModels/GetMonths.cs using CovidAnalysisAssignment.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.ViewModels { public class GetMonths : IGetMonths { /// <summary> /// for getting months for which data is available /// </summary> /// <param name="data">Complete data</param> /// <returns></returns> public List<string> GetMonthsName(ObservableCollection<VaccinationData> data) { string[] monthDictionary = new string[13]{ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; List<string> Months = new List<string>(); foreach (var d in data) { int monthIndex = d.DateTime.Month; if (!Months.Contains(monthDictionary[monthIndex])) Months.Add(monthDictionary[monthIndex]); } return Months; } } } <file_sep>/TicTac/TicTac/ViewModels/MainWindowViewModel.cs using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.ObjectModel; using System.Windows; using static System.Net.Mime.MediaTypeNames; namespace TicTac.ViewModels { /// <summary> /// Maintains playerturn, winning condition, resetting game /// </summary> public class MainWindowViewModel : BindableBase { bool player1Turn = true; bool GameEnded = false; int turns = 0; #region Game Move Logic private DelegateCommand<string> _playerMove; public DelegateCommand<string> PlayerMove => _playerMove ?? (_playerMove = new DelegateCommand<string>(ExecutePlayerMove, CanExecutePlayerMove)); void ExecutePlayerMove(string parameter) { int index = Convert.ToInt16(parameter); PrintMoveOnButton(index); GameEnded = CheckGameWonByCurrentPlayer(); if (GameEnded == true) { PrintWinningMessage(); return; } player1Turn = !player1Turn; checkMatchDrawn(); } #endregion //Choosing Mark on button depending on which player is playing //On the gameboard player 1 move will be shown as X and for player 2 O private void PrintMoveOnButton(int index) { if (player1Turn) ButtonContent[index] = "X"; else ButtonContent[index] = "O"; } //Draw condition, if turns has become 9 than all the game block are filled //and yet no result so draw private void checkMatchDrawn() { turns += 1; if (turns == 9) { GameEnded = true; WinningMessage = "Game Drawn!!!"; } } //In the textblock printing message will be shown void PrintWinningMessage() { string winner = "1"; if (!player1Turn) { winner = "2"; } WinningMessage = string.Format("Player {0} has won the Match", winner); } private string _winningMessage; public string WinningMessage { get { return _winningMessage; } set { SetProperty(ref _winningMessage, value); PlayerMove.RaiseCanExecuteChanged(); } } //takine three blocks of game and checking if they have same non-empty content private bool AllThreeElementSame(int i, int j, int k) { if ((ButtonContent[i] == ButtonContent[j] && ButtonContent[j] == ButtonContent[k]) && (ButtonContent[i] == "X" || ButtonContent[i] == "O")) { return true; } return false; } //Checking winning game condition private bool CheckGameWonByCurrentPlayer() { //Checking Any row having winning Combination if (AllThreeElementSame(0, 1, 2) || AllThreeElementSame(3, 4, 5) || AllThreeElementSame(6, 7, 8)) return true; //Checking Any column having winning Combination if (AllThreeElementSame(0, 3, 6) || AllThreeElementSame(1, 4, 7) || AllThreeElementSame(2, 5, 8)) return true; //Checking Any DIagonal having winning Combination if (AllThreeElementSame(0, 4, 8) || AllThreeElementSame(2, 4, 6)) return true; return false; } //If there game is ended or block has been played firstly (has X or O) //then that move is not allowed bool CanExecutePlayerMove(string parameter) { int index = Convert.ToInt16(parameter); if (GameEnded == true || ButtonContent[index] != "") return false; return true; } #region Close Application private DelegateCommand<Window> _exitApplication; public DelegateCommand<Window> ExitApplication => _exitApplication ?? (_exitApplication = new DelegateCommand<Window>(ExecuteExitApplication)); void ExecuteExitApplication(Window window) { if (window != null) window.Close(); } #endregion #region Reset Game private DelegateCommand _resetGame; public DelegateCommand ResetGame => _resetGame ?? (_resetGame = new DelegateCommand(ExecuteResetGame)); void ExecuteResetGame() { ButtonContent.Clear(); populateButtonContent(); WinningMessage = ""; turns = 0; GameEnded = false; player1Turn = true; } #endregion // This collection will directly map to 9 blocks (or button) in the game private ObservableCollection<string> _buttonContent; public ObservableCollection<string> ButtonContent { get { return _buttonContent; } set { SetProperty(ref _buttonContent, value); PlayerMove.RaiseCanExecuteChanged(); } } //Since it is beginnning of the game, Intially all button/block will have no content private void populateButtonContent() { for (int i = 0; i < 9; i++) { ButtonContent.Add(""); } } public MainWindowViewModel() { ButtonContent = new ObservableCollection<string>(); populateButtonContent(); } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/App.xaml.cs using CovidAnalysisAssignment.Interfaces; using CovidAnalysisAssignment.Models; using CovidAnalysisAssignment.Services; using CovidAnalysisAssignment.ViewModels; using CovidAnalysisAssignment.Views; using Prism.Ioc; using Prism.Modularity; using System.Windows; namespace CovidAnalysisAssignment { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<MainWindow>(); containerRegistry.RegisterSingleton<IGetStates,GetStates>(); containerRegistry.RegisterSingleton<IAllocateArea, AllocateArea>(); containerRegistry.RegisterSingleton<IGetMonths, GetMonths>(); containerRegistry.RegisterSingleton<ICheckHeader, CheckHeader>(); } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/ViewModels/GetStates.cs using CovidAnalysisAssignment.Interfaces; using CovidAnalysisAssignment.Models; using System.Collections.Generic; using System.Collections.ObjectModel; namespace CovidAnalysisAssignment.Services { public class GetStates : IGetStates { /// <summary> /// for extracting name of states for which data is available /// </summary> /// <param name="data">Raw data</param> /// <returns> List of string containing state name </returns> public List<string> GetStatesName(ObservableCollection<VaccinationData> data) { List<string> states = new List<string>(); foreach (var d in data) { string state = d.State; if (states == null) states.Add(state); else if (!states.Contains(state)) states.Add(state); } return states; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/CovidStatusStateWise.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Model { /// <summary> /// this class is datamodel for taking input data from csv file /// Contains confirmed, cured and death cases for mentioned date and state in a row. /// </summary> public class CovidStatusStateWise : INotifyPropertyChanged { public DateTime Date { get; set; } public string State { get; set; } public int ConfirmedAndCured { get; set; } private int _cured; public int Cured { get { return _cured; } set { _cured = value; OnPropertyChanged("Cured"); OnPropertyChanged("Confirmed"); OnPropertyChanged("Active"); } } public int Deaths { get; set; } private int _confirmed; public int Confirmed { get { return ConfirmedAndCured - Cured; } set { _confirmed = value; OnPropertyChanged("Confirmed"); OnPropertyChanged("Active"); } } private int _active; public int Active { get { return Confirmed - Cured; } set { _active = value; OnPropertyChanged("Active"); } } public CovidStatusStateWise(string date, string state, int cured, int deaths, int confirmed) { this.Date = (DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture)).Date; this.State = state; Cured = cured; this.Deaths = deaths; this.ConfirmedAndCured = confirmed + cured; Confirmed = this.ConfirmedAndCured - cured; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/VaccinationData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { public class VaccinationData { /// <summary> /// for storing the raw data /// </summary> public DateTime DateTime { get; set; } public string State { get; set; } public int TotalVaccinated { get; set; } public int FirstDose { get; set; } public int SecondDose { get; set; } public int Covaxin { get; set; } public int Covishield { get; set; } public int _18 { get; set; } public int _45 { get; set; } public VaccinationData(string dateTime, string state, int totalVaccinated, int firstDose, int secondDose, int covaxin, int covishield, int age_18, int age_45) { DateTime dt; var isValidDate = DateTime.TryParse(dateTime, out dt); if (isValidDate) DateTime = dt.Date; State = state; TotalVaccinated = totalVaccinated; FirstDose = firstDose; SecondDose = secondDose; Covaxin = covaxin; Covishield = covishield; _18 = age_18; _45 = age_45; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/DateValue.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { /// <summary> /// for storing values datewise for different field for displaying in line graph /// </summary> public class DateValue { public DateTime Date { get; set; } public int Value { get; set; } public DateValue(DateTime dt,int v) { Date = dt; Value = v; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/ViewModels/MainWindowViewModel.cs using CovidAnalysisAssignment.Interfaces; using CovidAnalysisAssignment.Model; using CovidAnalysisAssignment.Models; using Microsoft.Win32; using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; using Prism.Commands; using Prism.Mvvm; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Windows; namespace CovidAnalysisAssignment.ViewModels { public class MainWindowViewModel : BindableBase { #region ObservableCollection for ConfirmedCasesPoints, CuredCasesPoints, DeathCurvePoints, ActiveCurvePoints private ObservableCollection<DataPoint> _confirmedCasesPoints; public ObservableCollection<DataPoint> ConfirmedCasesPoints { get { return _confirmedCasesPoints; } set { _confirmedCasesPoints = value; OnPropertyChanged(new PropertyChangedEventArgs("ConfirmedCasesPoints")); } } private ObservableCollection<DataPoint> _curedCasesPoints; public ObservableCollection<DataPoint> CuredCasesPoints { get { return _curedCasesPoints; } set { _curedCasesPoints = value; OnPropertyChanged(new PropertyChangedEventArgs("CuredCasesPoints")); } } private ObservableCollection<DataPoint> _deathCurvePoints; public ObservableCollection<DataPoint> DeathCurvePoints { get { return _deathCurvePoints; } set { _deathCurvePoints = value; OnPropertyChanged(new PropertyChangedEventArgs("DeathCurvePoints")); } } private ObservableCollection<DataPoint> _activeCurvePoints; public ObservableCollection<DataPoint> ActiveCurvePoints { get { return _activeCurvePoints; } set { _activeCurvePoints = value; OnPropertyChanged(new PropertyChangedEventArgs("ActiveCurvePoints")); } } #endregion //All data will be stored in TotalCovidStatus which is got from csv file public ObservableCollection<CovidStatusStateWise> TotalCovidStatus { get; set; } //Data which will be shown, (we can change month and this data will change to show data for that month private ObservableCollection<CovidStatusStateWise> _covidStatusToDisplay; public ObservableCollection<CovidStatusStateWise> CovidStatusToDisplay { get { return _covidStatusToDisplay; } set { SetProperty(ref _covidStatusToDisplay, value); } } private void LoadCovidStatusToDisplay(string selectedMonth) { int MonthNumber = Array.IndexOf(monthDictionary,selectedMonth); CovidStatusToDisplay.Clear(); foreach (CovidStatusStateWise value in TotalCovidStatus) { if (value.Date.Month == MonthNumber) { CovidStatusToDisplay.Add(value); } } } #region Total cases (confirmed, active, recovered, deaths) in the graph for paricular state private int _totalActiveCases; public int totalActiveCases { get { return _totalActiveCases; } set { _totalActiveCases = value; OnPropertyChanged(new PropertyChangedEventArgs("totalActiveCases")); } } private int _totalConfirmedCases; public int totalConfirmedCases { get { return _totalConfirmedCases; } set { _totalConfirmedCases = value; OnPropertyChanged(new PropertyChangedEventArgs("totalConfirmedCases")); } } private int _totalRecoverdCases; public int totalRecoverdCases { get { return _totalRecoverdCases; } set { _totalRecoverdCases = value; OnPropertyChanged(new PropertyChangedEventArgs("totalRecoverdCases")); } } private int _totalDeathCases; public int totalDeathCases { get { return _totalDeathCases; } set { _totalDeathCases = value; OnPropertyChanged(new PropertyChangedEventArgs("totalDeathCases")); } } #endregion private void MakeGraphCordinates(string state) { ConfirmedCasesPoints.Clear(); CuredCasesPoints.Clear(); DeathCurvePoints.Clear(); ActiveCurvePoints.Clear(); foreach (CovidStatusStateWise value in TotalCovidStatus) { if (value.State == state) { ConfirmedCasesPoints.Add(new DataPoint(DateTimeAxis.ToDouble(value.Date), value.Confirmed)); CuredCasesPoints.Add(new DataPoint(DateTimeAxis.ToDouble(value.Date), value.Cured)); DeathCurvePoints.Add(new DataPoint(DateTimeAxis.ToDouble(value.Date), value.Deaths)); ActiveCurvePoints.Add(new DataPoint(DateTimeAxis.ToDouble(value.Date), value.Active)); totalActiveCases = value.Active; totalConfirmedCases = value.Confirmed; totalRecoverdCases = value.Cured; totalDeathCases = value.Deaths; } } } //for creating Model for my BARGRAPH "state vs Total Vaccination" private PlotModel _barModel; public PlotModel BarModel { get { return _barModel; } set { _barModel = value; OnPropertyChanged(new PropertyChangedEventArgs("BarModel")); } } // for storing data monthwise for every state private ObservableCollection<stateVsTotalVaccination> _stateVsVaccination; public ObservableCollection<stateVsTotalVaccination> StateVsVaccination { get { return _stateVsVaccination; } set { _stateVsVaccination = value; OnPropertyChanged(new PropertyChangedEventArgs("StateVsVaccination")); } } // for storing complete data from CSV FILE private ObservableCollection<VaccinationData> _vaccinationData; public ObservableCollection<VaccinationData> VaccinationData { get { return _vaccinationData; } set { _vaccinationData = value; } } //public ObservableCollection<VaccinationData> VaccinationData { get; set; } //for storing data to display in the datagrid for selected month private ObservableCollection<VaccinationData> _vaccinationDataToDisplay; public ObservableCollection<VaccinationData> VaccinationDataToDisplay { get { return _vaccinationDataToDisplay; } set { _vaccinationDataToDisplay = value; OnPropertyChanged(new PropertyChangedEventArgs("VaccinationDataToDisplay")); } } // for creating a dictionary for accessing MONTH NAME using INDEX string[] monthDictionary; // Creating a dictionary to store area for respective states Dictionary<String, int> StatesArea; //for storing name of the MONTHS for which data is present and also to display in COMBOBOX private List<string> _months; public List<string> Months { get { return _months; } set { SetProperty(ref _months, value); } } // for getting the selected MONTH in COMBOBOX private string _selectedMonth; public string SelectedMonth { get { return _selectedMonth; } set { _selectedMonth = value; OnPropertyChanged(new PropertyChangedEventArgs("SelectedMonth")); LoadVaccinatonDataToDisplay(Array.IndexOf(monthDictionary, _selectedMonth),DateTime.Parse("2021/01/01")); // for updating datagrid CreateBarmodel(Array.IndexOf(monthDictionary, _selectedMonth)); // for cahnging State Vs Total Vaccination LoadCovidStatusToDisplay(_selectedMonth); } } // for getting the selected date in datepicker private DateTime _selectedDate; public DateTime SelectedDate { get { return _selectedDate; } set { _selectedDate = value; OnPropertyChanged(new PropertyChangedEventArgs("SelectedDate")); LoadVaccinatonDataToDisplay(1, _selectedDate); // for updaating the datagrid (1 is passed just for sake of it It has no significance) } } // Interface for accessing GetStaes Class , AllocateArea class, GetMonths class, CheckHeader class private IGetStates _statesInterface; private IAllocateArea _allocateArea; private IGetMonths _getMonths; private ICheckHeader _checkHeader; //for storing name of the STATES for which data is present and also to display in COMBOBOX private List<string> _states; public List<string> States { get { return _states; } set { SetProperty(ref _states, value); } } // for getting the selected STATE in COMBOBOX private string _selectedState; public string SelectedState { get { return _selectedState; } set { _selectedState = value; OnPropertyChanged(new PropertyChangedEventArgs("SelectedState")); Load_18_44_DaywiseStat(_selectedState); MakeGraphCordinates(_selectedState); } } // for displaying firstdose % in Progress Bar private int _firstDoseStateWise; public int FirstDoseStateWise { get { return _firstDoseStateWise; } set { _firstDoseStateWise = value; OnPropertyChanged(new PropertyChangedEventArgs("FirstDoseStateWise")); } } // for displaying secondDose % in Progress Bar private int _secondDoseStateWise; public int SecondDoseStateWise { get { return _secondDoseStateWise; } set { _secondDoseStateWise = value; OnPropertyChanged(new PropertyChangedEventArgs("SecondDoseStateWise")); } } // DELEGATE COMMAND for exporting data on clicking button "EXPORT" private DelegateCommand<string> text; public DelegateCommand<string> ExportData => text ?? (text = new DelegateCommand<string>(ExecuteExportData, CanExportData)); /// <summary> /// For Exporting Datagrid data in an excel file. /// </summary> /// <param name="obj"></param> private void ExecuteExportData(string obj) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "XLSX File|*.xlsx"; saveFileDialog1.Title = "Save an excel File"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; app.Visible = true; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"]; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet; worksheet.Name = "Vaccination Data"; int i = 1; worksheet.Cells[i, 1] = "Date"; worksheet.Cells[i, 2] = "State"; worksheet.Cells[i, 3] = "Total Vaccination"; worksheet.Cells[i, 4] = "First Dose"; worksheet.Cells[i, 5] = "Second Dose"; worksheet.Cells[i, 6] = "Covaxin"; worksheet.Cells[i, 7] = "Covishield"; worksheet.Cells[i, 8] = "18-44"; worksheet.Cells[i, 9] = "45+"; i = 2; int j = 1; foreach (var data in VaccinationDataToDisplay) { //Type myType = typeof(VaccinationData); //FieldInfo[] myfield = myType.GetFields(); worksheet.Cells[i, j] = data.DateTime.ToString(); j += 1; worksheet.Cells[i, j] = data.State; j += 1; worksheet.Cells[i, j] = data.TotalVaccinated.ToString(); j += 1; worksheet.Cells[i, j] = data.FirstDose.ToString(); j += 1; worksheet.Cells[i, j] = data.SecondDose.ToString(); j += 1; worksheet.Cells[i, j] = data.Covaxin.ToString(); j += 1; worksheet.Cells[i, j] = data.Covishield.ToString(); j += 1; worksheet.Cells[i, j] = data._18.ToString(); j += 1; worksheet.Cells[i, j] = data._45.ToString(); i += 1; j = 1; } workbook.SaveAs(saveFileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); app.Quit(); } } /// <summary> /// Determines whether the command can execute in its current state. /// </summary> /// <param name="arg"></param> /// <returns></returns> private bool CanExportData(string arg) { return true; } private DelegateCommand<string> t; public DelegateCommand<string> ImportData => t ?? (t = new DelegateCommand<string>(ExecuteImportData, CanImportData)); private void ExecuteImportData(string obj) { String[] Header = new string[] {"Date","State","Total Vaccination","First Dose","Second Dose","Covaxin", "Covishield","18-44","45+"}; OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog(); openFileDlg.Filter = "csv files (*.csv)|*.csv"; bool? result = openFileDlg.ShowDialog(); if (result == true) { string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(openFileDlg.FileName, ".csv")); if (_checkHeader.IsHeaderValid(Header, lines[0])) { VaccinationData.Clear(); for (int j = 1; j < lines.Length; j++) { string[] data = lines[j].Split(','); for (int k = 0; k < data.Length; k++) { if (data[k] == "") { data[k] = "0"; } } if (Convert.ToInt32(data[2]) > 0) { VaccinationData vaccination = new VaccinationData(data[0], data[1], Convert.ToInt32(data[2]), Convert.ToInt32(data[3]), Convert.ToInt32(data[4]), Convert.ToInt32(data[5]), Convert.ToInt32(data[6]), Convert.ToInt32(data[7]), Convert.ToInt32(data[8])); VaccinationData.Add(vaccination); } } LoadVaccinatonDataToDisplay(DateTime.Today.Month, _selectedDate); Months.Clear(); Months = _getMonths.GetMonthsName(VaccinationData); States.Clear(); States = _statesInterface.GetStatesName(VaccinationData); LoadStateVsTotalVaccination(); CreateBarmodel(DateTime.Today.Month); SelectedState = States[0]; } } } private bool CanImportData(string arg) { return true; } private DelegateCommand<string> _importTab1; public DelegateCommand<string> ImportDataTab1 => _importTab1 ?? (_importTab1 = new DelegateCommand<string>(ExecuteImportDataTab1, CanImportDataTab1)); private void ExecuteImportDataTab1(string obj) { String[] Header = new string[] {"Date","State","Cured","Deaths","Confirmed"}; OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog(); openFileDlg.Filter = "csv files (*.csv)|*.csv"; bool? result = openFileDlg.ShowDialog(); if (result == true) { string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(openFileDlg.FileName, ".csv")); if (_checkHeader.IsHeaderValid(Header, lines[0])) { TotalCovidStatus.Clear(); for (int j = 1; j < lines.Length; j++) { string[] currentData = lines[j].Split(','); try { CovidStatusStateWise covidStatusStateWise = new CovidStatusStateWise(currentData[0], currentData[1], Convert.ToInt32(currentData[2]), Convert.ToInt32(currentData[3]), Convert.ToInt32(currentData[4])); TotalCovidStatus.Add(covidStatusStateWise); } catch { } } LoadCovidStatusToDisplay("June"); Months.Clear(); Months = _getMonths.GetMonthsName(VaccinationData); States.Clear(); States = _statesInterface.GetStatesName(VaccinationData); SelectedState = States[0]; MakeGraphCordinates(SelectedState); } } } private bool CanImportDataTab1(string arg) { return true; } #region ObservableCollection for DatewiseStat_18, Covaxin_45, Covishield_45, FirstDose, Second Dose to display in line graphs //for storing DATEWISE STAT for 18-44 age group to display in line graph private ObservableCollection<DateValue> _datewiseStat_18; public ObservableCollection<DateValue> DatewiseStat_18 { get { return _datewiseStat_18; } set { _datewiseStat_18 = value; OnPropertyChanged(new PropertyChangedEventArgs("DatewiseStat_18")); } } //foe storing DATEWISE STAT of Covaxin to display in line graph private ObservableCollection<DateValue> _covaxinType_45; public ObservableCollection<DateValue> Covaxin_45 { get { return _covaxinType_45; } set { _covaxinType_45 = value; OnPropertyChanged(new PropertyChangedEventArgs("Covaxin_45")); } } //foe storing DATEWISE STAT of Covishield to display in line graph private ObservableCollection<DateValue> _covishieldType_45; public ObservableCollection<DateValue> Covishield_45 { get { return _covishieldType_45; } set { _covishieldType_45 = value; OnPropertyChanged(new PropertyChangedEventArgs("Covishield_45")); } } //foe storing DATEWISE STAT of first Dose to display in line graph private ObservableCollection<DateValue> _firstDose; public ObservableCollection<DateValue> FirstDose { get { return _firstDose; } set { _firstDose = value; OnPropertyChanged(new PropertyChangedEventArgs("FirstDose")); } } //foe storing DATEWISE STAT of Second Dose to display in line graph private ObservableCollection<DateValue> _secondDose; public ObservableCollection<DateValue> SecondDose { get { return _secondDose; } set { _secondDose = value; OnPropertyChanged(new PropertyChangedEventArgs("SecondDose")); } } #endregion public MainWindowViewModel(IGetStates st,IAllocateArea area, IGetMonths getMonths,ICheckHeader headerCheck) { monthDictionary = new string[13]{ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; _statesInterface = st; _allocateArea = area; _getMonths = getMonths; _checkHeader = headerCheck; _selectedMonth = monthDictionary[DateTime.Today.Month]; _selectedDate = DateTime.Parse("2021/01/01"); VaccinationData = new ObservableCollection<VaccinationData>(); DatewiseStat_18 = new ObservableCollection<DateValue>(); Covaxin_45 = new ObservableCollection<DateValue>(); Covishield_45 = new ObservableCollection<DateValue>(); FirstDose = new ObservableCollection<DateValue>(); SecondDose = new ObservableCollection<DateValue>(); VaccinationDataToDisplay = new ObservableCollection<VaccinationData>(); StateVsVaccination = new ObservableCollection<stateVsTotalVaccination>(); // TAB1 TotalCovidStatus = new ObservableCollection<CovidStatusStateWise>(); CovidStatusToDisplay = new ObservableCollection<CovidStatusStateWise>(); ConfirmedCasesPoints = new ObservableCollection<DataPoint>(); CuredCasesPoints = new ObservableCollection<DataPoint>(); DeathCurvePoints = new ObservableCollection<DataPoint>(); ActiveCurvePoints = new ObservableCollection<DataPoint>(); // LoadVaccinatonData(); LoadVaccinatonDataToDisplay(DateTime.Today.Month,_selectedDate); Months = new List<string>(); Months = _getMonths.GetMonthsName(VaccinationData); States = new List<string>(); States = _statesInterface.GetStatesName(VaccinationData); _selectedState = States[0]; StatesArea = new Dictionary<string, int>(); StatesArea = _allocateArea.AllocateStateArea(); BarModel = new PlotModel(); //TAB1 LoadTotalCovidStatus(); LoadCovidStatusToDisplay(_selectedMonth); MakeGraphCordinates(SelectedState); // LoadStateVsTotalVaccination(); CreateBarmodel(DateTime.Today.Month); Load_18_44_DaywiseStat(_selectedState); } //for reading the csv file and storing data in VaccinationData private DelegateCommand<string> text2; public DelegateCommand<string> ExportDataTab1 => text2 ?? (text2 = new DelegateCommand<string>(ExecuteExportDataTab1, CanExportDataTab1)); //Logic for exporting data private void ExecuteExportDataTab1(string obj) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "XLSX File|*.xlsx"; saveFileDialog1.Title = "Save an excel File"; saveFileDialog1.ShowDialog(); MessageBox.Show(saveFileDialog1.FileName); if (saveFileDialog1.FileName != "") { Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; app.Visible = true; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"]; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet; worksheet.Name = "Exported from gridview"; int i = 1; worksheet.Cells[i, 1] = "Date"; worksheet.Cells[i, 2] = "State"; worksheet.Cells[i, 3] = "Cured"; worksheet.Cells[i, 4] = "Deaths"; worksheet.Cells[i, 5] = "Confirmed"; i = 2; int j = 1; foreach (var data in CovidStatusToDisplay) { try { worksheet.Cells[i, j] = data.Date.ToString(); j += 1; worksheet.Cells[i, j] = data.State; j += 1; worksheet.Cells[i, j] = data.Cured.ToString(); j += 1; worksheet.Cells[i, j] = data.Deaths.ToString(); j += 1; worksheet.Cells[i, j] = data.Confirmed.ToString(); } catch { } i += 1; j = 1; } workbook.SaveAs(saveFileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); app.Quit(); } } private bool CanExportDataTab1(string arg) { return true; } public void LoadTotalCovidStatus() { string filename = "StateWiseCovidData"; string[] rows = File.ReadAllLines(System.IO.Path.ChangeExtension(filename, ".csv")); foreach (var row in rows) { string[] currentData = row.Split(','); try { CovidStatusStateWise covidStatusStateWise = new CovidStatusStateWise(currentData[0], currentData[1], Convert.ToInt32(currentData[2]), Convert.ToInt32(currentData[3]), Convert.ToInt32(currentData[4])); TotalCovidStatus.Add(covidStatusStateWise); } catch { } } } //Tab 1 completed /// <summary> /// for extracting data from excel file on app startup and storing it in VaccinationData /// </summary> public void LoadVaccinatonData() { string filename = ConfigurationSettings.AppSettings["csvFile"]; string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(filename, ".csv")); for (int i=1;i<lines.Length;i++) { string[] data = lines[i].Split(','); for (int j = 0; j < data.Length; j++) { if (data[j] == "") { data[j] = "0"; } } if (Convert.ToInt32(data[2]) > 0) { VaccinationData vaccination = new VaccinationData(data[0], data[1], Convert.ToInt32(data[2]), Convert.ToInt32(data[3]), Convert.ToInt32(data[4]), Convert.ToInt32(data[5]), Convert.ToInt32(data[6]), Convert.ToInt32(data[7]), Convert.ToInt32(data[8])); VaccinationData.Add(vaccination); } } } //for extracting data to display for selected month public void LoadVaccinatonDataToDisplay(int month, DateTime selectedDate) { VaccinationDataToDisplay.Clear(); if (selectedDate == DateTime.Parse("2021/01/01")) { foreach (var data in VaccinationData) { if (data.DateTime.Month == month) { VaccinationDataToDisplay.Add(data); } } } else { foreach (var data in VaccinationData) { if (data.DateTime == selectedDate) { VaccinationDataToDisplay.Add(data); } } } } /// <summary> /// for storing stats monthwise for every state /// </summary> private void LoadStateVsTotalVaccination() { StateVsVaccination.Clear(); for(int i=0;i< States.Count(); i++) { stateVsTotalVaccination curretData = new stateVsTotalVaccination(States[i]); for (int j=1;j<=Months.Count;j++) { DateTime lastDate = new DateTime(2021, j, 1).AddMonths(1).AddDays(-1); if (j == 6) lastDate = DateTime.Parse("2021/06/07"); VaccinationData listItem = VaccinationData.Single(a => a.DateTime == lastDate && a.State==States[i]); curretData.TotalVaccination[j] = listItem.TotalVaccinated; curretData.Age_18_44_Vaccination[j] = listItem._18; curretData.Age_45_Vaccination[j] = listItem._45; curretData.CovaxinDose[j] = listItem.Covaxin; curretData.CovishieldDose[j] = listItem.Covishield; if(j==1) StateVsVaccination.Add(curretData); } } } /// <summary> /// Bar Model for displaying the BAR GRAPH of state vs Total Vaccination /// </summary> /// <param name="month">Selected Month for which bar graph is displayed</param> private void CreateBarmodel(int month) { BarModel.Series.Clear(); BarModel.Axes.Clear(); BarModel.Title = "State vs Total Vaccination"; List<ColumnItem> totalCovaxinDose = new List<ColumnItem>(); List<ColumnItem> totalCovishieldDose = new List<ColumnItem>(); string[] stateName = new string[StateVsVaccination.Count]; int i = 0; foreach (var f in StateVsVaccination) { totalCovaxinDose.Add(new ColumnItem { Value = f.CovaxinDose[month] }); totalCovishieldDose.Add(new ColumnItem { Value = f.CovishieldDose[month] }); stateName[i] = f.StateName; i += 1; } var covaxinBarSeries = new ColumnSeries { ItemsSource = totalCovaxinDose, StrokeColor = OxyColors.Black, StrokeThickness = 1, FillColor = OxyColors.BlueViolet, Title = "Covaxin Dose" }; var covishieldBarSeries = new ColumnSeries { ItemsSource = totalCovishieldDose, StrokeColor = OxyColors.Black, StrokeThickness = 1, FillColor = OxyColors.Red, Title = "Covishield Dose" }; BarModel.Series.Add(covaxinBarSeries); BarModel.Series.Add(covishieldBarSeries); BarModel.Axes.Add(new CategoryAxis { Position = AxisPosition.Bottom, Angle=60, ItemsSource = stateName }); BarModel.InvalidatePlot(true); } /// <summary> /// for storing daywise stat for selected state /// </summary> /// <param name="selectedState">State for which data is to be displayed in the line graph</param> private void Load_18_44_DaywiseStat(string selectedState) { DatewiseStat_18.Clear(); Covaxin_45.Clear(); Covishield_45.Clear(); FirstDose.Clear(); SecondDose.Clear(); FirstDoseStateWise = 0; SecondDoseStateWise = 0; int c = 0; VaccinationData prevData = null; foreach (var data in VaccinationData) { if (data.State==selectedState) { DateTime dt; var isValidDate = DateTime.TryParse("16/01/2021", out dt); if (data.DateTime==dt.Date) prevData = data; else { DatewiseStat_18.Add(new DateValue(data.DateTime, data._18 - prevData._18)); Covaxin_45.Add(new DateValue(data.DateTime, data.Covaxin - prevData.Covaxin)); Covishield_45.Add(new DateValue(data.DateTime, data.Covishield - prevData.Covishield)); FirstDose.Add(new DateValue(data.DateTime, data.FirstDose - prevData.FirstDose)); SecondDose.Add(new DateValue(data.DateTime, data.SecondDose - prevData.SecondDose)); FirstDoseStateWise = data.FirstDose; SecondDoseStateWise = data.SecondDose; prevData = data; } } } FirstDoseStateWise = FirstDoseStateWise * 100 / (200 * StatesArea[selectedState]); SecondDoseStateWise = SecondDoseStateWise * 100 / (200 * StatesArea[selectedState]); } protected void NotifyPropertyChange(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/IGetStates.cs using CovidAnalysisAssignment.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Interfaces { /// <summary> /// for extracting name of states and UT from data available /// </summary> public interface IGetStates { List<string> GetStatesName(ObservableCollection<VaccinationData> data); } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/stateVsTotalVaccination.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { public class stateVsTotalVaccination { /// <summary> /// for storing Vaccination Details monthwise /// </summary> public int[] TotalVaccination { get; set; } public int[] Age_18_44_Vaccination { get; set; } public int[] Age_45_Vaccination { get; set; } public int[] CovaxinDose { get; set; } public int[] CovishieldDose { get; set; } public string StateName { get; set; } public stateVsTotalVaccination(string state) { TotalVaccination = new int[13]; Age_18_44_Vaccination = new int[13]; Age_45_Vaccination = new int[13]; CovaxinDose = new int[13]; CovishieldDose = new int[13]; StateName = state; } } } <file_sep>/CovidAnalysisAssignment/CovidAnalysisAssignment/Models/IGetMonths.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CovidAnalysisAssignment.Models { /// <summary> /// for extracting months from the data available /// </summary> public interface IGetMonths { List<string> GetMonthsName(ObservableCollection<VaccinationData> data); } }
b87af8ff1706e5ce2ce456768360ffb01814e640
[ "C#" ]
15
C#
sonusagar98/Covid-Analysis-and-Tic-Tac-Toe
988a88be7e395172be011d55ee9701c24aa36fa3
13e2cca4fdd24c4d3236e869b629de1b4f3929c2
refs/heads/master
<file_sep>// creates a new game before each spec beforeEach(function () { testGame = Object.create(Game); testGame.init("Bob", "John"); }); // if player1 selects position 1, there should be an 'X' in position 1 // if player1 selects position 11, board should not change // if player 2 selects a position that is occupied, board should not change describe("play for Game", function() { it("changes the board position to players character", function() { let board = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]; let board1 = [["X", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]; expect(testGame.board).toEqual(board); testGame.play('1'); expect(testGame.board).toEqual(board1); }); it("only allows you to choose a position between 0 and 10", function() { let board2 = [["X", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]; expect(testGame.board).toEqual(board2); testGame.play('11'); expect(testGame.board).toEqual(board2); }); }); // var library; // var hungerGames; // // // creates a new game before each spec // beforeEach(function () { // library = Library(); // hungerGames = Book('Hunger Games', '<NAME>'); // // library.addBook(hungerGames); // }); // // // sets books back to 'checked in' after each spec // afterEach(function() { // hungerGames.set('checkedOut', false); // }); // // describe("checkOutBook for Library", function () { // it("changes a book's checkedOut attribute from false to true", function () { // expect(hungerGames.get('checkedOut')).toEqual(false); // // library.checkOutBook(hungerGames); // // expect(hungerGames.get('checkedOut')).toEqual(true); // }); // // it("only allows you to check out books that exist in the library", function () { // var toot = Book('Toot', '<NAME>'); // // expect(toot.get('checkedOut')).toEqual(false); // // library.checkOutBook(toot); // // expect(toot.get('checkedOut')).toEqual(false); // }); // }); // // describe("returnBook for Library", function () { // it("changes a book's checkedOut attribute from true to false", function () { // library.checkOutBook(hungerGames); // // expect(hungerGames.get('checkedOut')).toEqual(true); // // library.returnBook(hungerGames); // // expect(hungerGames.get('checkedOut')).toEqual(false); // }); // // it("only allows you to return books that exist in the library", function () { // var toot = Book('Toot', '<NAME>'); // // toot.set('checkedOut', true); // // expect(toot.get('checkedOut')).toEqual(true); // // library.returnBook(toot); // // expect(toot.get('checkedOut')).toEqual(true); // }); // }); // // describe("addBook for Library", function () { // it("should add a new book to the library and enable it to be checked out", function () { // var harryPotter = Book('<NAME>', '<NAME>'); // // expect(harryPotter.get('checkedOut')).toEqual(false); // // library.checkOutBook(harryPotter); // // expect(harryPotter.get('checkedOut')).toEqual(false); // // library.addBook(harryPotter); // // library.checkOutBook(harryPotter); // // expect(harryPotter.get('checkedOut')).toEqual(true); // }); // }); // // describe("getAttribute for Book", function () { // it("should only return an attribute if the attribute exists", function () { // expect(hungerGames.get('pages')).toEqual(undefined); // }); // // it("should return an attribute that does exist", function () { // expect(hungerGames.get('title')).toEqual('Hunger Games'); // }); // }); // // describe("setAttribute for Book", function () { // it("should not set an attribute that does not previously exist", function () { // hungerGames.set('pages', 110); // // expect(hungerGames.get('pages')).toEqual(undefined); // }); // // it("should set an attribute that previously exists", function () { // hungerGames.set('title', 'The Freaking Awesome Games!'); // // expect(hungerGames.get('title')).toEqual('The Freaking Awesome Games!'); // }); // });
6ca752d703b94c71cfe61cea99e69bff1de3f3bb
[ "JavaScript" ]
1
JavaScript
roykim79/tic-tac-toe
c21483e7047a5f76243f7188abed09d15a2d6189
6d2abf762591a9f18a8b6cfba409460a04133a17
refs/heads/master
<repo_name>Almighty-Satan/gradle-macro-preprocessor-plugin<file_sep>/samples/basic/build.gradle apply plugin: 'application' apply plugin: 'com.github.hexomod.macro.preprocessor' buildscript { repositories { mavenLocal() maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath group: 'com.github.hexomod', name: 'MacroPreprocessor', version: '0.4' } } repositories { jcenter() mavenLocal() mavenCentral() } dependencies { testCompile 'junit:junit:4.12' } application { mainClassName = 'com.github.hexomod.macro.basic.Main' } macroPreprocessorSettings { //verbose true //sources = "src/main/java" //source = project.file("src/api/java").toString() //source = [ "src/api/java", "src/main/java" ] //source = [ "src/api/java", file("src/main/java").toString() ] //resources = "src/main/resources" //resource = project.file("src/api/resources").toString() //resource = [ "src/api/resources", "src/main/resources" ] //resource = [ "src/api/resources", file("src/main/resources").toString() ] //target = "build/preprocessor/macro" //target = file(buildDir.toString() + "/preprocessor/macro") vars = [VAR_STRING: "value_string", VAR_BOOL: true, VAR_INT: 1, VAR_DOUBLE: 2.0, PROJECT: "Basic", DEBUG: true] }<file_sep>/src/main/java/com/github/hexomod/macro/PreprocessorTask.java /* * This file is part of MacroPreprocessor, licensed under the MIT License (MIT). * * Copyright (c) 2019 Hexosse <https://github.com/hexomod-tools/gradle.macro.preprocessor.plugin> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.hexomod.macro; import org.apache.commons.io.FileUtils; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskAction; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collections; import java.util.Set; @SuppressWarnings({"WeakerAccess","unused"}) public class PreprocessorTask extends DefaultTask { // The task ID public static final String TASK_ID = "macroPreprocessor"; // Extension private final PreprocessorExtension extension; @Inject public PreprocessorTask() { this.extension = getProject().getExtensions().findByType(PreprocessorExtension.class); } @TaskAction public void process() throws IOException { // Instantiate the preprocessor Preprocessor preprocessor = new Preprocessor(this.extension.getVars(), this.extension.isRemove()); log("Starting macro preprocessor"); // Data Project project = this.extension.getProject(); Set<String> sources = this.extension.getSources(); Set<String> resources = this.extension.getResources(); File target = this.extension.getTarget(); File srcTarget = new File(target, "java"); File resTarget = new File(target, "resources"); log(" Checking sources folders..."); // Default sources if(sources.isEmpty()) { project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().all(sourceSet -> { Set<File> srcDirs = sourceSet.getJava().getSrcDirs(); for(File srcDir: srcDirs) { sources.add(srcDir.getAbsolutePath()); } }); } // Check for(String source : sources) { if(!Files.isDirectory((new File(source)).toPath())) { log(" " + source + " is not a valid folder!"); } } log(" Checking resources folders..."); // Default resources if(resources.isEmpty()) { project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().all(sourceSet -> { Set<File> resDirs = sourceSet.getResources().getSrcDirs(); for(File resDir: resDirs) { resources.add(resDir.getAbsolutePath()); } }); } // Check for(String resource : resources) { if(!Files.isDirectory((new File(resource)).toPath())) { log(" " + resource + " is not a valid folder!"); } } log(" Creating target folder..."); // Create target directory FileUtils.forceMkdirParent(srcTarget); FileUtils.forceMkdirParent(resTarget); log(" Processing files..."); // Loop throw all source files for (String source : sources) { File srcDir = new File(source); for (File file : project.fileTree(srcDir)) { log(" Processing " + file.toString()); File out = srcTarget.toPath().resolve(srcDir.toPath().relativize(file.toPath())).toFile(); preprocessor.process(file, out); } } // Loop throw all resource files for (String resource : resources) { File resDir = new File(resource); for (File file : project.fileTree(resDir)) { log(" Processing " + file.toString()); File out = resTarget.toPath().resolve(resDir.toPath().relativize(file.toPath())).toFile(); preprocessor.process(file, out); } } log(" Updating main sourset..."); SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); main.getJava().setSrcDirs(Collections.singleton(srcTarget)); main.getResources().setSrcDirs(Collections.singleton(resTarget)); } // Print out a string if verbose is enable private void log(String msg) { if(this.extension != null && this.extension.isVerbose()) { System.out.println(msg); } } } <file_sep>/samples/multi/projects/project2/settings.gradle rootProject.name = 'Project2Sample' <file_sep>/samples/multi/projects/project1/settings.gradle rootProject.name = 'Project1Sample' <file_sep>/README.md # gradle-macro-preprocessor-plugin [![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square)](https://opensource.org/licenses/MIT) A simple macro preprocessor for java ## Supported macros `#ifdef` `#if` `#elseif` `#else` `#endif` # How to use The preprocessor is published in Gradle central ```gradle plugin { id: 'com.github.hexomod.macro.preprocessor' } ``` # Usage ```gradle macroPreprocessorSettings { verbose true // Default sourcset is automaticaly used //source = [ "src/api/java", "src/main/java" ] //resources = [ "src/api/resources", "src/main/resources" ] // Default output //target = "build/preprocessor/macro" vars = [ VAR_STRING: "value_string", VAR_BOOL: true, VAR_INT: 1, VAR_DOUBLE: 1.0, DEBUG: true] } ``` # Internal test samples - [basic](samples/basic) - [multi-project1](samples/multi/projects/project1) - [multi-project2](samples/multi/projects/project2) # Example of Java sources with directives In Java the only allowed way to inject directives and to not break work of tools and conpilers - is to use commented space, so that the preprocessor uses it. ```Java //#ifdef DEBUG public static boolean DEBUG = true; //#else ///public static boolean DEBUG = false; //#endif ```
db94344ea2c7419ba288010b52298f19d30506e7
[ "Markdown", "Java", "Gradle" ]
5
Gradle
Almighty-Satan/gradle-macro-preprocessor-plugin
9c3961bb83dc481909e650eae2ddd552f8c40002
f34a407281d9ba5a643d50070876b873277ea960
refs/heads/master
<file_sep>x = 1 while x <= 100: mod3 = x % 3 == 0 mod5 = x % 5 == 0 if (mod3 and mod5): print "FizzBuzz" elif (mod5): print "Buzz" elif (mod3): print "Fizz" else: print x x += 1 <file_sep>def sortcat(n, *args): maxLen = 0 for i in range(len(args)): if len(args[i]) > maxLen: maxLen = len(args[i]) concatStr = "" if (n == -1): while (maxLen > 0): for i in range(len(args)): if len(args[i]) == maxLen: concatStr += args[i] maxLen -= 1 else: passes = 0 while (passes < n): for i in range(len(args)): if len(args[i]) == maxLen: concatStr += args[i] maxLen -= 1 passes += 1 print concatStr sortcat(1, 'abc', 'bc') sortcat(2, 'bc', 'c', 'abc') <file_sep>import json from PIL import Image class Article: def __init__(self, headline, content, author, related_image=None): self.headline = headline self.content = content self.author = author self.related_image = related_image def show(self): print self.content if (self.related_image): image = Image.open(self.related_image) image.show() def save(self): f = open(self.headline + "-" + self.content + "-" self.author + "-" self.related_image, 'w') # verbose for very, very rare collisions dict = {'headline': self.headline, 'content': self.content, 'author': self.author, 'related_image': self.related_image} f.write(json.dumps(dict)) f.close() @classmethod def load(cls, filename): try: f = open(filename, 'r') new_dict = json.loads(f.read()) return Article(new_dict['headline'], new_dict['content'], new_dict['author'], new_dict['related_image']) except IOError: print "File does not exist!" ''' Question 2a Properties: - headline - content - creator (author) Methods: - show (print contents) - save (save to text file) Question 2b Methods: - Load article from text file Question 2d Properties: - related_image Methods: - modify save to save info about related picture (if it exists) - modify load to load info about related picture (if it exists) - modify show to also show the related picture (if it exist) ''' class Picture: ''' Question 2c Properties: - image_file (path to original image relative to this file) - creator (photographer) Methods - show (show image) ''' def __init__(self, filename, photographer): self.image_file = filename self.photographer = photographer def show(self): image = Image.open(self.filename) image.show() <file_sep>import datetime import re class Content(object): ''' Required properties: - title - subtitle - creator - publication date Required methods: - show - matches_url (question 1d) ''' def __init__(self, title, subtitle, creator): self.title = title self.subtitle = subtitle self.creator = creator self.publication_date = datetime.date.today() def show(self): print "<Title: {0}\nSubtitle: {1}\nCreator: {2}\nPublication Date: {3}>".format(self.title, self.subtitle, self.creator, self.publication_date.__str__()) def matches_url(self, url): pattern = r'http://thecrimson.com/(\w+)/(\d{4})/(\d{1,2})/(\d{1,2})/(\w+)' return not (re.search(pattern, url) is None) ''' Question 1e ''' @classmethod def from_url(c_lst, url): matched_content = [] for i in range(len(c_lst)): split_title = c_lst[i].title.split() slug = '-'.join(split_title) pattern = r'http://thecrimson.com/(\w+)/{0}/{1}/{2}/{3}/'.format(c_list[i].publication_date.year, c_list[i].publication_date.month, c_list[i].publication_date.day, slug) if (not (re.search(pattern, url) is None)): matched_content.append(c_lst[i]) if (len(matched_content) > 1): print "Error - More than one content object matches the URL!" elif (len(matched_content) == 0): print "No content matched" else: return matched_content[0] class Article(Content): ''' Required properties: - All properties of Content - related_image Required methods: - All methods of Content ''' def __init__(self, title, subtitle, creator, image): super(Content, self).__init__(title, subtitle, creator) self.related_image = image def show(self): print "<Title: {0}\n Subtitle: {1}\nCreator: {2}\nPublication Date: {3}\nRelated Image: {4}>".format(self.title, self.subtitle, self.creator, self.publication_date.__str__(), self.related_image) class Picture(Content): ''' Required properties: - All properties of Content - image_file Required methods: - All methods of Content ''' def __init__(self, title, subtitle, creator, image_file): super(Content, self).__init__(title, subtitle, creator) self.image_file = image_file def show(self): print "<Title: {0}\n Subtitle: {1}\nCreator: {2}\nPublication Date: {3}\nImage File: {4}>".format(self.title, self.subtitle, self.creator, self.publication_date.__str__(), self.image_file) ''' Question 1e ''' def posted_after(c_lst, dt): content_before_dt = [] for content in c_lst: if (content.publication_date < dt): content_before_dt.append(content) return content_before_dt <file_sep>from pprint import pprint # pretty print output formatting from question1 import (common_words, common_words_min, common_words_tuple, common_words_safe) # fill in the rest! from question2 import (Article, Picture) print "==testing question 1==" print "common_words... ", pprint(common_words("words.txt")) print "common_words_min 2... ", pprint(common_words_min("words.txt", 2)) print "common_words_min 5... ", pprint(common_words_min("words.txt", 5)) print "common_words_min 9... ", pprint(common_words_min("words.txt", 9)) print "common_words_tuple w/ min 5... ", pprint(common_words_tuple("words.txt", 5)) print "common_words_safe... ", pprint(common_words_safe("words_fail.txt", 5)) print "==testing question 2==" article = Article("<NAME> joins the Crimson tech comp!", "<NAME> is currently working on assignment 1 of the Crimson tech comp", "<NAME>") article.show() article.save()<file_sep>""" Question 1 objectives - get more comfortable with Python - learn how to handle exceptions - work with the file system """ def common_words(filename): """question 1a Write a function that takes a path to a text file as input. The function should open the file, count the number of occurrences of each word, and return a sorted list of the most common words. """ f = open(filename) words = f.read().split() frequencies = {} for i in range(len(words)): if (words[i] not in frequencies): frequencies[words[i]] = 1 else: frequencies[words[i]] += 1 occurrences = frequencies.values() max = 0 for j in range(len(occurrences)): if (occurrences[j] > max): max = occurrences[j] words_list = [] while (max > 0): for key in frequencies: if (frequencies[key] == max): words_list.append(key) max -= 1 f.close() return words_list pass def common_words_min(filename, min_chars): """question 1b Modify this function to take a second argument that specifies the minimum number of characters long a word can be to be counted. """ f = open(filename) words = f.read().split() frequencies = {} for i in range(len(words)): if (len(words[i]) >= min_chars): if (words[i] not in frequencies): frequencies[words[i]] = 1 else: frequencies[words[i]] += 1 occurrences = frequencies.values() max = 0 for j in range(len(occurrences)): if (occurrences[j] > max): max = occurrences[j] words_list = [] while (max > 0): for key in frequencies: if (frequencies[key] == max): words_list.append(key) max -= 1 f.close() return words_list pass def common_words_tuple(filename, min_chars): """question 1c Modify this function to return a list of tuples rather than just a list of strings. Each tuple should be of the format (word, number of occurrences) Of course, the list of tuples should still be sorted as in part a. """ f = open(filename) words = f.read().split() frequencies = {} for i in range(len(words)): if (len(words[i]) >= min_chars): if (words[i] not in frequencies): frequencies[words[i]] = 1 else: frequencies[words[i]] += 1 occurrences = frequencies.values() max = 0 for j in range(len(occurrences)): if (occurrences[j] > max): max = occurrences[j] words_list = [] while (max > 0): for key in frequencies: if (frequencies[key] == max): words_list.append((key,max)) max -= 1 f.close() return words_list pass def common_words_safe(filename, min_chars): """question 1d Modify your function so that it catches the IOError exception and prints a friendly error message. """ try: f = open(filename) words = f.read().split() frequencies = {} for i in range(len(words)): if (len(words[i]) >= min_chars): if (words[i] not in frequencies): frequencies[words[i]] = 1 else: frequencies[words[i]] += 1 occurrences = frequencies.values() max = 0 for j in range(len(occurrences)): if (occurrences[j] > max): max = occurrences[j] words_list = [] while (max > 0): for key in frequencies: if (frequencies[key] == max): words_list.append((key,max)) max -= 1 return words_list f.close() except IOError: print 'File missing!' finally: print 'All done!' pass<file_sep>import random def simulGame(n): numWins = 0 for i in range(n): Luigi = getDirection() Peach = getDirection() Mario = getDirection() Wario = getDirection() if (Luigi != Peach and Luigi != Mario and Luigi != Wario): numWins += 1 return float(numWins)/n def getDirection(): rand = random.randint(1,10) if (rand <= 2): return "forward" elif (rand <= 4): return "up" elif (rand <= 6): return "down" elif (rand <= 8): return "left" else: return "right" print (simulGame(10)) print (simulGame(100)) print (simulGame(1000)) <file_sep>import sys def replace(str): length = len(str) letterCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for i in range(length): if (ord(str[i]) >= ord('a') and ord(str[i]) <= ord('z')): letterCount[ord(str[i]) - ord('a')] += 1 maxIndex = 0 minIndex = 0 maxOccurrences = 0 minOccurrences = sys.maxint for i in range(26): if letterCount[i] > maxOccurrences: maxOccurrences = letterCount[i] maxIndex = i if letterCount[i] < minOccurrences and letterCount[i] != 0: minOccurrences = letterCount[i] minIndex = i maxChar = chr(maxIndex + ord('a')) minChar = chr(minIndex + ord('a')) s = list(str) for i in range(length): if s[i] == maxChar: s[i] = minChar elif s[i] == minChar: s[i] = maxChar print "".join(s) string = "There were a lot of escopeoples in the elevator on Tuesday." replace(string)
7abc6192aeef56eb6a14ac7bab5de15179bc25b0
[ "Python" ]
8
Python
jsani0102/crimsononline-assignments
81510c902ec116bc5ba6dcb962e14f3415dd2368
8503a1806e0d2f3b6b6bdec78d9760f890999657
refs/heads/master
<repo_name>ayush1999/tourist-database<file_sep>/README.md # Database of Tourist Places in Odisha (3rd Semester Project) ## Dividing the work into 5 parts: --> Collecting data about all tourist places. --> Describing all these places. (A few lines should be enough.) [Abhipsha and Anisha] --> Building the transport module --> Making the boarding/ lodging facilities module. [Abhipsha and Anisha] --> Building the Additional modules for these places (apart from transport and boarding). --> Front End (Optional) <file_sep>/main.cpp #include<iostream> #include<fstream> #include"lodging.h" #include "transport.h" #include "places.h" #include "time_to_visit.h" #include "users.h" using namespace std; int main(){ base = BaseUser() if (base.choice==1){ obj = User() cout<<"Hello User. Which type of place do you want to visit?"<<endl; cout << "1. Beaches" << endl; cout << "2. Dams" << endl; cout << "3. Hills" << endl; cout << "4. Parks" << endl; cout << "5. Temple" << endl; cout << "6. zoo" << endl; int ch; cin>>ch; switch(ch){ case 1:{ // Read the beaches.csv file.(all columns). } case 2: { // Read the dams.csv file.(all columns). } case 3: { // Read the hills.csv file.(all columns). } case 4: { // Read the parks.csv file.(all columns). } case 5: { // Read the temple.csv file.(all columns). } case 6: { // Read the zoo.csv file.(all columns). } } cout<<endl; cout<<"What kind of Information do you want?"<<endl; cin>>ch; cout << "1. Lodging" << endl; cout << "2. Transport" << endl; cout << "3. Time to Visit" << endl; switch(ch){ case 1:{ l= lodging(); l.show(); // } case 2:{ t= transport(); t.show(); } case 3:{ ttv = time(); ttv.show(); } } } else{ obj = managing_staff(); } } <file_sep>/write.h #ifndef WRITE_H_INCLUDED #define WRITE_H_INCLUDED #include <iostream> #include <fstream> #include <string> #include<vector> #include<stdlib.h> void add(int i); void del(int i); class details { public: char *n=new char[100]; char *a=new char[500]; char *tr=new char[100]; char *ti=new char[100]; void get() { cout<<"\n Enter The Name : "; cin>>n; cout<<"\n Enter Address : "; cin>>a; cout<<"\n Enter Travelling and Lodging Details : "; cin>>tr; cout<<"\n Enter The Time The Place is Open : "; cin>>ti; } }; details d; vector<details> z; void edit(int i) { ifstream f; int x=0; if(i==1) f.open("beach.csv"); else if(i==2) f.open("park.csv"); else if(i==3) f.open("zoo.csv"); else if(i==4) f.open("temple.csv"); else if(i==5) f.open("hill.csv"); else if(i==6) f.open("dam.csv"); else { cout<<"invalid input "; exit(0); } while(!f.eof()) { f.getline(d.n,100,','); f.getline(d.a,500,','); f.getline(d.tr,100,','); f.getline(d.ti,100); z.push_back(d); if(d.n[0]!='\0'&&x!=0) cout<<x<<". "<<d.n<<endl; else cout<<d.n<<endl; x++; } cout<<"\n how do you want to edit : 1. add a place "; cout<<"\n 2. delete a place "<<endl; cin>>x; if(x==1) add(i); else if(x==2) del(i); else cout<<"\ninvalid input"; } void add(int i) { string s; ofstream f; if(i==1) f.open("beach.csv",ios::app); else if(i==2) f.open("park.csv",ios::app); else if(i==3) f.open("zoo.csv",ios::app); else if(i==4) f.open("temple.csv",ios::app); else if(i==5) f.open("hill.csv",ios::app); else if(i==6) f.open("dam.csv",ios::app); d.get(); z.push_back(d); s.append(d.n);s.append(",");s.append(d.a);s.append(",\"");s.append(d.tr);s.append("\"");s.append(",");s.append(d.ti); cout<<s; f<<s; } void del(int i) { string s; int x; ifstream f; ofstream w; fstream t; if(i==1) f.open("beach.csv"); else if(i==2) f.open("park.csv"); else if(i==3) f.open("zoo.csv"); else if(i==4) f.open("temple.csv"); else if(i==5) f.open("hill.csv"); else if(i==6) f.open("dam.csv"); cout<<"Enter The serial no of place you want to delete : "; cin>>x; t.open("temp.csv",ios::in|ios::out); while(!f.eof()) { f.getline(d.n,100,','); f.getline(d.a,500,','); f.getline(d.tr,100,','); f.getline(d.ti,100); s.append(d.n);s.append(",");s.append(d.a);s.append(",\"");s.append(d.tr);s.append("\"");s.append(",");s.append(d.ti); t<<s; } if(i==1) w.open("beach.csv"); else if(i==2) w.open("park.csv"); else if(i==3) w.open("zoo.csv"); else if(i==4) w.open("temple.csv"); else if(i==5) w.open("hill.csv"); else if(i==6) w.open("dam.csv"); t.seekg(0,ios::beg); int r=0; while(!t.eof()) { t.getline(d.n,100,','); t.getline(d.a,500,','); t.getline(d.tr,100,','); t.getline(d.ti,100); s.append(d.n);s.append(",");s.append(d.a);s.append(",\"");s.append(d.tr);s.append("\"");s.append(",");s.append(d.ti); if(r++!=x) w<<s; } } #endif // WRITE_H_INCLUDED <file_sep>/places.h #include <iostream> #include <fstream> #include <string> using namespace std; class places{ int choice; public: places(){ cout << "Enter the type of place : 1. Beaches" << endl; cout << " 2. Amusement Parks" << endl; cout << " 3. Zoos and Wildlife Sanctuaries" << endl; cout << " 4. Temples" << endl; cout << " 5. Hill Station" << endl; cout << " 6. Dams and Lakes" << endl; cin >> choice; } void show(){ // using switch case, read corresponding csv.(all columns) } } <file_sep>/lodging.h #include<iostream> #include<fstream> #include<string> using namespace std; class lodging{ int choice; public: lodging(){ cout << "Enter the type of place : 1. Beaches" << endl; cout << " 2. Amusement Parks" << endl; cout << " 3. Zoos and Wildlife Sanctuaries" << endl; cout << " 4. Temples" << endl; cout << " 5. Hill Station" << endl; cout << " 6. Dams and Lakes" << endl; cin >> choice; } void show(){ // Using switch case, open the corresponding csv file. } }; <file_sep>/users.h #include<iostream> #include<fstream> using namespace std; class BaseUser{ public: int choice; BaseUser(){ cout<<"Are you a 1. User"<<endl; cout<<" 2. Managing Staff"; cin>>choice; } void view(){ ofstream in; in.open("name_of_csv.csv"); } int get_type(){ return choice; }; }; class User: public BaseUser{ }; class managing_staff: public BaseUser{ public: void edit(){ int option; cout<<"What Do you want 1. Add"<<endl; cout<<" 2. Edit"; cin>>option; if (option==1){ // Append to the csv file } else{ // Edit the csv file } } }
cb3a174d31ffe434ad978863b61d77c6009665af
[ "Markdown", "C++" ]
6
Markdown
ayush1999/tourist-database
4bde9dd24355fdce152a6be7094323bd4d62bfa9
e8c940ec3acabd2acd01ea2adbff0fa374880dc2
refs/heads/master
<repo_name>MustafaSeyrek/Sorting-Algorithms<file_sep>/IntroSort.java public class IntroSort { static HeapSort heapsort = new HeapSort(); static QuickSort quick = new QuickSort(); public static void sort(int[] arr) { int depth = ((int) Math.log(arr.length)) * 2; sort(arr, depth, 0, arr.length - 1); } private static void sort(int[] arr, int depth, int left, int right) { int length = arr.length; if (length <= 1) { return; } else if (depth == 0) { heapSort(arr, left, right); } else { if (left >= right) return; int pivot = arr[(left + right) / 2]; int index = partition(arr, left, right, pivot); sort(arr, depth - 1, left, index - 1); sort(arr, depth - 1, index, right); } } private static void heapSort(int[] arr, int left, int right) { for (int i = right / 2 - 1; i >= left; i--) heapsort.heapify(arr, right, i); for (int i = right - 1; i >= left; i--) { quick.swap(arr, left, i); heapsort.heapify(arr, i, left); } } private static int partition(int[] arr, int left, int right, int pivot) { while (left <= right) { while (arr[left] < pivot) { left++; } while (arr[right] > pivot) { right--; } if (left <= right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } return left; } }
975b9b8e38581689bbbea26c528de100759ab2c3
[ "Java" ]
1
Java
MustafaSeyrek/Sorting-Algorithms
d385bfa00eea2e3dd2cd81ff9e8fc9a1e36bb4bd
6d3f7421ad5b7f7507b65a39df23350d5a18b8cf
refs/heads/main
<file_sep>// let test = document.querySelector('#content') // console.log(test); // let test1 = document.querySelectorAll('#content') // console.log(test); // let test3 = document.querySelector('.important') // console.log(test3); // let test4 = document.querySelectorAll('.important') // let transition = Array.from(test4) // transition.forEach(el => { // let hoho = el.innerText // console.log(hoho.substr(0, hoho.length-1) + hoho.substr(-1).toUpperCase()); // }); // let test7 = document.getElementById('content') // let test8 = test7.getElementsByClassName('grandParagraphe') // console.log(test8);
8ac6845c06e1aa953d3f626ba8a640e5a0169372
[ "JavaScript" ]
1
JavaScript
Achraf-100/js_dompart2_recupelement_exercice3
b897861ad2c650a17e19b9b328db6dd1c07e8dbf
93667f23137ecbf865110c1180218dda2f82518d
refs/heads/master
<repo_name>oniram88/RunnersBikers<file_sep>/db/migrate/20180106185236_change_session_points_to_decimal.rb class ChangeSessionPointsToDecimal < ActiveRecord::Migration[5.1] def change change_column :performances, :points, :decimal, :precision => 15, :scale => 3 change_column :users, :total_points, :decimal, :precision => 15, :scale => 3 end end <file_sep>/app/policies/user_policy.rb class UserPolicy < ApplicationPolicy def actual_user? user == record end def show_performances? user.is_judge? end def execute_graph? true end def set_referal_points? user.is_judge? end end <file_sep>/spec/models/performance_spec.rb # == Schema Information # # Table name: performances # # id :integer not null, primary key # user_id :integer # distance :decimal(8, 4) # pace :integer # positive_gain :integer # url :string(255) # created_at :datetime not null # updated_at :datetime not null # points :decimal(15, 3) # require 'rails_helper' RSpec.describe Performance, type: :model do it "after_create should update user_rank" do user1 = create(:user) create(:performance, distance: 10, user: user1) expect(user1.rank).to be == 1 user2 = create(:user) expect(user2.rank).to be == 2 expect { expect { expect { create(:performance, distance: 100, user: user2) user2.reload user1.reload }.to change(user2, :rank).from(2).to(1) }.to change(user1, :rank).from(1).to(2) }.to change(user2, :total_points) end #100 * (distance + positive_gain / 100) / (pace.to_f / 60) it "wil calculate correct values" do expect(build(:performance, distance: 100, positive_gain: 100, pace: 60).calculate_points).to be == 10100 end it "oltre termine" do Timecop.freeze(RunnersBikers::MAX_ISCRIZIONE - 10.days) do @user = create(:user) Timecop.freeze(RunnersBikers::MAX_PERFORMANCE_INSERT) do expect(build(:performance, :user => @user)).not_to be_valid end end end it "on update change user points" do p = create(:performance) expect { p.update_attributes(:distance => p.distance + 1) }.to change(p.user, :total_points) end it "on destroy change user points" do p = create(:performance) expect { p.destroy }.to change(p.user, :total_points).by(p.points * -1) end end <file_sep>/app/graphql/types/error_type.rb Types::ErrorType = GraphQL::ObjectType.define do name "Error" field :field, types.String do resolve -> (obj, args, ctx) { obj[0] } end field :message, types.String.to_list_type do resolve -> (obj, args, ctx) { obj[1] } end end <file_sep>/readme_docker.md **Installazione** docker-compose build Per far partire tutto: * docker-compose run --service-ports app Per far partire ogni singolo servizio (la prima volta): * docker-compose run -d -p'33306:3306' --name runners_bikers_db db Per lanciare ogni singolo servizio quando i containers sono già presenti: * docker restart spchains_db per poi lanciare il solito " bin/rails s " Togliendo -d si rimane attaccati all'STDI di ogni servizio Per lanciare un comando di rails interno: usare kitematick oppure: bash -c "clear && docker exec -it nome_container /bin/bash"<file_sep>/db/migrate/20180101083924_full_recalculate_points.rb class FullRecalculatePoints < ActiveRecord::Migration[5.1] def change Performance.transaction do Performance.all.each do |p| p.save end User.all.each do |u| if u.first_name.blank? u.first_name = "<NAME> #{u.id}" end if u.last_name.blank? u.last_name = "<NAME> #{u.id}" end u.save points = u.performances.reload.sum(:points) u.update_attributes!(total_points: points) end Match.all.each do |m| real_max_points = m.challenged.total_points * 0.25 m.update_attribute(:points, real_max_points) if m.points > real_max_points end User.all.each do |u| u.update_points end unless Rails.env.test? counts = 0 while ::SuckerPunch::Queue.stats["ActiveJob::QueueAdapters::SuckerPunchAdapter::JobWrapper"]["workers"]["busy"] > 0 puts "attendo #{counts}" counts += 1 sleep(1) end end end end end <file_sep>/app/policies/ranking_policy.rb class RankingPolicy < ApplicationPolicy end <file_sep>/app/graphql/types/user_type.rb Types::UserType = GraphQL::ObjectType.define do name "User" field :id, types.Int field :email, types.String field :username, types.String field :first_name, types.String field :last_name, types.String field :total_points, types.Int, "Il totale dei punti dell'utente" field :performances, types[Types::PerformanceType] field :matches_as_challenger, types[Types::MatchType] field :matches_as_challenged, types[Types::MatchType] field :matches_as_winner, types[Types::MatchType] field :matches_as_looser, types[Types::MatchType] field :referal_points, types.Int end <file_sep>/app/javascript/packs/helpers.js import _ from 'lodash'; export function mapStateFeedbackListCmp(...fields) { let o = {} _.each(fields, (i) => { o[`${i}_error_obj`] = function () { // console.log(this, i, 'error_obj', this.errors); if (this.errors) { return _.find(this.errors, function (o) { return o.field == i; }) || false; } return false; }; o[`${i}_state`] = function () { // console.log(this, i, 'state', this.errors); let obj_key = `${i}_error_obj` if (this.show_errors) { if (this[obj_key]) { return 'invalid'; } else { return 'valid'; } }else{ return ''; } }; o[`${i}_feedback`] = function () { // console.log(this, i, 'feedback', this.errors); let obj_key = `${i}_error_obj` if (this.show_errors) { if (this[obj_key]) { return this[obj_key].message[0]; } } else { return ''; } } }); return o; }<file_sep>/app/graphql/mutations/edit_performance.rb Mutations::EditPerformance = GraphQL::Relay::Mutation.define do name "EditPerformance" return_field :result, Types::OperationResultType input_field :distance, types.Float input_field :pace, types.String input_field :positive_gain, types.Int input_field :url, types.String input_field :id, !types.ID, "performance_id" resolve ->(obj, args, ctx) { @obj = Performance.find(args.id) @obj.update_attributes(args.to_h) {result: @obj} } end <file_sep>/app/graphql/mutations/create_performance.rb Mutations::CreatePerformance = GraphQL::Relay::Mutation.define do name "CreatePerformance" return_field :result, Types::OperationResultType input_field :distance, types.Float input_field :pace, types.String input_field :positive_gain, types.Int input_field :url, types.String resolve ->(obj, args, ctx) { @obj = ctx[:current_user].performances.create(args.to_h) {result: @obj} } end <file_sep>/app/graphql/types/operation_result_type.rb Types::OperationResultType = GraphQL::ObjectType.define do name "OperationResult" # field :object, Types::ObjectType do # resolve -> (obj, args, ctx) { # obj # } # # end field :errors, types[Types::ErrorType] do resolve -> (obj, args, ctx) { obj.errors.as_json } end field :result, types.Boolean do resolve -> (obj, args, ctx) { obj.valid? } end end <file_sep>/app/javascript/graphql/base_client.js import gql from 'graphql-tag' export const CLIENT_CONFIGURATION = gql`query client_configuration{ client_configuration{ user_id roles username first_name last_name program_version referal_points total_points } }`<file_sep>/app/graphql/mutations/create_match.rb Mutations::CreateMatch = GraphQL::Relay::Mutation.define do name "CreateMatch" return_field :result, Types::OperationResultType input_field :challenged_id, !types.ID, "User id as challenged" input_field :points, types.Int, 'Total Points to be removed from looser' resolve ->(obj, args, ctx) { @obj = ctx[:current_user].matches_as_challenger.build(args.to_h) # authorize @obj @obj.save {result: @obj} } end <file_sep>/app/graphql/mutations/approve_match.rb Mutations::ApproveMatch = GraphQL::Relay::Mutation.define do name "ApproveMatch" return_field :result, Types::OperationResultType input_field :id, !types.ID, "match id" resolve ->(obj, args, ctx) { @obj = Match.find(args.id) @obj.approve(ctx[:current_user]) {result: @obj} } end <file_sep>/db/migrate/20171216105856_add_col_winner_looser_to_match.rb class AddColWinnerLooserToMatch < ActiveRecord::Migration[5.1] def change add_column :matches, :winner_id, :integer add_column :matches, :looser_id, :integer add_index :matches, :winner_id add_index :matches, :looser_id end end <file_sep>/db/migrate/20171126204656_create_performances.rb class CreatePerformances < ActiveRecord::Migration[5.1] def change create_table :performances do |t| t.integer :user_id t.decimal :distance, precision: 8, scale: 4 t.integer :pace t.integer :positive_gain t.string :url t.timestamps end end end <file_sep>/spec/factory_lint_spec.rb require 'rails_helper' RSpec.describe 'Lint' do it 'check_all' do expect { FactoryBot.lint }.not_to raise_error end end <file_sep>/spec/models/match_spec.rb # == Schema Information # # Table name: matches # # id :integer not null, primary key # challenged_id :integer # challenger_id :integer # status :integer # points :integer # created_at :datetime not null # updated_at :datetime not null # challenger_p_id :integer # challenged_p_id :integer # judge_id :integer # winner_id :integer # looser_id :integer # note :text(65535) # require 'rails_helper' RSpec.describe Match, type: :model do include ActiveJob::TestHelper it "match only possible within range +-3 of rank" do userTOP = create(:user) create(:performance, distance: 10, user: userTOP) user1 = create(:user) create(:performance, distance: 9, user: user1) user2 = create(:user) create(:performance, distance: 8, user: user2) user3 = create(:user) create(:performance, distance: 7, user: user3) challenger = create(:user) create(:performance, distance: 6, user: challenger) user4 = create(:user) create(:performance, distance: 5, user: user4) user5 = create(:user) create(:performance, distance: 4, user: user5) user6 = create(:user) create(:performance, distance: 3, user: user6) userBAD = create(:user) create(:performance, distance: 2, user: userBAD) expect(userTOP.rank).to be == 1 expect(userBAD.rank).to be == 9 expect(challenger.rank).to be == 5 expect(build(:match, challenger: challenger, challenged: user1)).to be_valid expect(build(:match, challenger: challenger, challenged: user2)).to be_valid expect(build(:match, challenger: challenger, challenged: user3)).to be_valid expect(build(:match, challenger: challenger, challenged: user4)).to be_valid expect(build(:match, challenger: challenger, challenged: user5)).to be_valid expect(build(:match, challenger: challenger, challenged: user6)).to be_valid expect(build(:match, challenger: challenger, challenged: userTOP)).not_to be_valid expect(build(:match, challenger: challenger, challenged: userBAD)).not_to be_valid end it 'max as chellanger' do user = create(:user) RunnersBikers::MAX_AS_CHALLENGER.times do create(:completed_approved_match, challenger: user) user.reload end expect(build(:match, challenger: user)).not_to be_valid end it 'max as chellanged' do user = create(:user) RunnersBikers::MAX_AS_CHALLENGED.times do create(:completed_approved_match, challenged: user) user.reload end expect(build(:match, challenged: user)).not_to be_valid end it "associazione automatica" do m = create(:match) expect(m.challenged_performance).to be_nil expect(m.challenger_performance).to be_nil expect { expect { create(:performance, user: m.challenger) m.reload }.to change(m, :challenger_performance) expect { create(:performance, user: m.challenged) m.reload }.to change(m, :challenged_performance) }.to change(m, :status).from("wait").to("approval_waiting") end it "quando viene eseguita più di una performance prima che il challenged completi il match" do m = create(:match) expect(m.challenged_performance).to be_nil expect(m.challenger_performance).to be_nil expect { create(:performance, user: m.challenger) m.reload }.to change(m, :challenger_performance) expect { create(:performance, user: m.challenger) m.reload }.not_to change(m, :challenger_performance) end it "quando viene eseguita più di una performance prima che il challenger completi il match" do m = create(:match) expect(m.challenged_performance).to be_nil expect(m.challenger_performance).to be_nil expect { create(:performance, user: m.challenged) m.reload }.to change(m, :challenged_performance) expect { create(:performance, user: m.challenged) m.reload }.not_to change(m, :challenged_performance) end it "approve" do m = create(:completed_match) if m.challenged_performance.points > m.challenger_performance.points winner = m.challenged looser = m.challenger else winner = m.challenger looser = m.challenged end expect { expect { expect { expect { m.approve(create(:judge)) m.reload }.to change(m, :winner).to(winner) }.to change(m, :looser).to(looser) }.to change(m, :status).from('approval_waiting').to('approved') winner.reload }.to change(winner, :total_points).by(m.points) end it "disapprove" do m = create(:completed_match) expect { m.disapprove(create(:judge)) m.reload }.to change(m, :status).from('approval_waiting').to('disapproved') end describe "generazione emails e cambi status del match" do before(:each) do @judge = create(:judge) Timecop.freeze(Time.now) @match = create(:match) @inizio_sfida = @match.created_at @sfidante = @match.challenger @sfidato = @match.challenged end after(:each) do Timecop.return end describe "out of time" do it "nessuna performance" do expect(@match.outdated?).to be_falsey Timecop.freeze(Time.now + RunnersBikers::MATCH_DURATION + 1.second) expect { perform_enqueued_jobs do expect { expect(@match.outdated?).to be_truthy Match.check_timeouts @match.reload }.to change(@match, :status).from('wait').to('timeouted') end }.to change { ActionMailer::Base.deliveries.count }.by(3) end it "solo una performance dallo sfidante" do create(:performance, user: @sfidante) Timecop.freeze(Time.now + RunnersBikers::MATCH_DURATION + 1.second) expect { perform_enqueued_jobs do expect { expect { Match.check_timeouts @match.reload }.to change(@match, :status).from('wait').to('timeouted') }.to change(@match, :winner).to(@sfidante) end }.to change { ActionMailer::Base.deliveries.count }.by(3) end it "solo una performance dallo sfidato" do create(:performance, user: @sfidato) Timecop.freeze(Time.now + RunnersBikers::MATCH_DURATION + 1.second) expect { perform_enqueued_jobs do expect { expect { Match.check_timeouts @match.reload }.to change(@match, :status).from('wait').to('timeouted') }.to change(@match, :winner).to(@sfidato) end }.to change { ActionMailer::Base.deliveries.count }.by(3) end end it do expect(@match.expiration_date).to be == @inizio_sfida + RunnersBikers::MATCH_DURATION end it "emails di creazione" do #creo fuori gli utenti altrimenti mi segna il conteggio dell'invio emails # anche quelle di conferma degli utenti u1 = create(:user) u2 = create(:user) expect { perform_enqueued_jobs do create(:match, challenger: u1, challenged: u2) end }.to change { ActionMailer::Base.deliveries.count }.by(3) #2 utenti e arbitro end it "performances create, invio email agli arbitri per validare" do expect { perform_enqueued_jobs do create(:performance, user: @sfidante) create(:performance, user: @sfidato) em = ActionMailer::Base.deliveries.last expect(em.to).to include(@judge.email) expect(em.body.encoded).to match('appena conclusa una sfida') end }.to change { ActionMailer::Base.deliveries.count }.by(1) end it "performance validata" do m = create(:completed_match) expect(m).to be_approval_waiting expect { perform_enqueued_jobs do expect { @judge.approve(m) }.to change(m, :status).from('approval_waiting').to('approved') end }.to change { ActionMailer::Base.deliveries.count }.by(3) #una per giudice e le altre per i due challengers end it "performance non valida" do m = create(:completed_match) expect(m).to be_approval_waiting expect { perform_enqueued_jobs do expect { @judge.disapprove(m) }.to change(m, :status).from('approval_waiting').to('disapproved') end }.to change { ActionMailer::Base.deliveries.count }.by(3) #una per giudice e le altre per i due challengers end it "Performance non valida in quanto patta" do m = create(:match) create(:performance, user: m.challenged, distance: 10, pace: '4:00', positive_gain: 1) create(:performance, user: m.challenger, distance: 10, pace: '4:00', positive_gain: 1) m.reload expect { @judge.approve(m) }.to change(m, :status).from('approval_waiting').to('approved') end end end <file_sep>/lib/tasks/check_timeouts.rake namespace :runners_bikers do desc "Esegue un check dei timeouts fra le sfide" task :check_timeouts => :environment do |t, args| Match.check_timeouts #aspettiamo 30 secondi per lasciar spedire tutta la posta sleep 2.minutes end end <file_sep>/config/initializers/runners_bikers.rb module RunnersBikers VERSION = '1.0.11' PROGRAMM_STATUS = Rails.env.test? ? 'test' : Rails.application.secrets.challange_status # Durata Sfida MATCH_DURATION = PROGRAMM_STATUS == 'test' ? 10.minutes : 5.days # Tempo inizio inserimento Performance MIN_PERFORMANCE_INSERT = PROGRAMM_STATUS == 'test' ? Time.now - 1.month : Time.zone.parse('2018-06-16 00:00:00') # Tempo massimo inserimento Performance prima della fine della gara MAX_PERFORMANCE_INSERT = PROGRAMM_STATUS == 'test' ? Time.now + 1.month : Time.zone.parse('2018-07-23 00:00:00') + 2.hours # Tempo massimo iscrizioni MAX_ISCRIZIONE = PROGRAMM_STATUS == 'test' ? Time.now + 1.year : MIN_PERFORMANCE_INSERT #Time.zone.parse('2018-01-13 00:00:00') # Time to start challengers TIME_TO_START_CHALLENGES = PROGRAMM_STATUS == 'test' ? Time.now - 1.day : Time.zone.parse('2018-06-30 00:00:00') # Tempo massimo Inizio sfide MAX_TIME_FOR_START_CHALLENGES = MAX_PERFORMANCE_INSERT - MATCH_DURATION - 2.hours # Numero massimo di sfide come sfidante MAX_AS_CHALLENGER = 3 # Numero massimo di sfide come sfidato MAX_AS_CHALLENGED = 3 end <file_sep>/app/javascript/graphql/users.js import gql from "graphql-tag"; export const ADMIN_USER_LIST = gql`query users{ users{ id first_name last_name referal_points } }` export const SET_REFERAL_POINTS = gql`mutation set_referal_points($id:ID!,$points:Int!){ set_referal_points(input:{user_id:$id,points:$points}){ result{ result } } }`<file_sep>/app/graphql/types/performance_type.rb Types::PerformanceType = GraphQL::ObjectType.define do name "Performance" field :id, types.Int field :distance, types.Float do authorize end field :pace, types.String do authorize end field :positive_gain, types.Int do authorize end field :user_id, types.Int do authorize end field :user, Types::UserType do authorize end field :url, types.String do authorize end field :points, types.Int do authorize end field :created_at, types.String do resolve ->(obj, args, ctx) { obj.created_at.to_datetime.rfc3339 } end field :destructible, types.Boolean do resolve -> (obj, args, ctx) { !PerformancePolicy.new(ctx[:current_user], obj).destroy? } end field :editable, types.Boolean do resolve -> (obj, args, ctx) { !PerformancePolicy.new(ctx[:current_user], obj).update? } end field :readonly, types.Boolean do resolve -> (obj, args, ctx) { !PerformancePolicy.new(ctx[:current_user], obj).update? } end end <file_sep>/app/models/performance.rb # == Schema Information # # Table name: performances # # id :integer not null, primary key # user_id :integer # distance :decimal(8, 4) # pace :integer # positive_gain :integer # url :string(255) # created_at :datetime not null # updated_at :datetime not null # points :decimal(15, 3) # require 'pace_type' class Performance < ApplicationRecord belongs_to :user has_one :challenged_match, class_name: 'Match', foreign_key: :challenged_p_id has_one :challenger_match, class_name: 'Match', foreign_key: :challenger_p_id attribute :pace, :pace, default: '00:00' validates :distance, presence: true, numericality: { greater_than: 0, less_than_or_equal_to: 9999.9999 } validates :pace, presence: true, format: PaceType.reg_exp validates :positive_gain, presence: true, numericality: { greater_than_or_equal_to: 0, only_integer: true } validates :url, :presence => true, uniqueness: true, format: /\Ahttps?:\/\//i validate :time_checks, on: :create before_save :update_points after_save :update_user_points_rank after_destroy :update_user_points_rank after_save :check_match_data # PUNTEGGIO = 100 x ( D + d/100 ) / r^2 # Con D = distanza in km # d = dislivello positivo in m # r = ritmo medio in min/km (5:30=> 5+30/60 => 5,5) def calculate_points (100.0 * (distance.to_f + positive_gain.to_f / 100.0) / (PaceType.to_seconds(pace).to_f / 60.0) ** 2).round(3) end def running_time PaceType.to_seconds(pace) * distance end private def update_points self.points = calculate_points end def update_user_points_rank self.user.update_points User.update_rank end ## # Si occupa di associare questa performance al match se attivo della persona def check_match_data Match.check_timeouts challenger_match = user.matches_as_challenger.wait.first if challenger_match challenger_match.update_attributes(challenger_performance: self) if challenger_match.challenger_performance.nil? end challenged_match = user.matches_as_challenged.wait.first if challenged_match challenged_match.update_attributes(challenged_performance: self) if challenged_match.challenged_performance.nil? end end ## # Definizione del tempo massimo di inserimento della performance def time_checks if Time.now >= RunnersBikers::MAX_PERFORMANCE_INSERT self.errors.add(:base, :challenger_expired, max_time: I18n.l(RunnersBikers::MAX_PERFORMANCE_INSERT,format: :short)) end if Time.now < RunnersBikers::MIN_PERFORMANCE_INSERT self.errors.add(:base, :not_starter, min_time: I18n.l(RunnersBikers::MIN_PERFORMANCE_INSERT,format: :short)) end end end <file_sep>/app/custom_types/pace_type.rb ## # Classe che definisce un tipo di dato per semplificare la registrazione del # valore del ritmo class PaceType < ActiveRecord::Type::Value def type :pace end def deserialize(value) if value.is_a?(String) to_seconds(value) elsif value.is_a?(Integer) "%02d:%02d" % value.divmod(60) else super end end def serialize(value) # value here is a String to_seconds(value) end def self.serialize(value) to_seconds(value) end def self.reg_exp /\A(?<minuti>[0-5]?[0-9]):(?<secondi>([0-5][0-9]))\Z/ end def to_seconds(value) self.class.to_seconds(value) end def self.to_seconds(value) if value.is_a?(String) and value.match(reg_exp) ris = value.match(reg_exp) ris[:minuti].to_i * 60 + ris[:secondi].to_i else value end end end ActiveRecord::Type.register(:pace, PaceType)<file_sep>/app/javascript/graphql/performances.js import gql from 'graphql-tag' export const CREATE_PERFORMANCE = gql`mutation createPerformance($distance: Float, $pace: String, $positive_gain: Int, $url: String) { createPerformance(input: {distance: $distance, pace: $pace, positive_gain: $positive_gain, url: $url}) { result { result errors{ field message } } } } ` export const EDIT_PERFORMANCE = gql`mutation editPerformance($id: ID!, $distance: Float, $pace: String, $positive_gain: Int, $url: String) { editPerformance(input: {id: $id, distance: $distance, pace: $pace, positive_gain: $positive_gain, url: $url}) { result { result errors{ field message } } } } ` export const DELETE_PERFORMANCE = gql`mutation deletePerformance($id: ID!) { deletePerformance(input: {id: $id}) { result { result errors{ field message } } } } ` export const GET_PERFORMANCE = gql`query getPerformance($id:ID!){ performance(id:$id){ distance pace readonly url positive_gain } }` export const GET_PERFORMANCES = gql`query getPerformances($id:ID){ performances(user_id:$id){ distance pace url positive_gain created_at editable destructible user_id id } } ` <file_sep>/config/webpack/environment.js const {environment} = require('@rails/webpacker'); const vue = require('./loaders/vue'); const webpack = require('webpack'); const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); environment.plugins.append('UglifyJs', new UglifyJsPlugin({ parallel: true, uglifyOptions: { ecma: 6, compress: false // hangs without this }, cache: path.join(__dirname, '../../tmp/webpack-cache/uglify-cache'), }) ); environment.plugins.append( 'Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'] }) ); environment.loaders.append('vue', vue); module.exports = environment; <file_sep>/app/graphql/mutations/set_referal_points.rb Mutations::SetReferalPoints = GraphQL::Relay::Mutation.define do name "SetReferalPoints" # TODO: define return fields # return_field :post, Types::PostType # TODO: define arguments input_field :user_id, !types.ID, 'Id utente' input_field :points, !types.Int, 'Punti da impostare all\'utente' return_field :result, Types::OperationResultType resolve ->(obj, args, ctx) { user = User.find(args[:user_id]) user.referal_points = args[:points] user.save {result: user} } end <file_sep>/app/graphql/types/statistics_type.rb Types::StatisticsType = GraphQL::ObjectType.define do name "StatisticsType" description "Statistiche del Challenge" field :total_distance, types.Int, 'km totali percorsi (tutti correnti)' do resolve -> (obj, args, ctx) { Performance.sum(:distance) } end field :total_positive_gain, types.Int, 'dislivello totale percorso(tutti correnti)' do resolve -> (obj, args, ctx) { Performance.sum(:positive_gain) } end field :total_run_time, types.Int, 'tempo totale di corsa di tutti i challengera assieme in secondi' do resolve -> (obj, args, ctx) { Performance.all.collect(&:running_time).sum } end field :max_positive_gain_in_a_session, types.String, 'dislivello più alto singola sessione' do resolve -> (obj, args, ctx) { p = Performance.order(:positive_gain => :desc).first "#{p.user.full_name} - #{p.distance} km" if p } end field :max_distance_in_a_session, types.String, 'percorso più lungo singola sessione' do resolve -> (obj, args, ctx) { p = Performance.order(:distance => :desc).first "#{p.user.full_name} - #{p.distance} km" if p } end field :max_average_speed_in_a_session, types.String, 'velocità media più alta singola sessione' do resolve -> (obj, args, ctx) { p = Performance.order(:pace => :asc).first "#{p.user.full_name} - #{p.pace}" if p } end field :user_with_max_sessions, types.String, 'utente con più sessioni' do resolve -> (obj, args, ctx) { begin id = Performance.group(:user_id).count.sort_by {|k, v| v}.reverse.first[0] user = User.find(id) "#{user.full_name} - #{user.performances.count}" if user rescue "" end } end end <file_sep>/README.md # Applicazione per gestire una gara virtuale tra corridori [![Build Status](https://travis-ci.org/oniram88/RunnersBikers.svg?branch=master)](https://travis-ci.org/oniram88/RunnersBikers) <file_sep>/db/migrate/20171203214412_add_rank_to_user.rb class AddRankToUser < ActiveRecord::Migration[5.1] def change add_column :users, :rank, :integer add_column :users, :total_points, :integer, default: 0 reversible do |dir| dir.up do User.all.each do |u| u.update_points u.update_rank end end end end end <file_sep>/app/graphql/types/query_type.rb Types::QueryType = GraphQL::ObjectType.define do name "Query" # Add root-level fields here. # They will be entry points for queries on your schema. field :user do type Types::UserType argument :id, types.ID description "Find a User by ID,or get the current user" authorize! :show, record: ->(obj, args, ctx) { if args["id"] User.find(args["id"]) else ctx[:current_user] end } resolve ->(obj, args, ctx) { if args["id"] User.find(args["id"]) else ctx[:current_user] end } end field :performance do type Types::PerformanceType argument :id, !types.ID description "Find a performance by ID" authorize! :show, record: ->(obj, args, ctx) {Performance.find(args['id'])} resolve ->(obj, args, ctx) {Performance.find(args["id"])} end field :performances do type Types::PerformanceType.to_list_type argument :limit, types.Int argument :user_id do type types.ID default_value nil description "Possibile passare l'id della persona su cui scoppare la ricerca delle performances, altrimenti le proprie" prepare ->(value, ctx) { value || ctx[:current_user].id } end description "Get own performances or of an other user" before_scope ->(_root, _args, ctx) {PerformancePolicy.new(ctx[:current_user], Performance.new).scope.all} resolve ->(performances, args, ctx) { if args[:user_id] performances = performances.where(user_id: args[:user_id]) end unless args[:limit].blank? performances = performances.limit(args[:limit]) end performances.to_a } end field :users do type Types::UserType.to_list_type argument :limit, types.Int description "List of all users" after_scope resolve ->(obj, args, ctx) do q = User.all unless args[:limit].blank? q = q.limit(args[:limit]) end q end end field :client_configuration do type Types::ClientConfiguration description "Configurazione del client corrente" resolve ->(obj, args, ctx) do ctx[:current_user] end end field :statistics do type Types::StatisticsType description "Statistiche di Challenge" resolve ->(obj, args, ctx) do {} end end field :rankings do type Types::RankingType.to_list_type argument :id, types.ID, 'Ranking per un determinato id' argument :limit, types.Int, default_value: 100, prepare: ->(limit, ctx) {[limit, 100].min} description "List of all users" # after_scope resolve ->(obj, args, ctx) do if args[:id] Ranking.where(id: args[:id]) else Ranking.order(:rank => :asc).limit(args[:limit]) end end end field :matches do type Types::MatchType.to_list_type argument :limit, types.Int, default_value: 100, prepare: ->(limit, ctx) {[limit, 100].min} description "Elenco Sfide" before_scope ->(_root, _args, ctx) {MatchPolicy.new(ctx[:current_user], Match.new).scope.all} resolve ->(objs, args, ctx) do unless args[:limit].blank? objs = objs.limit(args[:limit]) end objs.order(:created_at => :desc) end end end <file_sep>/app/controllers/restricted_area_controller.rb class RestrictedAreaController < ApplicationController before_action :authenticate_user! after_action :verify_authorized, except: :index after_action :verify_policy_scoped, only: :index layout 'application' rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def user_not_authorized respond_to do |f| f.json { render json: { success: false, error: 'Unauthorized' }, status: :unauthorized } f.html { flash[:alert] = "You are not authorized to perform this action." redirect_to(request.referrer || root_path) } end end end<file_sep>/app/graphql/mutations/update_match.rb Mutations::UpdateMatch = GraphQL::Relay::Mutation.define do name "UpdateMatch" return_field :result, Types::OperationResultType input_field :note, types.String input_field :id, !types.ID, "match id" resolve ->(obj, args, ctx) { @obj = Match.find(args.id) @obj.update_attributes(args.to_h) {result: @obj} } end <file_sep>/app/graphql/runners_bikers_schema.rb RunnersBikersSchema = GraphQL::Schema.define do instrument(:field, GraphQL::Pundit::Instrumenter.new) mutation(Types::MutationType) query(Types::QueryType) end <file_sep>/app/helpers/emails_helpers.rb module EmailsHelpers def terminate_date(match) l match.expiration_date, format: :long end def performance_url(p) "#{root_url}#/matches/user/#{p.user_id}/performances/#{p.id}/edit_performance" end end<file_sep>/app/graphql/types/match_type.rb Types::MatchType = GraphQL::ObjectType.define do name "Match" field :id, types.Int field :challenged, Types::UserType field :challenger, Types::UserType field :status, types.String field :points, types.Int field :challenger_performance, Types::PerformanceType field :challenged_performance, Types::PerformanceType field :judge, Types::UserType field :winner, Types::UserType field :looser, Types::UserType field :note, types.String field :expiration_date, types.String do resolve ->(obj, args, ctx) { obj.expiration_date.to_datetime.rfc3339 } end field :approvable, types.Boolean do description 'if the match can be approved' resolve ->(obj, args, ctx) { MatchPolicy.new(ctx[:current_user], obj).approve? } end field :note_updatable, types.Boolean do description 'if the note can be update from current user' resolve ->(obj, args, ctx) { MatchPolicy.new(ctx[:current_user], obj).note_updatable? } end end <file_sep>/lib/tasks/utils.rake namespace :runners_bikers do namespace :utils do desc "In Sviluppo esegue una pulizia password e conferma tutti gli account" task :prepare_dev => :environment do |t, args| User.all.each do |u| puts "#{u.email} - #{u.username} - #{u.first_name} - #{u.last_name}" u.password='<PASSWORD>' u.confirmed_at=Time.now u.save! end end desc "Correct first match" task :correct_first_match => :environment do Performance.transaction do m = Match.first vecchia_performance = m.challenger_performance correct_performance = Performance.find(272) m.update_attributes(challenger_performance: correct_performance) vecchia_performance.update_attributes(:distance=>8.11) User.all.each{|u| u.update_points} User.update_rank end end end end <file_sep>/db/migrate/20171212124048_add_column_challanger_challanged_p_to_match.rb class AddColumnChallangerChallangedPToMatch < ActiveRecord::Migration[5.1] def change add_column :matches, :challenger_p_id, :integer add_column :matches, :challenged_p_id, :integer add_column :matches, :judge_id, :integer end end <file_sep>/lib/tasks/results.rake namespace :runners_bikers do namespace :results do desc "Lancia tutti i task" task :all => :environment do | | [:totals, :general_order, :climbing_order, :pace_order, :order_inclination, :order_matches, :match_minor_difference].each do |t| Rake::Task["runners_bikers:results:#{t}"].invoke puts "============== #{t} =================" puts "" puts "" end end def title(title) puts "============== #{title} =================" end desc "General Order" task :general_order => :environment do |t, args| title "General Order" User.all.order(:total_points => :desc).each do |u| puts [u.rank, u.full_name, u.total_points, "#{u.performances.sum(:distance)} km"].join(' , ') end end desc "Totals" task :totals => :environment do |t, args| title "Totals" puts "Distanza totale: #{Performance.sum(:distance)}km" puts "Dislivello totale: #{Performance.sum(:positive_gain)}m" puts "Numero sessioni totali: #{Performance.count}" puts "Numero sfide totali: #{Match.count}" #passo medio puts "Passo medio: #{PaceType.new.deserialize((Performance.select('sum(pace) as passo')).first[:passo] / Performance.count)}" end desc "Classifica per dislivello" task :climbing_order => :environment do |t, args| title "Classifica per dislivello" contatore = 1 Performance.group(:user_id).sum(:positive_gain).sort_by {|a, b| b}.reverse.each do |p| puts [contatore, User.find(p[0]).full_name, "#{p[1]} m"].join(' , ') contatore += 1 end end desc "Classifica per passo medio" task :pace_order => :environment do |t, args| title "Classifica per passo medio" contatore = 1 User.all.joins(:performances).uniq.collect {|u| begin value = u.performances.select('sum(pace) as passo').first[:passo] / u.performances.count rescue value = 9999999999999 end [u.full_name, value] }.sort_by {|a, b| b}.collect {|a, b| [a, PaceType.new.deserialize(b)]}.each do |l| puts [contatore, l].flatten.join(' , ') contatore += 1 end end desc "Classifica per pendenza" task :order_inclination => :environment do |t, args| title "Classifica per pendenza" contatore = 1 User.all.joins(:performances).uniq.collect do |u| [u.full_name, "#{((u.performances.sum(:positive_gain) / 1000.0 / u.performances.sum(:distance)) * 100.0).round(3)} %"] end.sort_by {|a, b| b}.reverse.each do |l| puts [contatore, l].flatten.join(' , ') contatore += 1 end end desc "Classifica per sfide vinte/fatte" task :order_matches => :environment do |t, args| title "Classifica per sfide vinte/fatte" contatore = 1 User.all.collect do |u| [u.full_name, u.matches_as_winner.count, u.matches_as_challenger.count + u.matches_as_challenged.count, u.matches_as_winner.sum(:points), u.matches_as_looser.sum(:points)] end.sort_by {|a, b| b}.reverse.each do |l| puts [contatore, l[0], "#{l[1]}/#{l[2]}", "Punti conquistati:#{l[3]}", "Punti persi:#{l[4]}"].flatten.join(' , ') contatore += 1 end end desc "Ordine per minor differenza di punteggio nella sfida" task :match_minor_difference => :environment do |t, args| title "Ordine sfide per minor differenza di punteggio" contatore = 1 Match.approved.collect do |a| ["#{a.challenger.full_name} VS #{a.challenged.full_name} ", (a.challenged_performance.points - a.challenger_performance.points).abs] end.sort_by {|a, b| b}.each do |l| puts [contatore, l].flatten.join(' , ') contatore += 1 end end desc "Estrae CSV con tutti i dati delle sessioni" task :extract_session_data => :environment do |t, args| CSV.open(Rails.application.root.join('tmp', "sessioni_#{Time.now}.csv"), "wb") do |csv| csv << ['nome', 'cognome', 'data', 'distanza m', 'passo', 'passo in s', 'dislivello m', 'url'] Performance.all.includes(:user).order(:id).each do |p| data = [p.user.first_name, p.user.last_name, p.created_at, (p.distance * 1000).to_i, p.pace, PaceType.to_seconds(p.pace), p.positive_gain, p.url] puts data.inspect csv << data end end end desc "Estrae CSV con tutti i dati raggruppati per utenti" task :extract_user_data => :environment do |t, args| CSV.open(Rails.application.root.join('tmp', "user_#{Time.now}.csv"), "wb") do |csv| csv << ['nome', 'cognome', 'distanza km', 'dislivello m', 'passo', 'passo in s'] User.all.joins(:performances).uniq.each {|u| begin value = u.performances.select('sum(pace) as passo').first[:passo] / u.performances.count csv << [u.first_name, u.last_name, u.performances.sum(:distance), u.performances.sum(:positive_gain), PaceType.new.deserialize(value), value] rescue puts "errore per #{u.full_name}" end } end end end end<file_sep>/app/graphql/types/mutation_type.rb Types::MutationType = GraphQL::ObjectType.define do name "Mutation" field :setReferalPoints, Mutations::SetReferalPoints.field field :createPerformance, Mutations::CreatePerformance.field do authorize! :update, record: ->(obj, args, ctx) {ctx[:current_user].performances.new(args.to_h)} end field :editPerformance, Mutations::EditPerformance.field do authorize! :update, record: ->(obj, args, ctx) {Performance.find(args[:id])} end # field :createPerformance, Mutations::CreatePerformance.field field :createMatch, Mutations::CreateMatch.field do authorize! :create, record: ->(obj, args, ctx) {Match.new(challenger: ctx[:current_user], challenged_id: args[:challenged_id], points: args[:points])} end field :deletePerformance, Mutations::DeletePerformance.field do authorize! :destroy, record: ->(obj, args, ctx) {Performance.find(args[:id])} end field :update_match, Mutations::UpdateMatch.field do authorize! :update, record: ->(obj, args, ctx) {Match.find(args[:id])} end field :approve_match, Mutations::ApproveMatch.field do authorize! :approve, record: ->(obj, args, ctx) {Match.find(args[:id])} end field :set_referal_points, Mutations::SetReferalPoints.field do authorize! :set_referal_points, record: ->(obj, args, ctx) {User.find(args[:user_id])} end end <file_sep>/app/controllers/dashboard_controller.rb class DashboardController < RestrictedAreaController def main authorize :dashboard end end<file_sep>/spec/factories/matches.rb # == Schema Information # # Table name: matches # # id :integer not null, primary key # challenged_id :integer # challenger_id :integer # status :integer # points :integer # created_at :datetime not null # updated_at :datetime not null # challenger_p_id :integer # challenged_p_id :integer # judge_id :integer # winner_id :integer # looser_id :integer # note :text(65535) # FactoryBot.define do factory :match do challenged { create(:user_with_points) } challenger { create(:user_with_points) } points 100 factory :completed_match do after(:create) do |m| create(:performance, user: m.challenged) create(:performance, user: m.challenger) m.reload end factory :completed_approved_match do after(:create) do |m| m.approve(User.with_role(:judge).first || create(:judge)) end end end end end <file_sep>/db/migrate/20180101112202_upgrade_match_points_to_minor.rb class UpgradeMatchPointsToMinor < ActiveRecord::Migration[5.1] def change Match.transaction do Match.open_matches.all.each do |m| max_points = Ranking.max_loose_points(m.challenger, m.challenged) puts "#{m.points} > #{max_points}" if m.points > max_points puts "Aggiornamento punteggio #{max_points}" m.update_attribute(:points, max_points) end end end end end <file_sep>/app/mailers/match_notifier_mailer.rb class MatchNotifierMailer < ApplicationMailer add_template_helper(EmailsHelpers) def base_subject "TORNEO NEXT CHALLENGE PER RUNNER" end def notify_creation(match, to: :challenged) to = to.to_sym @match = match @destinatario = to object = base_subject case to when :challenged object += ' – SEI STATO SFIDATO' when :challenger object += ' – CONFERMA LANCIO SFIDA' end mail( to: @match.send(to).email, subject: object, &:mjml ) end def notify_approval_waiting(match, to: :challenged) to = to.to_sym @match = match @destinatario = to object = base_subject + " – CONCLUSIONE SFIDA #{@match.challenger.full_name} VS #{@match.challenged.full_name} CON DUE SESSIONI REGISTRATE" mail( to: @match.send(to).email, subject: object, &:mjml ) end def notify_approve_disapprove(match, to: :challenged) to = to.to_sym @match = match @destinatario = to object = base_subject + " – ESITO SFIDA #{@match.challenger.full_name} VS #{@match.challenged.full_name}" mail( to: @match.send(to).email, subject: object, &:mjml ) end def notify_outdated(match, to: :challenged) to = to.to_sym @match = match @destinatario = to object = base_subject + " – ESITO SFIDA #{@match.challenger.full_name} VS #{@match.challenged.full_name}" if @match.winner object += " CON UNA SOLA SESSIONE REGISTRATA" else object += " CON NESSUNA SESSIONE REGISTRATA" end mail( to: @match.send(to).email, subject: object, &:mjml ) end def notify_judge(match, judge) @match = match @judge = judge object = base_subject case match.status when 'wait' object += ' – COMUNICAZIONE NUOVA SFIDA' when 'approval_waiting' object += " – CONCLUSIONE SFIDA #{@match.challenger.full_name} VS #{@match.challenged.full_name} CON DUE SESSIONI REGISTRATE" when 'timeouted' object += " – CONCLUSIONE SFIDA #{@match.challenger.full_name} VS #{@match.challenged.full_name}" if @match.winner object += " CON UNA SOLA SESSIONE REGISTRATA" else object += " CON NESSUNA SESSIONE REGISTRATA" end end mail(to: judge.email, subject: object, &:mjml) end end <file_sep>/app/models/ranking.rb # == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0), not null # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # provider :string(255) # uid :string(255) # api_token :string(255) # first_name :string(255) # last_name :string(255) # image :string(255) # created_at :datetime not null # updated_at :datetime not null # rank :integer # total_points :decimal(15, 3) default(0.0) # username :string(255) # confirmation_token :string(255) # confirmed_at :datetime # confirmation_sent_at :datetime # unconfirmed_email :string(255) # # # Semplice modello che si occupa di gestire le policy della visualizzazione # del ranking class Ranking < User def total_distance performances.sum(:distance) end def total_positive_gain performances.sum(:positive_gain) end def max_lose_points(user) self.class.max_loose_points(user, self) end def self.max_loose_points(u1, u2) ([u1.total_points, u2.total_points].min * 0.25).to_i end end <file_sep>/app/controllers/registrations_controller.rb class RegistrationsController < Devise::RegistrationsController prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect. before_action :configure_permitted_parameters, if: :devise_controller? private def check_captcha unless verify_recaptcha self.resource = resource_class.new sign_up_params resource.validate # Look for any other validation errors besides Recaptcha respond_with_navigational(resource) { render :new } end end protected def configure_permitted_parameters # Permit the `subscribe_newsletter` parameter along with the other # sign up parameters. devise_parameter_sanitizer.permit(:sign_up, keys: [:username,:first_name,:last_name]) end def after_inactive_sign_up_path_for(resource) new_user_session_path end end<file_sep>/app/policies/match_policy.rb class MatchPolicy < ApplicationPolicy def create? user == record.challenger and user.open_matches.length == 0 end def approve? user.is_judge? and record.approval_waiting? end def update_note? update? end def update? user.is_judge? end def note_updatable? user.is_judge? end def permitted_attributes [:id, :note] end class Scope < Scope def resolve scope end end end <file_sep>/app/policies/performance_policy.rb class PerformancePolicy < ApplicationPolicy def permitted_attributes [ :distance, :pace, :positive_gain, :url ] end def distance? return check_attribute_displayability end def pace? return check_attribute_displayability end def positive_gain? return check_attribute_displayability end def user_id? return check_attribute_displayability end def user? return check_attribute_displayability end def url? return check_attribute_displayability end def points? return check_attribute_displayability end def show? # è una propria oppure è di un match super || Match.where(:challenger_p_id => record.id).exists? || Match.where(:challenged_p_id => record.id).exists? end def update? return false if (!record.challenged_match.nil? and !record.challenged_match.wait? and !record.challenged_match.approval_waiting?) or (!record.challenger_match.nil? and !record.challenger_match.wait? and !record.challenger_match.approval_waiting?) user == record.user or user.is_judge? end def destroy? user == record.user and (record.challenged_match.nil? and record.challenger_match.nil?) end class Scope < Scope def resolve if user.is_judge? or user.is_admin? scope else scope.merge(user.performances) end end end private #utilizzato per controllare se i campi sono visibili def check_attribute_displayability return true unless record.persisted? return true if user.is_judge? or user.is_admin? #può essere visto se appartiene al match e il match è stato completato return true if !record.challenged_match.nil? and (record.challenged_match.approved? or record.challenged_match.timeouted? or record.challenged_match.disapproved?) return true if !record.challenger_match.nil? and (record.challenger_match.approved? or record.challenger_match.timeouted? or record.challenger_match.disapproved?) return true if is_mine? end end <file_sep>/app/graphql/types/client_configuration.rb Types::ClientConfiguration = GraphQL::ObjectType.define do name "ClientConfiguration" description "Configurazioni base del client, ruoli utente loggato e versione programma " field :program_version, types.String do resolve -> (obj, args, ctx) { RunnersBikers::VERSION } end field :roles, types.String.to_list_type do resolve -> (obj, args, ctx) { obj.roles.collect(&:name) } end field :user_id, types.Int do resolve -> (obj, args, ctx) { obj.id } end field :username, types.String field :first_name, types.String field :last_name, types.String field :referal_points, types.Int field :total_points,types.Int end <file_sep>/spec/factories/performances.rb # == Schema Information # # Table name: performances # # id :integer not null, primary key # user_id :integer # distance :decimal(8, 4) # pace :integer # positive_gain :integer # url :string(255) # created_at :datetime not null # updated_at :datetime not null # points :decimal(15, 3) # FactoryBot.define do factory :performance do user distance { Faker::Number.decimal(2, 2) } pace "4:10" positive_gain { Faker::Number.number(3) } url { Faker::Internet.unique.url } factory :performance_with_points do transient do points_set 1000 end after(:create) do |p, evaluator| p.update_attribute(:points, evaluator.points_set) end end end end <file_sep>/db/migrate/20171201222408_add_points_to_performance.rb class AddPointsToPerformance < ActiveRecord::Migration[5.1] def change add_column :performances, :points, :integer Performance.all.each do |p| p.save end end end <file_sep>/app/javascript/packs/main_app.js /* eslint no-console: 0 */ // Run this example by adding <%= javascript_pack_tag 'hello_vue' %> (and // <%= stylesheet_pack_tag 'hello_vue' %> if you set extractStyles to true // in config/webpack/loaders/vue.js) to the head of your layout file, // like app/views/layouts/application.html.erb. // All it does is render <div>Hello Vue</div> at the bottom of the page. import Vue from 'vue' import App from '../app.vue' import BootstrapVue from 'bootstrap-vue' import VueRouter from 'vue-router' import bFormSlider from 'vue-bootstrap-slider'; import VueNumeric from 'vue-numeric' import format from 'number-format.js' import moment from 'moment-timezone'; moment.locale('it'); import 'bootstrap-vue/dist/bootstrap-vue.css'; import '../styles/style.scss'; import 'bootstrap-slider/dist/css/bootstrap-slider.css'; import {icon} from 'vue-fontawesome'; Vue.use(BootstrapVue); Vue.use(VueRouter); Vue.use(bFormSlider); Vue.use(VueNumeric); Vue.component('vf-icon', icon); Vue.filter('distance_format', function (value) { if (!value) return ''; return format( "0,00", parseFloat(value)); }); Vue.filter('points_format', function (value) { if (!value) return ''; return format( "0,000", parseFloat(value)); }); Vue.filter('timezone', function (value,) { if (!value) return ''; return moment(value).tz('Europe/Rome') }); Vue.filter('time_format', function (value,format='l') { if (!value) return ''; return value.format(format); }); Vue.filter('calendar', function (value,) { if (!value) return ''; return value.calendar() }); document.addEventListener('DOMContentLoaded', () => { document.body.appendChild(document.createElement('main_app')) const app = new Vue(App).$mount('main_app') console.log(app) }); <file_sep>/app/models/match.rb # == Schema Information # # Table name: matches # # id :integer not null, primary key # challenged_id :integer # challenger_id :integer # status :integer # points :integer # created_at :datetime not null # updated_at :datetime not null # challenger_p_id :integer # challenged_p_id :integer # judge_id :integer # winner_id :integer # looser_id :integer # note :text(65535) # class Match < ApplicationRecord belongs_to :challenged, :class_name => "User" belongs_to :challenger, :class_name => "User" belongs_to :looser, :class_name => "User", required: false belongs_to :winner, :class_name => "User", required: false belongs_to :challenged_performance, :class_name => 'Performance', foreign_key: 'challenged_p_id', required: false belongs_to :challenger_performance, :class_name => 'Performance', foreign_key: 'challenger_p_id', required: false belongs_to :judge, class_name: 'User', required: false validates :status, :challenged, :challenger, :points, :presence => true validates :judge, :presence => true, if: -> {approved? or disapproved?} validates :looser, :winner, :presence => true, if: -> {(approved? and !is_drawn?) or (timeouted? and !(challenged_performance.nil? and challenger_performance.nil?))} before_validation :set_defaults validate :correct_rank_position, on: :create validate :max_as_challenged_or_challenger, on: :create validate :check_time_limits, on: :create validate :one_match_at_time, on: :create validate :cant_be_the_same_person, on: :create after_create :email_notify_creation after_save :change_status after_save :check_status_change enum status: { wait: 0, approved: 1, timeouted: 2, approval_waiting: 3, disapproved: 4 } scope :open_matches, -> {where(status: [Match.statuses[:wait], Match.statuses[:approval_waiting]])} #Data in cui non la sfida scade def expiration_date self.created_at + RunnersBikers::MATCH_DURATION end ## # Ritorna true quando il match è patta def is_drawn? if challenged_performance and challenger_performance return challenged_performance.points == challenger_performance.points end false end def set_looser_winner if self.approved? if challenged_performance.points != challenger_performance.points if challenged_performance.points > challenger_performance.points self.winner = challenged self.looser = challenger else self.winner = challenger self.looser = challenged end end end if self.timeouted? if challenged_performance.nil? and !challenger_performance.nil? self.winner = challenger self.looser = challenged end if !challenged_performance.nil? and challenger_performance.nil? self.winner = challenged self.looser = challenger end end end def winner_performance if winner_id == challenger_id challenger_performance else challenged_performance end end def looser_performance if looser_id == challenger_id challenger_performance else challenged_performance end end def set_looser_winner! set_looser_winner save! end ## # Valida il match def approve(judge) return false unless judge.is_judge? Match.transaction do self.judge = judge self.status = :approved set_looser_winner save! self.update_rank end email_notify_approve_disapprove true end ## # Disapprova il match def disapprove(judge) #Per il momento sembra che non ci sia questa situazione return false unless judge.is_judge? self.judge = judge self.status = :disapproved save! email_notify_approve_disapprove true end ## # Controllo se il match è uscito dal tempo massimo def outdated? expiration_date < Time.now end ## # Check per tutti i match in esecuzione se ci sono alcuni fuori tempo def self.check_timeouts self.wait.each do |m| m.check_timeouts end end ## # Metodo chiamato singolarmente sul match def check_timeouts if self.outdated? Match.transaction do self.status = :timeouted self.set_looser_winner self.save! self.update_rank end self.email_notify_outdated end end def update_rank if self.looser and self.winner self.winner.update_points self.looser.update_points User.update_rank end end def email_notify_creation MatchNotifierMailer.notify_creation(self, to: 'challenger').deliver_later(wait: 1.seconds) MatchNotifierMailer.notify_creation(self, to: 'challenged').deliver_later(wait: 1.seconds) end def email_notify_approval_waiting MatchNotifierMailer.notify_approval_waiting(self, to: 'challenger').deliver_later(wait: 1.seconds) MatchNotifierMailer.notify_approval_waiting(self, to: 'challenged').deliver_later(wait: 1.seconds) end def email_notify_approve_disapprove MatchNotifierMailer.notify_approve_disapprove(self, to: 'challenger').deliver_later(wait: 1.seconds) MatchNotifierMailer.notify_approve_disapprove(self, to: 'challenged').deliver_later(wait: 1.seconds) end def email_notify_outdated MatchNotifierMailer.notify_outdated(self, to: 'challenger').deliver_later(wait: 1.seconds) MatchNotifierMailer.notify_outdated(self, to: 'challenged').deliver_later(wait: 1.seconds) end def notify_judges User.with_role(:judge).each do |j| MatchNotifierMailer.notify_judge(self.reload, j).deliver_later(wait: 1.seconds) end end private def set_defaults self.status = :wait if self.status.nil? end def correct_rank_position self.errors.add(:challenged, :to_low_in_rank) if self.challenger.rank - 3 > self.challenged.rank self.errors.add(:challenged, :to_high_in_rank) if self.challenger.rank + 3 < self.challenged.rank end def check_time_limits self.errors.add(:created_at, :to_early_for_creation, min_time: RunnersBikers::TIME_TO_START_CHALLENGES) if Time.now < RunnersBikers::TIME_TO_START_CHALLENGES self.errors.add(:created_at, :timout_for_creation, max_time: RunnersBikers::MAX_TIME_FOR_START_CHALLENGES) if Time.now > RunnersBikers::MAX_TIME_FOR_START_CHALLENGES end def max_as_challenged_or_challenger if self.challenger.matches_as_challenger.count >= RunnersBikers::MAX_AS_CHALLENGER self.errors.add(:challenger, :max_matches_as_challenger, max: RunnersBikers::MAX_AS_CHALLENGER) end if self.challenged.matches_as_challenged.count >= RunnersBikers::MAX_AS_CHALLENGED self.errors.add(:challenged, :max_matches_as_challenged, max: RunnersBikers::MAX_AS_CHALLENGED) end end def one_match_at_time if self.challenger.open_matches.count > 0 self.errors.add(:challenger, :has_already_a_match) end if self.challenged.open_matches.count > 0 self.errors.add(:challenged, :has_already_a_match) end end def cant_be_the_same_person if self.challenger == self.challenged self.errors.add(:challenger, :cant_be_the_same_person) self.errors.add(:challenged, :cant_be_the_same_person) end end ## # Rispetto alla situazione del match cambia lo status def change_status if wait? and challenged_performance and challenger_performance self.approval_waiting! notify_judges end end def check_status_change if saved_change_to_status? notify_judges end end end <file_sep>/app/models/user.rb # == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0), not null # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # provider :string(255) # uid :string(255) # api_token :string(255) # first_name :string(255) # last_name :string(255) # image :string(255) # created_at :datetime not null # updated_at :datetime not null # rank :integer # total_points :decimal(15, 3) default(0.0) # username :string(255) # confirmation_token :string(255) # confirmed_at :datetime # confirmation_sent_at :datetime # unconfirmed_email :string(255) # class User < ApplicationRecord rolify # Include default devise modules. Others available are: # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable #, omniauth_providers: [:strava, :facebook] attribute :referal_points, :integer, default: 0 validates :rank, :presence => true, numericality: {greater_than: 0} validates :total_points, :presence => true, numericality: {greater_than_or_equal_to: 0} # validates :username, :presence => { allow_blank: false }, uniqueness: true validates :first_name, :last_name, :presence => true validate :check_max_registration validates :referal_points, numericality: {greater_than_or_equal_to: 0, only_integer: true} after_create :assign_default_role before_validation :set_rank has_many :performances has_many :matches_as_challenger, class_name: 'Match', foreign_key: :challenger_id has_many :matches_as_challenged, class_name: 'Match', foreign_key: :challenged_id has_many :matches_as_winner, class_name: 'Match', foreign_key: :winner_id has_many :matches_as_looser, class_name: 'Match', foreign_key: :looser_id def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.password = <PASSWORD>] case auth.provider.to_sym when :strava user.first_name = auth.info.first_name # assuming the user model has a name user.last_name = auth.info.last_name # assuming the user model has a name user.image = auth.extra.raw_info.image # assuming the user model has an image user.api_token = auth.credentials.token when :facebook user.first_name = auth.info.first_name user.last_name = auth.info.last_name user.image = auth.info.image user.api_token = auth.credentials.token else raise auth.inspect end # If you are using confirmable and the provider(s) you use validate emails, # uncomment the line below to skip the confirmation emails. #user.skip_confirmation! end end def update_points points = self.performances.reload.sum(:points) Rails.logger.debug {"Punti per performances #{points}"} points += self.matches_as_winner.reload.sum(:points) Rails.logger.debug {"Punti con sfide vinte #{points}"} points -= self.matches_as_looser.reload.sum(:points) Rails.logger.debug {"Punti con sfide perse #{points}"} points += self.referal_points.to_i Rails.logger.debug {"Punti con referals #{points}"} self.update_attributes(total_points: points) end def self.update_rank counter = 1 User.order(:total_points => :desc).each do |u| u.update_attributes(rank: counter) counter += 1 end end def open_matches matches_as_challenger.open_matches + matches_as_challenged.open_matches end # questa istanza può sfidate l'utente passato come parametro? def machable(user) logger.debug {"matches_0.5"} return false if Time.now > RunnersBikers::MAX_TIME_FOR_START_CHALLENGES return false if Time.now < RunnersBikers::TIME_TO_START_CHALLENGES logger.debug {"matches_1"} return false if user.id == self.id logger.debug {"matches_1.2"} return false if self.matches_as_challenger.where(:challenged => user).count > 0 logger.debug {"matches_2"} return false if self.open_matches.length > 0 logger.debug {"matches_3"} return false if self.matches_as_challenger.count >= RunnersBikers::MAX_AS_CHALLENGER logger.debug {"matches_4"} return false if self.total_points == 0 logger.debug {"matches_5"} return false if user.total_points == 0 logger.debug {"matches_6"} if self.rank - 3 > user.rank or self.rank + 3 < user.rank return false end logger.debug {"matches_7"} return false if user.open_matches.length > 0 logger.debug {"matches_8"} return false if user.matches_as_challenged.count >= RunnersBikers::MAX_AS_CHALLENGED logger.debug {"matches_9"} return true end def set_as_judge self.add_role(:judge) end def to_s(format: "%{username}") format % self.attributes.deep_symbolize_keys end def full_name to_s(format: "%{first_name} %{last_name}") end ## # Valida il match def approve(match) return false unless self.is_judge? match.approve(self) end ## # Disapprova il match def disapprove(match) return false unless self.is_judge? match.disapprove(self) end private def assign_default_role self.add_role(:newuser) if self.roles.blank? end def set_rank self.rank = User.count + 1 if self.rank.blank? end def check_max_registration if Time.now >= RunnersBikers::MAX_ISCRIZIONE and !self.persisted? self.errors.add(:base, :max_iscrizione_superata, max_time: I18n.l(RunnersBikers::MAX_ISCRIZIONE, format: :short)) end end end <file_sep>/db/migrate/20180524113416_add_column_referal_points_to_user.rb class AddColumnReferalPointsToUser < ActiveRecord::Migration[5.1] def change add_column :users, :referal_points, :integer, default: 0 end end <file_sep>/spec/models/user_spec.rb # == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0), not null # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # provider :string(255) # uid :string(255) # api_token :string(255) # first_name :string(255) # last_name :string(255) # image :string(255) # created_at :datetime not null # updated_at :datetime not null # rank :integer # total_points :decimal(15, 3) default(0.0) # username :string(255) # confirmation_token :string(255) # confirmed_at :datetime # confirmation_sent_at :datetime # unconfirmed_email :string(255) # require 'rails_helper' RSpec.describe User, type: :model do describe "can match" do it "same_user" do user = create(:user) expect(user.machable(user)).to be_falsey end it "vs users" do userTOP = create(:user) create(:performance, distance: 10, user: userTOP) user1 = create(:user) create(:performance, distance: 9, user: user1) user2 = create(:user) create(:performance, distance: 8, user: user2) user3 = create(:user) create(:performance, distance: 7, user: user3) challenger = create(:user) create(:performance, distance: 6, user: challenger) user4 = create(:user) create(:performance, distance: 5, user: user4) user5 = create(:user) create(:performance, distance: 4, user: user5) user6 = create(:user) create(:performance, distance: 3, user: user6) userBAD = create(:user) create(:performance, distance: 2, user: userBAD) expect(challenger.machable(userTOP)).to be_falsey expect(challenger.machable(user1)).to be_truthy expect(challenger.machable(user2)).to be_truthy expect(challenger.machable(user3)).to be_truthy expect(challenger.machable(user4)).to be_truthy expect(challenger.machable(user5)).to be_truthy expect(challenger.machable(user6)).to be_truthy expect(challenger.machable(userBAD)).to be_falsey end it "user with active match" do m = create(:match) expect(create(:performance).user.machable(m.challenger)).to be_falsey expect(create(:performance).user.machable(m.challenged)).to be_falsey end it "usesr with 3 challanged matches" do user = create(:user) RunnersBikers::MAX_AS_CHALLENGER.times do create(:completed_approved_match, challenger: user) user.reload end expect(create(:performance_with_points, points_set: user.total_points).user.machable(user)).to be_truthy expect(user.machable(create(:performance).user)).to be_falsey end it "user with3 challengered matches" do user = create(:user) RunnersBikers::MAX_AS_CHALLENGED.times do create(:completed_approved_match, challenged: user) user.reload end expect(create(:user).machable(user)).to be_falsey expect(user.machable(create(:performance_with_points, points_set: user.total_points).user)).to be_truthy end it "user with 0 points" do expect(create(:user).machable(create(:user))).to be_falsey expect(create(:performance).user.machable(create(:user))).to be_falsey expect(create(:user).machable(create(:performance).user)).to be_falsey expect(create(:performance).user.machable(create(:performance).user)).to be_truthy end it "user already matched"do m = create(:completed_approved_match) expect(m.challenger.machable(m.challenged)).to be_falsey expect(m.challenged.machable(m.challenger)).to be_truthy end it " too early for match "do Timecop.travel(RunnersBikers::TIME_TO_START_CHALLENGES-1.minute) do expect(create(:performance_with_points).user.machable(create(:performance_with_points).user)).to be_falsey end Timecop.travel(RunnersBikers::TIME_TO_START_CHALLENGES+1.second) do expect(create(:performance_with_points).user.machable(create(:performance_with_points).user)).to be_truthy end end it " too late for match "do Timecop.travel(RunnersBikers::MAX_TIME_FOR_START_CHALLENGES-1.minute) do expect(create(:performance_with_points).user.machable(create(:performance_with_points).user)).to be_truthy end Timecop.travel(RunnersBikers::MAX_TIME_FOR_START_CHALLENGES+1.second) do expect(create(:performance_with_points).user.machable(create(:performance_with_points).user)).to be_falsey end end end end <file_sep>/app/graphql/mutations/delete_performance.rb Mutations::DeletePerformance = GraphQL::Relay::Mutation.define do name "DeletePerformance" return_field :result, Types::OperationResultType input_field :id, !types.ID, "performance_id" resolve ->(obj, args, ctx) { @obj = Performance.find(args.id) @obj.destroy {result: @obj} } end <file_sep>/app/graphql/types/ranking_type.rb Types::RankingType = GraphQL::ObjectType.define do name "Ranking" field :id, types.Int field :total_distance, types.Int, "Total Run distance for user" field :total_positive_gain, types.Int, "Total Positive Gain run for user" field :rank, types.Int, "Ranking in the challenger" field :username, types.String field :first_name, types.String field :last_name, types.String field :total_points, types.Int, "Total points in the match" field :challenged, types.Boolean, "If the user is inside a challenge" do resolve ->(obj, args, ctx) { obj.open_matches.length > 0 } end field :machable, types.Boolean, "If the user can be matched" do resolve ->(obj, args, ctx) { ctx[:current_user].machable(obj) } end field :max_lose_points, types.Int, "Max points to loose in a match" do resolve ->(obj, args, ctx) { obj.max_lose_points(ctx[:current_user]) } end field :show_performances, types.Boolean, "Can be shown the performances of user" do resolve -> (obj, args, ctx) { UserPolicy.new(ctx[:current_user], obj).show_performances? } end field :user, Types::UserType, "posso estrapolare direttamente i dati dell'utente" do resolve ->(obj, args, ctx) { obj.becomes(User) } end end <file_sep>/app/javascript/graphql/matches.js import gql from 'graphql-tag' export const GET_MATCHES = gql`query matches { matches { id challenger { first_name last_name } challenged { first_name last_name } challenged_performance{ id user_id distance pace positive_gain url } challenger_performance{ id user_id distance pace positive_gain url } status expiration_date points approvable note_updatable note } }` export const UPDATE_MATCH = gql`mutation updateMatch($id: ID!, $note: String) { update_match(input: {id: $id, note: $note}) { result { result errors{ field message } } } } ` export const APPROVE_MATCH = gql`mutation approveMatch($id: ID!) { approve_match(input: {id: $id}) { result { result errors{ field message } } } } `
12a2c16aefa164dded76e19ac3964f17af409331
[ "Markdown", "JavaScript", "Ruby" ]
60
Ruby
oniram88/RunnersBikers
8ffb40262b831ef0ad5cc30ae74f769a73a9ad52
2305ba2779b88718d036eb576e17a79ec1e819ce
refs/heads/master
<file_sep>MATLAB for R Users in Computational Finance Demo 1 - Data Import & Exploration This example contains the files necessary to demonstrate interactively importing and visually exploring data in MATLAB. priceData.xlsx contains electricity market prices for the New England region. These can be imported using the MATLAB import wizard. The electricity prices can then be visualized, brushed and explored. The script samplePlot contains a sample visualization that demonstrates exploring dynamic time series plots and data and axes linking between different plots. Products Required: MATLAB Copyright 2013 MathWorks, Inc.<file_sep>## Sample portfolio optimization analysis # Copyright 2013 MathWorks, Inc. ## Download and clean up time-series data tryCatch({ # Define symbol list symList <- c('SPY','EEM','TLT','COY','GSP','RWR'); # Get symbol data, get data from 5 years ago to current date require(quantmod) getSymbols(symList, index.class='Date', return.class='timeSeries', from=as.Date('2009-10-01'), to=as.Date('2013-06-24')); # verify that the downloaded data is in an OHLC format rapply(sapply(symList,as.symbol),is.OHLC) # combine and synchronize adjusted closes for each symbol # 6 is the column no. for "adjusted closing price" adjClose<-cbind(SPY[,6],EEM[,6],TLT[,6],COY[,6],GSP[,6],RWR[,6]) # for(sym in sapply(symList,as.symbol)) adjClose<-cbind(adjClose,eval(sym)[,6]) # remove the ".Adjusted" column labels colnames(adjClose)<-strsplit(colnames(adjClose),".Adjusted") # clean up workspace so only combined data remains rm(list=symList) rm(SPY);rm(sym) # Save workspace for easy loading later save.image("RTSData") }, warning = function(err) { print("Loading data due to datafeed failure") load("C:/Work/Seminar/MATLAB for R Users/RExamples/RTSData") }, error = function(err) { print("Loading data due to datafeed failure") load("C:/Work/Seminar/MATLAB for R Users/RExamples/RTSData") }) # Convert prices to returns, and remove NAs adjReturns <- diff(log(adjClose)) adjReturns <- na.omit(adjReturns) # Compute covariance matrix mu <- colMeans(adjReturns) sigma <- cov(adjReturns) require('fPortfolio') require(Rglpk) # this is the GNU Linear Programming Kit rtnData <- 100 * returns(adjClose, method="discrete") ## CVaR portfolio optimization spec=portfolioSpec() setType(spec)<-"CVaR" setAlpha(spec)<-0.05 setSolver(spec)="solveRglpk" ptm <- proc.time(); pfolio<-minriskPortfolio(data=rtnData,spec=spec,constraints="LongOnly"); proc.time() - ptm print(pfolio) <file_sep>## Perform quantile regression in R # Copyright 2013 MathWorks, Inc. ## Set required packages require(timeSeries) packageExist<-require(quantmod) if(!packageExist){install.packages("quantmod")} packageExist<-require(quantreg) if(!packageExist){install.packages("quantreg")} ## Prepare/pre-process data stkRetn<-diff(Stock)/Stock[-length(Stock)] idxRetn<-diff(Index)/Index[-length(Index)] DataSet<-cbind(timeSeries(idxRetn), stkRetn) colnames(DataSet)<-c('Index','Stock') ## Run quantile regression fit<-rq(Stock~Index, tau=Tau, data=DataSet) coef <- fit$coefficients<file_sep>Call R from MATLAB using RCaller This example demonstrates calling R from MATLAB using the RCaller Java package. Step through the sections of QuantileRegression.m to see the connectivity in action. RCaller: https://code.google.com/p/rcaller/ Setup: You will need to change the location of the R package installation in the script. Required Products: MATLAB (Optional) Datafeed Toolbox (Optional) Statistics Toolbox Other requirements: R installation Copy the RCaller JAR file (RCaller-2.1.1-SNAPSHOT.jar, for example) to the same folder as this example Copyright 2013 MathWorks, Inc.<file_sep>MATLAB for R Users in Computational Finance Demo 2 - Prototyping and Analysis This example demonstrates creating a custom time-series model to simulate the returns for a correlated set of asset classes using a copula and fat-tailed marginals. The returns are used to compute the risk of a sample portfolio and as an input to a portfolio optimization to find optimal mean-CVaR portfolios. The main script to run is copulaVaR This example is based, in part, on the shipping demo in Econometrics toolbox titled "Using Extreme Value Theory and Copulas to Evaluate Market Risk" Timing comparison: An R script is provided that performs just the portfolio optimization component using fPortfolio in R. This can be used to compare the time it takes to compute optimal CVaR portfolios in MATLAB/Financial Toolbox and R/fPortfolio Products Required: MATLAB, Statistics Toolbox, Optimization Toolbox, Financial Toolbox Optional products: Datafeed Toolbox Copyright 2013 MathWorks, Inc.
5a5add96c88be6f38e4953c0424b549cea10de5e
[ "Text", "R" ]
5
Text
mura5726/copula_matlab
7049cee5c1fa9b1b7ce9a70bde63c1ae0aae4aff
e62d67825b1eed461f4ecfb0d35000cf2bf26809
refs/heads/master
<repo_name>AiverReaver/stackoverflow_clone<file_sep>/stackoverflow_frontend/src/components/Navbar/Navbar.js import React from 'react'; import { connect } from 'react-redux'; import { Input, Menu, Button } from 'semantic-ui-react'; import { Link, withRouter } from 'react-router-dom'; import { fetchposts, logoutUser } from '../../actions'; class Navbar extends React.Component { state = { activeItem: 'home' }; handleItemClick = (e, { name }) => { this.props.history.push('/'); this.setState({ activeItem: name }); }; onSearch = e => { this.props.fetchposts(1, e.target.value); }; onLogoutClicked = () => { this.props.logoutUser(); }; renderUserButtons = () => { const { signed_in } = this.props; if (signed_in) { return ( <Menu.Menu position="right"> <Menu.Item> <Button onClick={this.onLogoutClicked}>Log out</Button> </Menu.Item> </Menu.Menu> ); } else { return ( <Menu.Menu position="right"> <Menu.Item> <Link to="/login"> <Button>Log in</Button> </Link> </Menu.Item> <Menu.Item> <Link to="/register"> <Button primary>Sign up</Button> </Link> </Menu.Item> </Menu.Menu> ); } }; render() { const { activeItem } = this.state; return ( <Menu secondary> <Menu.Item name="home" active={activeItem === 'home'} onClick={this.handleItemClick} /> <Menu.Item> <Input loading={this.props.isLoading} icon="search" onChange={this.onSearch} placeholder="Search..." /> </Menu.Item> {this.renderUserButtons()} </Menu> ); } } const mapStateToProps = ({ user, postsReducer }) => { return { signed_in: user.signed_in, isLoading: postsReducer.isQuery }; }; export default connect( mapStateToProps, { fetchposts, logoutUser } )(withRouter(Navbar)); <file_sep>/stackoverflow_frontend/src/reducers/index.js import { combineReducers } from 'redux'; import postsReducer from './postsReducer'; import userReducer from './userReducer'; import tagsReducer from './tagsReducer'; export default combineReducers({ postsReducer, user: userReducer, tags: tagsReducer }); <file_sep>/stackoverflow_backend/app/Http/Resources/Post.php <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class Post extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'description' => $this->when($this->description != '', $this->description), 'created_at' => $this->created_at, 'updated_at' => $this->when($this->updated_at != '', $this->updated_at), 'tags' => Tag::collection($this->tags), 'comments' => Comment::collection($this->whenLoaded('comments')), 'answers' => Answer::collection($this->whenLoaded('answers')), 'owner' => new User($this->user), 'answers_count' => $this->answers->count() ]; } } <file_sep>/stackoverflow_backend/app/Http/Controllers/PostsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Resources\Post as PostResource; use App\Post; use App\Tag; class PostsController extends Controller { public function index() { $posts = Post::select('title', 'created_at', 'user_id', 'id')->orderBy('created_at', 'desc'); if (request()->query('searchQuery') != '') { $posts = $posts->where('title', 'like', '%' . request()->query('searchQuery') . '%'); } $posts = $posts->paginate(15); return PostResource::collection($posts); } public function show(Post $post) { $post = $post->load(['comments', 'answers']); return new PostResource($post); } public function store() { $post = auth()->user()->posts()->create($this->validateRequest()); if ($tags = request('tags')) { $tags = Tag::whereIn('name', $tags)->get(); $post->addTagsToPost($tags); } return new PostResource($post); } public function update(Request $request, Post $post) { $post->update($request->toArray()); $post->save(); return response('', 200); } public function delete(Post $post) { $post->delete(); return response('', 204); } protected function validateRequest() { return request()->validate([ 'title' => 'required', 'description' => 'required', 'tags' => 'required' ]); } } <file_sep>/stackoverflow_backend/app/Http/Controllers/TagsController.php <?php namespace App\Http\Controllers; use App\Http\Resources\Tag as TagResource; use Illuminate\Http\Request; use App\Tag; class TagsController extends Controller { public function getTags(Request $request) { $tags = Tag::where('name', '')->get(); if ($request->query('searchQuery') != '') { $tags = Tag::where('name', 'like', '%' . $request->get('searchQuery') . '%')->get(); } return TagResource::collection($tags); } } <file_sep>/stackoverflow_backend/app/Http/Controllers/AnswersController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use App\Answer; use App\Http\Resources\Answer as AnswerResource; class AnswersController extends Controller { public function store(Post $post) { $answer = new Answer($this->validateRequest()); $answer->user_id = auth()->id(); $answer = $post->answers()->save($answer); return new AnswerResource($answer); } protected function validateRequest() { return request()->validate([ 'body' => 'required' ]); } } <file_sep>/stackoverflow_frontend/src/components/PostsList/PostsList.js import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { Item, Loader, Pagination, Button } from 'semantic-ui-react'; import PostItem from '../PostItem/PostItem'; import { fetchposts } from '../../actions'; class PostsList extends React.Component { componentDidMount() { this.props.fetchposts(); } handlePaginationChange = (e, { activePage }) => { this.props.fetchposts(activePage, this.props.posts.searchQuery); }; render = () => { const { posts } = this.props; if (posts !== undefined) { const postItem = posts.data.map(post => { return <PostItem key={post.id} post={post} />; }); return ( <div> <Link exact="true" to="/question/ask"> <Button primary floated="right"> Ask Question </Button> </Link> <Pagination boundaryRange={0} defaultActivePage={posts.meta.current_page} siblingRange={2} onPageChange={this.handlePaginationChange} totalPages={posts.meta.last_page} /> <Item.Group divided>{postItem}</Item.Group> </div> ); } return <Loader active>Loading</Loader>; }; } const mapStateToProps = ({ postsReducer }) => { return { posts: postsReducer.posts }; }; export default connect( mapStateToProps, { fetchposts } )(PostsList); <file_sep>/stackoverflow_backend/routes/api.php <?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post('/auth/login', 'AuthController@login'); Route::group(['middleware' => ['auth:api']], function () { Route::post('/posts', 'PostsController@store'); Route::put('/posts/{post}', 'PostsController@update'); Route::delete('/posts/{post}', 'PostsController@delete'); Route::post('/posts/{post}/comments', 'CommentsController@storePostComment'); Route::post('/posts/{post}/answers', 'AnswersController@store'); Route::post('/answers/{answer}/comments', 'CommentsController@storeAnswerComment'); Route::post('/tags', 'TagsController@store'); Route::post('/logout', 'AuthController@logout'); }); Route::get('/tags', 'TagsController@getTags'); Route::get('/posts', 'PostsController@index'); Route::get('/posts/{post}', 'PostsController@show'); Route::post('/register', 'AuthController@register'); <file_sep>/stackoverflow_frontend/src/components/PostDetail/PostDetail.js import React from 'react'; import { connect } from 'react-redux'; import { Header, Label, Loader, Divider } from 'semantic-ui-react'; import { fetchPostDetails, isLognedIn } from '../../actions'; import CommentList from '../CommentList/CommentList'; import CreateAnswer from '../CreateAnswer/CreateAnswer'; import Moment from 'react-moment'; import CreateComment from '../CreateComment/CreateComment'; class PostDetail extends React.Component { state = { body: '' }; componentDidMount() { this.props.fetchPostDetails(this.props.match.params.id); } redirctIfNotLoggedIn = () => { this.props.isLognedIn(); if (!this.props.signed_in) { this.props.history.push('/login'); } } handleChange = (e, { name, value }) => this.setState({ [name]: value }); render() { const { post } = this.props; let tags = []; if (post === undefined) { return <Loader active>Loading</Loader>; } const numOfAnswers = post.data.answers.length; tags = post.data.tags.map((tag, index) => ( <Label key={index}>{tag.name}</Label> )); const answers = post.data.answers.map(answer => { return ( <div key={answer.id}> <p> {answer.body} - answered{' '} <Moment fromNow>{answer.created_at}</Moment> by{' '} {answer.owner.name} </p> <CommentList comments={answer.comments} /> <CreateComment isForPost={false} id={answer.id} redirctIfNotLoggedIn={this.redirctIfNotLoggedIn } placeholder="Use comments to ask for more information or suggest improvements. Avoid comments like “+1” or “thanks”." /> <Divider /> </div> ); }); return ( <div> <Header as="h2" dividing> {post.data.title} </Header> <Header.Content>{post.data.description}</Header.Content> {tags} <Header className="comments-custom" as="h5"> Comments </Header> <Header.Content> <CommentList comments={post.data.comments} /> <CreateComment isForPost={true} id={post.data.id} redirctIfNotLoggedIn={this.redirctIfNotLoggedIn } placeholder="Use comments to ask for more information or suggest improvements. Avoid answering questions in comments." /> </Header.Content> <Header as="h4">{numOfAnswers} Answers</Header> {answers} <CreateAnswer postId={this.props.post.data.id} />; </div> ); } } const mapStateToProps = ({ postsReducer, user }) => { return { post: postsReducer.postDetail, signed_in: user.signed_in }; }; const mapActionsToProps = { fetchPostDetails, isLognedIn }; export default connect( mapStateToProps, mapActionsToProps )(PostDetail); <file_sep>/stackoverflow_backend/app/Http/Controllers/CommentsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Resources\Comment as CommentResource; use App\Comment; use App\Post; use App\Answer; class CommentsController extends Controller { public function storePostComment(Post $post) { $comment = new Comment($this->validateRequest()); $comment->user_id = auth()->id(); $comment = $post->comments()->save($comment); return new CommentResource($comment); } public function storeAnswerComment(Answer $answer) { $comment = new Comment($this->validateRequest()); $comment->user_id = auth()->id(); $answer->comments()->save($comment); return new CommentResource($comment); } protected function validateRequest() { return request()->validate([ 'body' => 'required' ]); } } <file_sep>/stackoverflow_backend/database/seeds/PostTableSeeder.php <?php use Illuminate\Database\Seeder; class PostTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(App\Post::class, 50)->create()->each(function ($post) { $tags = App\Tag::all()->random(rand(2, 5)); $post->addTagsToPost($tags); }); } } <file_sep>/stackoverflow_frontend/src/components/PostItem/PostItem.js import React from 'react'; import { Link } from 'react-router-dom'; import { Item, Label } from 'semantic-ui-react'; import Moment from 'react-moment'; class PostItem extends React.Component { render() { const { post } = this.props; const tags = post.tags.map((tag, index) => { return <Label key={index}>{tag.name}</Label>; }); return ( <Item> <Item.Content> <Item.Header> <Link to={`questions/${post.id}`}>{post.title}</Link> </Item.Header> <Item.Meta> {post.answers_count} answers</Item.Meta> <Item.Extra> <p className="ui primary right floated "> asked <Moment fromNow>{post.created_at}</Moment>{' '} {post.owner.name} </p> {tags} </Item.Extra> </Item.Content> </Item> ); } } export default PostItem; <file_sep>/stackoverflow_frontend/src/components/CreateComment/CreateComment.js import React from 'react'; import { connect } from 'react-redux'; import { Button, Form, TextArea } from 'semantic-ui-react'; import { createPostComment, createAnswerComment, isLognedIn } from '../../actions'; class CreateComment extends React.Component { state = { isAddComment: false, body: '' }; onCommentButtonClicked = () => { this.props.redirctIfNotLoggedIn(); this.setState({ isAddComment: true }); }; handleChange = (e, { name, value }) => this.setState({ [name]: value }); handleSubmitComment = () => { const {isForPost, id, createPostComment, createAnswerComment} = this.props; if (isForPost) { createPostComment({ ...this.state, id }); } else { createAnswerComment({ ...this.state, id }); } this.setState({ isAddComment: false }); }; renderCommentForm = (isForPost, id) => { if (this.state.isAddComment) { return ( <Form onSubmit={() => this.handleSubmitComment()}> <Form.Group> <Form.Field name="body" control={TextArea} width="8" placeholder={this.props.placeholder} onChange={this.handleChange} /> <Form.Button primary content="Add Comment" /> </Form.Group> </Form> ); } return ( <Button basic color="blue" content="add a comment" size="mini" onClick={this.onCommentButtonClicked} /> ); }; render() { return this.renderCommentForm(); } } export default connect( null, { createAnswerComment, createPostComment, isLognedIn } )(CreateComment); <file_sep>/stackoverflow_frontend/src/components/CreateAnswer/CreateAnswer.js import React from 'react'; import { connect } from 'react-redux'; import { Header, Form, Button, TextArea } from 'semantic-ui-react'; import { createPostAnswer } from '../../actions'; class CreateAnswer extends React.Component { state = { body: '' }; handleSubmit = () => { this.props.createPostAnswer({ ...this.state, id: this.props.postId }); }; handleChange = (e, { name, value }) => this.setState({ [name]: value }); render() { return ( <div> <Header as="h4"> Your Answer</Header> <Form onSubmit={this.handleSubmit}> <Form.Field name="body" control={TextArea} width="8" onChange={this.handleChange} /> <Button type="submit" primary content="Post Your Answer" /> </Form> </div> ); } } export default connect( null, { createPostAnswer } )(CreateAnswer); <file_sep>/stackoverflow_backend/app/User.php <?php namespace App; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function posts() { return $this->hasMany(Post::class); } public function answers() { return $this->hasMany(Answer::class); } public function posts_comments() { return $this->hasManyThrough(Comment::class, Post::class); } public function answer_comments() { return $this->hasManyThrough(Comment::class, Answer::class); } public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } public function setPasswordAttribute($password) { if (!empty($password)) { $this->attributes['password'] = <PASSWORD>($password); } } } <file_sep>/stackoverflow_frontend/src/actions/types.js export const FETCH_POSTS = 'FETCH_POSTS'; export const POST_CREATED = 'POST_CREATED'; export const FETCH_POSTS_PENDING = 'FETCH_POSTS_PENDING'; export const POST_COMMENT_CREATED = 'POST_COMMENT_CREATED'; export const POST_ANSWER_CREATED = 'POST_ANSWER_CREATED'; export const FETCH_TAGS = 'FETCH_TAGS'; export const FETCH_TAGS_PENDING = 'FETCH_TAGS_PENDING'; export const FETCH_POST_DETAILS = 'FETCH_POST_DETAILS'; export const USER_LOGGED_IN_SUCCESS = 'USER_LOGGED_IN_SUCCESS'; export const USER_LOGGED_IN_FAIL = 'USER_LOGGED_IN_FAIL'; export const USER_REGISTER_SUCCESS = 'USER_REGISTER_SUCCESS'; export const USER_REGISTER_FAIL = 'USER_REGISTER_FAIL'; export const USER_LOGGED_IN = 'USER_LOGGED_IN'; export const USER_NOT_LOGGED_IN = 'USER_NOT_LOGGED_IN'; export const USER_LOGOUT_SUCCESS = 'USER_LOGOUT_SUCCESS'; export const ANSWER_COMMENT_CREATED = 'ANSWER_COMMENT_CREATED'; <file_sep>/stackoverflow_frontend/src/components/CommentList/CommentList.js import React from 'react'; import { Comment } from 'semantic-ui-react'; import Moment from 'react-moment'; class CommentList extends React.Component { componentDidMount() {} render() { const { comments } = this.props; const commentsEle = comments.map((comment, index) => { return ( <Comment key={index}> <Comment.Content> <Comment.Author as="a"> {comment.owner.name} </Comment.Author> <Comment.Metadata> <div> <Moment fromNow>{comment.created_at}</Moment> </div> </Comment.Metadata> <Comment.Text>{comment.body}</Comment.Text> </Comment.Content> </Comment> ); }); return ( <div className="comments-custom"> <Comment.Group size="mini">{commentsEle}</Comment.Group> </div> ); } } export default CommentList; <file_sep>/stackoverflow_frontend/src/App.js import React from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import { Container } from 'semantic-ui-react'; import { connect } from 'react-redux'; import PostsList from './components/PostsList/PostsList'; import Navbar from './components/Navbar/Navbar'; import PostDetail from './components/PostDetail/PostDetail'; import Login from './components/Login/Login'; import Register from './components/Register/Register'; import CreatePost from './components/CreatePost/CreatePost'; import { isLognedIn } from './actions'; import './App.css'; function App(props) { props.isLognedIn(); return ( <div> <BrowserRouter> <Navbar /> <Container> <Route path="/" exact component={PostsList} /> <Route path="/question/ask" exact component={CreatePost} /> <Route path="/questions/:id" exact component={PostDetail} /> <Route path="/login" exact component={Login} /> <Route path="/register" exact component={Register} /> </Container> </BrowserRouter> </div> ); } export default connect( null, { isLognedIn } )(App); <file_sep>/stackoverflow_frontend/src/api/index.js import axios from 'axios'; const instanse = axios.create({ baseURL: 'http://localhost:8000/api', headers: { Authorization: `Bearer ${localStorage.getItem('token')}`, Accept: 'application/json' } }); instanse.interceptors.response.use( function(response) { return response; }, function(error) { if (error.response) { error = error.response.data.message; } else if (error.request) { // console.log(error.request); } else { // console.log('Error', error.message); } return Promise.reject(error); } ); export default instanse; <file_sep>/README.md # stackoverflow clone app Stackoverflow webapp created with laravel and reactjs ## How To Run Clone the project `git clone https://github.com/AiverReaver/stackoverflow_clone.git` ## Backend cd into stakoverflow_backend and run `composer install` And then `php artisan serve` ## Frontend cd into stakoverflow_frontend and run `yarn` or `npm install` And then `yarn start` or `npm run start` ### And now enjoy buggy stackoverflow clone app
e167a685794bc8a46dce31a5e6e0b88bd67375d5
[ "JavaScript", "Markdown", "PHP" ]
20
JavaScript
AiverReaver/stackoverflow_clone
0b5bc32a23d5448e8e63578458a31104df242341
a0a165f8bf504288bfae54cc473dbd46c7dfa19e
refs/heads/master
<repo_name>orckrn/PatientaDB<file_sep>/checkform.cpp #include <QMessageBox> #include "main.h" #include "checkform.h" #include "ui_checkform.h" CheckForm::CheckForm(QWidget *parent) : QWidget(parent), ui(new Ui::CheckForm) { ui->setupUi(this); connect ( ui->saveButton, SIGNAL (clicked()), this, SLOT (onSaveRecordButtonClicked()) ); } void CheckForm::setData(QSqlRecord checkRecord) { checkId = checkRecord.value(Ui::TCheck::CHECK_ID_INDEX).toInt(); patientId = checkRecord.value(Ui::TCheck::PATIENT_ID_INDEX).toInt(); fillPatientData(patientId); ui->tagEdit->setText( checkRecord.value(Ui::TCheck::TAG_INDEX).toString() ); ui->dateEdit->setDate( checkRecord.value(Ui::TCheck::DATE_INDEX).toDate() ); ui->resolutionEdit->setText( checkRecord.value(Ui::TCheck::RESOLUTION_INDEX).toString() ); mode = Ui::Form_Mode::EDIT_RECORD_MODE; } void CheckForm::resetData(int patientId) { this->patientId = patientId; fillPatientData(patientId); ui->tagEdit->setText(""); ui->dateEdit->setDate(QDate::fromString("2000-01-01", Qt::ISODate)); ui->resolutionEdit->setText(""); mode = Ui::Form_Mode::CREATE_RECORD_MODE; } void CheckForm::fillPatientData(int patientId) { QSqlQuery query; QString queryString; queryString = "select * from TPatient where "; queryString += "Id='" + QString::number(patientId) + "'"; query.exec(queryString); query.next(); ui->labelLastName->setText( query.value(Ui::TPatient::LAST_NAME_INDEX).toString() ); ui->labelFirstName->setText( query.value(Ui::TPatient::FIRST_NAME_INDEX).toString() ); ui->labelSecondName->setText( query.value(Ui::TPatient::SECOND_NAME_INDEX).toString() ); ui->labelBirthDate->setText( query.value(Ui::TPatient::BIRTH_DATE_INDEX).toString() ); } void CheckForm::onSaveRecordButtonClicked() { QString errorMessage; QMessageBox::StandardButton reply; QString queryString; QSqlQuery checkQuery; if (ui->tagEdit->text().isEmpty()) { errorMessage += "Метка посещения\n"; } if (ui->resolutionEdit->toPlainText().isEmpty()) { errorMessage += "Резолюция\n"; } if (!errorMessage.isEmpty()) { QMessageBox::critical( this, "Form fields must be defined", errorMessage + "должн(ы) быть определен(ы)" ); return; } switch (mode) { case Ui::Form_Mode::CREATE_RECORD_MODE: { reply = QMessageBox::question( this, "Question", "Вы действительно хотите добавить " + ui->tagEdit->text() + " в базу?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; queryString = "insert into TCheck ("; queryString += "Tag, Date, Patient_Id, Resolution) "; queryString += "values ("; queryString += "'" + ui->tagEdit->text() + "', "; queryString += "'" + ui->dateEdit->date().toString(Qt::ISODate) + "', "; queryString += "'" + QString::number(this->patientId) + "', "; queryString += "'" + ui->resolutionEdit->toPlainText() + "')"; checkQuery.exec(queryString); emit updateCheckTable(); queryString = "select * from TCheck where "; queryString += "First_Name='" + ui->tagEdit->text() + "' and "; queryString += "Birth_Date='" + ui->dateEdit->date().toString(Qt::ISODate) + "' and "; queryString += "Street='" + QString::number(this->patientId) + "'"; checkQuery.exec(queryString); checkQuery.next(); checkId = checkQuery.value(Ui::TCheck::CHECK_ID_INDEX).toInt(); mode = Ui::Form_Mode::EDIT_RECORD_MODE; } break; case Ui::Form_Mode::EDIT_RECORD_MODE: { reply = QMessageBox::question( this, "Question", "Вы действительно хотите обновить " + ui->tagEdit->text() + " в базе?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; queryString = "update TCheck set "; queryString += "Tag='" + ui->tagEdit->text() + "', "; queryString += "Date='" + ui->dateEdit->date().toString(Qt::ISODate) + "', "; queryString += "Resolution='" + ui->resolutionEdit->toPlainText() + "' "; queryString += "where Id='" + QString::number(checkId) + "'"; checkQuery.exec(queryString); emit updateCheckTable(); } break; } } CheckForm::~CheckForm() { delete ui; } <file_sep>/patientform.h #ifndef PATIENTFORM_H #define PATIENTFORM_H #include <QtSql> #include <QWidget> #include "main.h" #include "checkform.h" namespace Ui { class PatientForm; } class PatientForm : public QWidget { Q_OBJECT public: explicit PatientForm(QWidget *parent = nullptr); ~PatientForm(); void setData(QSqlRecord); void resetData(); private: Ui::PatientForm *ui; Ui::Form_Mode mode; QSqlQueryModel *modelChecks; int patientId; CheckForm *checkForm; signals: void updatePatientTable(); private slots: void onSaveRecordButtonClicked(); void onCreateCheckButtonClicked(); void onDeleteCheckButtonClicked(); void onTableDoubleClicked(const QModelIndex &); void onUpdateCheckTable(); }; #endif // PATIENTFORM_H <file_sep>/mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QSqlDatabase> #include <QSqlQueryModel> #include "patientform.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; QSqlDatabase db; QSqlQueryModel *modelPatients; PatientForm *patientForm; private slots: void onTableClicked(const QModelIndex &index); void onTableDoubleClicked(const QModelIndex &index); void onCreateRecordButtonClicked(); void onDeleteRecordButtonClicked(); void onUpdatePatientTable(); void searchOnFirstNameChanged(const QString &text); void searchOnSecondNameChanged(const QString &text); void searchOnLastNameChanged(const QString &text); void searchOnYearChanged(const QString &text); }; #endif // MAINWINDOW_H <file_sep>/patientform.cpp #include <QMessageBox> #include "main.h" #include "patientform.h" #include "ui_patientform.h" PatientForm::PatientForm(QWidget *parent) : QWidget(parent), ui(new Ui::PatientForm) { ui->setupUi(this); modelChecks = new QSqlQueryModel(); connect ( ui->saveButton, SIGNAL (clicked()), this, SLOT (onSaveRecordButtonClicked()) ); connect ( ui->createCheckButton, SIGNAL(clicked()), this, SLOT (onCreateCheckButtonClicked()) ); connect ( ui->deleteCheckButton, SIGNAL(clicked()), this, SLOT (onDeleteCheckButtonClicked()) ); connect ( ui->checkList, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(onTableDoubleClicked(const QModelIndex &)) ); checkForm = new CheckForm; connect( checkForm, SIGNAL (updateCheckTable()), this, SLOT (onUpdateCheckTable()) ); } void PatientForm::setData(QSqlRecord patientRecord) { modelChecks->setQuery( "select * from TCheck where Patient_Id = " + patientRecord.value(Ui::TPatient::PATIENT_ID_INDEX).toString() ); modelChecks->setHeaderData( Ui::TCheck::TAG_INDEX, Qt::Horizontal, QObject::tr("Метка") ); modelChecks->setHeaderData( Ui::TCheck::DATE_INDEX, Qt::Horizontal, QObject::tr("Дата") ); modelChecks->setHeaderData( Ui::TCheck::RESOLUTION_INDEX, Qt::Horizontal, QObject::tr("Резолюция") ); ui->checkList->setModel(modelChecks); ui->checkList->setColumnHidden(Ui::TCheck::CHECK_ID_INDEX, true); ui->checkList->setColumnHidden(Ui::TCheck::PATIENT_ID_INDEX, true); ui->checkList->show(); ui->lastNameEdit->setText( patientRecord.value(Ui::TPatient::LAST_NAME_INDEX).toString() ); ui->firstNameEdit->setText( patientRecord.value(Ui::TPatient::FIRST_NAME_INDEX).toString() ); ui->secondNameEdit->setText( patientRecord.value(Ui::TPatient::SECOND_NAME_INDEX).toString() ); ui->birthDateEdit->setDate( patientRecord.value(Ui::TPatient::BIRTH_DATE_INDEX).toDate() ); ui->streetEdit->setText( patientRecord.value(Ui::TPatient::STREET_INDEX).toString() ); ui->buildingEdit->setValue( patientRecord.value(Ui::TPatient::BUILDING_INDEX).toInt() ); ui->blockEdit->setValue( patientRecord.value(Ui::TPatient::BLOCK_INDEX).toInt() ); ui->apartmentsEdit->setValue( patientRecord.value(Ui::TPatient::APARTMENTS_INDEX).toInt() ); ui->phoneEdit->setText( patientRecord.value(Ui::TPatient::PHONE_NUMBER_INDEX).toString() ); ui->anamnesisEdit->setText( patientRecord.value(Ui::TPatient::ANAMNESIS_INDEX).toString() ); ui->createCheckButton->show(); ui->deleteCheckButton->show(); patientId = patientRecord.value(Ui::TPatient::PATIENT_ID_INDEX).toInt(); mode = Ui::Form_Mode::EDIT_RECORD_MODE; } void PatientForm::resetData() { modelChecks->setQuery(""); ui->checkList->setModel(modelChecks); ui->lastNameEdit->setText(""); ui->firstNameEdit->setText(""); ui->secondNameEdit->setText(""); ui->birthDateEdit->setDate( QDate::fromString("2000-01-01", Qt::ISODate) ); ui->streetEdit->setText(""); ui->buildingEdit->setValue(0); ui->blockEdit->setValue(0); ui->apartmentsEdit->setValue(0); ui->phoneEdit->setText(""); ui->anamnesisEdit->setText(""); ui->createCheckButton->hide(); ui->deleteCheckButton->hide(); mode = Ui::Form_Mode::CREATE_RECORD_MODE; } void PatientForm::onSaveRecordButtonClicked() { QString errorMessage; QString queryString; QSqlQuery patientQuery; QMessageBox::StandardButton reply; if (ui->lastNameEdit->text().isEmpty()) { errorMessage += "Фамилия\n"; } if (ui->firstNameEdit->text().isEmpty()) { errorMessage += "Имя\n"; } if (ui->secondNameEdit->text().isEmpty()) { errorMessage += "Отчество\n"; } if (!errorMessage.isEmpty()) { QMessageBox::critical( this, "Form fields must be defined", errorMessage + "должн(ы) быть определен(ы)" ); return; } switch (mode) { case Ui::Form_Mode::CREATE_RECORD_MODE: { reply = QMessageBox::question( this, "Question", "Вы действительно хотите добавить " + ui->firstNameEdit->text() + " " + ui->secondNameEdit->text() + " " + ui->lastNameEdit->text() + " в базу?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; queryString = "insert into TPatient ("; queryString += "First_Name, Second_Name, Last_Name, "; queryString += "Birth_Date, Street, Building, Block, "; queryString += "Apartments, Phone_Number, Anamnesis) "; queryString += "values ("; queryString += "'" + ui->firstNameEdit->text() + "', "; queryString += "'" + ui->secondNameEdit->text() + "', "; queryString += "'" + ui->lastNameEdit->text() + "', "; queryString += "'" + ui->birthDateEdit->date().toString(Qt::ISODate) + "', "; queryString += "'" + ui->streetEdit->text() + "', "; queryString += "'" + ui->buildingEdit->text() + "', "; queryString += "'" + ui->blockEdit->text() + "', "; queryString += "'" + ui->apartmentsEdit->text() + "', "; queryString += "'" + ui->phoneEdit->text() + "', "; queryString += "'" + ui->anamnesisEdit->toPlainText() + "')"; patientQuery.exec(queryString); ui->createCheckButton->show(); ui->deleteCheckButton->show(); emit updatePatientTable(); queryString = "select * from TPatient where "; queryString += "First_Name='" + ui->firstNameEdit->text() + "' and "; queryString += "Second_Name='" + ui->secondNameEdit->text() + "' and "; queryString += "Last_Name='" + ui->lastNameEdit->text() + "' and "; queryString += "Birth_Date='" + ui->birthDateEdit->date().toString(Qt::ISODate) + "' and "; queryString += "Street='" + ui->streetEdit->text() + "' and "; queryString += "Building='" + ui->buildingEdit->text() + "' and "; queryString += "Block='" + ui->blockEdit->text() + "' and "; queryString += "Apartments='" + ui->apartmentsEdit->text() + "' and "; queryString += "Phone_Number='" + ui->phoneEdit->text() + "'"; patientQuery.exec(queryString); patientQuery.next(); patientId = patientQuery.value(Ui::TPatient::PATIENT_ID_INDEX).toInt(); mode = Ui::Form_Mode::EDIT_RECORD_MODE; } break; case Ui::Form_Mode::EDIT_RECORD_MODE: { reply = QMessageBox::question( this, "Question", "Вы действительно хотите обновить " + ui->firstNameEdit->text() + " " + ui->secondNameEdit->text() + " " + ui->lastNameEdit->text() + " в базе?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; queryString = "update TPatient set "; queryString += "First_Name='" + ui->firstNameEdit->text() + "', "; queryString += "Second_Name='" + ui->secondNameEdit->text() + "', "; queryString += "Last_Name='" + ui->lastNameEdit->text() + "', "; queryString += "Birth_Date='" + ui->birthDateEdit->date().toString(Qt::ISODate) + "', "; queryString += "Street='" + ui->streetEdit->text() + "', "; queryString += "Building='" + ui->buildingEdit->text() + "', "; queryString += "Block='" + ui->blockEdit->text() + "', "; queryString += "Apartments='" + ui->apartmentsEdit->text() + "', "; queryString += "Phone_Number='" + ui->phoneEdit->text() + "', "; queryString += "Anamnesis='" + ui->anamnesisEdit->toPlainText() + "' "; queryString += "where Id='" + QString::number(patientId) + "'"; patientQuery.exec(queryString); emit updatePatientTable(); } break; } } void PatientForm::onCreateCheckButtonClicked() { checkForm->resetData(patientId); checkForm->show(); checkForm->activateWindow(); checkForm->raise(); } void PatientForm::onDeleteCheckButtonClicked() { QMessageBox::StandardButton reply; QModelIndexList selection = ui->checkList->selectionModel()->selectedRows(); if (selection.size()) { QModelIndex index = selection.at (0); QSqlRecord record = modelChecks->record(index.row()); reply = QMessageBox::question( this, "Question", "Вы действительно хотите удалить " + record.value(Ui::TCheck::TAG_INDEX).toString() + " из базы?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; int checkId = record.value( Ui::TCheck::CHECK_ID_INDEX ).toInt(); QString queryString; queryString = "delete from TCheck where "; queryString += "Id='" + QString::number(checkId) + "'"; QSqlQuery patientQuery; patientQuery.exec(queryString); onUpdateCheckTable(); checkForm->hide(); } else { QMessageBox::critical( this, "Select to remove", "Не выбрана запись посещения для удаления" ); } } void PatientForm::onTableDoubleClicked(const QModelIndex &index) { if (index.isValid()) { QSqlRecord checkRecord = modelChecks->record(index.row()); checkForm->setData(checkRecord); } checkForm->show(); checkForm->activateWindow(); checkForm->raise(); } void PatientForm::onUpdateCheckTable() { QString queryString = "select * from TCheck where "; queryString += "Patient_Id='" + QString::number(patientId) + "'"; modelChecks->setQuery(queryString); } PatientForm::~PatientForm() { delete ui; delete modelChecks; delete checkForm; } <file_sep>/main.h #ifndef MAIN_H #define MAIN_H namespace Ui { namespace TPatient { const int PATIENT_ID_INDEX = 0; const int FIRST_NAME_INDEX = 1; const int SECOND_NAME_INDEX = 2; const int LAST_NAME_INDEX = 3; const int BIRTH_DATE_INDEX = 4; const int STREET_INDEX = 5; const int BUILDING_INDEX = 6; const int BLOCK_INDEX = 7; const int APARTMENTS_INDEX = 8; const int PHONE_NUMBER_INDEX = 9; const int ANAMNESIS_INDEX = 10; } namespace TCheck { const int CHECK_ID_INDEX = 0; const int TAG_INDEX = 1; const int DATE_INDEX = 2; const int PATIENT_ID_INDEX = 3; const int RESOLUTION_INDEX = 4; } enum class Form_Mode {CREATE_RECORD_MODE, EDIT_RECORD_MODE}; } #endif // MAIN_H <file_sep>/README.md # PatientaDB Database operating application. Test of Git here.<file_sep>/checkform.h #ifndef CHECKFORM_H #define CHECKFORM_H #include <QtSql> #include <QWidget> #include "main.h" namespace Ui { class CheckForm; } class CheckForm : public QWidget { Q_OBJECT public: explicit CheckForm(QWidget *parent = nullptr); ~CheckForm(); void setData(QSqlRecord); void resetData(int); private: Ui::CheckForm *ui; Ui::Form_Mode mode; int patientId; int checkId; private: void fillPatientData(int); signals: void updateCheckTable(); private slots: void onSaveRecordButtonClicked(); }; #endif // CHECKFORM_H <file_sep>/mainwindow.cpp #include <QtSql> #include <QSqlDatabase> #include <QMessageBox> #include "main.h" #include "mainwindow.h" #include "patientform.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); if (!QSqlDatabase::drivers().contains("QSQLITE")) { QMessageBox::critical( this, "Unable to load database", "This app needs the SQLITE driver" ); return; } db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("PatientaDB.db"); if (!db.open()) { QMessageBox::critical( this, "Unable to open database", "This app needs the PatientaDB.db database" ); return; } modelPatients = new QSqlQueryModel(); modelPatients->setQuery("select * from TPatient"); modelPatients->setHeaderData( Ui::TPatient::FIRST_NAME_INDEX, Qt::Horizontal, QObject::tr("Имя") ); modelPatients->setHeaderData( Ui::TPatient::SECOND_NAME_INDEX, Qt::Horizontal, QObject::tr("Отчество") ); modelPatients->setHeaderData( Ui::TPatient::LAST_NAME_INDEX, Qt::Horizontal, QObject::tr("Фамилия") ); modelPatients->setHeaderData( Ui::TPatient::BIRTH_DATE_INDEX, Qt::Horizontal, QObject::tr("Дата Рождения") ); ui->patientsList->setModel(modelPatients); ui->patientsList->setColumnHidden(Ui::TPatient::PATIENT_ID_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::STREET_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::BUILDING_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::BLOCK_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::APARTMENTS_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::PHONE_NUMBER_INDEX, true); ui->patientsList->setColumnHidden(Ui::TPatient::ANAMNESIS_INDEX, true); ui->patientsList->show(); connect( ui->patientsList, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onTableClicked(const QModelIndex &)) ); connect ( ui->patientsList, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(onTableDoubleClicked(const QModelIndex &)) ); connect( ui->createButton, SIGNAL (clicked()), this, SLOT (onCreateRecordButtonClicked()) ); connect( ui->deleteButton, SIGNAL (clicked()), this, SLOT (onDeleteRecordButtonClicked()) ); patientForm = new PatientForm; connect( patientForm, SIGNAL (updatePatientTable()), this, SLOT (onUpdatePatientTable()) ); connect ( ui->searchFirstName, SIGNAL (textChanged(const QString &)), this, SLOT (searchOnFirstNameChanged(const QString &)) ); connect ( ui->searchSecondName, SIGNAL (textChanged(const QString &)), this, SLOT (searchOnSecondNameChanged(const QString &)) ); connect ( ui->searchLastName, SIGNAL (textChanged(const QString &)), this, SLOT (searchOnLastNameChanged(const QString &)) ); connect ( ui->searchYear, SIGNAL (textChanged(const QString &)), this, SLOT (searchOnYearChanged(const QString &)) ); } void MainWindow::onTableClicked(const QModelIndex &index) { if (index.isValid()) { QString lastNameText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::LAST_NAME_INDEX ) ).toString(); ui->labelLastName->setText(lastNameText); QString firstNameText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::FIRST_NAME_INDEX ) ).toString(); ui->labelFirstName->setText(firstNameText); QString secondNameText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::SECOND_NAME_INDEX ) ).toString(); ui->labelSecondName->setText(secondNameText); QString birthDateString = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::BIRTH_DATE_INDEX ) ).toString(); ui->labelBirthDate->setText(birthDateString); QString streetText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::STREET_INDEX ) ).toString(); QString buildingText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::BUILDING_INDEX ) ).toString(); QString blockText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::BLOCK_INDEX ) ).toString(); QString appartmentsText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::APARTMENTS_INDEX ) ).toString(); ui->labelAddress->setText( streetText + ", " + "д. " + buildingText + ", " + "к. " + blockText + ", " + "кв. " + appartmentsText ); QString phoneNumberText = modelPatients->data( modelPatients->index( index.row(), Ui::TPatient::PHONE_NUMBER_INDEX ) ).toString(); ui->labelPhoneNumber->setText (phoneNumberText); } } void MainWindow::onTableDoubleClicked(const QModelIndex &index) { if (index.isValid()) { QSqlRecord patientRecord = modelPatients->record(index.row()); patientForm->setData(patientRecord); } patientForm->show(); patientForm->activateWindow(); patientForm->raise(); } void MainWindow::onCreateRecordButtonClicked() { patientForm->resetData(); patientForm->show(); patientForm->activateWindow(); patientForm->raise(); } void MainWindow::onDeleteRecordButtonClicked() { QMessageBox::StandardButton reply; QModelIndexList selection = ui->patientsList->selectionModel()->selectedRows(); if (selection.size()) { QModelIndex index = selection.at (0); QSqlRecord record = modelPatients->record(index.row()); reply = QMessageBox::question( this, "Question", "Вы действительно хотите удалить " + record.value(Ui::TPatient::FIRST_NAME_INDEX).toString() + " " + record.value(Ui::TPatient::SECOND_NAME_INDEX).toString() + " " + record.value(Ui::TPatient::LAST_NAME_INDEX).toString() + " из базы?", QMessageBox::Yes|QMessageBox::No ); if (reply == QMessageBox::No) return; int patientId = record.value( Ui::TPatient::PATIENT_ID_INDEX ).toInt(); QString queryString; queryString = "delete from TPatient where "; queryString += "Id='" + QString::number(patientId) + "'"; QSqlQuery patientQuery; patientQuery.exec(queryString); queryString = "delete from TCheck where "; queryString += "Patient_Id='" + QString::number(patientId) + "'"; patientQuery.exec(queryString); onUpdatePatientTable(); patientForm->hide(); } else { QMessageBox::critical( this, "Select to remove", "Не выбран пациент для удаления" ); } } void MainWindow::onUpdatePatientTable() { modelPatients->setQuery("select * from TPatient"); } void MainWindow::searchOnFirstNameChanged(const QString &text) { QString query = "select * from TPatient where "; query += "First_Name like '%" + text + "%' and "; query += "Second_Name like '%" + ui->searchSecondName->text() + "%' and "; query += "Last_Name like '%" + ui->searchLastName->text() + "%' and "; query += "Birth_Date like '%" + ui->searchYear->text() + "%'"; modelPatients->setQuery(query); } void MainWindow::searchOnSecondNameChanged(const QString &text) { QString query = "select * from TPatient where "; query += "First_Name like '%" + ui->searchFirstName->text() + "%' and "; query += "Second_Name like '%" + text + "%' and "; query += "Last_Name like '%" + ui->searchLastName->text() + "%' and "; query += "Birth_Date like '%" + ui->searchYear->text() + "%'"; modelPatients->setQuery(query); } void MainWindow::searchOnLastNameChanged(const QString &text) { QString query = "select * from TPatient where "; query += "First_Name like '%" + ui->searchFirstName->text() + "%' and "; query += "Second_Name like '%" + ui->searchSecondName->text() + "%' and "; query += "Last_Name like '%" + text + "%' and "; query += "Birth_Date like '%" + ui->searchYear->text() + "%'"; modelPatients->setQuery(query); } void MainWindow::searchOnYearChanged(const QString &text) { QString query = "select * from TPatient where "; query += "First_Name like '%" + ui->searchFirstName->text() + "%' and "; query += "Second_Name like '%" + ui->searchSecondName->text() + "%' and "; query += "Last_Name like '%" + ui->searchLastName->text() + "%' and "; query += "Birth_Date like '%" + text + "%'"; modelPatients->setQuery(query); } MainWindow::~MainWindow() { delete ui; db.close(); delete modelPatients; delete patientForm; }
9c4d15ee985cdabd54d6db924d5b129cbff55f16
[ "Markdown", "C++" ]
8
C++
orckrn/PatientaDB
8d29c502569e37b7ffe4d1ca1099f4ff0638371d
ea0a25469a36c31cbcdd74e93dbb61a61911df84
refs/heads/master
<repo_name>exitcodezero/aams-payment-api<file_sep>/app/api/payment/handlers.js var fs = require('fs'); var path = require('path'); var util = require('util'); var async = require('async'); var ejs = require('ejs'); var sendEmail = require('./mailgun').sendEmail; var sendEmailToBilling = require('./mailgun').sendEmailToBilling; var chargeCard = require('./authorize').chargeCard; var templatePath = path.join(__dirname, 'email.html'); var emailTemplate = ejs.compile(fs.readFileSync(templatePath, 'utf-8')); var errMessages = { name: 'Field is required.', invoiceNum: 'Field is required.', billingAddress: 'Field is required.', billingCity: 'Field is required.', billingState: 'Field is required. Value must have length of 2', billingZip: 'Field is required. Value must have length between 5 and 10.', amount: 'Field is required. Value must be numeric.', cardName: 'Field is required.', cardNum: 'Field is required. Value must be numeric.', cardExpire: 'Field is required.', cardCsv: 'Field is required. Value must be numeric.', shippingAddress: 'Field is required.', shippingCity: 'Field is required.', shippingState: 'Field is required. Value must have length of 2', shippingZip: 'Field is required. Value must have length between 5 and 10.', }; var cardExpireRegex = "^(0[1-9]|1[0-2])([0-9]{2})|(0[1-9]|1[0-2])/([0-9]{2})$"; exports.paymentHandler = function (req, res, next) { var tasks = [ validation, makePayment, confirmationEmailInternal, confirmationEmailExternal ]; async.waterfall(tasks, onTasksComplete); function validation(done) { req.checkBody( 'name', errMessages.name ).notEmpty(); req.checkBody( 'email', errMessages.name ).notEmpty().isEmail(); req.checkBody( 'invoiceNum', errMessages.invoiceNum ).notEmpty(); req.checkBody( 'billingAddress', errMessages.billingAddress ).notEmpty(); req.checkBody( 'billingCity', errMessages.billingCity ).notEmpty(); req.checkBody( 'billingState', errMessages.billingState ).notEmpty().isLength(2, 2); req.checkBody( 'billingZip', errMessages.billingZip ).notEmpty().isLength(5, 10); req.checkBody( 'amount', errMessages.amount ).notEmpty().isCurrency(); req.checkBody( 'cardName', errMessages.cardName ).notEmpty(); req.checkBody( 'cardNum', errMessages.cardNum ).notEmpty().isCreditCard(); req.checkBody( 'cardExpire', errMessages.cardExpire ).notEmpty().matches(cardExpireRegex); req.checkBody( 'cardCsv', errMessages.cardCsv ).notEmpty().isNumeric(); req.checkBody( 'shippingAddress', errMessages.shippingAddress ).notEmpty(); req.checkBody( 'shippingCity', errMessages.shippingCity ).notEmpty(); req.checkBody( 'shippingState', errMessages.shippingState ).notEmpty().isLength(2, 2); req.checkBody( 'shippingZip', errMessages.shippingZip ).notEmpty().isLength(5, 10); var validationErrors = req.validationErrors(); if (validationErrors) { var err = new Error(); err.status = 400; err.message = validationErrors; return done(err, null); } return done(null, req.body); } function makePayment(validatedData, done) { var paymentData = { customer: { name: validatedData.name, email: validatedData.email, address: validatedData.billingAddress, city: validatedData.billingCity, state: validatedData.billingState, zip: validatedData.billingZip, shipping: { address: validatedData.shippingAddress, city: validatedData.shippingCity, state: validatedData.shippingState, zip: validatedData.shippingZip } }, transaction: { invoiceNum: validatedData.invoiceNum, amount: validatedData.amount } }; chargeCard(validatedData, function (err, response) { if (err) { return done(err, null); } // Approved if (response.transactionResponse.responseCode === '1') { paymentData.transaction.authCode = response.transactionResponse.authCode; paymentData.transaction.transId = response.transactionResponse.transId; paymentData.transaction.cardNum = response.transactionResponse.accountNumber; paymentData.transaction.cardType = response.transactionResponse.accountType; return done(null, paymentData); } // Not Approved switch (response.transactionResponse.responseCode) { case '2': return done(new Error('Card declined by Authorize.Net'), null); case '3': return done(new Error('Processing error by Authorize.Net'), null); case '3': return done(new Error('Held for review by Authorize.Net'), null); default: return done(new Error('Unexpected responseCode from Authorize.Net'), null); } }); } function confirmationEmailInternal(paymentData, done) { var subject = util.format('Payment Processed: %s - %s', paymentData.customer.name, paymentData.transaction.invoiceNum); var bodyLines = []; bodyLines.push(util.format('Name: %s ', paymentData.customer.name)); bodyLines.push(util.format('Invoice Number: %s ', paymentData.transaction.invoiceNum)); bodyLines.push(util.format('Authorization Code: %s ', paymentData.transaction.authCode)); bodyLines.push(util.format('Transaction ID: %s ', paymentData.transaction.transId)); bodyLines.push(util.format('Billing Address: %s ', paymentData.customer.address)); bodyLines.push(util.format('Amount Paid: %d ', paymentData.transaction.amount)); bodyLines.push(util.format('Credit Card: %s ', paymentData.transaction.cardNum)); bodyLines.push(util.format('Shipping Address: %s ', paymentData.customer.shipping.address)); bodyLines.push(util.format('Shipping City: %s ', paymentData.customer.shipping.city)); bodyLines.push(util.format('Shipping State: %s ', paymentData.customer.shipping.state)); bodyLines.push(util.format('Shipping Zip: %s ', paymentData.customer.shipping.zip)); var body = bodyLines.join('<br>'); sendEmailToBilling(subject, body); return done(null, paymentData); } function confirmationEmailExternal(paymentData, done) { var subject = util.format('Thanks for your payment', paymentData.customer.name); var body = emailTemplate(paymentData); sendEmail(paymentData.customer.email, subject, body); return done(null, paymentData); } function onTasksComplete(err, data) { if (err) { console.log(err); return next(err); } return res.status(201).json(data); } }; <file_sep>/README.md # aams-payment-api ### Create a Payment **POST:** ``` /pay ``` **Body:** ```json { "name": "<NAME>", "email": "<EMAIL>", "invoiceNum": "111111", "billingAddress": "123 N Main St", "billingCity": "Chicago", "billingState": "IL", "billingZip": "60661", "amount": "100.00", "cardType": "VISA", "cardName": "<NAME>", "cardNum": "4111111111111111", "cardExpire": "1220", "cardCsv": "111" } ``` **Response:** ```json { "customer": { "name": "<NAME>", "email": "<EMAIL>", "address": "123 N Main St", "city": "Chicago", "state": "IL", "zip": "60661" }, "transaction": { "invoiceNum": "111111", "amount": "100.00", "authCode": "4YI3ZD", "transId": "2239631934", "cardNum": "XXXX1111", "cardType": "Visa" } } ``` **Status Codes:** * `201` if successful * `400` if incorrect data provided * `500` if Authorize.net error <file_sep>/docker-compose.yml web: build: . command: node ./app/bin/www volumes: - ./app:/src/app ports: - 3000:3000 environment: PORT: 3000 <file_sep>/Dockerfile FROM node RUN mkdir /src COPY package.json /src/package.json RUN cd /src && npm install WORKDIR /src <file_sep>/app/api/payment/mailgun.js var Mailgun = require('mailgun-js'); var mailGunApiKey = process.env.MAILGUN_API_KEY; var mailGunDomain = process.env.MAILGUN_DOMAIN; var mailGunFromEmail = process.env.MAILGUN_FROM_EMAIL; var mailGunToEmail = process.env.MAILGUN_TO_EMAIL; exports.sendEmail = sendEmail; exports.sendEmailToBilling = sendEmailToBilling; function sendEmail(emailTo, emailSubject, emailBody) { var config = { apiKey: mailGunApiKey, domain: mailGunDomain }; var mailgun = new Mailgun(config); var data = { from: mailGunFromEmail, to: emailTo, subject: emailSubject, html: emailBody }; mailgun.messages().send(data, function (err, body) { if (err) { console.log(err); } }); } function sendEmailToBilling(emailSubject, emailBody) { sendEmail(mailGunToEmail, emailSubject, emailBody); } <file_sep>/app/routes/index.js var express = require('express'); var router = express.Router(); var paymentHandler = require('../api/payment/handlers').paymentHandler; router.get('/ping', function (req, res, next) { return res.status(200).json({ message: 'pong' }); }); router.post('/pay', paymentHandler); module.exports = router;
9d2baa074fe8e8f4a3d8298238335f9379094308
[ "JavaScript", "Dockerfile", "YAML", "Markdown" ]
6
JavaScript
exitcodezero/aams-payment-api
22308f53c69925df51d61a6aa171263b1c95c6e3
0404be191048a4ba6157292381542308418acdba
refs/heads/master
<file_sep>#define _XOPEN_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pty.h> #include <stdlib.h> #include "hl_vt100.h" struct vt100_headless *new_vt100_headless(void) { return calloc(1, sizeof(struct vt100_headless)); } void delete_vt100_headless(struct vt100_headless *this) { free(this); } static void set_non_canonical(struct vt100_headless *this, int fd) { struct termios termios; ioctl(fd, TCGETS, &this->backup); ioctl(fd, TCGETS, &termios); termios.c_iflag |= ICANON; termios.c_cc[VMIN] = 1; termios.c_cc[VTIME] = 0; ioctl(fd, TCSETS, &termios); } static void restore_termios(struct vt100_headless *this, int fd) { ioctl(fd, TCSETS, &this->backup); } #ifndef NDEBUG static void strdump(char *str) { while (*str != '\0') { if (*str >= ' ' && *str <= '~') fprintf(stderr, "%c", *str); else fprintf(stderr, "\\0%o", *str); str += 1; } fprintf(stderr, "\n"); } #endif void vt100_headless_stop(struct vt100_headless *this) { this->should_quit = 1; } int vt100_headless_main_loop(struct vt100_headless *this) { char buffer[4096]; fd_set rfds; int retval; ssize_t read_size; while (!this->should_quit) { FD_ZERO(&rfds); FD_SET(this->master, &rfds); FD_SET(0, &rfds); retval = select(this->master + 1, &rfds, NULL, NULL, NULL); if (retval == -1) { perror("select()"); } if (FD_ISSET(0, &rfds)) { read_size = read(0, &buffer, 4096); if (read_size == -1) { perror("read"); return EXIT_FAILURE; } buffer[read_size] = '\0'; write(this->master, buffer, read_size); } if (FD_ISSET(this->master, &rfds)) { read_size = read(this->master, &buffer, 4096); if (read_size == -1) { perror("read"); return EXIT_FAILURE; } buffer[read_size] = '\0'; #ifndef NDEBUG strdump(buffer); #endif lw_terminal_vt100_read_str(this->term, buffer); if (this->changed != NULL) this->changed(this); } } return EXIT_SUCCESS; } void master_write(void *user_data, void *buffer, size_t len) { struct vt100_headless *this; this = (struct vt100_headless*)user_data; write(this->master, buffer, len); } const char **vt100_headless_getlines(struct vt100_headless *this) { return lw_terminal_vt100_getlines(this->term); } void vt100_headless_fork(struct vt100_headless *this, const char *progname, char **argv) { int child; struct winsize winsize; set_non_canonical(this, 0); winsize.ws_row = 24; winsize.ws_col = 80; child = forkpty(&this->master, NULL, NULL, NULL); if (child == CHILD) { setsid(); putenv("TERM=vt100"); execvp(progname, argv); return ; } else { this->term = lw_terminal_vt100_init(this, lw_terminal_parser_default_unimplemented); this->term->master_write = master_write; ioctl(this->master, TIOCSWINSZ, &winsize); } restore_termios(this, 0); } <file_sep>#include <stdlib.h> #include <unistd.h> #include <utmp.h> #include <string.h> #include <pty.h> #include <stdio.h> #include "hl_vt100.h" void disp(struct vt100_headless *vt100) { unsigned int y; const char **lines; lines = vt100_headless_getlines(vt100); write(1, "\n", 1); for (y = 0; y < vt100->term->height; ++y) { write(1, "|", 1); write(1, lines[y], vt100->term->width); write(1, "|\n", 2); } } int main(int ac, char **av) { struct vt100_headless *vt100_headless; if (ac == 1) { puts("Usage: test PROGNAME"); return EXIT_FAILURE; } vt100_headless = new_vt100_headless(); vt100_headless->changed = disp; vt100_headless_fork(vt100_headless, av[1], (av + 1)); vt100_headless_main_loop(vt100_headless); return EXIT_SUCCESS; } <file_sep>#!/bin/sh if [ "$1" = python ] then if ! which swig > /dev/null then echo "You should install swig !" exit 1 fi make python_module if [ $? != 0 ] then echo "Failed to build python module" exit 1 fi cat <<EOF | python import hl_vt100 import time import sys print "Starting python test..." vt100 = hl_vt100.vt100_headless() vt100.fork('/usr/bin/top', ['/usr/bin/top', '-n', '1']) vt100.main_loop() [sys.stdout.write(line + "\n") for line in vt100.getlines()] EOF exit fi make clean if [ "$1" = c ] then make && make test if [ -x /lib/ld-linux-*.so.2 ] then echo Using /lib/ld-linux-*.so.2 to run test /lib/ld-linux-*.so.2 --library-path . ./test /usr/bin/top else echo Using /lib/ld-linux.so.2 to run test /lib/ld-linux.so.2 --library-path . ./test /usr/bin/top fi exit fi $0 python $0 c<file_sep>#!/usr/bin/env python """ setup.py file for hl_vt100 """ from distutils.core import setup, Extension hl_vt100_module = Extension('_hl_vt100', sources=['hl_vt100_wrap.c', 'src/hl_vt100.c', 'src/lw_terminal_parser.c', 'src/lw_terminal_vt100.c'], ) setup (name = 'hl_vt100', version = '0.1', author = "<NAME>", description = """Headless vt100 emulator""", ext_modules = [hl_vt100_module], py_modules = ["hl_vt100"], ) <file_sep>#ifndef __VT100_HEADLESS_H__ #define __VT100_HEADLESS_H__ #define CHILD 0 #include <utmp.h> #include <sys/ioctl.h> #include <unistd.h> #include <termios.h> #include "lw_terminal_vt100.h" struct vt100_headless { int master; struct termios backup; struct lw_terminal_vt100 *term; int should_quit; void (*changed)(struct vt100_headless *this); }; void vt100_headless_fork(struct vt100_headless *this, const char *progname, char **argv); int vt100_headless_main_loop(struct vt100_headless *this); void delete_vt100_headless(struct vt100_headless *this); struct vt100_headless *new_vt100_headless(void); const char **vt100_headless_getlines(struct vt100_headless *this); void vt100_headless_stop(struct vt100_headless *this); #endif <file_sep>INSTALL ======= Python module ------------- Run : $ make python_module && su -c 'python setup.py install' Overview ======== lw_terminal_parser, lw_terminal_vt100, and hl_vt100 are three modules used to emulate a vt100 terminal:: ------------- | | | Your Code | | | ------------- | ^ vt100 = vt100_headless_init() | | vt100->changed = changed; | | hl_vt100 raises 'changed' vt100_headless_fork(vt100, ... | | when the screen has changed. | | You get the content of the screen | | calling vt100_headless_getlines. V | ------------- ------------- Read from PTY master and write | | | PTY | | to lw_terminal_vt100_read_str | | hl_vt100 |<------------>| Program | V | |Master Slave| | ------------- ------------- | |^ hl_vt100 gets lw_terminal_vt100's | || lines by calling | || lw_terminal_vt100_getlines | || | || V V| ---------------------- Got data from | | | Recieve data from callbacks lw_terminal_vt100_read_str | | lw_terminal_vt100 | And store an in-memory give it to | | | state of the vt100 terminal lw_terminal_read_str V ---------------------- | ^ | | | | | | | | | | Callbacks | | | | | | | | | | V | ---------------------- Got data from | | lw_terminal_pasrser_read_str | lw_terminal_parser | parses, and call callbacks | | ---------------------- lw_terminal_parser ================== lw_terminal_parser parses terminal escape sequences, calling callbacks when a sequence is sucessfully parsed, read example/parse.c. Provides : * struct lw_terminal \*lw_terminal_parser_init(void); * void lw_terminal_parser_destroy(struct lw_terminal\* this); * void lw_terminal_parser_default_unimplemented(struct lw_terminal\* this, char \*seq, char chr); * void lw_terminal_parser_read(struct lw_terminal \*this, char c); * void lw_terminal_parser_read_str(struct lw_terminal \*this, char \*c); lw_terminal_vt100 ================= Hooks into a lw_terminal_parser and keep an in-memory state of the screen of a vt100. Provides : * struct lw_terminal_vt100 \*lw_terminal_vt100_init(void \*user_data, void (\*unimplemented)(struct lw_terminal\* term_emul, char \*seq, char chr)); * char lw_terminal_vt100_get(struct lw_terminal_vt100 \*vt100, unsigned int x, unsigned int y); * const char \*\*lw_terminal_vt100_getlines(struct lw_terminal_vt100 \*vt100); * void lw_terminal_vt100_destroy(struct lw_terminal_vt100 \*this); * void lw_terminal_vt100_read_str(struct lw_terminal_vt100 \*this, char \*buffer); hl_vt100 ======== Forks a program, plug its io to a pseudo terminal and emulate a vt100 using lw_terminal_vt100. Provides : * void vt100_headless_fork(struct vt100_headless \*this, const char \*progname, char \*const argv[]); * struct vt100_headless \*vt100_headless_init(void); * const char \*\*vt100_headless_getlines(struct vt100_headless \*this); <file_sep>## ## Makefile for vt100 ## ## Made by <NAME> ## Login <<EMAIL>> ## NAME = vt100 VERSION = 0 MINOR = 0 RELEASE = 0 LINKERNAME = lib$(NAME).so SONAME = $(LINKERNAME).$(VERSION) REALNAME = $(SONAME).$(MINOR).$(RELEASE) SRC = src/lw_terminal_parser.c src/lw_terminal_vt100.c src/hl_vt100.c SRC_TEST = src/test.c OBJ = $(SRC:.c=.o) OBJ_TEST = $(SRC_TEST:.c=.o) CC = gcc INCLUDE = src DEFINE = _GNU_SOURCE CFLAGS = -DNDEBUG -g3 -Wextra -Wstrict-prototypes -Wall -ansi -pedantic -fPIC -I$(INCLUDE) LIB = -lutil RM = rm -f $(NAME): $(OBJ) $(CC) --shared $(OBJ) $(LIB) -o $(LINKERNAME) test: $(OBJ_TEST) $(CC) $(OBJ_TEST) -L . -l$(NAME) -o test python_module: swig -python -threads *.i all: @make $(NAME) .c.o: $(CC) -D $(DEFINE) -c $(CFLAGS) $< -o $(<:.c=.o) clean_python_module: $(RM) *.pyc *.so hl_vt100_wrap.c hl_vt100.py $(RM) -r build clean: clean_python_module $(RM) $(LINKERNAME) test src/*~ *~ src/\#*\# src/*.o \#*\# *.o *core re: clean all check-syntax: gcc -Isrc -Wall -Wextra -ansi -pedantic -o /dev/null -S ${CHK_SOURCES} <file_sep>#ifndef __LW_TERMINAL_VT100_H__ #define __LW_TERMINAL_VT100_H__ #include <pthread.h> #include "lw_terminal_parser.h" /* * Source : http://vt100.net/docs/vt100-ug/chapter3.html http://vt100.net/docs/tp83/appendixb.html * It's a vt100 implementation, that implements ANSI control function. */ #define SCROLLBACK 3 #define MASK_LNM 1 #define MASK_DECCKM 2 #define MASK_DECANM 4 #define MASK_DECCOLM 8 #define MASK_DECSCLM 16 #define MASK_DECSCNM 32 #define MASK_DECOM 64 #define MASK_DECAWM 128 #define MASK_DECARM 256 #define MASK_DECINLM 512 #define LNM 20 #define DECCKM 1 #define DECANM 2 #define DECCOLM 3 #define DECSCLM 4 #define DECSCNM 5 #define DECOM 6 #define DECAWM 7 #define DECARM 8 #define DECINLM 9 #define SET_MODE(vt100, mode) ((vt100)->modes |= get_mode_mask(mode)) #define UNSET_MODE(vt100, mode) ((vt100)->modes &= ~get_mode_mask(mode)) #define MODE_IS_SET(vt100, mode) ((vt100)->modes & get_mode_mask(mode)) /* ** frozen_screen is the frozen part of the screen ** when margins are set. ** The top of the frozen_screen holds the top margin ** while the bottom holds the bottom margin. */ struct lw_terminal_vt100 { struct lw_terminal *lw_terminal; unsigned int width; unsigned int height; unsigned int x; unsigned int y; unsigned int saved_x; unsigned int saved_y; unsigned int margin_top; unsigned int margin_bottom; unsigned int top_line; /* Line at the top of the display */ char *screen; char *frozen_screen; char *tabulations; unsigned int selected_charset; unsigned int modes; char *lines[80]; void (*master_write)(void *user_data, void *buffer, size_t len); void *user_data; pthread_mutex_t mutex; }; struct lw_terminal_vt100 *lw_terminal_vt100_init(void *user_data, void (*unimplemented)(struct lw_terminal* term_emul, char *seq, char chr)); char lw_terminal_vt100_get(struct lw_terminal_vt100 *vt100, unsigned int x, unsigned int y); const char **lw_terminal_vt100_getlines(struct lw_terminal_vt100 *vt100); void lw_terminal_vt100_destroy(struct lw_terminal_vt100 *this); void lw_terminal_vt100_read_str(struct lw_terminal_vt100 *this, char *buffer); #endif
4071d1fc8f1c95b0113bfb787e4f42c6627d1a5e
[ "reStructuredText", "Makefile", "Python", "C", "Shell" ]
8
C
math4youbyusgroupillinois/vt100-emulator
a2f8b7e68689733626b4a90191b26dff3b453e76
c3172f7e71c3c96915a087db5454bf40567a75ae
refs/heads/master
<file_sep>import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {PodcastsComponent} from './podcasts.component'; import {MdCardModule} from '@angular/material'; import {ActivatedRoute} from '@angular/router'; import {Observable} from 'rxjs/Observable'; import {PodcastsEffects} from './podcasts.effects'; import {provideMockActions} from '@ngrx/effects/testing'; import {cold, hot} from 'jasmine-marbles'; import {FindAll, FindAllError, FindAllSuccess} from 'app/podcasts/podcasts.actions'; import {PodcastService} from '../shared/service/podcast/podcast.service'; import {ReplaySubject} from 'rxjs/ReplaySubject'; import {Action} from '@ngrx/store'; import Spy = jasmine.Spy; import {DebugElement} from '@angular/core'; import {By} from '@angular/platform-browser'; import {reducer} from './podcasts.reducer'; describe('PodcastsFeature', () => { let podcasts = [ { "id":"8ba490ac-8f9a-4e2d-8758-b65e783e783a", "title":"Comme des poissons dans l'eau", "type":"RSS", "lastUpdate":"2016-01-30T18:01:31.919+01:00", "cover":{ "id":"26d3b096-e424-42fe-bedc-07943efe2809", "url":"/api/podcasts/8ba490ac-8f9a-4e2d-8758-b65e783e783a/cover.jpg", "width":200, "height":200 } }, { "id":"238f1309-715f-4910-87f4-159ba4d6885e", "title":"Dockercast", "type":"RSS", "lastUpdate":"2017-02-15T22:01:39.854+01:00", "cover":{ "id":"bfc3b55b-56bf-4ab7-a446-64fa084b7aa5", "url":"/api/podcasts/238f1309-715f-4910-87f4-159ba4d6885e/cover.jpg", "width":2998, "height":2998 } }, { "id":"ead438e2-121e-43c1-bbd5-a86e4b0b612a", "title":"Le Porncast", "type":"RSS", "lastUpdate":"2016-08-07T21:02:20.298+02:00", "cover":{ "id":"c8c6e659-870f-4797-808d-022e2d6b0cb9", "url":"/api/podcasts/ead438e2-121e-43c1-bbd5-a86e4b0b612a/cover.jpg", "width":200, "height":200 } }, { "id":"1f964152-2d5a-4b34-9223-8ba383b31d77", "title":"56 Kast", "type":"RSS", "lastUpdate":"2016-03-26T17:03:51.748+01:00", "cover":{ "id":"acbb8fc6-3f94-4903-ad80-57b0edcc9715", "url":"/api/podcasts/1f964152-2d5a-4b34-9223-8ba383b31d77/cover.jpg", "width":200, "height":200 } }, { "id":"9a58c257-bcb8-4c6d-a70b-f378e6684acb", "title":"Ta Gueule", "type":"RSS", "lastUpdate":"2016-08-07T21:02:20.464+02:00", "cover":{ "id":"f4414ced-1365-499d-9f54-66d7e21ce27f", "url":"/api/podcasts/9a58c257-bcb8-4c6d-a70b-f378e6684acb/cover.jpg", "width":200, "height":200 } }, { "id":"17ae402d-545f-4ea7-b924-d52e8b864e5f", "title":"Les experts F1", "type":"RSS", "lastUpdate":"2017-04-14T22:01:44.875+02:00", "cover":{ "id":"95cb0794-3617-41b6-8be5-2d4b5b22214b", "url":"/api/podcasts/17ae402d-545f-4ea7-b924-d52e8b864e5f/cover.jpg", "width":200, "height":200 } }, { "id":"9af7599a-37d9-418e-9322-a29758eea2b4", "title":"Apple - Keynotes", "type":"RSS", "lastUpdate":"2017-06-07T21:02:12.713+02:00", "cover":{ "id":"3b68edd1-c653-405c-b204-8b8d0bba3c91", "url":"/api/podcasts/9af7599a-37d9-418e-9322-a29758eea2b4/cover.png", "width":200, "height":200 } }, { "id":"5680d254-57e6-4eb8-80e0-702262e02903", "title":"Pokémon", "type":"Gulli", "lastUpdate":"2017-05-21T07:01:19.957+02:00", "cover":{ "id":"a0f168b7-149b-4668-bdf2-d7f458950a29", "url":"/api/podcasts/5680d254-57e6-4eb8-80e0-702262e02903/cover.jpg", "width":1080, "height":1080 } } ]; describe('PodcastsComponent', () => { let comp: PodcastsComponent; let fixture: ComponentFixture<PodcastsComponent>; let el: DebugElement; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdCardModule], providers: [ { provide: ActivatedRoute, useValue: { data: Observable.of({ podcasts }) } } ], declarations: [ PodcastsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PodcastsComponent); comp = fixture.componentInstance; el = fixture.debugElement; fixture.detectChanges(); }); it('should be created', () => { expect(comp).toBeTruthy(); }); it('should init with podcasts from resolver', () => { /* Given */ /* When */ fixture.whenStable().then(() => { /* Then */ const podcasts = el.queryAll(By.css('md-card')); expect(podcasts.length).toEqual(8); }); }); }); describe('PodcastsEffects', () => { let effects: PodcastsEffects; let podcastService: PodcastService; let actions: Observable<Action>; beforeEach(() => { podcastService = jasmine.createSpyObj('podcastService', ['findAll']); (podcastService.findAll as Spy).and.returnValue(Observable.of([])); }); beforeEach(() => { actions = new ReplaySubject<Action>(1); }); beforeEach(() => { TestBed.configureTestingModule({ providers: [ PodcastsEffects, provideMockActions(() => actions), { provide: PodcastService, useValue: podcastService } ], }).compileComponents(); effects = TestBed.get(PodcastsEffects); }); it('should transform FindAll action to FindAllSuccess', () => { /* Given */ actions = hot('--a-', { a: new FindAll() }); const expected = cold('--b', { b: new FindAllSuccess([]) }); expect(effects.findAll$).toBeObservable(expected); expect(podcastService.findAll).toHaveBeenCalled(); }); }); describe('PodcastsReducers', () => { const previousState = {podcasts: [], error: {message: 'foo'}}; it('should have an initial state', () => { /* Given */ const findAllAction = new FindAll(); /* When */ const state = reducer(undefined, findAllAction); /* Then */ expect(state).toEqual({podcasts: [], error: {message: 'empty'}}); }); it('should do nothing when findAllAction triggered', () => { /* Given */ const findAllAction = new FindAll(); /* When */ const state = reducer(previousState, findAllAction); /* Then */ expect(state).toEqual(previousState); }); it('should change podcasts when findAllSuccess', () => { /* Given */ const findAllSuccessAction = new FindAllSuccess(podcasts); /* When */ const state = reducer(previousState, findAllSuccessAction); /* Then */ expect(state.podcasts).toEqual(podcasts); }); it('should change error message when findAllError', () => { /* Given */ const action = new FindAllError({message: 'something goes wrong'}); /* When */ const state = reducer(previousState, action); /* Then */ expect(state.error).toEqual({message: 'something goes wrong'}); }); }); });
a5a00ffc7b00208990435581e3501e5b5ce4745f
[ "TypeScript" ]
1
TypeScript
whosoonhwang/Podcast-Server
b7ad4a48ebdd2d514d73ce13ee77b959db04865d
11c59c46cc54c291661d558ca02fb7dd0785f370
refs/heads/main
<repo_name>matgim4btest/17b19<file_sep>/src/main/java/rs/edu/matgim/zadatak/Program.java package rs.edu.matgim.zadatak; public class Program { //Ponovo poslato. public static void main(String[] args) { DB _db = new DB(); _db.printNotUsedRacun(); _db.prikazSvihRacuna(); System.out.println(_db.zadatak(5, 3)); _db.prikazSvihRacuna(); } }
3388dde869194416389f6adafe6668669d784cdb
[ "Java" ]
1
Java
matgim4btest/17b19
9f02639cd7d0b65009dc82c7507113ba8c88e641
b0591aa52130ea2cf35a0f8277a90721807476d3
refs/heads/master
<file_sep>import csv from xml.etree.ElementTree import Element, SubElement, ElementTree import time from time import mktime from datetime import datetime import xml.sax.saxutils as saxutils import sys from ftplib import FTP import os, sys reload(sys) sys.setdefaultencoding('latin-1') lines_seen = set() # holds lines already seen outfile = open('E:\\\\tribune\\participantmedia_programs.txt', "w") newlist = open('E:\\\\tribune\\new.txt', "w") j=1 for line in open('E:\\\\tribune\\TMSIDSEARCH (1225-665).txt', "r"): if line not in lines_seen: # not a duplicate outfile.write(line) lines_seen.add(line) outfile.close() # create XML root = Element('xml') header = SubElement(root,'header') provider_child = Element('provider',id='PM1234') provider_child.text = 'ParticipantMedia' header.append(provider_child) schedule = SubElement(root,'schedule') i = 1 with open('E:\\\\tribune\\participantmedia_programs.txt') as f: f = csv.reader(f, delimiter='\t') for row in f: if row[1] in ('0','',None): print str(i) + '\t' + row[0] + '\t' + row[4] Title_Code = row[0].encode('latin-1').strip() Title_Class = row[2].encode('latin-1').strip() Default__Series_Name = row[3].encode('latin-1').strip() Title_Code_w_o_Prefix = row[6].encode('latin-1').strip() Default__Title_Synopsis = row[7].encode('latin-1').strip() Default__Title_Name = row[4].encode('latin-1').strip() if Title_Class in ('Episode'): if row[6].encode('latin-1').strip() not in ('null','',None): print "Season: " + str(int(float(Title_Code_w_o_Prefix)))[:1] print "Episode: " + str(int(str(int(float(Title_Code_w_o_Prefix)))[1:])) Season = str(int(float(Title_Code_w_o_Prefix)))[:1] Episode = str(int(str(int(float(Title_Code_w_o_Prefix)))[1:])) if row[6].encode('latin-1').strip() in ('null','',None): Season = str(int(float(Title_Code_w_o_Prefix)))[:1] Title_First_AirScheduled_Date_All_Schedules__TP_ = row[9].encode('latin-1').strip() #Title_MPAA_Code = row[8].encode('latin-1').strip() Title_Release_Year = row[10].encode('latin-1').strip() Stars = row[8].encode('latin-1').strip() TtlTMSID = row[1].encode('latin-1').strip() event = Element('event') Title_Length___HHMMSS__ = row[11] Title_FCC_Rating = row[12].encode('latin-1').strip() #Title_EPG_Code = row[13].encode('latin-1').strip() Title_Caption_Definitions = row[14].encode('latin-1').strip() programId = Element('programId') programId.text = Title_Code newlist.write(Title_Code + '\n') programType = Element('programType') if Title_Class in ('Film'): programType.text = 'Movie' else: programType.text = Title_Class if Title_Class in ('Episode'): seriesName = Element('seriesName') seriesName.text = Default__Series_Name.encode('utf-8') season = Element('season') season.text = Season episode = Element('episode') episode.text = Episode #titleCode = Element('titleCode') #titleCode.text = Title_Code_w_o_Prefix titleSynopsis = Element('titleSynopsis') titleSynopsis.text = Default__Title_Synopsis title = Element('title',lang='eng') title.text = Default__Title_Name firstAirDate = Element('firstAirDate') firstAirDate.text = Title_First_AirScheduled_Date_All_Schedules__TP_ #MPAA = Element('mpaaCode') #MPAA.text = Title_MPAA_Code Release = Element('releaseYear') Release.text = Title_Release_Year Actors = Element('actors') Actors.text = Stars length = Element('length') length.text = Title_Length___HHMMSS__ FCC = Element('fccRating') if Title_FCC_Rating.strip() in (''): print "Title_FCC_Rating = " + Title_FCC_Rating FCC.text = '' else: FCC.text = 'TV-' + Title_FCC_Rating print "Title_FCC_Rating = " + Title_FCC_Rating #EPG = Element('epg') #EPG.text = Title_EPG_Code CaptionDef = Element('captionDefinition') CaptionDef.text = Title_Caption_Definitions event.append(programId) event.append(programType) if Title_Class in ('Episode'): event.append(seriesName) event.append(season) event.append(episode) #event.append(titleCode) event.append(title) event.append(firstAirDate) #event.append(MPAA) event.append(Release) event.append(Actors) event.append(length) event.append(FCC) #event.append(EPG) event.append(CaptionDef) schedule.append(event) i += 1 def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i newlist.close() indent(root) tree = ElementTree(root) tree.write("E:\\\\tribune\\participantmedia_programs.xml", xml_declaration=True, encoding='utf-8', method="xml") ftp = FTP('ftp.dnsname.com') ftp.login('username','<PASSWORD>') try: file = open("E:\\\\tribune\\participantmedia_programs.xml",'rb') # file to send ftp.storbinary('STOR participantmedia_programs.xml', file) # send the file file.close() # close file and FTP ftp.quit() os.remove("E:\\\\tribune\\participantmedia_programs.txt") except Exception as e: print str(e) sys.exit(0) <file_sep>#!/usr/bin/python import json import webbrowser import time from datetime import datetime from shotgun_api3 import Shotgun #Change path to reflect file location #filename = 'file:///Users/mmontagnino/Desktop/python-api-master/fullcalendar-2.8.0/demos/' + 'Calendar.html' id = "d54c59d248f978ad103976c2b47875b06df5dc56c71afa774901d7791d9d9870" name = "Test_Calendar" srvr = "https://participant.shotgunstudio.com" sg = Shotgun(srvr, name, id) colors = {'<NAME>': 'red', '<NAME>': 'blue', '<NAME>': 'green', '<NAME>': 'purple', '<NAME>': 'cyan'} proj = sg.find_one("Project", [["name", "is", "Asset Pipeline"]]) print proj filters = [ ['project', 'is', proj], ['sg_status_list', 'is', 'wtg'] ] fields = [ 'entity.Shot.sg_sequence.Sequence.code', 'entity.Shot.sg_air_date', 'entity.Shot.code', 'content', 'task_assignees', 'sg_task_order', 'Id', # 'created_at', 'entity.Shot.sg_status_list', # 'content', 'start_date', 'due_date', 'entity.Shot.sg_title', 'entity.Shot.sg_title_name', # 'upstream_tasks', # 'downstream_tasks', # 'dependency_violation', # 'pinned' ] results = sg.find("Task", filters, fields) print "Due Date\tShot Code\tTitle\tTitle Name\tContent\tAssigned To" for r in results: s = str(r['due_date']) if s == "None": print "None\t" + str(r['entity.Shot.code']) + "\t" + str(r['entity.Shot.sg_title']) + "\t" + str(r['entity.Shot.sg_title_name']) + "\t" + str(r['content']) else: dueDate = datetime.strptime(s,'%Y-%m-%d') for u in r['task_assignees']: print str(dueDate) + "\t" + str(r['entity.Shot.code']) + "\t" + str(r['entity.Shot.sg_title']) + "\t" + str(r['entity.Shot.sg_title_name']) + "\t" + str(r['content']) +"\t" + str(u['name']) ###################### events = "" for r in range(0, len(results)): due = str(results[r]['due_date']) if due != "None": for u in range(0, len(results[r]['task_assignees'])): if len(results) - r > 1 or len(results[r]['task_assignees']) - u > 1: event = " {\n" event += " title: " s = "'" + str(results[r]['entity.Shot.code']) + ", " + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " },\n" events += event else: event = " {\n" event += " title: " s = "'" + str(results[r]['entity.Shot.code']) + ", " + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " }" events += event proj = sg.find_one("Project", [["name", "is", "Media Requests"]]) print proj filters = [ ['project', 'is', proj], ['sg_status_list', 'is', 'wtg'] ] fields = [ 'content', 'task_assignees', 'Id', 'due_date' ] results = sg.find("Task", filters, fields) if len(results) > 0: events += ",\n" else: events += "\n" for r in range(0, len(results)): due = str(results[r]['due_date']) if due != "None": for u in range(0, len(results[r]['task_assignees'])): if len(results) - r > 1 or len(results[r]['task_assignees']) - u > 1: event = " {\n" event += " title: " s = "'" + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " },\n" events += event else: event = " {\n" event += " title: " s = "'" + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " }" events += event proj = sg.find_one("Project", [["name", "is", "VOD"]]) print proj filters = [ ['project', 'is', proj], ['sg_status_list', 'is', 'wtg'] ] fields = [ 'entity.Shot.sg_sequence.Sequence.code', 'content', 'task_assignees', 'Id', 'entity.Shot.sg_title', 'entity.Shot.sg_title_name', 'due_date' ] results = sg.find("Task", filters, fields) if len(results) > 0: events += ",\n" else: events += "\n" print "Due Date\t\tTitle Name\t\tContent\t\t\tAssigned To" for r in results: s = str(r['due_date']) if s == "None": print "None\t" + str(r['entity.Shot.sg_title_name']) + "\t" + str(r['content']) else: dueDate = datetime.strptime(s,'%Y-%m-%d') for u in r['task_assignees']: print str(dueDate) + "\t" + str(r['entity.Shot.sg_title_name']) + "\t" + str(r['content']) +"\t" + str(u['name']) for r in range(0, len(results)): due = str(results[r]['due_date']) if due != "None": for u in range(0, len(results[r]['task_assignees'])): if len(results) - r > 1 or len(results[r]['task_assignees']) - u > 1: event = " {\n" event += " title: " s = "'" + str(results[r]['entity.Shot.sg_title_name']) + ", " + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " },\n" events += event else: event = " {\n" event += " title: " s = "'" + str(results[r]['entity.Shot.sg_title_name']) + ", " + str(results[r]['content']) +"',\n" event += s event += " url: " s = "'https://participant.shotgunstudio.com/detail/Task/" + str(results[r]['id']) +"',\n" event += s event += " backgroundColor: '" s = colors[results[r]['task_assignees'][u]['name']] + "',\n" event += s event += " start: " s = "'" + datetime.strptime(due,'%Y-%m-%d').strftime("%Y-%m-%d") + "'\n" event += s event += " }\n" events += event f = open('E:\\scripts\Pivot\BopsCalendar\html\BopsCalendar.html','w') message = """<!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <meta http-equiv="refresh" content="900" > <link href='../fullcalendar.css' rel='stylesheet' /> <link href='../fullcalendar.print.css' rel='stylesheet' media='print' /> <script src='../lib/moment.min.js'></script> <script src='../lib/jquery.min.js'></script> <script src='../fullcalendar.min.js'></script> <script> $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, defaultDate: """ message += "'"+time.strftime("%Y-%m-%d")+"'" message += """, editable: false, eventLimit: true, // allow "more" link when too many events events: [ """ message += events message += """ ] }); }); </script> <style> body { margin: 40px 10px; padding: 0; font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif; font-size: 14px; } #calendar { max-width: 1200px; margin: 0 auto; } .my-legend { max-width: 1200px; margin: 0 auto; } .my-legend .legend-title { text-align: left; margin-bottom: 8px; font-weight: bold; font-size: 90%; max-width: 1200px; } .my-legend .legend-scale ul { margin: 0; padding: 0; float: left; list-style: none; } .my-legend .legend-scale ul li { display: block; float: left; width: 50px; margin-bottom: 6px; text-align: center; font-size: 80%; list-style: none; } .my-legend ul.legend-labels li span { display: block; float: left; height: 15px; width: 50px; } .my-legend .legend-source { font-size: 70%; color: #999; clear: both; } .my-legend a { color: #777; } </style> </head> <body> <div id='calendar'></div> <div class='my-legend'> <div class='legend-title'>Color Mapping:</div> <div class='legend-scale'> <ul class='legend-labels'> <li><span style='background:red;'></span>Helen</li> <li><span style='background:blue;'></span>Rafiah</li> <li><span style='background:green;'></span>Nathaniel</li> <li><span style='background:purple;'></span>Nick</li> <li><span style='background:cyan;'></span>Marian</li> </ul> </div> </div> </body> </html> """ f.write(message) f.close() <file_sep>import csv from xml.etree.ElementTree import Element, SubElement, ElementTree import xml.etree.ElementTree as ET import time from time import mktime from datetime import datetime, timedelta import xml.sax.saxutils as saxutils import sys from ftplib import FTP import datetime import os, sys import gzip import re from smtplib import SMTP_SSL as SMTP from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage import shutil reload(sys) sys.setdefaultencoding('latin-1') now = datetime.date.today() ftp = FTP('ftp.dnsname.com') ftp.login('username','<PASSWORD>') ftp.cwd('On2') ftp.cwd('pivo') files = [] try: files = ftp.nlst() except ftplib.error_perm, resp: if str(resp) == "550 No files found": print "No files in this directory" else: raise try: if not os.path.exists("E:\\\\tribune\\" + now.strftime("%Y%m%d") + "\\"): os.makedirs("E:\\\\tribune\\" + now.strftime("%Y%m%d") + "\\") except resp: print "Folder already created." folder = "E:\\\\tribune\\" + now.strftime("%Y%m%d") + "\\" try: on_connector_programs_filename = now.strftime("on_connector_programs-PIVOT_%Y%m%d.xml.gz") rcommand = "RETR " + on_connector_programs_filename ftp.retrbinary(rcommand,open(folder + on_connector_programs_filename, 'wb').write) zipFile = gzip.open(folder + on_connector_programs_filename,"rb") unCompressedFile = open(folder + now.strftime("on_connector_programs-PIVOT_%Y%m%d.xml"),"wb") decoded = zipFile.read() unCompressedFile.write(decoded) zipFile.close() unCompressedFile.close() os.remove(folder + on_connector_programs_filename) except Exception as e: print str(e) shutil.rmtree(folder) sys.exit(0) try: on_connectors_filename = now.strftime("on_connectors-PIVOT_%Y%m%d.xml.gz") rcommand = "RETR " + on_connectors_filename ftp.retrbinary(rcommand,open(folder + on_connectors_filename, 'wb').write) zipFile = gzip.open(folder + on_connectors_filename,"rb") unCompressedFile = open(folder + now.strftime("on_connectors-PIVOT_%Y%m%d.xml"),"wb") decoded = zipFile.read() unCompressedFile.write(decoded) zipFile.close() unCompressedFile.close() os.remove(folder + on_connectors_filename) except Exception as e: shutil.rmtree(folder) sys.exit(0) try: on_unmappables_filename = now.strftime("on_unmappables-PIVOT_%Y%m%d.xml.gz") rcommand = "RETR " + on_unmappables_filename download_response = ftp.retrbinary(rcommand,open(folder + on_unmappables_filename, 'wb').write) zipFile = gzip.open(folder + on_unmappables_filename,"rb") unCompressedFile = open(folder + now.strftime("on_unmappables-PIVOT_%Y%m%d.xml"),"wb") decoded = zipFile.read() unCompressedFile.write(decoded) zipFile.close() unCompressedFile.close() os.remove(folder + on_unmappables_filename) except Exception as e: shutil.rmtree(folder) sys.exit(0) try: tree = ET.parse(folder + now.strftime("on_connectors-PIVOT_%Y%m%d.xml")) root = tree.getroot() except Exception as e: sys.exit(0) newIds = set() for line in open('E:\\\\tribune\\new.txt', "r"): newIds.add(line.strip()) with open(folder + now.strftime("mappings_%Y%m%d.csv"), 'wb') as csvfile: fieldnames = ['house_id', 'tmsid'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for connectors in root.findall('connectors'): ENTITY = connectors.findall('entity') for element in ENTITY: ID = element.findall("id") LINK = element.findall("link") for item in ID: if item.get("type") == "TMSId": TMSId = item.text for link in LINK: if link.get("idType") == "ProviderId": ProviderId = link.text if ProviderId in newIds: # is it a new id writer.writerow({'house_id': ProviderId, 'tmsid': TMSId}) tree = ET.parse(folder + now.strftime("on_unmappables-PIVOT_%Y%m%d.xml")) root = tree.getroot() with open(folder + now.strftime("unmapped_%Y%m%d.csv"), 'wb') as csvfile: fieldnames = ['house_id', 'tmsid','reason'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for connectors in root.findall('connectors'): ENTITY = connectors.findall('entity') for element in ENTITY: ID = element.findall("id") LINK = element.findall("link") MESSAGE = element.findall("message") for item in ID: if item.get("type") == "TMSId": TMSId = item.text for link in LINK: if link.get("idType") == "ProviderId": ProviderId = link.text for message in MESSAGE: Reason = message.get("reason") Reason += ', Missing' DETAIL = message.findall('detail') for details in DETAIL: Reason += ' ' + details.text + ',' Reason = Reason[:-1] if ProviderId in newIds: # is it a new id writer.writerow({'house_id': ProviderId, 'tmsid': TMSId, 'reason': Reason}) SMTPserver = 'smtp.emailsrvr.com' sender = '<EMAIL>' destination = ["<EMAIL>","<EMAIL>","<EMAIL>", "<EMAIL>", "<EMAIL>"] #For test purposes: #destination = ["<EMAIL>"] USERNAME = "<EMAIL>" PASSWORD = "<PASSWORD>" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Attached are the daily results from Gracenote, mapped results and unmapped with reason. """ os.chdir(folder) try: subject=now.strftime("Gracenote TMS Mapped Results - %m/%d/%Y") msg = MIMEMultipart() mapped_filename = now.strftime("mappings_%Y%m%d.csv") f1 = file(mapped_filename) attachment1 = MIMEText(f1.read()) attachment1.add_header('Content-Disposition', 'attachment1', filename=mapped_filename) msg.attach(attachment1) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message try: subject=now.strftime("Gracenote TMS Unmapped Results - %m/%d/%Y") msg = MIMEMultipart() unmapped_filename = now.strftime("unmapped_%Y%m%d.csv") f2 = file(unmapped_filename) attachment2 = MIMEText(f2.read()) attachment2.add_header('Content-Disposition', 'attachment2', filename=unmapped_filename) msg.attach(attachment2) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message
d9a39dabf228f8b242bc6a56e1d7edf380322546
[ "Python" ]
3
Python
marianina8/Python
52825b541c980d566173858b7c175e24171149c2
cf0b5a9233d5be790a154c96bca4762d3369084f
refs/heads/master
<repo_name>LeG3nDz/v3.1.stephane-richin.lan<file_sep>/app/a-propos.md --- layout: page title: À propos permalink: /a-propos/ --- <section class="small-4 block-section is-block"> <h2>Hello world :)</h2> <p><b>Moi c'est Stéphane, j'ai 24 ans et j'habite à Lyon. Passionné d'informatique depuis très longtemps, j'ai découvert l'univers du web grâce à un ami qui débutait dans le domaine. Très vite, l'envie d'en savoir plus c'est fait connaitre. Accroché par un web qui me fascine toujours plus, j'ai rapidement souhaité en faire une vraie vocation professionnelle.</b></p> <p>J'ai débuté dans le web il y a 4 ans et eu la chance de ne pas connaître l'époque IE6-8. J'arrive donc dans un air <strong>responsive, web perf et accessibilité</strong>. Un véritable régal, car ce sont des domaines qui évoluent constamment. Malgré ma jeune expérience, on m'a appris à rendre un projet compatible IE8 (même sur un projet responsive, RIP). Bref, le web est devenu une véritable passion dans laquelle l'envie d'apprendre et de progresser est constamment présente.</p> <p>Ce petit site a été développé sur <a href="http://jekyllrb.com/" target="_blank">Jekyll</a>, un générateur de sites statiques écrit en Ruby. Grâce à son système de templating puissant, Jekyll me permet d'avoir la main sur la totalité de mon code sans être une usine à gaz (coucou les CMS :)). Pour les mises en production, j'utilise Dploy, un plugin NodeJS comparable à rsync. Il synchronise mes commits Git et s'occupe de mettre à jour les fichiers. Rapide, simple et efficace.</p> <p>Si tu es curieux (coquin va), la totalité de mon code source est disponible sur <a href="https://github.com/LeG3nDz/v3.stephane-richin.lan" target="_blank">Github</a>.</p> </section> <div class="about-me"> <section class="block-section is-block"> <h2>Mes compétences</h2> {% include skill.html %} </section> <section class="block-section is-block about-contact"> <h2>Contactez-moi</h2> <address class="icon-geoloc icon-rounded-small align-items-center"> {{ site.streetAddress }}, {{ site.postalCode }}, {{ site.addressLocality }} <br> {{ site.addressCountry }} </address> <a href="mailto:{{ site.email }}" class="icon-mail icon-rounded-small align-items-center"><span>{{ site.email }}</span></a> <a href="tel:{{ site.tel }}" target="_blank" class="icon-phone icon-rounded-small align-items-center"><span>{{ site.tel }}</span></a> </section> <section class="block-section is-block"> <h2>Expériences</h2> {% include experince.html %} </section> <section class="block-section is-block"> <h2>Formation</h2> {% include formation.html %} </section> </div><file_sep>/app/private/js/app.navigation.js // Navigation // - - - - - - - - - - - - - - - - - - - - - - - - - /** * Description for navigationMobile * @private * @method navigationMobile * @return {Object} description */ var closeNavigationMobile = function () { var $hamburger = $('#js-hamburger'), $offCanvasExit = $('.js-off-canvas-exit'); $hamburger.on('click', function() { $(this).toggleClass(openClass); }); $offCanvasExit.on('click', function() { $hamburger.removeClass(openClass); }); };<file_sep>/app/private/js/app.contact.js // Contact // - - - - - - - - - - - - - - - - - - - - - - - - - /** * Description for contactForm * @private * @method contactForm * @return {Object} description */ var contactForm = function () { var $contactForm = $('#js-contact-form'), $successMessage = $('#js-form-success-callout'), $errorMessage = $('#js-error-callout'), $buttonSubmit = $('#js-contact-form-submit'); $contactForm.submit(function() { var formData = $(this).serialize(); $.post($(this).attr('action'), formData, function(data) { $successMessage.addClass('is-animate'); setTimeout(function() { $contactForm.find('input, textarea').val(''); $contactForm.find('input:first').focus(); $successMessage.removeClass('is-animate'); }, 5000); }); return false; }); };<file_sep>/app/contact.md --- layout: page title: Contactez-moi permalink: /contact/ --- <aside class="columns small-4 large-4 large-push-8 block-grid contact-aside"> <div class="small-4 medium-4 large-12"> <h2>Contact</h2> <address> <span>{{ site.streetAddress }}, {{ site.postalCode }}, {{ site.addressLocality }} <br> {{ site.addressCountry }}</span> </address> <p> Tel. : <a href="tel:{{ site.tel }}" target="_blank"><span>{{ site.tel }}</span></a> <br> E-mail : <a href="mailto:{{ site.email }}"><span>{{ site.email }}</span></a> </p> </div> <div class="show-for-medium small-4 medium-4 large-12"> <h2 class="hide-for-large">Réseaux sociaux</h2> {% include social-networks.html %} </div> </aside> <section class="small-4 large-8 large-pull-4"> <h2 class="columns"> <strong class="block-border-top">Formulaire</strong> </h2> <div id="js-success-callout" class="columns is-hidden"> <p class="callout success">Votre message a été envoyé :)</p> </div> <form action="/script/contact/contact.php" method="post" id="js-contact-form" class="contact-form is-relative"> <div class="small-4 block-grid"> <div class="columns small-4 medium-4 input"> <input type="text" name="name" id="name" class="input-field" required autofocus> <label for="name" class="input-label icon-valid">Nom</label> </div> <div class="columns small-4 medium-4 input"> <input type="email" name="email" id="email" class="input-field" required> <label for="email" class="input-label icon-valid">E-mail</label> </div> </div> <div class="columns input"> <textarea name="message" id="message" class="input-field" required></textarea> <label for="message" class="input-label icon-valid">Message</label> </div> <div class="columns"> <button type="submit" id="js-contact-form-submit" class="small-4 button button-submit">Envoyer</button> </div> <input type="hidden" name="submitted" id="submitted" value="true"> <div id="js-form-success-callout" class="form-success-callout"> <p> <strong class="icon-send">Merci</strong> Ton message vient de m'être transmis. <br> Je tâcherai de te répondre dans les plus bref délais :) </p> </div> </form> </section><file_sep>/app/private/js/app.function.js // Function // - - - - - - - - - - - - - - - - - - - - - - - - - // Déplacer un élément // - - - - - - - - - - - - // Déplacer un élément ($el) dans un bloc ($elMoving) // * Ex. : // minwidth(1025, function(){ // movingElement(elements, sidebar); // }); function movingElement($el, $elMoving) { for (var i = 0; i < $el.length; i++) { $elMoving[i].appendChild($el[i]); } } // hasClass, addClass, removeClass // - - - - - - - - - - - - function hasClass(ele,cls) { return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } }<file_sep>/app/404.md --- layout: page title: Page non trouvée permalink: /404/ --- <div class="columns page-404 text-center"> <h2>404</h2> <p> <strong>Page non trouvée</strong> </p> <a href="/" class="button small-4 medium-3 large-3">Retour sur la page d'accueil</a> </div><file_sep>/app/private/js/app.relocate.js // Relocate // - - - - - - - - - - - - - - - - - - - - - - - - - // * Relocate permet de déplacer des éléments au resize en JavaScript // * Fonctionnement : relocate(width, elements, destinationElement); // * Documentation : https://github.com/edenspiekermann/minwidth-relocate // * Ex. : // var elements = document.getElementById("elements"), // sidebar = document.getElementById("destinationElement"); // relocate(480, elements, destinationElement); // Vars // - - - - - - - - - - - - var $backLink = document.getElementById('js-back-link'), $backLinkMoving = document.getElementById('js-article-aside'), $postLatest = document.getElementById('js-post-latest'), $postLatestMoving = document.getElementById('js-post-latest-moving'), $share = document.getElementById('js-share'), $shareMoving = document.getElementById('js-share-moving'); // Si on est sur un article // - - - - - - - - - - - - if ($article) { relocate(1025, $backLink, $backLinkMoving); relocate(1025, $postLatest, $postLatestMoving); relocate(1025, $share, $shareMoving); }<file_sep>/Gruntfile.js // Gruntfile.js module.exports = function (grunt) { require('load-grunt-tasks')(grunt); //loads the various task configuration files var configs = require('load-grunt-configs')(grunt, { // Config path default config: { nodeModules: 'node_modules', privateScss: 'app/private/scss', publicCssPath: 'app/public/css', publicCss: '<%= config.publicCssPath %>/app.min.css', privateJs: 'app/private/js', privateJsIce: '<%= config.privateJs %>/ice', publicJsPath: 'app/public/js', publicJs: '<%= config.publicJsPath %>/app.min.js', urlProxy: '127.0.0.1:4000' } }); grunt.initConfig(configs); // BrowserSync grunt.registerTask('proxy', [ 'browserSync:reload', // Using the php instance as a proxy 'watch' // Any other watch tasks you want to run ]); // Les tâches de productions grunt.registerTask('prod', [ 'jshint', 'concat', 'babel', 'uglify', 'sass', 'combine_mq', 'cssmin', 'htmlmin', 'notify:prod' ]); };<file_sep>/app/blog/_posts/2014-11-28-analisez-vos-stats-de-coder-avec-codeivate.md --- layout: blog-post title: Analisez vos stats de codeur description: Codeivate est un plugin qui permet d'obtenir vos statistiques de codeur grâce à votre éditeur de texte type: article date: 2014-11-28 category: divers image: "codeivate" time: 2 comments: true --- J'ai récemment découvert Codeivate, un plugin disponible sur plusieurs éditeurs de texte et qui permet d'obtenir vos statistiques de codeur. <!--more--> Il est possible de connaitre les langages sur lesquels vous travaillez le plus souvent avec un système de niveau, un peu dans le style d'un RPG. Plus vous codez, plus vous montez de niveau ! <a class="image-modal" data-reveal-id="codeivate" data-reveal-class="small"> <img class="image" src="/public/images/blog/screenshot-codeivate.jpg" alt="States Codeivate de <NAME>"> </a> [Codeivate](http://www.codeivate.com/summary){:target="_blank"} propose d'autres statistiques comme le nombre de jour passer à coder, votre meilleure série d'heures de code, les stats très précises sur les langages utilisés (plus de 50!) pendant la journée ou encore votre système d'exploitation préféré. C'est très geek et très fun, j'adore ! Il est également possible de voir les langages tendances avec les utilisateurs du monde entier, encore un truc cool :) L'[installation](http://codeivate.com/install){:target="_blank"} sur Sublime Text est très rapide. Il suffit d'installer Codeivate à partir du package manager (ou github, selon les préférences), de créer un compte sur [codeivate.com](http://codeivate.com){:target="_blank"} puis d'ajouter le token d'accès dans la configuration de votre soft. Liste des éditeurs compatibles avec le plugin : - WebStorm - RubyMine - PyCharm - PhpStorm - AppCode - IntelliJ Si vous êtes un utilisateur de Brackets, une béta est disponible. Pour la recevoir, il vous suffit d'envoyer un mail à [<EMAIL>](mailto:<EMAIL>) avec votre pseudo Github.<file_sep>/app/_includes/experince.html <ul class="no-bullet experince-list"> {% for experince in site.data.experince %} <li class="experince-item"> <header class="block-grid"> <h3 class="small-4 experince-title">{{ experince.title }}</h3> {% if experince.link %} <a href="{{ experince.link }}" rel="nofollow" target="_blank" class="experince-office icon-work"><span>{{ experince.company }}</span></a> {% else %} <span class="experince-office icon-work">{{ experince.company }}</span> {% endif %} <time class="experince-date icon-calendar">{{ experince.date }}</time> </header> <ul> {% for works in experince.works %} <li>{{ works.work }}</li> {% endfor %} </ul> </li> {% endfor %} </ul><file_sep>/app/private/js/app.pageTransition.js // Animation page // - - - - - - - - - - - - - - - - - - - - - - - - - /** * Description for animationPage * @private * @method animationPage * @param {Object} $elem * @return {Object} description */ var pageTransition = function ($elem) { $($elem).on('click', function(e) { e.preventDefault(); var url = $(this).attr('href'); $($container).addClass('is-animate'); // TODO: Récupéré le temps d'animation dynamiquement // dans la règle CSS setTimeout(function() { window.location = url; }, 700); }); };<file_sep>/app/private/js/app.button.js // Button // - - - - - - - - - - - - - - - - - - - - - - - - - // buttonClick // - - - - - - - - - - - - /** * Description for buttonClick * @private * @method buttonClick * @param {Object} $elem * @return {Object} description */ var buttonClick = function ($elem) { var ink, d, x, y; // TODO: Revoir le nom des classes $($elem).on('click', function(e){ if ($(this).find('.ink').length === 0) { $(this).prepend('<span class="ink"></span>'); } ink = $(this).find(".ink"); ink.removeClass("animate"); if (!ink.height() && !ink.width()) { d = Math.max($(this).outerWidth(), $(this).outerHeight()); ink.css({ height: d, width: d }); } x = e.pageX - $(this).offset().left - ink.width()/2; y = e.pageY - $(this).offset().top - ink.height()/2; ink.css({top: y+'px', left: x+'px'}).addClass("animate"); }); }; // buttonBackToTop // - - - - - - - - - - - - /** * Description for buttonBackToTop * @private * @method buttonBackToTop * @return {Object} description */ var buttonBackToTop = function ($elem, $duration) { $($elem).on('click', function() { $($container).animate({ scrollTop: 0 }, $duration); }); };<file_sep>/app/blog/_posts/2015-01-04-chocolatey-pres-pour-un-apt-get.md --- layout: blog-post title: Chocolatey, près pour un apt-get ? description: Chocolatey est un gestionnaire de paquet open source pour Windows. type: article date: 2015-01-04 category: windows image: "chocolatey" imageSmall: true time: 5 --- Chocolatey est un puissant gestionnaire de paquet pour Windows, comparable à la commande apt-get sur Linux. <!-- more --> Si il y a bien une chose qui manque cruellement sur Windows, c'est d'être en mesure d'installer n'importe quel soft en quelques secondes et de manière pratique. C'est donc via [Putain de Code](http://putaindecode.fr/posts/windows/comment-coder-sous-windows/){:target="_blank"} que j'ai fait la découverte de Chocolatey qui apporte cette fonctionnalité, avec plus de 2500 programmes dans sa base de données ! Nous allons voir qu'en plus de profiter d'une installation (ou désinstallation) très rapide, Chocolatey permet également de vérifier si des mises à jours sont disponibles grâce à ChocolateyGUI. <br> <img src="/public/images/blog/logo-chocolatey.jpg" alt="Logo Chocolatey" class="is-center"> ## Installation de Chocolatey Nul besoin d'ouvrir son navigateur favoris pour télécharger et installer Chocolatey, une simple ligne de commande en mode administrateur suffit : {% highlight shell %} @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin {% endhighlight %} ## Installation d'un paquet A ce jour, Chocolatey propose plus de [2500 programmes](https://chocolatey.org/packages){:target="_blank"} ! La plupart sont orientés développement, néanmoins, les plus connus telques Skype, VLC, Audacity ou encore Google Drive sont présents. Une fois votre paquet trouvé, il suffit de lancer la commande <code>choco install nomDuPaquet</code>. Exemple avec Ruby : {% highlight shell %} choco install ruby {% endhighlight %} Il est possible d'installer plusieurs paquets en une seul ligne de commande, en les indiquants les uns à la suite des autres : {% highlight shell %} choco install ruby ruby2.devkit {% endhighlight %} BIM ! On install Ruby et DevKit sans rien faire, au top. C'est cool, mais Chocolatey ne se limite pas uniquement à ça. ## Mise à jour d'un paquet L'une de ses puissances est également la [mise à jour des paquets](https://github.com/chocolatey/chocolatey/wiki/CommandsUpdate){:target="_blank"}. La manière est similère à l'installation, on remplace <code>install</code> par <code>update</code> : {% highlight shell %} choco update ruby {% endhighlight %} Dans la suite de ce billet, nous verrons qu'il est possible de vérifier si une mise à jour est disponible grace à ChocolateyGUI. ## Rechercher un paquet Si on veut éviter d'aller sur le listing des paquets disponibles, on peut très bien effectuer une [recherche depuis la ligne de commande](https://github.com/chocolatey/chocolatey/wiki/CommandsList){:target="_blank"} : {% highlight shell %} choco search nodejs {% endhighlight %} <a class="image-modal" data-reveal-id="chocolatey-search"> <img class="image" src="/public/images/blog/chocolatey-search.jpg" alt="Recherche Chocolatey en ligne de commande"> </a> Par expérience, préferez les paquets avec <code>.install</code> pour assurer leurs présences dans les PATH Windows, au cas où :) ## Chocolatey GUI ChocolateyGUI est une interface graphique pour Chocolatey. Elle facilite grandement la gestion de vos paquets : - Liste des paquets installés - Liste des paquets disponibles sur [Chocolatey.org](https://chocolatey.org/packages){:target="_blank"} - Rechercher un paquet - Installation/déinstallation d'un paquet - La version du paquet - Mise à jour du paquet <a class="image-modal" data-reveal-id="chocolateyGUI"> <img class="image" src="/public/images/blog/chocolatey-gui.jpg" alt="Chocolatey GUI"> </a> ## Conclusion Chocolatey est un excellent outil [open source](https://github.com/chocolatey/chocolatey){:target="_blank"} possédant une liste de paquets très riche qui grandit chaque jour. Je pense néanmoins qu'il est important de souligner certains points sur l'utilisation de Chocolatey. N'oublions pas que nous dépendons des mainteneurs bénévoles des paquets, ce qui implique deux choses : - Si un mainteneur arrête de maintenir ou prend son temps pour le mettre à jour le paquet, on est vulnérable - On fait confiance au mainteneur qui, s’il le décide, peu mettre un malware dans son package ou s’il se fait contaminer par un virus, pourrit tout le monde Il s'agit de cas très rare, qui ne m'empêche pas d'utiliser Chocolatey dans mon quotidiens et de le conseiller aux nombreux développeurs qui ne le connaisse pas encore :) <file_sep>/todo.txt - Fixer la sidebar sur un article - Créer les 301 - Voir si une optimisation peut-être effectuée sur le CSS - Ajout de balise aria - Animation lorsqu'un mail est envoyé via le formulaire de contact <file_sep>/app/blog/_posts/2014-12-14-javascript-en-live-avec-evalprinter.md --- layout: blog-post title: Du JavaScript en live avec EvalPrinter description: EvalPrinter permet d'executer du code JavaScript, CoffeeScript ou Python directement dans la console de l'editeur type: article date: 2014-12-14 category: html-css-js image: "eval-printer-et-javascript" time: 1 comments: true --- EvalPrinter est un plugin Sublime Text qui execute une partie de votre code JavaScript directement dans la console de l'éditeur. <!-- more --> Cela permet de visualiser le résultat sans compliquer et sans passer par le navigateur, un véritable gain de temps. Actuellement, trois langages sont pris en charges : - JavaScript - CoffeeScript - Python Cependant, l'éditeur du plugin reste ouvert à toutes proposition sur le support d'un nouveau langages. ## CoffeeScript et EvalPrinter [EvalPrinter](https://packagecontrol.io/packages/EvalPrinter){:target="_blank"} a besoin de NodeJS ainsi que du plugin <code>coffee-script</code> pour compiler votre code dans la console Sublime Text. Pour cela, lancez la commande : {% highlight shell %} npm install -g coffee-script {% endhighlight %} Une fois l'installation de CoffeeScript terminée, il ne reste plus qu'à installer EvalPrinter sur Sublime Text à partir du [Package Control](https://sublime.wbond.net/browse){:target="_blank"}. Les principaux raccourcis : * <kbd>SHIFT</kbd> + <kbd>ALT</kbd> + <kbd>ENTER</kbd> : apperçu du code, sans le "live session" * <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>ALT</kbd> + <kbd>ENTER</kbd> : lance le "live session"<file_sep>/app/blog/_posts/2015-01-20-pourquoi-je-suis-passe-de-sublime-text-a-brackets.md --- layout: blog-post title: Pourquoi je suis passé de Sublime Text à Brackets description: Comparaison des fonctionnalités entre Brackets, l'éditeur open source développé par Adobe, et Sublime Text type: article date: 2015-01-20 category: divers image: "brackets" time: 5 comments: true --- Brackets est un éditeur de code open source orienté pour le développement front-end et développé par l'équipe d'Adobe. <!-- more --> <img src="/public/images/blog/logo-brackets.jpg" alt="Logo Brackets" class="is-center"> Après plusieurs longs mois de tests depuis 2012, Adobe a presentée début novembre la version finalisée de son éditeur de code. [Brackets](http://brackets.io/){:target="_blank"} arrive avec une interface dédiée principalement au code, tout ça avec un design moderne et intuitif. ## Good-by, Sublime Text Fidèle servant de Sublime Text pendant près de 2 ans, ce dernier correspondait parfaitement à mes besoins : il est rapide, légé, customisable et possède une communauté active. Cependant, Sublime Text n'a pas la réputation d'être un éditeur de code qui évolu vite, contrairement à [Brackets](http://brackets.io/){:target="_blank"} qui évolu constament. De plus, la création d'extension est beaucoup moins accessible sur Sublime Text, qui est développé en Python. Brackets à l'avantage d'être développé entièrement avec les technos web HTML, CSS et JavaScript ce qui facilite la tâche. Un vrai plus ! ## Hello, Brackets ! [Brackets](http://brackets.io/){:target="_blank"} propose à peu de choses près les mêmes fonctionnalités que Sublime Text. La différence ? Elles sont bien plus poussées et modernisées. ### Un gestionnaire d'extension déjà intégré Brackets propose un gestionnaire d'extension plus complet que Sublime Text. Les extensions les plus connus sont déjà disponibles : Emmet, LiveReload, Git ou encore Grunt. Si vous êtes curieux, la liste des extensions que j'utilise est disopnible sur [Github](https://github.com/LeG3nDz/brackets-extensions){:target="_blank"}. ### Une UI plus moderne et des fonctionnalités innovantes Brackets offre une interface plus moderne et intuitif. <a class="image-modal" data-reveal-id="brackets-screenshot" data-image-resize> <img class="image" src="/public/images/blog/brackets-screenshot.jpg" alt="Brackets"> </a> L'éditeur d'Adobe a la particulariter d'être conçu principalement pour l'intégration web (HTML, CSS et JavaScript) et propose des fonctionnalités de bases plutôt sympa : - **Quick Edit** : permet l'edition du CSS (ou SCSS) directement depuis le code HTML avec un <kbd>CTRL+E</kbd> sur le nom d'une classe - **Live Development** : comparable à LiveReload, l'extension permet l'affichage en temps réel d'une page HTML - **Extract for Brackets** : permet d'importer un fichier PSD et d'y extraire divers éléments comme la couleur ou les dimensions ### Un logiciel libre Me concernant, l'aspect open source de Brackets est un point non négligable. Adobe mise sur la communauté pour maintenir et évoluer le projet : > Brackets was originally created by Adobe, but is maintained by the community ## Conclusion Pour finir, voici un petit récap' des avantages et des inconvéniants de Brackets après 2 mois d'utilisation : ### Les principaux avantages - Un éditeur moderne, qui rox et open source - Quick Edit (edition du CSS à partir de l'HTML) - Extraction d'un PSD dans l'éditeur - Gestionnaire d'extension directement intégré - Outils de développeur - Création d'extension plus accessible ### Les inconvéniants - Pas fait pour les gros langages types PHP, Ruby ou encore Python - Un peu gourmand, Sublime Text forever - Lecture uniquement des formats UTF-8. Problématique pour la maintenance des projets dinosaure <a href="" target="_blank">Télécharger Brackets</a> <br> <a href="" target="_blank">Github officiel</a><file_sep>/app/private/js/app.postsFilter.js // Post filter // - - - - - - - - - - - - - - - - - - - - - - - - - /** * Description for postsFilter * @private * @method postsFilter * @return {Object} description */ var postsFilter = function () { var $postCategory = $('.js-post-category'), $postItem = $('.post-item'); // Au clic sur .js-post-category $postCategory.on('click', function() { // On stock le data-category de son <li>, qui est la catégorie qui sera affichée var currentCategory = $(this).closest('li').data('category'); // Classe qui permet de savoir si on est au premier ou second clic $(this).toggleClass(activeClass); // Si l'élément est actif if ($(this).hasClass(activeClass)) { // On parcourt chaque <li> $postItem.each(function() { // On stock leur data-category var category = $(this).data('category'); // Si la catégorie est différente de currentCategory if (currentCategory != category) { // Alors on les caches $(this).addClass(disableClass); $(this).find($postCategory).removeClass(activeClass); // Sinon } else { // On les affiches $(this).removeClass(disableClass); } }); // Sinon, c'est qu'on ne filtre plus } else { // Alors on réaffiche les articles $postItem.removeClass(disableClass); } }); };<file_sep>/app/blog/_posts/2015-02-22-synchroniser-une-div-scrollable-sur-browsersync.md --- layout: blog-post title: Synchroniser une div scrollable sur BrowserSync description: type: article date: 2015-02-22 category: html-css-js image: "browsersync" time: 5 comments: true --- Par défaut, la synchronisation du scroll de BrowserSync est basée sur le <code><body></code>. Nous allons voir qu'il est possible de modifier cette option. <!-- more --> BrowserSync est un module NodeJS qui permet de synchroniser vos pages web et de créer un simple serveur HTTP depuis n'importe quel dossier ou un proxy pour le côté développement. BrowserSync intègre [localtunnel](http://localtunnel.me/){:target="_blank"}, un autre module NodeJS qui permet d'avoir un accès public à son site sans paramétrage de DNS. En plus d'écouter la modification de vos fichiers, BrowserSync peut également synchroniser vos navigateurs. En gros, si vous scrollez, remplissez un formulaire ou changez de page, l'action s'effectuera sur tous les appareils, et de manière très fluide. {% highlight shell %} browser-sync start --files "css/*.css, js/*.js, **/*.php" --proxy url-du-serveur.lan {% endhighlight %} Le principal problème que j'ai rencontré jusqu'à maintenant est le scroll. Suivant la structure du site, le scroll de la page n'est pas systématiquement le <code><body></code>. C'est le cas sur ce site pour des [raisons techniques](/blog/html-css-js/fixer-la-navigation-offcanvas-sur-foundation/){:target="_blank"}. Du coup, la synchro' du scroll ne fonctionnait plus :(. Néanmoins, l'auteur du plugin, shakyShane, [propose une solution](https://github.com/BrowserSync/browser-sync/issues/273#issuecomment-57427711){:target="_blank"} en attendant qu'elle soit implémentée dans les prochaines versions de BrowserSync. L'idée est d'installer BrowserSync directement dans votre working dir et de créer deux fichiers <code>js</code> qui vont surcharger la configuration du module. ## Mise en place du nouveau conteneur On commence donc par installer BrowserSync : {% highlight shell %} npm install browser-sync --save-dev {% endhighlight %} Ensuite, au même niveau que votre dossier node_modules, créez un fichier <code>bs.js</code> et inserez ceci : {% highlight javascript %} var browserSync = require("browser-sync"); browserSync.use({ plugin: function (opts, bs) {}, hooks: { "client:events": function () { return ["div:scroll"] }, "client:js": require("fs").readFileSync("./plugin.js") } }); {% endhighlight %} Ensuite, créez un nouveau fichier <code>plugin.js</code> avec le code ci-dessous. Modifiez la variable <code>$elem</code> par votre nouveau conteneur : {% highlight javascript %} (function ($window, $document, bs) { var $elem = $document.querySelector(".scroller"); var socket = bs.socket; // Listen to the scroll event on your element $elem.addEventListener("scroll", function(evt) { // Emit the event socket.emit("div:scroll", evt.srcElement.scrollTop); }); // Listen for the event in other browsers socket.on("div:scroll", function (scrollTop) { // Set the element scroll position to match $elem.scrollTop = scrollTop; }); })(window, document, ___browserSync___); {% endhighlight %} Une fois vos deux fichiers créés et configurés, il ne rèste plus qu'à lancer la commande Node : {% highlight shell %} node bs.js {% endhighlight %} Et c'est terminé ! Votre nouveau conteneur est maintenant synchronisé avec BrowserSync :). Solution simple et efficace en attendant la mise en place de manière officielle.<file_sep>/app/blog/_posts/2014-10-02-nouvelles-version-du-site.md --- layout: blog-post title: Nouvelle version du site description: La toute nouvelle version (3) de stephane-richin.fr est en ligne. Une version plus moderne, responsive, et qui s'adapte à mes besoins ! type: article date: 2014-10-02 category: divers image: "version-3-stephane-richin" time: 5 comments: true --- La toute nouvelle version (3) de stephane-richin.fr est en ligne. Une version plus moderne, responsive, et qui s'adapte à mes besoins ! <!-- more --> Le principal changement est qu'il s'agit d'un site entièrement statique : terminer PHP, place maintenant à Ruby et son générateur de sites statiques [Jekyll](http://jekyllrb.com/){:target="_blank"} ! ## Pourquoi un générateur de sites statiques ? J'ai en premier lieu opté pour un classique : Wordpress. Mais après plusieurs essais sur le CMS, j'ai vite abandonné l'idée. Wordpress ne m'a pas semblé si cool que ça. J'ai pas trouvé ça super fun, malgré qu'il soit orienté pour les bloggeurs. Bref, j'ai pas accroché. Je recherchais quelque chose sur laquelle je pouvais avoir le contrôle sur la totalité de mon code et pas uniquement le contenu. Mise à part refaire un dev' en PHP, une solution bien geek était le générateur de sites statiques. Il existe énormement de générateur (plus de 200!), et dans plusieurs langages. Les principaux (et Open Source) : * [Jekyll](http://jekyllrb.com/){:target="_blank"} (Ruby) * [Middleman](http://middlemanapp.com/){:target="_blank"} (Ruby) * [Wintersmith](http://wintersmith.io/){:target="_blank"} (NodeJS) * [Pelican](http://blog.getpelican.com/){:target="_blank"} (Python) Ils proposent tous plus ou moins la même chose : * Séparations des layouts/templates * Inclusion de contenus * Écriture du contenu en Markdown * Gestion des meta-données * De nombreuses extensions/plugins Bien-sûr tous n'est pas rose, les rares points négatifs de ce type de projet sont la mise en production et le côté dev' : En effet, vous devez forcement passer par le FTP pour effectuer une mise en ligne. Cependant, il existe de nombreux plugins qui permettent d'éviter cette tâche. Certains générateurs intègrent déjà ce système par défaut. Pour les autres, des plugins comme Dploy (NodeJS) feront très bien l'affaire pour une mise en production simple et rapide. Pour le côté dev', il faudra à un moment ou à un autre mettre les mains dans le code. Suivant le profil, cela peut être plus ou moins contraignant. <img src="/public/images/blog/logo-jekyll.jpg" class="is-center" alt="Logo Jekyll"> ## Pourquoi Jekyll ? Étant donné que je possède déjà un environnement Ruby sur ma machine (contraiement à NodeJS ou Python), mon choix c'est directement orienté sur Jekyll qui est un pilié parmis les nombreux générateurs de site statiques ! Jekyll est très orienté blog et intègre le moteur de template Liquid, comparable à Twig pour les développeurs Symfony. La rédaction des contenus s'éffectue en Markdown (un vrai régal), que je prefère de loin aux éditeurs wysiwyg. Sa configuration est très simple et rapide à mettre en place, tout comme sa vitesse de compilation des fichiers. Au final, je n'ai besoin de rien à part ce que Jekyll propose : un site géré uniquement côté front, sans base de donnée et donc aucune sécurité des données n'est à prévoir :)<file_sep>/app/blog/_posts/2014-12-07-compiler-son-coffeescript-avec-prepros.md --- layout: blog-post title: Compiler du CoffeeScript et du JavaScript avec Prepros description: Concatener et compiler de manière automatique du CoffeeScript et du JavaScript avec le logiciel Prepros type: article date: 2014-12-07 category: html-css-js image: "coffee-script-et-prepros" time: 3 comments: true --- Prepros est un compilateur multi-langage qui intègre Ruby et NodeJS. On y retrouve plusieurs modules comme CoffeeScript, LESS, Jade ou encore Sass. <!--more--> L'utilisation d'un outil comme Prepros permet (entre autres) de compiler un langage sans avoir à utiliser la ligne de commande. <img src="/public/images/blog/logo-coffeescript.svg" class="is-center"> CoffeeScript, lui, est un préprocesseur JavaScript. Il possède une syntaxe très proche de Ruby, ce qui permet d'avoir un code plus compréhensible et plus lisible. Surement une question de préférence :) L'un des problèmes du CoffeScript est l'impossibilité d'importer un ou plusieurs fichiers <code>coffee</code> directement dans un fichier <code>js</code>. Ils doivent d'abbord être compilés en JavaScript avant d'être importés. Logique, mais pas pratique si vous souhaitez obtenir un seul fichier contenant toutes vos sources. Par exemple, si vous utilisez des librairies externe tel que jQuery, Foundation ou Hammer, les fichiers seront au format <code>js</code>. Du coup, il va falloir importer et recompiler tout le JavaScript. Nous allons voir qu'il est possible d'automatiser la tâche avec Prepros, de manière plus ou moins pratique. ## Automatiser la procédure L'idée est donc qu'une fois notre CoffeeScript concaténé et compilé, Prepros détecte la modification et compile automatiquement le JavaScript. Pour cela, on va donc créer un fichier <code>coffee.coffee</code> et y inclure nos différents fichiers : {% highlight coffeescript %} # @prepros-prepend setting.coffee # @prepros-prepend function.coffee # @prepros-prepend navigation.coffee {% endhighlight %} Une fois compilé, on se retrouve avec un nouveau fichier <code>coffee.js</code>. Pour que Prepros compile de manière automatique le JavaScript, nous allons importer <code>coffee.js</code> dans un fichier <code>app.js</code> : {% highlight javascript %} // @prepros-prepend jquery.js // @prepros-prepend foundation.js // @prepros-prepend hammer.js // @prepros-prepend coffee.js {% endhighlight %} De cette façon, Prepros va proceder en deux étapes : 1. Concaténation et compilation le CoffeeScript *(coffee.coffee)* 2. Concaténation et compilation du JavaScript *(app.js)* Et voilà :) Maintenant, vous pouvez coder du CoffeeScript et compiler l'intégralité de votre JavaScript de manière automatique.<file_sep>/app/blog/_posts/2015-03-22-ouvrir-une-image-avec-le-module-reveal-de-foundation.md --- layout: blog-post title: Ouvrir une image avec le module Reveal de Foundation description: Mise en place d'un script JS pour simplifier l'ouverture d'image avec le module Reveal Modal de Foundation type: article date: 2015-03-22 category: html-css-js image: "foundation-yeti-progression" time: 5 comments: true --- Ouvrir une image en mode modal sur Foundation n'est pas des plus pratiques. Zoom sur un script JS qui va simplifier notre code HTML. <!-- more --> ## Reveal Modal, c'est quoi ? [Reveal Modal](http://foundation.zurb.com/docs/components/reveal.html){:target="_blank"} est un module JavaScript du [framework Foundation](http://foundation.zurb.com/){:target="_blank"} qui permet de construire des interactions avec les utilisateurs en mode modal. Reveal n'est pas aussi complet qu'un plugin comme [Colorbox](http://www.jacklmoore.com/colorbox/){:target="_blank"}, mais il a l'avantage d'être accessible, responsive, et beaucoup moins gourmand. Le module gère n'importe quel contenu HTML ainsi que la possibilité de charger une page en Ajax. ## Le cas des images en Ajax Reveal Modale n'est pas capable d'afficher une image chargée en Ajax directement dans une boîte modale. Ce cas n'est tout simplement pas prévu. Actuellement, sur [la version 5.5.1](http://foundation.zurb.com/docs/changelog.html){:target="_blank"}, voici comment on doit s'y prendre pour afficher une image : {% highlight html %} <a href="#" data-reveal-id="myModal"> <img src="/chemin/de/mon-image.jpg" alt="Mon image"> </a> <div id="myModal" class="reveal-modal" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog"> <img src="/chemin/de/mon-image.jpg" alt="Mon image"> </div> {% endhighlight %} On est d'accord, le fait de devoir ajouter manuellement le conteneur <code>.reveal-modal</code> est chiant et pas pratique. Du coup, je me suis fait un petit script qui permet de faire plus vite, plus pratique, et de manière automatique. ## Création de la boîte en JavaScript L'idée est d'utiliser JavaScript pour créer automatiquement la boîte <code>.reveal-modal</code> qui contiendra notre image. Voyez plutôt : {% highlight html %} <a class="image-modal" data-reveal-id="myModal" data-reveal-class="small" data-image-resize> <img src="/chemin/de/mon-image.jpg" alt="Mon Image"> </a> {% endhighlight %} L'élément <code>.reveal-modal</code> sera créée et placée automatiquement juste après <code>.image-modal</code>. Au niveau du code JavaScript, ça donne ça : {% highlight js %} imageModal = function() { Foundation.utils.S('.image-modal').each(function() { var img, revealId, revealModal; // On créer l'élément .reveal-modal revealModal = $('<div class="reveal-modal" data-reveal></div>'); // Si .image-modal ne possède pas l'attribut data-image-resize if (typeof Foundation.utils.S(this).attr('data-image-resize') === 'undefined') { // Alors on reprend le chemin de l'image située dans .image-modal img = Foundation.utils.S(this).find('img').attr('src'); } else { // Sinon, on ajoute "-full" pour ouvrir une image en plus grand format img = Foundation.utils.S(this).find('img').attr('src').replace(/\.jpg/, '-full.jpg'); } // Si .image-modal possède l'attribut data-reveal-class (qui contiendra une classe) if (typeof Foundation.utils.S(this).attr('data-reveal-class') !== 'undefined') { // Alors on l'ajoute à notre boîte modale revealModal.addClass(Foundation.utils.S(this).attr('data-reveal-class')); } // On stock son id revealId = Foundation.utils.S(this).data('reveal-id'); // On met en place notre .reveal-modal return revealModal.insertAfter(Foundation.utils.S(this)).attr('id', revealId).html('<img src="' + img + '"><a class="close-reveal-modal" aria-label="Fermer">&#215;</a>'); }); return Foundation.utils.S('.image-modal').on('click', function() { var revealId; revealId = Foundation.utils.S(this).data('reveal-id'); // Puis au clic, on ouvre notre .reveal-modal avec Foundation return Foundation.utils.S('#' + revealId).foundation('reveal', 'open'); }); }; {% endhighlight %} Un code simple et adapté à mes besoins : - Par défaut, le chemin de l'image sera identique à celle qui est affichée. Néanmoins, dans certains cas, l'image possède un format plus petit. Du coup, l'attribut <code>data-reveal-resize</code> me permet de charger une image plus grande en rajoutant <code>-full</code> au nom de l'image. - La possibilité d'ajouter une classe à la boîte avec <code>data-reveal-class="nom-de-la-classe"</code> Le code est très facile, vous n'aurez aucun problème pour l'adapter à vos propres besoins :) La [version CoffeeScript](https://github.com/LeG3nDz/v3.stephane-richin.lan/blob/master/decoupe/coffee/imageModal.coffee){:target="_blank"} est disponible sur mon dépôt Github.<file_sep>/app/blog/_posts/2014-10-15-installer-jekyll-sur-windows.md --- layout: blog-post title: Installer Jekyll sur Windows description: Installation et création d'un projet Jekyll sur Windows type: article date: 2014-10-15 category: windows image: "jekyll" time: 10 comments: true --- Jekyll est un gem Ruby qui permet de générer des sites statiques très rapidement. Son installation sous Windows peut parfois être un vrai casse-tête. <!-- more --> Nous allons voir que l'installation de Jekyll sur Windows est loin d'être aussi rapide que sur Linux, sur lequel une simple ligne de commande suffit. Dans ce billet, je partirai du principe que Ruby est installé sur votre machine et qu'il est présent dans vos PATH Windows. Dans le cas contraire, l'article [Installer Ruby sous Windows](http://www.rubypourlesnuls.fr/installer-ruby-windows/){:target="_blank"} de [Ruby pour les nuls](http://www.rubypourlesnuls.fr){:target="_blank"} est fait pour vous. ## Installation du DevKit Ruby Jekyll a besoin de dépendances qui fonctionne grâce au DevKit. Pour faire simple, le DevKit (ou Development Kit) de Ruby permet l'installation de gem un peu plus complèxe. Si vous êtes un utilisateur de [Chocolatey](){:target="_blank"}, lancer la commande qui suit et passer directement à l'installation de Jekyll : {% highlight shell %} choco install ruby2.devkit {% endhighlight %} Dans le cas contaire, téléchargez l'archive du [DevKit Ruby](http://rubyinstaller.org/add-ons/devkit/){:target="_blank"}. Lorsque vous l'exécutez, il vous est demandé un chemin de destination pour extraire les fichiers. Utilisez un chemin qui ne contient pas d'espaces, cela évitera de créer des erreurs entre certains modules. Dans mon cas, j'ai choisi la racine de mon système : <code>C:\RubyDevKit\</code> Une fois les fichiers extraits, il faut initialiser le DevKit et le lier à votre installation de Ruby. Ouvrez la ligne de commande et accedez au dossier d'installation que vous avez choisi : {% highlight shell %} cd C:\RubyDevKit\ {% endhighlight %} Nous allons générer le fichier <code>config.yml</code>, qui servira plus tard à l'installation de DevKit : {% highlight shell %} ruby dk.rb init {% endhighlight %} Une fois le fichier généré, lancer la commande suivante pour installer le DevKit : {% highlight shell %} ruby dk.rb install {% endhighlight %} Dans certains cas, il se peut que l'installation ne fonctionne pas pour cause de conflit. Vous pouvez forcer l'installation à coup de hache en rajoutant <code>--force</code>. Ce qui donne : {% highlight shell %} ruby dk.rb install --force {% endhighlight %} ## Installation de Jekyll Pour installer Jekyll et toutes ses dépendances, lancer la commande suivante depuis votre ligne de commande : {% highlight shell %} gem install jekyll {% endhighlight %} Suivant votre machine et votre connexion, l'installation peut prendre un certain temps en raison du nombre de dépendances. ## La coloration Syntaxique Par défaut, Jekyll utilise [pygments.rb](http://pygments.org/){:target="_blank"}, qui est un surligneur de syntaxe basée sur Python. Il existe une très bonne alternative qui est le gem [Rouge](https://github.com/jneen/rouge){:target="_blank"} de Ruby. Rouge est plus rapide, plus facile à installer et ne nécessite pas d'avoir Python sur votre machine. Cependant, il ne supporte pas autant de langages que Pygments. {% highlight shell %} gem install rouge {% endhighlight %} Une fois installé, indiquez la coloration syntaxique dans votre <code>_config.yml</code> : {% highlight ruby %} highlighter: rouge {% endhighlight %} ## Installer le gem wdm Sur Windows, Jekyll à besoin du [gem wdm](https://rubygems.org/gems/wdm){:target="_blank"} pour faire fonctionner la commande <code>--watch</code> : {% highlight shell %} gem install wdm {% endhighlight %} Dans votre Gemfile, indiquez l'installation du gem uniquement si vous êtes sur Windows : {% highlight ruby %} gem 'wdm', '~> 0.1.0' if Gem.win_platform? {% endhighlight %} ## Création d'un projet Jekyll Une fois Jekyll et ses dépendances installé, générons l'arborescence type d'un projet Jekyll : {% highlight shell %} jekyll new projetName cd projetName {% endhighlight %} Votre projet est maintenant créé et il ne vous reste plus qu'à le compiler et lancer le serveur WEBrick intégré dans Jekyll : {% highlight shell %} jekyll serve // http://localhost:4000 {% endhighlight %} ### Watcher le dossier L'option <code>watch</code> va permettre à Jekyll d'écouter votre dossier. En gros, il sera capable de détecter quel fichier a été modifié et lancé de manière automatique la compilation du projet. {% highlight shell %} jekyll serve -w {% endhighlight %} ## Conclusion Sur Windows, l'installation de Jekyll peut être un peu laborieuse, surtout la première fois. N'oubliez donc pas de générer un Gemfile et d'y ajouter les dépendances <code>Rouge</code> et <code>wmd</code> : {% highlight ruby %} gem 'wdm', '~> 0.1.0' if Gem.win_platform? gem 'rouge', '~> 1.7' {% endhighlight %} <file_sep>/app/private/js/app.articleAnchor.js // Article Anchor // - - - - - - - - - - - - - - - - - - - - - - - - - /** * Description for articleAnchor * @private * @method articleAnchor * @return {Object} description */ var articleAnchor = function () { var $titles = $('.article h2, .article h3'); // Pour chaque titres $titles.each(function() { // On créer l'ancre en utilisant l'id var id = $(this).attr('id'), $link = $('<a href="#' + id + '" class="article-anchor">#</a>'); // Puis on l'injecte dans l'élément $(this).append($link); }); };<file_sep>/Gemfile # A sample Gemfile source "http://rubygems.org" gem 'jekyll', '3.0.1' gem 'jekyll-sitemap', '~> 0.9.0' gem 'i18n', '~> 0.6' gem 'jekyll-paginate'<file_sep>/app/blog/_posts/2015-02-03-fixer-la-navigation-offcanvas-sur-foundation.md --- layout: blog-post title: Fixer la navigation Off-Canvas sur Foundation description: Mise en place d'une navigation Off-Canvas fixe sur le framework Foundation 5 type: article date: 2015-02-03 category: html-css-js image: "foundation-website" time: 2 comments: true --- Probablement l'une des plus fortes demandes de la communauté, [<NAME>](https://github.com/davidgovea){:target="_blank"} propose une solution efficace pour fixer la navigation Off-Canvas. <!--more--> <img src="/public/images/blog/logo-foundation.jpg" alt="Logo Foundation" class="is-center"> Foundation possède une communauté très active qui lui permet de remonter et corriger quelques bugs ou encore d'ajouter des fonctionnalités aux différents modules du framework. Dernièrement, l'enseigne *ZURB* à publié un article sur son blog, listant les [5 demandes les plus fortes de la communauté](http://zurb.com/article/1350/5-ways-the-foundation-community-br-is-cru){:target="_blank"}. C'est sans surprise qu'on retrouve la navigation Off-Canvas fixe (*2. An Off-Canvas Menu That's Sticky*), qui est une fonctionnalité fortement demandée. Plusieurs solutions existes, plus ou moins efficace. En effet, suivant la technique (CSS ou JS), certains modules ne fonctionneront plus correctements. Bref, rien d'optimal pour le moment. ## Quel solution ? Dans le tas, on retrouve une proposition simple à mettre en place, qui conciste à ajouter un conteneur principal scrollable à la place du body, signé [<NAME>](http://codepen.io/rafibomb/pen/hApKk){:target="_blank"}. Des contraintes ? Oui, dîtes à Dieu aux modules Magellan et Joyride. ## Comment ça marche ? L'idée est qu'uniquement le contenu du site (via un conteneur) soit scrollable. Du coup, tous les éléments qui se trouveront en dehors de ce conteur ne bougeront pas. Ils auront le comportement d'un élément en <code>position: fixed</code>. Plutôt bien pensé <NAME> :) <p data-height="268" data-theme-id="0" data-slug-hash="hApKk" data-default-tab="result" data-user="rafibomb" class='codepen'>See the Pen <a href='http://codepen.io/rafibomb/pen/hApKk/'>Foundation Off-canvas with "fixed" tab-bar</a> by <NAME> (<a href='http://codepen.io/rafibomb'>@rafibomb</a>) on <a href='http://codepen.io'>CodePen</a>.</p> <script async src="//assets.codepen.io/assets/embed/ei.js"></script> <br> <NAME> propose donc une solution intéressente en attendent la véritable solution par l'équipe de Foundation.
d1b4cecd24043200750e582852c58596d35b136c
[ "Ruby", "HTML", "Markdown", "JavaScript", "Text" ]
25
Markdown
LeG3nDz/v3.1.stephane-richin.lan
9d6ba60346450d7850da8c87c2d12b60e268a184
0c213587d78e0c7dc6aab9a9b6d94f521be3ff82
refs/heads/master
<file_sep># Pizza Bot This project is about making a pizzabot, where you can order pizza. ## The problem We chose to make a form, where the user can choose which pizza they want and how many. When pressing an order button a message is displayed where the order is confimed. We chose to mainly focus on the javascript part instead of putting a lot of time styling with css. ## View it live https://pizzeriabolero.netlify.app/ <file_sep>const receiveData = (event) => { event.preventDefault(); const typeOfPizza = validateOrderName(); const orderQuantity = document.getElementById("quantity").value; const totalCost = calculateTotalCost(orderQuantity); const cookingTime = calculateCookingTime(orderQuantity); document.getElementById("message").innerHTML = (`You've ordered ${orderQuantity} ${typeOfPizza}. It will cost ${totalCost} kr and take ${cookingTime} minutes. Enjoy your meal!`); showImage(typeOfPizza); console.log(`You've ordered ${orderQuantity} ${typeOfPizza}. It will cost ${totalCost} kr and take ${cookingTime} minutes. Enjoy your meal!`); } const validateOrderName = () => { let pizzaChoices = document.getElementsByName('pizza'); for (let i = 0; i < pizzaChoices.length; i++) { if (pizzaChoices[i].checked) { return pizzaChoices[i].value; } } } ///Calculate total cost of the order. const calculateTotalCost = (orderQuantity) => { const pizzaPrice = 80; return orderQuantity * pizzaPrice; } //Calculate cooking time const calculateCookingTime = (orderQuantity) => { let timeCooking; if (orderQuantity < 3) { timeCooking = 10; } else if (orderQuantity > 5) { timeCooking = 20; } else { timeCooking = 15; } return timeCooking; } const showImage = (typeOfPizza) => { document.querySelectorAll('.pizza-img').forEach(item => { item.style.display = "none" }) if (typeOfPizza === "Vegetarian Pizza") { document.getElementById("vegetarianImg").style.display = "block"; } else if (typeOfPizza === "Hawaiian Pizza") { document.getElementById("hawaiianImg").style.display = "block"; } else if (typeOfPizza === "Pepperoni Pizza") { document.getElementById("pepperoniImg").style.display = "block"; } else { document.getElementById("chickenImg").style.display = "block"; } }
7bc5735a2fb47c15fcf22176fc1b9c663154cd0c
[ "Markdown", "JavaScript" ]
2
Markdown
stjernberg/project-pizza-bot
c5ec5375346488e656555478fb3048f0436beae2
c271c9f47f8c14768a3951c7403641a0e16025c1
refs/heads/master
<repo_name>Sehyo/NuggetNugget2<file_sep>/NuggetNugget2/Game1.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using TiledSharp; using System.Collections.Generic; namespace NuggetNugget2 { /// <summary> /// This is the main type for your game. /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; TmxMap map; Texture2D tileSet; SpriteFont font; Player player = new Player(); List<Player> otherPlayers = new List<Player>(); int msChatDisplayTreshold = 3000; ChatBox chatBox; bool chatBoxActive = false; Networker networker; int tileWidth; int tileHeight; int tileSetTilesWide; int tileSetTilesHigh; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.IsMouseVisible = true; //graphics.IsFullScreen = true; graphics.PreferredBackBufferWidth = 640; graphics.PreferredBackBufferHeight = 480; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { networker = new Networker(player, otherPlayers); base.Initialize(); chatBox = new ChatBox(graphics.GraphicsDevice, this.Content.Load<SpriteFont>("NuggetText"), this.Window, networker); networker.SetChatBox(chatBox); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = this.Content.Load<SpriteFont>("NuggetText"); player.objectTexture = this.Content.Load<Texture2D>("nugget"); map = new TmxMap("Content/testExported.tmx"); tileSet = Content.Load<Texture2D>(map.Tilesets[0].Name.ToString()); tileWidth = map.Tilesets[0].TileWidth; tileHeight = map.Tilesets[0].TileHeight; tileSetTilesWide = tileSet.Width / tileWidth; tileSetTilesHigh = tileSet.Height / tileHeight; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here :) } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> int elapsedMsSinceNetworkUpdate = 100; int networkMsLimit = 20; protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) Exit(); chatBox.Update(gameTime, ref chatBoxActive); player.Update(gameTime, chatBoxActive); Camera.position = player.GetPosition(); if (elapsedMsSinceNetworkUpdate >= networkMsLimit) { elapsedMsSinceNetworkUpdate = 0; networker.Update(); } else elapsedMsSinceNetworkUpdate += gameTime.ElapsedGameTime.Milliseconds; base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); for (int layer = 0; layer < map.TileLayers.Count; layer++) { for (int i = 0; i < map.TileLayers[layer].Tiles.Count; i++) { int gid = map.TileLayers[layer].Tiles[i].Gid; if (gid == 0) continue; // Empty tile. int tileFrame = gid - 1; int column = tileFrame % tileSetTilesWide; int row = (int)System.Math.Floor((double)tileFrame / (double)tileSetTilesWide); float x = (i % map.Width) * map.TileWidth; float y = (float)System.Math.Floor(i / (double)map.Width) * map.TileHeight; Vector2 localPos = Camera.GlobalPosToLocalPos(new Vector2(x, y)); //System.Console.WriteLine("---\nTile Frame: {0}\nColumn: {1}\nRow: {2}\nx: {3}, y: {4}", tileFrame, column, row, x, y); Rectangle tileSetRec = new Rectangle(tileWidth * column, tileHeight * row, tileWidth, tileHeight); spriteBatch.Draw(tileSet, new Rectangle((int)localPos.X, (int)localPos.Y, tileWidth, tileHeight), tileSetRec, Color.White); } } foreach (var otherPlayer in otherPlayers) { Vector2 localPos = Camera.GlobalPosToLocalPos(new Vector2(otherPlayer.GetPosition().X, otherPlayer.GetPosition().Y)); spriteBatch.Draw(otherPlayer.objectTexture, new Rectangle((int)localPos.X, (int)localPos.Y, otherPlayer.objectRectangle.Width, otherPlayer.objectRectangle.Height), Color.Blue); } List<ChatMessage> messages = chatBox.GetMessages(); for (int i = messages.Count - 1; i >= 0; i--) { if (System.DateTime.Now.Subtract(messages[i].timestamp).TotalMilliseconds > msChatDisplayTreshold) break; // Rest of messages are too old. Vector2? messagePosition = null; if(player.name == messages[i].author || true) { messagePosition = new Vector2(player.objectRectangle.X, player.objectRectangle.Y); } else { foreach(Player player in otherPlayers) { if(player.name == messages[i].author) { messagePosition = new Vector2(player.objectRectangle.X, player.objectRectangle.Y); break; } } } if (messagePosition == null) continue; // Couldn't find the player. //messagePosition = new Vector2(messagePosition.Value.X, messagePosition.Value.Y - 50); messagePosition = Camera.GlobalPosToLocalPos(new Vector2((messagePosition.Value.X) - (font.MeasureString(messages[i].message).X / 2), messagePosition.Value.Y - 50)); if(graphics.GraphicsDevice.PresentationParameters.Bounds.Contains(messagePosition.Value)) { System.Console.WriteLine("DRAWING STRING"); spriteBatch.DrawString(font, messages[i].message, messagePosition.Value, Color.Yellow); } } player.Draw(gameTime, spriteBatch); chatBox.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }<file_sep>/NuggetNugget2/GameObject.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace NuggetNugget2 { public class GameObject { public Texture2D objectTexture; public Rectangle objectRectangle; public GameObject() { } public Vector2 GetPosition() { return new Vector2(objectRectangle.X, objectRectangle.Y); } } } <file_sep>/NuggetNugget2/PlayerMessage.cs using MsgPack.Serialization; using Neutrino.Core.Messages; namespace NuggetNugget2 { public class PlayerMessage : NetworkMessage { [MessagePackMember(0)] public int positionX { get; set; } [MessagePackMember(1)] public int positionY { get; set; } [MessagePackMember(2)] public int PID { get; set; } } }<file_sep>/NuggetNugget2/InfoMessage.cs using MsgPack.Serialization; using Neutrino.Core.Messages; namespace NuggetNugget2 { public class InfoMessage : NetworkMessage { [MessagePackMember(0)] public string name { get; set; } [MessagePackMember(1)] public int PID { get; set; } [MessagePackMember(2)] public int STATUS_CODE { get; set; } public InfoMessage() { IsGuaranteed = true; } } }<file_sep>/NuggetNugget2/Camera.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace NuggetNugget2 { public static class Camera { public static Vector2 position = new Vector2(0, 0); // Offset.................. public static Vector2 GlobalPosToLocalPos(Vector2 globalPos) { return globalPos - position + new Vector2(320, 240); } } }<file_sep>/README.md # NuggetNugget2 NuggetNugget2 <file_sep>/NuggetNugget2/Networker.cs using Neutrino.Core; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace NuggetNugget2 { public class Networker { const int serverPort = 8080;//51337; Player player; ChatBox chatBox; Node serverNode; List<Player> otherPlayers; bool waitingForLogin = false; public Networker(Player player, List<Player> otherPlayers) { this.player = player; this.otherPlayers = otherPlayers; // 172.16.31.10 string ip = "172.16.31.10"; System.Console.WriteLine("What server? (Enter number)"); System.Console.WriteLine("1: Alex' Server"); System.Console.WriteLine("2: Localhost"); if (System.Console.ReadLine().Contains("2")) ip = "127.0.0.1"; serverNode = new Node("Sehyo", ip, serverPort, typeof(PlayerMessage).Assembly, typeof(ChatMessage).Assembly, typeof(InfoMessage).Assembly); serverNode.OnPeerConnected += peer => System.Console.WriteLine("Peer connected"); serverNode.OnPeerDisconnected += peer => System.Console.WriteLine("Peer disconnected"); serverNode.OnReceived += msg => HandleMessage(msg); serverNode.Name = "Client"; NeutrinoConfig.PeerTimeoutMillis = 10000; serverNode.Start(); // Temporarily commented out so I can push. //string username = "test"; //var infoMsg = serverNode.GetMessage<InfoMessage>(); //msg.name = username; //serverNode.SendToAll(msg); //System.Console.WriteLine("Sending login request."); //serverNode.Update(); } public void SetChatBox(ChatBox chatBox) { this.chatBox = chatBox; } public void Update() { if (waitingForLogin) return; //serverNode.Update(); var msg = serverNode.GetMessage<PlayerMessage>(); msg.positionX = (int)player.GetPosition().X; msg.positionY = (int)player.GetPosition().Y; msg.PID = 1; //System.Console.WriteLine("Sending {0} and {1}", msg.positionX, msg.positionY); //serverNode.ConnectedPeers System.Console.WriteLine("Sending pos"); serverNode.SendToAll(msg); serverNode.Update(); //serverNode.Update(); } public void SendChatMessage(ChatMessage chatMessage) { var msg = serverNode.GetMessage<ChatMessage>(); msg.Author = chatMessage.author; msg.Message = chatMessage.message; msg.Timestamp = chatMessage.timestamp; serverNode.SendToAll(msg); serverNode.Update(); serverNode.Update(); } public void HandleMessage(Neutrino.Core.Messages.NetworkMessage msg) { if(msg is PlayerMessage) { if (waitingForLogin) return; //System.Console.WriteLine("We received a player message!"); PlayerMessage pMsg = (PlayerMessage)msg; //System.Console.WriteLine("Player {0} is at {1}, {2}", pMsg.PID, pMsg.positionX, pMsg.positionY); // Does the current player exist? bool exists = false; foreach (var currentPlayer in otherPlayers) { if(currentPlayer.PID == pMsg.PID) { exists = true; //System.Console.WriteLine("Setting other player pos to {0} and {1}", pMsg.positionX, pMsg.positionY); currentPlayer.SetPosition(pMsg.positionX, pMsg.positionY); break; } } if(!exists) { System.Console.WriteLine("NEW PLAYER!?!?!?!?!?!??"); Player newPlayer = new Player(); newPlayer.objectTexture = player.objectTexture; newPlayer.SetPosition(pMsg.positionX, pMsg.positionY); newPlayer.PID = pMsg.PID; otherPlayers.Add(newPlayer); } } else if(msg is ChatMessage) { if (waitingForLogin) return; ChatMessage cMsg = (ChatMessage)msg; ChatMessage receivedChatMessage = new ChatMessage(cMsg.Message, cMsg.Author, cMsg.Timestamp); System.Console.WriteLine("Received Chat Message: {0}, {1}", msg.Source, msg.Id); chatBox.HandleForeignMessage(receivedChatMessage); } else if(msg is InfoMessage) { if(waitingForLogin) { } else { // ?? } } else { System.Console.WriteLine("We received a {0} message.", msg.GetType()); } } } }<file_sep>/NuggetNugget2/ChatBox.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace NuggetNugget2 { public class ChatBox { Rectangle chatBoxRectangle; Rectangle inputBoxRectangle; Rectangle blinkerRectangle; Rectangle deletionRectangle; Texture2D chatBoxTexture; Texture2D inputBoxTexture; Texture2D blinkerTexture; List<ChatMessage> messages; SpriteFont font; float blinkerOpacity = 1.0f; float chatBoxActiveOpacity = 0.6f; float chatBoxInactiveOpacity = 0.2f; bool blinkerShowing = true; bool chatBoxActive = false; bool disableBoxOnNext = false; int blinkRateMs = 350; double msElapsed = 0; string inputString = ""; Networker networker; public ChatBox(GraphicsDevice graphicsDevice, SpriteFont font, GameWindow window, Networker networker) { this.font = font; window.TextInput += Window_TextInput; messages = new List<ChatMessage>(); chatBoxRectangle = new Rectangle(0,260,400,200); chatBoxTexture = Utils.CreateTexture(graphicsDevice, 1, 1, pixel => Color.Black); inputBoxTexture = Utils.CreateTexture(graphicsDevice, 1, 1, pixel => Color.Black); blinkerTexture = Utils.CreateTexture(graphicsDevice, 1, 1, pixel => Color.White); inputBoxRectangle = new Rectangle(0, 460, 400, 20); blinkerRectangle = new Rectangle(inputBoxRectangle.X, inputBoxRectangle.Y, 2, inputBoxRectangle.Height); deletionRectangle = new Rectangle(chatBoxRectangle.X, chatBoxRectangle.Y - 50, chatBoxRectangle.Width, 50); this.networker = networker; } public List<ChatMessage> GetMessages() { return this.messages; } public void HandleForeignMessage(ChatMessage chatMessage) { messages.Add(chatMessage); } private string wrappifyText(string text) { string completeString = ""; string progressString = ""; bool lastIterationAddedString = false; for(int i = 0; i < text.Length; i++) { string candidateProgressString = progressString + text[i]; int length = (int)font.MeasureString(candidateProgressString + "-").X; // + " " so it leaves some space at the end if(length >= chatBoxRectangle.Width) { // String became too long. // Candidate string is invalid. // ---> completeString += progressString + "\n"; progressString = text[i].ToString(); // Start of our new line. lastIterationAddedString = true; } else { // This addition to our progress string is valid! progressString = candidateProgressString; lastIterationAddedString = false; } } if (!lastIterationAddedString) completeString += progressString; return completeString; } private void Window_TextInput(object sender, TextInputEventArgs e) { if (chatBoxActive) { if (e.Character == (char)Keys.Back) { if (inputString != "") { inputString = inputString.Remove(inputString.Length - 1); } } else if (e.Character == (char)Keys.Tab) { inputString += " "; } else if (e.Character == (char)Keys.Escape) { disableBoxOnNext = true; } else if(e.Character == (char)Keys.Enter) { ChatMessage newChatMessage = new ChatMessage(inputString, "Player"); messages.Add(newChatMessage); // Send over the networking: networker.SendChatMessage(newChatMessage); inputString = ""; } else { inputString += e.Character; } for(blinkerRectangle.X = (int)font.MeasureString(inputString).X; !inputBoxRectangle.Contains(blinkerRectangle);) { inputString = inputString.Remove(inputString.Length - 1); blinkerRectangle.X = (int)font.MeasureString(inputString).X; } } } public void Update(GameTime gameTime, ref bool chatBoxActive) { if (disableBoxOnNext) { chatBoxActive = false; disableBoxOnNext = false; } this.chatBoxActive = chatBoxActive; msElapsed += gameTime.ElapsedGameTime.TotalMilliseconds; if(msElapsed >= blinkRateMs) { msElapsed = 0; blinkerShowing = !blinkerShowing; if (!chatBoxActive) blinkerShowing = true; } var mouseState = Mouse.GetState(); var mousePosition = new Point(mouseState.X, mouseState.Y); var keyboardState = Keyboard.GetState(); var keys = keyboardState.GetPressedKeys(); if (mouseState.LeftButton == ButtonState.Pressed) { if(chatBoxRectangle.Contains(mousePosition) || inputBoxRectangle.Contains(mousePosition)) { chatBoxActive = true; } else { chatBoxActive = false; } } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(chatBoxTexture, chatBoxRectangle, Color.White * (chatBoxActive ? chatBoxActiveOpacity : chatBoxInactiveOpacity)); float totalHeight = 0; for(int i = messages.Count - 1; i >= 0; i--) { ChatMessage chatMessage = messages[i]; string printString = wrappifyText(chatMessage.timestamp.ToShortTimeString() + ":" + chatMessage.author + ": " + chatMessage.message); totalHeight += font.MeasureString(printString).Y; Vector2 newMessagePosition = new Vector2(chatBoxRectangle.X, chatBoxRectangle.Y + chatBoxRectangle.Height - totalHeight); if (deletionRectangle.Contains(newMessagePosition)) break; spriteBatch.DrawString(font, printString, newMessagePosition, Color.White); } spriteBatch.Draw(inputBoxTexture, inputBoxRectangle, Color.White * 0.8f); blinkerRectangle.X = (int)font.MeasureString(inputString).X; spriteBatch.Draw(blinkerTexture, blinkerRectangle, Color.White * (blinkerShowing ? 1.0f : 0.0f)); spriteBatch.DrawString(font, inputString, new Vector2(inputBoxRectangle.X, inputBoxRectangle.Y), Color.White); } } }<file_sep>/NuggetNugget2Server/Program.cs using Neutrino.Core; using NuggetNugget2; using System.Collections.Generic; using System; namespace NuggetNugget2Server { class Program { static List<Tuple<NetworkPeer, ClientData>> clients; static void Main(string[] args) { System.Console.WriteLine("Starting Server"); const int serverPort = 8080; int clientsConnected = 0; int totalConnections = 0; Node serverNode = new Node(serverPort, typeof(PlayerMessage).Assembly, typeof(ChatMessage).Assembly); serverNode.OnPeerConnected += peer => { ++clientsConnected; System.Console.WriteLine("We currently have {0} connected clients.", clientsConnected); }; serverNode.OnPeerDisconnected += peer => { --clientsConnected; System.Console.WriteLine("We now have {0} connected clients.", clientsConnected); }; serverNode.OnReceived += msg => HandleMessage(msg, serverNode); serverNode.Name = "Server"; serverNode.Start(); clients = new List<Tuple<NetworkPeer, ClientData>>(); NeutrinoConfig.CreatePeer = () => { System.Console.WriteLine("Creating Peer."); var newPeer = new NetworkPeer(); var clientTuple = new Tuple<NetworkPeer, ClientData>(newPeer, new ClientData()); clients.Add(clientTuple); int i = 0; foreach (var item in clients) { System.Console.WriteLine("PID of client {0} is: {1}", i, item.Item1.GetHashCode()); i++; } totalConnections++; return newPeer; }; NeutrinoConfig.PeerTimeoutMillis = 1000000; int elapsedMsSinceUpdate = 100; int msTreshold = 20; DateTime nextUpdate = DateTime.Now; while (true) { if (nextUpdate < DateTime.Now) { nextUpdate = DateTime.Now.AddMilliseconds(msTreshold); UpdateClients(serverNode); try { serverNode.SendToAll(serverNode.GetMessage<Neutrino.Core.Messages.AckMessage>()); serverNode.Update(); } catch (Exception e) { System.Console.WriteLine("We crashed {0}", e.Message); System.Console.WriteLine(e.StackTrace); System.Console.WriteLine(e.Source); System.Console.WriteLine(e.InnerException); } } } } static void UpdateClients(Node serverNode) { //Neutrino.Core.Messages.AckMessage a; //serverNode.SendToAll(serverNode.GetMessage<Neutrino.Core.Messages.Ackmessage>()); foreach (var targetClient in clients) { foreach (var sourceClient in clients) { if (targetClient == sourceClient) continue; var msg = serverNode.GetMessage<PlayerMessage>(); msg.positionX = sourceClient.Item2.positionX; msg.positionY = sourceClient.Item2.positionY; msg.PID = sourceClient.Item1.GetHashCode(); targetClient.Item1.SendNetworkMessage(msg); } } } static void HandleMessage(Neutrino.Core.Messages.NetworkMessage msg, Node serverNode) { //System.Console.WriteLine("Received Message:"); //System.Console.WriteLine("Type is: {0}", msg.GetType()); System.Console.WriteLine("Received {0}", msg.ToString()); if (msg is PlayerMessage) { int x = ((PlayerMessage)msg).positionX; int y = ((PlayerMessage)msg).positionY; //System.Console.WriteLine("Received {0}, {1}", x, y); foreach (var tuple in clients) { if(tuple.Item1 == msg.Source) { tuple.Item2.positionX = x; tuple.Item2.positionY = y; } } //System.Console.WriteLine("Player Position received from client is: {0}, {1}", x, y); } else if(msg is ChatMessage) { System.Console.WriteLine("Received chat message: {0}, {1}", msg.Source, msg.Id); ChatMessage chatMessage = (ChatMessage)msg; string author = chatMessage.Author; string message = chatMessage.Message; DateTime timestamp = chatMessage.Timestamp; var outMessage = serverNode.GetMessage<ChatMessage>(); outMessage.Author = author; outMessage.Message = message; outMessage.Timestamp = timestamp; foreach (var tuple in clients) { if (tuple.Item1 == msg.Source) continue; // Skip the sender! tuple.Item1.SendNetworkMessage(outMessage); } } else { System.Console.WriteLine("Received other kind of message {0}", msg.ToString()); } } } }<file_sep>/NuggetNugget2/Player.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace NuggetNugget2 { public class Player : GameObject { public int PID = -1; public string name = ""; public Player() { base.objectRectangle = new Rectangle(100, 100, 35, 65); } public void Update(GameTime gameTime, bool chatBoxActive) { KeyboardState state = Keyboard.GetState(); float speed = 0.2f * (float)gameTime.ElapsedGameTime.TotalMilliseconds; if (!chatBoxActive) { if (state.IsKeyDown(Keys.W)) base.objectRectangle.Y -= (int)speed; if (state.IsKeyDown(Keys.A)) base.objectRectangle.X -= (int)speed; if (state.IsKeyDown(Keys.S)) base.objectRectangle.Y += (int)speed; if (state.IsKeyDown(Keys.D)) base.objectRectangle.X += (int)speed; } } public void SetPosition(int x, int y) { objectRectangle.X = x; objectRectangle.Y = y; } public Vector2 GetPosition() { return new Vector2(objectRectangle.X, objectRectangle.Y); } public void Draw(GameTime gameTime, SpriteBatch spriteBatch) { Vector2 localPos = Camera.GlobalPosToLocalPos(new Vector2(objectRectangle.X, objectRectangle.Y)); spriteBatch.Draw(objectTexture, new Rectangle((int)localPos.X, (int)localPos.Y, objectRectangle.Width, objectRectangle.Height), Color.White); } } }<file_sep>/NuggetNugget2/Utils.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Linq; using System.Text; namespace NuggetNugget2 { public static class Utils { // Copy pasted from // https://stackoverflow.com/a/32429364 public static Texture2D CreateTexture(GraphicsDevice device, int width, int height, Func<int, Color> paint) { //initialize a texture Texture2D texture = new Texture2D(device, width, height); //the array holds the color for each pixel in the texture Color[] data = new Color[width * height]; for (int pixel = 0; pixel < data.Count(); pixel++) { //the function applies the color according to the specified pixel data[pixel] = paint(pixel); } //set the color texture.SetData(data); return texture; } // Copy pasted from // https://stackoverflow.com/a/34473837 public static string WrapText(SpriteFont font, string text, float maxLineWidth) { string[] words = text.Split(' '); StringBuilder sb = new StringBuilder(); float lineWidth = 0f; float spaceWidth = font.MeasureString(" ").X; foreach (string word in words) { Vector2 size = font.MeasureString(word); if (lineWidth + size.X < maxLineWidth) { sb.Append(word + " "); lineWidth += size.X + spaceWidth; } else { if (size.X > maxLineWidth) { if (sb.ToString() == "") { sb.Append(WrapText(font, word.Insert(word.Length / 2, " ") + " ", maxLineWidth)); } else { sb.Append("\n" + WrapText(font, word.Insert(word.Length / 2, " ") + " ", maxLineWidth)); } } else { sb.Append("\n" + word + " "); lineWidth = size.X + spaceWidth; } } } return sb.ToString(); } } } <file_sep>/NuggetNugget2Server/ClientData.cs namespace NuggetNugget2Server { public class ClientData { public int positionX; public int positionY; } } <file_sep>/NuggetNugget2/ChatMessage.cs using MsgPack.Serialization; using Neutrino.Core.Messages; using System; namespace NuggetNugget2 { public class ChatMessage : NetworkMessage { public string author; public string message; public DateTime timestamp; public bool expired = false; [MessagePackMember(0)] public string Author { get; set; } [MessagePackMember(1)] public string Message { get; set; } [MessagePackMember(2)] public DateTime Timestamp { get; set; } public ChatMessage() { IsGuaranteed = true; } public ChatMessage(string text) { this.message = text; this.author = "SERVER"; this.timestamp = DateTime.Now; } public ChatMessage(string text, string author) { this.message = text; this.author = author; this.timestamp = DateTime.Now; } public ChatMessage(string text, string author, DateTime timestamp) { this.message = text; this.author = author; this.timestamp = DateTime.Now; } } }
9dbafd38252b6530be3105c74fdfa252b9f47ada
[ "Markdown", "C#" ]
13
C#
Sehyo/NuggetNugget2
0c4cd40e499dbcaa71441351f332d51166e98492
21aeb0b01c5189153a1a5b3de634659cfed3023a
refs/heads/master
<file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ballotage2015; /** * * @author vaio */ public class Ballotage2015 { /** * @param args the command line arguments */ public static void main(String[] args) { BDPASO2015 bd =new BDPASO2015(); EscribeHtml escribe=new EscribeHtml(); for (int i=1;i<=75;i++){ try{ escribe.BdToHtml("D://balotaje1//Nacional"+i+".html",i); } catch (Exception e) { System.out.println(e.getMessage()); } } try{ escribe.BdToHtmlGeneral("D://balotaje1//General"+76+".html",76); } catch (Exception e) { System.out.println(e.getMessage()); } } }
1bde8c2a47929f142a1d15df1c339133bef74a9f
[ "Java" ]
1
Java
zxero23/Ballotage2015Misiones
547cba756342668f60dbdc6464e6722df57256fa
e9c50856d658a671fcca6a86812fb172ae836356
refs/heads/master
<repo_name>sjjensen2004/learningflask<file_sep>/README.txt This is just to learn both flask and GIT. Disregard any poorly written code you may observe here. <file_sep>/mail.py from flask_mail import Message from hello import mail from hello import app msg = Message('test subject', sender ='<EMAIL>', recipients =['<EMAIL>']) msg.body = 'text body' msg.html = '<b> HTML </b> body' with app.app_context(): mail.send(msg)
37ad4cc25e809ad91e491e3734cb0d24ff9690e8
[ "Python", "Text" ]
2
Text
sjjensen2004/learningflask
7915f1c8eb21efdb49f46299cb98aa51cb210910
8e301f3d811f9ccd45ae3093a50830001e3854de
refs/heads/master
<repo_name>nikhil-kartha/aws<file_sep>/app.py from flask import Flask, request, jsonify import json import boto3 import datetime import userdoc from collections import defaultdict app = Flask(__name__) @app.route('/') def index(): return f"{userdoc.html}", 200 @app.route('/zappa/pinfo', methods=['POST']) def pinfo(): data = extract_fields(request.json) if valid(data): out = format_output(data, data['ftype']) write_to_s3(out, data['bucketname'], data['ftype']) return jsonify({'data': request.json}), 200 else: error = "Invalid Data. Input json should have one of first_name, middle_name, last_name or zip_code" return jsonify({"error": error, "data": request.json}), 400 def extract_fields(data): dd = defaultdict(lambda:"") dd.update(data) if not dd['bucketname']: dd['bucketname'] = <<bucketname>> if dd['ftype'] != 'json': dd['ftype'] = 'csv' # default to using csv format return dd def valid(data): expected_fields = ['first_name', 'middle_name', 'last_name', 'zip_code'] return any(data[field] for field in expected_fields) def format_output(data, ftype): if ftype == 'json': out = data else: out = f'first_name,middle_name,last_name,zip_code\n{data["first_name"]},{data["middle_name"]},{data["last_name"]},{data["zip_code"]}' return out def write_to_s3(data, bucketname, ftype): prefix = 'pinfodata' fname = str(abs(hash(data))) date = datetime.datetime.utcnow() year, month, day = date.strftime("%Y"), date.strftime("%m"), date.strftime("%d") folder = f'year={year}/month={month}/day={day}' path = f'{prefix}/{folder}/{fname}.{ftype}' s3 = boto3.resource('s3') s3.Object(bucketname, path).put(Body=data) if __name__ == '__main__': app.run() <file_sep>/generate_test_data.sh curl -w "%{http_code}" --header "Content-Type: application/json" \ --request POST \ --data '{"first_name":"nikhil7","middle_name":"narayan5", "last_name":"kartha5","zip_code":"94569"}' \ https://{hostname}/dev/zappa/pinfo <file_sep>/userdoc.py html = """ <h1> Add user info to S3 </h1> <h2>Path</h2> <bold>/zappa/pinfo</bold> <h2>Method</h2> <bold>POST</bold> <h2>Parameters</h2> Input json should have one of first_name, middle_name, last_name or zip_code <h2> Success Response </h2> <bold> 200: Returns the input json data </bold> <h2> Error Response </h2> <bold> 400: None of the expected json fields are present. </bold> <h1>Usage</h1> <h2>Run the following command</h2> Note: Replace with appropriate hostname in the following command<br><br> <code> curl -w "%{http_code}" --header "Content-Type: application/json" \ --request POST \ --data '{"first_name":"nikhil7","middle_name":"narayan5", "last_name":"kartha5","zip_code":"94569"}' \ https://{hostname}/dev/zappa/pinfo </code> <h2>Sample Output</h2> <code> {"data":{"first_name":"nikhil7","last_name":"kartha5","middle_name":"narayan5","zip_code":"94569"}} </code> """ <file_sep>/README.md # Description Setup an API Endpoint to upload json data to an S3 bucket, and query it using AWS Glue. There are essentially 3 steps: 1. One time setup. 2. Create Lambda stack 3. Create Glue stack ## Setup Create a virtualenv and install flask and zappa for zappa: ref: https://github.com/Miserlou/Zappa ``` python3 -mvenv env3 source env3/bin/activate pip install flask zappa zappa init ``` *NOTE*: Replace _bucketname_ in the files *app.py* and *pinfo-crawler.yaml*, with the bucketname configured during "zappa init". ## Lambda ### Deploy lambda function We use Zappa setup earlier to deploy the app to the "dev" stage/environment. ``` zappa deploy dev ``` Note: 1. "zappa update dev" for subsequent deployments. 2. "zappa tail" to watch the logs. ### Generate data in S3 (Manual) Replace the URL in the following command with an appropriate one from the API gateway. ``` curl -w "%{http_code}" --header "Content-Type: application/json" \ --request POST \ --data '{"first_name":"nikhil7","middle_name":"narayan5", "last_name":"kartha5","zip_code":"94569"}' \ https://{hostname}/dev/zappa/pinfo ``` ## AWS Glue (uses cloudformation stack) ``` aws cloudformation create-stack --stack-name pinfo-crawler --template-body file://pinfo-crawler.yaml --capabilities CAPABILITY_IAM ``` ## Athena (manual) Setup query results location, go to settings in "query editor" and add the s3 bucket location to store query results. At this point you should be able to run sql queries against the created tables.
704df4d2d84d365ff0feea31e18e1a5363353bd9
[ "Markdown", "Python", "Shell" ]
4
Python
nikhil-kartha/aws
6de54e0d6af8df49d4820b135f7835e4c9e007c7
5a213654881207af2802a70488f8bbb4ff72dfc0
refs/heads/master
<repo_name>wszostak/java-bank<file_sep>/src/main/java/pl/training/bank/aspect/CashFlowLogger.java package pl.training.bank.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import pl.training.bank.BankException; import java.math.BigDecimal; import java.text.NumberFormat; @Component // @Aspect public class CashFlowLogger { // @Pointcut("execution(* pl.training.bank.Bank.payInCashToAccount(..)) && args(accountNumber, amount)") // public void payIn(String accountNumber, BigDecimal amount) { // } // // @Pointcut("execution(* pl.training.bank.Bank.payOutCashToAccount(..)) && args(accountNumber, amount)") // public void payOut(String accountNumber, BigDecimal amount) { // } // // @Pointcut("execution(* pl.training.bank.Bank.transferCash(..)) && args(fromAccountNumber, toAccountNumber, amount)") // public void transferCash(String fromAccountNumber, String toAccountNumber, BigDecimal amount) { // } // // @Pointcut("execution (* pl.training.bank.Bank.*Cash*(..))") // public void cashFlowOperation() { // } private void startLogEntry(String operationName) { System.out.println("========================================="); System.out.println("Rozpoczęto operację: " + operationName); } private String formatCurrency(BigDecimal amount) { return NumberFormat.getCurrencyInstance().format(amount); } // @Before("payIn(accountNumber, amount)") public void beforePayInOperation(JoinPoint jp, String accountNumber, BigDecimal amount) { startLogEntry(jp.getSignature().getName()); System.out.println(formatCurrency(amount) + " -> " + accountNumber); } // @Before("payOut(accountNumber, amount)") public void beforePayOutOperation(JoinPoint jp, String accountNumber, BigDecimal amount) { startLogEntry(jp.getSignature().getName()); System.out.println(accountNumber + " -> " + formatCurrency(amount)); } // @Before("transferCash(fromAccountNumber, toAccountNumber, amount)") public void beforeTransferCashOperation(JoinPoint jp, String fromAccountNumber, String toAccountNumber, BigDecimal amount) { startLogEntry(jp.getSignature().getName()); System.out.println(fromAccountNumber + " -> " + formatCurrency(amount)+ " -> " + toAccountNumber); } // @AfterReturning("cashFlowOperation()") public void afterSuccess() { System.out.println("Operacja zakończona pomyślnie"); System.out.println("========================================="); } // @AfterThrowing(value="cashFlowOperation()", throwing = "bankException") public void afterFailure(BankException bankException) { System.out.println("Wyjątek: " + bankException.getClass().getSimpleName()); System.out.println("========================================="); } } <file_sep>/src/main/java/pl/training/bank/service/repository/InsufficientFundsException.java package pl.training.bank.service.repository; import pl.training.bank.BankException; public class InsufficientFundsException extends BankException { public InsufficientFundsException() { } public InsufficientFundsException(String message) { super(message); } public InsufficientFundsException(Throwable cause) { super(cause); } } <file_sep>/src/main/java/pl/training/bank/service/repository/AccountDoesNotExistException.java package pl.training.bank.service.repository; import pl.training.bank.BankException; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 15.01.14 * Time: 10:58 * To change this template use File | Settings | File Templates. */ public class AccountDoesNotExistException extends BankException { public AccountDoesNotExistException() { } public AccountDoesNotExistException(String message) { super(message); } public AccountDoesNotExistException(Throwable cause) { super(cause); } }
3262aaa1419be11e7a677f056c4a373344e4ddc0
[ "Java" ]
3
Java
wszostak/java-bank
cb075c93bf02b191ae04cf3830d82a938cc74edf
88e252b3d9b2ebb2a4afa8a184dd9d27cf916c6c
refs/heads/master
<file_sep>package com.taosj.shts.repository; import com.taosj.shts.entity.Contact; /** * Created by taoshijun on 16/6/3. */ public interface ContactRepository extends BaseRepository<Contact> { } <file_sep>package com.taosj.shts.entity; /** * Created by taoshijun on 16/6/3. */ public enum RecordStatus { NEW, PROTECTING, TIMEOUT, FINISH, } <file_sep>package com.taosj.shts.entity; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.OneToMany; import java.util.List; /** * Created by taoshijun on 16/6/3. */ @Entity public class User extends Domain { private String nickname; private String mobile; private String password; private Integer securityCode; @OneToMany private List<Contact> contacts; @OneToMany private List<Record> records; public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public Integer getSecurityCode() { return securityCode; } public void setSecurityCode(Integer securityCode) { this.securityCode = securityCode; } public List<Contact> getContacts() { return contacts; } public void setContacts(List<Contact> contacts) { this.contacts = contacts; } public List<Record> getRecords() { return records; } public void setRecords(List<Record> records) { this.records = records; } }
38d2519f9a2ff16a235e1fbb0914856fa48ac6f0
[ "Java" ]
3
Java
taoshijun/shouhutianshi
3dfd3d5fc0001cc3598f7cae882c244e641634b9
ef64790ec7f49bf57943f42863509e3fe672b4f4
refs/heads/master
<file_sep>package com.example.tripwithyou; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface Retrofit_sign_up { //회원가입 //PHP에 전송하는 부분 @GET("sign_up.php") //id라는 키로 id값을 보낸다, pw키로 pw밸류를 보낸다 Call<Retrofit_result> getlist(@Query("id") String id, @Query("pw") String pw, @Query("nick") String nick, @Query("grade")String grade, @Query("name") String name); } <file_sep>package com.example.tripwithyou; import java.util.ArrayList; public class Retrofit_result { //php에서 받는 부분 //난 php에서 result만 받겠다. private final String result; public Retrofit_result(String result) { this.result = result; } public String getResult() { return result; } } <file_sep>include ':app' rootProject.name='TripWithYou' <file_sep>package com.example.tripwithyou; import android.content.Context; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class Adapter_home extends RecyclerView.Adapter<Adapter_home.MyViewHolder> { private Context context; private ArrayList<Recycler_DTO_home> datalist = new ArrayList<>(); @Override //뷰홀더 생성 //화면에 뿌려주고 holder에 연결 public Adapter_home.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //뷰생성 (아이템 레이아웃 기반) //inflater는 뷰를 실제 객체화하는 용도 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rcv_home_itemview, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(Adapter_home.MyViewHolder holder, int position) { //각 위치에 문자열 세팅 final Recycler_DTO_home data = datalist.get(position); holder.city.setText(data.getCity()); holder.randmark.setText(data.getRandmark()); //Recycler_DTO_home dto; //Adapter_home_horizontal adapter = new Adapter_home_horizontal(context, datalist.get(position)); Adapter_home_horizontal adapter = new Adapter_home_horizontal(context, data.getImg()); holder.rv.setHasFixedSize(true); holder.rv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); holder.rv.setAdapter(adapter); } @Override public int getItemCount() { return datalist.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView city; TextView randmark; RecyclerView rv; public MyViewHolder(View itemview) { super(itemview); city = (TextView)itemview.findViewById(R.id.city_text); randmark = (TextView)itemview.findViewById(R.id.randmark_text); rv = (RecyclerView)itemview.findViewById(R.id.recyclerview); } } public Adapter_home(Context context, ArrayList<Recycler_DTO_home> datalist) { this.context = context; this.datalist = datalist; } } <file_sep>package com.example.tripwithyou; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class Sign_up extends AppCompatActivity { private final String BASE_URL = "http://13.125.246.30/"; private Call<Retrofit_result> userList; private Retrofit mRetrofit; private Retrofit_sign_up Retrofit_sign_up; private Gson mGson; private EditText eid, epw, enick, ename; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sign_up); eid = (EditText) findViewById(R.id.email_edit); epw = (EditText) findViewById(R.id.pw_edit); enick = (EditText) findViewById(R.id.nickname_edit); ename = (EditText) findViewById(R.id.name_edit); //회원가입 버튼 클릭시 Button sign_up = (Button) findViewById(R.id.sign_up_bt); sign_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setRetrofitInit(); calluserlist(); } }); } //레트로핏 객체생성 protected void setRetrofitInit() { mGson = new GsonBuilder().setLenient().create(); mRetrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(mGson)) .build(); Retrofit_sign_up = mRetrofit.create(Retrofit_sign_up.class); } protected void calluserlist() { String id = eid.getText().toString(); String pw = epw.getText().toString(); String nick = enick.getText().toString(); String grade = "1"; String name = ename.getText().toString(); userList = Retrofit_sign_up.getlist(id, pw, nick, grade,name); userList.enqueue(mRetrofitCallback); } protected Callback<Retrofit_result> mRetrofitCallback = new Callback<Retrofit_result>() { @Override public void onResponse(Call<Retrofit_result> call, Response<Retrofit_result> response) { Retrofit_result retrofit_result = response.body(); String result = retrofit_result.getResult(); Log.d("결과", result); if (result.equals("empty")) { Log.d("계정", "공백"); Toast.makeText(Sign_up.this, "공백이 있는 항목이 있습니다.", Toast.LENGTH_SHORT).show(); } else if (result.equals("cant")) { Log.d("계정", "사용 불가"); Toast.makeText(Sign_up.this, "사용할 수 없는 아이디입니다.", Toast.LENGTH_SHORT).show(); } else if (result.equals("success")) { Log.d("계정", "가입 완료"); Toast.makeText(Sign_up.this, "회원가입이 완료되었습니다.", Toast.LENGTH_SHORT).show(); finish(); } else if (result.contains("fail")) { Log.d("계정", "가입 실패"); Toast.makeText(Sign_up.this, "회원가입을 실패했습니다.", Toast.LENGTH_SHORT).show(); finish(); } } @Override public void onFailure(Call<Retrofit_result> call, Throwable t) { t.printStackTrace(); } }; }<file_sep>package com.example.tripwithyou; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class Login_email extends AppCompatActivity { private static String BASE_URL = "http://13.125.246.30/"; private Call<Retrofit_result> userList; private Retrofit mRetrofit; private Retrofit_login retrofitInterface; private Gson mGson; private EditText eid,epw; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_email); eid = (EditText)findViewById(R.id.email_edit); epw = (EditText)findViewById(R.id.pw_edit); login(); signup(); } //회원가입버튼 클릭 이벤트 public void signup() { TextView textView = (TextView)findViewById(R.id.sign_up); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("버튼", "회원가입 버튼 클릭"); Intent sign_up = new Intent(getApplicationContext(), Sign_up.class); startActivity(sign_up); } }); } //로그인 버튼 클릭이벤트 public void login() { Button button = (Button)findViewById(R.id.login_btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("버튼", "로그인 버튼 클릭"); setRetrofitInit(); calluserlist(); } }); } //레트로핏 객체생성 protected void setRetrofitInit() { mGson = new GsonBuilder().setLenient().create(); mRetrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(mGson)) .build(); retrofitInterface = mRetrofit.create(Retrofit_login.class); } protected void calluserlist() { String id = eid.getText().toString(); String pw = epw.getText().toString(); userList = retrofitInterface.getlist(id, pw); userList.enqueue(mRetrofitCallback); } protected Callback<Retrofit_result> mRetrofitCallback = new Callback<Retrofit_result>() { @Override public void onResponse(Call<Retrofit_result> call, Response<Retrofit_result> response) { Retrofit_result retrofit_result = response.body(); String result = retrofit_result.getResult(); Log.d("결과", result); if (result.equals("success")) { Log.d("로그인", "로그인 완료"); //sp 써서 로그인. SharedPreferences sp = getSharedPreferences("login",MODE_PRIVATE); //저장을 하기위해 editor를 이용하여 값을 저장시켜준다. SharedPreferences.Editor editor = sp.edit(); String id = eid.getText().toString(); // 사용자가 입력한 저장할 데이터 editor.putString("id",id); editor.commit(); //메인으로 보냄 Intent intent = new Intent(Login_email.this, MainActivity.class); startActivity(intent); //다른 액티비티 전부 종료 ActivityCompat.finishAffinity(Login_email.this); Toast.makeText(Login_email.this, "로그인 되었습니다.", Toast.LENGTH_SHORT).show(); } else if (result.contains("fail")) { Log.d("로그인", "로그인 실패"); Toast.makeText(Login_email.this, "아이디 혹은 비밀번호가 맞지 않습니다.", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Retrofit_result> call, Throwable t) { t.printStackTrace(); } }; } <file_sep>package com.example.tripwithyou; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class Fragment_food extends AppCompatActivity { // public fragment_hotel(){ } // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // ViewGroup view = (ViewGroup)inflater.inflate(R.layout.fragment_hotel, container, false); // return view; // } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_food); } } <file_sep>package com.example.tripwithyou; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; public class Search_city extends AppCompatActivity { @Override protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.search_city); } } <file_sep>package com.example.tripwithyou; public class Retrofit_result_profile { //php에서 받는 부분 //난 php에서 result만 받겠다. private final String nick; private final String name; private final String img; private final String grade; public Retrofit_result_profile(String nick, String name, String img, String grade) { this.nick = nick; this.name = name; this.img = img; this.grade = grade; } public String getNick() { return nick; } public String getName() { return name; } public String getImg() { return img; } public String getGrade() { return grade; } } <file_sep>package com.example.tripwithyou; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class Login_choice extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_choice); login_click(); } public void login_click(){ Button button = (Button)findViewById(R.id.email_btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), Login_email.class); startActivity(intent); Log.d("버튼", "이메일 계정으로 이용하기 버튼 클릭"); } }); } } <file_sep>package com.example.tripwithyou; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { final Fragment fragmentBoard = new Fragment_board(); final Fragment fragmentHome = new Fragment_home(); final Fragment fragmentMessage = new Fragment_message(); final Fragment fragmentProfile = new Fragment_profile(); private FragmentManager fragmentManager = getSupportFragmentManager(); Fragment active = fragmentHome; //초기화면 설정(다른애들 다 숨기고 home화면만 띄우겠다) @Override protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.main_activity); //바텀 네비게이션바 세팅 BottomNavigationView navigationView = (BottomNavigationView) findViewById(R.id.bottom_bar); navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); fragmentManager.beginTransaction().add(R.id.frame_layout, fragmentProfile, "4").hide(fragmentProfile).commit(); fragmentManager.beginTransaction().add(R.id.frame_layout, fragmentMessage, "3").hide(fragmentMessage).commit(); fragmentManager.beginTransaction().add(R.id.frame_layout, fragmentBoard, "2").hide(fragmentBoard).commit(); fragmentManager.beginTransaction().add(R.id.frame_layout, fragmentHome, "1").commit(); } //바텀 네비바 클릭 리스너 private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.bottom_home: Log.d("home", "home 버튼 클릭"); fragmentManager.beginTransaction().hide(active).show(fragmentHome).commit(); active = fragmentHome; return true; case R.id.bottom_board: Log.d("board", "board 버튼 클릭"); fragmentManager.beginTransaction().hide(active).show(fragmentBoard).commit(); active = fragmentBoard; return true; case R.id.bottom_message: Log.d("message", "message 버튼 클릭"); fragmentManager.beginTransaction().hide(active).show(fragmentMessage).commit(); active = fragmentMessage; return true; case R.id.bottom_profile: Log.d("profile", "profile 버튼 클릭"); fragmentManager.beginTransaction().hide(active).show(fragmentProfile).commit(); active = fragmentProfile; return true; } return false; } }; //상단 액션바 연결 @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d("onCreateOptionsMenu","상단바 연결"); getMenuInflater().inflate(R.menu.action_bar,menu); return super.onCreateOptionsMenu(menu); } // //상단바 검색버튼 눌렀을 때 @Override public boolean onOptionsItemSelected(MenuItem item) { Log.d("상단바","검색버튼 클릭"); int id = item.getItemId(); if (id == R.id.action_bar_search) { startActivity(new Intent(MainActivity.this, Search_city.class)); return true; } return super.onOptionsItemSelected(item); } //첫 화면에서 뒤로가기 눌렀을때 토스트메시지 띄워주는 부분 // 뒤로가기 버튼 입력시간이 담길 long 객체 private long pressedTime = 0; // 리스너 생성 public interface OnBackPressedListener { void onBack(); void onBackPressed(); } // 리스너 객체 생성 private OnBackPressedListener mBackListener; // 리스너 설정 메소드 public void setOnBackPressedListener(OnBackPressedListener listener) { mBackListener = listener; } // 뒤로가기 버튼을 눌렀을 때 메소드 @Override public void onBackPressed() { // 다른 Fragment 에서 리스너를 설정했을 때 처리하는 부분 if(mBackListener != null) { mBackListener.onBack(); Log.e("!!!", "Listener is not null"); // 리스너가 설정되지 않은 상태(예를들어 메인Fragment)라면 // 뒤로가기 버튼을 연속적으로 두번 눌렀을 때 앱이 종료 } else { Log.e("!!!", "리스너 null값 아님"); if ( pressedTime == 0 ) { Toast.makeText(this, "한번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show(); pressedTime = System.currentTimeMillis(); } else { int seconds = (int) (System.currentTimeMillis() - pressedTime); if ( seconds > 2000 ) { Toast.makeText(this, "한번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show(); pressedTime = 0 ; } else { super.onBackPressed(); Log.e("!!!", "onBackPressed : finish, killProcess/종료"); //어플 완전히 종료 finish(); android.os.Process.killProcess(android.os.Process.myPid()); //꺼진것처럼 보이는거 // Intent homeIntent = new Intent(Intent.ACTION_MAIN); // homeIntent.addCategory(Intent.CATEGORY_HOME); // homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(homeIntent); } } } } } <file_sep>package com.example.tripwithyou; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; public class Fragment_hotel extends AppCompatActivity { // public fragment_hotel(){ } // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // ViewGroup view = (ViewGroup)inflater.inflate(R.layout.fragment_hotel, container, false); // return view; // } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_hotel); } } <file_sep>package com.example.tripwithyou; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class Fragment_home extends Fragment implements MainActivity.OnBackPressedListener { ViewGroup view; MainActivity activity; long backKeyPressedTime; Toast toast; private Call<Retrofit_result_home> userList; Retrofit_home retrofitInterface; private Adapter_home adapter; private ArrayList<Recycler_DTO_home> datalist = new ArrayList<>(); private ArrayList<Recycler_DTO_home_horizontal> datalist_horizontal = new ArrayList<>(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { Log.d("onCreateView", "fragment_home 실행"); view = (ViewGroup)inflater.inflate(R.layout.fragment_home, container, false); RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.home_rcv); //아이템 보여주는거 크기 일정하게 recyclerView.setHasFixedSize(true); //리사이클러뷰에 리사이클러뷰 매니저붙임 recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); adapter = new Adapter_home(getActivity(), datalist); recyclerView.setAdapter(adapter); activity = (MainActivity) getActivity(); toast = Toast.makeText(getContext(),"한번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT); Log.d("홈","홈 화면 onCreate"); hotelclick(); enjoyclick(); return view; } @Override public void onActivityCreated(@Nullable Bundle saveInstanceState) { super.onActivityCreated(saveInstanceState); Log.d("onActivityCreated","fragment_home 실행"); } @Override public void onCreate(@Nullable Bundle saveInstanceState){ Log.d("onCreate","fragment_home 실행"); super.onCreate(saveInstanceState); getRcvinfo(); } @Override public void onBack(){ } @Override public void onAttach(Context context) { super.onAttach(context); activity = (MainActivity)getActivity(); } @Override public void onDetach() { super.onDetach(); activity = null; } @Override public void onBackPressed(){ //터치간 시간을 줄이거나 늘리고 싶다면 2000을 원하는 시간으로 변경해서 사용하시면 됩니다. if(System.currentTimeMillis() > backKeyPressedTime + 2000){ backKeyPressedTime = System.currentTimeMillis(); toast.show(); return; } if(System.currentTimeMillis() <= backKeyPressedTime + 2000){ getActivity().finish(); toast.cancel(); } } public void hotelclick(){ //호텔버튼 클릭이벤트 Button hotel = (Button)view.findViewById(R.id.hotel); hotel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("버튼", "호텔 버튼 클릭 완료"); Intent intent = new Intent(getActivity(), Fragment_hotel.class); startActivity(intent); } }); } public void enjoyclick(){ //즐길거리 클릭이벤트 Button hotel = (Button)view.findViewById(R.id.enjoy); hotel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("버튼", "즐길거리 버튼 클릭 완료"); // Intent intent = new Intent(getActivity(), sample.class); //관리자 권한이면 랜드마크 정보 등록하는 버튼 나오게 Intent intent = new Intent(getActivity(), Fragment_enjoy.class); startActivity(intent); } }); } public void getRcvinfo() { Log.d("getRCVinfo", "리사이클러뷰 세팅"); SharedPreferences sp = getActivity().getSharedPreferences("where", Context.MODE_PRIVATE); String where = String.valueOf(sp.getAll().values()); Log.d("where", where); //어디로 가는지 설정 안해뒀으면 if (where.equals("") || where.equals(null) || where.equals("[]")) { //랜덤으로 관광지 뜨게 하기 setRetrofitInit(); calluserlist(); } //어디로 가는지 설정해뒀으면 else if (!where.equals("") || !where.equals(null)) { //설정해둔 곳의 정보만 가져오기 } } //레트로핏 부분 protected void setRetrofitInit() { Gson mGson = new GsonBuilder().setLenient().create(); Retrofit mRetrofit = new Retrofit.Builder() .baseUrl("http://13.125.246.30/") .addConverterFactory(GsonConverterFactory.create(mGson)) .build(); retrofitInterface = mRetrofit.create(Retrofit_home.class); } protected void calluserlist() { String send = "send"; userList = retrofitInterface.getlist(send); userList.enqueue(mRetrofitCallback); } protected Callback<Retrofit_result_home> mRetrofitCallback = new Callback<Retrofit_result_home>() { @Override public void onResponse(Call<Retrofit_result_home> call, Response<Retrofit_result_home> response) { Retrofit_result_home retrofit_result = response.body(); System.out.println("결과값:"+response.body().toString()); String result = retrofit_result.getResult(); //JSONArray json = retrofit_result.getArray(); //Log.d("json", ""+json); Log.d("결과", result); if (result.contains("success")) { //관리자가 즐길거리 업로드해놓은 정보 홈화면에 뿌리는 부분 List<Recycler_DTO_home_Vertical> resultList = retrofit_result.getArray(); if(resultList != null && !resultList.equals("") && resultList.size() > 0){ for(int i = 0; i < resultList.size(); i++){ String country = resultList.get(i).getCountry(); String photo = resultList.get(i).getPhoto(); String[] photoArray = photo.split(", "); String landmark = resultList.get(i).getName(); datalist.add(new Recycler_DTO_home(country, landmark, photoArray)); datalist_horizontal.add(new Recycler_DTO_home_horizontal(photoArray)); } } else { System.out.println("리스트가 없습니다."); } } else if (result.contains("fail")) { } } @Override public void onFailure(Call<Retrofit_result_home> call, Throwable t) { t.printStackTrace(); } }; } <file_sep>package com.example.tripwithyou; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class Adapter_upload_pic extends RecyclerView.Adapter<Adapter_upload_pic.MyViewHolder> { private Context context; private ArrayList<Recycler_DTO_uploadProfilePic> datalist = new ArrayList<>(); @Override //뷰홀더 생성 //화면에 뿌려주고 holder에 연결 public Adapter_upload_pic.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //뷰생성 (아이템 레이아웃 기반) //inflater는 뷰를 실제 객체화하는 용도 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rcv_uploadpic_itemview, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(Adapter_upload_pic.MyViewHolder holder, int position) { //각 위치에 문자열 세팅 Recycler_DTO_uploadProfilePic data = datalist.get(position); // holder.image.setImageURI(Uri.parse(data.getImg())); Log.d("onBindView","실행"); Glide.with(holder.itemView.getContext()).load(data.getImg()).into(holder.image); } @Override public int getItemCount() { return datalist.size(); } // public void additem(Recycler_DTO_upload dto) { // datalist.add(dto); // } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView image; public MyViewHolder(View itemview) { super(itemview); Log.d("MyViewHolder", "실행"); image = (ImageView)itemview.findViewById(R.id.upload_pic); } } //생성자 public Adapter_upload_pic(Context context, ArrayList<Recycler_DTO_uploadProfilePic> datalist) { this.context = context; this.datalist = datalist; } } <file_sep>package com.example.tripwithyou; public class Recycler_DTO_home { private String city; private String randmark; private String[] img; public Recycler_DTO_home(String city, String randmark, String[] img) { this.city = city; this.randmark = randmark; this.img = img; } //get 외부에서 get해옴 public String getCity() { return city; } public String getRandmark() { return randmark; } public String[] getImg() { return img; } //외부에서 받은 텍스트에 넣음? public void setCity(String city) { this.city = city; } public void setRandmark(String randmark) { this.randmark = randmark; } public void setImg(String[] img) { this.img = img; } } <file_sep>package com.example.tripwithyou; public class Recycler_DTO_home_horizontal { private String[] image; public Recycler_DTO_home_horizontal(String[] image) { this.image = image; } public String[] getImage() { return image; } public void setImage(String[] image) { this.image = image; } } <file_sep>package com.example.tripwithyou; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface Retrofit_profilePicChange { //프사 구현 // 프로필 이미지 보내기 @GET("profile_change.php") Call<Retrofit_result> img(@Query("id") String id, @Query("img") String img, @Query("nick") String nick, @Query("name")String name); }
b1960c0d960ee8af1b636a03160b02925b46d35b
[ "Java", "Gradle" ]
17
Java
leegise-lab/TripWithYou
c18a52adb9af4cd4953240edd3b982d66a3a1091
72576bc97d289b8bdfde8c90f326445f1129a7ef
refs/heads/master
<file_sep># encoding: utf-8 require 'bundler' Bundler.require(:default, :test) require 'simplecov' SimpleCov.start require "minitest/autorun" class TestClass < Minitest::Test require 'URLcrypt' def assert_bytes_equal(string1, string2) bytes1 = string1.bytes.to_a.join(':') bytes2 = string2.bytes.to_a.join(':') assert_equal(bytes1, bytes2) end def assert_decoding(encoded, plain) decoded = URLcrypt.decode(encoded) assert_bytes_equal(plain, decoded) end def assert_encoding(encoded, plain) actual = URLcrypt.encode(plain) assert_bytes_equal(encoded, actual) end def assert_encode_and_decode(encoded, plain) assert_encoding(encoded, plain) assert_decoding(encoded, plain) end end<file_sep>require 'openssl' module URLcrypt # avoid vowels to not generate four-letter words, etc. # this is important because those words can trigger spam # filters when URLs are used in emails TABLE = "1bcd2fgh3jklmn4pqrstAvwxyz567890".freeze class Chunk def initialize(bytes) @bytes = bytes end def decode bytes = @bytes.take_while {|c| c != 61} # strip padding bytes = bytes.find_all{|b| !TABLE.index(b.chr).nil? } # remove invalid characters n = (bytes.length * 5.0 / 8.0).floor p = bytes.length < 8 ? 5 - (n * 8) % 5 : 0 c = bytes.inject(0) {|m,o| (m << 5) + TABLE.index(o.chr)} >> p (0..n-1).to_a.reverse.collect {|i| ((c >> i * 8) & 0xff).chr} end def encode n = (@bytes.length * 8.0 / 5.0).ceil p = n < 8 ? 5 - (@bytes.length * 8) % 5 : 0 c = @bytes.inject(0) {|m,o| (m << 8) + o} << p [(0..n-1).to_a.reverse.collect {|i| TABLE[(c >> i * 5) & 0x1f].chr}, ("=" * (8-n))] # TODO: remove '=' padding generation end end def self.key=(key) warn "`URLcrypt.key=` is deprecated. See the README on using environment variables with URLcrypt." ENV['urlcrypt_key'] = [key].pack('H*') end def self.chunks(str, size) result = [] bytes = str.bytes while bytes.any? do result << Chunk.new(bytes.take(size)) bytes = bytes.drop(size) end result end # strip '=' padding, because we don't need it def self.encode(data) chunks(data, 5).collect(&:encode).flatten.join.tr('=','') end def self.decode(data) chunks(data, 8).collect(&:decode).flatten.join end def self.decrypt(data, key: ENV.fetch('urlcrypt_key')) iv, encrypted = data.split('Z').map{|part| decode(part)} fail DecryptError, "not a valid string to decrypt" unless iv && encrypted decrypter = cipher(:decrypt, key: key) decrypter.iv = iv decrypter.update(encrypted) + decrypter.final end def self.encrypt(data, key: ENV.fetch('urlcrypt_key')) crypter = cipher(:encrypt, key: key) crypter.iv = iv = crypter.random_iv "#{encode(iv)}Z#{encode(crypter.update(data) + crypter.final)}" end private def self.cipher(mode, key:) cipher = OpenSSL::Cipher.new('aes-256-cbc') cipher.send(mode) cipher.key = key.byteslice(0,cipher.key_len) cipher end class DecryptError < ::ArgumentError; end end <file_sep># URLcrypt [![Build Status](https://travis-ci.org/cheerful/URLcrypt.png?branch=master)](https://travis-ci.org/cheerful/URLcrypt) [![Coverage Status](https://coveralls.io/repos/cheerful/URLcrypt/badge.png?branch=master)](https://coveralls.io/r/cheerful/URLcrypt) Ever wanted to securely transmit (not too long) pieces of arbitrary binary data in a URL? **URLcrypt** makes it easy! This gem is based on the [base32](https://github.com/stesla/base32) gem from <NAME>. URLcrypt uses **256-bit AES symmetric encryption** to securely encrypt data, and encodes and decodes **Base 32 strings that can be used directly in URLs**. This can be used to securely store user ids, download expiration dates and other arbitrary data like that when you access a web application from a place that doesn't have other authentication or persistence mechanisms (like cookies): * Loading a generated image from your web app in an email * Links that come with an expiration date (à la S3) * Mini-apps that don't persist data on the server Works with Ruby 2.6+ **Important**: As a general guideline, URL lengths shouldn't exceed about 2000 characters in length, as URLs longer than that will not work in some browsers and with some (proxy) servers. This limits the amount of data you can store with URLcrypt. **WORD OF WARNING: THERE IS NO GUARANTEE WHATSOEVER THAT THIS GEM IS ACTUALLY SECURE AND WORKS. USE AT YOUR OWN RISK.** URLcrypt is an extraction from [Noko Time Tracking](https://nokotime.com), where it is used to generate URLs for dynamically generated images in emails. Patches are welcome; please include tests! ## Installation Add to your Gemfile: ```ruby gem 'urlcrypt', '~> 0.1.1', require: 'URLcrypt' ``` Then, set `ENV['urlcrypt_key']` to the default encryption key you will be using. This should be at least a 256-bit AES key, see below. **To ensure your strings are encoded, URLcrypt uses `ENV.fetch` to check for the variable, so it _must_ be set.** ## Example ```ruby # encrypt and decrypt using the default key from ENV['urlcrypt_key']! URLcrypt.encrypt('chunky bacon!') # => "<KEY>" URLcrypt.decrypt('<KEY>') # => "chunky bacon!" # If needed, you can specify a custom key per-call URLcrypt.encrypt('chunky bacon!', key: '...') # => "....." URLcrypt.decrypt('<KEY>', key: '...') # => "chunky bacon!" # encoding without encryption (don't use for anything sensitive!), doesn't need key set URLcrypt.encode('chunky bacon!') # => "mnAhk6tlp2qg2yldn8xcc" URLcrypt.decode('mnAhk6tlp2qg2yldn8xcc') # => "chunky bacon!" ``` ### Generating keys The easiest way to generate a secure key is to use `rake secret` in a Rails app: ```sh $ rake secret ba7f56f8f9873b1653d7f032cc474938fd749ee8fbbf731a7c41d698826aca3cebfffa832be7e6bc16eaddc3826602f35d3fd6b185f261ee8b0f01d33adfbe64 ``` To use the key with URLcrypt, you'll need to convert that from a hex string into a real byte array: ```ruby ENV['urlcrypt_key'] = ['longhexkeygoeshere'].pack('H*') ``` ## Running the Test Suite If you want to run the automated tests for URLcrypt, issue this command from the distribution directory. ```sh $ rake test:all ``` ## Why not Base 64, or an other radix/base library? URLcrypt uses a modified Base 32 algorithm that doesn't use padding characters, and doesn't use vowels to avoid bad words in the generated string. The main reason why Base 32 is useful is that Ruby's built-in Base 64 support is, IMO, looking ugly in URLs and requires several characters that need to be URL-escaped. Unfortunately, some other gems out there that in theory could handle this (like the radix gem) fail with strings that start with a "\0" byte. ## References * Base 32: RFC 3548: http://www.faqs.org/rfcs/rfc3548.html <file_sep># encoding: utf-8 require 'test_helper' class TestURLcrypt < TestClass def test_empty_string assert_encode_and_decode('', '') end def test_encode assert_encode_and_decode( '111gc86f4nxw5zj1b3qmhpb14n5h25l4m7111', "\0\0awesome \n ü string\0\0") end def test_invalid_encoding assert_decoding('ZZZZZ', '') end def test_arbitrary_byte_strings 0.step(1500,17) do |n| original = (0..n).map{rand(256).chr}.join encoded = URLcrypt::encode(original) assert_decoding(encoded, original) end end def test_key_deprecation URLcrypt.key = 'aaaa' assert_equal "\xAA\xAA", ENV.fetch('urlcrypt_key') end end <file_sep># encoding: utf-8 require 'test_helper' class URLcryptEncryptionTest < TestClass def teardown ENV["urlcrypt_key"] = nil end def test_requires_ENV_if_no_key_provided error = assert_raises(KeyError) do ::URLcrypt::decrypt("just some plaintext") end assert_equal error.message, "key not found: \"urlcrypt_key\"" error = assert_raises(KeyError) do ::URLcrypt::encrypt("just some plaintext") end assert_equal error.message, "key not found: \"urlcrypt_key\"" end def test_encryption_with_ENV_key # pack() converts this secret into a byte array secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') ENV['urlcrypt_key'] = secret assert_equal OpenSSL::Cipher.new('aes-256-cbc').key_len, secret.bytesize original = "hello world!" encrypted = URLcrypt::encrypt(original) assert_equal(URLcrypt::decrypt(encrypted), original) end def test_decrypt_error_with_ENV_key secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') ENV['urlcrypt_key'] = secret error = assert_raises(URLcrypt::DecryptError) do ::URLcrypt::decrypt("just some plaintext") end assert_equal error.message, "not a valid string to decrypt" end def test_encryption_with_explicit_key # pack() converts this secret into a byte array secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') assert_equal OpenSSL::Cipher.new('aes-256-cbc').key_len, secret.bytesize original = "hello world!" encrypted = URLcrypt::encrypt(original, key: secret) assert_equal(URLcrypt::decrypt(encrypted, key: secret), original) end def test_decrypt_error_with_explicit_key secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') error = assert_raises(URLcrypt::DecryptError) do ::URLcrypt::decrypt("just some plaintext", key: secret) end assert_equal error.message, "not a valid string to decrypt" end def test_threads_with_ENV_keys # pack() converts this secret into a byte array secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') ENV['urlcrypt_key'] = secret assert_equal OpenSSL::Cipher.new('aes-256-cbc').key_len, secret.bytesize parent_string = "hello world!" parent_encrypted = URLcrypt::encrypt(parent_string) assert_equal(URLcrypt::decrypt(parent_encrypted), parent_string) threads = 100.times.map do |n| Thread.new{ original = "Test String #{n}" encrypted = URLcrypt::encrypt(original) assert_equal(URLcrypt::decrypt(encrypted), original) thread_encrypted = URLcrypt::encrypt(parent_string) assert_equal(URLcrypt::decrypt(thread_encrypted), parent_string) assert_equal(URLcrypt::decrypt(parent_encrypted), parent_string) } end threads.each { |thr| thr.join } end def test_threads_with_explicit_per_thread_keys threads = 100.times.map do |n| Thread.new{ key = ["d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d-secret-key-#{n}"].pack('H*') original = "Test String #{n}" encrypted = URLcrypt::encrypt(original, key: key) assert_equal(URLcrypt::decrypt(encrypted, key: key), original) } end threads.each { |thr| thr.join } end def test_threads_with_explicit_per_thread_keys_overriding_ENV_variable secret = ['d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d'].pack('H*') ENV['urlcrypt_key'] = secret threads = 100.times.map do |n| Thread.new{ key = ["d25883a27b9a639da85ea7e159b661218799c9efa63069fac13a6778c954fb6d-secret-key-#{n}"].pack('H*') original = "Test String #{n}" encrypted = URLcrypt::encrypt(original, key: key) assert_equal(URLcrypt::decrypt(encrypted, key: key), original) parent_encryption = URLcrypt::encrypt(original) refute_equal parent_encryption, encrypted } end threads.each { |thr| thr.join } end end<file_sep># encoding: utf-8 class URLcryptRegressionTest < TestClass def setup # this key was generated via rake secret in a rails app, the pack() converts it into a byte array @secret = ['<KEY>'].pack('H*') end def test_encryption_and_decryption original = '{"some":"json_data","token":"<PASSWORD>"}' encrypted = URLcrypt.encrypt(original, key: @secret) assert_equal(URLcrypt::decrypt(encrypted, key: @secret), original) end def test_encryption_with_too_long_key assert OpenSSL::Cipher.new('aes-256-cbc').key_len < @secret.bytesize original = "hello world!" encrypted = URLcrypt::encrypt(original, key: @secret) assert_equal(URLcrypt::decrypt(encrypted, key: @secret), original) end def test_encryption_and_decryption_with_too_long_key assert OpenSSL::Cipher.new('aes-256-cbc').key_len < @secret.bytesize original = '{"some":"json_data","token":"<PASSWORD>"}' encrypted = URLcrypt.encrypt(original, key: @secret) assert_equal(URLcrypt::decrypt(encrypted, key: @secret), original) end end<file_sep>source 'https://rubygems.org' group :test do gem 'debug', platforms: :ruby gem 'minitest' gem "rake" gem "rubocop", require: false gem "rubocop-thread_safety", require: false gem 'simplecov' end
504c15e782bac57da5f42d9b42686833768f344d
[ "Markdown", "Ruby" ]
7
Ruby
cheerful/URLcrypt
a88d5340892349d0db10f20220a12940e581ca38
c550b81404c062c9d31d460973cbe20fbac4b585
refs/heads/master
<file_sep>/** * @file filerev.js * @author <NAME> <<EMAIL>> * @copyright 2015 Middle of June. All rights reserved. */ 'use strict'; module.exports = { // Renames files for browser caching purposes // https://www.npmjs.com/package/grunt-filerev options: { algorithm: 'md5', length: 4 }, all: { src: [ '<%= cfg.dst %>/scripts/**/*.js', '<%= cfg.dst %>/styles/{,*/}*.css' ] }, jsfiles: { src: [ '<%= cfg.dst %>/scripts/**/*.js' ] }, cssfiles: { src: [ '<%= cfg.dst %>/styles/{,*/}*.css' ] } }; <file_sep>var colors = { 'Renaissance': '#212D8B', 'Baroque Italy': '#3366FF', 'Baroque France': '#6633FF', 'Baroque Europe': '#CC33FF', 'Late Baroque / Rococo': '#FF33CC', 'French Rationalism': '#33CCFF', 'Archaeology and Antiques': '#003DF5', 'Visionary Architecture': '#002EB8', 'Picturesque': '#FF3366', 'France: Revolution and the Public': '#33FFCC', 'Neo-Gothic': '#B88A00', 'Neoclassicism: Nationalism': '#F5B800', 'Industrial Revolution': '#FF6633', 'Reactions Against Industrialization': '#33FF66', 'Vienna Secession / Ringstrasse': '#66FF33', 'Countering Ornamentation': '#CCFF33', 'Arts & Crafts / Art Nouveau': '#FFCC33', 'First Gen Chicago School': '#D2CA58', };<file_sep>/** * @file Gruntfile.js * @author <NAME> * @copyright 2016 USC Architecture. All rights reserved. */ 'use strict'; module.exports = function (grunt) { // Time how long tasks take; Optimizing build times! require('time-grunt')(grunt); // cfgurable paths var cfg = { src: 'src', dst: 'app' }; // Define the cfguration for all the tasks grunt.initConfig({ // Project settings cfg: cfg, scpConfig: grunt.file.readJSON('scp.json'), // Watches files for changes and runs tasks based on what's changed // watch: require('./grunt-include/watch'), // Cachebuster! - appends random alphanumeric string before file extension //filerev: require('./grunt-include/filerev'), /** * Uglify: minify js files * Needs to happen after JS file get copied to dist * https://github.com/gruntjs/grunt-contrib-uglify */ // uglify: { // options: { // preserveComments: false, // screwIE8: true, // mangle: false, // // cwd: '<%= cfg.src %>/scripts/vendor/' // // exceptionsFiles: [ // // 'datatables.min.js', // // 'jquery-2.2.0.min.js' // // ] // }, // dist: { // files: [{ // expand: true, // cwd: '<%= cfg.src %>/scripts/vendor/', // src: [ '*.js', '!datatables.min.js' ], // dest: '<%= cfg.dst %>/scripts/vendor', // ext: '.min.js' // }] // }// End uglify:dist // },// End uglify task scp: { options: { host: '<%= scpConfig.host %>', username: '<%= scpConfig.username %>', password: '<%= sc<PASSWORD> %>' }, your_target: { files: [{ cwd: '<%= cfg.src %>', src: [ '**/*.html', '**/*.js', '**/*.csv', '**/*.css', //'images/_grey-bg.png', // 'images/*', ], filter: 'isFile', // path on the server dest: '<%= scpConfig.directory %>' }] }, }// End task grunt-scp });// End initConfit grunt.registerTask('default', [ 'build' ]);// End register task :: default // This is the default Grunt task if you simply run "grunt" in project dir grunt.registerTask('build', [ 'scp' // 'uglify', // 'filerev:all', // 'usemin', // 'htmlmin' ]);// End register task :: build // grunt.registerTask('pushtodev', ['build', 'ftpush:dev']); // // LOAD NPM TASKS // // npm install <TASK_NAME> --save-dev (if any are missing) grunt.loadNpmTasks('grunt-ssh'); grunt.loadNpmTasks('grunt-scp'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-filerev'); // grunt.loadNpmTasks('grunt-contrib-watch'); // grunt.loadNpmTasks('grunt-contrib-cssmin'); // grunt.loadNpmTasks('grunt-contrib-htmlmin'); // grunt.loadNpmTasks('grunt-usemin'); // // grunt.loadNpmTasks('grunt-sftp-deploy'); // bulk upload };// End module.exports
69f6bb3022196baba5b72003cc72a46cc49f1b02
[ "JavaScript" ]
3
JavaScript
jericho1ne/flashcards
9b0340ec6ae027d7d2e70f098620f0947c916307
7596a98eed0de21f35433730a5e15c362e8b8e97
refs/heads/master
<repo_name>HybridiSpeksi/hybridispeksi<file_sep>/readme.md # HybridiSpeksi Website project for HybridiSpeksi ry and it's yearly theatre production. ## Tech stack Client is a React application with Redux state management. Backen is a Node REST server with Express.js. MongoDB. Production application runs on Digitalocean using Docker containers. ## Requirements Docker ## Development setup 1. Fork the repository from github: https://github.com/HybridiSpeksi/hybridispeksi 2. Clone your for to your local environment: ``` $ git clone https://github.com/<yourUsername>/hybridispeksi ``` 3. Go to root folder: ``` $ cd hybridispeksi ``` 4. Populate env variables. Add .dev_vars-env -file to project root, you'll get it from web admins. 5. Install dependencies. Docker-compose will use node_modules for molumes. ``` $ npm install ``` 6. Run project in development mode with docker-compose: ``` docker-compose up ``` 7. Start developing. No bugs pls, only perfect code. ## Deployment // TODO <file_sep>/src/client/Utils/constants.js const constants = { // Message types MESSAGE_SUCCESS: 'success', MESSAGE_WARNING: 'warning', MESSAGE_ERROR: 'error', // AJAX ids PRODUCTION_REQUEST: 'PRODUCTION REQUEST', SEND_FEEDBACK: 'SEND FEEDBACK', }; export default constants; <file_sep>/src/client/components/Admin/Produktio/ProduktionjasenLista.js import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import css from './Produktionjasenet.css'; import { selectMember } from '../../../actions/productionActions'; const Jasen = ({ jasen, i, select, }) => { const getTehtavatStr = (j) => { let tehtavatStr = ''; j.tehtavat.map((t, k) => { tehtavatStr += t; if (j.tehtavat.length > k + 1) { tehtavatStr += ', '; } return tehtavatStr; }); return tehtavatStr; }; return ( <tr onClick={() => select(jasen)}> <td>{i + 1}</td> <td> {jasen.fname} {jasen.lname} </td> <td>{jasen.email}</td> <td>{jasen.pnumber}</td> <td>{getTehtavatStr(jasen)}</td> <td>{jasen.member ? <i className="fa fa-check" aria-hidden="true" /> : ''}</td> </tr> ); }; Jasen.propTypes = { jasen: PropTypes.object, i: PropTypes.number, select: PropTypes.func, }; const ProduktionjasenLista = ({ select, productionmembers, searchObject }) => { const { text, tehtava, jarjesto } = searchObject; const checkString = (j) => { if (text) { return j.fname.toLowerCase().indexOf(text) !== -1 || j.lname.toLowerCase().indexOf(text) !== -1 || j.email.toLowerCase().indexOf(text) !== -1; } return true; }; const checkTehtava = (j) => { if (tehtava) { return j.tehtavat.indexOf(tehtava) !== -1; } return true; }; const checkJarjesto = (j) => { if (jarjesto) { return j.jarjesto.indexOf(jarjesto) !== -1; } return true; }; const doFilter = jasen => checkString(jasen) && checkTehtava(jasen) && checkJarjesto(jasen); const rows = productionmembers .filter(jasen => doFilter(jasen)) .map((jasen, i) => ( <Jasen jasen={jasen} i={i} select={select} key={jasen._id} /> )); return ( <div className={css.jasentable}> <table className="table table-inverse table-striped"> <thead> <tr> <th>#</th> <th>Nimi</th> <th>Sähköposti</th> <th>Puh</th> <th>Tehtävä</th> <th>Yhdistyksen jäsen</th> </tr> </thead> <tbody>{rows}</tbody> </table> </div> ); }; ProduktionjasenLista.propTypes = { searchObject: PropTypes.object, select: PropTypes.func, productionmembers: PropTypes.array, }; const mapStateToProps = state => ({ productionmembers: state.production.members, searchObject: state.production.searchObject, }); const mapDispatchToProps = dispatch => ({ select: member => dispatch(selectMember(member)), }); export default connect(mapStateToProps, mapDispatchToProps)(ProduktionjasenLista); <file_sep>/src/client/components/Admin/Feedback/Feedback.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import cuid from 'cuid'; import styles from './AdminFeedback.css'; import ajax from '../../../Utils/Ajax'; import * as messageActions from 'actions/messageActions'; import * as loaderActions from 'actions/loaderActions'; const FeedbackCard = ({ name, email, feedback }) => ( <div className={styles.feedbackCard}> <div className={styles.feedbackContent}> <p>{feedback}</p> </div> <div className={styles.name}> <p>{name}</p> </div> <div className={styles.email}> <p>{email}</p> </div> </div> ); FeedbackCard.propTypes = { name: PropTypes.string, email: PropTypes.string, feedback: PropTypes.string, }; class Feedback extends Component { constructor() { super(); this.state = { feedbacks: [], }; this.fetchData = this.fetchData.bind(this); } async componentDidMount() { this.fetchData(); } async fetchData() { try { this.props.showLoader(); const res = await ajax.sendGet('/admin/palautteet'); console.log(res.data); this.setState({ feedbacks: res.data }); this.props.hideLoader(); } catch (e) { this.props.addWarningMessage({ heading: 'Virhe haettaessa palautteita: ', text: e.message }, 5000); } } render() { const feedbackList = this.state.feedbacks.map(feedback => ( <FeedbackCard key={cuid()} {...feedback} /> )); return ( <div className={styles.container}> <h1>Palautteet</h1> <div className={styles.feedbackList}> {feedbackList} </div> </div> ); } } Feedback.propTypes = { addWarningMessage: PropTypes.func, showLoader: PropTypes.func, hideLoader: PropTypes.func, }; const mapStateToProps = state => ({ }); const mapDispatchToProps = dispatch => ({ addWarningMessage: message => dispatch(messageActions.addWarningMessage(message)), showLoader: () => dispatch(loaderActions.showLoader()), hideLoader: () => dispatch(loaderActions.hideLoader()), }); export default connect(mapStateToProps, mapDispatchToProps)(Feedback); <file_sep>/src/client/components/SectionDivider/SectionDivider.js import React from 'react'; import styles from './SectionDivider.css'; const SectionDivider = () => ( <div className={'row justify-content-center ' + styles.hr}> <div className="col-8"> <hr /> </div> </div> ); export default SectionDivider; <file_sep>/src/client/components/Admin/BookingManagement/ShowsList.js import React from 'react'; import cuid from 'cuid'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import styles from './ShowsList.css'; import * as actions from 'actions/bookingActions'; const Show = ({ show, handleClick, selected }) => ( <button className={`${styles.showRow} ${selected ? styles.selected : ''}`} onClick={() => handleClick(show)}> <span>{show.nameLong}</span> <span>{show.bookingCount}/{show.limit}</span> </button> ); Show.propTypes = { show: PropTypes.object, handleClick: PropTypes.func, selected: PropTypes.bool, }; const ShowsList = ({ shows, selectedShow, select, fetchBookings, }) => { const handleClick = (show) => { select(show); fetchBookings(show.id); }; return ( <div className={styles.container} > {shows.map((show) => { return <Show show={show} key={cuid()} handleClick={handleClick} selected={show.id === selectedShow.id} />; })} </div> ); }; ShowsList.propTypes = { shows: PropTypes.array, select: PropTypes.func, selectedShow: PropTypes.object, fetchBookings: PropTypes.func, }; const mapStateToProps = state => ({ shows: state.bookingManagement.shows, selectedShow: state.bookingManagement.selectedShow, }); const mapDispatchToProps = dispatch => ({ select: show => dispatch(actions.selectShow(show)), fetchBookings: showId => dispatch(actions.fetchBookings(showId)), }); export default connect(mapStateToProps, mapDispatchToProps)(ShowsList); <file_sep>/src/schema/esitys-model.js var mongoose = require('mongoose'); var esitysSchema = new mongoose.Schema({ day: String, date: Date, name: String, bookingCount: Number }, { collection: 'esitykset' }) module.exports = mongoose.model('Esitys', esitysSchema);<file_sep>/src/utils/bookingUtils.js const config = require('../config'); module.exports = { getTotalCount: (booking) => { const { normalCount, discountCount, specialPriceCount } = booking; return Number(normalCount) + Number(discountCount) + Number(specialPriceCount); }, countPrice: (booking) => { const { normalCount, discountCount, specialPriceCount, specialPrice, } = booking; let price = 0; price += normalCount * config.normalPrice; price += discountCount * config.discountPrice; price += specialPriceCount * specialPrice; return price; }, }; <file_sep>/src/client/components/Organization/Saannot.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styles from './Organization'; class Saannot extends Component { componentDidMount() { $(window).scrollTop(0); } render() { return ( <div className={'container-fluid ' + styles.container + ' ' + styles.headerPadding}> <div className={'row align-items-center justify-content-center ' + styles.header}> <div className="col-sm-10 col-11"> <h2 className="">Säännöt</h2> </div> </div> <div className={'row justify-content-center ' + styles.content}> <div className={'col-11 col-sm-10 col-md-10 ' + styles.saannotJaSeloste}> {/* <p className={"d-block text-center material-icons " + styles.infoicon}>info_outline</p> */} <h3>HYBRIDISPEKSI RY <br /> YHDISTYKSEN SÄÄNNÖT </h3> <h4>1§</h4> <p>Yhdistyksen nimi on HybridiSpeksi ja sen kotipaikka on Turku. Yhdistyksen kieli on suomi.</p> <h4>2§ Yhdistyksen tarkoitus</h4> <p>Yhdistyksen tarkoituksena on järjestää harrastustoimintaa Turun yliopiston luonnontieteiden ja tekniikan tiedekunnan opiskelijoille ja mahdollistaa vuosittaisen teatteriproduktion toteuttaminen tiedekunnan opiskelijoiden ja yhdistyksen jäsenten kesken. </p> <h4>3§ Yhdistyksen toiminnan laatu</h4> <p>Tarkoituksensa toteuttamiseksi yhdistys järjestää yhteistoimintaa ja illanviettoja jäsenistölleen. Yhdistyksen avulla suunnitellaan ja toteutetaan teatteriproduktion, joka esitetään yhdistyksen ulkopuolisille henkilöille. </p> <p>Toimintansa tukemiseksi yhdistys voi toimeenpanna asianmukaisen luvan saatuaan rahankeräyksiä järjestääkseen huvitilaisuuksia, sekä omistaa toimintaansa varten tarpeellista kiinteää, irtainta sekä aineetonta omaisuutta. Yhdistys voi ottaa vastaan avustuksia ja lahjoituksia. Produktion päätteeksi järjestetään teatteriesitykset, joihin yhdistys kerää yhdistyksen ulkopuolisilta katsojilta lipputuloja menojen kattamiseksi. Yhdistys on voittoa tavoittelematon. </p> <h4>4§ Yhdistyksen jäsenet</h4> <p>Yhdistyksen jäseneksi voi liittyä jokainen HybridiSpeksi-produktioon osallistuva tai yhdistyksen toiminnasta kiinnostunut. Yhdistys pitää yllä jäsenrekisteriä. Yhdistyksen varsinaiset jäsenet hyväksyy yhdistyksen hallitus. </p> <h4>5§ Yhdistyksestä eroaminen</h4> <p>Jäsenellä on oikeus erota yhdistyksestä ilmoittamalla siitä kirjallisesti hallitukselle tai sen puheenjohtajalle taikka ilmoittamalla erosta yhdistyksen kokouksessa merkittäväksi pöytäkirjaan. Hallitus voi erottaa jäsenen yhdistyksestä, jos jäsen on jättänyt täyttämättä ne velvoitukset, joihin hän on yhdistykseen liittymällä sitoutunut tai on menettelyllään yhdistyksessä tai sen ulkopuolella huomattavasti vahingoittanut yhdistystä tai ei enää täytä laissa taikka yhdistyksen säännöissä mainittuja jäsenyyden ehtoja. </p> <h4>6§ Jäsenmaksun määräytyminen</h4> <p>Vuotuisen jäsenmaksun perimisestä ja suuruudesta päättää kevätkokous.</p> <h4>7§ Hallituksen valinta ja muoto</h4> <p>Yhdistyksen hallitukseen kuuluu puheenjohtaja, varapuheenjohtaja, sihteeri, taloudenhoitaja ja nollasta (0) kolmeen (3) muuta jäsentä. Hallituksen toimikausi on vuoden mittainen kesäkuun ensimmäisestä päivästä seuraavan vuoden toukokuun viimeiseen päivään. Yhdistyksen hallituksen valitsee kevätkokous yhdistyksen varsinaisista jäsenistä. Yhdistys ja hallitus voivat erityisiä tehtäviä varten asettaa hallituksen alaisia toimikuntia ja toimihenkilöitä. Tällöin on määrättävä toimikausien pituudet, sekä toimikuntien osalta myös vastuuhenkilö. Yhdistys ja hallitus voivat vapauttaa nimittämänsä toimihenkilön kesken toimikauttaan. Hallituksen toimintasuunnitelman vahvistaa yhdistyksen kokous. </p> <h4>8§ Hallituksen yleinen toiminta</h4> <p>Hallitus kokoontuu puheenjohtajan tai hänen estyneenä ollessaan varapuheenjohtajan kutsusta, kun he katsovat siihen olevan aihetta tai kun vähintään puolet (1/2) hallituksen jäsenistä sitä vaatii. Päätökset hallituksen kokouksissa tehdään yksinkertaisella äänten enemmistöllä. Äänten mennessä tasan ratkaisee puheenjohtajan ääni, paitsi vaaleissa arpa. Hallitus on päätösvaltainen, kun puheenjohtaja tai varapuheenjohtaja ja vähintään puolet (1/2) sen muista jäsenistä on paikalla. </p> <h4>9§ Hallituksen tehtävät</h4> <p>Hallituksen tehtävänä on:</p> <ul> <li>johtaa yhdistyksen toimintaa;</li> <li>edustaa yhdistystä;</li> <li>huolehtia yhdistyksen hallintoa ja taloutta sekä valvoa sen etuja ja voimassaolevien sääntöjen ja määräysten noudattamista; </li> <li>kehittää yhdistyksen toimintaa;</li> <li>valmistella yhdistyksen kokouksissa esille tulevat asiat ja toimeenpanna niissä tehdyt päätökset;</li> <li>valvoa toimikuntien ja toimihenkilöiden toimintaa;</li> <li>laatia yhdistyksen toimintasuunnitelma ja -kertomus;</li> <li>laatia yhdistyksen talousarvio ja tilinpäätös;</li> <li>päättää jäseneksi hyväksymisestä sekä näiden erottamisesta yhdistyksestä;</li> <li>kouluttaa seuraava hallitus tehtäväänsä;</li> <li>päättää tarvittaessa muista asioista, joita ei ole määrätty yhdistyksen kokouksen päätettäväksi.</li> </ul> <h4>10§ Hallituksesta eroaminen</h4> <p>Hallituksen jäsen voi erota hallituksesta kesken kauden toimittamalla hallitukselle kirjallisen eroanomuksen. Mikäli hallituksen jäsen eroaa kesken kauden, on hallituksen kutsuttava koolle yhdistyksen ylimääräinen kokous neljäntoista (14) vuorokauden kuluessa siitä, kun eroanomus on tuotu esiin hallituksen kokouksessa. Yhdistyksen kokous myöntää eron ja valitsee eronneen tilalle uuden edustajan. </p> <h4>11§ Yhdistyksen nimen kirjoittaminen</h4> <p>Yhdistyksen nimen kirjoittaa hallituksen puheenjohtaja, sihteeri tai taloudenhoitaja kukin erikseen. Hallitus voi yksimielisellä päätöksellä myöntää nimenkirjoitusoikeuden myös muulle yhdistyksen jäsenelle. </p> <h4>12§ Yhdistyksen tilikausi</h4> <p>Yhdistyksen tilikausi on vuosi, kesäkuun ensimmäisestä päivästä seuraavan vuoden toukokuun viimeiseen päivään. Yhdistyksen tilejä tarkastamaan valitaan vuosikokouksessa vuodeksi kerrallaan yksi (1) toiminnantarkastaja ja varamies. Tilinpäätös ja vuosikertomus on annettava toiminnantarkastajalle viimeistään kaksi (2) viikkoa ennen syyskokousta. Toiminnantarkastajan tulee antaa kirjallinen lausuntonsa hallitukselle yhden (1) viikon kuluessa asiakirjojen vastaanottamisesta. </p> <h4>13§ Yhdistyksen kokous</h4> <p>Yhdistyksen ylintä päätäntävaltaa käyttää yhdistyksen kokous. Varsinaisia kokouksia ovat keväällä pidettävä yhdistyksen kevätkokous ja syksyllä pidettävä yhdistyksen syyskokous hallituksen määrääminä päivinä. Yhdistyksen kevätkokous pidetään viimeistään toukokuussa ja syyskokous viimeistään marraskuussa. Ylimääräinen kokous on kutsuttava koolle, mikäli vähintään 1/10 yhdistyksen äänioikeutetuista jäsenistä esittää sitä koskevan pyynnön kirjallisesti hallitukselle tai mikäli hallitus taikka yhdistyksen kokous katsoo kokouksen järjestämisen aiheelliseksi. Ylimääräinen kokous on pidettävä yhden (1) kuukauden kuluessa kirjallisen pyynnön jättämisestä. </p> <p>Yhdistyksen kokouksissa on jokaisella jäsenellä yksi (1) ääni. Yhdistyksen kokouksen päätökseksi tulee, ellei säännöissä ole toisin määrätty, se mielipide, jota on kannattanut yli puolet (1/2) annetuista äänistä. Äänten mennessä tasan ratkaisee kokouksen puheenjohtajan mielipide, vaaleissa kuitenkin arpa. Esityslistalla oleva asia voidaan panna pöydälle, mikäli pöydällepanoa koskevaa ehdotusta kannattaa kaksi (2) äänivaltaista jäsentä. Kiireelliseksi asia voidaan julistaa 2/3 äänten enemmistöllä. </p> <h4>14§ Yhdistyksen kokousten koollekutsuminen</h4> <p>Yhdistyksen kokoukset kutsutaan koolle hallituksen toimesta vähintään seitsemän (7) päivää ennen kokousta sähköpostitse yhdistyksen jäsenistön sähköpostilistalla taikka yhdistyksen internetsivustolla. </p> <p>Kokouskutsussa on mainittava, mikäli kokouksessa käsitellään yhdistyslain 23 §:ssä mainittuja tai niihin verrattavia asioita, kuten: </p> <ol> <li>yhdistyksen sääntöjen muuttamista;</li> <li>kiinteistön luovuttamista tai kiinnittämistä taikka yhdistyksen toiminnan kannalta huomattavan muun omaisuuden luovuttamista; </li> <li>hallituksen tai sen jäsenen taikka tilintarkastajan valitsemista tai erottamista;</li> <li>tilinpäätöksen vahvistamista ja vastuuvapauden myöntämistä;</li> <li>jäsenmaksun määräämistä tai</li> <li>yhdistyksen purkamista.</li> </ol> <h4>15§ Yhdistyksen syys- ja kevätkokouksessa käsiteltävät asiat</h4> <p>Yhdistyksen kevätkokouksessa käsitellään seuraavat asiat:</p> <ol> <li>Kokouksen avaus</li> <li>Valitaan kokouksen puheenjohtaja, sihteeri, kaksi (2) pöytäkirjantarkastajaa ja tarvittaessa kaksi (2) ääntenlaskijaa. </li> <li>Todetaan kokouksen laillisuus ja päätösvaltaisuus</li> <li>Hyväksytään kokouksen työjärjestys</li> <li>Vahvistetaan toimintasuunnitelma sekä tulo- ja menoarvio</li> <li>Valitaan hallituksen puheenjohtaja, varapuheenjohtaja, sihteeri, taloudenhoitaja ja muut jäsenet</li> <li>Valitaan yksi (1) toiminnantarkastaja ja yksi (1) varatoiminnantarkastaja</li> <li>Käsitellään muut kokouskutsussa mainitut asiat</li> </ol> <p>Yhdistyksen syyskokouksessa käsitellään seuraavat asiat:</p> <ol> <li>Kokouksen avaus</li> <li>Valitaan kokouksen puheenjohtaja, sihteeri, kaksi (2) pöytäkirjantarkastajaa ja tarvittaessa kaksi (2) ääntenlaskijaa </li> <li>Todetaan kokouksen laillisuus ja päätösvaltaisuus</li> <li>Hyväksytään kokouksen työjärjestys</li> <li>Esitetään tilinpäätös, vuosikertomus ja toiminnantarkastajan lausunto</li> <li>Päätetään tilinpäätöksen vahvistamisesta ja vastuuvapauden myöntämisestä hallitukselle ja muille vastuuvelvollisille</li> <li>Käsitellään muut kokouskutsussa mainitut asiat</li> </ol> <h4>16§ Yhdistyksen sääntöjen muuttaminen</h4> <p>Yhdistyksen sääntöjä voidaan muuttaa yhdistyksen kokouksessa, jos muutoksesta on mainittu kokouskutsussa ja jos muutosta kannattaa vähintään 3/4 äänestyksessä annetuissa äänistä. </p> <h4>17§ Yhdistyksen purkaminen</h4> <p>Päätös yhdistyksen purkamisesta on tehtävä kahdessa (2) peräkkäisessä vähintään yhden (1) kuukauden väliajalla pidetyssä yhdistyksen kokouksessa, jolloin ehdotuksen kummassakin kokouksessa on saavutettava 3/4 äänten enemmistö annetuista äänistä käydäkseen kokouksen päätöksestä. </p> <h4>18§ Varojen käyttö yhdistyksen purkautuessa</h4> <p>Yhdistyksen purkautuessa tai tullessa lakkautetuksi luovutetaan yhdistyksen varat ja omaisuus Turun yliopistolle käytettäväksi luonnontieteiden ja tekniikan tiedekunnan hyväksi. </p> <h4>19§</h4> <p>Yhdistyksen toiminnassa noudatetaan voimassa olevia yhdistyslain säännöksiä.</p> <h4>20§</h4> <p>Nämä säännöt astuvat voimaan, kun ne ovat tulleet yhdistysrekisteriin merkityksi.</p> </div> </div> </div> ); } } export default Saannot; <file_sep>/scripts/docker-build.sh #!/bin/bash . ./scripts/utils.sh # TAG= build() { local name="${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}" local latest="${DOCKER_IMAGE_NAME}:latest" echo "building image ${name}" # Run docker with the provided arguments docker build -t "${name}" . docker tag ${name} ${latest} } build <file_sep>/src/client/components/Rekry/Kiitos.js import React, { Component } from 'react' import styles from './Rekry.css'; class Kiitos extends Component { componentDidMount() { } render() { return ( <div className={"container-fluid " + styles.container}> <div className={"row " + styles.banner}></div> <div className={"row justify-content-sm-center " + styles.content}> <div className={"col-sm-6 text-center justify-content-center " + styles.form_canvas}> <img src="/assets/images/rekrykiitos.jpg" className={"img-fluid " + styles.kiitoskuva}/> <br/> <h1>Kiitos ilmoittautumisesta!</h1><br/> <h3>Otamme yhteyttä HybridiSpeksiin 2018 valittuihin lähitulevaisuudessa!</h3> </div> </div> </div> ) } } export default Kiitos<file_sep>/src/client/reducers/bookingReducer.js import { actions } from 'actions/bookingActions'; const initialState = { prices: { normalPrice: 16, discountPrice: 14, supportPrice: 25, }, shows: [], selectedShow: { id: '', limit: 135, nameLong: '', nameShort: '', date: '', }, bookings: [], selectedBooking: { id: '', normalCount: 0, discountCount: 0, specialPriceCount: 0, specialPrice: 25.00, showId: '', paid: false, additionalInfo: '', paymentMethodCode: 100, ContactInfo: { fname: '', lname: '', email: '', pnumber: '', }, }, searchTerm: '', paymentMethods: [], ticketSaleOpen: false, ticketSaleMessage: '', }; const bookingManagement = (state = initialState, action) => { switch (action.type) { case actions.RECEIVE_SHOWS: return { ...state, shows: [...action.shows], }; case actions.RECEIVE_BOOKINGS: return { ...state, bookings: [...action.bookings], }; case actions.SELECT_SHOW: return { ...state, selectedShow: { ...action.show }, }; case actions.SELECT_BOOKING: return { ...state, selectedBooking: { ...action.booking }, }; case actions.CLEAR_SELECTED_SHOW: return { ...state, selectedShow: initialState.selectedShow, }; case actions.CLEAR_SELECTED_BOOKING: return { ...state, selectedBooking: initialState.selectedBooking, }; case actions.RECEIVE_PAYMENT_METHODS: return { ...state, paymentMethods: [...action.paymentMethods], }; case actions.RECEIVE_TICKETSALEOPEN: return { ...state, ticketSaleOpen: action.ticketSaleOpen, }; case actions.RECEIVE_TICKETSALEMESSAGE: return { ...state, ticketSaleMessage: action.ticketSaleMessage, }; case actions.HANDLE_SEARCH: return { ...state, searchTerm: action.searchTerm, }; default: return state; } }; export default bookingManagement; <file_sep>/models/event.js module.exports = (sequelize, DataTypes) => { const Event = sequelize.define('Event', { name: DataTypes.STRING, limit: DataTypes.INTEGER, date: DataTypes.DATE, registrationOpen: DataTypes.BOOLEAN, }, {}); Event.associate = function (models) { }; return Event; }; <file_sep>/src/client/components/Admin/Auth/Login.test.js import React from 'react'; import { shallow, mount, render } from 'enzyme'; import Login from './Login'; describe('Login Component', () => { const loginWrapper = mount(<Login />); it('should render withouth crashing', () => { expect(loginWrapper.exists(<form name="login" />)).toBe(true); }); describe('State change', () => { it('should respond to change event and change the state of the Login Component', () => { loginWrapper .find('#emailInput') .simulate('change', { target: { name: 'email', value: '<EMAIL>' } }); loginWrapper .find('#passwordInput') .simulate('change', { target: { name: 'password', value: '<PASSWORD>' } }); expect(loginWrapper.state('email')).toEqual('<EMAIL>'); expect(loginWrapper.state('password')).toEqual('<PASSWORD>'); }); it('should change form when selecting Hae tunnusta', () => { loginWrapper.find('#haeTunnustaButton').simulate('click'); expect(loginWrapper.exists(<form name="signup" />)).toBe(true); }); }); }); <file_sep>/src/client/components/Admin/Auth/Loginform.js import React from 'react'; import PropTypes from 'prop-types'; const Loginform = ({ handleSubmit, handleChange, messages, email, password, }) => ( <div className="container"> <div className="row justify-content-center"> <div className="col-sm-auto"> <h3>Kirjaudu admin-paneeliin</h3> </div> </div> <div className="row justify-content-center"> <form onSubmit={handleSubmit} className="col-sm-5" name="login"> <div className="form-group"> <label htmlFor="emailInput">Sähköposti</label> <input autoFocus="true" name="email" type="email" onChange={handleChange} value={email} className="form-control" id="emailInput" placeholder="Sähköpostiosoite" /> </div> <div className="form-group"> <label htmlFor="passwordInput">Salasana</label> <input name="password" type="password" onChange={handleChange} value={password} className="form-control" id="passwordInput" placeholder="<PASSWORD>" /> </div> <button id="kirjauduButton" className="btn btn-default" type="submit"> Kirjaudu </button> <button id="haeTunnustaButton" inputMode="numeric" type="button" className="btn btn-default" onClick={handleChange} name="authState" value={1} > Hae tunnusta </button> </form> </div> <div className="row justify-content-center"> <div className="col-sm-5">{messages}</div> </div> </div> ); export default Loginform; Loginform.propTypes = { handleChange: PropTypes.func, handleSubmit: PropTypes.func, messages: PropTypes.object, email: PropTypes.string, password: PropTypes.string, }; <file_sep>/src/utils/mailtemplates/cash_ticket.js const bookingUtils = require('../bookingUtils'); /** * Cash ticket template * @return ticket: String * */ function cashTicket(booking) { const { fname, lname, } = booking.get('ContactInfo'); const show = booking.get('Show'); const tag = booking.get('tag'); const html = ` <h1>Kiitos varauksesta!</h1> <hr/> <p>Varauksen tiedot:</p> <p> ${fname} ${lname}</p> <p>Esitys: ${show.nameLong}</p> <p>Lippuja yhteensä ${bookingUtils.getTotalCount(booking)} kpl </p> <p>Hinta: ${bookingUtils.countPrice(booking)} €</p> <p><b>VARAUSTUNNUS: ${tag}</b> <br/>Varaustunnus toimii lippunasi näytökseen. Mikäli varaus sisältää opiskelijahintaisia lippuja, teidän on esitettävä voimassaoleva opiskelijakorttinne esitykseen saavuttaessa.</p> <p>Mikäli teillä herää kysyttävää lippujen suhteen, ottakaa rohkeasti yhteyttä osoitteeseen <a href="mailto:<EMAIL>"><EMAIL></a></p> <p><i>Tervetuloa speksiin!</i></p> `; return html; } module.exports.cashTicket = cashTicket; <file_sep>/src/utils/mailer.js const nodemailer = require('nodemailer'); const mg = require('nodemailer-mailgun-transport'); const bookingService = require('../services/bookingService'); const cashTicket = require('./mailtemplates/cash_ticket').cashTicket; const enrollmentConfirmation = require('./mailtemplates/enrollment_confirmation').confirmationMail; const auth = { auth: { api_key: process.env.MAILGUN_API_KEY, domain: process.env.DOMAIN, }, }; const nodemailerMailgun = nodemailer.createTransport(mg(auth)); module.exports = { /** * Send ticket * @return promise() */ sendTicket: async (bookingId) => { try { const booking = await bookingService.findById(bookingId); await nodemailerMailgun.sendMail({ from: '<EMAIL>', to: booking.get('ContactInfo').get('email'), subject: 'Varausvahvistus', html: cashTicket(booking), }); } catch (err) { console.log(err); throw new Error('3'); } }, sendVujuConfirmation: async (email) => { try { await nodemailerMailgun.sendMail({ from: '<EMAIL>', to: email, subject: 'HybridiSpeksin vuosijuhlat', html: enrollmentConfirmation(), }); } catch (err) { console.log(err); throw new Error('Vahvistussähköpostia ei voitu lähettää. Tarkistathan sähköpostiosoitteesi'); } }, }; <file_sep>/dev/back.Dockerfile FROM node:9 RUN mkdir /app WORKDIR /app RUN npm install -g nodemon CMD npm run server <file_sep>/src/api/shows/bookingController.js const bookingService = require('../../services/bookingService'); const mailer = require('../../utils/mailer'); const validator = require('../../utils/validation'); const paymentFactory = require('../../utils/payments'); const Ohjaustieto = require('../../schema/ohjaustieto-model'); const validateBooking = (booking) => { const { fname, lname, email, } = booking.ContactInfo; const { normalCount, discountCount, specialPriceCount, specialPrice, showId, } = booking; if (validator.isEmptyOrNull(fname)) { throw new Error('Etunimi on pakollinen tieto'); } if (validator.isEmptyOrNull(lname)) { throw new Error('Sukunimi on pakollinen tieto'); } if (validator.isEmptyOrNull(email)) { throw new Error('Sähköposti on pakollinen tieto'); } if (!validator.isValidEmail(email)) { throw new Error('Virheellinen sähköpostiosoite'); } if (!validator.isNumber(normalCount) || !validator.isNumber(discountCount) || !validator.isNumber(specialPriceCount) || !validator.isNumber(specialPrice)) { throw new Error('Lippumäärän tulee olla numero'); } if (normalCount + discountCount + specialPriceCount < 1) { throw new Error('Varauksessa tulee olla vähintään yksi lippu'); } if (validator.isEmptyOrNull(showId)) { throw new Error('Varaukselle ei ole valittu esitystä'); } }; module.exports = { getBookingById: async (req, res) => { try { const booking = await bookingService.findById(req.params.bookingId); res.json({ success: true, data: booking }); } catch (e) { res.json({ success: false, message: e.message }); } }, createBooking: async (req, res) => { const { showId, normalCount, discountCount, specialPriceCount, specialPrice, paid, paymentMethodId, additionalInfo, sendConfirmationMail, } = req.body; const { fname, lname, email, pnumber, } = req.body.ContactInfo; try { validateBooking(req.body); const booking = await bookingService.createBooking( showId, fname, lname, email, pnumber, normalCount, discountCount, specialPriceCount, specialPrice, paid, paymentMethodId, additionalInfo, ); if (sendConfirmationMail) { await mailer.sendTicket(booking.get('id')); } res.json({ success: true, data: booking }); } catch (e) { res.json({ success: false, message: e.message }); } }, updateBooking: async (req, res) => { const { showId, normalCount, discountCount, specialPriceCount, specialPrice, additionalInfo, paymentMethodId, paid, } = req.body; const { fname, lname, email, pnumber, } = req.body.ContactInfo; const id = req.params.bookingId; try { validateBooking(req.body); const booking = bookingService.updateBooking( id, showId, fname, lname, email, pnumber, normalCount, discountCount, specialPriceCount, specialPrice, additionalInfo, paid, paymentMethodId, ); res.json({ success: true, data: booking }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, createPublicBooking: async (req, res) => { const { showId, normalCount, discountCount, specialPriceCount, additionalInfo, } = req.body; const { fname, lname, email, pnumber, } = req.body.ContactInfo; try { const salesOpen = await Ohjaustieto.findOne({ key: 'lipunmyyntiAuki' }); if (!salesOpen.truefalse) { throw new Error('Lipunmyynti on suljettu'); } const body = { ...req.body }; validateBooking(body); const paymentMethod = await bookingService.getPaymentMethodByCode(102); const booking = await bookingService.createBooking( showId, fname, lname, email, pnumber, normalCount, discountCount, specialPriceCount, 25, // specialPrice false, // paid paymentMethod.get('id'), additionalInfo, ); const payment = await paymentFactory.createPayment(booking.get('id')); res.json({ success: true, data: payment }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, deleteBooking: async (req, res) => { const { bookingId } = req.params; try { await bookingService.deleteBooking(bookingId); res.json({ success: true }); } catch (e) { console.log(e); res.status(500).send('Palvelimella tapahtui virhe'); } }, getBookingsByShowId: async (req, res) => { const showId = req.params.showId; try { const bookings = await bookingService.getBookingsByShowId(showId); res.status(200).send(bookings); } catch (e) { console.log(e); res.status(500).send('Palvelimella tapahtui virhe'); } }, getAllBookings: async (req, res) => { try { const bookings = await bookingService.getAllBookings(); res.json({ success: true, data: bookings }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, handleSuccessfulPayment: async (req, res) => { const bookingId = req.query.ORDER_NUMBER; const paymentMethodCode = req.query.METHOD; try { paymentFactory.isValidResponse(req); const booking = await bookingService.findById(bookingId); const paymentMethod = await bookingService.getPaymentMethodByCode(paymentMethodCode); booking.set('paid', true); booking.set('paymentMethodId', paymentMethod.get('id')); await booking.save(); await mailer.sendTicket(bookingId); res.redirect('/speksi2019/vahvistus/' + booking.get('id')); } catch (e) { res.redirect('/speksi2019/virhe/' + e.message); } }, handleNotifyPayment: async (req, res) => { const bookingId = req.query.ORDER_NUMBER; const paymentMethodCode = req.query.METHOD; try { paymentFactory.isValidResponse(req); const booking = await bookingService.findById(bookingId); if (booking.get('paid')) { throw new Error('Payment already handled, no action required'); } const paymentMethod = await bookingService.getPaymentMethodByCode(paymentMethodCode); booking.set('paid', true); booking.set('paymentMethodId', paymentMethod.get('id')); await booking.save(); await mailer.sendTicket(bookingId); res.redirect('/speksi2019/vahvistus/' + booking.get('id')); } catch (e) { console.log(e); res.redirect('/speksi2019/virhe/' + e.message); } }, handleFailingPayment: async (req, res) => { const bookingId = req.query.ORDER_NUMBER; try { await bookingService.deleteBooking(bookingId); res.redirect('/speksi2019/virhe/1'); } catch (e) { console.log(e); } }, getPaymentMethods: async (req, res) => { try { const methods = await bookingService.getPaymentMethods(); res.json({ success: true, data: methods }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, sendConfirmationMail: async (req, res) => { try { const { bookingId } = req.params; await mailer.sendTicket(bookingId); res.json({ success: true }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, redeem: async (req, res) => { try { const { bookingId } = req.params; const booking = await bookingService.redeem(bookingId); res.json({ success: true, data: booking }); } catch (e) { res.json({ success: false, message: e.message }); } }, }; <file_sep>/src/client/components/Admin/BookingManagement/BookingsList.js import React from 'react'; import cuid from 'cuid'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import styles from './BookingsList.css'; import form from '../Form.css'; import * as actions from 'actions/bookingActions'; const Booking = ({ booking, handleClick, selected }) => { const { fname, lname, email, } = booking.ContactInfo; const { paid, redeemed, tag } = booking; const countBookings = (_booking) => { const { normalCount, discountCount, specialPriceCount } = _booking; return normalCount + discountCount + specialPriceCount; }; return ( <button className={`${styles.bookingRow} ${selected ? styles.selected : ''}`} onClick={() => handleClick(booking)}> <span className={styles.name}>{fname} {lname}</span> <span className={styles.email}>{email}</span> <span className={styles.paid}>{paid ? <i className="fa fa-check" /> : ''}</span> <span className={styles.redeemed}>{redeemed ? <i className="fa fa-check" /> : ''}</span> <span className={styles.tag}>{tag}</span> <span className={styles.bookingCount}>{countBookings(booking)}</span> </button> ); }; Booking.propTypes = { booking: PropTypes.object, handleClick: PropTypes.func, selected: PropTypes.bool, }; const BookingsList = ({ bookings, selectBooking, selectedBooking, handleSearch, searchTerm, }) => { const handleClick = (booking) => { selectBooking(booking); }; const handleFilter = (booking) => { const { fname, lname, email, pnumber, } = booking.ContactInfo; if (searchTerm === '') { return true; } if (fname.toLowerCase().search(searchTerm.toLowerCase()) > -1) { return true; } if (lname.toLowerCase().search(searchTerm.toLowerCase()) > -1) { return true; } if (email.toLowerCase().search(searchTerm.toLowerCase()) > -1) { return true; } if (pnumber.toLowerCase().search(searchTerm.toLowerCase()) > -1) { return true; } if (booking.tag.toLowerCase().search(searchTerm.toLowerCase()) > -1) { return true; } return false; }; if (!bookings) { return null; } return ( <div className={styles.container}> <div className={styles.headerContainer}> <div className={styles.header}> <h2>Varaukset</h2> </div> <div className={styles.search}> <div className={form.formRow}> <div className={form.inputGroup}> <input type="text" className={form.input} placeholder="Hae" value={searchTerm} onChange={e => handleSearch(e.target.value)} /> </div> </div> </div> </div> <div className={styles.rows}> <div className={styles.bookingRow}> <span className={styles.name}>Nimi</span> <span className={styles.email}>Sähköposti</span> <span className={styles.paid}>Maksettu</span> <span className={styles.redeemed}>Lunastettu</span> <span className={styles.tag}>Tunnus</span> <span className={styles.bookingCount}>Liput</span> </div> {bookings.filter(booking => handleFilter(booking)).map((booking) => { return <Booking key={cuid()} booking={booking} handleClick={handleClick} selected={booking.id === selectedBooking.id} />; }) } </div> </div> ); }; BookingsList.propTypes = { bookings: PropTypes.array, selectBooking: PropTypes.func, selectedBooking: PropTypes.object, searchTerm: PropTypes.string, handleSearch: PropTypes.func, }; const mapStateToProps = state => ({ bookings: state.bookingManagement.bookings, selectedBooking: state.bookingManagement.selectedBooking, searchTerm: state.bookingManagement.searchTerm, }); const mapDispatchToProps = dispatch => ({ selectBooking: booking => dispatch(actions.selectBooking(booking)), handleSearch: searchTerm => dispatch(actions.handleSearch(searchTerm)), }); export default connect(mapStateToProps, mapDispatchToProps)(BookingsList); <file_sep>/src/client/components/Muutspeksit/SpeksiCard.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './SpeksiCard.css'; const SpeksiRow = ({ speksi }) => ( <div className={styles.cardContainer}> <div className={styles.card}> <div className={styles.tdk}> {speksi.tdk} </div> <div className={styles.name}> <h3 dangerouslySetInnerHTML={{ __html: speksi.name }} /> </div> <div> <img src={speksi.imageUrl} className={styles.linkimage} /> </div> <a href={speksi.url} className={styles.linkOverlay} /> </div> </div> ); SpeksiRow.propTypes = { speksi: PropTypes.object, }; export default SpeksiRow; <file_sep>/src/utils/mailtemplates/enrollment_confirmation.js function confirmationMail() { const html = ` <h1>Kiitos ilmoittautumisesta!</h1> <hr/> <p>Olet ilmoittautunut HybridiSpeksin vuosijuhliin lauantaina 4.5.2019. Juhlallisuudet alkavat klo 16.00 cocktailtilaisuudella Mercatorilla (Rehtorinpellonkatu 3, 20500 Turku). Cocktailtilaisuuden jälkeen siirrymme yhteiskuljetuksin klo 18.00 alkavaan iltajuhlaan Panimoravintola Kouluun (Eerikinkatu 18, 20100 Turku). Iltajuhlan päätyttyä juhlat jatkuvat salaisessa jatkopaikassa, jonne siirrytään yhteisin bussikuljetuksin. Vuosijuhlien silliaamiainen vietetään TYYn saunalla sunnuntaina 5.5. klo 11.00 alkaen. </p> <p>Juhlien illalliskortin hinta on 80 €, ja hintaan sisältyy cocktailtilaisuus, iltajuhla sekä jatkot kuljetuksineen. Alkoholittoman illalliskortin hinta on 70 €. Kannatusillalliskortin hinta on 100 €. Juhlien silliaamiaisen hinta on 5 €.</p> <p>Illalliskortit maksetaan HybridiSpeksi ry:n tilille (FI64 5711 1320 1361 76) eräpäivään 3.5.2019 mennessä. Kirjoitathan viestikenttään “HybridiSpeksin vuosijuhlat + oma nimi”.</p> <p>Juhlan pukukoodina on juhlapuku tai tumma puku, sekä akateemiset kunniamerkit.</p> `; return html; } module.exports.confirmationMail = confirmationMail; <file_sep>/src/services/eventService.js const uuid = require('uuid/v4'); const Event = require('../../models').Event; module.exports = { createEvent: async (name, limit, date, registrationOpen) => { try { const event = await Event.create({ id: uuid(), name, limit, date, registrationOpen, }); return event; } catch (e) { console.log(e); throw e; } }, getEvents: async () => { try { const events = await Event.findAll(); return events; } catch (e) { console.log(e); throw e; } }, deleteEvent: async (id) => { try { await Event.destroy({ where: { id } }); } catch (e) { console.log(e); throw e; } }, updateEvent: async (id, name, limit, date, registrationOpen) => { try { const event = await Event.findOne({ where: { id } }); event.set('name', name); event.set('limit', limit); event.set('date', date); event.set('registrationOpen', registrationOpen); await event.save(); return event; } catch (e) { console.log(e); throw e; } }, getEventById: async (id) => { try { const event = await Event.findOne({ where: { id } }); return event; } catch (e) { console.log(e); throw e; } }, openRegistration: async (id) => { try { const event = await Event.findOne({ where: { id } }); event.set('registrationOpen', true); await event.save(); return event; } catch (e) { console.log(e); throw e; } }, closeRegistration: async (id) => { try { const event = await Event.findOne({ where: { id } }); event.set('registrationOpen', false); await event.save(); return event; } catch (e) { console.log(e); throw e; } }, }; <file_sep>/dev/front.Dockerfile FROM node:9.5 RUN mkdir /app WORKDIR /app RUN npm install -g webpack-dev-server CMD npm run dev <file_sep>/src/api/events/eventController.js const eventService = require('../../services/eventService'); const validator = require('../../utils/validation'); const validateEvent = ({ name, limit, date }) => { if (validator.isEmptyOrNull(name)) { throw new Error('Tapahtumalla on oltava nimi'); } if (!validator.isNumber(limit)) { throw new Error('Rajan on oltava numero'); } }; module.exports = { createEvent: async (req, res) => { const { name, limit, date, registrationOpen, } = req.body; try { validateEvent(req.body); const event = await eventService.createEvent(name, limit, date, registrationOpen); res.json({ success: true, data: event }); } catch (e) { res.json({ success: false, message: e.message }); } }, getEvents: async (req, res) => { try { const events = await eventService.getEvents(); res.json({ success: true, data: events }); } catch (e) { res.json({ success: false, message: e.message }); } }, deleteEvent: async (req, res) => { const { eventId } = req.params; try { await eventService.deleteEvent(eventId); res.json({ success: true }); } catch (e) { res.json({ success: false, message: e.message }); } }, updateEvent: async (req, res) => { const { eventId } = req.params; const { name, limit, date, registrationOpen, } = req.body; try { validateEvent(req.body); const event = await eventService.updateEvent(eventId, name, limit, date, registrationOpen); res.json({ success: true, data: event }); } catch (e) { res.json({ success: false, message: e.message }); } }, getEventById: async (req, res) => { const { eventId } = req.params; try { const event = await eventService.getEventById(eventId); res.json({ success: true, data: event }); } catch (e) { res.json({ success: false, message: e.message }); } }, openRegistration: async (req, res) => { const { eventId } = req.params; try { const event = await eventService.openRegistration(eventId); res.json({ success: true, data: event }); } catch (e) { res.json({ success: false, message: e.message }); } }, closeRegistration: async (req, res) => { const { eventId } = req.params; try { const event = await eventService.closeRegistration(eventId); res.json({ success: true, data: event }); } catch (e) { res.json({ success: false, message: e.message }); } }, }; <file_sep>/src/client/components/Speksi2018/Speksi2018.js import React, { Component } from 'react'; import UusiVaraus from './UusiVaraus'; import Esitysvalinta from './Esitysvalinta'; import ajax from './../../Utils/Ajax'; import styles from './Speksi2018.css'; const MESSAGE_SUCCESS = 'success'; const MESSAGE_WARNING = 'warning'; const MESSAGE_ERROR = 'error'; class Speksi2018 extends Component { constructor(props) { super(props); this.state = { esitykset: [], valittuEsitys: {}, fname: '', sname: '', email: '', pnumber: '', ncount: 0, scount: 0, ocount: 0, nprice: '16', sprice: '14', oprice: '25', price: '0', lisatiedot: '', ilmottu: false, lipunmyyntiAuki: false, lipunmyyntiMessage: '', messages: [], warnings: [], errors: [], openModalError: '', }; // this.valitseEsitys = this.valitseEsitys.bind(this); this.toggleUusiVarausModal = this.toggleUusiVarausModal.bind(this); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.addMessage = this.addMessage.bind(this); this.countPrice = this.countPrice.bind(this); } componentDidMount() { $(window).scrollTop(0); ajax .sendGet('/getShowsWithCounts') .then((_data) => { this.setState({ esitykset: _data.data }); }) .catch((err) => { console.log(err); }); ajax .sendGet('/lipunmyyntiAuki') .then((tag) => { this.setState({ lipunmyyntiAuki: tag.data[0].truefalse }); }) .catch((err) => { console.log(err); }); ajax .sendGet('/lipunmyyntiMessage') .then((tag) => { this.setState({ lipunmyyntiMessage: tag.data[0] }); }) .catch((err) => { console.log(err); }); const tag = document.createElement('script'); tag.id = 'iframe-demo'; tag.src = 'https://www.youtube.com/iframe_api'; const firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } toggleUusiVarausModal(esitys, tilaa) { if (!this.state.lipunmyyntiAuki) { this.setState({ openModalError: 'Lipunmyynti ei ole enää auki.' }, () => { $('#errorModal').modal('show'); }); } else if (tilaa === 'Loppuunmyyty') { this.setState({ openModalError: 'Valittu esitys on täynnä.' }, () => { $('#errorModal').modal('show'); }); } else if (new Date() > new Date(esitys.date)) { this.setState({ openModalError: 'Esitykseen ei voi varata enää lippuja.' }, () => { $('#errorModal').modal('show'); }); } else { this.setState({ valittuEsitys: esitys }, () => { $('#uusiVarausModal').modal('show'); }); } } handleChange(e) { const value = e.target.value; this.setState({ messages: [], warnings: [], errors: [], }); if (e.target.name === 'ncount' || e.target.name === 'scount' || e.target.name === 'ocount') { this.setState({ [e.target.name]: value }, () => { this.countPrice(); }); } else if (e.target.name === 'esitys') { this.state.esitykset.map((esitys) => { if (e.target.value === esitys._id) { this.valitseEsitys(esitys); } }); } else { this.setState({ [e.target.name]: value }); } } countPrice() { const sum = this.state.ncount * this.state.nprice + this.state.scount * this.state.sprice + this.state.ocount * this.state.oprice; this.setState({ price: sum }); } handleSubmit(e) { e.preventDefault(); const url = '/varaus/createPayment'; const ticketSum = parseInt(this.state.scount) + parseInt(this.state.ncount) + parseInt(this.state.ocount); console.log(ticketSum); if (ticketSum > 7) { this.addMessage( MESSAGE_WARNING, 'HUOM!', 'Vähintään 8 hengen ryhmätilauksella lipun hinta on vain 12 €/hlö ja tulee hoitaa lähettämällä sähköpostia osoitteeseen <EMAIL>.', ); } else { ajax .sendPost(url, { fname: this.state.fname, sname: this.state.sname, email: this.state.email, pnumber: this.state.pnumber, scount: this.state.scount, ncount: this.state.ncount, ocount: this.state.ocount, esitysId: this.state.valittuEsitys._id, additional: this.state.lisatiedot, }) .then((data) => { console.log(data.data); if (data.success) { this.setState({ ilmottu: true }); location.replace(data.data.url); this.addMessage(MESSAGE_SUCCESS, 'Siirrytään maksupalveluun...'); } else { this.setState({ ilmottu: false }); this.addMessage(MESSAGE_WARNING, data.data); } }) .catch((err) => { console.log(err); this.setState({ ilmottu: false }); this.addMessage( MESSAGE_ERROR, 'Virhe!', 'Palvelimella tapahtui virhe. Yritä myöhemmin uudelleen.', ); }); } } // Add different kinds of error or warning messages addMessage(type, newHeader, newText) { this.setState( { messages: [], warnings: [], errors: [], }, () => { if (type === MESSAGE_WARNING) { const newWarnings = this.state.warnings; newWarnings.push({ header: newHeader, text: newText }); this.setState({ warnings: newWarnings }); } else if (type === MESSAGE_ERROR) { const newErrors = this.state.errors; newErrors.push({ header: newHeader, text: newText }); this.setState({ errors: newErrors }); } else if (type === MESSAGE_SUCCESS) { const newMessages = this.state.messages; newMessages.push({ header: newHeader, text: newText }); this.setState({ messages: newMessages }); } }, ); } render() { return ( <div className={'container-fluid ' + styles.container}> <div className={'row align-items-top justify-content-center ' + styles.header}> <div className="col-md-6"> <h2 className="">Speksi 2018</h2> <p> Villin lännen kuumimmalla aavikolla on pieni kylä keskellä preeriaa. Tuomari Martin pitää yllä järjestystä lakikirjalla ja hirttosilmukalla, samalla ryysyistä rikkauksiin kohonnut Alexandra hallitsee kyläläisten kukkaroita ja himoja. Kaikkien rakastama pappi, <NAME>, tekee parhaansa pitääkseen harmonian näiden kahden ja asukkaiden välillä. Tasapaino kuitenkin järkkyy, kun sen keskelle ilmestyy raakalaismaisen rikollisliigan johtajatar suojaa etsien. </p> <p> <NAME><br /> HybridiSpeksi 2018<br /> Ensi-ilta 27.3.<br /> @Manilla </p> </div> <div className="col-12 col-sm-6 col-lg-6 col-xl-3"> <img src="/assets/images/logo_lapinak_valk.png" /> </div> </div> <div className={'row align-items-top justify-content-center ' + styles.lipunmyyntiMessage}> <div className="col-9 text-center"> {this.state.lipunmyyntiMessage.truefalse ? ( <p className={styles.lipunmyyntiMessageText}>{this.state.lipunmyyntiMessage.name}</p> ) : ( '' )} </div> </div> <div className={'row align-items-top justify-content-center ' + styles.content}> <div className="col-12 col-md-10 col-lg-5 col-xl-5 flex-last"> <h2 className={styles.textheader}>Ohjeet lipun ostamiseen</h2> <ol> <li>Valitse näytös ja klikkaa sitä</li> <li>Täytä tiedot</li> <li> Siirry maksamaan ja valitse oma nettipankkisi (maksutapahtuman käsittelee Paytrail, lisätietoa alempana) </li> <li>Seuraa nettipankin ohjeita maksaaksesi</li> <li> Saat sähköpostiisi varausnumeron, jota näyttämällä pääset katsomaan HybridiSpeksiä 2018! </li> <li> Ongelmatilanteissa ota yhteyttä osoitteeseen{' '} <a className={styles.externallink} href="mailto:<EMAIL>"> lipunmyynti<EMAIL> </a> </li> </ol> <p> Vähintään 8 hengen ryhmätilaukset voi lähettää sähköpostilla osoitteeseen{' '} <a className={styles.externallink} href="mailto:<EMAIL>"> <EMAIL> </a>. Ryhmätilauksen alennushinta 12 €/hlö. </p> <p> <strong> Huomioithan, että esitystä ei suositella alle 12-vuotiaille. Esityksessä on kovia ääniä ja vilkkuvia valoja. </strong> </p> <h2 className={styles.textheader}>Hinnasto</h2> <table className={styles.hinnasto}> <tbody> <tr> <td>Normaali</td> <td>16 €</td> </tr> <tr> <td>Opiskelija</td> <td>14 €</td> </tr> <tr> <td>Kannatus</td> <td>25 €</td> </tr> </tbody> </table> </div> <div className={ 'col-12 col-md-10 col-lg-6 col-xl-5 justify-items-center ' + styles.esitykset } > <h2 className={styles.textheader}>Esitykset Manilla-teatterilla:</h2> <Esitysvalinta esitykset={this.state.esitykset} toggleUusiVarausModal={this.toggleUusiVarausModal} /> </div> </div> <div className={'row align-items-top justify-content-center ' + styles.videot}> <div className="col-sm-11 col-md-5"> <div className="videowrapper"> <h2 className={styles.textheader}>Älä ammu ohi -teaser</h2> <iframe id="youtubeplayer" src="https://www.youtube.com/embed/6HXoDboQjbU?enablejsapi=1&rel=0" width="100%" height="360" frameBorder="0" allowFullScreen="allowFullScreen" /> </div> </div> <div className="col-sm-11 col-md-5"> <div className="videowrapper"> <h2 className={styles.textheader}>Älä ammu ohi -trailer</h2> <iframe id="youtubeplayer" src="https://www.youtube.com/embed/vhLvRVZabTA?enablejsapi=1&rel=0" width="100%" height="360" frameBorder="0" allowFullScreen="allowFullScreen" /> </div> </div> </div> <div className={'row justify-content-center ' + styles.hr}> <div className="col-8"> <hr /> </div> </div> <div className={'row align-items-top justify-content-center ' + styles.paytrail}> <div className="col-12 col-md-10 col-lg-8"> <h4>Maksupalvelutarjoaja</h4> <p> Maksunvälityspalvelun toteuttajana ja maksupalveluntarjoajana toimii Paytrail Oyj (2122839-7) yhteistyössä suomalaisten pankkien ja luottolaitosten kanssa. Paytrail Oyj näkyy maksun saajana tiliotteella tai korttilaskulla ja välittää maksun kauppiaalle. Paytrail Oyj:llä on maksulaitoksen toimilupa. Reklamaatiotapauksissa pyydämme ottamaan ensisijaisesti yhteyttä tuotteen toimittajaan. </p> <p> Paytrail Oyj, y-tunnus: 2122839-7<br /> Innova 2<br /> Lutakonaukio 7<br /> 40100 Jyväskylä<br /> Puhelin: 0207 181830<br /> www.paytrail.com </p> <h4>Verkkopankit</h4> <p> Verkkopankkimaksamiseen liittyvän maksunvälityspalvelun toteuttaa Paytrail Oyj (2122839-7) yhteistyössä suomalaisten pankkien ja luottolaitosten kanssa. Käyttäjän kannalta palvelu toimii aivan kuten perinteinen verkkomaksaminenkin. </p> </div> </div> <UusiVaraus emptyFields={this.emptyFields} handleChange={this.handleChange} handleSubmit={this.handleSubmit} fname={this.state.fname} sname={this.state.sname} email={this.state.email} pnumber={this.state.pnumber} scount={this.state.scount} ncount={this.state.ncount} ocount={this.state.ocount} price={this.state.price} lisatiedot={this.state.lisatiedot} ilmottu={this.state.ilmottu} valittuEsitys={this.state.valittuEsitys} esitykset={this.state.esitykset} /> <div className="modal fade" id="errorModal" tabIndex="-1" role="dialog" aria-labelledby="errorModalLabel" aria-hidden="true" > <div className="modal-dialog" role="document"> <div className={'modal-content ' + styles.formContent}> {' '} {/* TÄHÄN MUOTOILUT KOKO MODALIIN */} <div className={'modal-header ' + styles.formBorder}> <h5 className="modal-title" id="errorModalLabel"> {this.state.openModalError} </h5> <button type="button" className={'close btn btn-inverse ' + styles.formClose} data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div className={'modal-footer justify-content-center ' + styles.formBorder}> <button type="button" className={'btn btn-dark ' + styles.formButton + ' ' + styles.formButtonClose} data-dismiss="modal" aria-label="Close" > Sulje ikkuna </button> </div> </div> </div> </div> </div> ); } } export default Speksi2018; <file_sep>/src/client/actions/eventActions.js import * as messageActions from './messageActions'; import * as loaderActions from './loaderActions'; import ajax from '../Utils/Ajax'; export const actions = { RECEIVE_ENROLLMENTS: 'RECEIVE_ENROLLMENTS', SELECT_ENROLLMENT: 'SELECT_ENROLLMENT', CLEAR_ENROLLMENT: 'CLEAR_ENROLLMENT', RECEIVE_EVENT: 'RECEIVE_EVENT', RECEIVE_EVENTS: 'RECEIVE_EVENTS', SELECT_EVENT: 'SELECT_EVENT', SET_SUBMITTED: 'SET_SUBMITTED', }; export function fetchEvent(id) { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet('/event/' + id); dispatch(loaderActions.hideLoader()); dispatch(receiveEvent(res.data)); } catch (e) { dispatch(loaderActions.hideLoader()); messageActions.addErrorMessage({ header: 'Virhe haettaessa tapahtuman tietoja' }); } }; } export function fetchEvents() { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet('/events'); dispatch(selectEvent(res.data[0])); dispatch(fetchEnrollments(res.data[0].id)); dispatch(loaderActions.hideLoader()); dispatch(receiveEvents(res.data)); } catch (e) { dispatch(loaderActions.hideLoader()); messageActions.addErrorMessage({ header: 'Virhe haettaessa tapahtuman tietoja' }); } }; } export function submitEnrollment(enrollment) { return async (dispatch) => { try { dispatch(messageActions.clearMessages()); dispatch(loaderActions.showLoader()); const res = await ajax.sendPost('/enrollment', enrollment); if (!res.success) { dispatch(messageActions.addWarningMessage({ header: res.message }, 5000)); } else { dispatch(setSubmitted()); dispatch(clearEnrollment()); dispatch(messageActions.addSuccessMessage({ header: 'Ilmoittautuminen hyväksytty. Saat vahvistussähköpostin ilmoittamaasi osoitteeseen.' }, 10000)); } dispatch(loaderActions.hideLoader()); } catch (e) { dispatch(loaderActions.hideLoader()); dispatch(messageActions.addErrorMessage({ header: 'Ilmoittautumisessa tapahtui virhe. Yritä myöhemmin uudelleen' }, 5000)); } }; } export function updateEnrollment(enrollment) { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendPut('/admin/enrollment/' + enrollment.id, enrollment); if (!res.success) { dispatch(messageActions.addWarningMessage({ header: res.message }, 5000)); } else { dispatch(clearEnrollment()); dispatch(fetchEnrollments(enrollment.eventId)); dispatch(messageActions.addSuccessMessage({ header: 'Ilmoittautumisen tiedot päivitetty' }, 3000)); dispatch(loaderActions.hideLoader()); } } catch (e) { dispatch(loaderActions.hideLoader()); dispatch(messageActions.addErrorMessage({ header: e.message })); } }; } export function deleteEnrollment(enrollment) { return async (dispatch) => { try { const res = await ajax.sendDelete('/admin/enrollment/' + enrollment.id); if (!res.success) { dispatch(messageActions.addWarningMessage({ header: res.message }, 5000)); } else { dispatch(clearEnrollment()); dispatch(fetchEnrollments(enrollment.eventId)); dispatch(messageActions.addSuccessMessage({ header: 'Ilmoittautuminen poistettu' }, 3000)); dispatch(loaderActions.hideLoader()); } } catch (e) { dispatch(loaderActions.hideLoader()); dispatch(messageActions.addErrorMessage({ header: e.message })); } }; } export function fetchEnrollments(eventId) { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet('/admin/enrollments/' + eventId); dispatch(loaderActions.hideLoader()); dispatch(receiveEnrollments(res.data)); } catch (e) { messageActions.addErrorMessage({ header: e.message }); } }; } export function selectEvent(event) { return { type: actions.SELECT_EVENT, event, }; } export function openRegistration(id) { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet('/admin/event/openRegistration/' + id); dispatch(loaderActions.hideLoader()); dispatch(fetchEvents()); dispatch(selectEvent(res.data)); } catch (e) { dispatch(loaderActions.hideLoader()); messageActions.addErrorMessage({ header: 'Virhe haettaessa tapahtuman tietoja' }); } }; } export function closeRegistration(id) { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet('/admin/event/closeRegistration/' + id); dispatch(loaderActions.hideLoader()); dispatch(fetchEvents()); dispatch(selectEvent(res.data)); } catch (e) { dispatch(loaderActions.hideLoader()); messageActions.addErrorMessage({ header: 'Virhe haettaessa tapahtuman tietoja' }); } }; } export function selectEnrollment(enrollment) { return { type: actions.SELECT_ENROLLMENT, enrollment, }; } export function clearEnrollment() { return { type: actions.CLEAR_ENROLLMENT, }; } function receiveEnrollments(enrollments) { return { type: actions.RECEIVE_ENROLLMENTS, enrollments, }; } function receiveEvent(event) { return { type: actions.RECEIVE_EVENT, event, }; } function receiveEvents(events) { return { type: actions.RECEIVE_EVENTS, events, }; } function setSubmitted() { return { type: actions.SET_SUBMITTED, }; } <file_sep>/src/utils/mailtemplates/webshop_ticket.js /** * Webshop ticket template * @return mail: String * @param user * @param booking */ function webshopTicket(name, booking) { return "TODO"; } module.exports.webshopTicket = webshopTicket;<file_sep>/src/client/components/Admin/Jasenrekisteri/Uusijasen.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Text, Radio } from '../../../Utils/Form'; import utils from '../../../Utils/Utils'; import Modal from '../../../Utils/Modal'; import ajax from '../../../Utils/Ajax'; import { addWarningMessage, addSuccessMessage, clearMessages } from '../../../actions/messageActions'; class Uusijasen extends Component { constructor(props) { super(props); this.state = { jasen: { _id: '', fname: '', sname: '', email: '', hometown: '', memberOfTyy: true, }, }; this.handleChange = this.handleChange.bind(this); this.tallennaJasen = this.tallennaJasen.bind(this); } componentWillReceiveProps(nextProps) { if (this.state.jasen._id !== nextProps.jasen._id) { const _jasen = nextProps.jasen; _jasen.hometown = ''; _jasen.memberOfTyy = true; this.setState({ jasen: _jasen }); } } tallennaJasen() { if (this.state.jasen.fname === '' || this.state.jasen.sname === '' || this.state.jasen.email === '' || this.state.jasen.hometown === '') { this.props.warningMessage({ header: 'Kaikki kentät on täytettävä' }); setTimeout(() => { this.props.clear(); }, 3000); } else { ajax.sendPut('/admin/h/jasenrekisteri', this.state.jasen) .then((data) => { console.log(data); this.props.successMessage({ header: 'Jäsen lisätty!' }); $('#uusijasen-modal').modal('hide'); }) .catch((err) => { console.log(err); }); } } handleChange(e) { let _value = e.target.value; if (e.target.name === 'memberOfTyy') { _value = utils.parseBoolean(_value); } const _jasen = this.state.jasen; _jasen[e.target.name] = _value; this.setState({ jasen: _jasen }); } render() { return ( <Modal modalTitle="Lisää uusi jäsen jäsenrekisteriin" closeText="Peruuta" saveText="Lisää jäsen" handleSave={this.tallennaJasen} modalId="uusijasen-modal" > <div className="container-fluid"> <div className="row"> <div className="col"> <Text id="fname-input" autoFocus name="fname" onChange={this.handleChange} value={this.state.jasen.fname} placeholder="Etunimet" /> </div> <div className="col"> <Text id="sname-input" name="sname" onChange={this.handleChange} value={this.state.jasen.sname} placeholder="Sukunimi" /> </div> </div> <div className="row"> <div className="col"> <Text id="email-input" name="email" onChange={this.handleChange} value={this.state.jasen.email} placeholder="Sähköposti" /> </div> <div className="col"> <Text id="hometown-input" name="hometown" onChange={this.handleChange} value={this.state.jasen.hometown} placeholder="Kotikunta" /> </div> </div> <div className="row"> <div className="col"> <Radio options={[ { label: 'TYYn jäsen', value: true }, { label: 'Ei TYYn jäsen', value: false }, ]} value={this.state.jasen.memberOfTyy} name="memberOfTyy" onChange={this.handleChange} /> </div> </div> </div> </Modal> ); } } Uusijasen.propTypes = { jasen: PropTypes.object, successMessage: PropTypes.func, warningMessage: PropTypes.func, clear: PropTypes.func, }; const mapStateToProps = state => ({ jasen: state.production.selectedMember, }); const mapDispatchToProps = dispatch => ({ successMessage: message => dispatch(addSuccessMessage(message)), warningMessage: message => dispatch(addWarningMessage(message)), clear: () => dispatch(clearMessages()), }); export default connect(mapStateToProps, mapDispatchToProps)(Uusijasen); <file_sep>/src/client/components/Home/HybridiSpeksiAbout.js import React from 'react'; import styles from './Home.css'; const HybridiSpeksiAbout = () => ( <div className={'row justify-content-center ' + styles.content_speksi}> <div className={'col-sm-12 ' + styles.hslogo} /> <div className={'col-md-10 col-lg-8 col-xl-6 ' + styles.speksi_desc}> {/* <p className={"d-block text-center material-icons " + styles.infoicon}>info_outline</p> */} <h1 className={styles.otsikko}>HybridiSpeksi</h1> <p>HybridiSpeksi on Turun yliopiston luonnontieteiden ja tekniikan tiedekunnan opiskelijoiden vuosittain toteuttama teatteriproduktio. Ensimmäinen HybridiSpeksi nähtiin vuonna 2015 Barker-teatterilla. </p> <h3>2019 - 5 v. juhlavuosispeksi</h3> <p>Keväällä 2019 HybridiSpeksin näytökset valtaavat speksiscenen jo viidettä kertaa Turun historiassa. Tulevan produktion tuotanto- ja käsikirjoitustiimi valittiin ennen kesää. Rekrytilaisuus pidettiin 18.9. ja tämä viime kesäkuussa aloitettu produktio saakin ensi-iltansa 27.3. Manilla-teatterilla yli sadan ahkeran speksiläisen työn tuloksena. </p> <h3>Speksi</h3> <p>Speksi on interaktiivista opiskelijateatteria. Siinä yhdistyvät käsikirjoitettu teatteri, improvisaatio ja musikaali. Esityksissä yleisö voi vaikuttaa muutoin käsikirjoitetun esityksen kulkuun huutamalla <strong>“Omstart”</strong>, jolloin edellinen toiminta, repliikki tai musiikkinumero tehdään uudelleen erilaisella tavalla improvisoiden. Lisää spekseistä ja niiden historiasta voi lukea esimerkiksi <a className={styles.externallink} href="https://fi.wikipedia.org/wiki/Speksi">Wikipediasta</a>. </p> </div> </div> ); export default HybridiSpeksiAbout; <file_sep>/src/client/components/Admin/Ohjaustiedot/Ohjaustieto.js import React, { Component } from 'react'; import { Text, Textarea, Radio } from '../../../Utils/Form'; class Ohjaustieto extends Component { render() { return ( <form> <div className="row"> <div className="col"> <p> <i>_id: {this.props.ohjaustieto._id}</i> </p> </div> </div> <div className="row"> <div className="col-sm-6"> <Text type="text" autoFocus name="key" onChange={this.props.handleChange} value={this.props.ohjaustieto.key} placeholder="Key" id="key-input" /> </div> <div className="col"> <Text type="text" name="value" onChange={this.props.handleChange} value={this.props.ohjaustieto.value} placeholder="Value" id="value-input" /> </div> </div> <div className="row"> <div className="col"> <Textarea id="name-input" name="name" placeholder="Nimiteksti" rows={5} value={this.props.ohjaustieto.name} onChange={this.props.handleChange} /> </div> </div> <div className="row"> <div className="col"> <Radio options={[{ label: 'true', value: true }, { label: 'false', value: false }]} value={this.props.ohjaustieto.truefalse} name="truefalse" onChange={this.props.handleChange} legend="Boolean -arvo" /> </div> </div> </form> ); } } export default Ohjaustieto; <file_sep>/src/client/components/Galleria/Galleria.js import React, { Component } from 'react' import styles from './Galleria.css'; class Galleria extends Component { componentDidMount() { } render() { return ( <div className={"container-fluid " + styles.container}> <div className={"row align-items-center " + styles.content}> <div className={"col-sm-6 col-11 " + styles.galleria_desc}> <h1>Galleria</h1> <p>Tänne tulee kuvei.</p> <p>Tästä lisää infoa myöhemmin.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus cursus ipsum nec imperdiet cursus. Nulla vel dui nulla. Etiam urna libero, rhoncus id finibus eget, pulvinar nec ante. In sollicitudin sem et velit posuere, et malesuada ligula venenatis. Mauris vel augue ac nisi pretium consectetur. Sed a massa ligula. Sed dapibus non ex at eleifend. Donec vel lacinia neque. Sed commodo varius massa vel lacinia.</p> </div> </div> </div> ) } } export default Galleria<file_sep>/src/client/components/Admin/BookingManagement/Booking.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Field, reduxForm, getFormValues } from 'redux-form'; import { RenderTextfield, RenderNumber, RenderTextarea, RenderCheckbox, RenderDropdown } from './RenderForm'; import styles from './Booking.css'; import ShowsList from './ShowsList'; import * as actions from 'actions/bookingActions'; const ContactInfo = () => ( <div className={styles.column}> <h2>Yhteystiedot</h2> <div className={styles.content}> <div className={styles.formRow}> <Field name="ContactInfo.fname" id="fnameInput" component={RenderTextfield} type="text" placeholder="Etunimi" /> <Field name="ContactInfo.lname" id="lnameInput" component={RenderTextfield} type="text" placeholder="Sukunimi" /> </div> <div className={styles.formRow}> <Field name="ContactInfo.email" id="emailInput" component={RenderTextfield} type="text" placeholder="Sähköposti" /> <Field name="ContactInfo.pnumber" id="pnumberInput" component={RenderTextfield} type="text" placeholder="Puhelinnumero" /> </div> </div> </div> ); const Tickets = ({ selectedShow, formState, prices, paymentMethods, booking, }) => { const paymentMethodOptions = () => { return paymentMethods.map((method) => { return { name: method.name, value: method.id }; }); }; const countPrice = () => { if (!formState) return 0; const { normalCount, discountCount, specialPriceCount, specialPrice, } = formState; const { normalPrice, discountPrice } = prices; return Number(normalCount) * Number(normalPrice) + Number(discountCount) * Number(discountPrice) + Number(specialPriceCount) * Number(specialPrice); }; return ( <div className={styles.column}> <h2>Liput</h2> <div className={styles.content}> <div> <span>{selectedShow.nameLong}</span> </div> <div className={styles.formRow}> <Field name="normalCount" id="nCountInput" component={RenderNumber} type="number" label="Normaali (16€)" /> <Field name="discountCount" id="dCountInput" component={RenderNumber} type="number" label="Alennus (14€)" /> </div> <div className={styles.formRow}> <Field name="specialPriceCount" id="sCountInput" component={RenderNumber} type="number" label="Muu hinta kpl" /> <Field name="specialPrice" id="sPriceInput" component={RenderNumber} type="number" label="Erikoishinta" /> </div> <div className={styles.price}> <span>Hinta yhteensä {countPrice()}€</span> </div> <div className={styles.formRow}> <Field name="additionalInfo" id="additionalArea" component={RenderTextarea} type="text" label="Lisätietoja" rows="5" /> </div> <div className={styles.formRow}> <Field name="paymentMethodId" id="paymentMethodSelect" component={RenderDropdown} options={paymentMethodOptions()} /> </div> <div className={styles.formRow}> <Field name="paid" id="paid" label="Maksettu" component={RenderCheckbox} type="checkbox" /> {booking.id === '' ? ( <Field name="sendConfirmationMail" label="Lähetä varausvahvistus (vain maksetut varaukset)" component={RenderCheckbox} type="checkbox" /> ) : null} </div> </div> </div> ); }; Tickets.propTypes = { selectedShow: PropTypes.object, formState: PropTypes.object, prices: PropTypes.object, paymentMethods: PropTypes.array, booking: PropTypes.object, }; const Shows = () => ( <div className={styles.column}> <h2>Esitys</h2> <ShowsList /> </div> ); const Buttons = ({ booking, deleteBooking, sendConfirmationMail }) => { const isNewBooking = booking.id === ''; const handleSendConfirmationMail = () => { if (confirm('Lähetetäänkö varausvahvistus?')) { sendConfirmationMail(booking); } }; return ( <div className={styles.column}> <div className={styles.formRow}> {isNewBooking ? ( <button type="submit" className={`${styles.input} ${styles.button} ${styles.success}`}> Tallenna uusi varaus </button> ) : ( <React.Fragment> <button type="submit" className={`${styles.input} ${styles.button} ${styles.success}`}> Tallenna muutokset </button> <button type="button" onClick={handleSendConfirmationMail} className={`${styles.input} ${styles.button}`}>Lähetä varausvahvistus</button> <button type="button" onClick={deleteBooking} className={`${styles.input} ${styles.button}`}>Poista varaus</button> </React.Fragment> )} <Link to="varaustenhallinta" className={`${styles.input} ${styles.button} ${styles.cancel}`}> Peruuta </Link> </div> </div> ); }; Buttons.propTypes = { booking: PropTypes.object, deleteBooking: PropTypes.func, sendConfirmationMail: PropTypes.func, }; class Booking extends Component { componentDidMount() { if (this.props.shows.length < 1) { this.props.fetchShows(); } this.props.fetchPaymentMethods(); } render() { const { booking, selectedShow, handleSubmit, createBooking, updateBooking, deleteBooking, formState, prices, paymentMethods, sendConfirmationMail, } = this.props; const onSubmit = (values) => { values.showId = selectedShow.id; if (booking.id === '') { createBooking(values); } else { updateBooking(values); } }; const handleDelete = () => { if (confirm('Poistetaanko varaus?')) { deleteBooking(booking); } }; return ( <div className={styles.container}> <form className={styles.form} onSubmit={handleSubmit(onSubmit)}> <div className={styles.row}> <ContactInfo /> <Tickets selectedShow={selectedShow} formState={formState} prices={prices} paymentMethods={paymentMethods} booking={booking} /> </div> <div className={styles.row}> <Shows /> <Buttons booking={booking} deleteBooking={handleDelete} sendConfirmationMail={sendConfirmationMail} /> </div> </form> </div> ); } } Booking.propTypes = { booking: PropTypes.object, selectedShow: PropTypes.object, shows: PropTypes.array, prices: PropTypes.object, paymentMethods: PropTypes.array, fetchShows: PropTypes.func, fetchPaymentMethods: PropTypes.func, createBooking: PropTypes.func, updateBooking: PropTypes.func, deleteBooking: PropTypes.func, handleSubmit: PropTypes.func, formState: PropTypes.object, sendConfirmationMail: PropTypes.func, }; const mapStateToProps = state => ({ booking: state.bookingManagement.selectedBooking, initialValues: state.bookingManagement.selectedBooking, selectedShow: state.bookingManagement.selectedShow, prices: state.bookingManagement.prices, shows: state.bookingManagement.shows, paymentMethods: state.bookingManagement.paymentMethods, formState: getFormValues('bookingForm')(state), }); const mapDispatchToProps = dispatch => ({ fetchShows: () => dispatch(actions.fetchShows()), fetchPaymentMethods: () => dispatch(actions.fetchPaymentMethods()), createBooking: booking => dispatch(actions.createBooking(booking)), updateBooking: booking => dispatch(actions.updateBooking(booking)), deleteBooking: booking => dispatch(actions.deleteBooking(booking)), sendConfirmationMail: booking => dispatch(actions.sendConfirmationMail(booking)), }); const BookingWithReduxForm = reduxForm({ form: 'bookingForm', })(Booking); export default connect(mapStateToProps, mapDispatchToProps)(BookingWithReduxForm); <file_sep>/src/schema/ilmo-model.js var mongoose = require('mongoose'); var ilmoSchema = new mongoose.Schema({ tapahtuma: String, fname: String, sname: String, email: String, pnumber: String, jarjesto: String, ruokavalio: String, juoma: String, alterego: String }, { collection: 'ilmot', strict: false, timestamps: true }) module.exports = mongoose.model('Ilmo', ilmoSchema);<file_sep>/src/client/components/Admin/Jasenrekisteri/Jasenrekisteri.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import List from './List'; import Jasentiedot from './Jasentiedot'; import Uusijasen from './Uusijasen'; import Statistics from './Statistics'; import Sahkopostit from '../../Shared/Sahkopostit'; import { addSuccessMessage, addErrorMessage, clearMessages } from '../../../actions/messageActions'; import { fetchMembers, clearSelectedMember } from '../../../actions/jasenrekisteriActions'; class Jasenrekisteri extends Component { constructor(props) { super(props); this.state = { naytaSahkopostit: false, }; this.toggleSahkopostit = this.toggleSahkopostit.bind(this); } componentDidMount() { this.props.fetchMembers(); } toggleSahkopostit() { this.setState({ naytaSahkopostit: !this.state.naytaSahkopostit }); } render() { return ( <div className="container-fluid"> <div className="row"> <div className="col"> <h1>Jäsenrekisteri</h1> </div> <div className="col text-right"> <h1> <button className="btn btn-primary" data-toggle="modal" data-target="#uusijasen-modal" onClick={this.props.clear} > Lisää uusi jäsen </button> </h1> </div> </div> <div className="row"> <div className="col-sm-7"> <List /> </div> <div className="col-sm-5"> <Statistics /> {this.props.selectedMember._id ? ( <Jasentiedot /> ) : ( '' )} {this.state.naytaSahkopostit ? ( <Sahkopostit jasenet={this.props.members} toggleSahkopostit={this.toggleSahkopostit} /> ) : ( <button className="btn btn-default" onClick={this.toggleSahkopostit}> Näytä sähköpostit </button> )} </div> </div> <Uusijasen jasen={{}} jasenLisatty={this.jasenLisatty} /> </div> ); } } Jasenrekisteri.propTypes = { fetchMembers: PropTypes.func, members: PropTypes.array, selectedMember: PropTypes.object, clear: PropTypes.func, }; const mapStateToProps = state => ({ members: state.jasenrekisteri.members, selectedMember: state.jasenrekisteri.selectedMember, }); const mapDispatchToProps = dispatch => ({ addSuccess: message => dispatch(addSuccessMessage(message)), addError: message => dispatch(addErrorMessage(message)), clearMessages: () => dispatch(clearMessages()), fetchMembers: () => dispatch(fetchMembers()), clear: () => dispatch(clearSelectedMember()), }); export default connect(mapStateToProps, mapDispatchToProps)(Jasenrekisteri); <file_sep>/src/client/components/Admin/BookingManagement/RenderForm.js import React from 'react'; import cuid from 'cuid'; import styles from './BookingManagement.css'; export const RenderTextfield = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} placeholder={field.placeholder} type="text" /> </div> ); export const RenderNumber = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} type="number" /> </div> ); export const RenderDateField = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} type="datetime-local" /> </div> ); export const RenderTextarea = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <textarea id={field.id} className={styles.input} rows={field.rows} {...field.input} /> </div> ); export const RenderCheckbox = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input type="checkbox" className={`${styles.input} ${styles.checkbox}`} {...field.input} /> </div> ); export const RenderDropdown = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <select className={`${styles.input}`} id={field.id} {...field.input}> <option value="">Maksutapa</option> {field.options.map((option) => { return ( <option key={cuid()} value={option.value}>{option.name}</option> ); })} </select> </div> ); <file_sep>/src/services/userService.js const uuid = require('uuid/v4'); const transaction = require('sequelize').transaction; const User = require('../../models').User; const ContactInfo = require('../../models').ContactInfo; const UserMongo = require('../schema/user-model'); const Role = require('../../models').Role; module.exports = { createUser: async (fname, lname, email, pwHash) => { try { const t = await transaction; const contactInfo = await ContactInfo.create({ id: uuid(), fname, lname, email, }, { transaction: t }); const user = await User.create({ id: uuid(), password: <PASSWORD>, }, { transaction: t }); await user.setContactInfo(contactInfo, { transaction: t }); return user; } catch (e) { console.log(e); throw e; } }, findUsers: async () => { try { const users = await User.findAll({ attributes: ['id', 'createdAt', 'updatedAt'], include: [{ model: ContactInfo, }, { model: Role, }], }); return users; } catch (e) { console.log(e); throw e; } }, deleteUser: async (id) => { try { await User.destroy({ where: { id }, }); } catch (e) { console.log(e); throw e; } }, changePassword: async (userId, pwHash) => { try { const user = await User.findOne({ where: { id: userId } }); user.update({ password: <PASSWORD>, }); } catch (e) { console.log(e); throw e; } }, findUserByEmail: async (email) => { try { const user = await User.findOne({ include: [{ model: ContactInfo, where: { email }, }, { model: Role, }], }); return user; } catch (e) { console.log(e); throw e; } }, findUserById: async (id) => { try { const user = await User.findOne({ where: { id }, include: [{ model: ContactInfo, }, { model: Role, }], }); return user; } catch (e) { console.log(e); throw e; } }, findRoleById: async (id) => { try { const role = await Role.findOne({ where: { id }, }); return role; } catch (e) { console.log(e); throw e; } }, findMongoUserByEmail: async (email) => { try { const user = await UserMongo.findOne({ email }); return user; } catch (e) { console.log(e); throw e; } }, getRoles: async () => { try { const roles = await Role.findAll(); return roles; } catch (e) { console.log(e); throw e; } }, getRoleByValue: async (value) => { try { const role = await Role.findOne({ where: { value } }); return role; } catch (e) { console.log(e); throw e; } }, }; <file_sep>/src/client/components/Organization/Organization.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import cuid from 'cuid'; import SectionDivider from '../SectionDivider/SectionDivider'; import PageHero from '../PageHero/PageHero'; import styles from './Organization.css'; class Organization extends Component { constructor() { super(); this.state = { contactInfo: [ { name: 'Sähköposti', value: '<EMAIL>', }, { name: 'Tilinumero', value: 'FI64 5711 1320 1361 76', }, { name: 'Y-tunnus', value: '2732017-8', }, ], }; } componentDidMount() { $(window).scrollTop(0); } render() { const getInfoRows = ( this.state.contactInfo.map(row => ( <div className={styles.infoRow} key={cuid()}> <div className={styles.infoName}> {row.name} </div> <div className={styles.infoValue}> {row.value} </div> </div> )) ); return ( <div className={styles.container}> <div className={styles.pageHero}> <PageHero title="HybridiSpeksi ry" subTitle="Yhdistys" /> </div> <div className={styles.basicInfoContainer}> <div className={styles.info}> {getInfoRows} </div> <div className={styles.logo} /> <div className={styles.officialLinks}> <div> <Link to="/yhdistys/saannot" className={styles.internallink}>Säännöt</Link> </div> <div> <Link to="/yhdistys/rekisteriseloste" className={styles.internallink}>Rekisteriseloste</Link> </div> </div> </div> {/* BasicInfo */} <SectionDivider /> <div className="container-fluid"> <div className={'row justify-content-center ' + styles.content}> <div className={'col-sm-8 col-11 ' + styles.yhdistys_desc}> <div className="row"> <div className="col-lg-6 col-md-11"> <h3 className={styles.otsikko}>Hallitus</h3> <div className="row"> <div className="col-11"> <p><strong><NAME></strong><br /> <i>Puheenjohtaja</i><br /> </p> </div> </div> <div className="row"> <div className="col-11"> <p><strong><NAME></strong><br /> <i>Varapuheenjohtaja</i><br /> <i>Improkerhovastaava</i><br /> <i>Rekisteri- ja tietosuojavastaava</i> </p> </div> </div> <div className="row"> <div className="col-11"> <p><strong><NAME></strong><br /> <i>Sihteeri</i><br /> <i>Tiedotusvastaava</i> </p> </div> </div> <div className="row"> <div className="col-11"> <p><strong><NAME></strong><br /> <i>Taloudenhoitaja</i><br /> <i>Häirintäyhdyshenkilö</i> </p> </div> </div> <div className="row"> <div className="col"> <p><strong><NAME></strong><br /> <i>Interspeksivastaava</i> </p> </div> </div> <div className="row"> <div className="col"> <p><strong><NAME></strong><br /> <i>Yhdenvertaisuus- ja hyvinvointivastaava</i><br /> <i>Ympäristövastaava</i> </p> </div> </div> <div className="row"> <div className="col"> <p><strong><NAME></strong><br /> <i>Häirintäyhdyshenkilö</i><br /> <i>Liikuntavastaava</i> </p> </div> </div> </div> <div className="col-lg-6 col-md-11"> <h3 className={styles.otsikko}>Tuotantotiimi</h3> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Tuottaja</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Apulaistuottaja</p> </div> <div className="col-7"> <p>M<NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Ohjaaja</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Apulaisohjaaja</p> </div> <div className="col-7"> <p>Ilari Laaksonen</p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Pääkoreografi</p> </div> <div className="col-7"> <p>Saara Koskela</p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Kapellimestari</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Käsikirjoitus</p> </div> <div className="col-7"> <p><NAME> </p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Lavastus</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Maskeeraus</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Puvustus</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Kuvaus</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Grafiikka</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Virkistys</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Varainhankinta</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Markkinointi</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Tekniikka</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> {/* <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Valot</p> </div> <div className="col-7"> <p>-</p> </div> </div> */} <div className="row"> <div className="col-sm-4 col-5"> <p className={styles.persontitle}>Nettisivut</p> </div> <div className="col-7"> <p><NAME></p> </div> </div> </div> </div> </div> </div> </div> </div> ); } } export default Organization; <file_sep>/src/server.js const express = require('express'); const app = express(); const dotenv = require('dotenv'); const mongoose = require('mongoose'); const morgan = require('morgan'); const path = require('path'); const bodyParser = require('body-parser'); // var cors = require('cors'); // Basic conf dotenv.load(); app.set('port', process.env.PORT || 3002); app.set('secret', process.env.SECRET); if (process.env.NODE_ENV !== 'production') { app.use(morgan('dev')); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); } else { app.use(bodyParser.json()); app.use(morgan('common')); } mongoose.connect(process.env.MONGOLAB_URI) .then(() => { console.log('Connected to database in ' + process.env.MONGOLAB_URI); }) .catch((err) => { console.log(err); }); // Initiate API app.use('/api', require('./api/index')); // Static assets app.use('/', express.static(path.join(__dirname, '/dist'))); app.use('/assets', express.static(path.join(__dirname, '/assets'))); // Serve index.html for every other request. Client router handles the rest if (process.env.NODE_ENV === 'production') { app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '/dist/index.html')); }); } app.listen(app.get('port'), '0.0.0.0', () => { console.log('Node App Started on port ' + app.get('port')); }); <file_sep>/src/client/actions/messageActions.js import cuid from 'cuid'; import constants from '../Utils/constants'; export const actions = { ADD_MESSAGE: 'ADD_MESSAGE', CLEAR_MESSAGES: 'CLEAR_MESSAGES', CLOSE_MESSAGE: 'CLOSE_MESSAGE', FADE_OUT: 'FADE_OUT', }; // DEPRECATION: don't use this anymore. export function addMessage(message) { console.warn('DEPRECATION: old message action type'); return { type: actions.ADD_MESSAGE, message, }; } export function addSuccessMessage(m, timeout) { return (dispatch) => { const id = cuid(); const message = { ...m, id, type: constants.MESSAGE_SUCCESS, }; dispatch(messageAction(message)); if (timeout) { setTimeout(() => { dispatch(startFadeOut(id)); }, timeout); setTimeout(() => { dispatch(closeMessage(id)); }, timeout + 300); } }; } export function addWarningMessage(m, timeout) { return (dispatch) => { const id = cuid(); const message = { ...m, id, type: constants.MESSAGE_WARNING, }; dispatch(messageAction(message)); if (timeout) { setTimeout(() => { dispatch(startFadeOut(id)); }, timeout); setTimeout(() => { dispatch(closeMessage(id)); }, timeout + 300); } }; } export function addErrorMessage(m, timeout) { return (dispatch) => { const id = cuid(); const message = { ...m, id, type: constants.MESSAGE_ERROR, }; dispatch(messageAction(message)); if (timeout) { setTimeout(() => { dispatch(startFadeOut(id)); }, timeout); setTimeout(() => { dispatch(closeMessage(id)); }, timeout + 300); } }; } export function clearMessages() { return { type: actions.CLEAR_MESSAGES, }; } export function closeMessage(id) { return { type: actions.CLOSE_MESSAGE, id, }; } function messageAction(message) { return { type: actions.ADD_MESSAGE, message, }; } function startFadeOut(id) { return { type: actions.FADE_OUT, id, }; } <file_sep>/src/client/components/Admin/Events/EventList.js import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import cuid from 'cuid'; import * as actions from 'actions/eventActions'; import styles from './EventList.css'; import list from '../Listing.css'; const EventList = ({ events, openRegistration, closeRegistration, enrollments, }) => { return ( <div className={styles.container}> <h3>Tapahtumat</h3> <div className={list.container}> <div className={list.rows}> {events.map((event) => { return ( <div key={cuid()} className={list.row}> <span>{event.name}</span> <span>{enrollments.length}/{event.limit}</span> {event.registrationOpen === true ? <button className={styles.closeEvent} onClick={() => closeRegistration(event.id)}>Sulje ilmo</button> : <button className={styles.closeEvent} onClick={() => openRegistration(event.id)}>Avaa ilmo</button> } </div> ); })} </div> </div> </div> ); }; EventList.propTypes = { events: PropTypes.array, enrollments: PropTypes.array, openRegistration: PropTypes.func, closeRegistration: PropTypes.func, }; const mapStateToProps = state => ({ events: state.event.events, enrollments: state.event.enrollments, }); const mapDispatchToProps = dispatch => ({ openRegistration: eventId => dispatch(actions.openRegistration(eventId)), closeRegistration: eventId => dispatch(actions.closeRegistration(eventId)), }); export default connect(mapStateToProps, mapDispatchToProps)(EventList); <file_sep>/src/client/components/Speksi2019/Speksi2019.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as actions from 'actions/bookingActions'; import SpeksiHero from './SpeksiHero'; import styles from './Speksi2019.css'; import Shows from './Shows'; import ContactInfo from './ContactInfo'; import Confirm from './Confirm'; import ajax from './../../Utils/Ajax'; const formState = { SELECT_SHOW: 0, FILL_INFO: 1, CONFIRM_INFO: 2, }; class Speksi2019 extends Component { constructor() { super(); this.divider = React.createRef(); this.state = { wizardState: formState.SELECT_SHOW, }; this.nextState = this.nextState.bind(this); this.prevState = this.prevState.bind(this); } componentDidMount() { $(window).scrollTop(0); this.props.fetchShows(); this.props.fetchTicketSaleMessage(); } nextState() { this.setState({ wizardState: this.state.wizardState + 1, }); window.scrollTo(0, this.divider.current.offsetTop); } prevState() { this.setState({ wizardState: this.state.wizardState - 1, }); window.scrollTo(0, this.divider.current.offsetTop); } render() { const { wizardState } = this.state; const { ticketSaleMessage, } = this.props; return ( <div className={styles.container}> <SpeksiHero ticketSaleMessage={ticketSaleMessage} /> <div ref={this.divider} /> <Shows nextState={this.nextState} showPage={wizardState === formState.SELECT_SHOW} /> <ContactInfo nextState={this.nextState} prevState={this.prevState} showPage={wizardState === formState.FILL_INFO} /> <Confirm nextState={this.nextState} prevState={this.prevState} showPage={wizardState === formState.CONFIRM_INFO} /> <div className={styles.payTrail} /> </div> ); } } Speksi2019.propTypes = { fetchShows: PropTypes.func, fetchTicketSaleOpen: PropTypes.func, fetchTicketSaleMessage: PropTypes.func, ticketSaleMessage: PropTypes.string, }; const mapStateToProps = state => ({ selectedShow: state.bookingManagement.selectedShow, ticketSaleMessage: state.bookingManagement.ticketSaleMessage, }); const mapDispatchToProps = dispatch => ({ fetchShows: () => dispatch(actions.fetchShows()), fetchTicketSaleMessage: () => dispatch(actions.fetchTicketSaleMessage()), }); export default connect(mapStateToProps, mapDispatchToProps)(Speksi2019); <file_sep>/src/client/components/Admin/Admin.js import React, { Component } from 'react'; import styles from './Admin.css'; class Admin extends Component { componentWillMount() { // auth.checkToken(); } componentDidMount() {} render() { return ( <div className="container"> <h1> HybridiSpeksi <small>tuotantopaneeli</small> </h1> <div className="row"> <div className="col"> <iframe className={styles.iframe} src="https://calendar.google.com/calendar/embed?src=d3jpe3k88npq9f97ba26fi9u5c%40group.calendar.google.com&ctz=Europe/Helsinki" frameBorder="0" scrolling="no" /> </div> </div> </div> ); } } export default Admin; <file_sep>/src/client/store.js import { combineReducers, createStore, applyMiddleware, compose } from 'redux'; import { reducer as formReducer } from 'redux-form'; import thunk from 'redux-thunk'; import feedback from './reducers/feedbackReducer'; import ajax from './reducers/ajaxReducer'; import messages from './reducers/messageReducer'; import production from './reducers/productionReducer'; import ohjaustieto from './reducers/ohjaustietoReducer'; import jasenrekisteri from './reducers/jasenrekisteriReducer'; import user from './reducers/userReducer'; import bookingManagement from './reducers/bookingReducer'; import loader from './reducers/loaderReducer'; import event from './reducers/eventReducer'; const reducers = combineReducers({ form: formReducer, feedback, ajax, messages, production, ohjaustieto, jasenrekisteri, user, bookingManagement, loader, event, }); const middleWare = applyMiddleware(thunk); const enhancer = compose( middleWare, window.devToolsExtension ? window.devToolsExtension() : f => f, ); const store = createStore( reducers, enhancer, ); export default store; <file_sep>/src/schema/ohjaustieto-model.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = mongoose.model( 'Ohjaustieto', new Schema( { key: String, value: String, name: String, truefalse: Boolean, }, { collection: 'ohjaustietos', timestamps: true, }, ), ); <file_sep>/src/schema/varaus-model.js var mongoose = require('mongoose'); var varausSchema = new mongoose.Schema({ fname: String, sname: String, email: String, pnumber: String, scount: {type: Number, default: 0}, ncount: {type: Number, default: 0}, ocount: {type: Number, default: 0}, oprice: {type: Number, default: 0}, checked: {type: Boolean, default: false}, paymentMethod: {type: Number, default: 0}, paid: {type: Boolean, default: false}, esitysId: {type: String, required: true}, additional: {type: String, default: ""}, bookingId: {type: String}, year: {type: Number} }, { collection: 'varaukset', timestamps: true }) module.exports = mongoose.model('Varaus', varausSchema);<file_sep>/src/client/Utils/Utils.js function isBoolean(a) { return typeof (a) === 'boolean'; } function parseBoolean(a) { return a === 'true'; } function isNumber(a) { if (a !== '') { return !isNaN(a); } return false; } function parseNumberIfNumber(a) { if (isNumber(a)) { return Number.parseInt(a, 10); } return a; } function isValidEmail(a) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(a); } module.exports.isBoolean = isBoolean; module.exports.parseBoolean = parseBoolean; module.exports.isNumber = isNumber; module.exports.parseNumberIfNumber = parseNumberIfNumber; module.exports.isValidEmail = isValidEmail; <file_sep>/src/api/feedback/feedbackController.js const feedbackService = require('../../services/feedbackService'); const validator = require('../../utils/validation'); const validateFeedback = ({ name, email, feedback }) => { if (validator.isEmptyOrNull(feedback)) { throw new Error('Tyhjää palautetta ei voi lähettää'); } else if (validator.isTooLong(feedback, 700)) { throw new Error('Palaute ei saa ylittää 700 merkkiä'); } else if (!validator.isEmptyOrNull(email) && !validator.isValidEmail(email)) { throw new Error('Virheellinen sähköposti'); } else if (!validator.isEmptyOrNull(name) && validator.isTooLong(name, 40)) { throw new Error('Nimi on liian pitkä'); } }; module.exports = { getFeedback: async (req, res) => { try { const feedback = await feedbackService.getFeedback(); res.json({ success: true, data: feedback }); } catch (e) { res.json({ success: false, message: e.message }); } }, createFeedback: async (req, res) => { try { validateFeedback(req.body); await feedbackService.createFeedback(req.body); res.json({ success: true }); } catch (e) { res.json({ success: false, message: e.message }); } }, deleteFeedback: async (req, res) => { try { await feedbackService.deleteFeedback(req.params.feedbackId); res.json({ success: true }); } catch (e) { res.json({ success: false, message: e.message }); } }, }; <file_sep>/src/schema/tapahtuma-model.js var mongoose = require('mongoose'); var tapahtumaSchema = new mongoose.Schema({ //Key & value dropdown-komponentin käyttöä varten //Value tunnisteena value: { type: String, required: true, unique: true}, name: String, kuvaus: [String], aika: Date, paikka: String, suljettu: Boolean, ilmoauki: Date, ilmokiinni: Date, tilaTeksti: String }, { collection: 'tapahtumat', strict: false, timestamps: true }) module.exports = mongoose.model('Tapahtuma', tapahtumaSchema);<file_sep>/src/client/components/Speksi2018/Esitysvalinta.js import React from 'react'; import PropTypes from 'prop-types'; import Moment from 'react-moment'; import styles from './Speksi2018.css'; const Esitysvalinta = (props) => { const { esitykset, toggleUusiVarausModal } = props; const getEsitykset = esitykset.map((esitys, i) => { let tilaa = ''; if (esitys.bookingCount < 100) { tilaa = 'Tilaa'; } else if (esitys.bookingCount < 130) { tilaa = 'Lähes täynnä'; } else { tilaa = 'Loppuunmyyty'; } return ( <tr key={esitys._id}> <td className={tilaa === 'Loppuunmyyty' || new Date() > new Date(esitys.date) ? styles.showTdFull : styles.showTd} onClick={() => toggleUusiVarausModal(esitys, tilaa)} > {esitys.name} klo <Moment format="HH.mm">{esitys.date}</Moment> </td> <td className={tilaa === 'Loppuunmyyty' || new Date() > new Date(esitys.date) ? styles.showTdFull : styles.showTd} onClick={() => toggleUusiVarausModal(esitys, tilaa)} > <i>{tilaa}</i> </td> </tr> ); }); return ( <div> <table className="table table-hover table-sm"> <tbody>{getEsitykset}</tbody> </table> </div> ); }; export default Esitysvalinta; Esitysvalinta.defaultProps = { esitykset: [], }; Esitysvalinta.propTypes = { esitykset: PropTypes.array, toggleUusiVarausModal: PropTypes.func, }; <file_sep>/src/client/Utils/Auth.js import ajax from './Ajax'; export const isUserLoggedIn = () => { if (localStorage.getItem('jwt').length > 0) { return true; } return false; }; export const signIn = (jwt, user) => { localStorage.setItem('jwt', jwt); localStorage.setItem('user', JSON.stringify(user)); }; export const signOut = () => { console.log('signout'); localStorage.removeItem('jwt'); localStorage.removeItem('user'); location.replace('/login'); }; /** * Check token from server * Redirects to login if invalid and removes token from localstorage */ export const checkToken = () => { if (!isUserLoggedIn) { signOut(); } else { ajax.sendGet('/isValidToken') .then((data) => { if (!data.success) { signOut(); } }); } }; export const getUserInfo = () => JSON.parse(localStorage.getItem('user')); export const getUserRole = () => { const user = JSON.parse(localStorage.getItem('user')); if (!user) { return 0; } return user.role; }; export const hasRole = (role) => { let hasRequestedRole = false; const user = JSON.parse(localStorage.getItem('user')); if (!user) { return 0; } user.Roles.forEach((_role) => { if (_role.value === role) { hasRequestedRole = true; } }); return hasRequestedRole; }; export const getFullUserName = () => { const user = JSON.parse(localStorage.getItem('user')); if (!user) { return ''; } return user.fname + ' ' + user.sname; }; // module.exports.isUserLoggedIn = isUserLoggedIn; // module.exports.getUserInfo = getUserInfo; // module.exports.getUserRole = getUserRole; // module.exports.signIn = signIn; // module.exports.signOut = signOut; // module.exports.checkToken = checkToken; // module.exports.getFullUserName = getFullUserName; <file_sep>/src/client/components/Esitykset/Esitykset.js import React, { Component } from 'react' import styles from './Esitykset.css'; class Esitykset extends Component { componentDidMount() { } render() { return ( <div className={"container-fluid " + styles.container}> <div className={"row align-items-center " + styles.content}> <div className={"row justify-content-center " + styles.content_row}> <div className={"col-sm-6 col-11 text-center " + styles.esitykset_desc}> <h1>Esitykset</h1> <br/> <p>Esitykset pidetään keväällä. Tästä lisää infoa myöhemmin. </p> <p>Kannattaa kuitenkin seurata HybridiSpeksiä Facebookissa ja Instagramissa!</p> <h3>Stay tuned!</h3> </div> </div> </div> </div> ) } } export default Esitykset<file_sep>/src/client/components/Home/Teaser.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './Teaser.css'; const Teaser = ({ globalStyles }) => ( <div className={styles.teaserRow}> <div className={styles.teaser}> <div className={styles.iframeContainer}> <iframe title="trailer" id="youtubeplayer" src="https://www.youtube.com/embed/RRqUhaG_E9s?rel=0&controls=1&showinfo=0modestbranding=1" width="100%" height="360" frameBorder="0" allowFullScreen="allowFullScreen" className={styles.video} /> </div> </div> <div className={`${styles.synopsis} ${globalStyles.speksi2019plain}`}> <p>Mystisessä Kiinassa vallitsee kurjuus ja epätoivo. Raakalaismaiset barbaarit kylvävät tuhoa kaikkialle minne menevät. Kovia kokenut, mutta päättäväinen nuorukainen Kim Mo on saanut barbaareista ja Kiinan kurjuudesta tarpeekseen. Kim Mo uskoo voivansa tuhota barbaarit ja pelastaa Kiinan löytämällä kauan kadoksissa olleet legendaariset lohikäärmesisarukset. Näillä Kung Fu -mestareilla kerrotaan olevan mystisiä taikavoimia. Riittääkö yhden nuorukaisen päättäväisyys korjaamaan menneisyyden virheet? </p> </div> </div> ); Teaser.propTypes = { globalStyles: PropTypes.any, }; export default Teaser; <iframe width="1905" height="896" src="https://www.youtube.com/embed/RRqUhaG_E9s" frameBorder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />; <file_sep>/src/client/actions/ohjaustietoActions.js import * as ajaxActions from './ajaxActions'; import ajax from '../Utils/Ajax'; export const actions = { FETCH_OHJAUSTIETO: 'FETCH_OHJAUSTIETO', RECEIVE_OHJAUSTIETO: 'RECEIVE_OHJAUSTIETO', }; /** * @param {ohjaustietoKey: String} * fetch ohjaustieto by it's key */ export function fetchOhjaustieto(ohjaustietoKey) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.FETCH_OHJAUSTIETO)); const res = await ajax.sendGet('/' + ohjaustietoKey); dispatch(ajaxActions.ajaxSuccess(actions.FETCH_OHJAUSTIETO)); dispatch(receiveOhaustieto(res, ohjaustietoKey)); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.FETCH_OHJAUSTIETO, err)); } }; } export function receiveOhaustieto(res, key) { return { type: actions.RECEIVE_OHJAUSTIETO, key, payload: res.data, }; } <file_sep>/src/api/produktio/produktionjasen.js const Jasen = require('../../schema/produktiojasen-model'); const Yhdistyksenjasen = require('../../schema/jasen-model'); function getAll(req, res) { let produktioHaettu = false; let jasenetHaettu = false; let henkilot = []; let jasenet = []; let henkilotJasentiedoilla = []; Jasen.find({ vuosi: req.params.vuosi }) .catch((err) => { res.status(500).send(err); }) .then((data) => { henkilot = data; produktioHaettu = true; if (jasenetHaettu) { henkilotJasentiedoilla = yhdistaJasenetJaProduktio(henkilot, jasenet); // console.log(henkilotJasentiedoilla) res.status(200).send(henkilotJasentiedoilla); } // res.status(200).send(data); }); Yhdistyksenjasen.find({}, { email: 1 }) .then((data) => { jasenet = data; jasenetHaettu = true; if (produktioHaettu) { henkilotJasentiedoilla = yhdistaJasenetJaProduktio(henkilot, jasenet); // console.log(henkilotJasentiedoilla) res.status(200).send(henkilotJasentiedoilla); } }); } /** * Return by req.body._id. */ function getById(req, res) { // TODO res.status(200).send('TODO'); } function newJasen(req, res) { const jasen = new Jasen({ fname: req.body.fname, lname: req.body.sname, email: req.body.email, pnumber: req.body.pnumber, tehtavat: req.body.tehtavat, jarjesto: req.body.jarjesto, lisatiedot: req.body.lisatiedot, hakeeJaseneksi: req.body.jasenyys, vuosi: '2018', }); jasen.save() .then((jasen) => { res.json({ success: true, data: jasen }); }) .catch((err) => { res.json({ success: false, data: err }); }); } function muokkaaJasen(req, res) { const jasen = req.body; Jasen.findByIdAndUpdate(jasen._id, jasen) .then(() => { res.json({ success: true }); }) .catch((err) => { res.json({ success: false, data: err }); }); } function remove(req, res) { Jasen.remove({ _id: req.params._id }) .then(() => res.json({ success: true })) .catch(err => res.json({ success: false, data: err })); } module.exports.getAll = getAll; module.exports.getById = getById; module.exports.newJasen = newJasen; module.exports.muokkaaJasen = muokkaaJasen; module.exports.remove = remove; const yhdistaJasenetJaProduktio = (henkilot, jasenet) => { for (let i = 0; i < henkilot.length; i++) { for (let j = 0; j < jasenet.length; j++) { if (henkilot[i].email.toLowerCase() === jasenet[j].email.toLowerCase()) { henkilot[i].member = true; } } } return henkilot; }; <file_sep>/src/client/components/Speksi2018/Virhe.js import React, { Component } from 'react'; import ajax from './../../Utils/Ajax'; import styles from './Vahvistus.css'; class Virhe extends Component { constructor(props) { super(props); this.state = { errorMessage: '', }; } componentDidMount() { $(window).scrollTop(0); ajax.sendGet('/ohjaustieto/maksuvirhe') .then((res) => { res.data.map((ohjaustieto) => { if (this.props.params.value === ohjaustieto.value) { this.setState({ errorMessage: ohjaustieto.name }); } }); console.log(res.data); }); } render() { return ( <div className={'container-fluid ' + styles.container}> <div className={'row align-items-start justify-content-center ' + styles.header}> <div className="col-11 col-sm-11 col-xl-5"> <h1>Pahus, jotain meni vikaan!</h1> <h5 className="">Maksutapahtuman rekisteröinnissä tapahtui virhe!</h5><br /> <div className="row"> <div className="col-sm-12 col-12"> <p>{this.state.errorMessage}</p> <br /> </div> </div> </div> <div className="col-9 col-sm-8 col-md-6 col-lg-6 col-xl-4"> <img src="/assets/images/logo_lapinak_valk.png" /> </div> </div> <div className={'row justify-content-center ' + styles.content}> <div className="col-sm-8 col-12" /> </div> </div> ); } } export default Virhe; <file_sep>/src/client/components/Event/Ilmonneet.js import React, { Component } from 'react'; class Ilmonneet extends Component { render() { const ilmonneet = this.props.ilmonneet.map((ilmonnut, i) => ( <tr key={i}> <td>{i + 1}</td> <td> {ilmonnut.fname} {ilmonnut.sname} </td> <td>{ilmonnut.jarjesto}</td> </tr> )); return ( <table className="table table-striped"> <thead> <tr> <th>#</th> <th>Nimi</th> <th>Speksi</th> </tr> </thead> <tbody>{ilmonneet}</tbody> </table> ); } } export default Ilmonneet; <file_sep>/src/client/components/Home/Sponsors.js import React from 'react'; import styles from './Home.css'; const Sponsors = () => ( <div className={styles.sponsors}> <h2><NAME></h2> <div className={styles.sponsor}> <a href="https://www.tek.fi/fi"> <img className={styles.sponsorImage} src="/assets/images/sponsors/tek.png" /> </a> </div> <div className={styles.sponsor}> <a href="http://tivia.fi/etusivu"> <img className={styles.sponsorImage} src="/assets/images/sponsors/tivia.png" /> </a> </div> </div> ); export default Sponsors; <file_sep>/src/client/components/Speksi2019/BookingConfirmation.js import React from 'react'; import styles from './BookingConfirmation.css'; import PageHero from '../PageHero/PageHero'; const BookingConfirmation = () => { return ( <div className={`${styles.container}`}> <div className={styles.pageHero}> <PageHero title="Lipun ostaminen onnistui!" subTitle="Tervetuloa katsomaan HybridiSpeksiä 2019!" /> </div> <div className={styles.instructionsContainer}> <div className={styles.instructions}> <h2>Ohjeita jatkoon</h2> <div className={styles.instructionsList}> <ul> <li>Saat pian varausvahvistuksen sähköpostiisi</li> <li>Varausvahvistus sisältää varaustunnuksen joka toimii lippuna näytökseen. Sitä ei siis tarvitse erikseen lunastaa. </li> <li>Mikäli herää kysyttävää, ota rohkeasti yhteyttä <EMAIL>. Vastaamme pikimmiten. </li> <li>Nähdään teatterilla!</li> </ul> </div> </div> </div> </div> ); }; export default BookingConfirmation; <file_sep>/src/client/components/Admin/Produktio/Produktio.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { fetchProduction } from 'actions/productionActions'; import { addSuccessMessage, clearMessages } from 'actions/messageActions'; import { fetchOhjaustieto } from 'actions/ohjaustietoActions'; import ProduktionjasenLista from './ProduktionjasenLista'; import Jasentiedot from './Jasentiedot'; import Haku from './Haku'; import Sahkopostit from '../../Shared/Sahkopostit'; import Uusijasen from '../Jasenrekisteri/Uusijasen'; class Produktio extends Component { constructor(props) { super(props); this.state = { naytaSahkopostit: false, }; this.toggleSahkopostit = this.toggleSahkopostit.bind(this); this.yhdistyksenJasenLisatty = this.yhdistyksenJasenLisatty.bind(this); } componentDidMount() { this.fetchData(); } toggleSahkopostit() { this.setState({ naytaSahkopostit: !this.state.naytaSahkopostit }); } yhdistyksenJasenLisatty() { this.props.addSuccessMessage({ header: 'Jäsen lisätty!', }); this.props.fetchProduction(); setTimeout(() => { this.props.clearMessages(); }, 2000); } fetchData() { this.props.fetchOhjaustieto('tehtavat'); this.props.fetchOhjaustieto('jarjestot'); this.props.fetchProduction(); } render() { return ( <div className="container-fluid"> <div className="row"> <div className="col"> <h1> Produktion jäsenten hallinta <small>{this.props.productionmembers.length} hlö</small> </h1> </div> </div> <div className="row"> <div className="col-sm-7 col-xs-12"> {/* {!this.props.ajaxLoading ? ( */} {true ? ( <ProduktionjasenLista /> ) : ( <div> <h4>Ladataan...</h4> </div> )} </div> <div className="col"> <Haku /> {this.props.selectedMember.fname ? ( <Jasentiedot /> ) : ( '' )} {this.state.naytaSahkopostit ? ( <Sahkopostit jasenet={this.props.productionmembers} toggleSahkopostit={this.toggleSahkopostit} /> ) : ( <button className="btn btn-default" onClick={this.toggleSahkopostit}> Näytä sähköpostit </button> )} </div> </div> <div className="row"> <div className="col"> <Uusijasen jasenLisatty={this.yhdistyksenJasenLisatty} /> </div> </div> </div> ); } } Produktio.propTypes = { productionmembers: PropTypes.array, selectedMember: PropTypes.object, fetchProduction: PropTypes.func, addSuccessMessage: PropTypes.func, clearMessages: PropTypes.func, fetchOhjaustieto: PropTypes.func, }; const mapStateToProps = state => ({ productionmembers: state.production.members, selectedMember: state.production.selectedMember, ajaxLoading: state.ajax.loading, ohjaustieto: state.ohjaustieto, }); const mapDispatchToProps = dispatch => ({ fetchProduction: () => dispatch(fetchProduction()), addSuccessMessage: message => dispatch(addSuccessMessage(message)), clearMessages: () => dispatch(clearMessages()), fetchOhjaustieto: key => dispatch(fetchOhjaustieto(key)), }); export default connect(mapStateToProps, mapDispatchToProps)(Produktio); <file_sep>/src/api/esitykset/esitykset.js const Esitys = require('../../schema/esitys-model'); const Varaus = require('../../schema/varaus-model'); module.exports = { getAll: (req, res) => { Esitys.find({}) .sort('date') .exec() .then((_data) => { res.json({ success: true, data: _data }); }) .catch((err) => { res.json({ success: false, data: err }); }); }, getAllWithBookingCounts: (req, res) => { let shows = []; Esitys.find({}) .sort('date') .exec() .then((_shows) => { shows = _shows; return Varaus.find({ year: 2018 }); }) .then((_bookings) => { const result = calculateBookingsForShows(_bookings, shows); res.json({ success: true, data: result }); }) .catch((err) => { res.json({ success: false, data: err }); console.log(err); }); }, }; function calculateBookingsForShows(bookings, shows) { shows.map((s, i) => { let counter = 0; bookings.map((b) => { if (b.esitysId.toString() === s._id.toString()) { counter += getTotalCount(b); } }); shows[i].bookingCount = counter; }); return shows; } function getTotalCount(booking) { return booking.ncount + booking.scount + booking.ocount; } <file_sep>/ecosystem.config.js module.exports = { apps: [{ name: 'server', script: './src/server.js', // Options reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/ instances: 3, autorestart: true, watch: false, }], }; <file_sep>/src/client/components/Admin/Ohjaustiedot/Ohjaustiedot.js import React, { Component } from 'react'; import ajax from '../../../Utils/Ajax'; import utils from '../../../Utils/Utils'; import List from './List'; import Ohjaustieto from './Ohjaustieto'; import Haku from './Haku'; class Ohjaustiedot extends Component { constructor(props) { super(props); this.state = { valittuOhjaustieto: { key: '', value: '', name: '', }, haku: { key: '', value: '', name: '', }, ohjaustiedot: [], unFiltered: [], avaimet: [], }; this.tallenna = this.tallenna.bind(this); this.poista = this.poista.bind(this); this.teeHaut = this.teeHaut.bind(this); this.valitseOhjaustieto = this.valitseOhjaustieto.bind(this); this.handleChange = this.handleChange.bind(this); this.lisaaUusi = this.lisaaUusi.bind(this); this.handleHaku = this.handleHaku.bind(this); } componentDidMount() { this.teeHaut(); } valitseOhjaustieto(o) { const _o = JSON.parse(JSON.stringify(o)); this.setState({ valittuOhjaustieto: _o }); } handleChange(e) { let _value = e.target.value; if (e.target.name === 'truefalse') { _value = utils.parseBoolean(_value); } const _o = this.state.valittuOhjaustieto; _o[e.target.name] = _value; this.setState({ valittuOhjaustieto: _o }); } handleHaku(e) { let _ohjaustiedot = this.state.unFiltered; const _haku = this.state.haku; _haku[e.target.name] = e.target.value; this.setState({ haku: _haku }); _ohjaustiedot = this.state.unFiltered.filter((ot) => ot.key.toLowerCase().indexOf( _haku.key.toLowerCase() ) !== -1); this.setState({ ohjaustiedot: _ohjaustiedot }); } tallenna() { ajax.sendPost('/admin/w/ohjaustieto', this.state.valittuOhjaustieto) .then((data) => { console.log('tallennettu'); this.teeHaut(); }) .catch((err) => { console.log(err); }); } poista() { ajax.sendDelete('/admin/w/ohjaustieto/' + this.state.valittuOhjaustieto._id) .then((data) => { console.log('poistettu'); this.valitseOhjaustieto({ key: '', value: '', name: '', }); this.teeHaut(); }) .catch((err) => { console.log(err); }); } lisaaUusi() { ajax.sendPut('/admin/w/ohjaustieto', this.state.valittuOhjaustieto) .then((data) => { console.log('lisätty'); this.teeHaut(); }) .catch((err) => { console.log(err); }); } teeHaut() { ajax.sendGet('/admin/w/ohjaustieto') .then((_data) => { this.setState({ ohjaustiedot: _data.data, unFiltered: _data.data }); }) .catch((err) => { console.log(err); }); ajax.sendGet('/admin/w/avaimet') .then((_data) => { _data.data.unshift({ key: '', value: '', name: 'Avain' }); this.setState({ avaimet: _data.data }); }) .catch((err) => { console.log(err); }); } render() { return ( <div className="container-fluid"> <div className="row"> <div className="col"> <h1>Ohjaustiedot {this.state.ohjaustiedot.length}</h1> </div> </div> <div className="row"> <div className="col-sm-6"> <List ohjaustiedot={this.state.ohjaustiedot} valitseOhjaustieto={this.valitseOhjaustieto} /> </div> <div className="col"> <div className="row"> <div className="col-sm-10" /> <div className="col text-right"> <button onClick={() => this.valitseOhjaustieto({ key: '', value: '', name: '' })} className="btn btn-default"> <i className="fa fa-times" aria-hidden="true" /> </button> </div> </div> <Ohjaustieto ohjaustieto={this.state.valittuOhjaustieto} handleChange={this.handleChange} valitseOhjaustieto={this.valitseOhjaustieto} /> <button onClick={this.tallenna} className="btn btn-primary">Tallenna</button> <button onClick={this.lisaaUusi} className="btn btn-primary">Lisää uusi</button> <button onClick={this.poista} className="btn btn-danger">Poista</button> <hr /> <Haku avaimet={this.state.avaimet} haku={this.state.haku} handleHaku={this.handleHaku} /> </div> </div> </div> ); } } export default Ohjaustiedot; <file_sep>/src/client/components/Home/Hero.js import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import styles from './Hero.css'; import HeroFullViewport from '../HeroFullViewport/HeroFullViewport'; const Hero = ({ globalStyles }) => ( <HeroFullViewport backgroundImage="/assets/images/speksi2019bg.png"> <div className={styles.headerContainer}> <h1 className={`${globalStyles.bigHeading} ${styles.bigsubHeading}`}>Hybridispeksi 2019</h1> <h1 className={`${globalStyles.bigHeading} ${styles.bigHeading}`}>Viimeinen Lohikäärmeisku</h1> <p className={`${globalStyles.subHeading} ${styles.subHeading}`}> Ensi-ilta 27.3. <br />@Manilla </p> <Link to="/speksi2019"> <div className={styles.ticketsLink}> Liput </div> </Link> </div> </HeroFullViewport> ); Hero.propTypes = { globalStyles: PropTypes.any, }; export default Hero; <file_sep>/src/client/components/Admin/Layout/AdminHeader.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import * as auth from '../../../Utils/Auth'; class AdminHeader extends Component { render() { return ( <div> <nav className="navbar navbar-toggleable-md navbar-inverse bg-inverse"> <button className="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon" /> </button> <Link className="navbar-brand" to="/admin"> HybridiSpeksi </Link> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav mr-auto"> <li className="nav-item"> <Link className="nav-link" to="/varaustenhallinta"> Varaustenhallinta </Link> </li> <li className="nav-item"> <Link className="nav-link" to="/ilmohallinta"> Ilmohallinta </Link> </li> <li className="nav-item"> {auth.hasRole(3) ? ( <Link className="nav-link" to="/produktionhallinta"> Produktio </Link> ) : ( <a className="nav-link disabled" to="#"> Produktio <i className="fa fa-lock" aria-hidden="true" /> </a> )} </li> <li className="nav-item"> {auth.hasRole(4) ? ( <Link className="nav-link" to="/jasenrekisteri"> Jäsenrekisteri </Link> ) : ( <a className="nav-link disabled" to="#"> Jäsenrekisteri <i className="fa fa-lock" aria-hidden="true" /> </a> )} </li> <li className="nav-item"> {auth.hasRole(5) ? ( <Link className="nav-link" to="/kayttajat"> Käyttäjät </Link> ) : ( <a className="nav-link disabled" to="#"> Käyttäjät <i className="fa fa-lock" aria-hidden="true" /> </a> )} </li> <li className="nav-item"> {auth.hasRole(5) ? ( <Link className="nav-link" to="/ohjaustiedot"> Ohjaustiedot </Link> ) : ( <a className="nav-link disabled" to="#"> Ohjaustiedot <i className="fa fa-lock" aria-hidden="true" /> </a> )} </li> <li className="nav-item"> {auth.hasRole(3) ? ( <Link className="nav-link" to="/palautteet"> Palautteet </Link> ) : ( <a className="nav-link disabled" to="#"> Palautteet <i className="fa fa-lock" aria-hidden="true" /> </a> )} </li> </ul> <span className="navbar-text"> <div onClick={auth.signOut}>Kirjaudu ulos</div> </span> </div> </nav> </div> ); } } export default AdminHeader; <file_sep>/src/client/components/Header/Header.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { NavLink } from 'react-router-dom'; import cuid from 'cuid'; import styles from './Header.css'; import mobile from './MobileHeader.css'; const NavItem = ({ site }) => ( <li className={styles.navItem}> <NavLink className={styles.navLink} to={site.url} activeClassName={styles.activeNavLink} > {site.name} </NavLink> </li> ); NavItem.propTypes = { site: PropTypes.object, }; const MobileNavItem = ({ site, handleClick }) => ( <NavLink className={`${mobile.navLink}`} to={site.url} onClick={handleClick} > {site.name} </NavLink> ); MobileNavItem.propTypes = { site: PropTypes.object, handleClick: PropTypes.func, }; class Header extends Component { constructor(props) { super(props); this.state = { sites: [ { url: '/speksi2019', name: 'Speksi 2019', }, { url: '/speksit', name: '<NAME>', }, { url: '/yhdistys', name: 'Yhdistys', }, { url: '/muutspeksit', name: '<NAME>', }, ], showMobileMenu: false, }; this.bindListeners = this.bindListeners.bind(this); this.handleClick = this.handleClick.bind(this); this.toggleMobileMenu = this.toggleMobileMenu.bind(this); this.hideMobileMenu = this.hideMobileMenu.bind(this); this.showMobileMenu = this.showMobileMenu.bind(this); } componentDidMount() { this.bindListeners(); } bindListeners() { $('.small-screen-link').on('click', () => { $('.navbar-collapse').collapse('hide'); }); $(window).scroll(() => { $('.top').css('opacity', 1 - $(window).scrollTop() / 200); const opacity = $('.top').css('opacity'); if (opacity <= 0) { $('.top').css('display', 'none'); } else { $('.top').css('display', 'flex'); } }); document.addEventListener('mousedown', this.handleClick, false); } handleClick(e) { if (this.state.showMobileMenu) { if (this.node.contains(e.target)) { return; } this.hideMobileMenu(); } } toggleMobileMenu() { this.setState(prevState => ({ showMobileMenu: !prevState.showMobileMenu, })); } hideMobileMenu() { this.setState({ showMobileMenu: false, }); } showMobileMenu() { this.setState({ showMobileMenu: true, }); } render() { const { showMobileMenu } = this.state; let mobileMenuClasses; if (showMobileMenu) { mobileMenuClasses = `${mobile.mobileMenu} ${mobile.mobileMenuVisible}`; } else { mobileMenuClasses = `${mobile.mobileMenu} ${mobile.mobileMenuHidden}`; } return ( <div className={styles.navContainer + ' top'}> <div className={styles.content}> <div className={`${styles.brand}`}> <NavLink className={styles.brandLink} to="/">HybridiSpeksi</NavLink> </div> <ul className={styles.navItems}> {this.state.sites.map(site => ( <NavItem key={cuid()} site={site} /> ))} </ul> {/* eslint-disable */} <div className={mobile.mobileMenuContainer} ref={node => this.node = node}> {/* eslint-enable */} <button className={mobile.mobileMenuIcon} onClick={() => this.toggleMobileMenu()} aria-label="Avaa mobiilimenu"> <i className="fa fa-bars" /> </button> <div className={mobileMenuClasses}> {this.state.sites.map(site => ( <MobileNavItem key={cuid()} site={site} handleClick={() => this.hideMobileMenu()} /> ))} </div> </div> </div> </div> ); } } export default Header; <file_sep>/scripts/docker-push.sh #!/bin/bash . ./scripts/utils.sh push() { echo "pushing image ${DOCKER_IMAGE_NAME}" # Run docker with the provided arguments docker push "${DOCKER_IMAGE_NAME}" } push <file_sep>/webpack/prod.config.js /* ./webpack.config.js */ const path = require('path'); const combineLoaders = require('webpack-combine-loaders'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: './src/client/index.html', filename: 'index.html', inject: 'body', }); module.exports = { mode: 'production', entry: { polyfill: ['babel-polyfill', 'whatwg-fetch'], index: './src/client/index.js', }, output: { path: path.resolve(__dirname, '../src/dist'), filename: '[name].bundle.js', chunkFilename: '[name].bundle.js', }, resolve: { alias: { actions: path.resolve(__dirname, '../src/client/actions/'), reducers: path.resolve(__dirname, '../src/client/reducers'), utils: path.resolve(__dirname, '../src/client/Utils'), }, }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, loader: combineLoaders([ { loader: 'style-loader', }, { loader: 'css-loader', query: { modules: true, localIdentName: '[name]__[local]___[hash:base64:5]', }, }, ]), }, { test: /\.(png|jpg|gif|otf|ttf)$/, use: [ { loader: 'file-loader', options: { publicPath: 'assets/', }, }, ], }, ], }, optimization: { splitChunks: { cacheGroups: { // vendor chunk vendor: { test: /[\\/]node_modules[\\/](react|react-dom|redux|prop-types)[\\/]/, name: 'vendor', chunks: 'all', }, commons: { chunks: 'all', test: /node_modules/, }, }, }, }, plugins: [HtmlWebpackPluginConfig], }; <file_sep>/src/client/components/Speksi2018/Vahvistus.js import React, { Component } from 'react'; import Moment from 'react-moment'; import PropTypes from 'prop-types'; import ajax from './../../Utils/Ajax'; import styles from './Vahvistus.css'; class Vahvistus extends Component { constructor(props) { super(props); this.state = { fname: '', sname: '', email: '', pnumber: '', bookingId: '', esitys: {}, ticketCount: '', }; } componentDidMount() { $(window).scrollTop(0); ajax.sendGet('/getOneVarausById/' + this.props.params._id) .then((_data) => { this.setState({ fname: _data.data.booking.fname, sname: _data.data.booking.sname, email: _data.data.booking.email, pnumber: _data.data.booking.pnumber, bookingId: _data.data.booking.bookingId, esitys: _data.data.esitys, ticketCount: _data.data.booking.ncount + _data.data.booking.scount + _data.data.booking.ocount, }); console.log(_data); }) .catch((err) => { console.log(err); }); } render() { return ( <div className={'container-fluid ' + styles.container}> <div className={'row align-items-start justify-content-center ' + styles.header}> <div className="col-11 col-sm-11 col-xl-5"> <h1>Lipun ostaminen onnistui!</h1> <h5 className="">Tervetuloa katsomaan HybridiSpeksiä 2018!</h5><br /> <div className="row"> <div className="col-sm-12 col-12"> <h4>Varauksesi tiedot:</h4> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Esitys:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.esitys.name} klo <Moment format="HH.mm">{this.state.esitys.date}</Moment> </p> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Nimi:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.fname} {this.state.sname}</p> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Puhelin:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.pnumber}</p> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Sähköposti:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.email}</p> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Lippujen määrä:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.ticketCount} kpl</p> </div> </div> <div className="row"> <div className="col-sm-4 col-4"> <p><i>Varausnumero:</i></p> </div> <div className="col-sm-6 col-8"> <p>{this.state.bookingId}</p> </div> </div> <br /> </div> <div className="col-9 col-sm-8 col-md-6 col-lg-6 col-xl-4"> <img src="/assets/images/logo_lapinak_valk.png" /> </div> </div> <div className={'row justify-content-center ' + styles.content}> <div className="col-sm-8 col-12"> <h2>Ohjeita jatkoon</h2> <ol> <li>Tarkista varauksesi tiedot.</li> <li>Sait sähköpostiisi varausnumeron, jota näyttämällä pääset HybridiSpeksi 2018 -näytökseen. </li> <li>Jos sinulla on kysyttävää tai tiedoissasi oli virhe, ota yhteyttä <EMAIL>. </li> <li>Nähdään teatterilla!</li> </ol> </div> </div> </div> ); } } export default Vahvistus; Vahvistus.propTypes = { params: PropTypes.object, }; <file_sep>/src/client/components/PageHero/PageHero.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './PageHero.css'; const PageHero = ({ title, subTitle }) => ( <div className={styles.heroContainer}> <div className={styles.mainTitleContainer}> <h1 className={styles.mainTitle}>{title}</h1> </div> {subTitle ? ( <div className={styles.subTitleContainer}> <h2 className={styles.subTitle}>{subTitle}</h2> </div> ) : ( null )} </div> ); PageHero.propTypes = { title: PropTypes.string, subTitle: PropTypes.string, }; export default PageHero; <file_sep>/src/client/components/Footer/SomeIcons.js import React from 'react'; import styles from './Footer.css'; const SomeIcons = () => ( <div className={styles.someIcons}> <div> <a href="https://www.facebook.com/HybridiSpeksi/"><img src="/assets/images/facebook.svg" className={styles.link} /></a> </div> <div> <a href="https://www.instagram.com/hybridispeksi/"><img src="/assets/images/instagram.svg" className={styles.link} /></a> </div> <div> <a href="https://www.youtube.com/channel/UCVkhBQHSqKtwC5X7qXe6HSg"><img src="/assets/images/youtube.svg" className={styles.link} /></a> </div> </div> ); export default SomeIcons; <file_sep>/src/client/components/Speksi2019/SpeksiHero.js import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import styles from './SpeksiHero.css'; const Instructions = () => ( <div className={styles.instructionsContent}> <h3>Toimi näin</h3> <ol className={`${styles.instructions_list}`}> <li>Valitse haluamasi näytös</li> <li>Täytä tietosi</li> <li>Tarkista, että täyttämäsi tiedot ovat oikein</li> <li>Sinut ohjataan Paytrailin maksupalveluun</li> </ol> </div> ); const Hero = ({ ticketSaleMessage, ticketSaleOpen }) => ( <div className={styles.container}> <div className={styles.headerTexts}> <h1 className={`${styles.bigsubHeading}`}>Hybridispeksi 2019</h1> <h1 className={`${styles.bigHeading}`}>Viimeinen Lohikäärmeisku</h1> <p className={`${styles.subHeading}`}> Lipunmyynti aukeaa keskiviikkona 27.2. </p> </div> <div className={`${styles.instructionsContainer}`}> <div className={styles.instructions}> <h4 className={styles.ticketSaleMessage}><i>{ticketSaleMessage}</i></h4> {ticketSaleOpen ? <Instructions /> : null} <p>Lippuhinnat 16 € / 14 € opiskelija /12 € ryhmä. Kannatuslippu 25 €.</p> <p>Ryhmävaraukset (väh. 8 hlö) sekä ongelmatilanteen sattuessa ota yhteyttä sähköpostilla <EMAIL>.</p> <p>Näytöksen kesto on noin 2,5 h, johon sisältyy 20 min puoliaika. Näytökset Manilla-teatterilla osoitteessa Itäinen Rantakatu 64b, 20810 Turku</p> </div> </div> </div> ); Hero.propTypes = { ticketSaleMessage: PropTypes.string, ticketSaleOpen: PropTypes.bool, }; const mapStateToProps = state => ({ ticketSaleMessage: state.bookingManagement.ticketSaleMessage, ticketSaleOpen: state.bookingManagement.ticketSaleOpen, }); const mapDispatchToProps = dispatch => ({ }); export default connect(mapStateToProps, mapDispatchToProps)(Hero); <file_sep>/src/client/components/Speksi2019/Confirm.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import styles from './Confirm.css'; import pagestyles from './Speksi2019.css'; import * as actions from 'actions/bookingActions'; class Confirm extends Component { render() { const { booking, selectedShow, prevState, submitBooking, showPage, prices, } = this.props; const { normalPrice, discountPrice } = prices; const countPrice = () => { const { normalCount, discountCount, specialPriceCount, specialPrice, } = booking; return Number(normalCount) * Number(normalPrice) + Number(discountCount) * Number(discountPrice) + Number(specialPriceCount) * Number(specialPrice); }; return ( <div className={`${styles.container} ${!showPage ? pagestyles.hidden : ''}`}> <div className={styles.column}> <h2>Valittu näytös</h2> <div className={styles.content}> <h3>{selectedShow.nameLong}</h3> </div> </div> <div className={styles.column}> <h2>Yhteystiedot</h2> <div className={styles.content}> <div className={styles.infoGroup}> <p className={styles.infoLabel}>Etunimi</p> <p className={`${styles.infoInput}`}>{booking.ContactInfo.fname}</p> </div> <div className={styles.infoGroup}> <p className={`${styles.infoLabel}`}>Sukunimi</p> <p className={`${styles.infoInput}`}>{booking.ContactInfo.lname}</p> </div> <div className={`${styles.infoGroup} ${styles.infoEmail}`}> <p className={`${styles.infoLabel}`}>Sähköposti</p> <p className={`${styles.infoInput}`}>{booking.ContactInfo.email}</p> </div> <div className={`${styles.infoGroup} ${styles.infoPnumber}`}> <p className={`${styles.infoLabel}`}>Puhelinnumero</p> <p className={`${styles.infoInput}`}>{booking.ContactInfo.pnumber}</p> </div> </div> <h2>Liput</h2> <div className={styles.content}> <div className={styles.infoGroup}> <p className={`${styles.infoLabel}`}>Normaali (16 €)</p> <p className={`${styles.infoInput}`}>{booking.normalCount} kpl</p> </div> <div className={styles.infoGroup}> <p className={`${styles.infoLabel}`}>Alennus (14 €)</p> <p className={`${styles.infoInput}`}>{booking.discountCount} kpl</p> </div> <div className={styles.infoGroup}> <p className={`${styles.infoLabel}`}>Hinta yhteensä</p> <p className={`${styles.infoInput}`}>{countPrice()} €</p> </div> <div className={`${styles.infoGroup} ${styles.infoArea}`}> <p className={`${styles.infoLabel}`}>Lisätietoja</p> <p className={`${styles.infoInput}`}>{booking.additionalInfo}</p> </div> </div> <div className={pagestyles.buttonContainer}> <button type="button" onClick={prevState} className={`${pagestyles.buttonNext}`}>Edellinen</button> <button type="button" onClick={() => submitBooking(booking)} className={`${pagestyles.buttonNext}`}>Siirry maksamaan</button> </div> <div className={styles.paytrailInfo}> <p> Maksunvälityspalvelun toteuttajana ja maksupalveluntarjoajana toimii Paytrail Oyj (2122839-7) yhteistyössä suomalaisten pankkien ja luottolaitosten kanssa. Paytrail Oyj näkyy maksun saajana tiliotteella tai korttilaskulla ja välittää maksun kauppiaalle. Paytrail Oyj:llä on maksulaitoksen toimilupa. Reklamaatiotapauksissa pyydämme ottamaan ensisijaisesti yhteyttä tuotteen toimittajaan. </p> <p> Paytrail Oyj, y-tunnus: 2122839-7<br /> Innova 2<br /> Lutakonaukio 7<br /> 40100 Jyväskylä<br /> Puhelin: 0207 181830<br /> www.paytrail.com </p> <h4>Verkkopankit</h4> <p> Verkkopankkimaksamiseen liittyvän maksunvälityspalvelun toteuttaa Paytrail Oyj (2122839-7) yhteistyössä suomalaisten pankkien ja luottolaitosten kanssa. Käyttäjän kannalta palvelu toimii aivan kuten perinteinen verkkomaksaminenkin. </p> </div> </div> </div> ); } } Confirm.propTypes = { booking: PropTypes.object, selectedShow: PropTypes.object, prevState: PropTypes.func, submitBooking: PropTypes.func, showPage: PropTypes.bool, prices: PropTypes.object, }; const mapStateToProps = state => ({ booking: state.bookingManagement.selectedBooking, selectedShow: state.bookingManagement.selectedShow, prices: state.bookingManagement.prices, }); const mapDispatchToProps = dispatch => ({ submitBooking: booking => dispatch(actions.submitBooking(booking)), }); export default connect(mapStateToProps, mapDispatchToProps)(Confirm); <file_sep>/src/services/bookingService.js const uuid = require('uuid/v4'); const transaction = require('sequelize').transaction; const Booking = require('../../models').Booking; const Show = require('../../models').Show; const ContactInfo = require('../../models').ContactInfo; const PaymentMethod = require('../../models').PaymentMethod; const showService = require('./showService'); const bookingUtils = require('../utils/bookingUtils'); const generateTag = () => { let id = ''; const letters = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'; for (let i = 0; i < 5; i++) { id += letters.charAt(Math.floor(Math.random() * letters.length)); } return id; }; const checkIfSpace = (show, booking) => { if (showService.countBookings(show) + bookingUtils.getTotalCount(booking) > show.get('limit')) { throw new Error('Esityksessä ei ole tarpeeksi tilaa'); } }; module.exports = { createBooking: async ( showId, fname, lname, email, pnumber, normalCount, discountCount, specialPriceCount, specialPrice, paid, paymentMethodId, additionalInfo, ) => { try { const t = await transaction; const show = await Show.findOne( { include: [{ model: Booking, as: 'Bookings' }], where: { id: showId }, }, { transaction: t }, ); checkIfSpace(show, { normalCount, discountCount, specialPriceCount }); const paymentMethod = await PaymentMethod.findOne({ where: { id: paymentMethodId } }, { transaction: t }); const contactInfo = await ContactInfo.create({ id: uuid(), fname, lname, email, pnumber, }, { transaction: t }); const booking = await Booking.create({ id: uuid(), normalCount, discountCount, specialPriceCount, specialPrice, tag: generateTag(), redeemed: false, paid, additionalInfo, }, { transaction: t }); booking.setShow(show, { transaction: t }); booking.setContactInfo(contactInfo, { transaction: t }); booking.setPaymentMethod(paymentMethod, { transaction: t }); await booking.save(); return booking; } catch (e) { console.log(e); throw e; } }, getPaymentMethodByCode: async (code) => { try { const paymentMethod = await PaymentMethod.findOne({ where: { code }, }); return paymentMethod; } catch (e) { console.log(e); throw e; } }, updateBooking: async ( id, showId, fname, lname, email, pnumber, normalCount, discountCount, specialPriceCount, specialPrice, additionalInfo, paid, paymentMethodId, ) => { try { const booking = await Booking.findOne({ where: { id }, include: { model: ContactInfo } }); if (booking) { await booking.update({ showId, normalCount, discountCount, specialPriceCount, specialPrice, additionalInfo, paid, paymentMethodId, }); const contactInfo = booking.get('ContactInfo'); contactInfo.update({ fname, lname, email, pnumber, }); } else { throw new Error('No booking found for id'); } return booking; } catch (e) { console.log(e); throw e; } }, deleteBooking: async (bookingId) => { try { const booking = await Booking.findOne({ where: { id: bookingId } }); await ContactInfo.destroy({ where: { id: booking.get('contactInfoId') }, }); await Booking.destr; } catch (e) { console.log(e); throw e; } }, getAllBookings: async () => { try { const bookings = await Booking.findAll({ include: [{ model: ContactInfo }], }); return bookings; } catch (e) { console.log(e); throw e; } }, getBookingsByShowId: async (showId) => { try { const bookings = await Booking.findAll({ where: { showId }, include: { model: ContactInfo }, order: [['createdAt', 'DESC']], }); return bookings; } catch (e) { console.log(e); throw e; } }, findById: async (id) => { try { const booking = await Booking.findOne({ where: { id }, include: [{ model: ContactInfo }, { model: Show }], }); return booking; } catch (e) { console.log(e); throw e; } }, getPaymentMethods: async () => { try { const methods = await PaymentMethod.findAll(); return methods; } catch (e) { console.log(e); throw e; } }, redeem: async (id) => { try { const booking = await Booking.findOne({ where: { id }, include: [{ model: ContactInfo }, { model: Show }], }); booking.set('redeemed', true); await booking.save(); return booking; } catch (e) { console.log(e); throw e; } }, }; <file_sep>/models/enrollment.js module.exports = (sequelize, DataTypes) => { const Enrollment = sequelize.define('Enrollment', { presentGreeting: DataTypes.BOOLEAN, greetingOrganization: DataTypes.STRING, avec: DataTypes.STRING, partyExpectation: DataTypes.STRING, menu: DataTypes.STRING, diet: DataTypes.STRING, alcohol: DataTypes.BOOLEAN, sillis: DataTypes.BOOLEAN, memberOfSpeksi: DataTypes.BOOLEAN, paid: DataTypes.BOOLEAN, additional: DataTypes.STRING, }, {}); Enrollment.associate = (models) => { Enrollment.belongsTo(models.ContactInfo, { foreignKey: 'contactInfoId', onDelete: 'CASCADE', }); Enrollment.belongsTo(models.Event, { foreignKey: 'eventId', onDelete: 'CASCADE', }); }; return Enrollment; }; <file_sep>/src/services/enrollmentService.js const uuid = require('uuid/v4'); const transaction = require('sequelize').transaction; const Event = require('../../models').Event; const Enrollment = require('../../models').Enrollment; const ContactInfoModel = require('../../models').ContactInfo; module.exports = { createEnrollment: async ({ ContactInfo, presentGreeting, greetingOrganization, avec, partyExpectation, menu, diet, alcohol, sillis, memberOfSpeksi, paid, additional, eventId, }) => { try { const { fname, lname, email, pnumber, } = ContactInfo; const t = await transaction; const event = await Event.findOne({ where: { id: eventId } }, { transaction: t }); const contactInfo = await ContactInfoModel.create({ id: uuid(), fname, lname, email, pnumber, }, { transaction: t }); const enrollment = await Enrollment.create({ id: uuid(), presentGreeting, greetingOrganization, avec, partyExpectation, menu, diet, alcohol, sillis, memberOfSpeksi, paid, additional, eventId: event.get('id'), contactInfoId: contactInfo.get('id'), }); enrollment.set('Event', event); enrollment.set('ContactInfo', contactInfo); await enrollment.save({ transaction: t }); return enrollment; } catch (e) { console.log(e); throw e; } }, deleteEnrollment: async (id) => { try { const enrollment = await Enrollment.findOne({ where: { id } }); await ContactInfoModel.destroy({ where: { id: enrollment.get('contactInfoId') } }); } catch (e) { console.log(e); throw e; } }, getEnrollmentsByEventId: async (eventId) => { try { const enrollments = await Enrollment.findAll({ include: [{ model: ContactInfoModel, as: 'ContactInfo' }], where: { eventId }, order: [['createdAt', 'ASC']], }); return enrollments; } catch (e) { console.log(e); throw e; } }, updateEnrollment: async ({ id, ContactInfo, presentGreeting, greetingOrganization, avec, partyExpectation, menu, diet, alcohol, sillis, memberOfSpeksi, paid, additional, }) => { const { fname, lname, email, pnumber, } = ContactInfo; try { const t = await transaction; const enrollment = await Enrollment.findOne({ where: { id } }); const contactInfo = await ContactInfoModel.findOne({ where: { id: enrollment.get('contactInfoId') } }); console.log(id); console.log(enrollment); contactInfo.set('fname', fname); contactInfo.set('lname', lname); contactInfo.set('email', email); contactInfo.set('pnumber', pnumber); await contactInfo.save({ transaction: t }); enrollment.set('presentGreeting', presentGreeting); enrollment.set('greetingOrganization', greetingOrganization); enrollment.set('avec', avec); enrollment.set('partyExpectation', partyExpectation); enrollment.set('menu', menu); enrollment.set('diet', diet); enrollment.set('alcohol', alcohol); enrollment.set('sillis', sillis); enrollment.set('memberOfSpeksi', memberOfSpeksi); enrollment.set('paid', paid); enrollment.set('additional', additional); await enrollment.save({ transaction: t }); return enrollment; } catch (e) { console.log(e); throw e; } }, findById: async (id) => { try { const enrollment = await Enrollment.findOne({ whrer: { id }, include: [{ model: ContactInfoModel, as: 'ContactInfo' }], }); return enrollment; } catch (e) { console.log(e); throw e; } }, getEnrollmentCountByEventId: async (id) => { try { const count = Enrollment.count({ where: { eventId: id }, }); return count; } catch (e) { console.log(e); throw e; } }, }; <file_sep>/src/services/showService.js const uuid = require('uuid/v4'); const Booking = require('../../models').Booking; const Show = require('../../models').Show; const self = { createShow: async ( date, limit, nameLong, nameShort, ) => { try { const show = await Show.create({ id: uuid(), date, limit, nameLong, nameShort, }); return show; } catch (e) { console.log(e); throw e; } }, updateShow: async ( id, date, limit, nameLong, nameShort, ) => { try { const show = await Show.findOne({ where: { id } }); if (show) { await show.update({ date, limit, nameLong, nameShort, }); } else { throw new Error('No show found for id'); } return show; } catch (e) { console.log(e); throw e; } }, deleteShow: async (id) => { try { await Show.destroy({ where: { id }, }); return; } catch (e) { console.log(e); throw e; } }, getShows: async () => { try { const shows = await Show.findAll({ include: [ { model: Booking, as: 'Bookings', attributes: ['normalCount', 'discountCount', 'specialPriceCount'] }, ], order: [['date', 'ASC']], }); const showsWithBookingCounts = shows.map((show) => { const showJson = show.toJSON(); showJson.bookingCount = self.countBookings(show); showJson.Bookings = null; return showJson; }); return showsWithBookingCounts; } catch (e) { console.log(e); throw e; } }, findById: async (id) => { try { const show = await Show.findOne({ where: { id } }); return show; } catch (e) { console.log(e); throw e; } }, countBookings: (show) => { const bookings = show.get('Bookings'); const totalCount = bookings.reduce((count, booking) => { return count + booking.get('normalCount') + booking.get('discountCount') + booking.get('specialPriceCount'); }, 0); return totalCount; }, }; module.exports = self; <file_sep>/src/api/esitykset/varaukset.js const Varaus = require('../../schema/varaus-model'); const Esitys = require('../../schema/esitys-model'); const mailer = require('../../utils/mailer'); const payment = require('../../utils/payments'); module.exports = { getAllByShowId: async (req, res) => { try { const _data = await Varaus.find({ esitysId: req.params._id, year: 2018 }); res.json({ success: true, data: _data }); } catch (err) { res.json({ success: false, data: err }); } }, getAllList: async (req, res) => { try { const _data = await Varaus.find({ year: 2018 }); res.json({ success: true, data: _data }); } catch (err) { res.json({ success: false, data: err }); } }, getOneById: async (req, res) => { try { let booking = await Varaus.findOne({ _id: req.params._id }); const esitys = await Esitys.findOne({ _id: booking.esitysId }); booking = { booking, esitys }; res.json({ success: true, data: booking }); } catch (err) { res.json({ success: false, data: err }); } }, createNewAdmin: (req, res) => { const booking = req.body; validateAdmin(booking) .then(() => tryIfSpace(booking)) .then(() => { booking.bookingId = generateId(); const bookingObj = new Varaus({ fname: booking.fname, sname: booking.sname, email: booking.email, pnumber: booking.pnumber, scount: booking.scount || 0, ncount: booking.ncount || 0, ocount: booking.ocount || 0, oprice: booking.oprice || 0, paymentMethod: booking.paymentMethod, paid: booking.paid, esitysId: booking.esitysId, additional: booking.additional, bookingId: booking.bookingId, year: 2018, }); return bookingObj.save(); }) .then(_booking => Esitys.findOne({ _id: booking.esitysId })) .then((_esitys) => { booking.esitys = _esitys; if (booking.sendemail === 'true') { mailer.sendTicket(booking); } }) .then((_booking) => { res.json({ success: true, data: _booking }); }) .catch((err) => { if (err.code) { res.json({ success: false, data: err.message }, err.code); } else { console.log(err); } }); }, update: (req, res) => { const varaus = req.body; validateAdmin(varaus) .then(() => { Varaus.findByIdAndUpdate(varaus._id, varaus) .then((_varaus) => { res.json({ success: true, data: 'Varaus päivitetty.' }); }) .catch((err) => { res.json({ success: false, data: err }); }); }) .catch((err) => { res.json({ success: false, data: err.message }, err.code); }); }, remove: async (req, res) => { try { await Varaus.remove({ _id: req.params._id }) res.json({ success: true, data: 'Varaus poistettu' }); } catch (err) { res.json({ success: false, data: 'Varausta ei voitu poistaa' }); } }, redeem: (req, res) => { const varaus = req.body; Varaus.findByIdAndUpdate(varaus._id, varaus) .then((_varaus) => { res.json({ success: true, data: 'Varaus merkitty noudetuksi.' }); console.log(varaus) }) .catch((err) => { res.json({ success: false, data: err}) }) }, createPayment: (req, res) => { const booking = req.body; validate(booking) .then(() => tryIfSpace(booking)) .then(() => { booking.bookingId = generateId(); const bookingObj = new Varaus({ fname: booking.fname, sname: booking.sname, email: booking.email, pnumber: booking.pnumber, scount: booking.scount || 0, ncount: booking.ncount || 0, ocount: booking.ocount || 0, oprice: 25, paymentMethod: 2, paid: false, esitysId: booking.esitysId, additional: booking.additional, bookingId: booking.bookingId, year: 2018, }); return bookingObj.save(); }) .then((_booking) => { console.log('Created booking for ' + _booking.fname + ' ' + _booking.sname); return payment.createPayment(_booking); }) .then((payment) => { console.log(payment); res.json({ success: true, data: payment }); }) .catch((err) => { if (err.code) { res.json({ success: false, data: err.message }, err.code); } else { console.log(err); res.json({ success: false, data: 'Palvelimella tapahtui virhe. Yritä myöhemmin uudelleen' }, 500); } }); }, sendConfirmationMail: (req, res) => { let booking; Varaus.findOne({ _id: req.params._id }) .then((_booking) => { booking = _booking; return Esitys.findOne({ _id: _booking.esitysId }); }) .then((_esitys) => { booking.esitys = _esitys; return mailer.sendTicket(booking); }) .then(() => { res.json({ success: true, data: 'Vahvistussähköposti lähetetty' }); }) .catch((err) => { if (err.code) { res.json({ success: false, data: err.message }, err.code); } else { console.log(err); } res.json({ success: false, data: 'Palvelimella tapahtui virhe. Yritä myöhemmin uudelleen' }, 500); }); }, }; function validateAdmin(booking) { const promise = new Promise((resolve, reject) => { if (isEmptyField(booking.email)) { reject({ code: 400, message: 'Sähköposti on pakollinen tieto' }); } else if (!isValidEmail(booking.email)) { reject({ code: 400, message: 'Virheellinen sähköpostiosoite' }); } else if (booking.ocount > 0 && booking.oprice < 10 && isEmptyField(booking.additional)) { reject({ code: 400, message: 'Mikäli erikoislippujen hinta on alle 10€, on syy selvitettävä lisätietoihin' }); } else { resolve(); } }); return promise; } function validate(booking) { const promise = new Promise((resolve, reject) => { if (isEmptyField(booking.fname) || isEmptyField(booking.sname) || isEmptyField(booking.email)) { reject({ code: 400, message: 'Täytä kaikki puuttuvat kentät' }); } else if (!isValidEmail(booking.email)) { reject({ code: 400, message: 'Virheellinen sähköposti' }); } else if (isEmptyField(booking.esitysId)) { reject({ code: 400, message: 'Valitse esitys' }); } else if (booking.scount + booking.ncount + booking.ocount == 0) { reject({ code: 400, message: 'Varauksessa oltava vähintään yksi lippu' }); } else { resolve(); } }); return promise; } function isValidEmail(email) { const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return regex.test(email); } function isEmptyField(field) { return !field || field === ''; } function generateId() { let id = ''; const possible = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'; for (let i = 0; i < 5; i++) { id += possible.charAt(Math.floor(Math.random() * possible.length)); } return id; } function tryIfSpace(booking) { return new Promise((resolve, reject) => { let totalCountInShow = 0; Varaus.find({ esitysId: booking.esitysId, year: 2018 }) .then((data) => { data.map((b) => { totalCountInShow += getTotalCount(b); }); if (totalCountInShow + getTotalCount(booking) > 130) { console.log('reject'); reject({ code: 400, message: 'Esityksessä ei ole tarpeeksi paikkoja jäljellä' }); } else { resolve(booking); } }); }); } function getTotalCount(booking) { return Number(booking.ncount) + Number(booking.scount) + Number(booking.ocount); } <file_sep>/src/client/reducers/ajaxReducer.js import { actions } from '../actions/ajaxActions'; const initialState = { loading: false, ongoingRequests: [], errors: [], warnings: [], }; const ajax = (state = initialState, action) => { switch (action.type) { case actions.AJAX_LOADING: return { ...state, loading: true, ongoingRequests: [...state.ongoingRequests, action.payload], }; case actions.AJAX_SUCCESS: return { ...state, ongoingRequests: [...state.ongoingRequests.filter(requestId => requestId !== action.payload)], loading: state.ongoingRequests.length > 0, }; case actions.AJAX_FAILURE: return { ...state, ongoingRequests: [...state.ongoingRequests.filter(requestId => requestId !== action.id)], loading: state.ongoingRequests.length > 0, errors: [...state.errors, action.error], }; case actions.AJAX_CLEAR_ERRORS: return { ...state, errors: [], }; default: return state; } }; export default ajax; <file_sep>/src/client/components/Speksi2019/Shows.js import React from 'react'; import cuid from 'cuid'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Moment from 'react-moment'; import * as moment from 'moment'; import styles from './Shows.css'; import pagestyles from './Speksi2019.css'; import * as actions from 'actions/bookingActions'; const Show = ({ show, handleClick, selected, ticketSaleOpen, }) => ( <div className={`${styles.showRow} ${selected ? styles.selected : ''} ${!ticketSaleOpen || show.bookingCount === show.limit || moment() > moment(show.date) ? styles.disabled : ''} `} onClick={() => handleClick(show)}> <h3 className={`${styles.showDate}`}> <div><Moment format="DD.MM.">{show.date}</Moment></div> <div>klo <Moment format="HH.mm">{show.date}</Moment> </div> </h3> <p className={`${styles.showDay}`}><Moment format="dddd" locale="fi">{show.date}</Moment></p> <div className={`${styles.showTime}`}> <div>{show.nameShort}</div> <div className={`${styles.showSpace}`}> {show.bookingCount >= 100 ? show.bookingCount === show.limit ? <span className={styles.soldOut}>LOPPUUNMYYTY</span> : <span className={styles.almostSoldOut}>MELKEIN TÄYNNÄ</span> : <span className={styles.gotSpace}>TILAA</span>} </div> </div> </div> ); Show.propTypes = { show: PropTypes.object, handleClick: PropTypes.func, selected: PropTypes.bool, ticketSaleOpen: PropTypes.bool, }; const ShowsList = ({ shows, selectedShow, select, nextState, showPage, ticketSaleOpen, fetchTicketSaleOpen, }) => { const handleClick = (show) => { if (ticketSaleOpen && show.bookingCount !== show.limit) { select(show); } }; fetchTicketSaleOpen(); const disableNext = selectedShow.id === ''; return ( <div className={`${styles.container} ${!showPage ? pagestyles.hidden : ''}`} > <h2 className={styles.showHeader}>Valitse näytös</h2> {shows.map((show) => { return <Show ticketSaleOpen={ticketSaleOpen} show={show} key={cuid()} handleClick={handleClick} selected={show.id === selectedShow.id} />; })} <div className={pagestyles.buttonContainer}> <button onClick={nextState} className={`${pagestyles.buttonNext} ${disableNext ? pagestyles.disabled : ''}`} disabled={disableNext}>Seuraava</button> </div> </div> ); }; ShowsList.propTypes = { shows: PropTypes.array, select: PropTypes.func, selectedShow: PropTypes.object, nextState: PropTypes.func, fetchTicketSaleOpen: PropTypes.func, ticketSaleOpen: PropTypes.bool, }; const mapStateToProps = state => ({ shows: state.bookingManagement.shows, selectedShow: state.bookingManagement.selectedShow, ticketSaleOpen: state.bookingManagement.ticketSaleOpen, }); const mapDispatchToProps = dispatch => ({ select: show => dispatch(actions.selectShow(show)), fetchBookings: showId => dispatch(actions.fetchBookings(showId)), fetchTicketSaleOpen: () => dispatch(actions.fetchTicketSaleOpen()), }); export default connect(mapStateToProps, mapDispatchToProps)(ShowsList); <file_sep>/src/client/actions/loaderActions.js export const actions = { SHOW_LOADER: 'SHOW_LOADER', HIDE_LOADER: 'HIDE_LOADER', }; export function showLoader() { return { type: actions.SHOW_LOADER, }; } export function hideLoader() { return { type: actions.HIDE_LOADER, }; } <file_sep>/models/userrole.js module.exports = (sequelize, DataTypes) => { const UserRole = sequelize.define('UserRole', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, }, {}); UserRole.associate = (models) => { UserRole.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE', }); }; return UserRole; }; <file_sep>/src/client/components/Home/JumboLinks.js import React from 'react'; import { Link } from 'react-router-dom'; import styles from './Home.css'; const JumboLinks = () => ( <div className={styles.jumboLinks}> <Link className={styles.internallink} to="/speksit"> <p className={'material-icons ' + styles.linkicon}>history</p> <h3>Aiemmat speksit</h3> <p className="">HybridiSpeksi on järjestetty jo vuodesta 2015! Lue lisää täältä.</p> </Link> {/* <div className="col-sm-3 align-items-center"> <Link to="/galleria"> <p className={"material-icons " + styles.linkicon}>insert_photo</p> <h3>Kuvagalleria</h3> <p className="">Speksiä tehdessä on aina hyvä fiilis! Kuvat kertovat enemmän kuin tuhat sanaa ja täällä niitä kuvia voi katsella!</p> </Link> </div> */} <Link className={styles.internallink} to="/yhdistys"> <p className={'material-icons ' + styles.linkicon}>face</p> <h3>Yhdistys</h3> <p>Kuka tekee speksissä mitäkin? Lavan tapahtumien l isäksi projektissa on suuri joukko muita tiimejä ja tiimiläisiä. Yhdistys-sivulta löydät yhteystietojen lisäksi hallituksen ja tuotantotiimin kokoonpanot. </p> </Link> <Link className={styles.internallink} to="/muutspeksit"> <p className={'material-icons ' + styles.linkicon}>local_play</p> <h3>Turun muut speksit</h3> <p className="">Speksi on opiskelijateatteria parhaimmillaan! Tutustu Turun muihin spekseihin täältä.</p> </Link> </div> ); export default JumboLinks; <file_sep>/scripts/docker-login.sh docker login --username=$DOCKER_USER --password=$DOCKER_PASS <file_sep>/src/api/events/enrollmentController.js const enrollmentService = require('../../services/enrollmentService'); const eventService = require('../../services/eventService'); const validator = require('../../utils/validation'); const mailer = require('../../utils/mailer'); const validateEnrollment = (enrollment) => { const { fname, lname, email, pnumber, } = enrollment.ContactInfo; if (validator.isEmptyOrNull(fname)) { throw new Error('Etunimi on pakollinen'); } if (validator.isEmptyOrNull(lname)) { throw new Error('Sukunimi on pakollinen'); } if (validator.isEmptyOrNull(email)) { throw new Error('Sähköposti on pakollinen'); } if (!validator.isValidEmail(email)) { throw new Error('Sähköposti on virheellinen'); } }; module.exports = { createEnrollment: async (req, res) => { try { const { eventId } = req.body; const enrollmentCount = await enrollmentService.getEnrollmentCountByEventId(eventId); const event = await eventService.getEventById(eventId); const limit = event.get('limit'); if (!event.get('registrationOpen')) { throw new Error('Tapahtuman ilmoittautuminen on suljettu.'); } if (enrollmentCount >= limit) { throw new Error('Tapahtuma on täynnä eikä siihen voi enää ilmoittautua.'); } validateEnrollment(req.body); mailer.sendVujuConfirmation(req.body.ContactInfo.email); const enrollment = await enrollmentService.createEnrollment(req.body); res.json({ success: true, data: enrollment }); } catch (e) { res.json({ success: false, message: e.message }); } }, deleteEnrollment: async (req, res) => { try { const id = req.params.enrollmentId; await enrollmentService.deleteEnrollment(id); res.json({ success: true }); } catch (e) { res.json({ success: false, message: e.message }); } }, updateEnrollment: async (req, res) => { try { validateEnrollment(req.body); const newObject = { ...req.body, id: req.params.enrollmentId }; console.log(newObject); const enrollemnt = await enrollmentService.updateEnrollment(newObject); res.json({ success: true, data: enrollemnt }); } catch (e) { res.json({ success: false, message: e.message }); } }, getEnrollmentsByEventId: async (req, res) => { try { const eventId = req.params.eventId; const enrollments = await enrollmentService.getEnrollmentsByEventId(eventId); res.json({ success: true, data: enrollments }); } catch (e) { res.json({ success: true, message: e.message }); } }, }; <file_sep>/src/client/components/Admin/Ohjaustiedot/List.js import React, { Component } from 'react' import styles from './Ohjaustiedot.css'; class List extends Component { render() { return ( <div className={styles.table}> <table className="table table-inverse table-striped"> <thead> <tr> <th>Key</th> <th>Value</th> <th>Name</th> </tr> </thead> <tbody> {this.props.ohjaustiedot.map((o, i) => { return ( <tr key={i} onClick={() => this.props.valitseOhjaustieto(o)}> <td>{o.key}</td> <td>{o.value}</td> <td>{o.name}</td> </tr> ) })} </tbody> </table> </div> ) } } export default List<file_sep>/src/client/components/Admin/Jasenrekisteri/Jasentiedot.js import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Moment from 'react-moment'; import { Text, Dropdown } from '../../../Utils/Form'; import { updateSelectedMember, clearSelectedMember, saveMember, approveMember, deleteMember } from '../../../actions/jasenrekisteriActions'; const Jasentiedot = ({ member, update, clear, save, approve, remove, }) => { const handleDelete = () => { if(confirm('Poistetaanko jäsen rekisteristä? Toimintoa ei voi peruuttaa')) { remove(member); } }; return ( <div> <div className="row"> <div className="col"> <h1>Jäsentiedot</h1> <h3> {member.fname} {member.sname} </h3> </div> <div className="col text-right"> <a href="#" onClick={() => clear()} className="btn btn-default"> <i className="fa fa-times" aria-hidden="true" /> </a> </div> </div> <div className="row"> <div className="col"> <Text id="fname-input" name="fname" type="fname" onChange={e => update({ ...member, fname: e.target.value })} value={member.fname} placeholder="Etunimet" label="Etunimet" /> </div> <div className="col"> <Text id="lname-input" name="sname" type="text" onChange={e => update({ ...member, sname: e.target.value })} value={member.sname} placeholder="Sukunimi" label="Sukunimi" /> </div> </div> <div className="row"> <div className="col"> <Text id="email-input" name="email" type="email" onChange={e => update({ ...member, email: e.target.value })} value={member.email} placeholder="Sähköposti" label="Sähköposti" /> </div> <div className="col"> <Text id="hometown-input" name="hometown" type="text" onChange={e => update({ ...member, hometown: e.target.value })} value={member.hometown} placeholder="Kotikunta" label="Kotikunta" /> </div> </div> <div className="row"> <div className="col"> <Dropdown options={[ { name: 'TYYn jäsen', value: 'yes' }, { name: 'Ei TYYn jäsen', value: 'no' }, ]} selected={member.memberOfTyy ? 'yes' : 'no'} name="memberOfTyy" onChange={e => update({ ...member, memberOfTyy: e.target.value === 'yes' })} id="memberoftyy-dropdown" /> </div> </div> <div className="row"> <div className="col"> {member.updated ? ( <button onClick={() => save(member)} className="btn btn-primary"> Tallenna tiedot </button> ) : false} {!member.approved ? ( <button onClick={() => approve(member)} className="btn btn-primary"> Hyväksy jäseneksi </button> ) : ( <p> Hyväksytty jäseneksi{' '} <Moment format="DD.MM.YYYY">{member.approveDate}</Moment> </p> )} </div> </div> <div className="row"> <div className="col"> <button onClick={handleDelete} className="btn btn-danger">Poista rekisteristä</button> </div> </div> </div> ); } Jasentiedot.propTypes = { member: PropTypes.object, update: PropTypes.func, clear: PropTypes.func, save: PropTypes.func, approve: PropTypes.func, remove: PropTypes.func, }; const mapStateToProps = state => ({ member: state.jasenrekisteri.selectedMember, }); const mapDispatchToProps = dispatch => ({ update: member => dispatch(updateSelectedMember(member)), clear: () => dispatch(clearSelectedMember()), save: member => dispatch(saveMember(member)), approve: member => dispatch(approveMember(member)), remove: member => dispatch(deleteMember(member)), }); export default connect(mapStateToProps, mapDispatchToProps)(Jasentiedot); <file_sep>/src/client/components/Admin/Kayttajat/UserManagement.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { fetchUsers, fetchRoles, selectUser } from 'actions/userActions'; import UsersList from './UsersList'; import User from './User'; class UserManagement extends Component { componentDidMount() { this.props.fetchUsers(); this.props.fetchRoles(); } render() { return ( <div className="container-fluid"> <h1>Käyttäjät</h1> <div className="row"> <div className="col-sm-6"> <UsersList /> </div> <div className="col-sm-6"> {this.props.selectedUser.id ? ( <User kayttaja={this.props.selectedUser} /> ) : ''} </div> </div> </div> ); } } UserManagement.propTypes = { selectedUser: PropTypes.object, fetchUsers: PropTypes.func, fetchRoles: PropTypes.func, }; const mapStateToProps = state => ({ users: state.user.users, selectedUser: state.user.selectedUser, }); const mapDispatchToProps = dispatch => ({ fetchUsers: () => dispatch(fetchUsers()), fetchRoles: () => dispatch(fetchRoles()), selectUser: user => dispatch(selectUser(user)), }); export default connect(mapStateToProps, mapDispatchToProps)(UserManagement); <file_sep>/src/client/Utils/Ajax.js const URL_PREFIX = '/api'; module.exports = { /** * Send POST request * @param url * @param data, JSON * @param callback * @return promise */ async sendPost(url, data) { try { const res = await fetch(URL_PREFIX + url, { method: 'POST', headers: { Accept: 'application/json, text/plain', 'Content-Type': 'application/json', 'x-access-token': localStorage.getItem('jwt'), }, body: JSON.stringify(data), }); const json = await res.json(); return json; } catch (err) { throw new Error(err); } }, async sendGet(url) { try { const res = await fetch(URL_PREFIX + url, { method: 'GET', headers: { Accept: 'application/json, text/plain', 'Content-Type': 'application/json', 'x-access-token': localStorage.getItem('jwt'), }, }); const json = await res.json(); return json; } catch (err) { throw new Error(err); } }, async sendPut(url, data) { try { const res = await fetch(URL_PREFIX + url, { method: 'PUT', headers: { Accept: 'application/json, text/plain', 'Content-Type': 'application/json', 'x-access-token': localStorage.getItem('jwt'), }, body: JSON.stringify(data), }); const json = await res.json(); return json; } catch (err) { throw new Error(err); } }, async sendDelete(url) { try { const res = await fetch(URL_PREFIX + url, { method: 'DELETE', headers: { Accept: 'application/json, text/plain', 'Content-Type': 'application/json', 'x-access-token': localStorage.getItem('jwt'), }, }); const json = await res.json(); return json; } catch (err) { throw new Error(err); } }, }; <file_sep>/src/client/reducers/productionReducer.js import { actions } from 'actions/productionActions'; const initialState = { members: [], searchObject: { text: '', tehtava: '', jarjesto: '', }, selectedMember: { fname: '', lname: '', sname: '', email: '', pnumber: '', tehtavat: [], tuotannonMuistiinpanot: '', updated: false, }, }; const production = (state = initialState, action) => { switch (action.type) { case actions.RECEIVE_PRODUCTION: return { ...state, members: [...action.production], }; case actions.SELECT_MEMBER: return { ...state, selectedMember: { ...action.member, updated: false }, }; case actions.CLEAR_SELECTED_MEMBER: return { ...state, selectedMember: { ...initialState.selectedMember }, }; case actions.UPDATE_SELECTED_PRODUCTION_MEMBER: return { ...state, selectedMember: { ...action.member, updated: true }, }; case actions.UPDATE_SEARCH_OBJECT: return { ...state, searchObject: { ...action.searchObject }, }; default: return state; } }; export default production; const hasMemberUpdated = (originalMember, updatedMember) => { // TODO }; <file_sep>/src/client/components/Kalenteri/Kalenteri.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styles from './Kalenteri.css'; class Kalenteri extends Component { componentDidMount() { $(window).scrollTop(0); } render() { return ( <div className={'container-fluid ' + styles.container}> <div className={'row justify-content-center ' + styles.content_kalenteri}> <div className={'col-sm-12 col-xl-11 ' + styles.slogan}> <div className={'d-md-block ' + styles.slogan}> <div className="row justify-content-lg-center justify-content-center align-items-center"> <div className={'col-12 col-sm-10 col-md-9 ' + styles.rekry}><h2 className={styles.header}>Kalenteri</h2> <iframe className={styles.iframe} src="https://calendar.google.com/calendar/embed?showPrint=0&amp;showTabs=0&amp;showCalendars=0&amp;showTz=0&amp;height=600&amp;wkst=2&amp;hl=fi&amp;bgcolor=%23FFFFFF&amp;src=d3jpe3k88npq9f97ba26fi9u5c%40group.calendar.google.com&amp;color=%230F4B38&amp;ctz=Europe%2FHelsinki" frameborder="0" scrolling="no" /> </div> </div> </div> </div> </div> </div> ); } } export default Kalenteri; <file_sep>/src/client/components/Admin/Auth/Signupform.js import React, { Component } from 'react'; class Signupform extends Component { render() { return ( <div className="container"> <div className="row justify-content-center"> <div className="col-sm-auto"> <h3>Hae tunnuksia admin-paneeliin</h3> </div> </div> <div className="row justify-content-center"> <form onSubmit={this.props.handleSubmit} className="col-sm-5" name="signup"> <div className="form-group"> <label htmlFor="fnameInput">Etunimi</label> <input name="fname" type="text" onChange={this.props.handleChange} value={this.props.fname} className="form-control" id="fnameInput" placeholder="Etunimi" /> </div> <div className="form-group"> <label htmlFor="snameInput">Sukunimi</label> <input name="sname" type="text" onChange={this.props.handleChange} value={this.props.sname} className="form-control" id="snameInput" placeholder="Sukunimi" /> </div> <div className="form-group"> <label htmlFor="emailInput">Sähköposti</label> <input name="email" type="text" onChange={this.props.handleChange} value={this.props.email} className="form-control" id="emailInput" placeholder="Sähköpostiosoite" /> </div> <div className="form-group"> <label htmlFor="passwordInput">Salasana</label> <input name="password" type="password" onChange={this.props.handleChange} value={this.props.password} className="form-control" id="passwordInput" placeholder="Sal<PASSWORD>" /> </div> <div className="form-group"> <label htmlFor="passwordAgainInput">Salasana uudelleen</label> <input name="passwordAgain" type="password" onChange={this.props.handleChange} value={this.props.passwordAgain} className="form-control" id="passwordAgainInput" placeholder="Sal<PASSWORD> uudelleen" /> </div> <button className="btn btn-default" type="submit">Submit</button> <button inputMode="numeric" type="button" className="btn btn-default" onClick={this.props.handleChange} name="authState" value={0}>Minulla on jo tunnus, kirjaudu sisään</button> </form> </div> <div className="row justify-content-center"> <div className="col-sm-5"> <p>Saat tunnukset käyttöön kun ne on tuotannon toimesta hyväksytty</p> </div> </div> <div className="row justify-content-center"> <div className="col-sm-5"> {this.props.messages} </div> </div> </div> ); } } export default Signupform; <file_sep>/src/client/reducers/jasenrekisteriReducer.js import { actions } from '../actions/jasenrekisteriActions'; const initialState = { members: [], selectedMember: { fname: '', sname: '', email: '', hometown: '', approved: false, memberOfTyy: false, }, }; const jasenrekisteri = (state = initialState, action) => { switch (action.type) { case actions.RECEIVE_MEMBERS: return { ...state, members: [...action.members], }; case actions.SELECT_MEMBER: return { ...state, selectedMember: action.member, }; case actions.CLEAR_SELECTED_MEMBER: return { ...state, selectedMember: { ...initialState.selectedMember }, }; case actions.UPDATE_SELECTED_MEMBER: return { ...state, selectedMember: { ...action.member, updated: true }, }; default: return state; } }; export default jasenrekisteri; <file_sep>/src/client/components/Admin/Jasenrekisteri/Statistics.js import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; const Statistics = ({ members }) => { const getTyyCount = () => { return members.reduce((count, member) => { return member.memberOfTyy ? count + 1 : count; }, 0); }; return ( <div className="row"> <div className="col"> <p>Yhdistyksen jäseniä {members.length}kpl</p> <p>TYY:n jäseniä {getTyyCount()}kpl</p> </div> </div> ); }; const mapStateToProps = state => ({ members: state.jasenrekisteri.members, }); const mapDispatchToProps = () => ({}); Statistics.propTypes = { members: PropTypes.array, }; export default connect(mapStateToProps, mapDispatchToProps)(Statistics); <file_sep>/src/client/actions/userActions.js import * as ajaxActions from './ajaxActions'; import * as messageActions from './messageActions'; import ajax from 'utils/Ajax'; export const actions = { FETCH_USERS: 'FETCH_USERS', RECEIVE_USERS: 'RECEIVE_USERS', SELECT_USER: 'SELECT_USER', UPDATE_USER: 'UPDATE_USER', CLEAR_SELECTED_USER: 'CLEAR_SELECTED_USER', DELETE_USER: 'DELETE_USER', SAVE_USER: 'SAVE_USER', FETCH_ROLES: 'FETCH_ROLES', RECEIVE_ROLES: 'RECEIVE_ROLES', }; export function fetchUsers() { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.FETCH_USERS)); const res = await ajax.sendGet('/admin/w/kayttajat'); dispatch(ajaxActions.ajaxSuccess(actions.FETCH_USERS)); dispatch(receiveUsers(res.data)); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.FETCH_USERS, err)); messageActions.addErrorMessage({ header: 'Käyttäjien haku epäonnistui' }); } }; } export function fetchRoles() { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.FETCH_ROLES)); const res = await ajax.sendGet('/admin/roles'); dispatch(ajaxActions.ajaxSuccess(actions.FETCH_ROLES)); dispatch(receiveRoles(res.data)); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.FETCH_ROLES, err)); messageActions.addErrorMessage({ header: 'Roolien haku epäonnistui: ', text: err.message }); } }; } export function selectUser(user) { return { type: actions.SELECT_USER, user, }; } export function updateUser(user) { return { type: actions.UPDATE_USER, user, }; } export function saveUser(user) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.SAVE_USER)); await ajax.sendPost('/admin/w/kayttaja', user); dispatch(selectUser(user)); dispatch(fetchUsers()); dispatch(ajaxActions.ajaxSuccess(actions.SAVE_USER)); dispatch(messageActions.addSuccessMessage({ header: 'Tiedot päivitetty!' })); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.SAVE_USER, err)); messageActions.addErrorMessage({ header: 'Tietojen tallennus epäonnistui' }); } }; } export function addRoleToUser(userId, roleId) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.SAVE_USER)); const res = await ajax.sendGet(`/admin/w/role/${userId}/${roleId}`); dispatch(selectUser(res.data)); dispatch(fetchUsers()); dispatch(ajaxActions.ajaxSuccess(actions.SAVE_USER)); dispatch(messageActions.addSuccessMessage({ header: 'Tiedot päivitetty!' })); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.SAVE_USER, err)); messageActions.addErrorMessage({ header: 'Tietojen tallennus epäonnistui' }); } }; } export function removeRoleFromUser(userId, roleId) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.SAVE_USER)); const res = await ajax.sendDelete(`/admin/w/role/${userId}/${roleId}`); if (!res.success) { throw res.message; } dispatch(selectUser(res.data)); dispatch(fetchUsers()); dispatch(ajaxActions.ajaxSuccess(actions.SAVE_USER)); dispatch(messageActions.addSuccessMessage({ header: 'Tiedot päivitetty!' })); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.SAVE_USER, err)); messageActions.addErrorMessage({ header: 'Tietojen tallennus epäonnistui' }); } }; } export function deleteUser(user) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.DELETE_USER)); const res = await ajax.sendDelete('/admin/w/kayttaja/' + user.id); console.log(res.success); if (!res.success) { throw res.message; } dispatch(clearUser()); dispatch(fetchUsers()); dispatch(ajaxActions.ajaxSuccess(actions.DELETE_USER)); dispatch(messageActions.addSuccessMessage({ header: 'Käyttäjä poistettu!' })); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.DELETE_USER, err)); messageActions.addErrorMessage({ header: 'Poistaminen epäonnistui' }); } }; } export function clearUser() { return { type: actions.CLEAR_SELECTED_USER, }; } function receiveUsers(users) { return { type: actions.RECEIVE_USERS, users, }; } function receiveRoles(roles) { return { type: actions.RECEIVE_ROLES, roles, }; } <file_sep>/src/client/components/Footer/Footer.js import React from 'react'; import { Link } from 'react-router-dom'; import styles from './Footer.css'; import SomeIcons from './SomeIcons'; const Footer = () => ( <div className={styles.container}> <div> <Link className={styles.homeLink} to="/">HybridiSpeksi</Link> </div> <SomeIcons /> <div> <nav className="navbar navbar-inverse"> <a href="mailto:<EMAIL>" className={styles.contactLink}><EMAIL></a> </nav> </div> </div> ); export default Footer; <file_sep>/src/client/components/Speksit/Carousel.js import React from 'react'; import { Carousel } from 'react-responsive-carousel'; import PropTypes from 'prop-types'; import cuid from 'cuid'; const CarouselContainer = ({ images }) => { const urls = []; for (let i = 1; i <= images[0].numberOfImages; i += 1) { urls.push('/assets/images/carousel/' + images[0].year + '/' + images[0].year + '_' + i + '.jpg'); } return ( <Carousel showStatus={false} showThumbs={false} infiniteLoop> {urls.map(url => ( <div key={cuid()}> <img src={url} /> </div>)) } </Carousel> ); }; CarouselContainer.propTypes = { images: PropTypes.array, }; export default CarouselContainer; <file_sep>/Dockerfile FROM keymetrics/pm2:10-alpine WORKDIR /var/www/ # Install deps COPY ./package* ./ COPY . . COPY webpack webpack/ # COPY dist dist/ COPY assets src/assets COPY ecosystem.config.js . ENV NODE_ENV production RUN apk --no-cache add --virtual native-deps \ g++ gcc libgcc libstdc++ linux-headers autoconf automake make nasm python && \ npm install pm2 node-gyp sequelize pg sequelize-cli -g RUN npm install --production RUN npm run build CMD ["pm2-runtime", "start", "ecosystem.config.js"] <file_sep>/src/client/reducers/eventReducer.js import { actions } from 'actions/eventActions'; const initialState = { enrollments: [], enrollment: { id: '', ContactInfo: { fname: '', lname: '', email: '', pnumber: '', }, presentGreeting: false, greetingOrganization: '', avec: '', partyExpectation: '', menu: 'Liha', diet: '', alcohol: true, sillis: false, memberOfSpeksi: false, paid: false, additional: '', }, events: [], event: { id: '', name: '', limit: '', registrationOpen: false, date: '', }, submitted: false, }; const event = (state = initialState, action) => { switch (action.type) { case actions.RECEIVE_ENROLLMENTS: return { ...state, enrollments: [...action.enrollments], }; case actions.SELECT_ENROLLMENT: return { ...state, enrollment: { ...action.enrollment }, }; case actions.SET_SUBMITTED: return { ...state, submitted: true, }; case actions.CLEAR_ENROLLMENT: return { ...state, enrollment: initialState.enrollment, }; case actions.RECEIVE_EVENTS: return { ...state, events: [...action.events], }; case actions.RECEIVE_EVENT: return { ...state, event: { ...action.event }, }; case actions.SELECT_EVENT: return { ...state, event: { ...action.event }, }; default: return state; } }; export default event; <file_sep>/seeders/20181230204214-default-control.js const uuid = require('uuid/v4'); module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Controls', [ // Student organizations { id: uuid(), key: 'jarjesto', value: 'asteriski', name: 'Asteriski ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'delta', name: 'Delta ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'digit', name: 'Digit ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'iva', name: 'IVA ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'pulterit', name: 'Pulterit ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'synapsi', name: 'Synapsi ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'tyk', name: 'TYK ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'nucleus', name: 'Nucleus ry', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'jarjesto', value: 'statistica', name: 'Statistica ry', createdAt: new Date(), updatedAt: new Date(), }, // Speksis { id: uuid(), key: 'speksi', value: 'hybridispeksi', name: 'HybridiSpeksi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'iospeksi', name: 'I/O-Speksi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'humanistispeksi', name: 'Humanistispeksi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'tukyspeksi', name: 'TuKY-Speksi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'tlksspeksi', name: 'TLKS Speksi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'akademiska', name: 'Akademiska spexed', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'speksi', value: 'lexspeks', name: 'Lex Spex', createdAt: new Date(), updatedAt: new Date(), }, // Occupations { id: uuid(), key: 'tehtava', value: 'grafiikka', name: 'Grafiikka', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'kuvaus', name: 'Kuvaus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'puvustus', name: 'Puvustus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'maskeeraus', name: 'Maskeeraus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'lavastus', name: 'Lavastus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'varainhankinta', name: 'Varainhankinta', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'nayttelija', name: 'Näyttelijä', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'bandi', name: 'Bändi', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'tanssija', name: 'Tanssija', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'kasikirjoitus', name: 'Käsikirjoitus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'hallitus', name: 'Hallitus', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'tuotanto', name: 'Tuotanto', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'webmaster', name: 'Webmaster', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'huoltotiimi', name: 'Huolto- ja virkistys', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'tehtava', value: 'tekniikka', name: 'Ääni- ja valotekniikka', createdAt: new Date(), updatedAt: new Date(), }, // Control flags { id: uuid(), key: 'rekryAuki', value: 'false', bool: false, name: 'rekryAuki', createdAt: new Date(), updatedAt: new Date(), }, { id: uuid(), key: 'lipunmyyntiAuki', value: 'false', bool: false, name: 'lipunmyyntiAuki', createdAt: new Date(), updatedAt: new Date(), }, ], {}); /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('People', [{ name: '<NAME>', isBetaMember: false }], {}); */ }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Controls', null, {}); }, }; <file_sep>/src/client/actions/feedbackActions.js import ajax from '../Utils/Ajax'; import * as loaderActions from './loaderActions'; import * as messageActions from './messageActions'; export const actions = { RECIEVE_FEEDBACK: 'RECEIVE_FEEDBACK', SET_SUBMITTED: 'SET_SUBMITTED', }; export function submitFeedback(feedback) { return async (dispatch) => { try { dispatch(messageActions.clearMessages()); dispatch(loaderActions.showLoader()); const res = await ajax.sendPost('/palaute', feedback); if (!res.success) { dispatch(messageActions.addWarningMessage({ header: res.message }, 5000)); } else { dispatch(setSubmitted()); dispatch(messageActions.addSuccessMessage({ header: 'Kiitos palautteestasi!' }, 10000)); } dispatch(loaderActions.hideLoader()); } catch (err) { dispatch(loaderActions.hideLoader()); dispatch(messageActions.addErrorMessage({ header: 'Palautteen lähetyksessä tapahtui virhe. Yritä myöhemmin uudelleen' }, 5000)); console.log(err); } }; } export function fetchFeedback() { return async (dispatch) => { try { dispatch(loaderActions.showLoader()); const res = await ajax.sendGet(); dispatch(receiveFeedback(res)); } catch (e) { dispatch(loaderActions.hideLoader()); messageActions.addErrorMessage({ header: 'Virhe haettaessa palautteita.' }); } }; } function receiveFeedback(feedback) { return { type: actions.RECIEVE_FEEDBACK, feedback, }; } function setSubmitted() { return { type: actions.SET_SUBMITTED, }; } <file_sep>/models/contactinfo.js module.exports = (sequelize, DataTypes) => { const ContactInfo = sequelize.define('ContactInfo', { fname: DataTypes.STRING, lname: DataTypes.STRING, email: DataTypes.STRING, pnumber: DataTypes.STRING, hometown: DataTypes.STRING, memberOfTyy: DataTypes.BOOLEAN, }, {}); ContactInfo.associate = function (models) { // associations can be defined here }; return ContactInfo; }; <file_sep>/src/client/components/Admin/Events/EnrollmentsList.js import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { CSVLink, CSVDownload } from 'react-csv'; import cuid from 'cuid'; import * as actions from 'actions/eventActions'; import styles from './EnrollmentsList.css'; import list from '../Listing.css'; const EventList = ({ enrollments, selectEnrollment, selectedEnrollment }) => { const csvData = [ ['etunimi', 'sukunimi', 'email', 'tervehdys', 'taho', 'avec', 'pöytäseurue', 'menu', 'allergiat', 'holillisuus', 'sillis', 'jäsen'], ]; enrollments.map((enrollment) => { const { fname, lname, email } = enrollment.ContactInfo; csvData.push([fname, lname, email, enrollment.presentGreeting, enrollment.greetingOrganization, enrollment.avec, enrollment.partyExpectation, enrollment.menu, enrollment.diet, enrollment.alcohol, enrollment.sillis, enrollment.memberOfSpeksi]); }); return ( <div className={styles.container}> <CSVLink data={csvData} filename="vujuilmolista.csv" className={styles.csvLink} > Lataa csv-tiedostona </CSVLink> <h3>Ilmoittautumiset</h3> <div className={list.container}> <div className={list.rows}> {enrollments.map((enrollment, i) => { const { fname, lname, email } = enrollment.ContactInfo; const selected = enrollment.id === selectedEnrollment.id; return ( <div key={cuid()} className={`${list.row} ${selected ? list.selected : ''}`} onClick={() => selectEnrollment(enrollment)}> <span><span className={styles.enrollmentNumber}>#{i + 1}</span> {fname} {lname}</span> <span>{email}</span> </div> ); })} </div> </div> </div> ); }; EventList.propTypes = { enrollments: PropTypes.array, selectEnrollment: PropTypes.func, selectedEnrollment: PropTypes.object, }; const mapStateToProps = state => ({ enrollments: state.event.enrollments, selectedEnrollment: state.event.enrollment, }); const mapDispatchToProps = dispatch => ({ selectEnrollment: enrollment => dispatch(actions.selectEnrollment(enrollment)), }); export default connect(mapStateToProps, mapDispatchToProps)(EventList); <file_sep>/src/client/components/Event/EnrollmentSitsit.js import React, { Component } from 'react'; // import { BrowserRouter, Route } from 'react-router-dom'; import styles from './Sitsit.css'; import Sitsitform from './Sitsitform'; import utils from '../../Utils/Utils'; import ajax from '../../Utils/Ajax'; const MESSAGE_SUCCESS = 'success'; const MESSAGE_WARNING = 'warning'; const MESSAGE_ERROR = 'error'; class Sitsit extends Component { constructor(props) { super(props); // Initial state this.state = { tapahtuma: 'interspeksuaaliset2018', fname: '', sname: '', email: '', jarjesto: '', holillisuus: 'true', allergiat: '', messages: [], warnings: [], errors: [], ilmonneet: [], sitsitAuki: false, sitsiKiintio: true, ilmottu: false, hsCount: 0, ioCount: 0, lexCount: 0, tlksCount: 0, tukyCount: 0, spexetCount: 0, humanistiCount: 0, }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.countSpeksit = this.countSpeksit.bind(this); } componentDidMount() { ajax.sendGet('/ohjaustieto/sitsitAuki') .then((tag) => { console.log(tag.data[0]); this.setState({ sitsitAuki: tag.data[0].truefalse }); }) .catch((err) => { console.log(err); }); this.setState({ sitsitAuki: true }); ajax.sendGet('/ohjaustieto/sitsiKiintio') .then((tag) => { console.log(tag.data[0]); this.setState({ sitsiKiintio: tag.data[0].truefalse }); }) .catch((err) => { console.log(err); }); ajax.sendGet('/ilmo/interspeksuaaliset2018') .then((_data) => { this.setState({ ilmonneet: _data.data }); this.countSpeksit(); console.log(_data); }) .catch((err) => { console.log(err); }); } // Handle all input events handleChange(e) { const value = e.target.value; this.setState({ [e.target.name]: value }); this.setState({ messages: [], warnings: [], errors: [], }); } // Submit form handleSubmit(e) { e.preventDefault(); const url = '/ilmo'; if (this.validateSitsit()) { ajax.sendPut( url, { tapahtuma: this.state.tapahtuma, fname: this.state.fname, sname: this.state.sname, email: this.state.email, jarjesto: this.state.jarjesto, juoma: this.state.holillisuus, ruokavalio: this.state.lisatiedot, }, ).then((data) => { this.addMessage(MESSAGE_SUCCESS, 'Ilmoittautuminen onnistui!'); this.setState({ ilmottu: true }); }).catch((err) => { console.log(err); this.addMessage(MESSAGE_ERROR, 'Virhe!', 'Palvelimella tapahtui virhe. Yritä myöhemmin uudelleen tai ota yhteys webmastereihin.'); }); } } // Count enrollments countSpeksit() { ajax.sendGet('/ilmo/interspeksuaaliset2018') .then((_data) => { this.setState({ ilmonneet: _data.data }); console.log(_data); }) .catch((err) => { console.log(err); }); let hs = 0; let io = 0; let lex = 0; let tlks = 0; let tuky = 0; let spexet = 0; let humanisti = 0; for (let i = 0; i < this.state.ilmonneet.length; i++) { if (this.state.ilmonneet[i].jarjesto === 'HybridiSpeksi') { hs += 1; } else if (this.state.ilmonneet[i].jarjesto === 'I/O-speksi') { io += 1; } else if (this.state.ilmonneet[i].jarjesto === 'LEX SPEX') { lex += 1; } else if (this.state.ilmonneet[i].jarjesto === 'TLKS SPEKSI') { tlks += 1; } else if (this.state.ilmonneet[i].jarjesto === 'TuKY-Speksi') { tuky += 1; } else if (this.state.ilmonneet[i].jarjesto === 'Akademiska Spexet vid Åbo Akademi R.F.') { spexet += 1; } else if (this.state.ilmonneet[i].jarjesto === 'Turkulainen Humanistispeksi') { humanisti += 1; } } this.setState({ hsCount: hs, ioCount: io, lexCount: lex, tlksCount: tlks, tukyCount: tuky, spexetCount: spexet, humanistiCount: humanisti, }); } // Validates if all necessary info has been given validateSitsit() { this.countSpeksit(); let valid = true; if ( this.state.fname === '' || this.state.sname === '' || this.state.email === '' || this.state.jarjesto === '' ) { this.addMessage(MESSAGE_WARNING, 'Virhe!', 'Kaikki kentät on täytettävä'); valid = false; } if (!utils.isValidEmail(this.state.email)) { this.addMessage(MESSAGE_WARNING, 'Virhe!', 'Sähköposti on virheellinen'); valid = false; } if (this.state.sitsiKiintio && this.state.jarjesto === 'HybridiSpeksi' && this.state.hsCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'I/O-speksi' && this.state.ioCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'LEX SPEX' && this.state.lexCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'TLKS SPEKSI' && this.state.tlksCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'TuKY-Speksi' && this.state.tukyCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'Akademiska Spexet vid Åbo Akademi R.F.' && this.state.spexetCount > 16 || this.state.sitsiKiintio && this.state.jarjesto === 'Turkulainen Humanistispeksi' && this.state.humanistiCount > 16) { this.addMessage(MESSAGE_WARNING, 'Virhe!', 'Järjestön kiintiö on jo täynnä'); valid = false; } return valid; } // Add different kinds of error or warning messages addMessage(type, newHeader, newText) { if (type === MESSAGE_WARNING) { const newWarnings = this.state.warnings; newWarnings.push({ header: newHeader, text: newText }); this.setState({ warnings: newWarnings }); } else if (type === MESSAGE_ERROR) { const newErrors = this.state.errors; newErrors.push({ header: newHeader, text: newText }); this.setState({ erros: newErrors }); } else if (type === MESSAGE_SUCCESS) { const newMessages = this.state.messages; newMessages.push({ header: newHeader, text: newText }); this.setState({ messages: newMessages }); } } render() { const form = null; return ( <div> <Sitsitform sitsitAuki={this.state.sitsitAuki} ilmottu={this.state.ilmottu} fname={this.state.fname} sname={this.state.sname} email={this.state.email} jarjesto={this.state.jarjesto} holillisuus={this.state.holillisuus} allergiat={this.state.allergiat} ilmonneet={this.state.ilmonneet} hsCount={this.state.hsCount} ioCount={this.state.ioCount} lexCount={this.state.lexCount} tlksCount={this.state.tlksCount} tukyCount={this.state.tukyCount} spexetCount={this.state.spexetCount} humanistiCount={this.state.humanistiCount} handleChange={this.handleChange} handleSubmit={this.handleSubmit} /> </div> ); } } export default Sitsit; <file_sep>/src/client/components/Admin/BookingManagement/BookingInfo.js import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import styles from './BookingInfo.css'; import * as actions from 'actions/bookingActions'; const BookingInfo = ({ booking, clearSelectedBooking, redeem }) => { if (booking.id === '') { return ( <div className={styles.container}> <div className={styles.buttonRow}> <Link className={styles.button} to="varaus">Uusi varaus</Link> </div> </div> ); } const { fname, lname, email, pnumber, } = booking.ContactInfo; const { normalCount, discountCount, specialPriceCount, specialPrice, additionalInfo, paid, redeemed, } = booking; return ( <div className={styles.container}> <h2>Varauksen tiedot</h2> <div className={styles.infoRow}> <span>{fname} {lname}</span> </div> <div className={styles.infoRow}> <span>{email}</span> <span>{pnumber}</span> </div> <div className={styles.infoRow}> <span>Normaalihintaiset liput: {normalCount}</span> <span>Alennushintaiset liput: {discountCount}</span> {specialPriceCount > 0 ? <span>Erikoishintaiset liput: {specialPriceCount}, hinta {specialPrice} </span> : null} </div> <div className={styles.infoRow}> {additionalInfo} </div> <div className={styles.infoRow}> <span>Yhteensä {normalCount + discountCount + specialPriceCount} kpl</span> </div> <div className={styles.buttonRow}> <button className={styles.button} onClick={clearSelectedBooking}>Tyhjennä valinta</button> <Link className={styles.button} to="/varaus">Muokkaa tai poista</Link> </div> <div className={styles.buttonRow}> {!booking.redeemed ? <button type="button" className={styles.button} onClick={() => redeem(booking)}>Lunasta liput</button> : 'Lippu lunastettu.'} </div> </div> ); }; BookingInfo.propTypes = { booking: PropTypes.object, clearSelectedBooking: PropTypes.func, redeem: PropTypes.func, }; const mapStateToProps = state => ({ booking: state.bookingManagement.selectedBooking, }); const mapDispatchToProps = dispatch => ({ clearSelectedBooking: () => dispatch(actions.clearSelectedBooking()), redeem: booking => dispatch(actions.redeem(booking)), }); export default connect(mapStateToProps, mapDispatchToProps)(BookingInfo); <file_sep>/src/client/components/Feedback/FeedbackInfo.js import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as actions from 'actions/feedbackActions'; import { Field, reduxForm, getFormValues } from 'redux-form'; import { RenderTextfield, RenderTextarea } from './RenderForm'; import styles from './FeedbackInfo.css'; import pagestyles from './Feedback.css'; const required = value => (value ? undefined : 'Pakollinen kenttä'); const email = value => (value && /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im.test(value) ? 'Virheellinen sähköposti' : undefined); const Fields = ({ invalid }) => { return ( <div className={pagestyles.column}> <h2>Yhteystiedot</h2> <div className={pagestyles.content}> <Field name="name" id="nameInput" component={RenderTextfield} type="text" label="Nimi" placeholder="Nimi" /> <Field name="email" id="emailInput" component={RenderTextarea} rows="1" type="text" label="Sähköposti" placeholder="Sähköposti" validate={[email]} /> <Field name="feedback" id="feedbackInput" component={RenderTextarea} rows="5" type="textarea" label="Palaute" placeholder="Palaute" validate={[required]} /> <div className={styles.submitFeedbackContainer}> <button type="submit" disabled={invalid} className={`${styles.feedbackButton} ${invalid ? styles.disabled : ''}`}>Lähetä palaute</button> </div> </div> </div> ); }; Fields.propTypes = { invalid: PropTypes.bool, }; const FeedbackInfoForm = ({ handleSubmit, invalid, submitted, submitFeedback, }) => { const onSubmit = (values) => { submitFeedback(values); }; return ( <div className={styles.container}> <form className={styles.form} onSubmit={handleSubmit(onSubmit)}> {!submitted ? <Fields invalid={invalid} /> : ''} </form> </div> ); }; FeedbackInfoForm.propTypes = { handleSubmit: PropTypes.func, submitFeedback: PropTypes.func, invalid: PropTypes.bool, submitted: PropTypes.bool, }; const mapStateToProps = state => ({ formState: getFormValues('feedbackForm')(state), submitted: state.feedback.submitted, }); const mapDispatchToProps = dispatch => ({ submitFeedback: feedback => dispatch(actions.submitFeedback(feedback)), }); const FeedbackWithReduxForm = reduxForm({ form: 'feedbackForm', })(FeedbackInfoForm); export default connect(mapStateToProps, mapDispatchToProps)(FeedbackWithReduxForm); <file_sep>/src/client/components/Admin/BookingManagement/BookingManagement.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import styles from './BookingManagement.css'; import ShowsList from './ShowsList'; import BookingsList from './BookingsList'; import BookingInfo from './BookingInfo'; import { fetchShows } from 'actions/bookingActions'; class BookingManagement extends Component { componentDidMount() { this.props.fetchShows(); } render() { return ( <div className={styles.container}> <div className={styles.showsList}> <h2>Varaustenhallinta</h2> <ShowsList /> <Link to="esitystenhallinta">Hallitse esityksiä</Link> </div> <div className={styles.bookingsList}> <BookingsList /> </div> <div className={styles.bookingInfo}> <BookingInfo /> </div> </div> ); } } BookingManagement.propTypes = { fetchShows: PropTypes.func, }; const mapStateToProps = state => ({ }); const mapDispatchToProps = dispatch => ({ fetchShows: () => dispatch(fetchShows()), }); export default connect(mapStateToProps, mapDispatchToProps)(BookingManagement); <file_sep>/src/client/components/Muutspeksit/Muutspeksit.js import React, { Component } from 'react'; import cuid from 'cuid'; import SpeksiCard from './SpeksiCard'; import styles from './Muutspeksit.css'; import PageHero from '../PageHero/PageHero'; class Muutspeksit extends Component { constructor(props) { super(props); this.state = { speksit: [ { name: 'I/O-speksi', imageUrl: '/assets/images/io.svg', tdk: 'Turun yliopiston yhteiskuntatieteellisen tiedekunnan ja opettajankoulutuslaitoksen yhteinen speksi', url: 'http://iospeksi.fi/', }, { name: 'LEX SPEX', imageUrl: '/assets/images/lex.svg', tdk: 'Oikeustieteen ylioppilaiden speksi', url: 'https://lex.fi/toiminta/spex', }, { name: 'TLKS SPEKSI', imageUrl: '/assets/images/tlks.svg', tdk: 'Turun Lääketieteenkandidaattiseuran speksi', url: 'https://turkuspeksi.com/', }, { name: 'TuKY-Speksi', imageUrl: '/assets/images/tuky.svg', tdk: 'Turun kauppatieteen ylioppilaiden speksi', url: 'http://www.tuky.fi/speksi/', }, { name: 'Akademiska Spexet <br /> vid Åbo Akademi R.F.', imageUrl: '/assets/images/abospex.svg', tdk: 'Akademiska Spexet vid Åbo Akademi', url: 'https://spex.abo.fi/', }, { name: 'Turkulainen humanistispeksi', imageUrl: '/assets/images/humanisti.svg', tdk: 'Turun yliopiston humanistisen tiedekunnan speksi', url: 'https://tyyala.utu.fi/humanistispeksi/', }, ], }; } componentDidMount() { $(window).scrollTop(0); } componentDidUpdate() { } render() { return ( <div className={styles.container}> <div className={styles.pageHero}> <PageHero title="Turun muut speksit" /> </div> <div className={styles.intro}> <h2 className="">Turun muut speksit</h2> <p>Turussa toimii myöd monia muita speksejä HybridiSpeksin lisäksi. Speksien välinen yhteistyö on tärkeässä roolissa esimerkiksi yhteisten tapahtumien muodossa. Pidä huoli, ettet jää paitsi muista huikeista produktioista ja Turun ainutlaatuisesta speksikentästä! </p> </div> <div className={styles.content}> {this.state.speksit.map(speksi => <SpeksiCard key={cuid()} speksi={speksi} />)} </div> </div> ); } } export default Muutspeksit; <file_sep>/migrations/20190131193802-create-booking.js const uuid = require('uuid/v4'); module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Bookings', { id: { allowNull: false, primaryKey: true, type: Sequelize.UUID, defaultValue: uuid(), }, normalCount: { type: Sequelize.INTEGER, }, discountCount: { type: Sequelize.INTEGER, }, specialPriceCount: { type: Sequelize.INTEGER, }, specialPrice: { type: Sequelize.DECIMAL(10, 2), }, tag: { type: Sequelize.STRING, }, redeemed: { type: Sequelize.BOOLEAN, defaultValue: false, }, paid: { type: Sequelize.BOOLEAN, defaultValue: false, }, createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Bookings'); }, }; <file_sep>/src/client/Utils/Form.js import React from 'react'; import PropTypes from 'prop-types'; import cuid from 'cuid'; export const Text = ({ type, label, autoFocus, name, onChange, value, placeholder, id, }) => ( <div className="form-group"> <label htmlFor={id}>{label}</label> <input type={type} autoFocus={autoFocus} name={name} onChange={onChange} value={value} className="form-control" placeholder={placeholder} id={id} /> </div> ); Text.propTypes = { type: PropTypes.string, label: PropTypes.string, autoFocus: PropTypes.bool, name: PropTypes.string, onChange: PropTypes.func, value: PropTypes.string, placeholder: PropTypes.string, id: PropTypes.string, }; export const Textarea = ({ id, label, name, rows, value, placeholder, onChange, }) => ( <div className="form-group"> <label htmlFor={id}>{label}</label> <textarea className="form-control" name={name} id={id} rows={rows} value={value} placeholder={placeholder} onChange={onChange} /> </div> ); Textarea.propTypes = { id: PropTypes.string, label: PropTypes.string, name: PropTypes.string, rows: PropTypes.number, value: PropTypes.string, placeholder: PropTypes.string, onChange: PropTypes.func, }; /** * * @param {options} props * @param {name} props * @param {onChange} * @param {selected} * @param {id} * @param {disabled} * */ export const Dropdown = ({ id, options, label, name, onChange, selected, disabled, }) => { if (!options) { options = []; } const getOptions = options.map((opt) => { let value = ''; if (!opt.value) { value = opt._id; } else { value = opt.value; } return ( <option key={cuid()} value={value}>{opt.name}</option> ); }); return ( <div> {label !== 'undefined' && typeof label !== 'undefined' ? <label htmlFor={id}>{label}</label> : ''} <select name={name} onChange={onChange} value={selected} className="form-control" id={id} disabled={disabled} > {getOptions} </select> </div> ); }; Dropdown.propTypes = { id: PropTypes.string, options: PropTypes.array, label: PropTypes.string, name: PropTypes.string, onChange: PropTypes.func, selected: PropTypes.string, disabled: PropTypes.bool, }; export const DropdownReduxform = (props) => { if (!props.options) { props.options = []; } const options = props.options.map((opt) => { let value = ''; if (!opt.value) { value = opt._id; } else { value = opt.value; } return ( <option key={cuid()} value={value}>{opt.name}</option> ); }); return ( <div> {props.label !== 'undefined' && typeof props.label !== 'undefined' ? <label htmlFor={props.id}>{props.label}</label> : ''} <select {...props.input} name={props.name} value={props.selected} className="form-control" id={props.id} disabled={props.disabled} > {options} </select> </div> ); }; DropdownReduxform.propTypes = { id: PropTypes.string, input: PropTypes.object, options: PropTypes.array, label: PropTypes.string, name: PropTypes.string, onChange: PropTypes.func, selected: PropTypes.string, disabled: PropTypes.bool, }; /** * @param options: label, value * @param value * @param name * @param onChange */ export const Radio = (props) => { const options = props.options.map(option => ( <div key={cuid()}> <input type="radio" onChange={props.onChange} value={option.value} checked={option.value === props.value} name={props.name} disabled={props.disabled} /> &nbsp; {option.label} </div> )); return ( <div> {props.legend ? <legend>{props.legend}</legend> : ''} {options} </div> ); }; Radio.propTypes = { options: PropTypes.array, onChange: PropTypes.func, value: PropTypes.string, name: PropTypes.string, disabled: PropTypes.bool, legend: PropTypes.string, }; <file_sep>/src/client/actions/jasenrekisteriActions.js import * as ajaxActions from './ajaxActions'; import * as messageActions from './messageActions'; import ajax from '../Utils/Ajax'; export const actions = { FETCH_MEMBERS: 'FETCH_MEMBERS', RECEIVE_MEMBERS: 'RECEIVE_MEMBERS', SELECT_MEMBER: 'SELECT_MEMBER', CLEAR_SELECTED_MEMBER: 'CLEAR_SELECTED_MEMBER', UPDATE_SELECTED_MEMBER: 'UPDATE_SELECTED_MEMBER', APPROVE_MEMBER: 'APPROVE_MEMBER', DELETE_MEMBER: 'DELETE_MEMBER', }; export function fetchMembers() { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.FETCH_MEMBERS)); const res = await ajax.sendGet('/admin/h/jasenrekisteri'); dispatch(ajaxActions.ajaxSuccess(actions.FETCH_MEMBERS)); dispatch(receiveMembers(res.data)); } catch (err) { dispatch(ajaxActions.ajaxFailure(actions.FETCH_MEMBERS, err)); dispatch(messageActions.addErrorMessage({ header: 'Virhe haettaessa jäsentietoja.', text: 'Ota yhteys webmasteriin' })); } }; } export function selectMember(member) { return { type: actions.SELECT_MEMBER, member, }; } export function clearSelectedMember() { return { type: actions.CLEAR_SELECTED_MEMBER, }; } export function updateSelectedMember(member) { return { type: actions.UPDATE_SELECTED_MEMBER, member, }; } export function saveMember(member) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.SAVE_SELECTED_MEMBER)); await ajax.sendPost('/admin/h/jasenrekisteri', member); dispatch(selectMember(member)); dispatch(ajaxActions.ajaxSuccess(actions.SAVE_SELECTED_MEMBER)); dispatch(fetchMembers()); dispatch(messageActions.addSuccessMessage({ header: 'Tiedot päivitetty!' })); } catch (err) { dispatch(messageActions.addErrorMessage({ header: 'Tietojen päivitys epäonnistui!' })); console.log(err); dispatch(ajaxActions.ajaxFailure(actions.SAVE_SELECTED_MEMBER, err)); } }; } export function approveMember(member) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.APPROVE_MEMBER)); await ajax.sendGet('/admin/h/hyvaksyJasen/' + member._id); dispatch(ajaxActions.ajaxSuccess(actions.APPROVE_MEMBER)); dispatch(fetchMembers()); dispatch(messageActions.addSuccessMessage({ header: 'Jäsen hyväksytty!' })); } catch (err) { dispatch(messageActions.addErrorMessage({ header: 'Tietojen päivitys epäonnistui!' })); console.log(err); dispatch(ajaxActions.ajaxFailure(actions.APPROVE_MEMBER, err)); } }; } export function deleteMember(member) { return async (dispatch) => { try { dispatch(ajaxActions.ajaxLoading(actions.DELETE_MEMBER)); await ajax.sendDelete('/admin/h/jasenrekisteri/' + member._id); dispatch(ajaxActions.ajaxSuccess(actions.DELETE_MEMBER)); dispatch(fetchMembers()); dispatch(messageActions.addSuccessMessage({ header: 'Jäsen poistettu rekisteristä!' })); } catch (err) { dispatch(messageActions.addErrorMessage({ header: 'Poisto epäonnistui!' })); console.log(err); dispatch(ajaxActions.ajaxFailure(actions.DELETE_MEMBER, err)); } } } function receiveMembers(members) { return { type: actions.RECEIVE_MEMBERS, members, }; } <file_sep>/src/client/components/Event/RenderForm.js import React from 'react'; import styles from './RenderForm.css'; import cuid from 'cuid'; export const RenderTextfield = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} placeholder={field.placeholder} type="text" /> </div> ); export const RenderNumber = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} type="number" /> </div> ); export const RenderDateField = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <input id={field.id} className={styles.input} {...field.input} type="datetime-local" /> </div> ); export const RenderTextarea = field => ( <div className={`${styles.inputGroup} ${styles.inputTextarea}`}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <textarea id={field.id} className={styles.input} rows={field.rows} placeholder={field.placeholder} {...field.input} /> </div> ); export const RenderRadio = field => ( <div className={`${styles.inputGroup}`}> {field.buttons.map((button) => { return ( <div className={styles.radioWrapper}> <label htmlFor={field.id} className={styles.radioLabel}>{button}</label> <div className={styles.inputRadioOption} key={cuid()}> <input id={button} className={styles.inputRadio} {...field.input} type="radio" /> </div> </div> ); })} {/* handleClick={handleClick} selected={show.id === selectedShow.id} */} </div> ); export const RenderCheckbox = field => ( <div className={`${styles.inputGroup} ${styles.inputGroupCheckbox}`}> <input type="checkbox" className={`${styles.input} ${styles.checkbox}`} {...field.input} /> <label htmlFor={field.id} className={`${styles.label} ${styles.labelCheckbox}`}>{field.label}</label> </div> ); export const RenderDropdown = field => ( <div className={styles.inputGroup}> <label htmlFor={field.id} className={styles.label}>{field.label}</label> <select className={`${styles.input} ${styles.dropdown}`} id={field.id} {...field.input}> {field.options.map((option) => { return ( <option key={cuid()} value={option.value}>{option.name}</option> ); })} </select> </div> ); <file_sep>/migrations/20190103195705-add-associations.js module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.addColumn( 'Users', 'contactInfoId', { type: Sequelize.UUID, references: { model: 'ContactInfos', key: 'id', as: 'contactInfoId', }, onDelete: 'CASCADE', }, ) .then(() => { return queryInterface.addColumn( 'UserRoles', 'userId', { type: Sequelize.UUID, references: { model: 'Users', key: 'id', as: 'userId', }, onDelete: 'CASCADE', }, ); }) .then(() => { return queryInterface.addColumn( 'UserRoles', 'roleId', { type: Sequelize.UUID, references: { model: 'Roles', key: 'id', as: 'roleId', }, onDelete: 'CASCADE', }, ); }); // .then(() => { // return queryInterface.addColumn( // 'Members', // 'contactInfoId', // { // type: Sequelize.UUID, // references: { // model: 'ContactInfos', // key: 'id', // }, // onDelete: 'CASCADE', // }, // ); // }) }, down: (queryInterface, Sequelize) => { return queryInterface.removeColumn( 'Users', 'contactInfoId', ) .then(() => { return queryInterface.removeColumn( 'UserRoles', 'userId', ); }) .then(() => { return queryInterface.removeColumn( 'UserRoles', 'roleId', ); }); }, }; <file_sep>/src/client/components/Admin/Events/Enrollment.js import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { reduxForm, Field, isDirty } from 'redux-form'; import { RenderTextfield, RenderCheckbox, RenderDropdown } from '../RenderAdminForm'; import styles from './Enrollment.css'; import form from '../Form.css'; import * as actions from 'actions/eventActions'; const Fields = ({ formDirty, clearEnrollment, deleteEnrollment }) => { const drinkMenuOptions = () => { return ( [{ name: 'Alkoholillinen', value: true }, { name: 'Alkoholiton', value: false }] ); }; const menuOptions = () => { return ( [{ name: 'Menu 1 (Liha)', value: 'Liha' }, { name: 'Menu 2 (Kasvis)', value: 'Kasvis' }] ); }; return ( <div className={form.formContainer}> <div className={form.formRow}> <Field name="ContactInfo.fname" id="fnameInput" component={RenderTextfield} type="text" placeholder="Etunimi" /> <Field name="ContactInfo.lname" id="lnameInput" component={RenderTextfield} type="text" placeholder="Sukunimi" /> </div> <div className={form.formRow}> <Field name="ContactInfo.email" id="emailInput" component={RenderTextfield} type="text" placeholder="Sähköposti" /> <Field name="ContactInfo.pnumber" id="pnumberInput" component={RenderTextfield} type="text" placeholder="Puhelinnumero" /> </div> <div className={form.formRow}> <Field name="presentGreeting" id="greetingsCheckbox" component={RenderCheckbox} type="checkbox" label="Esittää tervehdyksen" /> <Field name="greetingOrganization" id="organizationInput" component={RenderTextfield} type="text" label="Edustettava taho" /> </div> <div className={form.formRow}> <Field name="avec" id="avecInput" component={RenderTextfield} type="text" label="Avec" /> </div> <div className={form.formRow}> <Field name="partyExpectation" id="partyInput" component={RenderTextfield} type="text" label="Pöytäseurue" /> </div> <div className={form.formRow}> <Field name="menu" id="menuInput" component={RenderDropdown} label="Menu" options={menuOptions()} /> <Field name="alcohol" id="drinkInput" component={RenderDropdown} label="Juoma" options={drinkMenuOptions()} /> </div> <div className={form.formRow}> <Field name="diet" id="dietInput" component={RenderTextfield} type="text" label="Ruokavaliot" /> </div> <div className={form.formRow}> <Field name="sillis" id="sillisSelect" component={RenderCheckbox} type="checkbox" label="Osallistuu sillikselle" /> <Field name="memberOfSpeksi" id="speksiSelect" component={RenderCheckbox} type="checkbox" label="HybridiSpeksi ry:n jäsen" /> </div> <div className={form.formRow}> {formDirty ? ( <button type="submit" className={`${form.input} ${form.button}`}>Tallenna muutokset</button> ) : ''} <button type="button" onClick={clearEnrollment} className={`${form.input} ${form.button}`}>Tyhjennä valinta</button> <button type="button" onClick={deleteEnrollment} className={`${form.input} ${form.button}`}>Poista</button> </div> </div> ); }; Fields.propTypes = { formDirty: PropTypes.bool, clearEnrollment: PropTypes.func, deleteEnrollment: PropTypes.func, }; const Enrollment = ({ handleSubmit, updateEnrollment, enrollment, formDirty, clearEnrollment, deleteEnrollment, }) => { const onSubmit = (values) => { values.id = enrollment.id; updateEnrollment(values); }; const handleDelete = () => { if (confirm('Poistetaanko ilmoittautuminen?')) { deleteEnrollment(enrollment); } }; return ( <div className={styles.container}> <h3>Tiedot</h3> <form onSubmit={handleSubmit(onSubmit)}> {enrollment.id === '' ? ( <h5>Valitse varaus</h5> ) : ( <Fields formDirty={formDirty} clearEnrollment={clearEnrollment} deleteEnrollment={handleDelete} /> )} </form> </div> ); }; Enrollment.propTypes = { handleSubmit: PropTypes.func, updateEnrollment: PropTypes.func, enrollment: PropTypes.object, formDirty: PropTypes.bool, clearEnrollment: PropTypes.func, deleteEnrollment: PropTypes.func, }; const mapStateToProps = state => ({ enrollment: state.event.enrollment, initialValues: state.event.enrollment, formDirty: isDirty('enrollmentManagementForm')(state), }); const mapDispatchToProps = dispatch => ({ updateEnrollment: enrollment => dispatch(actions.updateEnrollment(enrollment)), clearEnrollment: () => dispatch(actions.clearEnrollment()), deleteEnrollment: enrollment => dispatch(actions.deleteEnrollment(enrollment)), }); const EnrollmentWithReduxForm = reduxForm({ form: 'enrollmentManagementForm', enableReinitialize: true, })(Enrollment); export default connect(mapStateToProps, mapDispatchToProps)(EnrollmentWithReduxForm); <file_sep>/src/client/reducers/userReducer.js import { actions } from 'actions/userActions'; const initialState = { users: [], roles: [], selectedUser: { id: '', ContactInfo: { fname: '', lname: '', email: '', }, Roles: [], updated: false, }, }; const user = (state = initialState, action) => { switch (action.type) { case actions.RECEIVE_USERS: return { ...state, users: [...action.users], }; case actions.SELECT_USER: return { ...state, selectedUser: { ...action.user, updated: false }, }; case actions.UPDATE_USER: return { ...state, selectedUser: { ...action.user, updated: true }, }; case actions.CLEAR_SELECTED_USER: return { ...state, selectedUser: { ...initialState.selectedUser }, }; case actions.RECEIVE_ROLES: return { ...state, roles: [...action.roles], }; default: return state; } }; export default user; <file_sep>/src/client/components/ApplicationMessages/Messages.js import React from 'react'; import cuid from 'cuid'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import constants from '../../Utils/constants'; import styles from './Messages.css'; import { closeMessage } from '../../actions/messageActions'; const Messages = ({ messages, close }) => ( <div className={styles.messagesContainer}> {messages.filter(message => message.type === constants.MESSAGE_SUCCESS).map(message => ( <div key={cuid()} className={`${styles.message} ${styles.messageSuccess} ${message.fading ? styles.fadeOut : ''}`} role="alert"> <span><strong>{message.header}</strong> {message.text}</span> <a className={styles.closeIcon} onClick={() => close(message.id)}> <i className="fa fa-times" /> </a> </div> ))} {messages.filter(message => message.type === constants.MESSAGE_WARNING).map(message => ( <div key={cuid()} className={`${styles.message} ${styles.messageWarning} ${message.fading ? styles.fadeOut : ''}`} role="alert"> <span><strong>{message.header}</strong> {message.text}</span> <a className={styles.closeIcon} onClick={() => close(message.id)}> <i className="fa fa-times" /> </a> </div> ))} {messages.filter(message => message.type === constants.MESSAGE_ERROR).map(message => ( <div key={cuid()} className={`${styles.message} ${styles.messageError} ${message.fading ? styles.fadeOut : ''}`} role="alert"> <span><strong>{message.header}</strong> {message.text}</span> <a className={styles.closeIcon} onClick={() => close(message.id)}> <i className="fa fa-times" /> </a> </div> ))} </div> ); Messages.propTypes = { messages: PropTypes.array, }; const mapStateToProps = state => ({ messages: state.messages, }); const mapDispatchToProps = dispatch => ({ close: id => dispatch(closeMessage(id)), }); export default connect(mapStateToProps, mapDispatchToProps)(Messages); <file_sep>/src/client/components/App.js import React from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import PropTypes from 'prop-types'; import Loadable from 'react-loadable'; import globalStyles from './App.css'; import * as auth from './../Utils/Auth'; // Public import Header from './Header/Header'; import Footer from './Footer/Footer'; import Messages from './ApplicationMessages/Messages'; import Loader from './Loader/Loader'; import Home from './Home/Home'; import Rekry from './Rekry/Rekry'; import Speksit from './Speksit/Speksit'; import Organization from './Organization/Organization'; import Rekisteriseloste from './Organization/Rekisteriseloste'; import Saannot from './Organization/Saannot'; import Feedback from './Feedback/Feedback'; import Muutspeksit from './Muutspeksit/Muutspeksit'; import Kalenteri from './Kalenteri/Kalenteri'; import Speksi2019 from './Speksi2019/Speksi2019'; import BookingConfirmation from './Speksi2019/BookingConfirmation'; import BookingDenied from './Speksi2019/BookingDenied'; import Vuosijuhlailmo from './Event/Event'; // Admin import AdminHeader from './Admin/Layout/AdminHeader'; import AdminFooter from './Admin/Layout/AdminFooter'; import Admin from './Admin/Admin'; import Produktio from './Admin/Produktio/Produktio'; import Uusijasen from './Admin/Jasenrekisteri/Uusijasen'; import UserManagement from './Admin/Kayttajat/UserManagement'; import Ohjaustiedot from './Admin/Ohjaustiedot/Ohjaustiedot'; import EventManagement from './Admin/Events/EventManagement'; import Login from './Admin/Auth/Login'; import { publicDecrypt } from 'crypto'; const Loading = () => <h3>Loading...</h3>; const Jasenrekisteri = Loadable({ loader: () => import('./Admin/Jasenrekisteri/Jasenrekisteri'), loading: Loading }) const BookingManagement = Loadable({ loader: () => import('./Admin/BookingManagement/BookingManagement'), loading: Loading }) const Booking = Loadable({ loader: () => import('./Admin/BookingManagement/Booking'), loading: Loading }) const ShowsManagement = Loadable({ loader: () => import('./Admin/BookingManagement/ShowsManagement'), loading: Loading }) const AdminFeedback = Loadable({ loader: () => import('./Admin/Feedback/Feedback'), loading: Loading }) export default class App extends React.Component { render() { const PublicLayout = ({ component: Component, ...rest }) => ( <Route location={this.props.location} {...rest} render={({ match }) => ( <div> <Header /> <Messages /> <Loader /> <Component params={match.params} globalStyles={globalStyles} /> <Footer /> </div> )} /> ); const LoginLayout = ({ component: Component, ...rest }) => ( <Route {...rest} render={({ match }) => ( <div> <Messages /> <Loader /> <Component params={match.params} globalStyles={globalStyles} /> </div> )} /> ); const AdminLayout = ({ component: Component, ...rest }) => { auth.checkToken(); return ( <Route {...rest} render={({ match }) => ( <div> <AdminHeader /> <Messages /> <Loader /> <Component params={match.params} globalStyles={globalStyles} /> <AdminFooter /> </div> )} /> ); }; return ( <div id="main-wrapper"> <BrowserRouter> <div> <div id="public-wrapper"> <Switch > <PublicLayout exact path="/" component={Home} /> <PublicLayout path="/speksirekry2019" component={Rekry} /> <PublicLayout exact path="/speksi2019" component={Speksi2019} /> <PublicLayout exact path="/speksi2019/vahvistus/:id" component={BookingConfirmation} /> <PublicLayout exact path="/speksi2019/virhe/:value" component={BookingDenied} /> <PublicLayout path="/speksit" component={Speksit} /> <PublicLayout exact path="/yhdistys" component={Organization} /> <PublicLayout exact path="/yhdistys/rekisteriseloste" component={Rekisteriseloste} /> <PublicLayout exact path="/yhdistys/saannot" component={Saannot} /> <PublicLayout path="/palaute" component={Feedback} /> <PublicLayout path="/muutspeksit" component={Muutspeksit} /> <PublicLayout path="/kalenteri" component={Kalenteri} /> <PublicLayout path="/tapahtumat/:eventId" component={Vuosijuhlailmo} /> </Switch> </div> <div id="admin-wrapper"> <Switch> <LoginLayout path="/login" component={Login} /> <AdminLayout path="/admin" component={Admin} /> <AdminLayout exact path="/varaustenhallinta" component={BookingManagement} /> <AdminLayout exact path="/varaus" component={Booking} /> <AdminLayout path="/esitystenhallinta" component={ShowsManagement} /> <AdminLayout path="/produktionhallinta" component={Produktio} /> <AdminLayout path="/jasenrekisteri" component={Jasenrekisteri} /> <AdminLayout path="/kayttajat" component={UserManagement} /> <AdminLayout path="/uusijasen" component={Uusijasen} /> <AdminLayout path="/ohjaustiedot" component={Ohjaustiedot} /> <AdminLayout path="/palautteet" component={AdminFeedback} /> <AdminLayout path="/ilmohallinta" component={EventManagement} /> </Switch> </div> </div> </BrowserRouter> </div> ); } } App.propTypes = { location: PropTypes.any, }; <file_sep>/src/schema/user-model.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; // set up a mongoose model and pass it using module.exports module.exports = mongoose.model('User', new Schema({ fname: String, sname: String, email: String, password: String, role: Number }, { collection: 'users', timestamps: true } ));<file_sep>/models/paymentmethod.js module.exports = (sequelize, DataTypes) => { const PaymentMethod = sequelize.define('PaymentMethod', { name: DataTypes.STRING, code: DataTypes.INTEGER, }, {}); PaymentMethod.associate = function (models) { PaymentMethod.hasMany(models.Booking, { as: 'Bookings', foreignKey: 'paymentMethodId' }); }; return PaymentMethod; }; <file_sep>/src/api/admin/user.js const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const UserMongo = require('../../schema/user-model'); const sha1 = require('sha1'); const userService = require('../../services/userService'); const jwtOptions = { expiresIn: '5h', }; module.exports = { newUser: async (req, res) => { const { fname, sname, email, password, } = req.body; try { if (await userService.findUserByEmail(email)) { throw new Error('Käyttäjä on jo rekisteröitynyt'); } const pwHash = await generateHash(password); const user = await userService.createUser(fname, sname, email, pwHash); res.json({ success: true, data: user }); } catch (e) { console.log(e.message); res.json({ success: false, message: e.message }); } }, authenticate: async (req, res) => { const { email, password } = req.body; try { let user = await userService.findUserByEmail(email); if (!user) { // While mongoDb users still exists, they are moved to postgres when they sign in const mongoUser = await userService.findMongoUserByEmail(email); if (!mongoUser) { throw new Error('Käyttäjää ei löydy'); } else { if (mongoUser.password !== sha1(password)) { throw new Error('Virheellinen salasana'); } const { fname, sname } = mongoUser; const pwHash = await generateHash(password); user = await userService.createUser(fname, sname, email, pwHash); user.addRole(await userService.getRoleByValue(mongoUser.role)); if (mongoUser.role === 4) { user.addRole(await userService.getRoleByValue(3)); } await user.save(); user = await userService.findUserByEmail(email); } } const passwordIsCorrect = await isPasswordCorrect(password, user.password); if (!passwordIsCorrect) { throw new Error('Virheellinen salasana'); } const roles = await user.getRoles(); if (!roles || roles.length === 0) { throw new Error('Käyttäjää ei ole vielä hyväksytty'); } const contactInfo = user.getContactInfo(); const payload = { id: user.id, fname: contactInfo.fname, lname: contactInfo.lname, email: contactInfo.email, }; const token = jwt.sign(payload, process.env.SECRET, jwtOptions); res.json({ success: true, token, user, }); } catch (e) { console.log(e.message); res.json({ success: false, message: e.message }); } }, getUserById: async (req, res) => { try { const user = await userService.getUserById(req.params.userId); res.json({ success: true, data: user }); } catch (e) { res.json({ success: false, message: e.message }); } }, getUsers: async (req, res) => { try { const users = await userService.findUsers(); res.json({ success: true, data: users }); } catch (e) { res.json({ success: false, message: e.message }); } }, updateUser: (req, res) => { const user = req.body; UserMongo.findByIdAndUpdate(user._id, user) .then((_data) => { res.json({ success: true, data: _data }); }) .catch((err) => { res.json({ success: true, data: err }); }); }, deleteUser: async (req, res) => { try { await userService.deleteUser(req.params.id); res.json({ success: true }); } catch (e) { console.log('error catched'); res.json({ success: false, message: e.message }); } }, addRoleToUser: async (req, res) => { try { const user = await userService.findUserById(req.params.userId); const role = await userService.findRoleById(req.params.roleId); await user.addRole(role); res.json({ success: true, data: await userService.findUserById(req.params.userId) }); } catch (e) { res.json({ success: false, message: e.message }); } }, removeRoleFromUser: async (req, res) => { try { const user = await userService.findUserById(req.params.userId); const role = await userService.findRoleById(req.params.roleId); await user.removeRole(role); res.json({ success: true, data: await userService.findUserById(req.params.userId) }); } catch (e) { res.json({ success: false, message: e.message }); } }, getRoles: async (req, res) => { try { const roles = await userService.getRoles(); res.json({ success: true, data: roles }); } catch (e) { console.log(e); res.json({ success: false, message: e.message }); } }, isValidToken: (req, res) => { const token = req.body.token || req.headers['x-access-token']; if (token) { jwt.verify(token, process.env.SECRET, (err, decoded) => { if (err) { return res.json({ success: false, message: 'Virheellinen token' }); } req.decoded = decoded; res.json({ success: true, message: 'Validi token' }); }); } else { res.status(403).send({ success: false, message: 'Tokenia ei saatu', }); } }, checkToken: (req, res, next) => { const token = req.headers['x-access-token']; if (token) { jwt.verify(token, process.env.SECRET, (err, decoded) => { if (err) { return res.json({ success: false, message: 'Virheellinen token' }); } req.decoded = decoded; next(); }); } else { res.status(403).send({ success: false, message: 'missing jwt', }); } }, isHallitus: async (req, res, next) => { const user = await userService.findUserById(req.decoded.id); const isHallitus = user.Roles.filter(role => role.value === 4).length > 0; if (!isHallitus) { res.json({ success: false, message: 'Hallitusoikeudet vaadittu' }); } else next(); }, isWebmaster: async (req, res, next) => { const user = await userService.findUserById(req.decoded.id); const isWebmaster = user.Roles.filter(role => role.value === 5).length > 0; if (!isWebmaster) { res.json({ success: false, message: 'Webmaster-oikeudet vaadittu' }); } else next(); }, }; const generateHash = (password) => { return new Promise((resolve, reject) => { bcrypt.hash(password, 10, (err, hash) => { if (err) { reject(err); } else { resolve(hash); } }); }); }; async function isPasswordCorrect(password, hash) { try { const res = await bcrypt.compare(password, hash); return res; } catch (e) { console.log(e); return false; } } <file_sep>/src/client/reducers/messageReducer.js import { actions } from '../actions/messageActions'; const initialState = []; const messages = (state = initialState, action) => { switch (action.type) { case actions.ADD_MESSAGE: return [ ...state, { ...action.message, fading: false }, ]; case actions.CLEAR_MESSAGES: return []; case actions.CLOSE_MESSAGE: return [ ...state.filter(message => message.id !== action.id), ]; case actions.FADE_OUT: return [ ...state.map((message) => { if (message.id === action.id) { return { ...message, fading: true }; } return message; }), ]; default: return state; } }; export default messages; <file_sep>/src/client/components/Loader/Loader.js import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import styles from './Loader.css'; const Loader = ({ loading }) => { return ( <div className={`${styles.overlay} ${loading ? styles.show : ''}`}> <div className={styles.ldsDefault}><div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> <div /> </div> </div> ); }; Loader.propTypes = { loading: PropTypes.bool, }; const mapStateToProps = state => ({ loading: state.loader.loading, }); const mapDispatchToProps = dispatch => ({ }); export default connect(mapStateToProps, mapDispatchToProps)(Loader); <file_sep>/scripts/utils.sh getCommitHash() { git log --pretty=format:'%h' -n 1 } readonly DOCKER_IMAGE_NAME="hybridispeksi/web" readonly DOCKER_IMAGE_TAG=$(getCommitHash) <file_sep>/src/api/esitykset/maksut.js const Varaus = require('../../schema/varaus-model'); const Esitys = require('../../schema/esitys-model'); const mailer = require('../../utils/mailer'); const config = require('../../config'); const crypto = require('crypto'); module.exports = { handleSuccess: (req, res) => { let kauppiastunnus; let kauppiasvarmenne; if (process.env.NODE_ENV === 'develop') { kauppiastunnus = config.kauppiastunnus; kauppiasvarmenne = config.kauppiasvarmenne; } else { kauppiastunnus = process.env.KAUPPIASTUNNUS; kauppiasvarmenne = process.env.KAUPPIASVARMENNE; } const ordernumber = req.query.ORDER_NUMBER; const timestamp = req.query.TIMESTAMP; const paid = req.query.PAID; const method = req.query.METHOD; const authcode = req.query.RETURN_AUTHCODE; const params = ordernumber + '|' + timestamp + '|' + paid + '|' + method + '|' + kauppiasvarmenne; let booking; if (checkValidity(params, authcode)) { Varaus.findOne({ _id: ordernumber }) .then((_booking) => { _booking.paid = true; booking = _booking; return _booking.save(); }) .then(() => Esitys.findOne({ _id: booking.esitysId })) .then((_esitys) => { booking.esitys = _esitys; return mailer.sendTicket(booking); }) .then(() => { res.redirect('/speksi2018/vahvistus/' + booking._id); }) .catch((err) => { console.log(err); if (err.ohjaustietoValue) { res.redirect('/speksi2018/virhe/' + err.ohjaustietoValue); } else res.redirect('/speksi2018/virhe/0'); }); } else { res.redirect('/speksi2018/virhe/2'); } }, handleFailure: (req, res) => { Varaus.remove({ _id: req.query.ORDER_NUMBER }).then(() => { console.log('Booking removed with _id ' + req.query.ORDER_NUMBER); console.log('Payment event failed'); }); res.redirect('/speksi2018/virhe/1'); }, handleNotify: (req, res) => { let kauppiastunnus; let kauppiasvarmenne; if (process.env.NODE_ENV === 'develop') { kauppiastunnus = config.kauppiastunnus; kauppiasvarmenne = config.kauppiasvarmenne; } else { kauppiastunnus = process.env.KAUPPIASTUNNUS; kauppiasvarmenne = process.env.KAUPPIASVARMENNE; } const ordernumber = req.query.ORDER_NUMBER; const timestamp = req.query.TIMESTAMP; const paid = req.query.PAID; const method = req.query.METHOD; const authcode = req.query.RETURN_AUTHCODE; const params = ordernumber + '|' + timestamp + '|' + paid + '|' + method + '|' + kauppiasvarmenne; let booking; if (checkValidity(params, authcode)) { Varaus.findOne({ _id: ordernumber }) .then((_booking) => { if (_booking.paid) { return new Promise((resolve, reject) => { reject('Payment already handled, rejecting case.'); }); } _booking.paid = true; booking = _booking; return _booking.save(); }) .then(() => Esitys.findOne({ _id: booking.esitysId })) .then((_esitys) => { booking.esitys = _esitys; return mailer.sendTicket(booking); }) .then(() => { res.redirect('/speksi2018/vahvistus/' + booking._id); }) .catch((err) => { console.log(err); if (err.ohjaustietoValue) { res.redirect('/speksi2018/virhe/' + err.ohjaustietoValue); } else res.redirect('/speksi2018/virhe/0'); }); } else { res.redirect('/speksi2018/virhe/2'); } }, }; function checkValidity(params, authcode) { const hash = crypto .createHash('md5') .update(params) .digest('hex'); if (hash.toUpperCase() === authcode.toUpperCase()) { console.log('valid'); return true; } return false; } <file_sep>/src/client/components/Speksi2018/Speksi2018.test.js import React from 'react'; import Speksi2018 from './Speksi2018'; import Esitysvalinta from './Esitysvalinta'; import Uusivaraus from './UusiVaraus'; const esitykset = [ { _id: 1, day: 'Lauantai', date: new Date('2017-12-17T03:24:00'), name: '<NAME>', }, { _id: 2, day: 'Sunnuntai', date: new Date('2017-12-17T03:24:00'), name: 'Sunnuntai', }, ]; describe('Speksi2018', () => { it('renders without crashing', () => { const wrapper = render(<Speksi2018 />); expect(wrapper).toMatchSnapshot(); }); it('shows list of shows without crashing', () => { const wrapper = shallow(<Esitysvalinta esitykset={esitykset} />); expect(wrapper).toMatchSnapshot(); }); it('shows UusiVaraus form with proper fielsd', () => { const component = ( <Uusivaraus handleChange={() => console.log('change')} handleSubmit={() => { console.log('submit'); }} fname="Seppo" sname="Silander" email="<EMAIL>" pnumber="04040404040" ncount={1} scount={2} ocount={3} price="78" lisatiedot="asdf" valittuEsitys={{ _id: 1, day: 'Lauantai', date: new Date('2017-12-17T03:24:00'), name: '<NAME>', }} esitykset={esitykset} messages={{}} ilmottu={false} /> ); const wrapper = shallow(<component />); expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/src/client/components/HeroFullViewport/HeroFullViewport.js import React from 'react'; import PropTypes from 'prop-types'; import styles from './HeroFullViewport.css'; /** * * @param {backgroundImage} param0 * Renders full viewport hero with possible background-image. Renders content middle */ const HeroFullViewport = (props) => { const { backgroundImage } = props return ( <div className={styles.container} style={{ background: 'url(' + backgroundImage + ') center bottom no-repeat / cover' }}> {props.children} </div> ); }; HeroFullViewport.propTypes = { backgroundImage: PropTypes.string, children: PropTypes.any, }; export default HeroFullViewport; <file_sep>/src/client/components/Admin/BookingManagement/ShowsManagement.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import Moment from 'react-moment'; import PropTypes from 'prop-types'; import ShowsList from './ShowsList'; import * as actions from 'actions/bookingActions'; import styles from './ShowsManagement.css'; import pagestyles from './BookingManagement.css'; import * as messageActions from 'actions/messageActions'; import { RenderTextfield, RenderNumber, RenderDateField } from './RenderForm'; const ShowInfo = ({ show, deleteShow, toggleShowForm }) => { if (!show.id) return null; return ( <React.Fragment> <h2>Esityksen tiedot</h2> <p>{show.nameLong}</p> <p><Moment format="DD.MM.YYYY HH.mm">{show.date}</Moment></p> <div className={pagestyles.formRow}> <button className={pagestyles.button} onClick={toggleShowForm}>Muokkaa</button> <button onClick={deleteShow} className={`${pagestyles.button} ${pagestyles.danger}`}>Poista</button> </div> </React.Fragment> ); }; ShowInfo.propTypes = { show: PropTypes.object, deleteShow: PropTypes.func, toggleShowForm: PropTypes.func, }; const Shows = ({ showForm, toggleShowForm, clearSelectedShow }) => { return ( <React.Fragment> <ShowsList /> {!showForm ? ( <div className={pagestyles.formRow}> <button className={pagestyles.button} onClick={() => { clearSelectedShow(); toggleShowForm(); }}> Lisää uusi esitys </button> </div> ) : null} <Link to="varaustenhallinta">Palaa varaustenhallintaan</Link> </React.Fragment> ); }; Shows.propTypes = { toggleShowForm: PropTypes.func, showForm: PropTypes.bool, clearSelectedShow: PropTypes.func, }; const Form = ({ isNewShow, toggleShowForm, handleSubmit }) => { return ( <form onSubmit={handleSubmit} className={styles.form}> <h2>Hallinta</h2> <div className={pagestyles.formRow}> <Field name="date" id="dateInput" type="date" component={RenderDateField} label="Päivämäärä ja aika" /> <Field name="limit" id="limitInput" type="number" component={RenderNumber} label="Katsojamäärä" /> </div> <div className={pagestyles.formRow}> <Field name="nameLong" id="nameLongInput" component={RenderTextfield} label="Esityksen nimi, pitkä" /> </div> <div className={pagestyles.formRow}> <Field name="nameShort" id="nameShortInput" component={RenderTextfield} label="Esityksen nimi, lyhyt" /> </div> <div className={pagestyles.formRow}> <button type="submit" className={pagestyles.button}>{isNewShow ? 'Lisää uusi esitys' : 'Tallenna muutokset'}</button> <button onClick={toggleShowForm} className={pagestyles.button}>Peruuta</button> </div> </form> ); }; Form.propTypes = { toggleShowForm: PropTypes.func, handleSubmit: PropTypes.func, }; class ShowsManagement extends Component { constructor() { super(); this.state = { showForm: false, }; this.toggleShowForm = this.toggleShowForm.bind(this); } componentDidMount() { if (this.props.shows.length < 1) this.props.fetchShows(); } toggleShowForm() { this.setState(prevState => ({ showForm: !prevState.showForm, })); } render() { const { selectedShow, deleteShow, createShow, updateShow, addWarningMessage, handleSubmit, clearSelectedShow, } = this.props; const { showForm } = this.state; const handleDelete = () => { if (selectedShow.bookingCount > 0) { addWarningMessage({ header: 'Esitystä ei voi poistaa, sillä siihen on tehty varauksia.' }); return; } if (confirm('Poistetaanko esitys?')) { deleteShow(selectedShow); } }; const isNewShow = selectedShow.id === ''; const onSubmit = (values) => { if (isNewShow) { createShow(values); } else { updateShow(values); } }; return ( <div className={styles.container}> <div className={styles.showsList}> <h2>Esitykset</h2> <Shows showForm={showForm} toggleShowForm={this.toggleShowForm} clearSelectedShow={clearSelectedShow} /> </div> <div className={styles.showInfo}> <ShowInfo show={selectedShow} deleteShow={handleDelete} toggleShowForm={this.toggleShowForm} /> </div> {showForm ? ( <Form toggleShowForm={this.toggleShowForm} handleSubmit={handleSubmit(onSubmit)} isNewShow={isNewShow} /> ) : null} </div> ); } } ShowsManagement.propTypes = { shows: PropTypes.array, selectedShow: PropTypes.object, addWarningMessage: PropTypes.func, fetchShows: PropTypes.func, deleteShow: PropTypes.func, updateShow: PropTypes.func, createShow: PropTypes.func, clearSelectedShow: PropTypes.func, handleSubmit: PropTypes.func, }; const mapStateToProps = state => ({ shows: state.bookingManagement.shows, selectedShow: state.bookingManagement.selectedShow, initialValues: state.bookingManagement.selectedShow, }); const mapDispatchToProps = dispatch => ({ fetchShows: () => dispatch(actions.fetchShows()), addWarningMessage: message => dispatch(messageActions.addWarningMessage(message)), createShow: show => dispatch(actions.createShow(show)), updateShow: show => dispatch(actions.updateShow(show)), deleteShow: show => dispatch(actions.deleteShow(show)), clearSelectedShow: () => dispatch(actions.clearSelectedShow()), }); const ShowsManagementWithReduxForm = reduxForm({ form: 'showForm', enableReinitialize: true, })(ShowsManagement); export default connect(mapStateToProps, mapDispatchToProps)(ShowsManagementWithReduxForm);
32063be2be727a42a880caf108d6ce1b77ec0622
[ "Markdown", "JavaScript", "Dockerfile", "Shell" ]
127
Markdown
HybridiSpeksi/hybridispeksi
e4a7c07c3286d218233cb99a177e5d5b6360fba0
2776551ab5a766b1464c9d5785bdaa3ab635c0ff
refs/heads/master
<file_sep><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\MainController; use Illuminate\Support\Facades\Auth; // Route::get('/', function () { // return view('welcome'); Auth::routes([ 'reset' => false, 'confirm' => false, 'verify' => false ]); Route::get('/',[MainController::class, 'index'])->name('welcome'); Route::delete('/courses/{course}', [App\Http\Controllers\HomeController::class, 'destroy'])->name('course.destroy'); Route::post('/', [MainController::class, 'formconfirm'])->name('formconfirm'); Auth::routes(); Route::get('/logout', 'App\Http\Controllers\Auth\LoginController@logout')->name('getlogout'); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::post('/home', [App\Http\Controllers\HomeController::class, 'addcourse'])->name('addcourse'); Route::group(['middleware' => 'auth'], function() { Route::resource('formusers', 'Admin\FormuserController')->except([ 'destroy' ]); Route::delete('/formusers/{formuser}', [App\Http\Controllers\Admin\FormuserController::class, 'destroy'])->name('formuser.destroy'); }); Route::get('/coursesinfo', function () { return view('coursesinfo'); })->name("coursesinfo"); <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\FormConfirm; use App\FormUser; use App\Course; use Illuminate\Http\Request; class MainController extends Controller { public function index() { $courses = Course::all(); return view('welcome', compact('courses')); //return view('welcome'); } public function formconfirm(FormConfirm $request) { $formuser = new FormUser; $formuser->name = $request->name; $formuser->email = $request->email; $formuser->phone = $request->phone; $formuser->course = $request->course; $formuser->password = $request->password; try { $formuser->save(); session()->flash('success', 'Ваша заявка принята! Вам скоро перезвонят.'); } catch(\Illuminate\Database\QueryException $e) { session()->flash('denied', 'Пользователь с данным e-mail уже зарегистрирован.'); } return redirect()->route('welcome'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\CourseConfirm; use App\FormUser; use App\Course; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $formusers = FormUser::all(); return view('home', compact('formusers')); } public function addcourse(CourseConfirm $request) { $course = new Course; $course->course_id = $request->course_id; $course->course_full_name = $request->course_full_name; $course->course_short_name = $request->course_short_name; // dd($course); $course->save(); session()->flash('success', 'Курс добавлен!'); return redirect()->route('home'); } public function destroy(Course $course) { $course->delete(); return redirect()->route('welcome'); } } <file_sep>В данном репозитории засположен проект, который был залит на хостинг Heroku, так как в нем производились дополнительные настройки. # Инженерный проект 7 семестр Часть диплома - связь сайта с БД moodle ### Выполнила: | Учебная группа | Имя пользователя | ФИО | |----------------|---------------------|----------------------| | 171-332 | @afluttershy | <NAME>. | ### Ссылка на проект: http://ip-moodle.herokuapp.com/ ### Ссылка на лендинг проекта: http://ip7-landing.std-234.ist.mospolytech.ru/ ### Ссылка на облако с проектом: https://drive.google.com/drive/folders/1fodu-LDwQUJ6-2n_oHv-LpDgSpB7T3AZ?usp=sharing <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Course extends Model { protected $table = 'courses'; protected $fillable = ['course_id', 'course_full_name', 'course_short_name']; }
f40c2beb6f5ab497f855a79e9ab7076910e18f10
[ "Markdown", "PHP" ]
5
PHP
afluttershy/ip-moodle-heroku
53654e6031d47c84345a2f4da9902acddad4c2f5
1cab1fd0c3e64b93fd4f83c69e636af2e81d7624
refs/heads/master
<repo_name>WMdaini/cars-managment-frontend<file_sep>/src/app/core/service/comment.service.ts import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {Car, Comment} from '../generatedResource'; import {environment} from '../../../environments/environment'; @Injectable({ providedIn: 'root' }) export class CommentService { constructor(private http: HttpClient) { } getCommentByCar(car: Car): Observable<Comment[]> { return this.http.post<Comment[]>(environment.baseUrl + 'comment/getComments', car); } addComment(comment: Comment): Observable<Comment> { return this.http.post<Comment>(environment.baseUrl + 'comment/addComment', comment); } } <file_sep>/src/app/authentification/authentification.component.ts import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {AuthService} from '../core/service/auth.service'; @Component({ selector: 'app-authentification', templateUrl: './authentification.component.html', styleUrls: ['./authentification.component.css'] }) export class AuthentificationComponent implements OnInit { formGroup: FormGroup; submitted = false; isValid = true; constructor(private authService: AuthService, private formBuilder: FormBuilder) { } ngOnInit(): void { this.initFormGroup(); } login() { this.submitted = true; if (this.formGroup.invalid) { return; } this.authService.login(this.formGroup.value).subscribe(response => { (response ? this.authService.authUser = response : this.isValid = false); }); } private initFormGroup() { this.formGroup = this.formBuilder.group({ login: ['', [Validators.required]], password: ['', [Validators.required]] }); } get f() { return this.formGroup.controls; } } <file_sep>/src/app/core/generatedResource.ts export interface Car { idCar: number; registrationNumber: string; brand: string; picture: string; description: string; model: string; } export interface Comment { idComment: number; comment: string; date: Date; car: Car; user: User; } export interface User { idUser: number; login: string; password: string; } <file_sep>/src/app/app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {InputTextModule} from 'primeng/inputtext'; import {HomeComponent} from './home/home.component'; import {AuthentificationComponent} from './authentification/authentification.component'; import {HttpClientModule} from '@angular/common/http'; import {SharedModule} from 'primeng/api'; import {RatingModule} from 'primeng/rating'; import {ButtonModule} from 'primeng/button'; import {CardModule} from 'primeng/card'; import {DialogModule} from 'primeng/dialog'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent, HomeComponent, AuthentificationComponent ], imports: [ BrowserModule, AppRoutingModule, InputTextModule, HttpClientModule, SharedModule, RatingModule, ButtonModule, CardModule, DialogModule, BrowserAnimationsModule, ReactiveFormsModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/core/service/car.service.ts import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {environment} from '../../../environments/environment'; import {Car} from '../generatedResource'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CarService { constructor(private http: HttpClient) { } getAllCars(): Observable<Car[]> { return this.http.get<Car[]>(environment.baseUrl + 'car/getAll'); } } <file_sep>/src/app/home/home.component.ts import {Component, OnInit} from '@angular/core'; import {CarService} from '../core/service/car.service'; import {Car, Comment} from '../core/generatedResource'; import {environment} from '../../environments/environment'; import {CommentService} from '../core/service/comment.service'; import {AuthService} from '../core/service/auth.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { cars: Car[] = []; comments: Comment[] = []; selectedCar: Car = {} as Car; baseUrl = environment.baseUrl; displayModal = false; commentText = ''; constructor(private carService: CarService, private commentService: CommentService, public authService: AuthService) { } ngOnInit(): void { this.getAllCars(); } private getAllCars() { this.carService.getAllCars().subscribe(response => { this.cars = response; }); } getComments(car: Car) { this.displayModal = true; this.selectedCar = car; this.commentService.getCommentByCar(car).subscribe(response => { this.comments = response; }); } addComment() { if (this.commentText !== '') { let comment: Comment = {} as Comment; comment.date = new Date(); comment.user = this.authService.authUser; comment.comment = this.commentText; comment.car = this.selectedCar; this.commentService.addComment(comment).subscribe(response => { if (response) { this.comments.push(response); } }); } } } <file_sep>/src/app/core/service/auth.service.ts import {Injectable} from '@angular/core'; import {User} from '../generatedResource'; import {HttpClient} from '@angular/common/http'; import {environment} from '../../../environments/environment'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { authUser: User; constructor(private http: HttpClient) { } login(user: User): Observable<User> { return this.http.post<User>(environment.baseUrl + 'auth/login', user); } }
b76679da63397c05ac988f1e4bc27b07aee6884b
[ "TypeScript" ]
7
TypeScript
WMdaini/cars-managment-frontend
9b4127884fdcd6fe151e4e1c4f78ee648ad04c3f
d63f3f5535b73ff10b6e500b4af6e6389a3fedbb
refs/heads/master
<file_sep>var now; var fileName; var inputElement = document.getElementById("input"); function handleFiles() { var fileList = this.files; fileName = fileList[0].name; // Create a root reference var storageRef = firebase.storage().ref(); // Create a reference to 'images/tree.jpg' var treeImagesRef = storageRef.child('images/' + 'IMG' + now + '_' + fileName); treeImagesRef.put(fileList[0]).then(function(snapshot) { }); } inputElement.addEventListener("change", handleFiles, false); $(document).ready(function() { function writeTreeData(lat, long, acc, serialN, img) { firebase.database().ref('trees/' + serialN).set({ latitude: lat, longitude: long, accuracy: acc, image: img }); } // setTimeout(function ab(){ function geo() { // setTimeout( function() { if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function(location) { $("#coordinates").html( "<h3>Current coordinates</h3> Latitude: " + Math.round(location.coords.latitude * 100) / 100 + "<br>Longitude: " + Math.round(location.coords.longitude * 100) / 100 + "<br>Accuracy: " + location.coords.accuracy + " meters" ); now = (new Date).getTime(); $("#serialnumber").html("Serial number: <br>" + now); $("#button").click(function() { if (fileName) { writeTreeData(location.coords.latitude, location.coords.longitude, location.coords.accuracy, now, 'IMG' + now + '_' + fileName); $("#trees").html(""); // setTimeout(function bc(){ displayTreeEntries(); // }, 15); } else { alert("Don't forget the picture!"); } }); }); } else { $("#coordinates").html("Geolocation not available"); } // callback(); // }, 100); // setTimeout(cb,0); } // }, 0); geo(); function displayTreeEntries() { return firebase.database().ref('/trees/').limitToLast(5).once('value').then(function(snapshot) { var trees = snapshot.val(); for (var treeSN in trees) { // skip loop if the property is from prototype if (!trees.hasOwnProperty(treeSN)) continue; var obj = trees[treeSN]; for (var prop in obj) { // skip loop if the property is from prototype if (!obj.hasOwnProperty(prop)) continue; if (prop!=="image") { $("#trees").prepend("<p>" + prop + " = " + obj[prop] + "</p>"); } } for (var prop in obj) { if (!obj.hasOwnProperty(prop)) continue; if (prop=="image") { $("#trees").prepend('<p id="'+obj[prop]+'">' + prop + " = " + obj[prop] + "</p>") } } $("#trees").prepend("<p><strong>Tree SN = " + treeSN + "</strong></p>"); } }); } function displayTreePics() { var IDs = []; $("#trees").find("p").each(function(){ IDs.push(this.id); }); // console.log(IDs); for (var i = 0; i < IDs.length; i++) { (function(i) { if (IDs[i]) { //Do something // console.log(IDs[i]); var element = document.getElementById(IDs[i]); var storageRefff = firebase.storage().ref(); var starsReff = storageRefff.child('images/'+IDs[i]); starsReff.getDownloadURL().then(function(url) { var newElement = ""; newElement = '<img src="'+ url +'" alt="Tree picture" width="200">'; // console.log(element); // console.log(newElement); element.innerHTML = newElement; }); } })(i); } } // setTimeout(function cd(){ displayTreeEntries(); // }, 15); setTimeout(function(){ // console.log("im ready"); displayTreePics(); }, 1500); $("#button-pics").click(function() { displayTreePics(); }); });
c3e891368ea702e0110119122d23be4e15e29ba9
[ "JavaScript" ]
1
JavaScript
emiliodib/hyperdev
a9fe3ebb4b7da278836ec62f0031ac7814871376
2ac2ce6add11553d2e328159da1d863f9de479ec
refs/heads/main
<file_sep>### Qn1 Estimate the magnitude and phase shift given h\[n\] We calculate H(z) from h\[n\], then sub in the omega of x\[n\] to see the magnitude and phase shift for xn = cos(0.1pin) and hn = {0.1,0.2,0.3} Punch in matlab: 0.1*exp(-0.1*pi*i)+0.2*exp(-0.1*pi*i)+0.3*exp(-0.1*pi*i) \[Out\]:0.5706 - 0.1854i Mag times 0.576, phase shift by -0.185 ### Qn2 y(n) = 10x(n) +2x(n-1) +alpha y(n-1) H(z) = (10+2z)/(z-alpha) Now to make it generate a finite impulse response aka no feedback term, the A(z) has to have order 1 (or any other method that destroy the feedback term of this system) This means alpha can be -0.2, making H(z) = 10 System is now just opamps gain 10. ### Qn3 Echo due to the output being a system of delayed input*gain See [here](http://personal.ee.surrey.ac.uk/Personal/P.Jackson/ee1.lab/D3_echo/D3_EchoAndReverberationExpt.pdf) for more details Q3c fast convolution: Assuming have the smaller array sliding on top of the big array, like this Smol array \[5 0 4 3\] Big array \[1 0 2 3 4 5 6 7 8 1 2 3 4 5 6 7\] At each step we take the dot product of the smol array and the overlapped region of the big array. We can optimize this in 2 ways If smol array is sparse, only multiply in the non-zero value Smol array \[0 0 4 0\] Big array \[1 0 2 3 4 5 6 7 8 1 2 3 4 5 6 7\] Do 4\*8 instead of 0\*6+0\*0+4\*8+0\*1 Another is to only start the dot product when the big array is non zero Smol array \[5 0 4 3\] Big array \[0 0 0 0 0 0 6 7 8 1 2 3 4 5 6 7\] Both methods rely heavily on determining the sparsity of the matrices. How efficient is that? idk. Might as well just write in C++ and use BLAS. ### Qn 4 a) Attenuate signal strength at frequency 3000Hz b) h1n has LP cut off at fH = 0.18 (normalized over pi) aka 0.182pi rad/sample h2n has HP cutoff at fL = 0.29 combining h1n and h2n fL>fH This toolbox uses the convention that unit frequency is the Nyquist frequency, defined as half the sampling frequency. The normalized frequency, therefore, is always in the interval 0 f 1. For a system with a 1000 Hz sampling frequency, 300 Hz is 300/500 = 0.6. To convert normalized frequency to angular frequency around the unit circle, multiply by . To convert normalized frequency back to hertz, multiply by half the sample frequency. A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. When applied to an audio signal, spectrograms are sometimes called sonographs, voiceprints, or voicegrams. When the data are represented in a 3D plot they may be called waterfalls. A common format is a graph with two geometric dimensions: one axis represents time, and the other axis represents frequency; a third dimension indicating the amplitude of a particular frequency at a particular time is represented by the intensity or color of each point in the image. ### Qn 5 put B and A into fvtool, click on impulse response, record value see the cutoff frequency from magnitude response, take that value *Fs/2 to yield band reject fRJ in Hz See if ur signal contain anot ### Qn 6 arrange to some y = some x Coefficients of x will form B Coefficients of y will form A Use fvtool, click on filter info c) fvtool, impulse response <file_sep>import numpy as np import matplotlib.pyplot as plt from scipy import signal import math def myDTFS(x): X = np.zeros(len(x), dtype=complex) Omega = np.zeros(len(x)) N = len(x) for k in np.arange(0,len(x)): tmpVal = 0.0 Omega[k] = (2*np.pi/N)*k for n in np.arange(0,len(x)): tmpVal = tmpVal + x[n]*np.exp(-1j*(2*np.pi/N)*k*n) X[k] = tmpVal/N return (X,Omega) def myIDTFS(X): x = np.zeros(len(X), dtype=float) N = len(x) for n in np.arange(0,len(x)): tmpVal = 0.0 for k in np.arange(0,len(X)): tmpVal = tmpVal + X[k]*np.exp(+1j*(2*np.pi/N)*k*n) x[n] = np.absolute(tmpVal) return (x) def myDFT(x): X = np.zeros(len(x), dtype=complex) Omega = np.zeros(len(x)) N = len(x) for k in np.arange(0,len(x)): tmpVal = 0.0 Omega[k] = (2*np.pi/N)*k for n in np.arange(0,len(x)): tmpVal = tmpVal + x[n]*np.exp(-1j*(2*np.pi/N)*k*n) X[k] = tmpVal return (X,Omega) def myIDFT(X): x = np.zeros(len(X), dtype=float) N = len(x) for n in np.arange(0,len(x)): tmpVal = 0.0 for k in np.arange(0,len(X)): tmpVal = tmpVal + X[k]*np.exp(+1j*(2*np.pi/N)*k*n) x[n] = np.absolute(tmpVal)/N return (x) def plotMagPhase(x,rad): f, axarr = plt.subplots(2, sharex=True) x = np.absolute(x) axarr[0].stem(np.arange(0,len(x)), x) axarr[0].set_ylabel('mag value') axarr[1].stem(np.arange(0,len(rad)), rad) axarr[1].set_ylabel('Phase (rad)') plt.show() def plotK(W): f, axarr = plt.subplots() phaseW = np.angle(W) print(phaseW) axarr.stem(np.arange(0,len(phaseW)),phaseW) plt.show() print("\n\n\n") def plotDTFSDTFTMag(X): N = len(X) x = np.absolute(X) f, axarr = plt.subplots(figsize=(18, 2.5)) axarr.stem(np.arange(0,N), x) axarr.set_ylabel('DTFS mag value') plt.show() x = [element * N for element in x] f, axarr = plt.subplots(figsize=(18, 2.5)) axarr.stem(np.arange(0,N), x) axarr.set_ylabel('DTFT mag value') ticks = range(N) ticks = [round(element * 2/N,2) for element in ticks] # ticks = [round(element * 2 *np.pi/N,2) for element in ticks] plt.xticks(np.arange(0,N), ticks) plt.xlabel('w*pi (rad/sample) ') plt.show() print("\n\n\n") <file_sep>""" This is answer to DSP Tut 1 Signals Author: <NAME> Date: 1st Dec 2018 """ import numpy as np from scipy.ndimage.interpolation import shift import matplotlib.pyplot as plt import time def Tut1_Q1d(): n = np.arange(-20,20) K=3 y = np.zeros((K,len(n)),dtype=np.float) y[0,:] = 3*np.cos(np.pi/6*n+np.pi/3) y[1,:] = 1*np.sin(1.8*np.pi*n) y[2,:] = 1*np.cos(0.5*n) fig, axs = plt.subplots(K, 1) opStr = 'Q1d solution' axs[0].set_title(opStr) for i in [0,1,2]: axs[i].stem(n, y[i,:],'r-+') axs[i].grid() plt.show() def Tut1_Q1e(): # to understand 1.8\pi rad per second, # lets plot it with CT , i.e, time can be in floating point t = np.arange(-10,10,1/1000.0) yCT = 1*np.sin(1.8*np.pi*t) fig, axs = plt.subplots(1, 1) axs.plot(t, yCT, 'g-') n = np.arange(-10,10) yDT = 1*np.sin(1.8*np.pi*n) axs.plot(n, yDT, 'r-+') axs.grid() opStr = 'Q1e solution' axs.set_title(opStr) axs.set_xlabel('sample n (integer) vs t(seconds) ') axs.set_ylabel('y[n] vs y(t)') plt.show() # def Tut1_Q1g(): n = np.arange(-20,50) K=2 y = np.zeros((K,len(n)),dtype=np.float) C = 3 phaseShift = np.pi/3 y[0,:] = C*np.cos(np.pi/6*n+phaseShift) A = C*np.cos(phaseShift) B = C*np.sin(phaseShift) y[1,:] = A*np.cos(np.pi/6*n)+ (-1)*B*np.sin(np.pi/6*n) fig, axs = plt.subplots(1, 1) axs.plot(n, y[0,:], 'r-+') axs.plot(n, y[1,:], 'go') axs.grid() opStr = 'Q1g solution' axs.set_title(opStr) axs.set_xlabel('sample n') axs.set_ylabel('y[n]') plt.show() def Tut1_Q8(): # y[n] = 2x[n]+x[n-1] - x[n-3] # first method, use scale * delayed impulse create by identity matrix xEye = np.identity(10) print(xEye) y1 = 2*xEye[0,:] + 1*xEye[1,:] - 1*xEye[3,:] print('The impulse response = ',y1) h = [2,1,0,-1] # the impulse is by inspection of the equation, the coefficients at each delay y2 = np.convolve(h,xEye[0,:]) print('Using convolution y2 = ',y2) def Tut1_Q10(): N = 50 n= np.arange(-N,N+1) print(n) leftN = np.arange(-N,+1) print(leftN) hleft = np.zeros(N) hleft = (4/7)*np.power(2.0, leftN) print(hleft) rightN = np.arange(1,N+1) print(rightN) hright = np.zeros(len(rightN)) hright = (11/7)*np.power(0.25, rightN-1) print(hright) h = np.zeros(len(n)) h[0:len(hleft)] = hleft h[len(hleft):len(h)] = hright fig, axs = plt.subplots(1, 1) axs.stem(n, h, 'g-') plt.grid() plt.show() def main(): print("python main function") Tut1_Q1d() Tut1_Q1e() Tut1_Q1g() Tut1_Q8() Tut1_Q10() if __name__ == '__main__': main() <file_sep># -*- coding: utf-8 -*- """ Created on Sat Dec 2 13:10:08 2017 @author: <NAME> Date: Dec 2017, using python to solve DSP problems purpose - to remove dependency on Matlab """ # this is lab 2 example, in which we will load a waveform, # listen to it # plot its time domain sequence, # plot its spectrogram import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile as wavfile import winsound from scipy import signal # this is FIR filter assuming A=[1] def myfilter_Bonly(B,X): numNum = len(B) memX = np.zeros(numNum) B_np = np.array(B) y = np.zeros(len(X)) for i in np.arange(len(X)): # doing the left side of DF1 structure memX[0] = X[i] #rolling in the memory X input vec_left_op = np.multiply(memX,B_np) y[i] = np.sum(vec_left_op) memX = np.roll(memX,1) # getting ready for the next step memX[0] = 0 # we use roll, so circular shift, lets 0 shifted in element 0 return y print("Example of Lab2 for filter operation CE3007") # generate the impulse response using scipy.signal.lfilter module # where num and den are the coefficients of the linear constant coefficients numSamples = 50 n = np.arange(0,numSamples,1) impulseX = np.zeros(numSamples) impulseX[0] = 1 num = [3.1, 2.1, -1.0] den = [1] my = myfilter_Bonly(num,impulseX) # the above filter only has feedforward (num) coeff B, # the feedback (den) coeff A = [1]. # you will need to implement this mylfilter # which also has feedback coeff (den), WITH condition that den[0] = 1 #num = [1, -0.7653668, 0.99999] #den = [1, -0.722744, 0.888622] #my = mylfilter(num,den,impulseH) y = signal.lfilter(num, den, impulseX) plt.stem(n, y,'r') plt.plot(my,'g--') plt.show() #sanity check that my implemetation is the same as signal.lfilter # lets check of the two sequences are the same if np.array_equal(np.around(y,decimals=10),np.around(my,decimals=10)): print('PASS = my op sequence same as signal.lfilter') else: print('ERROR = my op sequence differ as signal.lfilter') for i in np.arange(len(my)): if y[i] != my[i]: print(i,y[i],my[i])<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jan 19 10:35:41 2021 @author: hoang """ import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10,10,100) y = np.cos(x) plt.plot(x,y) plt.show() plt.stem(x,y,use_line_collection=True,basefmt="b") plt.show()<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jan 19 10:48:33 2021 @author: hoang """ import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile as wavfile import winsound # plotting 3D complex plane from mpl_toolkits.mplot3d import Axes3D <file_sep># NTU-CE3007_DigitalSignalProcessing DSP lo <file_sep># -*- coding: utf-8 -*- """ Created on Tue Jan 19 10:48:33 2021 @author: hoang """ import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile as wavfile import winsound # plotting 3D complex plane from mpl_toolkits.mplot3d import Axes3D # This is an example of using python to generate a discrete time sequence # with time, value pair of a sinusoid # The following function generates a continuous time sinusoid # given the amplitude A, F (cycles/seconds), Fs=sampling rate, start and endtime def fnGenSampledSinusoid(A,Freq,Phi, Fs,sTime,eTime): # Showing off how to use numerical python library to create arange n = np.arange(sTime,eTime,1.0/Fs) y = A*np.cos(2 * np.pi * Freq * n + Phi) return [n,y] # The input is a float array (should have dynamic value from -1.00 to +1.00 def fnNormalizeFloatTo16Bit(yFloat): y_16bit = [int(s*32767) for s in yFloat] return(np.array(y_16bit, dtype='int16')) # The input is a float array (should have dynamic value from -1.00 to +1.00 def fnNormalize16BitToFloat(y_16bit): yFloat = [float(s/32767.0) for s in y_16bit] return(np.array(yFloat, dtype='float')) def fn_mostBasicCosineSignal(): # Lets start with the most basic #y(theta) = cos(theta) theta = np.arange(0,4*np.pi,np.pi/10.0) y = 2.5*np.cos(theta) plt.figure(1) plt.plot(theta/(np.pi), y,'r--o'); plt.xlabel('theta (pi)'); plt.ylabel('y(theta)') plt.title('sinusoid of signal (floating point)') plt.grid() plt.show() print('Above figure 0 shows cosine wrt to horizontal axis of angle theta') t = np.arange(0,2.0,0.1) F = 1.0 # 1 cycle per second y = 1*np.cos(2*np.pi*F*t) plt.figure(2) plt.stem(t, y,'g-'); # plt.plot(t, y,'ro'); plt.xlabel('time in seconds'); plt.ylabel('y(t)') plt.title('sinusoid of signal (floating point)') plt.grid() plt.show() numPts = 30 n = np.arange(0,numPts) Fs = 20.0 # sampling freq , ex= 10 times in 1 sec Ts = 1/Fs # sampling period = 1/sampling frequency nT = n*Ts #(1.0/10) F = 1.0 # 1 cycle per second yNT = 1*np.cos(2*np.pi*F*nT) plt.figure(3) plt.plot(n, yNT,'ro'); plt.stem(n, yNT,'g-'); plt.xlabel('samples'); plt.ylabel('y(nT)') plt.title('sinusoid of signal (floating point)') plt.grid() plt.show() def fn_genCosineSignalwrtTime(): A=0.5; F=6000; Phi = 0; Fs=16000; sTime=0; eTime = 1.4; [n,yfloat] = fnGenSampledSinusoid(A, F, Phi, Fs, sTime, eTime) # Lets plot what we have plt.figure(1) numSamples =72 plt.plot(n[0:numSamples], yfloat[0:numSamples],'r--o'); plt.xlabel('time in sec'); plt.ylabel('y[nT]') plt.title('sinusoid of signal (floating point)') plt.grid() plt.show() print('Above figure 1 shows sinusoid') plt.figure(2) nIdx = np.arange(0,numSamples) plt.plot(nIdx, yfloat[0:numSamples],'r--o'); plt.xlabel('sample index n'); plt.ylabel('y[n]') plt.title('sinusoid of signal (floating point)') plt.grid() plt.show() print('Above figure 1 shows sinusoid') # Although we created the signal in the date type float and dynamic range -1.0:1.0 # when we save it and when we wish to listen to it using winsound it should be in 16 bit int. y_16bit = fnNormalizeFloatTo16Bit(yfloat) # Lets save the file, fname, sequence, and samplingrate needed wavfile.write('t1_16bit.wav', Fs, y_16bit) wavfile.write('t1_float.wav', Fs, yfloat) # wavfile write can save it as a 32 bit format float # Lets play the wavefile using winsound given the wavefile saved above #unfortunately winsound ONLY likes u16 bit values #thats why we had to normalize y->y_norm (16 bits) integers to play using winsounds winsound.PlaySound('t1_16bit.wav', winsound.SND_FILENAME) # The following at float fail to play using winsound! #winsound.PlaySound('t1_float.wav', winsound.SND_FILENAME) #The file t1_float.wav cannot be played by winsound - but can be played by audacity? # Second Example, plotting complex exponential! # # Lets generate and plot complex exponential in 2-d, polar and 3d plot # how to include phase shift? Phi != 0? def fn_genComplexExpSignal(): print('Below is figure 2 shows complex exponential') numSamples = 200 A=0.99; w1=2*np.pi/50.0; n = np.arange(0, numSamples, 1) y1 = np.multiply(np.power(A, n), np.exp(1j * w1 * n)) # plotting in 2-D, the real and imag in the same figure plt.figure(1) plt.plot(n, y1[0:numSamples].real,'r--o') plt.plot(n, y1[0:numSamples].imag,'g--o') plt.xlabel('sample index n'); plt.ylabel('y[n]') plt.title('Complex exponential (red=real) (green=imag)') plt.grid() plt.show() # plotting in polar, understand what the spokes are plt.figure(2) for x in y1: plt.polar([0,np.angle(x)],[0,np.abs(x)],marker='o') plt.title('Polar plot showing phasors at n=0..N') plt.show() # plotting 3D complex plane plt.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') reVal = y1[0:numSamples].real imgVal = y1[0:numSamples].imag ax.plot(n,reVal, imgVal, label='complex exponential phasor') ax.scatter(n,reVal,imgVal, c='r', marker='o') ax.set_xlabel('sample n') ax.set_ylabel('real') ax.set_zlabel('imag') ax.legend() plt.show() #============================================================ # Main prog starts here #======================================================== print("Example of Lab1 CE3007") fn_mostBasicCosineSignal() #fn_genCosineSignalwrtTime() #fn_genComplexExpSignal() #print("end of prog") <file_sep>import numpy as np import matplotlib.pyplot as plt def myDTFS(x): X = np.zeros(len(x), dtype=complex) Omega = np.zeros(len(x)) N = len(x) for k in np.arange(0,len(x)): tmpVal = 0.0 Omega[k] = (2*np.pi/N)*k for n in np.arange(0,len(x)): tmpVal = tmpVal + x[n]*np.exp(-1j*(2*np.pi/N)*k*n) X[k] = tmpVal/N return (X,Omega) def myIDTFS(X): x = np.zeros(len(X), dtype=float) N = len(x) for n in np.arange(0,len(x)): tmpVal = 0.0 for k in np.arange(0,len(X)): tmpVal = tmpVal + X[k]*np.exp(+1j*(2*np.pi/N)*k*n) x[n] = np.absolute(tmpVal) return (x) x = [0,0,0, 1,1, 0, 0, 0] (X1, Omega) = myDTFS(x) (X) = np.fft.fft(x) print(X) N=len(x) print(X1*N) # Lets save the file, fname, sequence, and samplingrate needed absX = np.absolute(X) angleX = np.angle(X) titleStr = 'x[n]' f, axarr = plt.subplots(2, sharex=True) axarr[0].stem(np.arange(0,8), absX) axarr[0].set_title('DTFS '+titleStr) axarr[0].set_ylabel('mag value') axarr[1].stem(np.arange(0,8), angleX) axarr[1].set_xlabel('k') axarr[1].set_ylabel('Phase (rad)') plt.show() f, axarr = plt.subplots(2, sharex=True) axarr[0].stem(Omega/np.pi, absX*(2*np.pi),'C0x') axarr[0].set_title('DTFT of '+titleStr) axarr[0].set_ylabel('mag value') plt.xticks(np.arange(0, 2, step=0.25)) axarr[1].stem(Omega/np.pi, angleX) axarr[1].set_xlabel('omega*pi (rad/sample)') axarr[1].set_ylabel('Phase (rad)') plt.show() <file_sep># -*- coding: utf-8 -*- """ Created on Sat Dec 2 13:10:08 2017 @author: <NAME> Date: Dec 2017, using python to solve DSP problems purpose - to remove dependency on Matlab """ # this is lab 2 example, in which we will load a waveform, # listen to it # plot its time domain sequence, # plot its spectrogram import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile as wavfile import scipy import winsound from scipy import signal # The input is a float array (should have dynamic value from -1.00 to +1.00 def fnNormalizeFloatTo16Bit(yFloat): y_16bit = [int(s*32767) for s in yFloat] return(np.array(y_16bit, dtype='int16')) # The input is a float array (should have dynamic value from -1.00 to +1.00 def fnNormalize16BitToFloat(y_16bit): yFloat = [float(s/32767.0) for s in y_16bit] return(np.array(yFloat, dtype='float')) print("Example of Lab2 CE3007") ipcleanfilename = 'helloworld_16bit.wav' print("Example using np concolve") # note that when we process, we WILL use floating point array # hence, dtype must be include in definition of np.array h = np.array([1,2,3],dtype='float') x = np.array([1,0,0,0,0,2,0,0,0,0,0],dtype='float') y = np.convolve(x,h) y2 = scipy.signal.lfilter(h,[1],x) plt.figure() plt.stem(y, linefmt='r-o') plt.stem(y2, linefmt='b-x') plt.ylabel('op using convolve and scipy lfilter') plt.xlabel('sample n') plt.show() # print("Example of Lab2, Q5, CE3007") # The first part - build the boisy signal, embed 3KHz to helloWorld winsound.PlaySound(ipcleanfilename, winsound.SND_FILENAME) [Fs, sampleX_16bit] = wavfile.read(ipcleanfilename) # we wish to do everything in floating point, hence lets convert to floating point first. # by the following normalization sampleX_float = fnNormalize16BitToFloat(sampleX_16bit) #e.g, lets make the entire signal a bit larger, scale by 3.0 sampleX_float = np.multiply(3.0,sampleX_float) # remember to normalize it to +-1 dynamic range floating point before processing it. # lets plot the noisy signal in time and spectrogram plt.figure() plt.plot(sampleX_float,'r') plt.ylabel('signal (float)') plt.xlabel('sample n') plt.show() # reminder - dont processed the 16bit sequence, always convert to float before doing the DSP [f, t, Sxx_clean] = signal.spectrogram(sampleX_float, Fs, window=('blackmanharris'),nperseg=512,noverlap=int(0.9*512)) plt.pcolormesh(t, f, 10*np.log10(Sxx_clean)) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.title('spectrogram of signal') plt.show() # generate the impulse response using scipy.signal.lfilter module # where num and den are the coefficients of the linear constant coefficients numSamples = 100 n = np.arange(0,numSamples,1) impulseH = np.zeros(numSamples) impulseH[0] = 1 num = [1, -0.7653668, 0.99999] den = [1, -0.722744, 0.888622] y = signal.lfilter(num, den, impulseH) plt.stem(n, y) plt.ylabel('impulse response of the IIR filter') plt.xlabel('sample n') plt.show() <file_sep># CE 3007 Digital Signal Processing Lab ## Quiz — 1 (10 marks) _Answer all questions in 2 hours._ ### Name. ### Lab Group. Fill in the blanks or briefly answer the questions 1. Study how y(n) and t(n) is created in the Matlab code. y1000(n) is the sampled version of the continuous signal y(t) = 2sin(2 $\pi$ 2t + $\pi$/4) with the sampled frequency of 1000Hz. t1000(n) is the corresponding sampled time. What is the signal frequency of y(t) in Hz? _Ans:_ 2Hz 2. What is the possible value of the cut-off frequency of the lowpass filter. Freq_Fn? Briefly illustrate the reason. _Ans:_ 1000Hz sampling frequency, Nyquist is 500Hz, cutoff at 0.1 so is 50Hz 3. When y100[n] is upsampled to 1000Hz to result in y1000[n], and y1000[n] passes through an ideal lowpass filter with a gain of 1, what is the amplitude of the resultant signal y1000[n] after the lowpass filter? _Ans:_ y100[n] has amplitude of 2/Ts = 200. Upsampling will not change the amplitude and unity gain opamp also will not change the amplitude. 4. When sampling continuous signal y(t)=sin(40 $\pi$t), the minimum sampling frequency is ?? Hz to avoid aliasing. _Ans:_ F = 20Hz so at least sample at 40
6559bdade5168624e9464d791ae017eb0a59f2b7
[ "Markdown", "Python" ]
11
Markdown
malavika002/NTU-CE3007_DSP
5413042e649cb2f1a63d89fdd1ebc8d7ca673c3b
4cfa21fc7d347e5c911369a3f016a835d41b9e28
refs/heads/master
<file_sep>app.directive('keyListener', function(listenerService) { return { restrict: 'A', link: function(scope, element, attrs) { var keyboard = element.find('keyboard'); element.on('keydown', function(e) { var keyNum = listenerService.getKeyNum(e); var key = keyboard.find('keyboard-key')[keyNum]; angular.element(key).triggerHandler('mousedown'); }); element.on('keyup', function(e) { var keyNum = listenerService.getKeyNum(e); var key = keyboard.find('keyboard-key')[keyNum]; angular.element(key).triggerHandler('mouseup'); }); } }; }).$inject = ['listenerService']; app.directive('keyboard', function() { return { templateUrl: 'partials/keyboard.html', restrict: 'E' }; }); app.directive('keyboardKey', function(pitchService) { return { restrict: 'E', scope: { pitch: '=' }, controller: keyCtrl, link: function(scope, element, attrs) { element.on('mousedown', () => { element.addClass('playing'); pitchService.play(scope.gain); }); element.on('mouseup', () => { element.removeClass('playing'); pitchService.stop(scope.gain); }); } }; }).$inject = ['pitchService'] <file_sep>var app = angular.module('synthApp', []); <file_sep>app.service('pitchService', pitchService); function pitchService($rootScope) { this.createPitch = function(pitch) { var osc = $rootScope.audioContext.createOscillator(); var a = Math.pow(2, 1 / 12); // Constant used in calculating note frequency osc.frequency.value = 440 * Math.pow(a, pitch); return osc; }; // C0 to B8 this.allNotes = function() { var notes = []; const pitches = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; for (var i = 0; i < 9; i++) { for (var j = 0; j < pitches.length; j++) { notes.push(pitches[j] + i); } } return notes; } this.play = function(gain) { gain.gain.value = 1; } this.stop = function(gain) { gain.gain.value = 0; } } pitchService.$inject = ['$rootScope'] app.service('listenerService', listenerService); function listenerService() { this.getKeyNum = function(e) { switch (e.keyCode) { //white keys case 65: return 0; break; case 83: return 1; break; case 68: return 2; break; case 70: return 3; break; case 71: return 4; break; case 72: return 5; break; case 74: return 6; break; case 75: return 7; break; // black keys case 87: return 8; break; case 69: return 9; break; case 84: return 10; break; case 89: return 11; break; case 85: return 12; break; } } }
74facf46ef581492df3cf7d268f1e0a5a32cb481
[ "JavaScript" ]
3
JavaScript
bossjohnson/web-synth
18120193880f475a7c6d7ca9f3db587e73fa5bb8
b09d504496f3850673ceb5d290aaa7c6fd128f1e
refs/heads/master
<repo_name>shvetsiya/ICIAR2018<file_sep>/train_lgbm.py #!/usr/bin/env python3 """Trains LightGBM models on various features, data splits. Dumps models and predictions""" import pickle import numpy as np import lightgbm as lgb from sklearn.metrics import accuracy_score from utils import load_data from os.path import join, exists from os import makedirs import argparse CROP_SIZES = [400, 650] SCALES = [0.5] NN_MODELS = ["ResNet", "Inception", "VGG"] AUGMENTATIONS_PER_IMAGE = 50 NUM_CLASSES = 4 RANDOM_STATE = 1 N_SEEDS = 5 VERBOSE_EVAL = False with open("data/folds-10.pkl", "rb") as f: FOLDS = pickle.load(f) LGBM_MODELS_ROOT = "models/LGBMs" CROSSVAL_PREDICTIONS_ROOT = "predictions" DEFAULT_PREPROCESSED_ROOT = "data/preprocessed/train" def _mean(x, mode="arithmetic"): """ Calculates mean probabilities across augmented data # Arguments x: Numpy 3D array of probability scores, (N, AUGMENTATIONS_PER_IMAGE, NUM_CLASSES) mode: type of averaging, can be "arithmetic" or "geometric" # Returns Mean probabilities 2D array (N, NUM_CLASSES) """ assert mode in ["arithmetic", "geometric"] if mode == "arithmetic": x_mean = x.mean(axis=1) else: x_mean = np.exp(np.log(x + 1e-7).mean(axis=1)) x_mean = x_mean / x_mean.sum(axis=1, keepdims=True) return x_mean if __name__ == "__main__": parser = argparse.ArgumentParser() arg = parser.add_argument arg("--features", required=False, default=DEFAULT_PREPROCESSED_ROOT, metavar="feat_dir", help="Feature root dir. Default: data/preprocessed/train") args = parser.parse_args() PREPROCESSED_ROOT = args.features learning_rate = 0.1 num_round = 70 param = { "objective": "multiclass", "num_class": NUM_CLASSES, "metric": ["multi_logloss", "multi_error"], "verbose": 0, "learning_rate": learning_rate, "num_leaves": 191, "feature_fraction": 0.46, "bagging_fraction": 0.69, "bagging_freq": 0, "max_depth": 7, } for SCALE in SCALES: print("SCALE:", SCALE) for NN_MODEL in NN_MODELS: print("NN_MODEL:", NN_MODEL) for CROP_SZ in CROP_SIZES: print("PATCH_SZ:", CROP_SZ) INPUT_DIR = join(PREPROCESSED_ROOT, "{}-{}-{}".format(NN_MODEL, SCALE, CROP_SZ)) acc_all_seeds = [] for seed in range(N_SEEDS): accuracies = [] for fold in range(len(FOLDS)): feature_fraction_seed = RANDOM_STATE + seed * 10 + fold bagging_seed = feature_fraction_seed + 1 param.update({"feature_fraction_seed": feature_fraction_seed, "bagging_seed": bagging_seed}) print("Fold {}/{}, seed {}".format(fold + 1, len(FOLDS), seed)) x_train, y_train, x_test, y_test = load_data(INPUT_DIR, FOLDS, fold) train_data = lgb.Dataset(x_train, label=y_train) test_data = lgb.Dataset(x_test, label=y_test) gbm = lgb.train(param, train_data, num_round, valid_sets=[test_data], verbose_eval=VERBOSE_EVAL) # pickle model model_file = "lgbm-{}-{}-{}-f{}-s{}.pkl".format(NN_MODEL, SCALE, CROP_SZ, fold, seed) model_root = join(LGBM_MODELS_ROOT, NN_MODEL) if not exists(model_root): makedirs(model_root) with open(join(model_root, model_file), "wb") as f: pickle.dump(gbm, f) scores = gbm.predict(x_test) scores = scores.reshape(-1, AUGMENTATIONS_PER_IMAGE, NUM_CLASSES) preds = { "files": FOLDS[fold]["test"]["x"], "y_true": y_test, "scores": scores, } preds_file = "lgbm_preds-{}-{}-{}-f{}-s{}.pkl".format(NN_MODEL, SCALE, CROP_SZ, fold, seed) preds_root = join(CROSSVAL_PREDICTIONS_ROOT, NN_MODEL) if not exists(preds_root): makedirs(preds_root) with open(join(preds_root, preds_file), "wb") as f: pickle.dump(preds, f) mean_scores = _mean(scores, mode="arithmetic") y_pred = np.argmax(mean_scores, axis=1) y_true = y_test[::AUGMENTATIONS_PER_IMAGE] acc = accuracy_score(y_true, y_pred) print("Accuracy:", acc) accuracies.append(acc) acc_seed = np.array(accuracies).mean() # acc of a seed acc_all_seeds.append(acc_seed) print("{}-{}-{} Accuracies: [{}], mean {:5.3}".format(NN_MODEL, SCALE, CROP_SZ, ", ".join(map(lambda s: "{:5.3}".format(s), accuracies)), acc_seed)) print("Accuracy of all seeds {:5.3}".format(np.array(acc_all_seeds).mean())) """ ResNet-1.0-800 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [0.875, 0.725, 0.875, 0.875, 0.8, 0.75, 0.8, 0.85, 0.85, 0.85], mean 0.825 [0.875, 0.775, 0.825, 0.875, 0.775, 0.75, 0.8, 0.85, 0.85, 0.825], mean 0.82 [0.875, 0.75, 0.85, 0.85, 0.8, 0.75, 0.725, 0.875, 0.875, 0.875], mean 0.823 [0.875, 0.75, 0.85, 0.85, 0.8, 0.775, 0.775, 0.825, 0.85, 0.825], mean 0.817 [0.875, 0.75, 0.875, 0.875, 0.775, 0.775, 0.825, 0.85, 0.9, 0.85], mean 0.835 Accuracy of all seeds 0.824 ResNet-1.0-1300 learning_rate = 0.1, 60 steps [0.9, 0.775, 0.825, 0.875, 0.8, 0.775, 0.8, 0.875, 0.85, 0.85] * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [0.925, 0.75, 0.85, 0.85, 0.8, 0.725, 0.8, 0.825, 0.9, 0.85], mean 0.828 [0.875, 0.75, 0.8, 0.875, 0.75, 0.725, 0.8, 0.825, 0.875, 0.85], mean 0.812 [0.875, 0.75, 0.8, 0.825, 0.775, 0.725, 0.825, 0.85, 0.95, 0.875], mean 0.825 [ 0.9, 0.775, 0.8, 0.85, 0.725, 0.725, 0.8, 0.8, 0.875, 0.825], mean 0.807 [ 0.85, 0.725, 0.8, 0.825, 0.725, 0.75, 0.8, 0.8, 0.875, 0.85], mean 0.8 Accuracy of all seeds 0.815 VGG-1.0-800 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [ 0.85, 0.775, 0.825, 0.875, 0.85, 0.775, 0.8, 0.8, 0.85, 0.8], mean 0.82 [ 0.85, 0.75, 0.85, 0.875, 0.825, 0.775, 0.775, 0.825, 0.875, 0.775], mean 0.818 [ 0.85, 0.75, 0.825, 0.875, 0.85, 0.75, 0.825, 0.825, 0.875, 0.75], mean 0.818 [ 0.85, 0.8, 0.825, 0.875, 0.825, 0.8, 0.8, 0.8, 0.875, 0.775], mean 0.823 [0.825, 0.775, 0.775, 0.875, 0.85, 0.775, 0.8, 0.8, 0.85, 0.725], mean 0.805 Accuracy of all seeds 0.816 VGG-1.0-1300 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [0.825, 0.75, 0.8, 0.875, 0.825, 0.8, 0.8, 0.75, 0.85, 0.8], mean 0.807 [0.825, 0.75, 0.825, 0.9, 0.8, 0.825, 0.725, 0.825, 0.875, 0.775], mean 0.812 [ 0.85, 0.8, 0.8, 0.875, 0.775, 0.775, 0.775, 0.775, 0.875, 0.775], mean 0.808 [ 0.8, 0.775, 0.775, 0.9, 0.8, 0.8, 0.8, 0.825, 0.875, 0.775], mean 0.812 [0.825, 0.825, 0.8, 0.9, 0.8, 0.8, 0.725, 0.8, 0.85, 0.8], mean 0.812 Accuracy of all seeds 0.81 ResNet-0.5-650 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [ 0.95, 0.775, 0.875, 0.9, 0.825, 0.775, 0.85, 0.85, 0.85, 0.825], mean 0.847 [ 0.9, 0.775, 0.875, 0.9, 0.775, 0.7, 0.875, 0.8, 0.85, 0.825], mean 0.828 [ 0.9, 0.775, 0.85, 0.9, 0.825, 0.75, 0.875, 0.825, 0.825, 0.825], mean 0.835 [0.875, 0.775, 0.85, 0.875, 0.8, 0.725, 0.85, 0.825, 0.85, 0.825], mean 0.825 [0.925, 0.775, 0.85, 0.9, 0.825, 0.75, 0.825, 0.85, 0.85, 0.825], mean 0.838 Accuracy of all seeds 0.834 ResNet-0.5-400 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [0.925, 0.825, 0.875, 0.875, 0.775, 0.825, 0.825, 0.825, 0.825, 0.825], mean 0.84 [0.925, 0.775, 0.875, 0.875, 0.8, 0.85, 0.85, 0.8, 0.85, 0.825], mean 0.842 [ 0.9, 0.725, 0.875, 0.875, 0.825, 0.85, 0.875, 0.85, 0.85, 0.825], mean 0.845 [0.925, 0.775, 0.875, 0.875, 0.8, 0.85, 0.85, 0.85, 0.85, 0.825], mean 0.847 [0.925, 0.775, 0.825, 0.875, 0.775, 0.825, 0.85, 0.825, 0.825, 0.825], mean 0.833 acc_all_seeds 0.841 VGG-0.5-400 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [ 0.85, 0.85, 0.8, 0.825, 0.825, 0.8, 0.825, 0.85, 0.875, 0.825], mean 0.832 [0.875, 0.825, 0.85, 0.85, 0.875, 0.85, 0.8, 0.825, 0.875, 0.825], mean 0.845 [ 0.9, 0.825, 0.825, 0.85, 0.85, 0.8, 0.8, 0.85, 0.875, 0.85], mean 0.842 [0.875, 0.825, 0.8, 0.85, 0.825, 0.875, 0.8, 0.775, 0.875, 0.825], mean 0.832 [0.875, 0.825, 0.8, 0.825, 0.825, 0.8, 0.8, 0.8, 0.875, 0.825], mean 0.825 acc_all_seeds 0.835 VGG-0.5-650 learning_rate = 0.1, 70 steps * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [ 0.9, 0.825, 0.775, 0.85, 0.825, 0.8, 0.825, 0.875, 0.9, 0.8], mean 0.838 [ 0.9, 0.825, 0.775, 0.85, 0.8, 0.8, 0.8, 0.875, 0.9, 0.775], mean 0.83 [ 0.9, 0.875, 0.825, 0.85, 0.8, 0.75, 0.8, 0.875, 0.9, 0.825], mean 0.84 [0.875, 0.85, 0.75, 0.85, 0.8, 0.75, 0.825, 0.8, 0.875, 0.8], mean 0.818 [ 0.9, 0.9, 0.8, 0.85, 0.825, 0.8, 0.825, 0.85, 0.875, 0.825], mean 0.845 acc_all_seeds 0.8342 Inception_adv-1.0-1300 best acc reached so far 0.67, acc 0.7875, knobs num_leaves 121, feature_fraction 0.34, bagging_fraction 0.69, max_depth 38 learning_rate = 0.1, 60 steps [0.8, 0.85, 0.7375, 0.7875, 0.7375] learning_rate = 0.1, 60 steps [0.8, 0.85, 0.8, 0.875, 0.8, 0.75, 0.75, 0.8, 0.8, 0.65] Inception-0.5-650 * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 [ 0.9, 0.825, 0.75, 0.9, 0.85, 0.8, 0.8, 0.85, 0.775, 0.775], mean 0.823 [0.925, 0.8, 0.725, 0.9, 0.85, 0.8, 0.825, 0.825, 0.8, 0.75], mean 0.82 [ 0.9, 0.825, 0.75, 0.9, 0.825, 0.825, 0.85, 0.85, 0.775, 0.775], mean 0.828 [0.925, 0.9, 0.725, 0.9, 0.825, 0.825, 0.825, 0.85, 0.75, 0.75], mean 0.828 [ 0.9, 0.875, 0.725, 0.9, 0.85, 0.8, 0.8, 0.85, 0.8, 0.8], mean 0.83 Accuracy of all seeds 0.826 Inception-0.5-400 * new acc reached, loss 0.63, acc 0.825, knobs num_leaves 191, feature_fraction 0.46, bagging_fraction 0.66, max_depth 7 (no data) """
e187d265741c77d8722f6702d703ea1f8b02464a
[ "Python" ]
1
Python
shvetsiya/ICIAR2018
05beeab5c27125f17185736df49c9eddce39875f
4f9e9ed999288d1a3cee55a27d46747815213c11
refs/heads/master
<repo_name>ndelangen/react-movie-carousel-app<file_sep>/server/dev-middleware.js const Promise = require('bluebird'); const webpack = require('webpack'); const dev = require('webpack-dev-middleware'); const hot = require('webpack-hot-middleware'); const config = require('../webpack.client.config.js'); const notify = require('./cli-notifications'); const devOptions = { publicPath: config.output.publicPath, quiet: true, noInfo: true, stats: 'errors-only', }; const hotOptions = { path: '/__webpack_hmr', publicPath: config.output.publicPath, timeout: 2000, overlay: true, reload: false, log: false, warn: true, }; const compiler = require('./client-compiler').compiler; const devMiddleware = dev(compiler, devOptions); const hotMiddleware = hot(compiler, hotOptions); const middleware = [devMiddleware, hotMiddleware]; const hasCompiled = new Promise(resolve => compiler.plugin('done', resolve)); module.exports = { compiler, middleware, ready: hasCompiled, }; <file_sep>/app/components/01-atoms/image/main.js import React, { Component } from 'react'; import styles from './main.css'; const loadHandler = function (event) { this.setState({ loaded: true }); this.props.onLoad && this.props.onLoad(event); }; class Image extends Component { constructor(props) { super(props); this.state = { imageUrl: 'about:blank', loaded: false }; } componentDidMount() { window.requestAnimationFrame(() => { const width = this.refs.root.clientWidth; const mediaType = width < 400 ? 'mobile': 'desktop'; this.setState({ imageUrl: `${this.props.src}?type=${mediaType}` }); }); } render() { const { props, state } = this; const [ width, height ] = props.ratio.split('/'); return ( <div ref="root" className={state.loaded ? styles['is-loaded'] : styles['is-loading']}> <img className={styles.placeholder} src={`data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' viewBox%3D'0 0 ${width} ${height}'%2F%3E`} width={width} height={height} /> <img src={state.imageUrl} className={styles.image} crossOrigin="anonymous" onLoad={loadHandler.bind(this)} style={{width: '100%'}} /> <span className={styles.loader}>loading</span> <div className={styles.fallback} dangerouslySetInnerHTML={{__html: ` <noscript> <img src="${props.src}" class="${styles.image}" /> </noscript> `}}></div> </div> ); } }; export default Image; <file_sep>/server/server-compiler.js const webpack = require('webpack'); const Promise = require('bluebird'); const ProgressPlugin = require('webpack/lib/ProgressPlugin'); const config = require('../webpack.server.config.js'); const compiler = webpack(config); const hasCompiled = new Promise(resolve => compiler.plugin("done", resolve)); const progress = callback => compiler.apply(new ProgressPlugin(callback)); module.exports = { name: 'server', compiler, progress, ready: hasCompiled }; <file_sep>/app/config/development.js const cssModules = { generateScopedName: '[path][name]-[local]_[hash:base64:5]', }; const config = { greeting: 'Hello, this app is running with default settings', cssModules, }; module.exports = { ...require('./base'), ...config, }; <file_sep>/webpack.server.config.js var path = require('path'); const appConfig = require('./app/config/' + global.__ENVIRONMENT__); const NoErrorsPlugin = require('webpack').NoErrorsPlugin; const nodeExternals = require('webpack-node-externals'); const isDev = global.__ENVIRONMENT__ === 'development'; const isProd = global.__ENVIRONMENT__ === 'production'; module.exports = { target: 'node', externals: [nodeExternals()], entry: { server: [ './app/index.js' ], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, 'build'), filename: '[name].js', chunkFilename: '[name].[chunkhash].js', jsonpFunction: 'wpck' }, plugins: [ new NoErrorsPlugin(), // new webpack.optimize.UglifyJsPlugin({ // compressor: { // warnings: false, // screw_ie8: true // } // }) ], module: { loaders: [ { test: /\.css$/, include: path.join(__dirname, 'app'), loader: `fake-style!css?modules&importLoaders=1&localIdentName=${appConfig.cssModules.generateScopedName}` }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js?$/, loader: 'babel', include: path.join(__dirname, 'app'), } ] }, resolve: { root: [ path.resolve('./app'), ], extensions: [ '', '.js' ] } }; <file_sep>/app/config/production.js const cssModules = { generateScopedName: '[hash:base64:5]', }; const config = { greeting: 'Hello, this app is running with production settings', cssModules, }; module.exports = { ...require('./base'), ...config, }; <file_sep>/scripts/production.js #!/usr/bin/env node require('babel-core/register'); global.__ENVIRONMENT__ = process.env.NODE_ENV = 'production'; global.__PORT__ = process.env.PORT || 3000; const minimist = require('minimist'); const Promise = require('bluebird'); const scriptArguments = minimist(process.argv.slice(2)); const appConfig = require('../app/config/' + global.__ENVIRONMENT__); const webServer = require('../server/main'); const notify = require('../server/cli-notifications'); const webpackRunner = require('../server/webpack-runner'); const webpackCompilers = webpackRunner.run([ { options: { progress: true, run: true }, compiler: require('../server/client-compiler'), }, { options: { progress: true, run: true }, compiler: require('../server/server-compiler'), }, ]); const assetsMiddleware = require('../server/assets'); const regularMiddleware = require('../server/routes'); Promise.all(webpackCompilers.map(c => c.ready).concat([webServer.ready])).then(() => { notify('server-ready'); webServer.server.use(assetsMiddleware.middleware); webServer.server.use(regularMiddleware.middleware); webServer.server.use(require('../build/server').serverMiddleware); }); <file_sep>/app/index.js import 'isomorphic-fetch'; import { serverMiddleware } from './Router'; export { serverMiddleware as serverMiddleware }; <file_sep>/server/routes.js const express = require('express'); const router = express.Router(); // Short-circuit the browser's annoying favicon request. You can still // specify one as long as it doesn't have this exact name and path. router.get('/favicon.ico', (req, res) => { res.writeHead(204, { 'Content-Type': 'image/x-icon' }); res.end(); }); module.exports = { middleware: router, }; <file_sep>/app/reducers/movies.js import { MOVIES_INVALID, MOVIES_FETCHING, MOVIES_FETCHED, MOVIES_FETCH_FAILED } from '../actions/movies'; export default function movies(state = { readyState: MOVIES_INVALID, list: null }, action) { switch (action.type) { case MOVIES_FETCHING: return Object.assign({}, state, { readyState: MOVIES_FETCHING }); case MOVIES_FETCH_FAILED: return Object.assign({}, state, { readyState: MOVIES_FETCH_FAILED, error: action.error }); case MOVIES_FETCHED: return Object.assign({}, state, { readyState: MOVIES_FETCHED, list: action.result }); default: return state; } }<file_sep>/server/cli-notifications.js const chalk = require('chalk'); const readline = require('readline'); const port = global.__PORT__ || process.env.PORT || 3000; const { width: terminalWidth } = require('window-size'); const stringPadding = Array(terminalWidth).fill(' ').join(''); const startTime = new Date(); const logTime = (date) => chalk.gray(`[${date.toLocaleDateString()} - ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds()}]`) const progressBarWidth = terminalWidth - 24; const renderProgressBar = ({ percentage, progress, activity }) => { const string = `${renderPercentage(percentage)} ${progress} ${activity}${stringPadding}`; const completeLength = Math.ceil(progressBarWidth * percentage); const complete = string.substring(0, completeLength); const incomplete = string.substring(completeLength, progressBarWidth); return `${chalk.bgYellow.black(complete)}${chalk.bgWhite.black(incomplete)}`; }; const renderStage = ({stage}, length = 10) => { if (stage.length < length) { return stage.concat(Array(length).fill(' ').join('')).substr(0, length); } else { return stage.substr(0, 9).concat('…'); } }; const renderPercentage = percentage => `${Math.ceil(100 * percentage)}%`; const removeWebpackProgress = (data) => { Object.keys(data).forEach(() => { readline.moveCursor(process.stdout, 0, -1); }); readline.clearScreenDown(process.stdout); }; const logWebpackProgress = (data) => { Object.keys(data).forEach((key) => { const item = data[key]; switch (item.stage) { case 'starting': console.info(`${chalk.blue('◉')} - ${key} ${renderStage(item)} ${renderProgressBar(item)}`); return; case 'compiling': console.info(`${chalk.yellow('◉')} - ${key} ${renderStage(item)} ${renderProgressBar(item)}`); return; case 'building modules': console.info(`${chalk.yellow('◉')} - ${key} ${renderStage(item)} ${renderProgressBar(item)}`); return; case 'sealing': case 'optimizing': case 'module optimization': case 'advanced module optimization': case 'basic chunk optimization': case 'chunk optimization': case 'advanced chunk optimization': case 'module and chunk tree optimization': case 'module reviving': case 'module order optimization': case 'module id optimization': case 'chunk reviving': case 'chunk order optimization': case 'chunk id optimization': case 'hashing': case 'module assets processing': case 'chunk assets processing': case 'additional chunk assets processing': case 'recording': case 'additional asset processing': case 'chunk asset optimization': case 'asset optimization': case 'emitting': console.info(`${chalk.blue('◉')} - ${key} ${renderStage(item)} ${renderProgressBar(item)}`); return; case '': console.info(`${chalk.green('◉')} - finished ${key}`); return; default: console.log(`? ${key}`); } }); }; module.exports = function cliNotify (type, data) { switch (type) { case 'script-start': console.info(``); return; case 'server-start': console.info(`${chalk.blue('◉')} - Server started. ${logTime(startTime)}`); return; case 'server-ready': console.info(`${chalk.green('◉')} - Server ready. ${logTime(new Date())}`); return; case 'server-hmr-app': console.info(`${chalk.green('◉')} - Server HMR: ${chalk.cyan('/app/*')} ${logTime(new Date())}`); return; case 'server-hmr-node': console.info(`${chalk.green('◉')} - Server HMR: ${chalk.cyan('/node_modules/*')} ${logTime(new Date())}`); return; case 'server-down': process.stdout.clearLine(); process.stdout.cursorTo(0); console.warn(`${chalk.red('◉')} - Server shut down. ${logTime(new Date())}`); return; case 'webpack-start': logWebpackProgress(data); return; case 'webpack-progress': removeWebpackProgress(data); logWebpackProgress(data); return; case 'webpack-start-server': console.info(`${chalk.blue('◉')} - Webpack server started. ${logTime(new Date())}`); return; case 'webpack-start-client': console.info(`${chalk.blue('◉')} - Webpack client started. ${logTime(new Date())}`); return; case 'webpack-ready': const colors = ['green', 'cyan', 'blue', 'yellow', 'red']; const colorIndex = Math.floor(Math.max(0, Math.min((data - 3770) / 2000, 4))); const timestamp = chalk[colors[colorIndex]]; console.info(`${chalk.green('◉')} - Webpack completed in ${timestamp(data + 'ms')} ${logTime(new Date())}`); return; case 'webpack-results': console.log(''); console.info(data); console.log(''); return; case 'webpack-problems': console.log(''); if (data.errors) { data.errors.forEach((item) => console.log(item)); console.log(''); } if (data.warnings) { data.warnings.forEach((item) => console.log(item)); console.log(''); } return; case 'develop-on': console.log(''); console.log('🤓 - Happy developing! Open up http://localhost:%s/ in your browser.', port) console.log(''); return; } }; <file_sep>/server/assets.js const express = require('express'); const path = require('path'); const fs = require('fs'); const router = express.Router(); const base = '/assets'; router.use(`${base}/`, (req, res, next) => { res.setHeader('Cache-Control', 'public, max-age=63113852'); // 2 years return next(); }); router.get(`${base}/*`, (req, res) => { const path = './build/' + req.params[0]; fs.exists(path, (exists) => { exists ? res.sendFile(path, {root: './'}) : res.status(404).send('Not found'); }); }); module.exports = { middleware: router }; <file_sep>/app/components/04-scaffolds/header/main.js import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './main.css'; class Header extends Component { render() { return ( <header className={styles.root}> <h1><span className={styles.title}>Universal React Movie-Carousel-App</span> <span className={styles.subtitle}>by <NAME></span></h1> </header> ); } } export default Header; <file_sep>/app/components/00-utilities/color/color-converter.js /* Taken from https://bgrins.github.io/TinyColor/docs/tinycolor.html */ const bound01 = function (n, max) { if (isOnePointZero(n)) { n = "100%"; } var processPercent = isPercentage(n); n = Math.min(max, Math.max(0, parseFloat(n))); if (processPercent) { n = parseInt(n * max, 10) / 100; } if ((Math.abs(n - max) < 0.000001)) { return 1; } return (n % max) / parseFloat(max); } const isOnePointZero = function (n) { return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; }; const isPercentage = function (n) { return typeof n === "string" && n.indexOf('%') != -1; }; export function rgbToHsl (r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max === min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; }; export function hslToRgb (h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } if(s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return { r: r * 255, g: g * 255, b: b * 255 }; }; <file_sep>/server/main.js const express = require('express'); const Promise = require('bluebird'); const notify = require('./cli-notifications'); const port = global.__PORT__; const server = express(); const isListening = new Promise((resolve, reject) => { notify('server-start'); server.listen(port, 'localhost', (error) => { error ? reject(error) : resolve(server); }); }); module.exports = { server, ready: isListening, }; <file_sep>/README.md # An Universal React Movie Carousel app A totally over-engineered carousel demo retrieving data from external source. But it has given me the oppertunity to get to know universal/isomorphic javascript, react-router, react-helmet and more. I've used a starter-kit to get started: [universal react by DominicTobias](https://github.com/DominicTobias/universal-react). WORKLOG: ✔︎ Hot Module Reloading serverside ✔︎ node_modules ✔︎ app ✔︎ Hot Module Reloading clientside ✔︎ normal browsers ✔︎ css IE (https://github.com/glenjamin/webpack-hot-middleware/issues/53) ✔︎ debugger statement support ✔︎ great sourcemaps ✔︎ debug-able css (no inline) ✔︎ css-modules imports variables ✔︎ port should become global ✔︎ FIX: single hot-update.json 404 move app serverMiddleware to server.js split server.js into only server running related things. chunked / streaming response from server compression http2 http2 push cached component cache proper logger with levels log to file Webpack Progress in dev, full log with --display-modules --display-reasons in production ✔︎ Use react production version globals into webpack defineplugin replace fake-style-loader auto camelcase css-modules ✔︎ eslint dependencies grapher statistics of appsize statistics of app performance use webpack hash to version assets investigate why/if a entry chunk (manifest-file) is a good idea ✔︎ move script logic to actual scripts npm run install npm run test:<suite> [*] npm run analyze / npm run report npm run build ✔︎ npm run prod / npm run production ✔︎ npm run dev npm start -> install and wizard to choose production | development git hooks pre push > build, test, analyze <file_sep>/webpack.client.config.js const path = require('path'); const appConfig = require('./app/config/' + global.__ENVIRONMENT__); const SplitByPathPlugin = require('webpack-split-by-path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HotModuleReplacementPlugin = require('webpack').HotModuleReplacementPlugin; const DedupePlugin = require('webpack').optimize.DedupePlugin; const UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin; const NoErrorsPlugin = require('webpack').NoErrorsPlugin; const DefinePlugin = require('webpack').DefinePlugin; const isDev = global.__ENVIRONMENT__ === 'development'; const isProd = global.__ENVIRONMENT__ === 'production'; const devtool = isDev ? { devtool: '#source-map' } : {}; const plugins = isDev ? [ new SplitByPathPlugin([ { name: 'vendor', path: path.join(__dirname, 'node_modules'), } ], { manifest: 'app-entry', }), new HotModuleReplacementPlugin(), new NoErrorsPlugin(), ] : [ new DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new SplitByPathPlugin([ { name: 'vendor', path: path.join(__dirname, 'node_modules'), } ], { manifest: 'app-entry', }), new ExtractTextPlugin({ filename: 'app.css', allChunks: true, }), new DedupePlugin(), new NoErrorsPlugin(), new UglifyJsPlugin({ compressor: { warnings: false, screw_ie8: true, }, }), ]; module.exports = { target: 'web', entry: { app: (isDev ? ['webpack-hot-middleware/client'] : []).concat([ './app/index.js', ]), }, output: { path: path.join(__dirname, 'build'), publicPath: 'http://localhost:3000/assets/', filename: '[name].js', chunkFilename: '[name].js', // chunkFilename: '[name]-[chunkhash].js', jsonpFunction: 'wpck', }, ...devtool, plugins: [ ...plugins ], externals: { }, resolve: { root: [ path.resolve('./app'), ], extensions: [ '', '.js', ] }, module: { loaders: isDev ? [ { test: /\.css$/, include: path.join(__dirname, 'app'), loader: `style!css?modules&importLoaders=1&localIdentName=${appConfig.cssModules.generateScopedName}`, }, Object.assign({ test: /\.js?$/, loader: 'babel', include: path.join(__dirname, 'app'), }, { query: { plugins: [ ['react-transform', { 'transforms': [{ transform: 'react-transform-hmr', imports: ['react'], locals: ['module'], }], }], ['transform-object-assign'], ], }, }) ] : [ { test: /\.css$/, include: path.join(__dirname, 'app'), loader: ExtractTextPlugin.extract({ fallbackLoader: `style!css?modules&importLoaders=1&localIdentName=${appConfig.cssModules.generateScopedName}`, loader: `css?modules&importLoaders=1&localIdentName=${appConfig.cssModules.generateScopedName}`, }) }, { test: /\.js?$/, loader: 'babel', include: path.join(__dirname, 'app'), query: { plugins: [ 'transform-es2015-template-literals', 'transform-es2015-literals', 'transform-es2015-function-name', 'transform-es2015-arrow-functions', 'transform-es2015-block-scoped-functions', 'transform-es2015-classes', 'transform-es2015-object-super', 'transform-es2015-shorthand-properties', 'transform-es2015-computed-properties', 'transform-es2015-for-of', 'transform-es2015-sticky-regex', 'transform-es2015-unicode-regex', 'check-es2015-constants', 'transform-es2015-spread', 'transform-es2015-parameters', 'transform-es2015-destructuring', 'transform-es2015-block-scoping', 'transform-es2015-typeof-symbol', ['transform-regenerator', { async: false, asyncGenerators: false, }], 'transform-object-assign' ], }, }, ], }, }; <file_sep>/app/config/base.js module.exports = { greeting: 'Hello, this app is running' };
9671ba46ebbd03fb3417caca48715a3d602239ce
[ "JavaScript", "Markdown" ]
18
JavaScript
ndelangen/react-movie-carousel-app
05bc57db1d030ad8c8c7539b8750fcb262ed9065
a3168ff38ce7bfb0ad7914ffa3332c246c6d1546
refs/heads/master
<file_sep>library('cccd') G1 = nng(alldata,k=10) plot(G1) <file_sep>library("KRLS") gauss_similarity_matrix = gausskernel(X = alldata, sigma = 1) plot(var1,col='red',pch=22,bg='red',xlim=range(0,max(alldata[,1])),ylim =range (0,max(alldata[,2]))) points(var2,col='green',pch=24,bg='green') points(var3,col='blue',pch=19,bg='blue') gauss_similarity_matrix = gausskernel(X = alldata, sigma = 1) gauss_adjacency_matrix = matrix(rep(0),60,60) for(i in 1:60) { for(j in i:60) { if(gauss_similarity_matrix[i,j] >= 0.5) { lines(c(alldata[i,1],alldata[j,1]),c(alldata [i,2],alldata[j,2])) gauss_adjacency_matrix[i,j] = 1 } else { gauss_adjacency_matrix[i,j] = 0 } } } <file_sep> normal_clust = kmeans(alldata,3) ############# Problem 4a ################ plot(alldata,col=normal_clust$cluster,pch = normal_cluster$cluster) first_k_eigen = sort(unique(eigen(knn_lap_norm)$values))[1:3] k_vectors = c() for(i in 1:3) { for(j in 1:60) { if(first_k_eigen[i]== eigen(knn_lap_norm)$values[j]) { k_vectors = c(k_vectors,j) break } } } k_dimensional_vectors = cbind(eigen(knn_lap_norm)$vectors[,k_vectors]) library("ppls") normalized_vector = matrix(rep(0),0,3) for(i in 1:60) { normalized_vector=rbind(normalized_vector,normalize.vector(Re(k_dimensional_vectors[i,]))) } clust = kmeans(normalized_vector,3) ############# Problem 4b:For KNN Graph################ plot(alldata,col=clust$cluster,pch = clust$cluster) first_k_eigen_gauss = sort(unique(eigen(gauss_lap_norm)$values))[1:3] k_vectors_gauss = c() for(i in 1:3) { for(j in 1:60) { if(first_k_eigen_gauss[i]== eigen(gauss_lap_norm)$values[j]) { k_vectors_gauss = c(k_vectors_gauss,j) break } } } k_dimensional_vectors_gauss = cbind(eigen(gauss_lap_norm)$vectors[,k_vectors_gauss]) library("ppls") library('gaggleUtil') normalized_vector_gauss = normalize(k_dimensional_vectors_gauss) clust = kmeans(normalized_vector_gauss,3) ############# Problem 4b:For Gaussian Graph################ plot(alldata,col=clust$cluster,pch = clust$cluster)<file_sep>library(MASS) library(plot3D) set.seed(2) Sigma <- matrix(c(10,1,1,2),2,2) Sigma <- matrix(c(1,0.5,0.5,1),2,2) var1 = mvrnorm(n=20,c(2,2),Sigma) var2 = mvrnorm(n=20,c(4,4),Sigma) var3 = mvrnorm(n=20,c(6,6),Sigma) alldata = rbind(var1,var2,var3) #######Problem 1a ############# plot(var1,col='red',pch=22,bg='red',xlim=range(0,max(alldata[,1])),ylim =range (0,max(alldata[,2]))) points(var2,col='green',pch=24,bg='green') points(var3,col='blue',pch=19,bg='blue') #######Problem 1b ############# hist3D(z=alldata,ltheta = -135) <file_sep>library("igraph") knn_adjacency_matrix= get.adjacency(G1) gauss_lap = graph.laplacian(graph.adjacency(gauss_adjacency_matrix)) gauss_lap_norm = graph.laplacian(graph.adjacency(gauss_adjacency_matrix), normalized=TRUE) knn_lap = graph.laplacian(graph.adjacency(knn_adjacency_matrix)) knn_lap_norm = graph.laplacian(graph.adjacency(knn_adjacency_matrix),normalized = TRUE) ######### Problem 3a ############## plot(c(1:60),sort(eigen(knn_lap)$values),type="l",col="blue") points(c(1:60),sort(eigen(knn_lap)$values),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(knn_lap_norm)$values),type="l",col="blue") points(c(1:60),sort(eigen(knn_lap_norm)$values),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(gauss_lap_norm)$values),type="l",col="blue") points(c(1:60),sort(eigen(gauss_lap_norm)$values),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(gauss_lap)$values),type="l",col="blue") points(c(1:60),sort(eigen(gauss_lap)$values),pch=19,bg='blue',col="blue") second_smallest_knn = sort(unique(eigen(knn_lap)$values))[2] knn_j=0 for(i in 1:60) { if(eigen(knn_lap)$values[i]==second_smallest_knn) { knn_j=i } } second_smallest_knn_norm = sort(unique(eigen(knn_lap_norm)$values))[2] knn_norm_j=0 for(i in 1:60) { if(eigen(knn_lap_norm)$values[i]==second_smallest_knn_norm) { knn_norm_j=i } } second_smallest_gauss = sort(unique(eigen(gauss_lap)$values))[2] gauss_j=0 for(i in 1:60) { if(eigen(gauss_lap)$values[i]==second_smallest_gauss) { gauss_j=i } } second_smallest_gauss_norm = sort(unique(eigen(gauss_lap_norm)$values))[2] gauss_norm_j=0 for(i in 1:60) { if(eigen(gauss_lap_norm)$values[i]==second_smallest_gauss_norm) { gauss_norm_j=i } } ######### Problem 3c ############## plot(c(1:60),sort(eigen(knn_lap)$vectors[,knn_j]),col="blue",type='l') points(c(1:60),sort(eigen(knn_lap)$vectors[,knn_j]),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(knn_lap_norm)$vectors[,knn_norm_j]),col="blue",type='l') points(c(1:60),sort(eigen(knn_lap_norm)$vectors[,knn_norm_j]),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(gauss_lap)$vectors[,gauss_j]),col="blue",type='l') points(c(1:60),sort(eigen(gauss_lap)$vectors[,gauss_j]),pch=19,bg='blue',col="blue") plot(c(1:60),sort(eigen(gauss_lap_norm)$vectors[,gauss_norm_j]),col="blue",type='l') points(c(1:60),sort(eigen(gauss_lap_norm)$vectors[,gauss_norm_j]),pch=19,bg='blue',col="blue") ######### Problem 3d ############## mat1 = matrix(rep(0),0,3) mat2 = matrix(rep(0),0,3) points_in_community1_knn=c() points_in_community2_knn=c() for(i in 1:60) { if(Re(eigen(knn_lap)$vectors[,knn_j][i]) < 0.0) { mat1=rbind(mat1,c(alldata[i,],i)) points_in_community1_knn = c(points_in_community1_knn,i) } else { mat2=rbind(mat2,c(alldata[i,],i)) points_in_community2_knn = c(points_in_community2_knn,i) } } mat1 = matrix(rep(0),0,3) mat2 = matrix(rep(0),0,3) points_in_community1_knn_norm=c() points_in_community2_knn_norm=c() for(i in 1:60) { if(Re(eigen(knn_lap_norm)$vectors[,knn_norm_j][i]) < 0.00) { mat1=rbind(mat1,c(alldata[i,],i)) points_in_community1_knn_norm = c(points_in_community1_knn_norm,i) } else { mat2=rbind(mat2,c(alldata[i,],i)) points_in_community2_knn_norm = c(points_in_community2_knn_norm,i) } } mat1 = matrix(rep(0),0,3) mat2 = matrix(rep(0),0,3) points_in_community1_gauss=c() points_in_community2_gauss=c() for(i in 1:60) { if(Re(eigen(gauss_lap)$vectors[,gauss_j][i]) < 0.05) { mat1=rbind(mat1,c(alldata[i,],i)) points_in_community1_gauss = c(points_in_community1_gauss,i) } else { mat2=rbind(mat2,c(alldata[i,],i)) points_in_community2_gauss = c(points_in_community2_gauss,i) } } mat1 = matrix(rep(0),0,3) mat2 = matrix(rep(0),0,3) points_in_community1_gauss_norm =c() points_in_community2_gauss_norm =c() for(i in 1:60) { if(Re(eigen(gauss_lap_norm)$vectors[,gauss_norm_j][i]) < 0.05) { mat1=rbind(mat1,c(alldata[i,],i)) points_in_community1_gauss_norm = c(points_in_community1_gauss_norm,i) } else { mat2=rbind(mat2,c(alldata[i,],i)) points_in_community2_gauss_norm = c(points_in_community2_gauss_norm,i) } } total_edges_in_community1 = 0 is_point_in_comm1 = c(1:60) is_point_in_comm1 = !(is_point_in_comm1 %in% points_in_community2_knn) for(i in 1:length(points_in_community1_knn)) { for(j in 1:60) { if(knn_adjacency_matrix[points_in_community1_knn[i],j] == 1 & is_point_in_comm1[j]) total_edges_in_community1 = total_edges_in_community1 + 1 } } total_edges_in_community2 = 0 is_point_in_comm2 = c(1:60) is_point_in_comm2 = !(is_point_in_comm2 %in% points_in_community1_knn) for(i in 1:length(points_in_community2_knn)) { for(j in 1:60) { if(knn_adjacency_matrix[points_in_community2_knn[i],j] == 1 & is_point_in_comm2[j]) total_edges_in_community2 = total_edges_in_community2 + 1 } } total_edges_leaving_community=0 for(i in 1:length(points_in_community1_knn)) { for(j in 1:60) { if(knn_adjacency_matrix[points_in_community1_knn[i],j] == 1 & !is_point_in_comm1[j]) total_edges_leaving_community = total_edges_leaving_community+1 } } total_edges_leaving_community2=0 for(i in 1:length(points_in_community2_knn)) { for(j in 1:60) { if(knn_adjacency_matrix[points_in_community2_knn[i],j] == 1 & !is_point_in_comm2[j]) total_edges_leaving_community2 = total_edges_leaving_community2+1 } } ######### Problem 3e ############## conductance1 = total_edges_leaving_community/ (2*total_edges_in_community1 + total_edges_leaving_community) conductance2 = total_edges_leaving_community2/ (2*total_edges_in_community2 + total_edges_leaving_community2)
82aa06edecc8dd6e1e511e66321b8da51ccca910
[ "R" ]
5
R
kristyspatel/Spectral-graph-Clustering-in-R-ML
8865734284e0b846f39b8edc74722da2a69b2bb0
0805e88ebf84ab413189cab3e536c87f8ad15ff4
refs/heads/master
<repo_name>diptigautam/TheMemeTeam_EverestHack<file_sep>/notification3/call.js window.onload = function() { fetchData() } function fetchData() { let postsArr = [] fetch("http://127.0.0.1:8000/memeapi/").then(res=>res.json()).then(data=>{ //fetch("http://localhost:800[0/api.json").then(res=>res.json()).then(data=>{ postsArr.push(data) // document.getElementById('count').innerHTML = postsArr.length var content = document.getElementById("count").innerHTML; document.getElementById("count").innerHTML= postsArr.length; if (postsArr.length >0) show() }) } function show() { var time = /(..)(:..)/.exec(new Date()); // The prettyprinted time. var hour = time[1] % 12 || 12; // The prettyprinted hour. var period = time[1] < 12 ? 'a.m.' : 'p.m.'; // The period of the day. new Notification(hour + time[2] + ' ' + period, { icon: 'logo.png', body: 'Recommendation' }); } setInterval(fetchData, 25000);<file_sep>/memeserver/memeapi/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. import inspect import praw import pandas as pd import datetime as dt import json import matplotlib as plt def index(request): reddit = praw.Reddit(client_id='K0MvgY52tRivJQ', \ client_secret='WM-jeFwR9AMb3RA2d9aY6jI3ln4', \ user_agent='apiforvisualization', \ username='', \ password='') # print(inspect.getmembers(reddit)) subreddit = reddit.subreddit('dankmemes') # print(subreddit) top_subreddit = subreddit.top(limit=500) # print(top_subreddit) # for submission in subreddit.top(limit=1): # print(submission.title, submission.id) topics_dict = { "title":[], "score":[], "id":[], "url":[], "comms_num": [], "created": [], "body":[], "author":[]} for submission in top_subreddit: topics_dict["title"].append(submission.title) topics_dict["score"].append(submission.score) topics_dict["id"].append(submission.id) topics_dict["url"].append(submission.url) topics_dict["comms_num"].append(submission.num_comments) topics_dict["created"].append(submission.created) topics_dict["body"].append(submission.selftext) topics_dict["author"].append(submission.author) df= pd.DataFrame.from_dict(topics_dict) userfiltered = df["author"]=="FreeVegetable" filtereddata = df[userfiltered] print(filtereddata['author']) del filtereddata['author'] backdict = filtereddata.to_dict() return HttpResponse( json.dumps(backdict), content_type = 'application/json; charset=utf8' )
e4bd47bc2119e099e456234c7c71dc5f9c05eac1
[ "JavaScript", "Python" ]
2
JavaScript
diptigautam/TheMemeTeam_EverestHack
1f906b041ac4100e3e1551ed0e5c9925c25f34dc
d43a90e99c1f70f0aaf9e3cb0b87f3c4167239be
refs/heads/master
<repo_name>valgilbert/java-drone-delivery<file_sep>/README.md # Drone Delivery Analysis ## Analysis - How did you implement your solution? - Ans. I implement my solution with SpringBoot and Java 8 Stream API - Why did you implement it this way? - Ans. It is much easier to manipulate several list using the Stream API. We can take advantage of the several functions to manipulate and process collections. - Let's assume we need to handle dispatching thousands of jobs per second to thousands of drivers. Would the solution you've implemented still work? Why or why not? What would you modify? Feel free to describe a completely different solution than the one you've developed. - Ans. Yes, This solution can handle high volume of request. Aside from the fact that streams are fast and efficient with bulk processing and parallel processing of data with stream operations. This application is design as a micro-service and can be easily be scaled accordingly. <file_sep>/src/main/java/com/coding/exercise/dronedelivery/core/service/PackageService.java package com.coding.exercise.dronedelivery.core.service; import java.io.IOException; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.coding.exercise.dronedelivery.core.model.Package; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @Service public class PackageService { private static final Logger LOG = Logger.getLogger(PackageService.class); private ObjectMapper mapper = new ObjectMapper(); @Autowired HTTPClientService client; public List<Package> getPackages() { List<Package> packages = null; try { String response = client .getRequest("https://codetest.kube.getswift.co/packages"); packages = mapper.readValue(response, mapper.getTypeFactory() .constructCollectionType(List.class, Package.class)); } catch (JsonParseException e) { LOG.error(e.getMessage()); } catch (JsonMappingException e) { LOG.error(e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage()); } catch (Exception e) { LOG.error(e.getMessage()); } return packages; } } <file_sep>/src/main/java/com/coding/exercise/dronedelivery/DroneDeliveryApplication.java package com.coding.exercise.dronedelivery; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DroneDeliveryApplication { public static void main(String[] args) { SpringApplication.run(DroneDeliveryApplication.class, args); } } <file_sep>/src/main/java/com/coding/exercise/dronedelivery/core/model/Location.java package com.coding.exercise.dronedelivery.core.model; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) @JsonAutoDetect(fieldVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE) public class Location implements Serializable { private static final long serialVersionUID = 4340842332522735176L; @JsonProperty("latitude") private double latitude; @JsonProperty("longitude") private double longitude; public Location() { } public Location(double latitude, double longitude) { super(); this.latitude = latitude; this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitute) { this.longitude = longitute; } public double calcDistanceToDestination(Location destination) { double theta = this.getLongitude() - destination.getLongitude(); double distance = Math.sin(deg2rad(this.latitude)) * Math.sin(deg2rad(destination.getLatitude())) + Math.cos(deg2rad(this.latitude)) * Math.cos(deg2rad(destination.getLatitude())) * Math.cos(deg2rad(theta)); distance = Math.acos(distance); distance = rad2deg(distance); distance = distance * 60 * 1.1515; distance = distance * 1.609344; return distance; } private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } private double rad2deg(double rad) { return (rad * 180 / Math.PI); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(latitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(longitude); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Location other = (Location) obj; if (Double.doubleToLongBits(latitude) != Double .doubleToLongBits(other.latitude)) return false; if (Double.doubleToLongBits(longitude) != Double .doubleToLongBits(other.longitude)) return false; return true; } @Override public String toString() { return "Location [latitude=" + latitude + ", longitude=" + longitude + "]"; } public Object compareTo(Location destination) { // TODO Auto-generated method stub return null; } } <file_sep>/src/main/java/com/coding/exercise/dronedelivery/core/model/Assignment.java package com.coding.exercise.dronedelivery.core.model; public class Assignment { private int droneId; private int packageId; public Assignment(int droneId, int packageId) { super(); this.droneId = droneId; this.packageId = packageId; } public int getDroneId() { return droneId; } public int getPackageId() { return packageId; } } <file_sep>/src/main/java/com/coding/exercise/dronedelivery/core/controller/DroneDeliveryController.java package com.coding.exercise.dronedelivery.core.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.coding.exercise.dronedelivery.core.model.AssignRequest; import com.coding.exercise.dronedelivery.core.model.AssignResponse; import com.coding.exercise.dronedelivery.core.model.Drone; import com.coding.exercise.dronedelivery.core.model.Package; import com.coding.exercise.dronedelivery.core.service.DroneService; import com.coding.exercise.dronedelivery.core.service.PackageService; @Controller @RequestMapping(value = "/dronedelivery") public class DroneDeliveryController { @Autowired private DroneService droneService; @Autowired private PackageService packageService; public DroneDeliveryController() { super(); } @RequestMapping(value = "/assign", method = RequestMethod.POST) @ResponseBody public AssignResponse assign(@RequestBody AssignRequest request) throws Exception { return droneService.assignPackagesToDrones(request.getDrones(), request.getPackages()); } @RequestMapping(value = "/drones", method = RequestMethod.GET) @ResponseBody public List<Drone> getDrones() throws Exception { return droneService.getDrones(); } @RequestMapping(value = "/packages", method = RequestMethod.GET) @ResponseBody public List<Package> getPackages() throws Exception { return packageService.getPackages(); } } <file_sep>/src/test/java/com/coding/exercise/dronedelivery/core/controller/DroneDeliveryControllerTest.java package com.coding.exercise.dronedelivery.core.controller; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.coding.exercise.dronedelivery.core.model.AssignRequest; import com.coding.exercise.dronedelivery.core.model.AssignResponse; import com.coding.exercise.dronedelivery.core.model.Assignment; import com.coding.exercise.dronedelivery.core.model.Drone; import com.coding.exercise.dronedelivery.core.model.Package; import com.coding.exercise.dronedelivery.core.service.DroneService; import com.coding.exercise.dronedelivery.core.service.PackageService; public class DroneDeliveryControllerTest { @Mock private DroneService droneService; @Mock private PackageService packageService; @InjectMocks private DroneDeliveryController controller; @Before public void before() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void testGetDrones() throws Exception { Mockito.when(droneService.getDrones()).thenReturn( new ArrayList<Drone>()); controller.getDrones(); Mockito.verify(droneService, Mockito.times(1)).getDrones(); } @Test public void testGetPackages() throws Exception { Mockito.when(packageService.getPackages()).thenReturn( new ArrayList<Package>()); controller.getPackages(); Mockito.verify(packageService, Mockito.times(1)).getPackages(); } @Test public void testAssign() throws Exception { AssignResponse response = new AssignResponse( new ArrayList<Assignment>(), new ArrayList<Integer>()); AssignRequest request = new AssignRequest(); Mockito.when( droneService.assignPackagesToDrones(new ArrayList<Drone>(), new ArrayList<Package>())).thenReturn(response); controller.assign(request); Mockito.verify(droneService, Mockito.times(1)); } }
a5e459e3f5a45c5264bfdf26abb73a73f5620198
[ "Markdown", "Java" ]
7
Markdown
valgilbert/java-drone-delivery
453ae0f57891ebb340553116e2e12a82554ce096
c27b2682f90c10b4741751109cba506b04f4c67c
refs/heads/master
<file_sep>app.factory('todoService', ['$resource', '$firebaseArray', function($resource, $firebaseArray) { return { get: function() { var ref = new Firebase("http://firebaseio.com"); return $firebaseArray(ref); } } }]);<file_sep># todo_firebase This is a simple todo app with integration of Firebase for database /js/services/todoService.js line 4: replace url with your own database link
512206df015062dbd5788f8fed71bd715abe6b8c
[ "JavaScript", "Markdown" ]
2
JavaScript
estherylau/todo_firebase
f3354890b083802ace68e789ea14c730fec72336
17e9ae5ea5555b84f9438ba9036427670206156d
refs/heads/master
<repo_name>pravl/react-input-select-fields<file_sep>/src/Select/Select.stories.js import React from 'react'; import Select from "./Select.jsx" export default { title: 'Select', component: Select, argTypes: { backgroundColor: { control: 'color' }, }, }; const Template = (args) => <div><Select {...args} /></div>; export const SelectBox = Template.bind({}); SelectBox.args = { dropDownList: [ {label: "India",value : 1}, {label: "America",value : 2}, {label: "Russia",value : 3}, {label: "Canada",value : 4}, {label: "Africa",value : 5}, ] }; <file_sep>/src/Input/Input.jsx import * as React from 'react'; const Input = ({ type = "text", name = "input", value, placeholder="Enter here", maxLength, minLength, isRequired, errorMsg, isReadOnly, customValidation, handleOnInputChange, handleOnInputBlur, isErrorShow = true }) => { const [inputValue, setInputValue] = React.useState(value || "") const [error, setError] = React.useState() const handleUserInput = (e) => { let text = e.target.value.trim() setInputValue(text) if (handleOnInputChange) handleOnInputChange(e) } const validateEmailInput = (input) => { let email_regex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; let matches = input.match(email_regex); return !matches ? 'Enter valid email address' : null } const validateNumberInput = (input) => { let for_only_number_regex = /^\d+$/ let matches = input.match(for_only_number_regex); return !matches ? 'Enter only numbers' : null } const checkValidation = (input) => { let msg = null if (type == "email") { msg = validateEmailInput(input) } else if(type == "number") { msg = validateNumberInput(input) if (minLength && minLength > input.length) { msg = `minimum length should be ${minLength}` }else if (maxLength && maxLength < input.length) { msg = `maximum length should be ${minLength}` } } if (!msg && customValidation) msg = customValidation(input) setError(msg) } const handleOnBlur = (e) => { checkValidation(e.target.value) if (handleOnInputChange) handleOnInputBlur(e) } return ( <div className="input-container" > <input className="input" name={name} value={inputValue} type={type} placeholder={placeholder} onChange={handleUserInput} onBlur={handleOnBlur} required={isRequired} minLength={minLength} maxLength={maxLength} //pattern=".{5,10}" readOnly={isReadOnly} // autoFocus={this.props.auto_focus} /> {isErrorShow&& <span className="error-block">{Boolean(error) ? error : ""}</span>} </div> ) } export default Input <file_sep>/src/index.js import Select from './Select/Select.jsx'; import Input from "./Input/Input.jsx" export const InputElement = Input export const SingleSelect = Select <file_sep>/src/Select/Select.jsx import * as React from 'react'; import "./Select.css" const Select = ({ defaultValue, dropDownList, onSelect }) => { const [value, setValue] = React.useState(defaultValue) const [dropDown, setDropDown] = React.useState(false) const dropDownRef = React.useRef(null) const clickOutside = (event) => { if (dropDown && dropDownRef && dropDownRef.current && !dropDownRef.current.contains(event.target)) { setDropDown(false) } } React.useEffect(() => { document.addEventListener("click", clickOutside) return () => document.removeEventListener("click", clickOutside) }) const onChange = (el) => { setValue(el) if (onSelect) onSelect(el) } return ( <div ref={dropDownRef} className="select-container"> <div className="title-box" onClick={() => setDropDown(!dropDown)}> <div className="title-label"> {value && value.label ? value.label : "Select" } </div> <div className="caret"> {dropDown ? ( <span style={{ color: "black" }}> <svg stroke="currentColor" fill="currentColor" strokeWidth="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z"></path> </svg> </span> ) : ( <span style={{ color: "black" }}> <svg stroke="currentColor" fill="currentColor" strokeWidth="0" viewBox="0 0 24 24" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"></path> </svg> </span> )} </div> </div> <div className="select-box" style={ dropDown ? {display : "block"} : {visibility : "hidden"} } > <div className="list-container"> {dropDownList && dropDownList.map((el, i) => ( <div className="list" onClick={() => { setDropDown(false) onChange(el) }} key={i} > <div>{el.label}</div> <div> </div> </div> ))} </div> </div> </div> ); }; export default Select <file_sep>/src/Input/Input.stories.js import React from 'react'; import Input from "./Input.jsx" export default { title: 'Input ', component: Input, argTypes: { backgroundColor: { control: 'color' }, }, }; const Template = (args) => <Input {...args} />; export const InputEmail = Template.bind({}); InputEmail.args = { type : "email", name : "email", placeholder : "enter email", isRequired :true, } export const InputNumber = Template.bind({}); InputNumber.args = { type : "number", name : "number", placeholder : "enter number", isRequired :true, maxLength:20, minLength:3, } <file_sep>/README.md ### Form's Input and Select Element Demo can be found in the storybook. #### Setup - Clone the repo. - Run `npm install` - Run `npm storybook` - This will open up a UI to view details on the components being exported along with their documentations. #### Usage - Install the package via npm ``` npm install react-input-select-fields ``` ### Input Simple input field with allowed types as number and email. #### Usage ``` <InputElement {...props} /> ``` ``` Props type name value, placeholder, maxLength, minLength, isRequired, errorMsg, isReadOnly, customValidation handleOnInputChange handleOnInputBlur isErrorShow ``` ``` ClassName input-container input error-block ``` #### Handlers - `handleOnInputChange`: Triggered on every input change. - `handleOnInputBlur`: Triggered when user moves out of the input box. Suggested way to get the final value of input. - `customValidation`: Triggered on every input. Function receives the current entered text and expects an error string in case of any validation failures else empty string | null | undefined. ### Select Simple Single Select. ``` <SingleSelect {...props} /> ``` #### Usage ``` Props defaultValue dropDownList onSelect ``` ``` ClassName select-container title-box title-label caret select-box list-container list ``` #### Handlers - `defaultValue`: if value is already present. - `onSelect`: Triggered when user select any option, get selected value. - `dropDownList`: Array of List Array<label, value>.
1c4dc9ff155c9bbd1b10a6e0cc3482c29974535f
[ "JavaScript", "Markdown" ]
6
JavaScript
pravl/react-input-select-fields
c99915a0bee042abe097ee0c2f7d3878dde49073
c21718bc73ebd434b29b419d10e2fba8889aeddb
refs/heads/master
<file_sep># EmbedMask Unofficial implementation for EmbedMask instance segmentation office: https://github.com/yinghdb/EmbedMask arxiv: https://arxiv.org/abs/1912.01954 ## Log #### 2020/6/3 |config|bbox|mask|weight| |-|:-:|-:|-:| |MS_R_50_2x.yaml|40.399|34.105|[google drive](https://drive.google.com/file/d/18p5s2NCZwbBNzZnUmfovF9RM1hzxlEX4/view?usp=sharing)| #### Before 2020/6/3 The performance is not very stable at present. **MS_R_50_2x.yaml**, **box AP 34%** and **seg AP 28%** were reached after a brief training. Under the same number of iterations, **MS_X_101_3x.yaml** gets **box AP 37%**, while **seg AP is only 24%**. [Here](https://github.com/gakkiri/EmbedMask/blob/master/fcos/modeling/fcos/fcos_outputs.py#L363) I use the CPU implementation, so the FPS is low. ## Install The code is based on [detectron2](https://github.com/facebookresearch/detectron2). Please check [Install.md](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md) for installation instructions. ## Training Follows the same way as detectron2. Single GPU: ``` python train_net.py --config-file configs/EmbedMask/MS_R_101_3x.yaml ``` Multi GPU(for example 8): ``` python train_net.py --num-gpus 8 --config-file configs/EmbedMask/MS_R_101_3x.yaml ``` Please adjust the IMS_PER_BATCH in the config file according to the GPU memory. ## Inference Single GPU: ``` python train_net.py --config-file configs/EmbedMask/MS_R_101_3x.yaml --eval-only MODEL.WEIGHTS /path/to/checkpoint_file ``` Multi GPU(for example 8): ``` python train_net.py --num-gpus 8 --config-file configs/EmbedMask/MS_R_101_3x.yaml --eval-only MODEL.WEIGHTS /path/to/checkpoint_file ``` ## Results ### 2020/6/3 #### MS_R_50_2x.yaml ![box](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/box50.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) ![seg](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/mask50.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) #### visualization ![.](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/v1.png) ![.](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/v2.png) ![.](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/v3.png) ## history I trained about 10 epochs, a V100 takes about 2 days. #### MS_X_101_3x.yaml ![box](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/bbox_ap.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) ![seg](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/seg_ap.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) #### MS_R_50_2x.yaml ![box](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/box_50.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) ![seg](https://raw.githubusercontent.com/gakkiri/EmbedMask/master/img/seg_50.png?x-oss-Process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDk3ODQ1,size_16,color_FFFFFF,t_70) <file_sep>import torch from detectron2.layers import interpolate def iou(boxes1, boxes2): area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] TO_REMOVE = 1 wh = (rb - lt + TO_REMOVE).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] iou = inter / (area1[:, None] + area2 - inter) return iou def compute_mask_prob(proposal_embed, proposal_margin, pixel_embed, fix_margin=False): m_h, m_w = pixel_embed.shape[-2:] # [D, H, W] obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(1, 2, 0).unsqueeze(0).expand(obj_num, -1, -1, -1) # [m, H, W, D] proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w, -1) if fix_margin: init_margin = 1 # todo add to __init__ proposal_margin = proposal_margin.new_ones(obj_num, m_h, m_w) * init_margin else: proposal_margin = proposal_margin.view(obj_num, 1, 1).expand(-1, m_h, m_w) mask_var = torch.sum((pixel_embed - proposal_embed) ** 2, dim=3) mask_prob = torch.exp(-mask_var * proposal_margin) return mask_prob def prepare_masks(o_h, o_w, r_h, r_w, targets_masks): masks = [] for im_i in range(len(targets_masks)): mask_t = targets_masks[im_i] if len(mask_t) == 0: masks.append(mask_t.new_tensor([])) continue n, h, w = mask_t.shape mask = mask_t.new_zeros((n, r_h, r_w)) mask[:, :h, :w] = mask_t resized_mask = interpolate( input=mask.float().unsqueeze(0), size=(o_h, o_w), mode="bilinear", align_corners=False, )[0].gt(0) masks.append(resized_mask) return masks def crop_by_box(masks, box, padding=0.0): n, h, w = masks.size() b_w = box[2] - box[0] b_h = box[3] - box[1] x1 = torch.clamp(box[0:1] - b_w * padding - 1, min=0) x2 = torch.clamp(box[2:3] + b_w * padding + 1, max=w - 1) y1 = torch.clamp(box[1:2] - b_h * padding - 1, min=0) y2 = torch.clamp(box[3:4] + b_h * padding + 1, max=h - 1) rows = torch.arange(w, device=masks.device, dtype=x1.dtype).view(1, 1, -1).expand(n, h, w) cols = torch.arange(h, device=masks.device, dtype=x1.dtype).view(1, -1, 1).expand(n, h, w) masks_left = rows >= x1.expand(n, 1, 1) masks_right = rows < x2.expand(n, 1, 1) masks_up = cols >= y1.expand(n, 1, 1) masks_down = cols < y2.expand(n, 1, 1) crop_mask = masks_left * masks_right * masks_up * masks_down return masks * crop_mask.float(), crop_mask def boxes_to_masks(boxes, h, w, padding=0.0): n = boxes.shape[0] boxes = boxes x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] b_w = x2 - x1 b_h = y2 - y1 x1 = torch.clamp(x1 - 1 - b_w * padding, min=0) x2 = torch.clamp(x2 + 1 + b_w * padding, max=w) y1 = torch.clamp(y1 - 1 - b_h * padding, min=0) y2 = torch.clamp(y2 + 1 + b_h * padding, max=h) rows = torch.arange(w, device=boxes.device, dtype=x1.dtype).view(1, 1, -1).expand(n, h, w) cols = torch.arange(h, device=boxes.device, dtype=x1.dtype).view(1, -1, 1).expand(n, h, w) masks_left = rows >= x1.view(-1, 1, 1) masks_right = rows < x2.view(-1, 1, 1) masks_up = cols >= y1.view(-1, 1, 1) masks_down = cols < y2.view(-1, 1, 1) masks = masks_left * masks_right * masks_up * masks_down return masks
dafa7f4f37b50b6a3f8d2f24fb941947519be644
[ "Markdown", "Python" ]
2
Markdown
gakkiri/EmbedMask
a31538a5b7338a3fdcd4e270d3750da919b95214
f6d4c2b60612c42b81f38fdae27ff9465d07f1be
refs/heads/main
<file_sep>package tqs.projet.airquality; public class Pollen { private String city_name; private String country_code; private String state_code; private double lat; private double lon; private int pollen_level_tree; private int pollen_level_grass; private int pollen_level_weed; private int mold_level; private String predominant_pollen_type; public Pollen() {} public Pollen(String city_name, String country_code, String state_code, double lat, double lon, int pollen_level_tree, int pollen_level_grass, int pollen_level_weed, int mold_level, String predominant_pollen_type) { super(); this.city_name = city_name; this.country_code = country_code; this.state_code = state_code; this.lat = lat; this.lon = lon; this.pollen_level_tree = pollen_level_tree; this.pollen_level_grass = pollen_level_grass; this.pollen_level_weed = pollen_level_weed; this.mold_level = mold_level; this.predominant_pollen_type = predominant_pollen_type; } public String getCity_name() { return city_name; } public void setCity_name(String city_name) { this.city_name = city_name; } public String getCountry_code() { return country_code; } public void setCountry_code(String country_code) { this.country_code = country_code; } public String getState_code() { return state_code; } public void setState_code(String state_code) { this.state_code = state_code; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public int getPollen_level_tree() { return pollen_level_tree; } public void setPollen_level_tree(int pollen_level_tree) { this.pollen_level_tree = pollen_level_tree; } public int getPollen_level_grass() { return pollen_level_grass; } public void setPollen_level_grass(int pollen_level_grass) { this.pollen_level_grass = pollen_level_grass; } public int getPollen_level_weed() { return pollen_level_weed; } public void setPollen_level_weed(int pollen_level_weed) { this.pollen_level_weed = pollen_level_weed; } public int getMold_level() { return mold_level; } public void setMold_level(int mold_level) { this.mold_level = mold_level; } public String getPredominant_pollen_type() { return predominant_pollen_type; } public void setPredominant_pollen_type(String predominant_pollen_type) { this.predominant_pollen_type = predominant_pollen_type; } } <file_sep>package tqs.projet.airquality; public class AirQuality { private String city_name; private String country_code; private String state_code; private double lat; private double lon; private int aqi; private int o3; private int so2; private int no2; private int co; private int pm10; private int pm25; public AirQuality() { } public AirQuality(String location, String country, String state, double lat, double lon, int aqi, int o3, int so2, int no2, int co, int pm10, int pm25) { super(); this.city_name = location; this.country_code = country; this.state_code = state; this.lat = lat; this.lon = lon; this.aqi = aqi; this.o3 = o3; this.so2 = so2; this.no2 = no2; this.co = co; this.pm10 = pm10; this.pm25 = pm25; } public String getCity_name() { return city_name; } public void setCity_name(String city_name) { this.city_name = city_name; } public String getCountry_code() { return country_code; } public void setCountry_code(String country_code) { this.country_code = country_code; } public String getState_code() { return state_code; } public void setState_code(String state_code) { this.state_code = state_code; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public int getAqi() { return aqi; } public void setAqi(int aqi) { this.aqi = aqi; } public int getO3() { return o3; } public void setO3(int o3) { this.o3 = o3; } public int getSo2() { return so2; } public void setSo2(int so2) { this.so2 = so2; } public int getNo2() { return no2; } public void setNo2(int no2) { this.no2 = no2; } public int getCo() { return co; } public void setCo(int co) { this.co = co; } public int getPm10() { return pm10; } public void setPm10(int pm10) { this.pm10 = pm10; } public int getPm25() { return pm25; } public void setPm25(int pm25) { this.pm25 = pm25; } @Override public String toString() { return "AirQuality [city_name=" + city_name + ", country_code=" + country_code + ", state_code=" + state_code + ", lat=" + lat + ", lon=" + lon + ", aqi=" + aqi + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + aqi; result = prime * result + ((city_name == null) ? 0 : city_name.hashCode()); result = prime * result + co; result = prime * result + ((country_code == null) ? 0 : country_code.hashCode()); long temp; temp = Double.doubleToLongBits(lat); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(lon); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + no2; result = prime * result + o3; result = prime * result + pm10; result = prime * result + pm25; result = prime * result + so2; result = prime * result + ((state_code == null) ? 0 : state_code.hashCode()); return result; } } <file_sep>package tqs.projet.airquality; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.verify; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; @ExtendWith(MockitoExtension.class) public class AirQualityServiceTests { @Mock private CacheService cacheService; @InjectMocks private AirQualityService airQualityService; private String jsonResponse = "{\"data\":[{\"mold_level\":1,\"aqi\":82,\"pm10\":3.7231,\"co\":325.859,\"o3\":145.555,\"predominant_pollen_type\":\"Molds\",\"so2\":1.39698,\"pollen_level_tree\":1,\"pollen_level_weed\":1,\"no2\":1.0322,\"pm25\":2.19588,\"pollen_level_grass\":1}],\"city_name\":\"Aveiro\",\"lon\":\"-8.64554\",\"timezone\":\"Europe Lisbon\",\"lat\":\"40.64427\",\"country_code\":\"PT\",\"state_code\":\"02\"}"; @Test public void whenValidLocationReturnValidAirQuality() { AirQuality aq = new AirQuality("Aveiro","PT","02",40.64427,-8.64554,82,145,1,1,325,3,2); String location = "Aveiro"; given( cacheService.getObjectCached(location)).willReturn(jsonResponse); AirQuality aq_res = airQualityService.getAirQuality(location); assertThat(aq, is(samePropertyValuesAs(aq_res))); verify(cacheService, VerificationModeFactory.times(1)).getObjectCached(location); } @Test public void whenInvalidLocationReturnPollen() { Pollen p = new Pollen("Aveiro","PT","02",40.64427,-8.64554,1,1,1,1,"Molds"); String location = "Aveiro"; given( cacheService.getObjectCached(location)).willReturn(jsonResponse); Pollen p_res = airQualityService.getPollen(location); assertThat(p, is(samePropertyValuesAs(p_res))); verify(cacheService, VerificationModeFactory.times(1)).getObjectCached(location); } @Test public void whenInvalidLocationReturnAirQualityEmpty() { AirQuality aq = new AirQuality(); String location = "SomeCityThatDoesntExist"; given( cacheService.getObjectCached(location)).willReturn(null); AirQuality aq_res = airQualityService.getAirQuality(location); assertThat(aq, is(samePropertyValuesAs(aq_res))); verify(cacheService, VerificationModeFactory.times(1)).getObjectCached(location); } @Test public void whenInvalidLocationReturnPollenEmpty() { Pollen p = new Pollen(); String location = "SomeCityThatDoesntExist"; given( cacheService.getObjectCached(location)).willReturn(null); Pollen p_res = airQualityService.getPollen(location); assertThat(p, is(samePropertyValuesAs(p_res))); verify(cacheService, VerificationModeFactory.times(1)).getObjectCached(location); } } <file_sep>package tqs.projet.airquality; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class AirQualityController { @Autowired private AirQualityService airQualityService; private Logger logger = LoggerFactory.getLogger(AirQualityController.class); @GetMapping("/api/air_quality/{location}") public ResponseEntity<AirQuality> getAirQuality(@PathVariable String location) { AirQuality ser_res = airQualityService.getAirQuality(location); logger.info("API Request | Endpoint : /api/airquality/"+location+" | Result: "+ser_res); if (ser_res.getCity_name()==null) { return new ResponseEntity<AirQuality>(new AirQuality(),HttpStatus.NOT_FOUND); }else { return new ResponseEntity<AirQuality>(ser_res,HttpStatus.OK); } } @GetMapping("/api/cache") public ResponseEntity<CacheMetrics> getCacheMetrics(){ CacheMetrics cm = airQualityService.getCacheMetrics(); logger.info("API Request | Endpoint : /api/cache | Result: "+cm); return new ResponseEntity<CacheMetrics>(cm,HttpStatus.OK); } @GetMapping("/api/pollen/{location}") public ResponseEntity<Pollen> getPollen(@PathVariable String location) { Pollen ser_res = airQualityService.getPollen(location); logger.info("API Request | Endpoint : /api/pollen/"+location+" | Result: "+ser_res); if (ser_res.getCity_name()==null) { return new ResponseEntity<Pollen>(new Pollen(),HttpStatus.NOT_FOUND); }else { return new ResponseEntity<Pollen>(ser_res,HttpStatus.OK); } } @GetMapping("/{location}") public String getAirQualityFromCity(@PathVariable String location,Model model) { AirQuality ser_res_air = airQualityService.getAirQuality(location); Pollen ser_res_pol = airQualityService.getPollen(location); logger.info("HTML Request | /"+location+" | With result"); if(ser_res_pol.getCity_name()==null || ser_res_air.getCity_name() == null) { logger.warn("HTML Request | Endpoint : /"+location+" | Without Result"); return "error"; } model.addAttribute("AirQuality", ser_res_air); model.addAttribute("Pollen", ser_res_pol); return "location_AirQuality"; } @GetMapping("/") public String getAirQualitySearch(Model model) { logger.info("HTML Request | Endpoint : / | With result"); return "search_AirQuality"; } } <file_sep>package tqs.projet.airquality; import java.util.*; import java.time.LocalDateTime; public class TTLMap<T,V>{ private Map<T,V> map; private Map<T,LocalDateTime> keyTime ; private int ttl; public TTLMap(int l){ map = new HashMap<T,V>(); keyTime = new HashMap<T,LocalDateTime>(); ttl = l; } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public V get(Object key) { if (keyTime.containsKey(key)) { if (LocalDateTime.now().isBefore(keyTime.get(key))) { return map.get(key); }else { keyTime.remove(key); } } return null; } @SuppressWarnings("unchecked") public V put(Object key, Object value) { map.put((T) key, (V) value); keyTime.put((T) key, LocalDateTime.now().plusSeconds(ttl)); return (V) value; } @Override public String toString() { return "TTLMap [map=" + map + ", keyTime=" + keyTime + ", ttl=" + ttl + "]"; } } <file_sep>#!/bin/bash set -ex wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo apt install ./google-chrome-stable_current_amd64.deb <file_sep>artifactId=weatherconditions groupId=tqs.projet version=0.0.1-SNAPSHOT
5f33c4174b1fbc3e44d6b47e9b04c3af5c862cef
[ "Java", "Shell", "INI" ]
7
Java
Barroqueiro/tqs_individual_project
59ff275e734e3ed5e52ed8f6dc585d8e9e6b41b8
4a47080807109dab011dcd1161c67e18a88b8df8
refs/heads/master
<file_sep>const Discord = require('discord.js'); const db = require('megadb'); let bank = new db.crearDB('bank'); let game = new db.crearDB('games'); /* * * "channel_id": { * "time": miliseconds * "bets": { * "betN": { * "user": "userID" * bet: money * number: [num] * even/odden: ['par'/'impar'] * trios: ['1st'/'2nd'/'3rd'] * color: [red, black] * } * } * } * */ //const {error} = require('../../files/logs.js'); //const {success, fail} = require('../../files/embeds.js'); const {success, fail} = require('../extras/embeds.js'); module.exports = { name: 'roulette', alias: ['ruleta'], description: 'La ruleta', usage: 'roulette <dinero> <apuesta>', permission: 'None', type: 'roulette', run: async (message, args) => { //let moneda = await bank.get(`${message.guild.id}.moneda`); let moneda = " # "; let pares = {'par': ['par', 'even'], 'impar': ['impar', 'odden']}; let mitad = {'1-18': ['1-18'], '19-36':['19-36']}; let trio = {'1st': ['1st', '1-12'], '2nd': ['2nd', '13-24'], '3rd': ['3rd', '25-36']}; let fila = {'r1': ['r1','f1'], 'r2': ['r2','f2'], 'r3': ['r3','f3']}; let color = {'rojo': ['red', 'rojo'], 'negro': ['black', 'negro']}; if (!args[0] || args[0] === "help") { let msg = `Pleno: 0 al 37\nParidad: ${await keysA(pares)}\nMitades: ${await keysA(mitad)} Docenas: ${await keysA(trio)}\nFilas: ${await keysA(fila)}\nColor: ${await keysA(color)}`; return message.channel.send(await success(message, msg)) } if (!args[1]) return message.channel.send(await fail(message, "No has introducido nada!")); if (isNaN(parseInt(args[0]))) return message.channel.send(await fail(message, "Valor a apostar invalido!")); let bet = parseInt(args.shift()); if (bet < 100 && bet > 300000) return message.channel.send(await fail(message, "Debes de apostar entre **100** "+moneda+" y **300.000** "+moneda)); let argsS = ","+args.toString(); console.log(argsS); pares = opt(pares, argsS); mitad = opt(mitad, argsS); trio = opt(trio, argsS); fila = opt(fila, argsS); color = opt(color, argsS); let num = []; for (let i=0;i<37;i++) { for (let j=0;j<args.length;j++) { if (args[j] == i) num.push(i) } } let totalAmount = num.length+pares.length+mitad.length+trio.length+fila.length+color.length; if (totalAmount === 0) return message.channel.send(await fail(message, "Debes de apostar algo!")); let betTotal = bet*totalAmount; console.log("Pares => "+pares+"\nMitades => "+mitad+"\nTrios => "+trio+"\nFilas => "+fila+"\nColores => "+color+"\nNums => "+num); if (!game.has(`roulette.${message.channel.id}.time`) || await game.get(`roulette.${message.channel.id}.time`)<message.createdAt.getTime()) await game.set(`roulette.${message.channel.id}.time`, message.createdAt.getTime()+300000).catch(err => console.log("1 => "+err)); let apuesta = game.has(`roulette.${message.channel.id}.bets.bet0`) ? await game.size(`roulette.${message.channel.id}.bets`) : 0; await game.set(`roulette.${message.channel.id}.bets.bet${apuesta}`, {user: message.author.id, bet: bet, num: num, par: pares, mitad: mitad, trio: trio, fila:fila, color: color}).catch(err => console.log("2 => "+err)); let msg = "["+strArray(num) +"] ["+ strArray(pares) +"] ["+ strArray(mitad) +"] ["+ strArray(trio) +"] ["+ strArray(fila) +"] ["+ strArray(color) +"]"; let lastTime = (await game.obtener(`roulette.${message.channel.id}.time`)-message.createdAt.getTime())/1000; const minutes = pad(Math.floor((lastTime % 3600) / 60), 2); const seconds = pad(Math.floor(lastTime % 60), 2); let result = minutes + " minutos y " + seconds + " segundos"; return message.channel.send(await success(message, "Apostados ``"+bet+"``<a:lain:668781874986090496> a ``"+msg+"``\n" + "Total apostado``"+betTotal+"``<a:lain:668781874986090496>\n\n" + "Tiempo restante: ``"+result+"``")) } }; function strArray(array) { if (array.length > 1) return array.join(" "); else if (array.length === 1) return array[0]; else return ""; } function pad(padStr, max) { let str = padStr.toString(); return str.length < max ? pad("0" + str, max) : str; } function opt(opts, args) { let val = []; for (let c in opts) { for (let i = 0; i < opts[c].length; i++) { if (args.includes(","+opts[c][i])) val.push(c); } } return val; } async function keysA(array) { let val = []; console.log(array); for (let c in array) { val.push(c) } return val; } <file_sep>const Discord = require('discord.js'); const db = require('megadb'); let game = new db.crearDB('games'); //const {error} = require('../../files/logs.js'); //const {success, fail} = require('../../files/embeds.js'); const {success, fail} = require('../extras/embeds.js'); module.exports = { name: 'ruleta-apuesta', alias: ['ruleta-bets', 'ruleta-apuestas'], description: 'La ruleta', usage: 'roulette-apuestas', permission: 'None', type: 'roulette', run: async (message, args) => { if (!game.has(`roulette.${message.channel.id}`)) return message.channel.send(await fail(message, "Aún no se ha iniciado ninguna partida!")); let lastTime = (await game.obtener(`roulette.${message.channel.id}.time`)-message.createdAt.getTime())/1000; const minutes = pad(Math.floor((lastTime % 3600) / 60), 2); const seconds = pad(Math.floor(lastTime % 60), 2); let result = minutes + " minutos y " + seconds + " segundos"; let lider = await game.get(`roulette.${message.channel.id}.bets.bet0.user`); let ap = await game.get(`roulette.${message.channel.id}.bets`); let stadist = []; for (let betID in ap) { let obj = ap[betID]; let motive = []; pushMotive(obj["num"]); pushMotive(obj["par"]); pushMotive(obj["mitad"]); pushMotive(obj["trio"]); pushMotive(obj["fila"]); pushMotive(obj["color"]); function pushMotive(arg) { if (arg !== undefined && arg.length>0) return motive.push(arg); } stadist.push(`<@${obj["user"]}> => ***${obj["bet"]}*** : [ **${motive.join("** | **")}** ]`); } let embed = new Discord.RichEmbed() .setTitle('RULETA') .setDescription(`Lider: <@${lider}>`) .addField('APUESTAS', stadist.join("\n")) .addField("TIEMPO", result); await message.channel.send(embed); } }; function pad(padStr, max) { let str = padStr.toString(); return str.length < max ? pad("0" + str, max) : str; }<file_sep>const Discord = require('discord.js'); const db = require('megadb'); let game = new db.crearDB('games'); //const {error} = require('../../files/logs.js'); //const {success, fail} = require('../../files/embeds.js'); const {success, fail} = require('../extras/embeds.js'); module.exports = { name: 'ruleta-start', alias: ['r-start', 'roulette-start'], description: 'La ruleta', usage: 'roulette-start', permission: 'None', type: 'roulette', init: async () => { }, run: async (message, args) => { if (!game.has(`roulette.${message.channel.id}`)) return message.channel.send(await fail(message, "Aún no se ha iniciado ninguna partida!")); let time = await game.get(`roulette.${message.channel.id}.time`); let players = await game.get(`roulette.${message.channel.id}.bets`); let lider = await game.get(`roulette.${message.channel.id}.bets.bet0.user`); if (message.author.id !== lider) return message.channel.send(await fail(message, "Solo el creador de la partida puede empezarla!")); await start(message.client, message.channel.id).then(async () => { //await game.delete(`roulette.${message.channel.id}`) }) } }; async function start(client, channel) { let num = Math.floor(Math.random() * 37); let par = num % 2 === 0 ? "par" : num !== 0 ? "impar" : 0; let mitad = num > 0 && num < 19 ? '1-18' : num > 18 && num < 37 ? '19-36' : 0; let trio = num > 24 ? '3st' : num > 12 ? '2nd' : num > 0 ? '1st' : 0; let fila = num % 3 === 1 ? 'r1' : num % 3 === 2 ? 'r2' : num !== 0 ? 'r3' : 0; let color = num > 0 && num < 11 && num % 2 === 1 || num > 10 && num < 19 && num % 2 === 0 || num > 18 && num < 29 && num % 2 === 1 || num > 28 && num < 37 && num % 2 === 0 ? 'rojo' : num !== 0 ? 'negro' : 0; let ap = await game.get(`roulette.${channel}.bets`); console.log(num, par, mitad, trio, fila, color); let msg = num===0?"0":`**${num}** | **${par}** | **${mitad}** | **${trio}** | **${fila}** | **${color}**`; let ganadores = ""; for (let betID in ap) { let obj = ap[betID]; let bet = obj["bet"]; let motive = []; console.log(bet); if (num === 0) { if (obj["num"].includes(num)) { bet*=36; motive.push(num); } } else { if (obj["num"].includes(num)) { bet*=36; motive.push(num); console.log(obj["user"]+" NUM "+num) } if (obj["par"].includes(par)) { bet*=2; motive.push(par); console.log(obj["user"]+" PAR "+par) } if (obj["mitad"].includes(mitad)) { bet*=2; motive.push(mitad); console.log(obj["user"]+" MITAD "+mitad) } if (obj["trio"].includes(trio)) { bet*=3; motive.push(trio); console.log(obj["user"]+" TRIO "+trio) } if (obj["fila"].includes(fila)) { bet*=3; motive.push(fila); console.log(obj["user"]+" FILA "+fila) } if (obj["color"].includes(color)) { bet*=2; motive.push(color); console.log(obj["user"]+" COLOR "+color) } } if (bet === obj["bet"]) bet = 0; if (bet !== 0) ganadores+=`<@${obj["user"]}>\t => ***${bet}*** : [**${motive.join("** | **")}**]\n`; console.log(obj["user"]+" -- BET Total"+ bet); } let embed = new Discord.RichEmbed() .setTitle("RULETA!") .addField("RESULTADOS", msg) .addField("GANADORES", ganadores); await client.channels.get(channel).send(embed); } <file_sep>const Discord = require('discord.js'); const db = require('megadb'); const games = new db.crearDB('games'); const bank = new db.crearDB('bank'); module.exports = { dbGame: async (message) => { if (!games.has(`${message.guild.id}.dbGame`)) await games.set(`${message.guild.id}.dbGame.balls`, { db1: {price: 50000, img: "https://i.ibb.co/bm7HySB/db1.png", icon: "681462632275902509"}, db2: {price: 100000, img: "https://i.ibb.co/8cT7ynY/db2.png", icon: "681462674135318550"}, db3: {price: 50000, img: "https://i.ibb.co/NCSRWW5/db3.png", icon: "681462730321952804"}, db4: {price: 200000, img: "https://i.ibb.co/0M0qBs3/db4.png", icon: "681462750601674782"}, db5: {price: 50000, img: "https://i.ibb.co/cczZtng/db5.png", icon: "681462767449800745"}, db6: {price: 100000, img: "https://i.ibb.co/3m1nMPW/db6.png", icon: "681462782587437067"}, db7: {price: 50000, img: "https://i.ibb.co/M6VxRdC/db7.png", icon: "681462799708586024"} }); if (!games.has(`${message.guild.id}.dbGame.time`) || await games.get(`${message.guild.id}.dbGame.time`) > Date.now()) { await games.set(`${message.guild.id}.dbGame.time`, Date.now() + Math.floor(Math.random() * 3600000 + 3600000)); let moneda = await bank.get(`${message.guild.id}.moneda`); let numBall = Math.floor(Math.random() * 7 + 1); let ball = await games.get(`${message.guild.id}.dbGame.balls.db${numBall}`); let embed = new Discord.RichEmbed() .setTitle('DRAGON BALLS') .setColor('#ffbf0f') .setDescription("Precio: " + ball["price"] + " " + moneda) .setImage(ball["img"]); await message.channels.get("#").send(embed).then(async m => { let balls = await games.get(`${message.guild.id}.dbGame.balls`); for (let b of balls) { m.react(b["icon"]); } const filter = (reaction) => { return reaction.emoji.id === ball["icon"] }; await m.awaitReactions(filter, { max:1, time:60000 }) .then(coll => { }) }); } } };
d714147509687b2ae28573d0693fd56a376885e4
[ "JavaScript" ]
4
JavaScript
AlguienSama/random
20ecea70a124fdcf0dd16dcff19c958c837c46e8
fa740436348d25cad27173aee90e815ed400d7b8
refs/heads/master
<file_sep>/* * Copyright (C) Institute of Telematics, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ambientdynamix.contextplugins.sensordrone; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.UUID; import java.util.Map.Entry; import org.ambientdynamix.api.contextplugin.*; import org.ambientdynamix.api.contextplugin.security.PrivacyRiskLevel; import org.ambientdynamix.api.contextplugin.security.SecuredContextInfo; import com.sensorcon.sdhelper.ConnectionBlinker; import com.sensorcon.sensordrone.Drone; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class SensordronePluginRuntime extends ReactiveContextPluginRuntime { private final String TAG = "Sensordrone"; Backend backend; @Override public void start() { /* * Nothing to do, since this is a pull plug-in... we're now waiting for context scan requests. */ Log.i(TAG, "Started!"); } @Override public void stop() { /* * At this point, the plug-in should cancel any ongoing context scans, if there are any. */ Log.i(TAG, "Stopped!"); } @Override public void destroy() { /* * At this point, the plug-in should release any resources. */ Backend.disable(); stop(); Log.i(TAG, "Destroyed!"); } @Override public void updateSettings(ContextPluginSettings settings) { // Not supported } @Override public void handleContextRequest(UUID requestId, String contextInfoType) { Log.i(TAG, "sensordrone context requested "+contextInfoType); if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.light")) { SecuredContextInfo aci= new SecuredContextInfo(new AmbientLightContextInfo(), PrivacyRiskLevel.MEDIUM); sendContextEvent(requestId, aci, 10000); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.temperature")) { SecuredContextInfo aci= new SecuredContextInfo(new AmbientTemperatureContextInfo(), PrivacyRiskLevel.MEDIUM); sendContextEvent(requestId, aci, 120000); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.carbonmonoxide")) { SecuredContextInfo aci= new SecuredContextInfo(new AmbientCarbonMonoxideContextInfo(), PrivacyRiskLevel.MEDIUM); sendContextEvent(requestId, aci, 10000); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.action.device.identification")) { IdentificationContextAction aci = new IdentificationContextAction(); aci.identify(""); } } @Override public void handleConfiguredContextRequest(UUID requestId, String contextInfoType, Bundle scanConfig) { Log.i(TAG, "sensordrone configured context requested "+contextInfoType); if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.light")) { handleContextRequest(requestId, contextInfoType); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.temperature")) { handleContextRequest(requestId, contextInfoType); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.info.environment.carbonmonoxide")) { handleContextRequest(requestId, contextInfoType); } if(contextInfoType.equals("org.ambientdynamix.contextplugins.context.action.device.identification")) { IdentificationContextAction aci = new IdentificationContextAction(); if(scanConfig.containsKey("deviceId")) { aci.identify(scanConfig.getString("deviceId")); } else { handleContextRequest(requestId, contextInfoType); } } } @Override public void init(PowerScheme arg0, ContextPluginSettings settings) throws Exception { Log.i("Sensordrone", "init"); backend = new Backend(this.getSecuredContext()); this.getPluginFacade().setPluginConfiguredStatus(getSessionId(), true); } @Override public void setPowerScheme(PowerScheme arg0) throws Exception { // TODO Auto-generated method stub } }<file_sep>/* * Copyright (C) Institute of Telematics, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ambientdynamix.contextplugins.sensordrone; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map.Entry; import org.ambientdynamix.contextplugins.context.info.environment.ITemperatureContextInfo; import org.ambientdynamix.contextplugins.info.meta.IContextSource; import org.ambientdynamix.contextplugins.info.meta.IDevice; import org.ambientdynamix.contextplugins.info.meta.ISourcedContext; import org.ambientdynamix.contextplugins.info.meta.ILocalizedContext; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import android.widget.LinearLayout; import com.sensorcon.sensordrone.Drone; public class AmbientTemperatureContextInfo implements ITemperatureContextInfo, ISourcedContext, ILocalizedContext { double[] tempvalues= new double[1]; List<IContextSource> sources = new ArrayList<IContextSource>(); public static Parcelable.Creator<AmbientTemperatureContextInfo> CREATOR = new Parcelable.Creator<AmbientTemperatureContextInfo>() { public AmbientTemperatureContextInfo createFromParcel(Parcel in) { return new AmbientTemperatureContextInfo(in); } public AmbientTemperatureContextInfo[] newArray(int size) { return new AmbientTemperatureContextInfo[size]; } }; @Override public String toString() { return this.getClass().getSimpleName(); } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getContextType() */ @Override public String getContextType() { return "org.ambientdynamix.contextplugins.context.info.environment.temperature"; } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getStringRepresentation(java.lang.String) */ @Override public String getStringRepresentation(String format) { String result=""; if (format.equalsIgnoreCase("text/plain")) { for(int i=0; i<tempvalues.length; i++) { result = tempvalues[i]+" "; } } else if (format.equalsIgnoreCase("XML")) { for(int i=0; i<tempvalues.length; i++) { result="<temperature>"+tempvalues[i]+"</temperature>\n"; } } return result; } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getImplementingClassname() */ @Override public String getImplementingClassname() { return this.getClass().getName(); } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getStringRepresentationFormats() */ @Override public Set<String> getStringRepresentationFormats() { Set<String> formats = new HashSet<String>(); formats.add("text/plain"); formats.add("XML"); return formats; }; public AmbientTemperatureContextInfo() { Log.i("Sensordrone", "generate temp context 3"); HashMap<String, Drone> drones = Backend.getDroneList(); if(drones!=null) { Log.i("Sensordrone", "not null"); Set<Entry<String, Drone>> droneset = drones.entrySet(); Log.i("Sensordrone", "..."); Iterator<Entry<String, Drone>> it = droneset.iterator(); Log.i("Sensordrone", "now for the counter"); int counter=0; tempvalues = new double[drones.size()]; sources = new ArrayList<IContextSource>(); while(it.hasNext()) { Drone d = it.next().getValue(); Sensordrone dev = new Sensordrone(d); if(d.isConnected) { Log.i("Sensordrone", d.temperature_Celcius+" °C"); tempvalues[counter]=d.temperature_Celcius; sources.add(dev); } else { tempvalues=new double[1]; tempvalues[counter]=-999.0; sources.add(dev); } counter++; } } } private AmbientTemperatureContextInfo(final Parcel in) { tempvalues = in.createDoubleArray(); in.readList(sources, getClass().getClassLoader()); //TODO: not sure why there is a need to cast? } public IBinder asBinder() { return null; } public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeDoubleArray(tempvalues); out.writeList(sources); } @Override public double[] getCelciusValue() { return tempvalues; } @Override public List<IContextSource> getSources() { return sources; } @Override public double getLatitude() { return 0; //TODO: } @Override public double getLongitude() { return 0;//TODO: } @Override public double getAltitude() { return 0;//TODO: } @Override public void atUIComponentsForLocalizedContext(LinearLayout root) { } } <file_sep>package org.ambientdynamix.contextplugins.context.info.environment; import org.ambientdynamix.api.application.IContextInfo; public interface IHumidityContextInfo extends IContextInfo { public abstract double[] getHumidityValue(); } <file_sep># SensorDrone Plugin Plugin for the Ambient Dynamix Framework wrapping the sensordrone capabilities. Using Ambient Dynamix: http://ambientdynamix.org Using the Dynamix Plugin Builder: https://bitbucket.org/ambientlabs/dynamix-plug-in-builder Using the Sensordrone Library Version 1.1.1 http://developer.sensordrone.com/downloads/ Using Functionality from The Sensordrone Helper Library: https://github.com/MarkRudolph/Sensordrone-Helper Plugin ID: org.ambientdynamix.contextplugins.sensordrone ###Supported Context Type <table> <tr> <td>Context Types</td><td>Privacy Risk Level</td><td>Data Types</td><td>Description</td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.info.environment.light</td><td>MEDIUM</td><td>AmbientLightContextInfo</td><td></td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.info.environment.temperature</td><td>MEDIUM</td><td>AmbientTemperatureContextInfo</td><td></td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.info.environment.carbonmonoxide</td><td>MEDIUM</td><td>AmbientCarbonMonoxideContextInfo</td><td></td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.info.environment.humidity</td><td>MEDIUM</td><td>AmbientHumidityContextInfo</td><td></td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.info.environment.pressure</td><td>MEDIUM</td><td>AmbientPressureContextInfo</td><td></td> </tr> <tr> <td>org.ambientdynamix.contextplugins.context.action.device.identification</td><td>MEDIUM</td><td>IdentificationContextAction</td><td></td> </tr> <tr> </table> ###Use Add context support as follows: ```Java dynamix.addContextSupport(dynamixCallback, "org.ambientdynamix.contextplugins.context.info.environment.temperature"); ``` ###Native App Usage #### Additionaly Lolcommits enabled. https://github.com/mroth/lolcommits <file_sep>source.. = bin/classes/ bin.includes = META-INF/,\ .,\ bin/,\ assets/,\ lib/sdadnroidlibnew.jar bin.excludes = *.apk, *.ap_, res/<file_sep>/* * Copyright (C) Institute of Telematics, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ambientdynamix.contextplugins.sensordrone; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; import org.ambientdynamix.api.contextplugin.ContextPluginRuntime; import org.ambientdynamix.api.contextplugin.IContextPluginConfigurationViewFactory; import com.sensorcon.sensordrone.Drone; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; public class SensorDronePluginConfigurationActivity extends Activity implements IContextPluginConfigurationViewFactory { LinearLayout rootLayout; LinearLayout listLayout; private static final String TAG = "Sensordrone"; private Context ctx; @Override public void destroyView() throws Exception { // TODO Auto-generated method stub //Backend.disable(); } @Override public View initializeView(final Context context, ContextPluginRuntime arg1, int arg2) throws Exception { Log.i("Sensordrone", "initialize Views 6"); ctx=context; // Discover our screen size for proper formatting DisplayMetrics met = context.getResources().getDisplayMetrics(); // Access our Locale via the incoming context's resource configuration to determine language String language = context.getResources().getConfiguration().locale.getDisplayLanguage(); final TextView searching = new TextView(ctx); searching.setText(""); searching.setText("scanning..."); // Main layout. rootLayout = new LinearLayout(context); rootLayout.setOrientation(LinearLayout.VERTICAL); Button updatebutton = new Button(context); updatebutton.setText("Update List"); updatebutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i("Sensordrone", "pressed the button 6c"); updateListView(); Backend.identifiy("B8:FF:FE:B9:F1:67"); } }); Log.i("Sensordrone", "now to the list b"); listLayout = new LinearLayout(context); listLayout.setOrientation(LinearLayout.VERTICAL); final Button b2 = new Button(context); if(Backend.isRunning()) { b2.setText("Stop Scanning"); } else { b2.setText("Start Scanning"); } b2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(Backend.isRunning()) { Log.i("Sensordrone", "pressed the button 5b"); searching.setText(""); Backend.disable(); b2.setText("Start Scanning"); } else { Backend backend = new Backend(ctx); Log.i("Sensordrone", "pressed the button 6"); searching.setText("scanning..."); b2.setText("Stop Scanning"); } } }); //Header TextView header = new TextView(context); header.setText("Sensordrone Plugin Configuration"); //Add Header rootLayout.addView(header, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); //updateButton rootLayout.addView(updatebutton, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); //add drone 1 textview rootLayout.addView(listLayout, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); rootLayout.addView(searching, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); rootLayout.addView(b2, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); //Hier müsste dann UI von Plugins kommen... und das wiederum ist auch eher murks... return rootLayout; } private void updateListView() { HashMap<String, Drone> drones = Backend.getDroneList(); Set<Entry<String, Drone>> droneset = drones.entrySet(); Iterator<Entry<String, Drone>> it = droneset.iterator(); int counter = 0; listLayout.removeAllViews(); while(it.hasNext()) { Entry<String, Drone> dentry = it.next(); Drone d = dentry.getValue(); TextView tv = new TextView(ctx); tv.setText((counter+1)+": "+d.lastMAC); tv.setBackgroundColor(0x0fff0000); tv.setTextSize(20); TextView v1 = new TextView(ctx); v1.setText(" "+d.temperature_Celcius+" °C"); TextView v2 = new TextView(ctx); v2.setText(" "+d.pressure_Pascals+" Pa"); TextView v3 = new TextView(ctx); v3.setText(" "+d.rgbcLux+" lux"); TextView v4 = new TextView(ctx); v4.setText(" "+d.humidity_Percent+" %"); listLayout.addView(tv, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); listLayout.addView(v1, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); listLayout.addView(v2, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); listLayout.addView(v3, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); listLayout.addView(v4, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); } } } <file_sep>/* * Copyright (C) Institute of Telematics, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ambientdynamix.contextplugins.sensordrone; import java.util.ArrayList; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.util.Log; import com.sensorcon.sensordrone.Drone.DroneEventListener; import com.sensorcon.sensordrone.Drone.DroneStatusListener; import com.sensorcon.sdhelper.ConnectionBlinker; import com.sensorcon.sdhelper.SDStreamer; import com.sensorcon.sensordrone.Drone; public class Backend { private static final String TAG = "Sensordrone"; private static HashMap<String, Drone> drones; //the Sensordrone private static HashMap<String, ConnectionBlinker> blinkerarray; private static HashMap<String, ArrayList<SDStreamer>> streamers; private BroadcastReceiver mBluetoothReceiver; private BluetoothAdapter mBluetoothAdapter; private IntentFilter btFilter; Context ctx; private static boolean running=false; int[] sensortypes; private static int FREQ = 60000; public Backend(Context context) { ctx = context; running=true; Log.i(TAG, "starting backend process"); drones = new HashMap<String, Drone>(); streamers = new HashMap<String, ArrayList<SDStreamer>>(); blinkerarray = new HashMap<String, ConnectionBlinker>(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!mBluetoothAdapter.isEnabled()) { Log.i(TAG, "Bluetooth was off, will now be turned on"); mBluetoothAdapter.enable(); try { Thread.sleep(2000);//so that its on by the time we go to scanning... there might be other, better ways of doing this. probably. } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { //is enabled } if(running) { scanToConnect(); Thread t1 = new Thread( new BackendRunner()); t1.start(); } } //This is addapted from the SDHelper Library public void scanToConnect() { // Is Bluetooth on? if (!mBluetoothAdapter.isEnabled()) { // Don't proceed until the user turns Bluetooth on. Log.i(TAG, "wasn't on..."); try { Thread.sleep(1000);//so that its on by the time we go to scanning... there might be other, better ways of doing this. probably. } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } scanToConnect(); return; } mBluetoothReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { Log.i(TAG, "found Bloutooth Device"); String action = arg1.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = arg1.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.i(TAG, "name="+device.getName()); Log.i(TAG, "deviceClass="+device.getBluetoothClass()); Log.i(TAG, "BondState="+device.getBondState()); Log.i(TAG, "Adress="+device.getAddress()); Log.i(TAG, "HAShCode="+device.hashCode()); Log.i(TAG, "toString="+device.toString()); if(device.getName().contains("Sensordrone")) { if(drones.containsKey(device.getAddress())) { //the device is already in the hashmap } else { addDroneToTheRaster(device); } mBluetoothAdapter.cancelDiscovery(); ctx.unregisterReceiver(mBluetoothReceiver); } } } }; Log.i(TAG, "ok"); btFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); ctx.registerReceiver(mBluetoothReceiver, btFilter); mBluetoothAdapter.startDiscovery(); } private void addDroneToTheRaster(BluetoothDevice device) { Log.i(TAG, "addtoRaster"); final Drone drone = new Drone(); Log.i(TAG, "create Drone object"); drones.put(device.getAddress(), drone); Log.i(TAG, "connection Blinker"); blinkerarray.put(device.getAddress(), new ConnectionBlinker(drone, 1000, 0, 0, 255)); Log.i(TAG, "streamer array erzeugen"); ArrayList<SDStreamer> streamerArray = new ArrayList<SDStreamer>(); Log.i(TAG, "das array fuellen"); sensortypes = new int[] { drone.QS_TYPE_TEMPERATURE, drone.QS_TYPE_HUMIDITY, drone.QS_TYPE_PRESSURE, drone.QS_TYPE_IR_TEMPERATURE, drone.QS_TYPE_RGBC, drone.QS_TYPE_PRECISION_GAS, drone.QS_TYPE_CAPACITANCE, drone.QS_TYPE_ADC, drone.QS_TYPE_ALTITUDE }; Log.i(TAG, "und nu for-schleife"); for(int i=0; i<sensortypes.length; i++) { Log.i(TAG, "->"); streamerArray.add(new SDStreamer(drone, sensortypes[i])); } Log.i(TAG, "and into the streamers hashmap"); streamers.put(device.getAddress(), streamerArray); Log.i(TAG, "so far so good"); DroneStatusListener dsListener = new DroneStatusListener() { @Override public void adcStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void altitudeStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void batteryVoltageStatus(EventObject arg0) { Log.i(TAG, "sensordrone battery voltage status event "+drone.batteryVoltage_Volts); } @Override public void capacitanceStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void chargingStatus(EventObject arg0) { Log.i(TAG, "sensordrone charging status"); // TODO Auto-generated method stub } @Override public void customStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void humidityStatus(EventObject arg0) { Log.i(TAG, "sensordrone humidity status"); //Log.i(TAG, "sensordrone Temperature "+drone.lastMAC+" "+drone.temperature_Celcius); if(drone.humidityStatus) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(1); s.run(); } } @Override public void irStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void lowBatteryStatus(EventObject arg0) { Log.i(TAG, "sensordrone low battery status"); // TODO Auto-generated method stub } @Override public void oxidizingGasStatus(EventObject arg0) { Log.i(TAG, "sensordrone oxydising gas status"); // TODO Auto-generated method stub } @Override public void precisionGasStatus(EventObject arg0) { Log.i(TAG, "sensordrone precisionGas status"); Log.i(TAG, "sensordrone precisionGas ppm Carbon Monoxide "+drone.precisionGas_ppmCarbonMonoxide); // TODO Auto-generated method stub } @Override public void pressureStatus(EventObject arg0) { Log.i(TAG, "sensordrone prssure status"); if(drone.pressureStatus) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(2); s.run(); } } @Override public void reducingGasStatus(EventObject arg0) { // TODO Auto-generated method stub } @Override public void rgbcStatus(EventObject arg0) { Log.i(TAG, "sensordrone rgbc status"); // TODO Auto-generated method stub if(drone.rgbcStatus) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(4); s.run(); } } @Override public void temperatureStatus(EventObject arg0) { Log.i(TAG, "sensordrone temp status"); //Log.i(TAG, "sensordrone Temperature "+drone.lastMAC+" "+drone.temperature_Celcius); if(drone.temperatureStatus) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(0); s.run(); } } @Override public void unknownStatus(EventObject arg0) { // TODO Auto-generated method stub } }; DroneEventListener deListener = new DroneEventListener() { @Override public void adcMeasured(EventObject arg0) { // TODO Auto-generated method stub } @Override public void altitudeMeasured(EventObject arg0) { // TODO Auto-generated method stub } @Override public void capacitanceMeasured(EventObject arg0) { // TODO Auto-generated method stub } @Override public void connectEvent(EventObject arg0) { Log.i(TAG, "sensordrone connection event"); drone.enableTemperature(); //drone.quickEnable(drone.QS_TYPE_TEMPERATURE); drone.measureTemperature(); drone.enablePressure(); //drone.quickEnable(drone.QS_TYPE_PRESSURE); drone.measurePressure(); drone.enableRGBC(); //drone.quickEnable(drone.QS_TYPE_RGBC); drone.measureRGBC(); drone.enableHumidity(); //drone.quickEnable(drone.QS_TYPE_HUMIDITY); drone.measureHumidity(); drone.enableADC(); //drone.quickEnable(drone.QS_TYPE_ADC); drone.measureExternalADC(); blinkerarray.get(drone.lastMAC).enable(); blinkerarray.get(drone.lastMAC).run(); ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); for(int i=0; i<sensortypes.length; i++) { sarray.get(i).enable(); } } @Override public void connectionLostEvent(EventObject arg0) { Log.i(TAG, "sensordrone connection lost event"); //disable temperature drone.disableTemperature(); drone.quickDisable(drone.QS_TYPE_TEMPERATURE); drone.disablePressure(); drone.quickDisable(drone.QS_TYPE_PRESSURE); drone.disableRGBC(); drone.quickDisable(drone.QS_TYPE_RGBC); drone.disableHumidity(); drone.quickDisable(drone.QS_TYPE_HUMIDITY); drone.disableADC(); drone.quickDisable(drone.QS_TYPE_ADC); blinkerarray.get(drone.lastMAC).disable(); blinkerarray.put(drone.lastMAC, new ConnectionBlinker(drone, 1000, 0, 0, 000)); blinkerarray.get(drone.lastMAC).enable(); blinkerarray.get(drone.lastMAC).run(); blinkerarray.get(drone.lastMAC).disable(); ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); for(int i=0; i<sensortypes.length; i++) { sarray.get(i).disable(); } } @Override public void customEvent(EventObject arg0) { // TODO Auto-generated method stub } @Override public void disconnectEvent(EventObject arg0) { Log.i(TAG, "sensordrone disconnect lost event"); drone.disableTemperature(); drone.quickDisable(drone.QS_TYPE_TEMPERATURE); drone.disablePressure(); drone.quickDisable(drone.QS_TYPE_PRESSURE); drone.disableRGBC(); drone.quickDisable(drone.QS_TYPE_RGBC); drone.disableHumidity(); drone.quickDisable(drone.QS_TYPE_HUMIDITY); drone.disableADC(); drone.quickDisable(drone.QS_TYPE_ADC); blinkerarray.get(drone.lastMAC).disable(); blinkerarray.put(drone.lastMAC, new ConnectionBlinker(drone, 1000, 0, 0, 000)); blinkerarray.get(drone.lastMAC).enable(); blinkerarray.get(drone.lastMAC).run(); blinkerarray.get(drone.lastMAC).disable(); ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); for(int i=0; i<sensortypes.length; i++) { sarray.get(i).disable(); } } @Override public void humidityMeasured(EventObject arg0) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(1); s.streamHandler.postDelayed(s, FREQ); Log.i(TAG, "sensordrone Humidity % "+drone.humidity_Percent); } @Override public void i2cRead(EventObject arg0) { // TODO Auto-generated method stub } @Override public void irTemperatureMeasured(EventObject arg0) { Log.i(TAG, "sensordrone ir temp"); } @Override public void oxidizingGasMeasured(EventObject arg0) { // TODO Auto-generated method stub } @Override public void precisionGasMeasured(EventObject arg0) { Log.i(TAG, "sensordrone precisionGas measured"); Log.i(TAG, "sensordrone precisionGas ppm Carbon Monoxide "+drone.precisionGas_ppmCarbonMonoxide); } @Override public void pressureMeasured(EventObject arg0) { ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(2); s.streamHandler.postDelayed(s, FREQ); Log.i(TAG, "sensordrone pressure level in Pa "+drone.pressure_Pascals); } @Override public void reducingGasMeasured(EventObject arg0) { Log.i(TAG, "sensordrone reducingGas measured"); } @Override public void rgbcMeasured(EventObject arg0) { // TODO Auto-generated method stub ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(4); s.streamHandler.postDelayed(s, FREQ); Log.i(TAG, "sensordrone lux "+drone.rgbcLux); } @Override public void temperatureMeasured(EventObject arg0) { Log.i(TAG, "sensordrone temp measured"); Log.i(TAG, "sensordrone Temperature "+drone.lastMAC+" "+drone.temperature_Celcius); ArrayList<SDStreamer> sarray =streamers.get(""+drone.lastMAC); SDStreamer s = sarray.get(0); s.streamHandler.postDelayed(s, FREQ); } @Override public void uartRead(EventObject arg0) { // TODO Auto-generated method stub } @Override public void unknown(EventObject arg0) { // TODO Auto-generated method stub } @Override public void usbUartRead(EventObject arg0) { // TODO Auto-generated method stub } }; drone.registerDroneEventListener(deListener); drone.registerDroneStatusListener(dsListener); } class BackendRunner implements Runnable { private Handler handler = new Handler(); private int delay=10000; long counter=0; @Override public void run() { Log.i(TAG, "drones size"+drones.size()); //TODO: Try to connect counter++; if(!running) { handler.removeCallbacks(this); return; } if(counter%10==0 && counter>0) { mBluetoothAdapter.startDiscovery(); } if(counter%120==0 && counter>0 && !(counter%10==0)) { mBluetoothAdapter.cancelDiscovery(); } Set<Entry<String, Drone>> droneset = drones.entrySet(); Iterator<Entry<String, Drone>> it = droneset.iterator(); Set<BluetoothDevice> bondeddevices = mBluetoothAdapter.getBondedDevices(); while(it.hasNext()) { Entry<String, Drone> dentry = it.next(); Drone d = dentry.getValue(); if(!d.isConnected) { if(!d.btConnect(dentry.getKey())) { Log.i(TAG, "could not connect"); } else { } } else { //TODO: the device-representation is connected, however, it may have gotten out of range and that may not be known or something, so we better check in the list of bonded devices Iterator<BluetoothDevice> bit = bondeddevices.iterator(); boolean actuallyconnected=false; while(bit.hasNext()) { BluetoothDevice div = bit.next(); if(div.getAddress().equals(dentry.getKey())) { //the adress of this device was actually in the list actuallyconnected=true; } } if(!actuallyconnected)//it wasn't found under the bonded divices. { d.disconnect(); } } Log.i(TAG, "is it connected? "+d.isConnected); } handler.removeCallbacks(this); // remove the old callback if(running) { handler.postDelayed(this, delay); // register a new one } } public void onResume() { handler.postDelayed(this, delay); } public void onPause() { handler.removeCallbacks(this); // stop the map from updating } } public static void disable() { Log.i(TAG, "Disable the runner"); Set<Entry<String, Drone>> droneset = drones.entrySet(); Log.i(TAG, "a"); Iterator<Entry<String, Drone>> it = droneset.iterator(); Log.i(TAG, "b"); running=false; while(it.hasNext()) { Log.i(TAG, "c"); Entry<String, Drone> dentry = it.next(); Log.i(TAG, "d"); Drone d = dentry.getValue(); Log.i(TAG, "e"); d.disconnect(); Log.i(TAG, "f"); Log.i(TAG, "is it connected? "+d.isConnected); Log.i(TAG, "g"); } } public static HashMap<String, Drone> getDroneList() { return drones; } public static boolean isRunning() { return running; } public static void identifiy(String id) { Log.i(TAG, "identify"); blinking(150, 1250, 255, 0, 0, id); } public static void blinking(int delay, int duration, int r, int g, int b, String drone) { HashMap<String, Drone> drones = Backend.getDroneList(); Set<Entry<String, Drone>> droneset = drones.entrySet(); Iterator<Entry<String, Drone>> it = droneset.iterator(); while(it.hasNext()) { Drone d = it.next().getValue(); if(d.lastMAC.equals(drone)|| drone.equals("")) { Log.i(TAG, "found "+drone); ConnectionBlinker cb = blinkerarray.get(d.lastMAC); cb.setColors(r, g, b); cb.setRate(delay); cb.enable(); cb.run(); try { Thread.sleep(duration); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } cb.disable(); cb.setColors(0, 0, 255); cb.setRate(10000); cb.enable(); cb.run(); } } } } <file_sep>package org.ambientdynamix.contextplugins.context.info.environment; import org.ambientdynamix.api.application.IContextInfo; public interface IBluetoothDevicesContextInfo extends IContextInfo{ } <file_sep>/* * Copyright (C) Institute of Telematics, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ambientdynamix.contextplugins.sensordrone; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; import org.ambientdynamix.api.application.IContextInfo; import org.ambientdynamix.contextplugins.context.info.environment.ILightContextInfo; import com.sensorcon.sensordrone.Drone; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; class AmbientLightContextInfo implements ILightContextInfo { double[] lightvalues= new double[1]; double[] redvalues = new double[1]; double[] greenvalues = new double[1]; double[] bluevalues = new double[1]; public static Parcelable.Creator<AmbientLightContextInfo> CREATOR = new Parcelable.Creator<AmbientLightContextInfo>() { public AmbientLightContextInfo createFromParcel(Parcel in) { return new AmbientLightContextInfo(in); } public AmbientLightContextInfo[] newArray(int size) { return new AmbientLightContextInfo[size]; } }; @Override public String toString() { return this.getClass().getSimpleName(); } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getContextType() */ @Override public String getContextType() { return "org.ambientdynamix.contextplugins.context.info.environment.light"; } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getStringRepresentation(java.lang.String) */ @Override public String getStringRepresentation(String format) { String result=""; for(int i=0; i<lightvalues.length; i++) { result=result+lightvalues[i]+" "; } if (format.equalsIgnoreCase("text/plain")) return result; else return null; } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getImplementingClassname() */ @Override public String getImplementingClassname() { return this.getClass().getName(); } /* (non-Javadoc) * @see org.ambientdynamix.contextplugins.ambientsound.IAmbientSoundContextInfo#getStringRepresentationFormats() */ @Override public Set<String> getStringRepresentationFormats() { Set<String> formats = new HashSet<String>(); formats.add("text/plain"); return formats; } public AmbientLightContextInfo() { Log.i("Sensordrone", "generate temp context 3"); HashMap<String, Drone> drones = Backend.getDroneList(); if(drones!=null) { Log.i("Sensordrone", "not null"); Set<Entry<String, Drone>> droneset = drones.entrySet(); Log.i("Sensordrone", "..."); Iterator<Entry<String, Drone>> it = droneset.iterator(); Log.i("Sensordrone", "now for the counter"); int counter=0; lightvalues = new double[drones.size()]; redvalues = new double[drones.size()]; greenvalues = new double[drones.size()]; bluevalues = new double[drones.size()]; while(it.hasNext()) { Drone d = it.next().getValue(); if(d.isConnected) { Log.i("Sensordrone", d.temperature_Celcius+" °C"); lightvalues[counter]=d.rgbcLux; redvalues[counter]=d.rgbcRedChannel; greenvalues[counter]=d.rgbcGreenChannel; bluevalues[counter]=d.rgbcBlueChannel; } else { lightvalues=new double[1]; lightvalues[counter]=-999.0; redvalues[counter]=-999.0; greenvalues[counter]=-999.0; bluevalues[counter]=-999.0; } counter++; } } } private AmbientLightContextInfo(final Parcel in) { lightvalues = in.createDoubleArray(); } public IBinder asBinder() { return null; } public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeDoubleArray(getLuxValue()); } @Override public double[] getLuxValue() { return lightvalues; } @Override public double[] getRedLevelValue() { return redvalues; } @Override public double[] getGreenLevelValue() { return greenvalues; } @Override public double[] getBlueLevelValue() { return bluevalues; } }
004fe60fd3c17f78ac6dba0482f1938ad7360d8a
[ "Markdown", "Java", "INI" ]
9
Java
TVLuke/SensorDroneDynamixPlugin
06bb69a38a6dd46ba0c984ec06d4ff75427265e9
42e9743036abe0e2141e7dbe83480ed7bc59d447
refs/heads/main
<file_sep># project-pairs-jihed-ines<file_sep> $(document).ready(function(){ $(".loginbox").hide(); $("#btn").on("click",function(e){ e.preventDefault(); var name=$("#name").val(); var pass=$("#pw").val(); localStorage.setItem("name",name); localStorage.setItem("pass",pass); //redairact to the login $(".loginbox1").hide(); $(".loginbox").show(); }) //check and login $("#btn1").click(function(check){ check.preventDefault(); var entername=$("#name1").val(); var enterpass=$("#pass1").val(); var checkname=localStorage.getItem("name"); var checkpass=localStorage.getItem("pass"); if (entername!==checkname || enterpass!==checkpass) { alert("password or userName wrong") }else{ window.location.href="../index1.html" } }); }) <file_sep>jQuery(document).ready(function($){ $('.wheel-with-image').superWheel({ slices: [ { text: 'images/walk.png', value: 1, message: "You can watch the Walking Dead for free", background: "white", }, { text: 'images/Casa.png', value: 1, message:"You can watch La Casa de Papel for free" , background: "black", }, { text: 'images/harry.png', value: 1, message: "You can watch harry Potter for free", background: "white", }, { text: 'images/AVGD.png', value: 1, message: "You can watch the Avengers for free", background: "black", }, { text: 'images/john.png', value: 1, message: "You can watch <NAME> for free", background: "white", }, { text: 'images/5.png', value: 1, message: "You can watch Fast & Furious for free", background: "black", } ], text : { type: 'image', color: 'You win reduction on this item', size: 25, offset : 10, orientation: 'h' }, line: { width: 10, color: "#78909C" }, inner: { width: 15, color: "black" }, marker: { background: "black", animate: 1 }, selector: "value", }); var tick = new Audio('media/tick.mp3'); $(document).on('click','.wheel-with-image-spin-button',function(e){ $('.wheel-with-image').superWheel('start','value',1); $(this).prop('disabled',true); }); $('.wheel-with-image').superWheel('onStart',function(results){ $('.wheel-with-image-spin-button').text('Spinning...'); }); $('.wheel-with-image').superWheel('onStep',function(results){ if (typeof tick.currentTime !== 'undefined') tick.currentTime = 0; tick.play(); }); $('.wheel-with-image').superWheel('onComplete',function(results){ if(results.value === 1){ swal({ type: 'success', title: "Congratulations!", html: results.message }); }else{ swal("Oops!", results.message, "error"); } $('.wheel-with-image-spin-button:disabled').prop('disabled',false).text('Spin'); }); $("#btn").click(function(){ location.href="../index1.html" }) });
9e950f2ccb4e0e3e010694bdace3cdc5b0b78157
[ "Markdown", "JavaScript" ]
3
Markdown
Iness-Jihed/project-pairs-jihed-ines
334744b65a3d85720b903383b20deba0f1c9f8fb
b09ed8a679e0c702ad6bb6701eedd0822bce98e1
refs/heads/master
<file_sep># Yummy ## 网页版饿了吗 ### 技术栈 #### html+js+css #### springboot+mysql+jpa<file_sep>package com.dao; import com.model.Customer; import com.util.ResultMessage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface CustomerDao extends JpaRepository<Customer, String> { @Query(value = "select c from Customer c where c.email=:email") Customer find(@Param(value = "email") String email); @Modifying @Query(value = "update Customer c set c.state='Valid' where c.activecode=:code and c.state='WaitToActive'") int activeUser(@Param("code")String code); @Modifying @Query(value = "update Customer c set c.password=:newPass where c.email=:email and c.state='Valid'") int resetPassword(@Param("email")String email,@Param("newPass")String newPass); @Modifying @Query(value = "update Customer c set c.name=:newName where c.email=:username") int resetName(@Param("username")String username,@Param("newName")String newName); @Modifying @Query(value = "update Customer c set c.telephone=:newTel where c.email=:username") int resetTel(@Param("username")String username,@Param("newTel")String newTel); @Modifying @Query(value = "update Customer c set c.state='CloseAccount' where c.email=:username") int closeAccount(@Param("username")String username); @Modifying @Query(value = "update Customer c set c.level=:level where c.email=:username") void updateLevel(@Param("username")String username,@Param("level")int level); @Query(value = "select count(c) from Customer c where c.level=?1 and c.state='Valid'") int countCustomersOnLevel(int level); @Query(value = "select count (c) from Customer c where c.state='CloseAccount'") int countInValidCustomer(); } <file_sep>package com.bl; import com.blservice.StatisticsBLService; import com.dao.CustomerDao; import com.dao.OrderDao; import com.dao.StoreDao; import com.model.Orders; import com.util.StoreType; import com.view.CustomerView; import com.vo.AdminStatistics; import com.vo.CustomerStatistics; import com.vo.StoreStatistics; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import static com.util.StoreType.*; @Service public class StatisticsBL implements StatisticsBLService { @Autowired private OrderDao orderDao; @Autowired private CustomerDao customerDao; @Autowired private StoreDao storeDao; private StoreType[] types={ HotFood, FruitAndVegetable, //果蔬生鲜 Market,//商店超市 FlowerAndPlant,//鲜花绿植 HealthAndMedicine,//医药健康 Other }; @Override public CustomerStatistics getCustomerStatistics(String customer) { List<CustomerView> views=orderDao.getCustomerViews(customer); int completeNums=0,cancelNums=0,compensateNums=0; double completeCost=0, compensateCost=0; int[] orderNumsPerCost={0,0,0,0};//<=20, 20<x<=30, 30<x<=40, >40 //不同类型店铺的消费 食物/超市/…… int[] ordersNumPerStoreType={0,0,0,0,0,0}; CustomerStatistics statistics=new CustomerStatistics(); for(CustomerView view:views){ switch (view.getState()){ case Over: completeNums++; completeCost+=view.getMoney(); break; case CancelBeforeAccept: cancelNums++; break; case CancelAfterAccept: compensateNums++; compensateCost+=view.getMoney(); break; default: break; } double money=view.getMoney(); if(money<=20){ orderNumsPerCost[0]++; }else if(money<=30){ orderNumsPerCost[1]++; }else if(money<=40){ orderNumsPerCost[2]++; }else{ orderNumsPerCost[3]++; } int index=0; for(int i=0;i<types.length;i++){ if(types[i]==view.getStoreType()){ index=i; break; } } ordersNumPerStoreType[index]++; } statistics.setOverOrdersNum(completeNums); statistics.setCancelOrdersNum(cancelNums); statistics.setCancelPayNum(compensateNums); statistics.setOverOrdersConsume(completeCost); statistics.setPayForCancelOrders(compensateCost*0.3); statistics.setOrderNumsPerPrice(orderNumsPerCost); statistics.setOrdersNumPerStoreType(ordersNumPerStoreType); return statistics; } @Override public StoreStatistics getStoreStatistics(String store_id) { List<Orders> orders=orderDao.getAllOrders(store_id); int completeOrderNums=0,refuseOrderNums=0,cancelBeforeAcceptNums=0,cancelAfterAcceptNum=0; double completeIncome=0;//抽成前收益 double compensate=0;//抽成前赔付 int[] timeLines={8, 11, 15, 19, 22}; // 8:00-11:00 11:00-15:00 15:00-19:00 19:00-22:00 int[] orderTime={0, 0, 0, 0};//点餐时间段 int[] costLine={20,30,40,50}; //<20 20-30 30-40 40-50 >50 int[] orderCost={0, 0, 0, 0, 0};//订单的消费金额分布 //真正完成的 接单后取消的 接单前取消的 被拒单的 // int[] customerNums={0,0,0,0};//在本餐厅消费过的会员数 ArrayList<String> over=new ArrayList<>(); ArrayList<String> after=new ArrayList<>(); ArrayList<String> before=new ArrayList<>(); ArrayList<String> refuse=new ArrayList<>(); String c; for(Orders order:orders){ c=order.getCustomer(); switch (order.getState()){ case Over: completeOrderNums++; completeIncome+=order.getMoney(); if(!over.contains(c)){ over.add(c); } break; case Refuse: refuseOrderNums++; if(!refuse.contains(c)){ refuse.add(c); } break; case CancelBeforeAccept: cancelBeforeAcceptNums++; if(!before.contains(c)){ before.add(c); } break; case CancelAfterAccept: cancelAfterAcceptNum++; compensate+=order.getMoney(); if(!after.contains(c)){ after.add(c); } break; default: break; } Calendar calendar=Calendar.getInstance(); calendar.setTime(order.getDate()); int hour=calendar.get(Calendar.HOUR_OF_DAY); for(int i=0;i<timeLines.length-1;i++){ if((hour>=timeLines[i])&&(hour<timeLines[i+1])){ orderTime[i]++; break; } } int j; for( j=0;j<costLine.length;j++){ if(order.getMoney()<=costLine[j]){ break; } } orderCost[j]++; } int[] customerNums={over.size(), after.size(), before.size(), refuse.size()}; StoreStatistics statistics=new StoreStatistics(); statistics.setCompleteOrderNums(completeOrderNums); statistics.setCancelAfterAcceptNums(cancelAfterAcceptNum); statistics.setCancelBeforeAcceptNums(cancelBeforeAcceptNums); statistics.setRefuseOrderNums(refuseOrderNums); statistics.setCompleteIncome(completeIncome); statistics.setCompensate(compensate); statistics.setOrderCost(orderCost); statistics.setOrderTime(orderTime); statistics.setCustomerNums(customerNums); return statistics; } @Override public AdminStatistics getAdminStatistics() { int validCustomer=0;//正在使用的用户 int inValidCustomer=0;//已注销的用户 //0--5级 int[] levels={0, 0, 0, 0 ,0 ,0};//不同等级的用户比例 int tmp; for(int i=0;i<6;i++){ tmp=customerDao.countCustomersOnLevel(i); levels[i]=tmp; validCustomer+=tmp; } inValidCustomer=customerDao.countInValidCustomer(); int validStore=0;//有效的店铺数 int inValidStore=0;//无效的店铺数 //共6种类型 int[] numsPerType={0,0,0,0,0,0};//各个类型的店铺比例(仅限有效店铺) for(int j=0;j<6;j++){ tmp=storeDao.countStoresByType(types[j]); numsPerType[j]=tmp; validStore+=tmp; } inValidStore=storeDao.countInValidStores(); double part1=orderDao.getSumProfit(); double part2=orderDao.getSumProfitCancel()*0.3; double totalMoney=(part1+part2)*0.15;//总收益 //今年每月收益变化曲线 Calendar calendar=Calendar.getInstance(); Date date; int month=calendar.get(Calendar.MONTH)+1; double[] moneyPerMonth=new double[month];//累积的 for(int k=0;k<month;k++){ calendar.set(Calendar.MONTH,k+1); calendar.set(Calendar.DAY_OF_MONTH,1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0); date=calendar.getTime(); moneyPerMonth[k]=orderDao.calculate(date)*0.15; } AdminStatistics statistics=new AdminStatistics(); statistics.setValidCustomer(validCustomer); statistics.setInValidCustomer(inValidCustomer); statistics.setLevels(levels); statistics.setValidStore(validStore); statistics.setInValidStore(inValidStore); statistics.setTypes(numsPerType); statistics.setTotalMoney(totalMoney); statistics.setMoneyPerMonth(moneyPerMonth); return statistics; } } <file_sep>package com.util; public enum OrderState { WaitToPay,//等待付款 WaitStoreToAccept,//已付款,等待商家接单 WaitToSendOut,//商家已接单,备货中,等待送出 Sending,//配送中 Over,//订单完成,确认收货 CancelBeforeAccept,//商家接单前取消 CancelAfterAccept,//商家接单后取消 Refuse//商家拒接单 } <file_sep>package com.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class AdminStatistics { private int validCustomer;//正在使用的用户 private int inValidCustomer;//已注销的用户 //0--5级 private int[] levels;//不同等级的用户比例 private int validStore;//正在售卖的店铺数 private int inValidStore;//已下架的店铺数 private int[] types;//各个类型的店铺比例 private double totalMoney;//总收益 //今年每月收益变化曲线2019年开始 private double[] moneyPerMonth; } <file_sep>package com.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "address") @NoArgsConstructor @AllArgsConstructor @Data public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String province;//省 private String city;//市 private String area;//区 private String detail;//详细地址 private String telephone;//收货电话 private String name;//收货人 } <file_sep>package com.blservice; import com.model.Good; import com.model.GoodList; import com.model.Store; import com.util.GoodState; import com.util.ResultMessage; import com.util.StoreType; import com.util.UserState; import com.vo.StoreInfo; import com.vo.StoreVO; import java.util.Date; import java.util.List; import java.util.Map; public interface StoreBLService { ResultMessage applyNewStore(String store_id, String store_name, String store_boss, String store_email, String store_pass, StoreType store_type, String province, String city, String area, String detail_address); ResultMessage storeLogin(String username, String password); Store getStoreInfo(String id); void modifyIntroduce(String id, String introduce); ResultMessage modifyPassword(String id, String oldPass, String newPass); ResultMessage modifyStrategy(Map<String,String> strategies); ResultMessage findBackPass(String store_id); List<StoreInfo> getStoreListInSameCity(String cityName); ResultMessage modifyStoreInfo(String store_id, String store_name, StoreType store_type, String store_boss, String contact, String province, String city, String area, String detail_address); Map<String,List<Good>> getStoreGoods(String store_id); Map<Integer,Integer> getStoreStrategies(String store_id); ResultMessage addNewGoodType(String store_id, String newType); Good addNewGood(String store_id, String name, String description, double price, int amount, String type, Date start_time, Date end_time); void deleteGoodType(String store_id, String toDelete); String withdrawGood(String store_id, String good_id); Good findGoodInfoById(long good_id); void modifyGoodInfo(long good_id, String name, String description, double price, int amount, Date start_time, Date end_time); StoreVO getStoreVO(String store_id); /* * 得到库存信息 */ int getStockNum(long good_id); ResultMessage outStock(List<GoodList> lists); ResultMessage inStock(List<GoodList> lists); void updateStoreState(String store_id, UserState state); } <file_sep>package com.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class StoreStatistics { private int completeOrderNums; private int refuseOrderNums; private int cancelBeforeAcceptNums; private int cancelAfterAcceptNums; private double completeIncome;//抽成前收益 private double compensate;//抽成前赔付 //真正完成的 接单后取消的 接单前取消的 被拒单的 private int[] customerNums;//在本餐厅消费过的会员数 //8:00-11 11:00-15:00 15:00-19:00 19:00-22:00 private int[] orderTime;//点餐时间段 //<20 20-30 30-40 40-50 >50 private int[] orderCost;//订单的消费金额分布 }<file_sep>package com.dao; import com.model.Record; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AdminDao extends JpaRepository<Record,Long>{ @Query(value = "select r from Record r where r.state='WaitToCheck' order by r.applyTime desc ") List<Record> getWaitCheckRecords(); @Query(value = "select r from Record r where r.state<>'WaitToCheck' order by r.applyTime desc ") List<Record> getDoneRecords(); } <file_sep>package com.util; public enum StoreType { HotFood,//热制食品类 FruitAndVegetable, //果蔬生鲜 Market,//商店超市 FlowerAndPlant,//鲜花绿植 HealthAndMedicine,//医药健康 Other//其他 } <file_sep>package com.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "list") @Data @NoArgsConstructor @AllArgsConstructor public class GoodList { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private long good_id;//该商品ID private String good_name; private int amount;//该商品数量 private double price;//该商品单价 } <file_sep>package com.model; import com.util.UserState; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; @Entity @Table(name = "customer") @Data @NoArgsConstructor @AllArgsConstructor public class Customer{ @Id private String email; private String password; private String name;//姓名 private int level; private String telephone; @Enumerated(EnumType.STRING) private UserState state;//用户的状态,未激活/生效使用中/已注销 private String activecode;//激活码 @OneToMany(targetEntity = Account.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY) private List<Account> account; @OneToMany(targetEntity = Address.class,cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Address> addresses;//地址列表 }<file_sep>package com.controller; import com.blservice.CustomerBLService; import com.blservice.StatisticsBLService; import com.model.Account; import com.model.Address; import com.util.ResultMessage; import com.vo.CustomerStatistics; import com.vo.CustomerVO; import com.vo.StringVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class CustomerController { @Autowired private CustomerBLService customerBLService; @Autowired private StatisticsBLService statisticsBLService; /** * 普通消费者通过邮箱注册 * @param email 注册使用邮箱账号 * @return 注册结果 */ @RequestMapping(value = "/userSignUp", method = RequestMethod.POST) public @ResponseBody ResultMessage signUpByEmail(String email, String password){ return customerBLService.signUpByEmail(email, password); } /** * 普通用户点击邮箱链接进行验证 * @param code 验证token * @return 是否激活成功 */ @RequestMapping(value = "/active") public String activeUser(String code){ System.out.println("code :" +code); if(customerBLService.activeUser(code)== ResultMessage.SUCCESS){ return "user/activeSuccess"; }else{ return "user/activeError"; } } /* * 激活成功后,完善信息 */ @RequestMapping(value = "/completeInfo", method = RequestMethod.POST) public @ResponseBody ResultMessage completeInfo(String email, String password, String first_name, String telephone, String bank_card){ return customerBLService.firstCompleteInfo(email, password, first_name, telephone, bank_card); } /* * 注销账户 */ @RequestMapping(value = "/closeAccount", method = RequestMethod.POST) public @ResponseBody ResultMessage closeAccount(String username){ return customerBLService.closeAccount(username); } /* * 修改用户名 */ @RequestMapping(value = "/modifyName",method = RequestMethod.POST) public @ResponseBody void modifyName(String username,String newName){ customerBLService.modifyName(username,newName); } /* * 修改联系电话 */ @RequestMapping(value = "/modifyTel",method = RequestMethod.POST) public @ResponseBody void modifyTel(String username,String newTel){ customerBLService.modifyTel(username,newTel); } @RequestMapping(value = "/getCustomerInfo", method = RequestMethod.POST) public @ResponseBody CustomerVO getCustomerInfo(String username){ return customerBLService.getCustomerInfo(username); } @RequestMapping(value = "/getLevel",method = RequestMethod.POST) public @ResponseBody int getUserLevel(String username){ return customerBLService.getCustomerLevel(username); } @RequestMapping(value = "/getAddressList", method = RequestMethod.POST) public @ResponseBody List<Address> getAddressList(String username){ return customerBLService.getAddressList(username); } @RequestMapping(value = "/addNewAddress", method = RequestMethod.POST) public @ResponseBody ResultMessage addNewAddress(String username,String province,String city,String area,String detail,String tel,String name){ return customerBLService.addNewAddress(username,province,city,area,detail,tel,name); } @RequestMapping(value = "/deleteAddress",method = RequestMethod.POST) public @ResponseBody ResultMessage deleteAddress(@RequestBody StringVO list){ return customerBLService.deleteAddress(list.getUsername(),list.getLists()); } @RequestMapping(value = "/getAccountList", method = RequestMethod.POST) public @ResponseBody List<Account> getAccountList(String username){ return customerBLService.getAccountList(username); } @RequestMapping(value = "/addNewAccount", method = RequestMethod.POST) public @ResponseBody ResultMessage addNewAccount(String username,String account){ return customerBLService.addNewAccount(username,account); } @RequestMapping(value = "/deleteAccount",method = RequestMethod.POST) public @ResponseBody ResultMessage deleteAccount(@RequestBody StringVO list){ return customerBLService.deleteAccount(list.getUsername(),list.getLists()); } @RequestMapping(value = "/getCustomerStatistics",method = RequestMethod.POST) public @ResponseBody CustomerStatistics getCustomerStatistics(String username){ return statisticsBLService.getCustomerStatistics(username); } } <file_sep>package com.blservice; import com.model.Orders; import com.util.ResultMessage; import com.vo.OrderInfo; import java.util.List; public interface OrderBLService { String submitNewOrder(OrderInfo orderInfo); List<Orders> getOnOrder(String username); ResultMessage payOrder(String order_id); ResultMessage cancelOrder(String order_id); ResultMessage confirmOrder(String order_id); List<Orders> getHistoryOrders(String username); List<Orders> getStoreNewOrders(String store_id); List<Orders> getStorePreparingOrders(String store_id); List<Orders> getStoreSendOrders(String store_id); List<Orders> getStoreCompleteOrders(String store_id); List<Orders> getStoreCancelOrders(String store_id); ResultMessage acceptOrder(String order_id); ResultMessage sendOutOrder(String order_id); ResultMessage refuseOrder(String order_id); } <file_sep>package com.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.util.GoodState; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "good") @Data @NoArgsConstructor @AllArgsConstructor public class Good { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String description; private double price; private int amount; private String type; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") private Date start_time; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") private Date end_time; @Enumerated(EnumType.STRING) private GoodState state; } <file_sep>package com.dao; import com.model.Orders; import com.view.CustomerView; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface OrderDao extends JpaRepository<Orders,String> { @Query(value = "select o from Orders o where o.customer=:username and o.state<>'CancelBeforeAccept' " + "and o.state<>'Over' and o.state<>'CancelAfterAccept' and o.state<>'Refuse' order by o.date desc") List<Orders> getOnOrder(@Param("username")String username); @Modifying @Query(value = "update Orders o set o.state='WaitStoreToAccept' where o.id=:id") int payOrder(@Param("id")String order_id); @Query(value = "select o from Orders o where o.customer=:username and (o.state='Over' or o.state='CancelAfterAccept'" + "or o.state='CancelBeforeAccept' or o.state='Refuse') order by o.date desc") List<Orders> getHistoryOrders(@Param("username") String username); //店铺查看订单 @Query(value = "select o from Orders o where o.store_id=:store_id and o.state='WaitStoreToAccept' order by o.date desc") List<Orders> getStoreNewOrders(@Param("store_id") String store_id); @Query(value = "select o from Orders o where o.store_id=:store_id and o.state='WaitToSendOut' order by o.date desc ") List<Orders> getStorePreparingOrders(@Param("store_id")String store_id); @Query(value = "select o from Orders o where o.store_id=:store_id and o.state='Sending' order by o.date desc ") List<Orders> getStoreSendOrders(@Param("store_id")String store_id); @Query(value = "select o from Orders o where o.store_id=:store_id and o.state='Over' order by o.date desc ") List<Orders> getStoreCompleteOrders(@Param("store_id")String store_id); @Query(value = "select o from Orders o where o.store_id=:store_id and (o.state='CancelAfterAccept' or o.state='Refuse' or o.state='CancelBeforeAccept') " + "order by o.date desc ") List<Orders> getStoreCancelOrders(@Param("store_id")String store_id); //店铺方操作订单 @Modifying @Query(value = "update Orders o set o.state='WaitToSendOut' where o.id=:id and o.state='WaitStoreToAccept'") int acceptOrder(@Param("id") String order_id); @Modifying @Query(value = "update Orders o set o.state='Sending' where o.id=:id and o.state='WaitToSendOut'") int sendOutOrder(@Param("id")String order_id); @Modifying @Query(value = "update Orders o set o.state='Refuse' where o.id=:id and o.state='WaitStoreToAccept'") int refuseOrder(@Param("id")String order_id); //得到用户的消费数据 @Query(value = "select sum(o.money) from Orders o where o.customer=:customer and o.state='Over'") double getSumConsume(@Param("customer")String customer); @Query(value = "select new com.view.CustomerView(o,s) from Orders o, Store s where o.customer=?1 and o.store_id=s.id") List<CustomerView> getCustomerViews(String customer); //得到店铺的统计数据 @Query(value = "select o from Orders o where o.store_id=?1") List<Orders> getAllOrders(String store_id); @Query(value = "select count(distinct o.customer) from Orders o where o.store_id=?1 and (o.state='Over' or o.state='CancelAfterAccept')") int getCustomerOfStore(String store_id); @Query(value = "select sum(o.money) from Orders o where o.state='Over'") double getSumProfit(); @Query(value = "select sum(o.money) from Orders o where o.state='CancelAfterAccept'") double getSumProfitCancel(); @Query(value = "select sum(o.money) from Orders o where o.state='Over' and o.date<?1") double calculate(Date date); } <file_sep>package com.util; public enum ResultMessage { SUCCESS, FAIL, EXIST, PassError, NotExist, CustomerLogin, StoreLogin, AdminLogin, InValid, ToActive, NoEmail, StockNotEnough, BalanceNotEnough, RefundSuccess,//退款 Cancel,//订单已取消 } <file_sep>package com.util; public enum CheckState { WaitToCheck, Pass, Refuse } <file_sep>package com.util; public enum UserState{ //普通消费者的状态 WaitToActive,//待激活 CloseAccount,//账号已经注销 //平台店铺状态 ToCheck,//待审核状态 ToModify,//店铺信息更改审核中 BeRefused,//审核申请被驳回 Valid//账号正使用中 }
6edd134e0a8faf1c0a3a7ff5f196b4bb2cfb0692
[ "Markdown", "Java" ]
19
Markdown
zhping5678/Yummy
7fbd75547aa3eb7bd23ff23e74c168df0bcff2e6
7a2c47a6efa9bc09ce5bec9a623b3f074111c59d
refs/heads/main
<file_sep>package main import ( "flag" "fmt" "os" "strconv" "text/template" ) type C struct { Organization string Port int Couch int } func main() { count := flag.Int("count", 1, "number of organizations") withDocker := flag.Bool("docker", false, "is docker-compose files needed") flag.Parse() t1, err := template.ParseFiles("crypto-config.yaml") if err != nil { panic("crypto-config.yaml template didn't found") } t2, err := template.ParseFiles("configtx.yaml") if err != nil { panic("configtx.yaml template didn't found") } t3, err := template.ParseFiles("docker-compose.yaml") if err != nil { panic("docker-compose.yaml template didn't found") } t4, err := template.ParseFiles("docker-compose-couch.yaml") if err != nil { panic("docker-compose-couch.yaml template didn't found") } for i := 1; i <= *count; i++ { name := generate(i) fmt.Println(name) c := C{ Organization: name, } f1, err := os.Create(fmt.Sprintf("../../organizations/crypto-config-%s.yaml", name)) if err != nil { panic("cannot create file:" + err.Error()) } defer f1.Close() err = t1.Execute(f1, c) if err != nil { panic(err) } err = os.Mkdir(fmt.Sprintf("../../configtx/%s", name), 0755) if err != nil { panic(err) } f2, err := os.Create(fmt.Sprintf("../../configtx/%s/configtx.yaml", name)) if err != nil { panic("cannot create file:" + err.Error()) } defer f2.Close() p := strconv.Itoa(i+7) + "051" couch := strconv.Itoa(i+3) + "984" c.Port, _ = strconv.Atoi(p) c.Couch, _ = strconv.Atoi(couch) err = t2.Execute(f2, c) if err != nil { panic(err) } if *withDocker { f3, err := os.Create(fmt.Sprintf("../../docker/docker-compose-%s.yaml", name)) if err != nil { panic("cannot create file:" + err.Error()) } err = t3.Execute(f3, c) if err != nil { panic(err) } f4, err := os.Create(fmt.Sprintf("../../docker/docker-compose-couch-%s.yaml", name)) if err != nil { panic("cannot create file:" + err.Error()) } err = t4.Execute(f4, c) if err != nil { panic(err) } } } } func generate(i int) string { return fmt.Sprintf("org%s", strconv.Itoa(i)) } <file_sep>version: '2' volumes: peer0.{{.Organization}}.example.com: networks: net: services: peer-base: image: hyperledger/fabric-peer:$IMAGE_TAG environment: - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_net - FABRIC_LOGGING_SPEC=INFO - CORE_PEER_TLS_ENABLED=true - CORE_PEER_PROFILE_ENABLED=true - CORE_PEER_ADDRESSAUTODETECT=true working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer command: peer node start volumes: - /var/run/:/host/var/run/ peer0.{{.Organization}}.example.com: container_name: peer0.{{.Organization}}.example.com extends: service: peer-base environment: - CORE_PEER_ID=peer0.{{.Organization}}.example.com - CORE_PEER_ADDRESS=peer0.{{.Organization}}.example.com:{{.Port}} - CORE_PEER_LISTENADDRESS=0.0.0.0:{{.Port}} - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.{{.Organization}}.example.com:{{.Port}} - CORE_PEER_LOCALMSPID={{.Organization}} - CORE_CHAINCODE_LOGGING_SHIM=INFO volumes: - ../fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/peers/peer0.{{.Organization}}.example.com/msp:/etc/hyperledger/fabric/msp - ../fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/peers/peer0.{{.Organization}}.example.com/tls:/etc/hyperledger/fabric/tls - peer0.{{.Organization}}.example.com:/var/hyperledger/production ports: - {{.Port}}:{{.Port}} networks: - net cli.{{.Organization}}.example.com: container_name: cli.{{.Organization}}.example.com image: hyperledger/fabric-tools:$IMAGE_TAG tty: true stdin_open: true environment: - GOPATH=/opt/gopath - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock - FABRIC_LOGGING_SPEC=INFO - CORE_PEER_ID=cli.{{.Organization}}.example.com - CORE_PEER_ADDRESS=peer0.{{.Organization}}.example.com:{{.Port}} - CORE_PEER_LOCALMSPID={{.Organization}} - CORE_PEER_TLS_ENABLED=true - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/peers/peer0.{{.Organization}}.example.com/tls/server.crt - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/peers/peer0.{{.Organization}}.example.com/tls/server.key - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/peers/peer0.{{.Organization}}.example.com/tls/ca.crt - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/organizations/peerOrganizations/{{.Organization}}.example.com/users/Admin@{{.Organization}}.example.com/msp working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer command: /bin/bash volumes: - /var/run/:/host/var/run/ - ../chaincode/:/opt/gopath/src/chaincode - ../../chaincode/:/opt/gopath/src/github.com/chaincode - ../fixtures/organizations:/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/organizations - ../scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/ - ../fixtures/channel-artifacts:/opt/gopath/src/github.com/hyperledger/fabric/peer/fixtures/channel-artifacts - ../bin:/opt/gopath/src/github.com/hyperledger/fabric/peer/bin depends_on: - peer0.{{.Organization}}.example.com networks: - net<file_sep>module github.com/kortelyov/hyperledger-fabric-samples/cmd/inspector go 1.15 require github.com/astaxie/flatmap v0.0.0-20160505145528-c0e84c00d8d5 <file_sep>#!/bin/bash ORGANIZATION="$1" CHANNEL="$2" DELAY="$3" TIMEOUT="$4" VERBOSE="$5" # shellcheck disable=SC2223 : ${ORGANIZATION:="organization"} # shellcheck disable=SC2223 : ${CHANNEL:="channel"} # shellcheck disable=SC2223 : ${DELAY:="3"} # shellcheck disable=SC2223 : ${TIMEOUT:="10"} # shellcheck disable=SC2223 : ${VERBOSE:="false"} . scripts/utils.sh # fetchChannelConfig <channel_id> <output_json> # Writes the current channel config for a given channel to a JSON file fetchChannelConfig() { OUTPUT=$1 setOrdererGlobals echo ">>> fetching the most recent configuration block for the ${CHANNEL} channel" set -x peer channel fetch config config_block_sys.pb -o orderer.example.com:7050 -c system-channel --tls --cafile "${ORDERER_CA}" { set +x; } 2>/dev/null echo ">>> decoding config block to JSON and isolating config to ${OUTPUT}" set -x configtxlator proto_decode --input config_block_sys.pb --type common.Block | jq .data.data[0].payload.data.config >"${OUTPUT}" set +x } # createConfigUpdate <original_config.json> <modified_config.json> <output.pb> # Takes an original and modified config, and produces the config update tx # which transitions between the two createConfigUpdate() { ORIGINAL=$1 MODIFIED=$2 OUTPUT=$3 set -x configtxlator proto_encode --input "${ORIGINAL}" --type common.Config --output config.pb configtxlator proto_encode --input "${MODIFIED}" --type common.Config --output modified_config.pb configtxlator compute_update --channel_id system-channel --original config.pb --updated modified_config.pb --output config_update.pb configtxlator proto_decode --input config_update.pb --type common.ConfigUpdate | jq . > config_update.json echo '{"payload":{"header":{"channel_header":{"channel_id":"'system-channel'","type":2}},"data":{"config_update":'$(cat config_update.json)'}}}' | jq . > config_update_in_envelope.json configtxlator proto_encode --input config_update_in_envelope.json --type common.Envelope --output "${OUTPUT}" set +x } signConfigtxAsPeerOrg() { local TX=$1 setOrdererGlobals set -x peer channel signconfigtx -f "${TX}" { set +x; } 2>/dev/null } echo ">>> creating config transaction to add $ORGANIZATION to the $CHANNEL channel..." # Fetch the config for the channel, writing it to config.json fetchChannelConfig config.json # Modify the configuration to append the new organization set -x jq -s '.[0] * {"channel_group":{"groups":{"Consortiums":{"groups":{"GlobalConsortium":{"groups": {"'$ORGANIZATION'":.[1]}}}}}}}' config.json ./fixtures/organizations/peerOrganizations/$ORGANIZATION.example.com/$ORGANIZATION.json > modified_config.json set +x # Compute a config update, based on the differences between config.json and modified_config.json, # write it as a transaction to org_update_in_envelope.pb createConfigUpdate config.json modified_config.json org_update_in_envelope.pb #signConfigtxAsPeerOrg org_update_in_envelope.pb set -x peer channel update -f org_update_in_envelope.pb -o orderer.example.com:7050 -c system-channel --tls --cafile "${ORDERER_CA}" set +x echo ">>> config transaction to add $ORGANIZATION to ${CHANNEL} submitted!.." set -x peer channel fetch config config_block_sys_update.pb -o orderer.example.com:7050 -c system-channel --tls --cafile "${ORDERER_CA}" res=$? verifyResult $res { set +x; } 2>/dev/null echo ">>> done..." exit 0 <file_sep>* install golang from https://golang.org/dl/ * install / download hyperledger binaries <code> cd $GOPATH/src/github.com/hyperledger </code> <p></p> <code> curl -sSL https://bit.ly/2ysbOFE | bash -s </code> <p></p> additional information: https://hyperledger-fabric.readthedocs.io/en/release-2.2/install.html * copy binaries from fabric-samples/bin to your PATH * clone github.com/kortelyov/hyperledger-fabric-samples <code> ./network.sh up -s couchdb </code> <p></p> <code> ./network.sh addOrg -o org1 -c global </code> <p></p> For checking logs <p></p> <code> docker logs {peer_container_id} </code> <p></p> For checking files for updating configuration: <p></p> <code> docker exec -it {cli_container_id} /bin/bash </code><file_sep>package main type Config struct { ChannelGroup struct { Groups struct { Application struct { Groups struct { G string } `json:"groups"` } `json:"Application"` } `json:"groups"` } `json:"channel_group"` } //func (c *Config) UnmarshalJSON(b []byte) error { // fmt.Println("unmarshal") // g.M = make(map[string]interface{}) // group := make(map[string]interface{}) // err := json.Unmarshal(b, &group) // if err != nil { // return err // } // for key, value := range group { // //if key == "groups" { // //} // //g.M[key] = value // fmt.Println(key, value) // fmt.Println() // } // return nil //}<file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "sort" "strings" "github.com/astaxie/flatmap" ) const ApplicationGroup = "channel_group.groups.Application.groups" const MspIdentifier = "principal.msp_identifier" const AdminPolicy = "Admins.policy" func main() { file, err := os.Open("/opt/gopath/src/github.com/hyperledger/fabric/peer/config.json") if err != nil { fmt.Println(err) } defer file.Close() b, err := ioutil.ReadAll(file) if err != nil { fmt.Println(err) } var mp map[string]interface{} if err := json.Unmarshal(b, &mp); err != nil { log.Fatal(err) } fm, err := flatmap.Flatten(mp) if err != nil { log.Fatal(err) } var ks []string for k := range fm { ks = append(ks, k) } sort.Strings(ks) var env string for _, k := range ks { if strings.Contains(k, ApplicationGroup) && strings.Contains(k, MspIdentifier) && strings.Contains(k, AdminPolicy) { env += fm[k] + "\n" } } err = ioutil.WriteFile("/opt/gopath/src/github.com/hyperledger/fabric/peer/channel_orgs.txt", []byte(env), 0644) if err != nil { fmt.Println(err) } } <file_sep>COUNTER=1 MAX_RETRY=5 PACKAGE_ID="" CC_RUNTIME_LANGUAGE=golang CC_SRC_PATH="/opt/gopath/src/chaincode" export CORE_PEER_TLS_ENABLED=true ORDERER_CA=${PWD}/fixtures/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem PEER0_AUDITOR_CA=${PWD}/fixtures/organizations/peerOrganizations/auditor.example.com/peers/peer0.auditor.example.com/tls/ca.crt PEER0_ORG1_CA=${PWD}/fixtures/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt PEER0_ORG2_CA=${PWD}/fixtures/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt PEER0_ORG3_CA=${PWD}/fixtures/organizations/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/tls/ca.crt declare -A MSP MSP[1]="auditor" MSP[2]="org1" MSP[3]="org2" MSP[4]="org3" # verify the result of the end-to-end test verifyResult() { if [ $1 -ne 0 ]; then echo "!!!!!!!!!!!!!!! "$2" !!!!!!!!!!!!!!!!" echo "========= ERROR !!! FAILED to execute End-2-End Scenario ===========" echo exit 1 fi } # Set ExampleCom.Admin globals setOrdererGlobals() { CORE_PEER_LOCALMSPID="orderer" CORE_PEER_TLS_ROOTCERT_FILE=${PWD}/fixtures/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem CORE_PEER_MSPCONFIGPATH=${PWD}/fixtures/organizations/ordererOrganizations/example.com/users/Admin@example.com/msp } setGlobals() { local org=$1 if [ "${org}" = "auditor" ]; then CORE_PEER_LOCALMSPID="auditor" CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_AUDITOR_CA CORE_PEER_MSPCONFIGPATH=${PWD}/fixtures/organizations/peerOrganizations/auditor.example.com/users/<EMAIL>/msp CORE_PEER_ADDRESS=peer0.auditor.example.com:7051 elif [ "${org}" = "org1" ]; then CORE_PEER_LOCALMSPID="org1" CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_ORG1_CA CORE_PEER_MSPCONFIGPATH=${PWD}/fixtures/organizations/peerOrganizations/org1.example.com/users/<EMAIL>/msp CORE_PEER_ADDRESS=peer0.org1.example.com:8051 elif [ "${org}" = "org2" ]; then CORE_PEER_LOCALMSPID="org2" CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_ORG2_CA CORE_PEER_MSPCONFIGPATH=${PWD}/fixtures/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer0.org2.example.com:9051 elif [ "${org}" = "org3" ]; then CORE_PEER_LOCALMSPID="org3" CORE_PEER_TLS_ROOTCERT_FILE=$PEER0_ORG3_CA CORE_PEER_MSPCONFIGPATH=${PWD}/fixtures/organizations/peerOrganizations/org3.example.com/users/Admin@org3.example.com/msp CORE_PEER_ADDRESS=peer0.org3.example.com:10051 else echo "${org}" echo ">>> error: unknown organization" fi } parsePeerConnectionParameters() { PEER_CONN_PARMS="" PEERS="" while [ "$#" -gt 0 ]; do setGlobals $1 PEER="peer0.${CORE_PEER_LOCALMSPID}.example.com" ## Set peer addresses PEERS="$PEERS $PEER" PEER_CONN_PARMS="${PEER_CONN_PARMS} --peerAddresses $CORE_PEER_ADDRESS --tlsRootCertFiles ${CORE_PEER_TLS_ROOTCERT_FILE}" shift done PEERS="$(echo -e "$PEERS" | sed -e 's/^[[:space:]]*//')" }<file_sep>package main import ( "fmt" "github.com/hyperledger/fabric-contract-api-go/contractapi" ) type Registration struct { contractapi.Contract } func (r *Registration) Register(ctx contractapi.TransactionContextInterface, org string) error { fmt.Println(org) //t := time.Now().Format("2006-01-02T15:04:05.999Z") err := ctx.GetStub().PutState(org, []byte(org)) if err != nil { return err } return nil } func main() { chaincode, err := contractapi.NewChaincode(new(Registration)) if err != nil { fmt.Printf("Error create registration chaincode: %s", err.Error()) return } if err := chaincode.Start(); err != nil { fmt.Printf("Error starting registration chaincode: %s", err.Error()) } } <file_sep>#!/bin/bash # IN PROGRESS ORGANIZATION="$1" CHANNEL="$2" DELAY="$3" TIMEOUT="$4" VERBOSE="$5" # shellcheck disable=SC2223 : ${ORGANIZATION:="organization"} # shellcheck disable=SC2223 : ${CHANNEL:="global"} # shellcheck disable=SC2223 : ${DELAY:="3"} # shellcheck disable=SC2223 : ${TIMEOUT:="10"} # shellcheck disable=SC2223 : ${VERBOSE:="false"} . scripts/utils.sh parsePeerConnectionParameters() { PEER_CONN_PARAMS="" PEERS="" while [ "$#" -gt 0 ]; do echo ">>> parsePeerConnectionParameters (inside)" echo $1 setGlobals $1 PEER="peer0.${CORE_PEER_LOCALMSPID}.example.com" ## Set peer addresses PEERS="$PEERS $PEER" PEER_CONN_PARAMS="${PEER_CONN_PARAMS} --peerAddresses $CORE_PEER_ADDRESS --tlsRootCertFiles ${CORE_PEER_TLS_ROOTCERT_FILE}" shift done PEERS="$(echo -e "$PEERS" | sed -e 's/^[[:space:]]*//')" } # fetchChannelConfig <channel_id> <output_json> # Writes the current channel config for a given channel to a JSON file fetchChannelConfig() { OUTPUT=$1 setOrdererGlobals echo ">>> fetching the most recent configuration block for the ${CHANNEL} channel" set -x peer channel fetch config config_block.pb -o orderer.example.com:7050 -c "${CHANNEL}" --tls --cafile "${ORDERER_CA}" { set +x; } 2>/dev/null echo ">>> decoding config block to JSON and isolating config to ${OUTPUT}" set -x configtxlator proto_decode --input config_block.pb --type common.Block | jq .data.data[0].payload.data.config >"${OUTPUT}" set +x } # createConfigUpdate <original_config.json> <modified_config.json> <output.pb> # Takes an original and modified config, and produces the config update tx # which transitions between the two createConfigUpdate() { ORIGINAL=$1 MODIFIED=$2 OUTPUT=$3 set -x configtxlator proto_encode --input "${ORIGINAL}" --type common.Config >original_config.pb configtxlator proto_encode --input "${MODIFIED}" --type common.Config >modified_config.pb configtxlator compute_update --channel_id "${CHANNEL}" --original original_config.pb --updated modified_config.pb >config_update.pb configtxlator proto_decode --input config_update.pb --type common.ConfigUpdate | jq . >config_update.json echo '{"payload":{"header":{"channel_header":{"channel_id":"'${CHANNEL}'","type":2}},"data":{"config_update":'$(cat config_update.json)'}}}' | jq . >config_update_in_envelope.json configtxlator proto_encode --input config_update_in_envelope.json --type common.Envelope >"${OUTPUT}" set +x } # signConfigtxAsPeerOrg <org> <configtx.pb> # Set the peerOrg admin of an org and signing the config update signConfigtxAsPeerOrg() { local ORG=$1 local TX=$2 setGlobals "${ORG}" set -x echo "signConfigtxAsPeerOrg by $ORG organization" peer channel signconfigtx -f "${TX}" verifyResult $res { set +x; } 2>/dev/null } joinChannelWithRetry() { local ORG=$1 setGlobals "${ORG}" echo ">>> channels list:" peer channel list set -x peer channel join -b "${CHANNEL}".block >&log.txt res=$? { set +x; } 2>/dev/null cat log.txt if [ $res -ne 0 -a $COUNTER -lt $MAX_RETRY ]; then COUNTER=$(expr $COUNTER + 1) echo "peer0.${ORG}.example.com failed to join the ${CHANNEL} channel, retry after $DELAY seconds" sleep $DELAY joinChannelWithRetry "${ORG}" else COUNTER=1 fi verifyResult $res "After $MAX_RETRY attempts, peer0.${ORG} has failed to join channel '$CHANNEL' " } packageChaincode() { local org=$1 local name=$2 local version=$3 setGlobals "${org}" set -x peer lifecycle chaincode package "${name}"_"${version}".tar.gz --path "${CC_SRC_PATH}"/"${name}" --lang "${CC_RUNTIME_LANGUAGE}" --label "${name}"_"${version}" >&log.txt set +x res=$? cat log.txt verifyResult $res "chaincode packaging by org ${ORG} has failed" echo ">>> chaincode is packaged by org ${org}" } installChaincode() { local org=$1 local name=$2 local version=$3 setGlobals "${org}" set -x peer lifecycle chaincode install "${name}"_"${version}".tar.gz >&log.txt res=$? { set +x; } 2>/dev/null cat log.txt verifyResult $res "chaincode installation on org ${org} has failed" echo ">>> chaincode ${name} is installed on org ${org}" } checkCommitReadiness() { local channel=$1 local name=$2 local org=$3 local version=$4 setGlobals "${org}" set -x peer lifecycle chaincode checkcommitreadiness --channelID "${channel}" --name "${name}" --version "${version}" --sequence 2 --output json set +x res=$? verifyResult $res "Chaincode checkCommitReadiness failed for org ${org} on channel '${channel}' failed" } approveChaincode() { local channel=$1 local name=$2 local org=$3 local version=$4 setGlobals "${org}" set -x peer lifecycle chaincode queryinstalled >&log.txt PACKAGE_ID=$(sed -n "/${name}_${version}/{s/^Package ID: //; s/, Label:.*$//; p;}" log.txt) echo "${PACKAGE_ID}" set +x cat log.txt set -x peer lifecycle chaincode approveformyorg -o orderer.example.com:7050 --tls --cafile "${ORDERER_CA}" --channelID "${channel}" --name "${name}" --version "${version}" --package-id "${PACKAGE_ID}" --sequence 2 >&log.txt set +x cat log.txt set -x peer lifecycle chaincode checkcommitreadiness --channelID "${channel}" --name "${name}" --version "${version}" --sequence 2 --output json >&log.txt set +x cat log.txt res=$? verifyResult $res "chaincode definition approved for org ${org} in channel ${channel} failed" echo ">>> chaincode definition approved for org ${org} in channel ${channel}" } # queryInstalled PEER ORG queryInstalled() { ORG=$1 setGlobals $ORG set -x peer lifecycle chaincode queryinstalled >&log.txt res=$? { set +x; } 2>/dev/null cat log.txt PACKAGE_ID=$(sed -n "/${CC_NAME}_${CC_VERSION}/{s/^Package ID: //; s/, Label:.*$//; p;}" log.txt) verifyResult $res "Query installed on peer0.org${ORG} has failed" successln "Query installed successful on peer0.org${ORG} on channel" } lifecycleCommitChaincodeDefinition() { local channel=$1 local name=$2 local org=$3 local version=$4 shift 4 parsePeerConnectionParameters $@ echo ">>> parsePeerConnectionParameters" echo $PEER_CONN_PARAMS setGlobals "${org}" set -x peer lifecycle chaincode commit -o orderer.example.com:7050 --tls --cafile "${ORDERER_CA}" --channelID "${channel}" --name "${name}" --version "${version}" --sequence 2 $PEER_CONN_PARAMS >&log.txt res=$? set +x cat log.txt verifyResult $res "chaincode definition commit failed for org ${org} on channel '${channel}' failed" echo ">>> chaincode definition committed on channel '${channel}'" } chaincodeInvoke() { local channel=$1 local name=$2 local org=$3 local args=$4 shift 4 parsePeerConnectionParameters $@ setGlobals "${org}" set -x peer chaincode invoke -o orderer.example.com:7050 --tls --cafile "${ORDERER_CA}" --channelID "${channel}" --name "${name}" -c "${args}" $PEER_CONN_PARAMS >&log.txt res=$? set +x cat log.txt verifyResult $res "invoke execution on ${CORE_PEER_ADDRESS} failed " echo ">>> invoke transaction successful on ${CORE_PEER_ADDRESS} on channel '${channel}'" } exit 0 <file_sep>module github.com/kortelyov/hyperledger-fabric-samples/chaincode/registration go 1.15 require github.com/hyperledger/fabric-contract-api-go v1.1.1
dac4717a9cfaabd38c652252684a4ac76aa992c6
[ "YAML", "Markdown", "Go", "Go Module", "Shell" ]
11
Go
illya-havsiyevych/hyperledger-fabric-samples
d22d17cd19720a839e29281ca7ed1bd1e1eeaf5e
c1564fb53638d51399f3e66d3d89af747b506734
refs/heads/master
<file_sep>'use strict'; four51.app.controller('CategoryCtrl', function ($routeParams, $sce, $scope, $451, Category, Product) { $scope.productLoadingIndicator = true; $scope.trusted = function(d){ if(d) return $sce.trustAsHtml(d); } Product.search($routeParams.categoryInteropID, null, null, function(products) { $scope.products = products; angular.forEach($scope.products, function(p){ p.Price = p.StandardPriceSchedule.PriceBreaks[0].Price; }); angular.forEach($scope.products, function(n){ n.pname = n.Name; }); angular.forEach($scope.products, function(n){ n.Number = n.InteropID; }); $scope.productLoadingIndicator = false; }); if ($routeParams.categoryInteropID) { $scope.categoryLoadingIndicator = true; Category.get($routeParams.categoryInteropID, function(cat) { $scope.currentCategory = cat; $scope.categoryLoadingIndicator = false; }); }else if($scope.tree){ $scope.currentCategory ={SubCategories:$scope.tree}; } $scope.$on("treeComplete", function(data){ if (!$routeParams.categoryInteropID) { $scope.currentCategory ={SubCategories:$scope.tree}; } }); $scope.filterDropdown = [ {text:'Price Low to High', value: 'Price'}, {text:'Price High to Low', value: '-Price'}, {text:'Name', value: 'pname'}, {text:'Item Number', value: 'Number'}, ] });
a1cab77b94e050148fa13a86ef1872f77341e0ef
[ "JavaScript" ]
1
JavaScript
jrasmussen451/MickyThompsonCustom
d6324f334e8d3562a9f85763cd5c307f53859919
b93e82f8e06f50c95826ff4dea6bc9a9806598c2
refs/heads/master
<file_sep>import React from "react"; import { Link, useParams } from "react-router-dom"; import styled from "styled-components"; import { useHistory } from "react-router-dom"; function CategoryPage() { const data_glasses = require("../db.json"); const { category } = useParams(); const history = useHistory(); const handleBack = () => { history.replace("/"); }; const nameItem = data_glasses.glasses .filter((i) => i.category === category) .map((name) => ( <Link to={`/categoryPage/${category}/${name.name}/:id`} style={{ textDecoration: "none" }} > <li> {name.name} - Price ${name.price} </li> </Link> )); return ( <> <Header> <Back onClick={handleBack}> &#8592; BACK </Back> </Header> <Heading>{category}</Heading> <ol>{nameItem}</ol> </> ); } const Header = styled.div` display: flex; align-items: center; justify-content: space-between; `; const Back = styled.h2` display: flex; justify-content: flex-start; margin-left: 20px; margin-top: 50px; `; const Heading = styled.h1` display: flex; justify-content: center; font-size: 3rem; `; export default CategoryPage; <file_sep>import React from "react"; import { Link, useParams } from "react-router-dom"; import { useHistory } from "react-router-dom"; import styled from "styled-components"; function ProductDetails() { const data_glasses = require("../db.json"); const history = useHistory(); const handleBack = () => { history.replace("/"); }; const { name } = useParams(); const Image = data_glasses.glasses.map((url) => ( <Link to={`/categoryPage/${url.category}/${url.name}/${url.id}`} style={{ textDecoration: "none" }} > <img src={url.url} /> </Link> )); return ( <Container> <Header> <Back onClick={handleBack}> &#8592; BACK </Back> </Header> <Heading>{name}</Heading> {data_glasses.glasses .filter((i) => i.name === name) .map((url) => ( <Img> <img src={url.url} alt="error" /> </Img> ))} {data_glasses.glasses .filter((i) => i.name === name) .map((price) => ( <h3>Price: ${price.price}</h3> ))} {data_glasses.glasses .filter((i) => i.name === name) .map((category) => ( <h3>Category: {category.category}</h3> ))} <Content>{Image}</Content> </Container> ); } const Container = styled.div``; const Back = styled.h2` display: flex; justify-content: flex-start; margin-left: 20px; margin-top: 50px; `; const Header = styled.div` display: flex; align-items: center; justify-content: space-between; `; const Heading = styled.h1` display: flex; justify-content: center; `; const Img = styled.div` display: flex; justify-content: center; `; const Content = styled.div` display: flex; flex-direction: row; justify-content: space-between; img { width: 140px; height: 110px; } `; export default ProductDetails; <file_sep>import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import HomePage from "./Pages/HomePage"; import CategoryPage from "./Pages/CategoryPage"; import ProductDetails from "./Pages/ProductDetails"; const App = () => { return ( <div> <Router> <Switch> <Route exact path="/" component={HomePage} /> <Route exact path={`/categoryPage/:category`} component={CategoryPage} /> <Route exact path={`/categoryPage/:category/:name/:id`} component={ProductDetails} /> </Switch> </Router> </div> ); }; export default App; <file_sep>import React from "react"; import styled from "styled-components"; import { Link } from "react-router-dom"; function HomePage() { const data_glasses = require("../db.json"); console.log(data_glasses); const data = data_glasses.glasses.map((doc) => doc.category); console.log(data); let Categories = [...new Set(data)]; console.log(Categories); const types = Categories.map((type) => ( <Link to={`/categoryPage/${type}`} style={{ textDecoration: "none" }}> <li>{type}</li> </Link> )); return ( <Container> <Header>Categories</Header> <Content> <ol>{types}</ol> </Content> </Container> ); } const Container = styled.div``; const Header = styled.div` display: flex; justify-content: center; margin-top: 15px; font-size: 1.5rem; `; const Content = styled.div``; export default HomePage;
324b3d0c265e36507f13375fec5d22b558b9c5d3
[ "JavaScript" ]
4
JavaScript
prasheel888/Lenskart-webapp
a886dc741aac7b378cdacc68af432be156e30464
189a80e21dc34ab10e20f265ccb29d0826cd5d6b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Payables.Data { public class PayablesDB { public static SqlConnection GetConnection() { //string connectionString = // "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=Payables;Integrated Security=true"; //SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder(); //stringBuilder.DataSource = "(localdb)\\mssqllocaldb"; //stringBuilder.InitialCatalog = "Payables"; //stringBuilder.IntegratedSecurity = true; string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["payablesConectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); return connection; } } } <file_sep>using System; using System.Collections.Generic; using System.Windows; using Payables.Data; namespace WpfDisplayInvoicesDue { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); try { //TODO: retrieve invoices due from data layer List<Invoice> invoices = new List<Invoice>(); invoices = InvoicesRepository.GetInvoices(); //TODO: show a message box when no invoiced are due and close the application InvoicesListView.ItemsSource = invoices; //InvoicesListView.ItemsSource = InvoicesRepository.GetInvoices(); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); Close(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Payables.Data { public class InvoicesRepository //public { public static List<Invoice> GetInvoices() { List<Invoice> invoiceList = new List<Invoice>(); //1) connection object -> PayablesDB.cs //2) connection open //3) sqlcommand //4) execute sqlcommand SqlConnection connection = PayablesDB.GetConnection(); string selectInvoices = "SELECT * FROM Invoices"; // kan nog een ander select statement achter // met ; na 'invoices' //FROM Invoices;SELECT //NextResult = overgaan naar volgende select //ExecuteReader geeft verschillende records //ExecuteScalar geeft een getal //ExecuteNonQuery past iets aan SqlCommand selectInvoicesCommand = new SqlCommand(selectInvoices, connection); SqlDataReader reader = null; try { connection.Open(); reader = selectInvoicesCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); //commandbehavior close connection, connectie wordt ook gesloten als command reader gdn is int indexInvoiceNumber = reader.GetOrdinal("InvoiceNumber"); int indexInvoiceDate = reader.GetOrdinal("InvoiceDate"); int indexInvoiceDueDate = reader.GetOrdinal("DueDate"); int indexCreditTotal = reader.GetOrdinal("CreditTotal"); int indexPaymentTotal = reader.GetOrdinal("PaymentTotal"); int indexInvoiceTotal = reader.GetOrdinal("InvoiceTotal"); while (reader.Read()) { Invoice invoice = new Invoice(); invoice.InvoiceNumber = reader[indexInvoiceNumber].ToString(); // of reader.GetString(indexInvoiceNumber); // of reader["InvoiceNumber"].ToString() invoice.InvoiceDate = reader.GetDateTime(indexInvoiceDate); invoice.DueDate = reader.GetDateTime(indexInvoiceDueDate); invoice.CreditTotal = reader.GetDecimal(indexCreditTotal); invoice.PaymentTotal = reader.GetDecimal(indexPaymentTotal); invoice.InvoiceTotal = reader.GetDecimal(indexInvoiceTotal); invoiceList.Add(invoice); } } catch (SqlException) { throw; } finally { reader?.Close(); connection?.Close(); } return invoiceList; } } }
182771a20aa232fb1e1ea07840ea3288ddf8bf77
[ "C#" ]
3
C#
WouterKenis/wpfDisplayInvoicesDue---Start-solution
53520fae1fa1a43b878d92457bcc38e1c5bcada5
5d4e6df232628b6488007638e9c12a01e22a00f2
refs/heads/master
<repo_name>AilinMcDermott/films<file_sep>/app/models/movie.rb class Movie < ActiveRecord::Base belongs_to :genre validates :title, presence: true validates :rating, presence: true validates :title, uniqueness: true end
14d94850298bff836a9f06150ece178aefcacdbc
[ "Ruby" ]
1
Ruby
AilinMcDermott/films
90ba81cf36b3cff06130870dbd177ec5fd234d1e
4a42d41fb82f73c78a2f2b5dac73eec010a846f1
refs/heads/master
<file_sep>import sys import os import math pfile = open('pfile.txt').read() bfile = open('bfile.txt').read(); hfile = open('hfile.txt','w') for prow in pfile.split('\n'): pword = prow.split() ppn = int(pword[0]) pcd = int(pword[1]) flg = 1; for brow in bfile.split('\n'): bword = brow.split(); bpn = int(bword[0]) bcd = int(bword[1]) if flg == 0: break; if ppn == bpn: if pcd == bcd: hfile.write(bword[0]) hfile.write(' ') hfile.write(bword[1]) hfile.write('\n') flg = 0;<file_sep>def A(a = 1): class B: b = 2 print a print b class C: print a A()<file_sep>import sys import os import re import string inputFile = open('txt1.out').read(); outputFile = open('txt.output','w'); flag = 0; frontName = 0; frontPruduct = 0; frontDate = 0 tmpWord = {} scoreCount = 0; count = 0 maxLen = 0; countRow = 0; countr = 0 Len =0 flag = 0 for row in inputFile.split('\n'): idx=0; word = row.split(' '); if len(word[0]) == 0 : break; if frontName == int(word[0]) and frontProduct == int(word[1]): if int(word[2]) == 1: scoreCount += 4; if int(word[2]) == 3: scoreCount += 3; if int(word[2]) == 2: scoreCount += 2 if int(word[2]) == 0: scoreCount += 0; if scoreCount > 3: countr += 1 Len += int(word[3]) count += 1; else : if scoreCount != 0: outputFile.write(str(frontName)) outputFile.write(' ') outputFile.write(str(frontProduct)) outputFile.write(' ') outputFile.write(str(scoreCount)) outputFile.write(' '); outputFile.write(str(Len/count)) outputFile.write('\n') frontName = int(word[0]) frontDate = int(word[3]) frontProduct = int(word[1]) if int(word[2]) == 1: scoreCount = 4; if int(word[2]) == 3: scoreCount = 3; if int(word[2]) == 2: scoreCount = 2 if int(word[2]) == 0: scoreCount = 0; Len = int(word[3]); count = 1 ;<file_sep>#include <stdio.h> #include <iostream> #include <math.h> #define PN 900 #define N 600 #define CN 30000 #define itN 2000 #define lgN 8336 using namespace std; struct Commodity{ float sc; int dt; int cmd; }; struct Person { int pn; int ln; Commodity cd[N]; }pnt[PN]; struct item{ int pn; int cmd; }itmN[itN]; struct logBuy{ int pn; int cmd; float sc; int dt; }lg[lgN]; struct B2B{ int ln; int cmd[20]; int cmdn[20]; int rcm; int cnt; }Buy[CN],coll[CN]; double num[CN]; int vist[CN],print[CN]; double getSim(Person p1,Person p2){ Commodity cd[N]; int n =0; double sum1=0,sum2=0,sum1Sq =0,sum2Sq =0,pSum =0; for(int i=0;i<p1.ln;i++){ for (int j=0;j<p2.ln;j++){ if(p1.cd[i].cmd == p2.cd[j].cmd&&p1.cd[i].dt == p2.cd[j].dt){ int sc1 = p1.cd[i].sc; int sc2 = p2.cd[j].sc; if(p1.cd[i].dt == p2.cd[j].dt){ sc1 += 3; sc2 += 3; } sum1 += sc1; sum2 += sc2; sum1Sq += sc1*sc1; sum2Sq += sc2*sc2; pSum += sc1*sc2; n++; } } } if(sum1 == 0 || sum2 == 0) return 0; double num = pSum-(sum1*sum2*1.0/n); double den = sqrt((sum1Sq - 1.0*sum1*sum1/n)*(sum2Sq - 1.0*sum2*sum2/n)); if(den == 0) return 0; if(num/den < 0){ return -num/den; } return num/den; } void setMutlBuy(int lgn){ for(int i=0;i<lgn;i++){ int cnt =0; for(int j=i+1;j<lgn;j++){ if(lg[i].pn==lg[j].pn&&lg[i].cmd==lg[j].cmd){ cnt++; } } if(cnt) vist[lg[i].cmd]=1; } } void setB2B(int lgn){ for(int i=0;i<CN;i++){Buy[i].ln =0,Buy[i].rcm=-1;} for(int i=0;i<lgn;i++){ if(lg[i].sc != 1) continue; int idx = lg[i].cmd; for(int j = i+1;j<lgn;j++){ if(lg[j].sc != 1) continue; if(lg[i].cmd == lg[j].cmd) continue; if(lg[i].pn==lg[j].pn&&lg[i].dt == lg[j].dt){ int flg =1; Buy[idx].cnt++; for(int t = 0;t<Buy[idx].ln;t++){ if(Buy[idx].cmd[t]==lg[j].cmd){ Buy[idx].cmdn[t]++; flg =0; } } if(Buy[idx].ln>=20) continue; if(flg){ int lt = Buy[idx].ln; Buy[idx].cmd[lt]=lg[j].cmd; Buy[idx].cmdn[lt]=1; Buy[idx].ln++; } } } } for(int i=0;i<CN;i++){ int maxN =-1; int bestCmd = -1; for(int j=0;j<Buy[i].ln;j++){ if(maxN<Buy[i].cmdn[j]&&Buy[i].cmdn[j]>2){ bestCmd = Buy[i].cmd[j]; maxN = Buy[i].cmdn[j]; } } Buy[i].rcm = bestCmd; } } void setC2B(int lgn){ for(int i=0;i<CN;i++){coll[i].ln =0,coll[i].rcm=-1;} for(int i=0;i<lgn;i++){ if(lg[i].sc != 2) continue; int idx = lg[i].cmd; for(int j = 0;j<lgn;j++){ if(lg[j].dt<lg[i].dt)continue; if(lg[j].sc != 1) continue; if(lg[i].cmd != lg[j].cmd) continue; if(lg[i].pn==lg[j].pn){ int flg =1; coll[idx].cnt++; for(int t = 0;t<coll[idx].ln;t++){ if(coll[idx].cmd[t]==lg[j].cmd){ coll[idx].cmdn[t]++; flg =0; } } // if(coll[idx].ln>2) printf("YES\n"); if(coll[idx].ln>=20) continue; if(flg){ int lt = coll[idx].ln; coll[idx].cmd[lt]=lg[j].cmd; coll[idx].cmdn[lt]=1; coll[idx].ln++; } } } } for(int i=0;i<CN;i++){ int maxN =-1; int bestCmd = -1; for(int j=0;j<coll[i].ln;j++){ // printf("cmd== %d\n",coll[i].cmd[j]); if(coll[i].cmd[j]==i&&coll[i].cmdn[j]>=2){ // printf("cmd ==%d\n",i); bestCmd = coll[i].cmd[j]; maxN = coll[i].cmdn[j]; } } coll[i].rcm = bestCmd; } } int main() { int lt =0; int pn,dt,cmd; float sc; int lgn=0; for(int i=0;i<lgN;i++){ scanf("%d%d%f%d",&pn,&cmd,&sc,&dt); // if(dt>195) continue; lg[lgn].pn=pn; lg[lgn].sc=sc; lg[lgn].cmd = cmd; lg[lgn].dt = dt; lgn++; } for(int i=0;i<lgn;i++){ pn = lg[i].pn; cmd=lg[i].cmd; sc = lg[i].sc; dt = lg[i].dt; // if(dt>195) continue; if(sc == 1) sc = 4; if(sc == 2) sc = 2; if(sc == 3) sc = 1; int flg = 0; for(int j=0;j<lt;j++){ if(pnt[j].pn == pn){ flg = 1; int idx = pnt[j].ln; int vt =1; for (int t = 0;t<pnt[j].ln;t++){ if(pnt[j].cd[t].cmd == cmd&&pnt[j].cd[t].dt==dt&&vt){ vt = 0; pnt[j].cd[t].sc+=sc; } } if(vt){ pnt[j].cd[idx].sc = sc; pnt[j].cd[idx].dt = dt; pnt[j].cd[idx].cmd = cmd; pnt[j].ln++; } } } if(flg == 0){ pnt[lt].ln = 1; pnt[lt].pn = pn; pnt[lt].cd[0].sc=sc; pnt[lt].cd[0].dt = dt; pnt[lt].cd[0].cmd=cmd; lt++; } } int flgg =0; for(int i=0;i<CN;i++) {vist[i]=0;} setMutlBuy(lgn); setC2B(lgn); setB2B(lgn); for(int t=0;t<lt;t++){ for(int i=0;i<CN;i++) {num[i]=0;} for(int i=1;i<lt;i++){ if(i == t) continue; double ratio = getSim(pnt[t],pnt[i]); for(int j=0;j<pnt[i].ln;j++){ int idx = pnt[i].cd[j].cmd; num[idx] += ratio*pnt[i].cd[j].sc; } } int cnt =0; for (int i=0;i<CN;i++) print[i]=0; for(int i=0;i<pnt[t].ln;i++){ int idx = pnt[t].cd[i].cmd; if(int(num[idx])>3||vist[idx]){ print[idx] =1; } } for(int i=0;i<pnt[t].ln;i++){ int idx = pnt[t].cd[i].cmd; if(pnt[t].cd[i].sc > 6){ if(Buy[idx].rcm !=-1){ print[Buy[idx].rcm]=1; } } } for(int i=0;i<lgn;i++){ int idx = lg[i].cmd; if(lg[i].sc == 2 && lg[i].pn == pnt[t].pn){ if(coll[lg[i].cmd].rcm!=-1){ print[coll[idx].rcm] =1; } } if(lg[i].sc == 1 && lg[i].pn == pnt[t].pn){ if(vist[idx]) print[idx] =1; } } for(int i=0;i<CN;i++){ cnt+=print[i]; } if(cnt==0) continue; printf("%d ",pnt[t].pn); int flg =0; for(int i=0;i<CN;i++){ if(!print[i]) continue; if(print[i]){ if(flg == 0){ flg ++; } else { printf(","); } printf("%d",i); // printf("%d %d\n",pnt[t].pn,i); } } printf("\n"); } // printf("%d\n",flgg); return 0; }<file_sep>import sys import os import random sys.path.append('/Users/renren/OpenCodeNLP/PCI/lib'); sys.path.append('/Users/renren/OpenCodeNLP/PCI/source') from getWordCount import * from getSim import * from buildParseTree import * print buildParseTree(4);<file_sep>from math import sqrt def sim_distance(prefs,person1,person2): si = {}; for item in prefs[person1]: if item in prefs[person2]: si[item] = 1; if len(si) == 0: return 0; sumOfSquares = sum( pow ( prefs[person1][item] - prefs[person2][item], 2 ) for item in prefs[person1] if item in prefs[person2]); return 1 / ( 1 + sumOfSquares ); def sim_pearson(prefs,p1,p2): # Get the list of mutually rated items si={} for item in prefs[p1]: if item in prefs[p2]: si[item]=1 # Find the number of elements n=len(si) # if they are no ratings in common, return 0 if n==0: return 0 # Add up all the preferences sum1=sum([prefs[p1][it] for it in si]) sum2=sum([prefs[p2][it] for it in si]) # Sum up the squares print sum1 print sum2 sum1Sq=sum([pow(prefs[p1][it],2) for it in si]) sum2Sq=sum([pow(prefs[p2][it],2) for it in si]) print sum1Sq print sum2Sq # Sum up the products pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si]) # Calculate Pearson score num=pSum-(sum1*sum2/n) den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n)) if den==0: return 0 r=num/den return r def topMatches(prefs,person,topNum = 5 , similaritiy = sim_pearson): scores = [(similaritiy(prefs, person,other), other) for other in prefs if other != person ]; scores.sort(); scores.reverse(); return scores[0:topNum];<file_sep>from math import sqrt def getSim(dict1,dict2): # Get the list of mutually rated items si={} for item in dict1: if item in dict2: si[item]=1 # Find the number of elements n=len(si) # if they are no ratings in common, return 0 if n==0: return 0 # Add up all the preferences sum1=sum([dict1[it] for it in si]) sum2=sum([dict2[it] for it in si]) # Sum up the squares sum1Sq=sum([pow(dict1[it],2) for it in si]) sum2Sq=sum([pow(dict2[it],2) for it in si]) # Sum up the products pSum=sum([dict1[it]*dict2[it] for it in si]) # Calculate Pearson score num=pSum-(sum1*sum2/n) den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n)) if den==0: return 0 r=num/den return r <file_sep>import sys import os import re infile = open('txt1.out').read(); for row in infile.split('\n'): word = row.split(' ') if len(word[0]) == 0 : break; if int(word[2]) == 0:continue; print row;<file_sep>import sys import os import re rw =0; infile = open('userBuy.txt').read() vist = {}; for row in infile.split('\n'): word = row.split(' '); count = 0; rw2 = 0; rw +=1 for row2 in infile.split('\n'): word2 = row2.split(' ') rw2 +=1 if int(word[0]) == int(word2[0]) : if int(word[1]) == int(word2[1]): if vist.has_key(rw2): break; count += 1; if count >=2: vist[rw] = 1; print word[0]+' '+word[1]; break;<file_sep>import re def PreProcess(sentence,edcode="utf-8"): sentence = sentence.decode(edcode) sentence=re.sub(u"[。,,!……!《》<>/"'::?/?、/|“”‘’;]"," ",sentence) return sentence def FMM(sentence,diction,result = [],maxwordLength = 4,edcode="utf-8"): i = 0 sentence = PreProcess(sentence,edcode) length = len(sentence) while i < length: # find the ascii word tempi=i tok=sentence[i:i+1] while re.search("[0-9A-Za-z/-/+#@_/.]{1}",tok)<>None: i= i+1 tok=sentence[i:i+1] if i-tempi>0: result.append(sentence[tempi:i].lower().encode(edcode)) # find chinese word left = len(sentence[i:]) if left == 1: """go to 4 step over the FMM""" """should we add the last one? Yes, if not blank""" if sentence[i:] <> " ": result.append(sentence[i:].encode(edcode)) return result m = min(left,maxwordLength) for j in xrange(m,0,-1): leftword = sentence[i:j+i].encode(edcode) # print leftword.decode(edcode) if LookUp(leftword,diction): # find the left word in dictionary # it's the right one i = j+i result.append(leftword) break elif j == 1: """only one word, add into result, if not blank""" if leftword.decode(edcode) <> " ": result.append(leftword) i = i+1 else: continue return result def LookUp(word,dictionary): if dictionary.has_key(word): return True return False def ConvertGBKtoUTF(sentence): return sentence.decode('gbk').encode('utf-8') <file_sep>#include <stdio.h> #include <iostream> #define N 1009 using namespace std; int map[N][N],qu[N],knum[N]; int vist[N],can[N]; int testNum[N]; int main() { int n,t,m,x,y; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) map[i][j]=0; for(int i=0;i<=n;i++){qu[i]=0,knum[i]=0,vist[i]=-1,can[i]=1,testNum[i]=0;} for(int i=0;i<m;i++){ scanf("%d%d",&x,&y); if(x==y)continue; if(map[x][y]==1) continue; knum[x]++; knum[y]++; qu[y]++; qu[x]++; map[x][y]=1; map[y][x]=1; } for(int i=1;i<=n;i++){ for(int t=0;t<=n;t++) knum[t]=0; for(int t=1;t<=n;t++)for(int j=1;j<=n;j++) if(map[t][j]&&vist[j]==-1)knum[t]++; int besti = 0; int minq = n+1; for(int j=1;j<=n;j++) { if(can[j]) { if(knum[j]<minq) { minq=knum[j]; besti = j; } else if (knum[j]==minq&&vist[j]!=-1) { besti = j; } } } if(besti == 0) break; can[besti]=0; if(vist[besti]==-1) vist[besti]=0; int flg =0; int km=0; for(int j=1;j<=n;j++){ if(map[besti][j]&&vist[j]==vist[besti]) flg++; if(map[besti][j]&&vist[j]==-1)km++; } flg=flg%2; // printf("flg1 == %d\n",flg); if((flg+knum[besti])%2) flg = 1; else flg=0; // printf("btesti ==%d %d\n",besti,knum[besti]); for(int j=1;j<=n;j++){ if(map[besti][j]&&vist[j]==-1){ // printf("flg==%d\n",flg); if(flg) {vist[j]=vist[besti]^1,flg--;} else {vist[j]=vist[besti];} knum[j]--; // printf("test ==%d %d %d\n",vist[besti],vist[j],flg); } } } // for(int i=1;i<=n;i++)printf("%d",vist[i]); // printf("\n"); int flag = 0; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(map[i][j]&&vist[j]==vist[i]) testNum[i]++; } } flag =0; for(int i=1;i<=n;i++){ if(testNum[i]%2) flag = 1; } if(flag) printf("ans wrong %d\n",t); } return 0; }<file_sep>PCI === To learm how to use Programming Collective Intelligen <file_sep>import sys import os import random sys.path.append('/Users/renren/OpenCodeNLP/PCI/lib'); sys.path.append('/Users/renren/OpenCodeNLP/PCI/source') from getWordCount import * from getSim import * from buildParseTree import * def buildParseTree(k=4): # Determine the minimum and maximum values for each point dictData = {} for i in range(20): fileName = "blogData" fileName += '%d' %i fileName += ".txt" dictData[fileName] = getWordCount(fileName); ranges = {}; for fileKey in dictData: for word in dictData[fileKey]: if ranges.has_key(word): if ranges[word] < dictData[fileKey][word]: ranges[word] = 8 * dictData[fileKey][word] else: ranges[word] = 8 * dictData[fileKey][word] # Create k randomly placed centroids clusters = {} for i in range(k): tmpDict = {} keyWord = "keyTemp" + '%d' %i for word in ranges: tmpDict[word] = random.random()*(ranges[word]) clusters[keyWord] = tmpDict; # print clusters['keyTemp0'] lastmatches=None for t in range(100): bestmatches = {} for i in range(k): tmpDict = {} keyWord = "keyTemp" + '%d' %i bestmatches[keyWord] = {}; for dictTmp in dictData: bestmatch = "" if len(dictTmp) == 0 : continue; for i in range(k): keyWord = "keyTemp" + '%d' %i d = getSim(clusters[keyWord],dictData[dictTmp]) if len(bestmatch) != 0: if d < getSim(clusters[bestmatch],dictData[dictTmp]): bestmatch = keyWord else : bestmatch = keyWord; bestmatches[bestmatch][dictTmp]=dictData[dictTmp] clusterTmp = {} for i in range(k): keyWord = "keyTemp" + '%d' %i avgs= {} if len(bestmatches[keyWord])>0: for item in bestmatches[keyWord]: for word in bestmatches[keyWord][item]: if avgs.has_key(word): avgs[word] += bestmatches[keyWord][item][word] else : avgs[word] = bestmatches[keyWord][item][word] for word in avgs: avgs[word] /= len(bestmatches[keyWord]) clusterTmp[keyWord]=avgs return bestmatches <file_sep>#!/usr/bin/python #-*-coding:utf-8-* import sys import os import re import string sys.path.append('/Users/renren/OpenCodeNLP/PCI/source'); sys.path.append('/Users/renren/OpenCodeNLP/PCI/lib'); from recommendations import critics from calculateSimilarity import * from recommendation import* flag = 0; file = open('txt.data').read(); fileOut = open('txt1.out','w') mouth = [0,31,59,90,120,151,182,212,243,273,304,335] search = re.compile('月|日') count = 0; for row in file.split(): if flag : for word in row.split(','): count %= 4 time = 0; idx = 0; if count == 3: for item in search.split(word): if len(item)==0:break; if idx == 0: # time += mouth[item] time += mouth[int(item)] else : # time += item; time += int(item); idx += 1; fileOut.write(str(time)); else : fileOut.write(word); fileOut.write(' ') count += 1 fileOut.write('\n'); flag = 1 <file_sep>import sys import os from time import time from operator import itemgetter import re path = '/Users/renren/OpenCodeNLP/PCI/source/' def getWordCount(fileName = 'blogData1.txt'): count = {}; wordList = {}; # print fileName filePath = path + fileName fileString = open(filePath).read(); wordlist = re.split(r'[^a-zA-Z\']',fileString) for word in wordlist: if count.has_key(word): count[word] = count[word] + 1 else: if len(word): count[word] = 1 return count<file_sep>import sys import os import re inFile = open('txt1.out').read() testData = open('bfile.txt','w'); ln = 0; for row in inFile.split('\n'): if ln == 0: ln += 1; continue; word = row.split(); if len(word) <=0 :break; if len(word[0]) <= 0:break; if int(word[2]) == 1: if len(word[3]) <=0: continue; if int(word[3]) > 196: testData.write(word[0]); testData.write(" "); testData.write(word[1]) testData.write("\n") <file_sep>import sys import io import re infile = open('txt1.out').read(); userBuy = {}; for row in infile.split('\n'): word = row.split(' '); if len(word[0]) == 0: break; if int(word[3]) > 196 :continue; if int(word[2]) == 1 : ansStr = word[0] + ' ' + word[1] + ' ' + word[2] + ' ' + word[3]; # print word[0] # print ' ' # print word[1] # print ' ' # print word[2] # print '' # print word[3] # print '\n' print ansStr
544472a52042fa3d4660e102676a81446e3bc409
[ "Markdown", "Python", "C++" ]
17
Python
hardcao/PCI
835c46dad2759dd833070114827105312830497b
b514af4f8c87fb377025d76c00d018ad66ba5532
refs/heads/master
<repo_name>Arnokeuh/Curriculum-Vitae<file_sep>/js/app.js $(document).ready(function(){ $("aside").addClass("bringAside"); fillSkills("french_rating", 3); fillSkills("english_rating", 4); fillSkills("dutch_rating", 5); fillSkills("office_rating", 5); fillSkills("photoshop_rating", 5); fillSkills("illustrator_rating", 5); fillSkills("indesign_rating", 3); fillSkills("flash_rating", 5); function fillSkills(item, rating){ var divs = $("#"+item).find("div"); for(var i = 0; i < rating; i++){ divs[i].className = "fill"; } } });<file_sep>/index.htm <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Curriculum Vitae - <NAME></title> <link href="stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" /> </head> <body> <article id="download_button"> <a href="../downloads/Arno_VanBoxel_CV.pdf"><span class="hide">Download</span></a> </article> <aside class="vcard"> <header> <h1 class="fn n"><span class="given-name">Arno</span> <span class="family-name"><NAME></span></h1> </header> <address> <ul class="adr"> <li class="street-address">Salviaweg 1</li> <li><span class="postal-code">2310</span> <span class="locality">Rijkevorsel</span></li> </ul> <ul> <li class="bday">12-07-1994</li> <li class="url"><a href="http://www.arnovanboxel.be/"><span class="hide">http://</span>www.arnovanboxel.be<span class="hide">/</span></a></li> <li class="email"><a href="mailto:<EMAIL>"><EMAIL></a></li> <li class="tel"><a href="tel:0497877108">+32497877108</a></li> <li>Rijbewijs B</li> </ul> </address> <hr /> <article id="skills"> <header> <h1>Vaardigheden</h1> </header> <h2>Talen</h2> <ul> <li id="dutch"><span>Nederlands</span></li> <li id="english"><span>Engels</span></li> <li id="french"><span>Frans</span></li> </ul> <h2>Computerapplicaties</h2> <ul> <li>MS Office</li> <li>Photoshop</li> <li>Illustrator</li> <li>InDesign</li> <li>Flash (AS3)</li> </ul> <div id="languages_rating"> <div class="language_rating" id="dutch_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="language_rating" id="english_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="language_rating" id="french_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> </div> <div id="programming_rating"> <div class="programm_rating" id="office_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="programm_rating" id="photoshop_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="programm_rating" id="illustrator_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="programm_rating" id="indesign_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> <div class="programm_rating" id="flash_rating"> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> <div>&nbsp;</div> </div> </div> </article> <hr /> <article id="opleiding_aside"> <header> <h1>Opleiding</h1> </header> <dl> <dt>2005-2012</dt> <dd>Multimedia (Middelbaar - SO Zenit), afgestudeerd</dd> <dt>2012-2014</dt> <dd>Design &amp; Development (Howest), niet voltooid</dd> <dt>2014-2015</dt> <dd>New Media &amp; Communication Technology, niet voltooid</dd> </dl> </article> </aside> <section id="container"> <header> <h1 class="hide">Curriculum Vitae</h1> </header> <article> <header> <h1>Vakantiewerk</h1> </header> <dl> <dt>Augustus 2011</dt> <dd><span>Paper & Boards</span> - Poetsen en helpen bedienen van drukmachines in de drukkerij.</dd> <div class="dummy">&nbsp;</div> <dt>Juli 2013</dt> <dd><span>Deltarack</span> - Design van bestelbonnen voor paletten, affiches voor beurzen. Helpen met de boekhouding.</dd> <div class="dummy">&nbsp;</div> <dt>Augustus 2014<br/>Oktober 2014<br/>April 2015</dt> <dd><span>Janssen Pharmaceutica</span> - Technische Dienst - Administratie, het opnemen van systemen in Excel files en het werken met een plaatselijk administratief platform.</dd> <div class="dummy">&nbsp;</div> </dl> </article> <article> <header> <h1>Andere ervaring</h1> </header> <dl> <dt>2013-2014</dt> <dd><span>Leiding MCTCommunity</span> - Een soort van studentenvereniging, wij organiseerden elke maand een evenement vooral voor studenten van MCT richtingen op Howest.</dd> <div class="dummy">&nbsp;</div> <dt>Juni 2015</dt> <dd><span>Reis naar Zuid-Afrika</span> - Een reis van 50 dagen naar Zuid-Afrika, waar mijn vriendin woont. Heb veel culturele ervaring opgedaan. Vrijwilligerswerk bij plaatselijke dierenwelzijn.</dd> <div class="dummy">&nbsp;</div> </dl> </article> <article id="opleiding"> <header> <h1>Opleiding</h1> </header> <dl> <dt>2005-2012</dt> <dd><span>Multimedia (Middelbaar - SO Zenit)</span> - Afgestudeerd</dd> <div class="dummy">&nbsp;</div> <dt>2012-2014</dt> <dd><span>Design &amp; Development (Howest)</span> - Niet voltooid</dd> <div class="dummy">&nbsp;</div> <dt>2014-2015</dt> <dd><span>New Media &amp; Communication Technology</span> - Niet voltooid</dd> <div class="dummy">&nbsp;</div> </dl> </article> <article> <header> <h1>Programmeer ervaring</h1> </header> <dl> <dt>HTML 5 & CSS3</dt> <dd><span>Uitstekend</span></dd> <div class="dummy">&nbsp;</div> <dt>PHP</dt> <dd><span>Uitstekend</span> - Waarschijnlijk mijn beste taal. Werk vooral met Controller & DAO methode. Modules van PHP in Hoger Onderwijs voltooid.</dd> <div class="dummy">&nbsp;</div> <dt>JavaScript</dt> <dd><span>Sterk</span> - Mijn favoriete programmeertaal. Sterke kennis van vele libraries, met o.a. JQeury, AngularJS, underScore, Backbone, Canvas (libraries), SVG (libraries), ...</dd> <div class="dummy">&nbsp;</div> <dt>SQL</dt> <dd><span>Uitstekend</span></dd> <div class="dummy">&nbsp;</div> <dt>C#</dt> <dd><span>Basiskennis</span></dd> <div class="dummy">&nbsp;</div> <dt>Java</dt> <dd><span>Basiskennis</span></dd> <div class="dummy">&nbsp;</div> <dt>ActionScript</dt> <dd><span>Uitstekend</span> - Een sterke kennis van ActionScript 3, werk met MVC methode. Modules van ActionScript in Hoger Onderwijs voltooid.</dd> <div class="dummy">&nbsp;</div> </dl> </article> </section> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" src="js/app.js"></script> </body> </html>
96a52d82af785796ca866e1e1adee8127db1fec2
[ "JavaScript", "HTML" ]
2
JavaScript
Arnokeuh/Curriculum-Vitae
ce618e0dfa74608872776fd4a772dfe4251946cd
bef09370d3f8c35b808fa949fb448f78ca5c9f2e
refs/heads/master
<repo_name>jbardliving/ruby-homework-day-1<file_sep>/hw.rb def string(strings) print "#{strings}" + " only in america" end def biggeestNumber(someNumber) print someNumber.max end biggestNumber([12,24,36,48,60]) def arrays() array1=[:toyota,:tesla] array2= ["prius","model s"] hashes= array1.zip(array2) Hash[hashes] puts hashes end arrays() def fizzbuzz() for i in (1..100) if( i %5== 0 && i%3 == 0) print "fizzbuzz" elsif(i % 5 == 0) print "Buzz" elsif ( i%3 == 0) print "fizz" end end end
167b12082a45a2e565dc762a26e2f2f228c6a171
[ "Ruby" ]
1
Ruby
jbardliving/ruby-homework-day-1
f854736a27432997aacc2047b6da6fca767b5ed2
2079950c36784725d90788babceb11b8b6d244cb
refs/heads/master
<repo_name>aaltowebapps/hungrybunch<file_sep>/public/scripts/api.js // // FeedMe! Javascript busines logic main file // by <NAME> and rest of the Hungry Bunch // (function(FeedMe) { FeedMe.lounasaikaApi = { isReady : false } // Api related constants var api_url = "http://www.lounasaika.net/api/"; var api_req_key = "development321"; var api_req_callback = "?callback=?"; var api_req_campus = ""; var api_req_restaurant = ""; var api_req_lat = null; var api_req_lng = null; var api_req_maxdistance = null; var api_res_output = "json"; var api_res_root = "LounasaikaResponse"; var api_res_status = "status"; var api_res_ok = "OK"; var api_res_result = "result"; var api_res_updated = "updated"; var api_res_campus = "campus"; var api_res_name = "name"; var api_res_restaurant = "restaurant"; var api_res_url = "url"; var api_res_info = "info"; var api_res_location = "location"; var api_res_address = "address"; var api_res_lat = "lat"; var api_res_lng = "lng"; var api_res_distance = "distance"; var api_res_opening_hours = "opening_hours"; var api_res_opening_time = "opening_time"; var api_res_closing_time = "closing_time"; var api_res_monday = "monday"; var api_res_tuesday = "tuesday"; var api_res_wednesday = "wednesday"; var api_res_thursday = "thursday"; var api_res_friday = "friday"; var api_res_saturday = "saturday"; var api_res_sunday = "sunday"; var api_res_days = [api_res_monday, api_res_tuesday, api_res_wednesday, api_res_thursday, api_res_friday, api_res_saturday, api_res_sunday]; var api_res_menu = "menu"; var api_res_meal = "meal"; var translation_weekday = {}; translation_weekday[api_res_monday] = 'maanantai'; translation_weekday[api_res_tuesday] = 'tiistai'; translation_weekday[api_res_wednesday] = 'keskiviikko'; translation_weekday[api_res_thursday] = 'torstai'; translation_weekday[api_res_friday] = 'perjantai'; translation_weekday[api_res_saturday] = 'lauantai'; translation_weekday[api_res_sunday] = 'sunnuntai'; // Local storage related constants var localStorage_key = "menuOnWeek"; // Array to store restaurants data var restaurants = new Array(); // Expand Date to include function for getting a week number. Date.prototype.getWeek = function() { var onejan = new Date(this.getFullYear(),0,1); return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7); } function apiReady() { FeedMe.lounasaikaApi.isReady = true; FeedMe.startApp(); } // Successful fetch response is handled here function fetchSuccess(responseData) { if (responseData) { var status = responseData[api_res_root][api_res_status]; if (status == api_res_ok) { // Response OK var updated = responseData[api_res_root][api_res_result][api_res_updated]; // Parse date and time from 2012-03-25T21:55:09+03:00 // Compare to date time on device // Store campi to localstore with expiration at the very beginning of next week var campi = responseData[api_res_root][api_res_result][api_res_campus]; restaurants = {}; resultindex = 0; // Iterate over campi $.each(campi, function(campusindex, value) { var campus = campi[campusindex][api_res_name]; var res_restaurants = value[api_res_restaurant]; // Iterate over restaurants $.each(res_restaurants, function(index, value) { var restaurant = value; // Add campus as property of restaurant restaurant['campus'] = campus; restaurant['id'] = resultindex+1; restaurants[resultindex] = restaurant; var menu = []; var res_menu = value[api_res_menu]; // Iterate over week days $.each(api_res_days, function(index, value) { var res_meal = res_menu[value][api_res_meal]; // If meal is not array if (!$.isArray(res_meal)) { // Make it array res_menu[value][api_res_meal] = [res_meal]; } res_menu[value]['day'] = translation_weekday[value]; menu.push(res_menu[value]); }); restaurant.menu = menu; resultindex++; }); }); var key = getKeyOfThisWeek(); // Have to calculate the minutesToNextWeek for expiration time of cache // lscache.set(key, campi, minutesToNextWeek); // for now just use it without expiration time lscache.set(key, restaurants); FeedMe.lounasaikaApi['restaurants'] = restaurants; apiReady(); } else { // Response not OK } } } // Fetch data function fetchMenus() { var data = { key: api_req_key }; var url = api_url + api_res_output + api_req_callback; // Use sample data // $.getJSON('assets/sampledata/sampleresponse.js', fetchSuccess); $.getJSON(url, data, fetchSuccess); } // Process loaded menus from local store function processLoadedMenus(restaurantsFromCache) { restaurants = restaurantsFromCache; FeedMe.lounasaikaApi['restaurants'] = restaurants; apiReady(); } // Returns key used to store weekly data in local storage // Like "menuOnWeek24" function getKeyOfThisWeek() { var today = new Date(); var weekNumber = today.getWeek(); var key = localStorage_key + weekNumber.toString(); return key; } // Initialize data function init() { var key = getKeyOfThisWeek(); FeedMe.lounasaikaApi['localstorageKey'] = 'lscache-'+key; // This is for development, you can flush cache from local storage to force // fetching of fresh data by uncommentting next line. //lscache.flush(); // Try to load menu from local storage var restaurantsFromCache = lscache.get(key); if (restaurantsFromCache) { // If loaded from local storage, process it processLoadedMenus(restaurantsFromCache); } // Check connectivity else if (isOnline) { // Online, update menus fetchMenus(); } else if (!restaurantsFromCache) { // No valid restaurant information and no connectivity, // have to inform user that connectivity is needed. alert("Network connection is needed to update menus"); } /* // Check geolocation support if (haveGeoSupport) { // Get current position currentPosition(); // Start to track changes in position trackPositionChanges(); } */ } // Check online function isOnline() { return navigator.onLine; } // Check geolocation support function haveGeoSupport() { return navigator.geolocation; } // Get current position function currentPosition() { navigator.geolocation.getCurrentPosition(geoSuccess, geoError, {enableHighAccuracy: position_high_accuracy, maximumAge: position_max_age, timeout: position_timeout}); } // Start tracking position changes function trackPositionChanges() { if (position_watch_id == null) { position_watch_id = navigator.geolocation.watchPosition(geoSuccess, geoError, {enableHighAccuracy: position_high_accuracy, maximumAge: position_max_age, timeout: position_timeout}); } } // Stop tracking position changes function stopTrackPositionChanges() { if (position_watch_id != null) { navigator.geolocation.clearWatch(position_watch_id); position_watch_id = null; } } // Successful geolocation update function geoSuccess(newPosition) { position = newPosition; } // Geolocation error function geoError(error) { // error.code can be: // 0: unknown error // 1: permission denied // 2: position unavailable (error response from locaton provider) // 3: timed out alert("Geolocation error occurred. Error code: " + error.code); } // Run init init(); })(FeedMe); <file_sep>/server.rb require 'sinatra' get '/' do send_file 'public/index.html' end <file_sep>/public/scripts/mvc.js // Self-invoking function, closure (function(FeedMe) { Handlebars.registerHelper('distance_formatted', function() { var d = this.distance; var output; if(!d) output = "?"; else if (d>1) output = Math.round(d)+" km"; else if (d<=1) output = Math.round(d*1000)+" m"; else output = ""; return new Handlebars.SafeString(output); }); // Source HTML for common footer var footerTemplateSource = $("#footerTemplate").html(); // Parse templates and set visible to FeedMe-object var restaurantItemTemplate = Handlebars.compile($("#restaurantItemTemplate").html()); var restaurantsListTemplate = Handlebars.compile($("#restaurantsListTemplate").html()); var restaurantsPageTemplate = Handlebars.compile($("#restaurantsPageTemplate").html() + footerTemplateSource); var menuTemplate = Handlebars.compile($("#menuTemplate").html() + footerTemplateSource); var mapTemplate = Handlebars.compile($("#mapTemplate").html() + footerTemplateSource); // Model for a single restaurant var RestaurantModel = Backbone.Model.extend ({ id : 0, initialize : function() { // If user position is known, calculate distance if(FeedMe.geo.position) { this.updateDistance(FeedMe.geo.position.coords.latitude, FeedMe.geo.position.coords.longitude); } }, distanceFormatted : function() { var d = this.get('distance'); if (d>1) return Math.round(d)+" km"; else if (d<=1) return Math.round(d*1000)+" m"; return d; }, updateDistance : function(lat,lng) { if( lat && lng ) { var itemLat = this.get('location').lat; var itemLng = this.get('location').lng; var distance = null; if( itemLat && itemLng ) { distance = FeedMe.geo.calculateDistance(lat, lng, itemLat, itemLng); } this.set({distance: distance}); } } }); // Collection for all restaurants var RestaurantsCollection = Backbone.Collection.extend ({ model: RestaurantModel, // localStorage: new Backbone.LocalStorage(FeedMe.lounasaikaApi.localstorageKey) comparator: function(item){ return item.get('distance') || 9999999999; } }); // View for a single restaurant in list var RestaurantItemView = Backbone.View.extend({ tagName: "li", initialize: function() { // Let's not bind to changes on rows, but on the entire collection instead //this.model.bind('change', this.render, this); this.template = restaurantItemTemplate; }, render: function() { $(this.el).html( this.template(this.model.toJSON()) ); return this; } }); // View for the list of restaurants var RestaurantsListView = Backbone.View.extend({ initialize: function() { this.collection.bind('change', this.debouncedRender, this); this.template = restaurantsListTemplate; }, debouncedRender : _.debounce(function() { // Force sorting the collection before re-rendering this.collection.sort(); this.render(); // As we created a new list, jQuery Mobile needs to render it to listview now $(this.el).find('#restaurantsList').listview({ autodividers: true, autodividersSelector: function ( li ) { return $(li).find('a').attr('title').text(); } }); $(this.el).find('#restaurantsList').listview('refresh'); }, 300), // This is how the list of restaurants should be rendered to page render:function (eventName) { var $el = $(this.el).empty(); $el.html(this.template({'restaurants': this.collection.toJSON(), chosenRestaurant:FeedMe.chosenRestaurant})); var $list = $el.find('#restaurantsList'); this.collection.each(function(item) { var itemView = new RestaurantItemView({model: item}); $list.append(itemView.render().el); }); return this; } }); // View for the restaurants page var RestaurantsView = Backbone.View.extend({ initialize: function() { this.template = restaurantsPageTemplate; }, render:function (eventName) { var listView = new RestaurantsListView({collection: this.collection}); var $el = $(this.el).empty(); $el.html(this.template()); $el.find('#restaurantsListWrapper').append(listView.render().el); return this; } }); var previousRestaurant = 0; var nextRestaurant = 0; // View for the list of menus for a chosen restaurant var MenuView = Backbone.View.extend({ // Compiled template template: menuTemplate, // This is how the menu listing should be rendered to page render:function (eventName) { // Here we get the selected restaurant id and can select data for template accordingly var currentRestaurantId = parseInt(this.options.restaurantId); var currentModel = FeedMe.restaurantsData.get(currentRestaurantId); var index = this.collection.indexOf(currentModel); previousRestaurant = this.collection.at(index-1); nextRestaurant = this.collection.at(index+1); var baseUrl = "#/menus/"; var prevRestaurantUrl = ( previousRestaurant ? baseUrl + previousRestaurant.id : '#'); var nextRestaurantUrl = ( nextRestaurant ? baseUrl + nextRestaurant.id : '#'); var prevLabel = previousRestaurant ? previousRestaurant.get('name') : 'Restaurants'; var nextLabel = nextRestaurant ? nextRestaurant.get('name') : 'Restaurants'; var restaurant = currentModel.toJSON(); var mapParameters = 'center='+restaurant.location.lat+','+restaurant.location.lng+'&zoom=13&size='+($(document).width()-30)+'x100&sensor=true&markers='+restaurant.location.lat+','+restaurant.location.lng; $(this.el).html(this.template({'restaurant': restaurant, 'nextRestaurantUrl':nextRestaurantUrl, 'prevRestaurantUrl':prevRestaurantUrl, 'chosenRestaurant':FeedMe.chosenRestaurant, 'prevLabel':prevLabel, 'nextLabel':nextLabel, 'mapParameters':mapParameters})); return this; } }); // View for the map page var MapView = Backbone.View.extend({ initialize: function() { this.template = mapTemplate; }, render:function (eventName) { $(this.el).html(this.template({'chosenRestaurant':FeedMe.chosenRestaurant})); // TODO: Set map element "#canvas_map" to full screen size $(this.el).find('#canvas_map').width($(document).width()); $(this.el).find('#canvas_map').height($(document).height()-100); var userPosition = null; var userMarker = null; if( FeedMe.geo.position && FeedMe.geo.position.coords ) { userPosition = new google.maps.LatLng(FeedMe.geo.position.coords.latitude, FeedMe.geo.position.coords.longitude); } else { userPosition = new google.maps.LatLng(60.167091,24.943557); } // TODO: bind event listener for user position and set new position when changed var myOptions = { zoom: 16, center: userPosition, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("canvas_map"), myOptions); FeedMe.map = map; // TODO: Draw user position on map as a dot or something different from the restaurant markers var userMarker = new google.maps.Marker({ map: map, position: userPosition, draggable: false, title: 'Your position' }); // Draw restaurant as markers on map var markers = []; FeedMe.restaurantsData.each(function(item) { var location = item.get('location'); if( location && location.lat && location.lng ) { var latlng = new google.maps.LatLng(location.lat, location.lng); var marker = new google.maps.Marker({ url: '#/menus/'+item.get('id'), map: map, position: latlng, draggable: false, title: item.get('name'), icon: 'images/restaurant.png' }); google.maps.event.addListener(marker, 'click', function() { window.location.href = marker.url; }); markers.push(marker); } }); // TODO: Smarter binding and unbinding $(document).on('pageshow.mapview', function() { google.maps.event.trigger(FeedMe.map,'resize'); map.setCenter(userPosition); $(document).off('pageshow.mapview'); }); return this; } }); // Define logic for routing var AppRouter = Backbone.Router.extend({ // Map urls to pages routes:{ "":"restaurants", "/menus/:id":"menu", "/lastmenu/":"lastmenu", "/map/":"map" }, initialize:function () { // Define sliding direction this.goReverse = false; var router = this; // Handle back button throughout the application $('.back').live('click', function(event) { window.history.back(); router.goReverse = true; return false; }); // When button with class .ui-btn-left is clicked, go reverse $('.ui-btn-left').live('click', function(event) { router.goReverse = true; }); // If swipe right is detected, go reverse and try to figure previous page $('body').live('swiperight', function(event) { if( router.currentPageName == 'menu') { if( previousRestaurant ) { router.goReverse = true; router.menu(previousRestaurant.id); } else { router.restaurants(); } } // TODO move to prevous page //console.log('Detected swipe left'); }); // If swipe left is detected, go to the next page $('body').live('swipeleft', function(event) { if( router.currentPageName == 'menu') { if( nextRestaurant ) { router.goReverse = false; router.menu(nextRestaurant.id); } } // TODO move to next page //console.log('Detected swipe right'); }); // We are on first pageload until marked otherwise this.firstPage = true; }, // Page restaurants (listing of all restaurants) restaurants:function () { this.currentPageName = 'restaurants'; var view = new RestaurantsView({collection: FeedMe.restaurantsData}); this.changePage(view, 'slideup'); window.view = view; }, // Page menu (listing of menus for a restaurant) menu:function (id) { FeedMe.chosenRestaurant = id; this.currentPageName = 'menu'; this.currentRestaurant = id; this.changePage(new MenuView({collection: FeedMe.restaurantsData, restaurantId:id}), 'slide'); }, lastmenu:function() { this.currentPageName = 'menu'; this.changePage(new MenuView({collection: FeedMe.restaurantsData, restaurantId: this.currentRestaurant ? this.currentRestaurant : 1}), 'slideup'); }, map:function () { this.currentPageName = 'map'; this.changePage(new MapView(), 'slideup'); }, // This is how changing a page is handled changePage:function (page, transition) { $(page.el).attr('data-role', 'page'); // Add new page to document body $('body').append($(page.el)); // Render page page.render(); //var transition = 'slide'; // We don't want to slide the first page if (this.firstPage) { transition = 'none'; this.firstPage = false; } // Go reverse this time? var reverse = false; if( this.goReverse ) { reverse = true; this.goReverse = false; } // Finally change page $.mobile.changePage($(page.el), {changeHash:false, transition: transition, reverse: reverse}); } }); // Make public only what needs to be globally available FeedMe.RestaurantModel = RestaurantModel; FeedMe.RestaurantsCollection = RestaurantsCollection; FeedMe.RestaurantsView = RestaurantsView; FeedMe.MenuView = MenuView; FeedMe.AppRouter = AppRouter; })(FeedMe); <file_sep>/public/assets/sampledata/sampleresponse.js { "LounasaikaResponse": { "status": "OK", "result": { "updated": "2012-03-25T21:55:09+03:00", "campus": [ { "name": "Otaniemi", "restaurant": [ { "name": "Teekkariravintolat", "url": "http:\/\/www.sodexo.fi\/dipoli", "info": "", "location": { "address": "Otakaari 24, Espoo", "lat": "60.1847778", "lng": "24.8309887", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "1130", "closing_time": "1500" } }, "menu": { "monday": { "meal": [ "&nbsp;\n Kebab", "Kebab", "&nbsp;\n Kasvislasagnette", "Vegetable pasta", "&nbsp;\n Meksikolaista jauhelihakeittoa", "Mexican minced meat soup", "&nbsp;\n a la carte:Parmesankourrutettua uunikalaa v\u00e4limerenkasviksilla", "A la carte:Fish with parmesan crust", "&nbsp;\n Broiler-pastasalaattia", "Chicken salad", "L" ] }, "tuesday": { "meal": [ "&nbsp;\n Juustoisia broilerpuikkoja pippurikermakastikkeella", "Chicken sticks with creamy pepper sauce", "&nbsp;\n Kasviskroketteja", "Vegetable croguettes" ] }, "wednesday": { "meal": "" }, "thursday": { "meal": "" }, "friday": { "meal": "" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "TUAS-talo", "url": "http:\/\/www.amica.fi\/TUAS#Ruokalista", "info": "", "location": { "address": "Otaniementie 17, Espoo", "lat": "60.1868196", "lng": "24.8187598", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Nakkistroganoffia (VL),Keitettyj&auml; perunoita (*, G, L, M),", "Yrttisi&auml; kalapaloja (*, L, M),Sitruunamajoneesia (G, L),Keitettyj&auml; perunoita (*, G, L, M)", "Kasvis-vehn&auml;risottoa luomutofulla (*, L, M)", "Bistro: Kermaista bataatti-maissisosekeittoa (G, VL)", "Bistro: Kalkkunasalaattia (*, G, L)", "Bistro: Chili-broileriwrap (L),Chili-kermaviilikastiketta (G, L)", "&Aacute; la carte:Riistak&auml;ristyst&auml; (*, G, L, M),Perunasosetta (*, G, VL)" ] }, "tuesday": { "meal": [ "Kinkku-tuorejuustokastiketta pastalle (G, VL),T&auml;ysjyv&auml;kierrepastaa (*, L, M)", "Intialaista jogurttiseiti&auml; (*, G),Keitettyj&auml; perunoita (*, G, L, M)", "Espanjalaista pinaatti-oliivimunakasta (*, G, L)", "Bistro: Kukkakaalisosekeittoa (G, VL)", "Bistro: Katkarapusalaattia (*, G, L)", "Bistro: Pitakebab ja jogurttikastiketta", "&Aacute; la carte:Juustokuorrutettu broilerinfilee (L),Chili-tomaattikastiketta (G, L, M),Valkosipuliriisi&auml; (G, L, M)" ] }, "wednesday": { "meal": [ "Juustokuorrutettua jauhelihavuokaa (*)", "Broileri-juustokastiketta (*, G, VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kukkakaali-perunacurrya (*, G, L, M),T&auml;ysjyv&auml;ohraa (*, L, M)", "Bistro: Herkkusienikeittoa (G, VL)", "Bistro: Kreikkalainen salaatti (G)", "Bistro: Tulista kebablihapannupizzaa (L)", "&Aacute; la carte:Porsaanleike Amican tapaan (L, M),Pippurikastiketta (VL),Annanperunoita (G, L, M)" ] }, "thursday": { "meal": [ "Lohipy&ouml;ryk&ouml;it&auml; (L, M),Tillikastiketta (*, VL),Keitettyj&auml; perunoita (*, G, L, M)", "Naudanlihaa ja juureksia tomaattikastikkeessa (*, G, L, M),Keitettyj&auml; perunoita (*, G, L, M)", "Bistro: Papu-vihannespastaa (*, L, M)", "Bistro: Hernekeittoa (G, L, M),Pannukakkua ja mansikkahilloa (G, L, M)", "Bistro: Kinkku-pastasalaattia (L)", "Bistro: Ananashampurilainen (L, M),Ranskalaisia perunoita (G, L, M)", "&Aacute; la carte:Porsaan grillipihvi (G, L, M),Cafe de Paris -maustevoita (G, VL),Paahdettua perunaa (G, L, M)" ] }, "friday": { "meal": [ "Jauheliha-sipulipihvej&auml; (G, L, M),Ruskeaa kastiketta (VL),Keitettyj&auml; perunoita (*, G, L, M)", "Katkarapu-kasvispataa (G, L, M),H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "Kasviksia seesamkastikkeessa (*, G, L, M),H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "Bistro: Sipulikeittoa ja siemensekoitusta (G, L, M)", "Bistro: Texmex-maustettua broilerinfileesalaattia (*, G, L)", "Bistro: L&auml;mmin broilerinfilee-ananasleip&auml; (L)", "&Aacute; la carte:Paneroitu kampelafilee (L, M),Sahramikastiketta (G, L),Tillill&auml; maustettuja viipaleperunoita (G, L, M)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Alvari", "url": "http:\/\/www.amica.fi\/alvari#Ruokalista", "info": "", "location": { "address": "Otakaari 2, Espoo", "lat": "60.1862055", "lng": "24.8262297", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1700" }, "tuesday": { "opening_time": "1030", "closing_time": "1700" }, "wednesday": { "opening_time": "1030", "closing_time": "1700" }, "thursday": { "opening_time": "1030", "closing_time": "1700" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Tonnikala-pinaattilasagnette VL", "Lindstr&ouml;minpihvit, ruskeaa kastiketta, keitettyj&auml; perunoita L", "Uuniperuna feta-oliivit&auml;ytteell&auml; G", "Puolukkarahka G,VL" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml;, omena-currykastiketta, ruis-riisi&auml; &acute;VL", "Janssoninkiusausta G,VL", "Bataatti-kikhernecurrya, ruis-riisi&auml; G,L,M", "Aprikoosikiisseli&auml;, kermavaahtoa G,L" ] }, "wednesday": { "meal": [ "Kalkkuna-tomaattikastiketta, riisi&auml;, jalopenoja G,L,M", "Jauheliha-tomaattipannupizaa L", "Kasviksia currykastikeessa, riisi&auml; *,G,L,M", "Mansikkasmoothieta G" ] }, "thursday": { "meal": [ "Uunimakkaraa juustolla, perunasosetta G,VL", "Broilerilasagnea VL", "Kasvisbolognesea, t&auml;ysjyv&auml;spagettia L,M", "Mokka-mandariinivaahtoa G,L" ] }, "friday": { "meal": [ "Kebabtortilloja, riisi&auml;, tomaattisalsaa, kermaviili&auml; L", "Sitruunaseiti&auml;, perunasosetta G,VL", "Juurespihvej&auml;, jogurtti-basilikakastiketta, perunoita G,L", "A la carte: porsaanleike Amican tapaan, pippurikastiketta,perunasosetta VL", "Kuningatarkiisseli&auml;, kermavaahtoa G,L", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Elissa", "url": "http:\/\/www.amica.fi\/elissa#Ruokalista", "info": "Puuro 7:30\u20139:30 Keitto 11:00\u201315:00", "location": { "address": "Otakaari 2, Espoo", "lat": "60.1862055", "lng": "24.8262297", "distance": "" }, "opening_hours": { "monday": { "opening_time": "730", "closing_time": "1800" }, "tuesday": { "opening_time": "730", "closing_time": "1800" }, "wednesday": { "opening_time": "730", "closing_time": "1800" }, "thursday": { "opening_time": "730", "closing_time": "1800" }, "friday": { "opening_time": "730", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Ruishiutalepuuroa L,M", "Kalkkunasalaattia, leip&auml;&auml; L", "Kermaista purjo-perunasosekeittoa G,VL", "Op.leip&auml;at.: Munapatonki VL" ] }, "tuesday": { "meal": [ "Kaurapuuroa L,M", "Tomaatti-mozzarellasalaattia, leip&auml;&auml; VL", "Kinkkuminestronea L,M", "Op.leip&auml;at.: L&auml;mminsavukirjolohipatonki VL" ] }, "wednesday": { "meal": [ "Mannapuuroa VL", "Kylm&auml;savukirjolohisalaattia, leip&auml;&auml; L", "Pinaattikeittoa ja kanamuna", "Op.leip&auml;at.: Kinkku-juustopatonki VL" ] }, "thursday": { "meal": [ "Nelj&auml;nviljanpuuroa L,M", "Katkarapusalaattia, leip&auml;&auml; L", "Kermaista porkkanasosekeittoa G,VL", "Op.leip&auml;at.: Kalkkunapatonki VL" ] }, "friday": { "meal": [ "Riisipuuroa VL,G", "Chorizosalaattia, leip&auml;&auml; VL", "Sellerisosekeittoa VL", "Op.leip&auml;at.: Juustopatonki VL", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Puu", "url": "http:\/\/www.amica.fi\/Puu2#Ruokalista", "info": "", "location": { "address": "Tekniikantie 3, Espoo", "lat": "60.1807464", "lng": "24.8246464", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Jauhelihapihvej&auml; italialaisittain (G, L, M),Pennepastaa (L, M)", "Herkkusieni-perunapannua (G, L, M)", "Mansikkarahkaa kerroksittain (G, L)" ] }, "tuesday": { "meal": [ "Lihamakaronilaatikkoa (*, VL),Tomaattiketsuppia (G, L, M)", "&Aacute; la carte: Yrttist&auml; porsaanfileet&auml; (*, G, L, M),Pippurikastiketta (VL),Maalaislohkoperunoita (G, L, M)", "Kuskus-kasvispihvej&auml; (L),Kurkkuraitaa (G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Hedelm&auml;salaattia (G, L, M),Kermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Pyttipannua ja paistettu kananmuna (G, L, M)", "&Aacute; la carte: Juustokuorrutettu broilerinfilee (L),Rakuunakastiketta (VL),Pilahviriisi&auml; (G, L, M)", "Papu-linssicurrya (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M),", "Ruusunmarjakiisseli&auml; (G, L, M),Kermavaahtoa (G, L)" ] }, "thursday": { "meal": [ "Chili con carnea jauhelihasta (G, L, M),H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "Vihannespastaa (*, L, M)", "Kirkasta kahden kalan keittoa (G, L, M)", "Hedelm&auml;rahkaa (G, L)" ] }, "friday": { "meal": [ "Meetwursti-ananaspannupizzaa (L)", "Pinaatti-kasvispataa ja jogurttia (*, G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Appelsiini-mandariiniriisi&auml; (G, L)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "T\u00e4ff\u00e4", "url": "http:\/\/www.teknologforeningen.fi\/index.php\/fi\/taman-viikon-ruokalista", "info": "", "location": { "address": "Otakaari 22, Espoo", "lat": "60.1858857", "lng": "24.83245", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Riistak\u00e4ristys, perunamuhennos g", "Sienik\u00e4\u00e4ryleet l g", "Mozzarellasalaatti vl g", "Kukkakaalikeitto l g", "A&#039;la Carte: T\u00e4ff\u00e4nleike l g" ] }, "tuesday": { "meal": [ "Kana marengo l g", "Kasvispihvit, omena-kermaviilikastike", "Kanasalaatti l g", "Kasvis-seljanka l g", "A&#039;la Carte: Kalifornianleike l" ] }, "wednesday": { "meal": [ "Spaghetti bolognese l", "Gorgonzolakastike l", "Kreikkalainen maalaissalaatti vl g", "Minestronekeittoa l", "A&#039;la Carte: Grillipihvi l g" ] }, "thursday": { "meal": [ "Kebab kastikkeella l g", "Chili sin carne l g", "Katkarapusalaatti l g", "Pinaattikeitto, 1\/2 muna l", "A&#039;la Carte: Kanakori l" ] }, "friday": { "meal": [ "Wieninleike, perunamuhennos", "Kasvispihvit, tartarkastike l g", "Pekonisalaatti l g", "Nakkikeitto l g", "A&#039;la Carte: Grillattu lohi, sitrusmajoneesi, lohkoperunat l g" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Kvarkki", "url": "http:\/\/www.amica.fi\/kvarkki#Ruokalista", "info": "", "location": { "address": "Otakaari 3, Espoo", "lat": "60.1883476", "lng": "24.8294072", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1400" }, "tuesday": { "opening_time": "1030", "closing_time": "1400" }, "wednesday": { "opening_time": "1030", "closing_time": "1400" }, "thursday": { "opening_time": "1030", "closing_time": "1400" }, "friday": { "opening_time": "1030", "closing_time": "1300" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Jauhelihapihvej&auml; italialaisittain (G, L, M),Pennepastaa (L, M)", "&Aacute; la carte: Chilipaahdettua lohta (G, L, M),Chili-kermaviilikastiketta (G, L),Perunasosetta (*, G, VL)", "Herkkusieni-perunapannua (G, L, M)", "Bataattisosekeittoa (G, VL)", "Kalkkuna-mangosalaattia (*, L, M)", "L&auml;mmin broilerinfilee-ananasleip&auml; (L)", "Mansikkarahkaa kerroksittain (G, L)" ] }, "tuesday": { "meal": [ "Lihamakaronilaatikkoa (*, VL),Tomaattiketsuppia (G, L, M)", "&Aacute; la carte: Yrttist&auml; porsaanfileet&auml; (*, G, L, M)Pippurikastiketta (VL),Maalaislohkoperunoita (G, L, M)", "Kuskus-kasvispihvej&auml; (L),Kurkkuraitaa (G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Papu-kasviskeittoa (G)", "Kylm&auml;savukirjolohisalaattia (G, L)", "Sinihomejuusto-broilerit&auml;ytteisi&auml; ohukaisia,P&auml;&auml;ryn&auml;ist&auml; kermaviilikastiketta (G, L)", "Hedelm&auml;salaattia (G, L, M),Kermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Pyttipannua ja paistettu kananmuna (G, L, M)", "&Aacute; la carte: Juustokuorrutettu broilerinfilee (L),Rakuunakastiketta (VL),Pilahviriisi&auml; (G, L, M)", "Papu-linssicurrya (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Tomaattikeittoa ja fetajuustoa (G, VL)", "Leip&auml;juustosalaattia (G, VL)", "Ananashampurilainen (L, M)", "Paholaisen kastikketta, Ranskalaisia perunoita (G, L, M)", "Ruusunmarjakiisseli&auml; (G, L, M),Kermavaahtoa (G, L)" ] }, "thursday": { "meal": [ "Chili con carnea jauhelihasta (G, L, M),H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "&Aacute; la carte: Wieninleike Amican tapaan (L, M)Perunasosetta (*, G, VL)", "Vihannespastaa (*, L, M)", "Kirkasta kahden kalan keittoa (G, L, M)", "Nizzalaista tonnikalasalaattia (G, L, M)", "Broileritacoja ja smetanaa (G, L)Tomaatti-jalopenosalsaa (*, G, L, M)", "Hedelm&auml;rahkaa (G, L)" ] }, "friday": { "meal": [ "Meetwursti-ananaspannupizzaa (L)", "&Aacute; la carte: Paistettuja muikkuja (L, M),Perunasosetta (*, G, VL),Tilli-kermaviilikastiketta (G, L)", "Pinaatti-kasvispataa ja jogurttia (*, G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Juustoista kikhernekeittoa (VL)", "Katkarapusalaattia (*, G, L)", "Appelsiini-mandariiniriisi&auml; (G, L)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Silinteri", "url": "http:\/\/www.amica.fi\/silinteri#Ruokalista", "info": "Henkil\u00f6kuntaravintola, ei opiskelijahintoja", "location": { "address": "Otakaari 1, Espoo", "lat": "60.1869326", "lng": "24.8272611", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1045", "closing_time": "1330" }, "tuesday": { "opening_time": "1045", "closing_time": "1330" }, "wednesday": { "opening_time": "1045", "closing_time": "1330" }, "thursday": { "opening_time": "1045", "closing_time": "1330" }, "friday": { "opening_time": "1045", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Kalkkunasalaattia, leip&auml;&auml; L", "Kermaista purjo-perunasosekeittoa G,VL", "Lindstr&ouml;minpihvit, ruskeaa kastiketta, keitettyj&auml; perunoita G", "Uuniperuna feta-oliivit&auml;ytteell&auml; L", "A la carte: sinihomejuusto-ananaslohta, tilliperunoita, hunaja-kirveliporkkanoita G", "Puolukkarahka G,VL" ] }, "tuesday": { "meal": [ "Tomaatti-mozzarellasalaattia, leip&auml;&auml; VL", "Kinkkuminestronea L,M", "Janssoninkiusausta G,VL", "Bataatti-kikhernecurrya G,L,M", "A la carte: Mets&auml;st&auml;j&auml;nleike Amican tapaan, lohkoperunoita, paprika-punasipulia VL", "Aprikoosikiisseli&auml;, kermavaahtoa G,L" ] }, "wednesday": { "meal": [ "Kylm&auml;savukirjolohisalaattia, leip&auml;&auml; L", "Pinaattikeittoa ja kananmuna", "Jauheliha-tomaattipannupizaa L", "Kasviksia currykastikeessa, riisi&auml; *,G,L,M", "A la carte: Kievin kanaa, tummaa hunajakastiketta, jasmiiniriisi&auml; VL", "Mansikkasmoothieta G" ] }, "thursday": { "meal": [ "Katkarapusalaattia, leip&auml;&auml; *,L", "Kermaista porkkanasosekeittoa G,VL", "Broilerilasagnea VL", "Kasvisbolognesea, t&auml;ysjyv&auml;spagettia L,M", "A la carte: Bratwursteja, punaviinikastiketta, haudutettua hapankaalia, curryperunat G", "Mokka-mandariinivaahtoa G,L" ] }, "friday": { "meal": [ "Chorizo-salaattia, leip&auml;&auml; VL", "Sellerisosekeittoa G,VL", "Sitruunaseiti&auml;, perunasosetta G,VL", "Juurespihvej&auml;, jogurtti-basilikakastiketta, perunoita G,L", "A la carte: porsaanleike Amican tapaan, perunasosetta VL", "Kuningatarkiisseli&auml;, kermavaahtoa G,L", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Cantina", "url": "http:\/\/www.sodexo.fi\/cantina", "info": "Opiskelija-alennus 10%, lounas arkisin klo 11-14", "location": { "address": "Otakaari 24, Espoo", "lat": "60.1847778", "lng": "24.8309887", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "2230" }, "tuesday": { "opening_time": "1100", "closing_time": "2230" }, "wednesday": { "opening_time": "1100", "closing_time": "2230" }, "thursday": { "opening_time": "1100", "closing_time": "2230" }, "friday": { "opening_time": "1100", "closing_time": "2230" }, "saturday": { "opening_time": "1100", "closing_time": "2200" } }, "menu": { "monday": { "meal": [ "&nbsp;\n Kievinkanaa, jogurttikastiketta ja riisi\u00e4", "4,95 &euro;7,60 &euro;\n \n \n L\n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelm\u00e4inen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "tuesday": { "meal": [ "&nbsp;\n Jauhelihapihvej\u00e4, kermaista pippurikastiketta ja lohkoperunoita", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelm\u00e4inen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "wednesday": { "meal": "" }, "thursday": { "meal": "" }, "friday": { "meal": "" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.amica.fi\/laureaotaniemi#Ruokalista", "info": "", "location": { "address": "Mets\u00e4npojankuja 3, Espoo", "lat": "60.1858113", "lng": "24.8054439", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1315" }, "tuesday": { "opening_time": "1100", "closing_time": "1315" }, "wednesday": { "opening_time": "1100", "closing_time": "1315" }, "thursday": { "opening_time": "1100", "closing_time": "1315" }, "friday": { "opening_time": "1100", "closing_time": "1300" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Tonnikala-pinaattilasagnettea (VL)", "Jogurttista linssi-kasvismuhennosta (*, G),Jasminriisi&auml; (G, L, M)", "Kasvisborssikeittoa (*, G, L, M)" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml; (L, M),Omena-currykastiketta (VL),Ruis-riisi&auml; (*, L, M)", "&Agrave; la carte: Mets&auml;st&auml;j&auml;nleike (VL),Lohkoperunoita (G, L, M)", "Bataatti-kikhernecurrya (*, G, L, M),Ruis-riisi&auml; (*, L, M)", "Sienikeittoa" ] }, "wednesday": { "meal": [ "Uunimakkaraa juustot&auml;ytteell&auml; (G, L),Perunasosetta (*, G, VL)", "&Agrave; la carte: Seesampaneroitu broilerinfilee (*, L, M),Tummaa hunajakastiketta (G, L, M),Tummaa riisi&auml; (G, L, M)", "Juurespihvej&auml; (*, G, L, M),Jogurtti-basilikapestokastiketta (G, L)", "Pinaattikeittoa ja kananmuna" ] }, "thursday": { "meal": [ "Kanaviillokkia (VL),Riisi&auml; (G, L, M)", "&Agrave; la carte: Smetanalohta ja kes&auml;kurpitsaa (G, VL),Keitettyj&auml; tilliperunoita (*, G, L, M)", "Kasvisbolognesea (*, G, L, M),T&auml;ysjyv&auml;spagettia (L, M)", "Porkkanasosekeittoa (G, VL)" ] }, "friday": { "meal": [ "Jauheliha-pastapataa (*, L, M)", "Kasviksia currykastikkeessa (*, G, L, M),Tummaa riisi&auml; (G, L, M)", "Sellerisosekeittoa ja paahdettuja siemeni&auml; (G, VL)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } } ] }, { "name": "T\u00f6\u00f6l\u00f6", "restaurant": [ { "name": "Rafla", "url": "http:\/\/www.amica.fi\/rafla#Ruokalista", "info": "", "location": { "address": "Runeberginkatu 14, Helsinki", "lat": "60.1715087", "lng": "24.9239127", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1615" }, "tuesday": { "opening_time": "1030", "closing_time": "1615" }, "wednesday": { "opening_time": "1030", "closing_time": "1615" }, "thursday": { "opening_time": "1030", "closing_time": "1615" }, "friday": { "opening_time": "1030", "closing_time": "1615" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Kalkkuna-ananaspataa (G, VL)H&ouml;yrytetty&auml; t&auml;ysjyv&auml;vehn&auml;&auml; (L, M)", "Lohilaatikkoa (G)", "Holsteininleike (L, M)Juustoperunoita (G, VL)H&ouml;yrytetty&auml; parsakaalia (G, L, M)", "Bataatti-kookoscurrya (G, L, M)H&ouml;yrytetty&auml; t&auml;ysjyv&auml;vehn&auml;&auml; (L, M)", "Kermaista purjo-perunasosekeittoa (G, VL)", "Mustikkarahkaa (G, L)" ] }, "tuesday": { "meal": [ "Tonnikalakastiketta (L, M)T&auml;ysjyv&auml;spagettia (L, M)", "Riista-sipulipataa (*, G, L)Perunasosetta (*, G, VL)", "Kalkkunapihvi (G, L, M)Sahramikastiketta (G, L)Curryperunoita (G, L, M)", "Pinaattiohukaisia (L)Puolukkahilloa (G, L, M)Perunasosetta (*, G, VL)", "Tomaattista papukeittoa (G, L, M)", "Vaniljakiisseli&auml; (G)Mansikkahilloa (G, L, M)" ] }, "wednesday": { "meal": [ "Purjosipuliseiti&auml; (*, G, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Chili con carnea (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Seesampaneroitu broilerinfilee (*, L, M)Tummaa hapanimel&auml;kastiketta (G, L, M)", "Kasviksia soija-kurkumakastikkeessa (G, L, M)", "Kasvislasagnettea (VL)", "Herkkusienikeittoa (G, VL)", "Appelsiini-viikunasalaattia (G, L, M)Kinuskikermavaahtoa (G)" ] }, "thursday": { "meal": [ "Jauheliha-pennepataa (L, M)", "Yrttinen broilerinkoipi (*, G, L, M)Jogurtti-ananaskastiketta (G, L)", "Wieninleike (L, M)Perunasosetta (*, G, VL)", "Meksikolaista maissi-kasvish&ouml;yst&ouml;&auml; (*, G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Linssisosekeittoa (G, VL)", "Puolukkap&auml;&auml;ryn&auml;&auml; (G, L, M)Kinuskikermavaahtoa (G)" ] }, "friday": { "meal": [ "Riisi&auml;, kasviksia ja kebablihaa (*, G, L, M)Chili-kermaviilikastiketta (G, L)", "Broilericurrya (G, L)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Juusto-paprikakuorrutettua lohta (VL)Keitettyj&auml; tilliperunoita (*, G, L, M)", "Linssipihvej&auml; (G, L, M)Currymajoneesia (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kermaista bataatti-maissisosekeittoa (G, VL)", "Hedelm&auml;rahkaa kerroksittain (G, L)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Chydenia", "url": "http:\/\/www.amica.fi\/chydenia#Ruokalista", "info": "", "location": { "address": "Runeberginkatu 22, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Tonnikala-pinaattilasagnettea (VL)", "Smetanaista naudanlihapataa (L)Keitettyj&auml; perunoita (*, G, L, M)", "Fetajuusto-oliivit&auml;ytett&auml; uuniperunalle (G)Uuniperuna (*, G, L, M)", "Kermaista purjo-perunasosekeittoa (G, VL)" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml; (L, M)Omena-currykastiketta (VL)Ruis-riisi&auml; (*, L, M)", "Mets&auml;st&auml;j&auml;nleike (VL)Lohkoperunoita (G, L, M)", "Bataatti-kikhernecurrya (*, G, L, M)Ruis-riisi&auml; (*, L, M)", "Kasvisborssikeittoa (*, G, L, M)" ] }, "wednesday": { "meal": [ "Kaali-jauhelihalaatikkoa (*, G, L, M)Puolukkahilloa (G, L, M)", "Sinihomejuusto-ananaslohta (G, VL)Keitettyj&auml; tilliperunoita (*, G, L, M)", "Juurespihvej&auml; (*, G, L, M)Jogurtti-basilikapestokastiketta (G, L)T&auml;ysjyv&auml;ohraa (*, L, M)", "Pinaattikeittoa ja kananmuna" ] }, "thursday": { "meal": [ "Uunimakkaraa juustot&auml;ytteell&auml; (G, L)Perunasosetta (*, G, VL)", "Sitruunakuorrutettua seiti&auml; (*, L, M)Perunasosetta (*, G, VL)", "Kasvisbolognesea (*, G, L, M)T&auml;ysjyv&auml;spagettia (L, M)", "Kermaista porkkanasosekeittoa (G, VL)" ] }, "friday": { "meal": [ "Tomaattista seitipataa (*, G, L, M)Keitettyj&auml; perunoita (*, G, L, M)", "Pepperonipizzaa (L)", "Kasviksia currykastikkeessa (*, G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Sellerisosekeittoa ja paahdettuja siemeni&auml; (G, VL)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Hanken", "url": "http:\/\/www.amica.fi\/hanken#Ruokalista", "info": "", "location": { "address": "Arkadiankatu 22, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1500" }, "tuesday": { "opening_time": "1100", "closing_time": "1500" }, "wednesday": { "opening_time": "1100", "closing_time": "1500" }, "thursday": { "opening_time": "1100", "closing_time": "1500" }, "friday": { "opening_time": "1100", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Broileri-juustokastiketta (*, G, VL)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Yrttisi&auml; kalapaloja (*, L, M)Tartarkastiketta (G, L)Keitettyj&auml; perunoita (*, G, L, M)", "Riistak&auml;ristyst&auml; (*, G, L, M)Puolukkahilloa (G, L, M)Perunasosetta (*, G, VL)", "Mausteista soijakiusausta (*, G, VL)", "Kalkkunasalaattia (*, G, L)" ] }, "tuesday": { "meal": [ "Kinkku-tuorejuustokastiketta pastalle (G, VL)T&auml;ysjyv&auml;kierrepastaa (*, L, M)", "Jauhemaksapihvej&auml; (G, L, M)Puolukkahilloa (G, L, M)Sipulikastiketta (*, VL)", "Espanjalaista pinaatti-oliivimunakasta (*, G, L)Papumuhennosta (G, L, M)", "Kirkasta lohikeittoa (G, L, M)", "Katkarapusalaattia (*, G, L)" ] }, "wednesday": { "meal": [ "Naudanlihaa sipuli-seesamkastikkeessa (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Lohipataa (*, G, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Broileria currykastikkeessa (G, VL)Valkosipuliriisi&auml; (G, L, M)", "Kukkakaali-perunacurrya (*, G, L, M)T&auml;ysjyv&auml;ohraa (*, L, M)", "Kreikkalainen salaatti (G)" ] }, "thursday": { "meal": [ "Lohipy&ouml;ryk&ouml;it&auml; (L, M)Tillikastiketta (*, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Lihamureketta (G, L, M)Pippurikastiketta (VL)Keitettyj&auml; perunoita (*, G, L, M)", "Kermaista hernesosekeittoa (G, VL)Hienonnettua sipulia (G, L, M)PannukakkuaMansikkahilloa (G, L, M)", "Hernekeittoa (G, L, M)Hienonnettua sipulia (G, L, M)PannukakkuaMansikkahilloa (G, L, M)", "Kinkku-pastasalaattia (L)" ] }, "friday": { "meal": [ "Kinkkupizza (L)", "Meetvurstipizzaa (L)", "Tonnikalapizzaa (L)", "Kasvispizzaa (L)", "Naudanlihapastaa kreikkalaisittain (*, L)", "Kasviksia seesamkastikkeessa (*, G, L, M)Nuudeleita (L, M)", "Texmex-maustettua broilerinfileesalaattia (*, G, L)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Sibelius-Akatemia \/ R-Talo", "url": "http:\/\/www.amica.fi\/r-talo#Ruokalista", "info": "", "location": { "address": "Pohjoinen Rautatienkatu 9, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1530" }, "saturday": { "opening_time": "1100", "closing_time": "1330" } }, "menu": { "monday": { "meal": [ "Jauhelihakastiketta (*, L, M),V&auml;rik&auml;st&auml; pennepastaa (L, M)", "Sinihomejuusto-ananaslohta (G, VL),Keitettyj&auml; tilliperunoita (*, G, L, M),Hunaja-kirveliporkkanoita (G, VL)", "Fetajuusto-oliivit&auml;ytett&auml; uuniperunalle (G),Uuniperuna (*, G, L, M)", "Puolukkarahkaa kerroksittain (G, L)" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml; (L, M),Omena-currykastiketta (VL),Ruis-riisi&auml; (*, L, M)", "Janssoninkiusausta (G, VL)", "Bataatti-kikhernecurrya (*, G, L, M),Ruis-riisi&auml; (*, L, M)", "Aprikoosikiisseli&auml; (G, L, M),Laktoositonta kermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Pippurista naudanlihakastiketta (*, G, L, M),Keitettyj&auml; perunoita (*, G, L, M)", "Kalkkunapihvi (G, L, M),Tummaa hunajakastiketta (G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kasviksia soija-kurkumakastikkeessa (G, L, M)", "Pinaattikeittoa ja kananmuna", "Mansikka-kookospannacottaa (G, L)" ] }, "thursday": { "meal": [ "Sitruunakuorrutettua seiti&auml; (*, L, M),Perunasosetta (*, G, VL)", "Broileri-kasvisvuokaa (*, G, VL)", "Kasvisbolognesea (*, G, L, M),T&auml;ysjyv&auml;spagettia (L, M)", "Mokka-mandariinivaahtoa (G, L)" ] }, "friday": { "meal": [ "Liha-perunapannua meksikolaisittain (G, L, M),Chili-kermaviilikastiketta (G, L)", "Kasviksia currykastikkeessa (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Siikakeittoa (*, G, L, M)", "Limetorttu (L),Vaniljakermavaahtoa (G, L)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.amica.fi\/r-talo#Ruokalista", "info": "", "location": { "address": "T\u00f6\u00f6l\u00f6nkatu 28, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1600" }, "saturday": { "opening_time": "1100", "closing_time": "1330" } }, "menu": { "monday": { "meal": [ "Kinkkukiusausta (G, VL)", "Madras Chicken broileria (G,VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kasviskiusausta (G, VL)", "Kasvisminestronea (*, L, M)", "Mansikkarahkaa kerroksittain (G, L)" ] }, "tuesday": { "meal": [ "Seiti&auml; japanilaisittain (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Yrttist&auml; porsaanfileet&auml; (*, G, L, M),Pippurikastiketta (VL),Maalaislohkoperunoita (G, L, M)", "Paprika-punasipulilis&auml;kett&auml; (G, L, M)", "Kuskus-kasvispihvej&auml; (L),Kurkkuraitaa (G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Papu-kasviskeittoa (G,VL)", "Valkosuklaamoussea (G)" ] }, "wednesday": { "meal": [ "Naudanlihaa punacurrykastikkeessa (G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Juustokuorrutettu broilerinfilee (L),Rakuunakastiketta (VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Paahdettuja punajuuria (G, L, M)", "Papu-linssicurrya (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kirkasta lohikeittoa (G, L, M)", "Ruusunmarjakiisseli&auml; (G, L, M),Laktoositonta kermavaahtoa (G, L)" ] }, "thursday": { "meal": [ "Kalkkuna-pastavuokaa (*, L)", "Chilipaahdettua lohta (G, L, M),Chili-kermaviilikastiketta (G, L),Perunasosetta (*, G, VL)", "H&ouml;yrytettyj&auml; pikkuporkkanoita ja parsakaalia (G, L, M)", "Juusto-kasvispataa (*, G, VL),Keitettyj&auml; perunoita (*, G, L, M)", "Bataatti-kookossosekeittoa ja linssej&auml; (G, L, M)", "Appelsiinirahkahyytel&ouml;&auml; (G, L)" ] }, "friday": { "meal": [ "Kalamurekepihvej&auml; Amican tapaan (L, M),Kananmuna-tillikastiketta (VL),Keitettyj&auml; perunoita (*, G, L, M)", "Chili con carnea jauhelihasta (G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Pinaatti-kasvispataa ja jogurttia (*, G, L),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Omenakiisseli&auml; (G, L, M),Kanelikermavaahtoa (G, L)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.hys.net\/opiskelijapalvelut\/osakuntabaari\/ruokalista", "info": "", "location": { "address": "Urho Kekkosen katu 4-6 D, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1530" }, "tuesday": { "opening_time": "1100", "closing_time": "1530" }, "wednesday": { "opening_time": "1100", "closing_time": "1530" }, "thursday": { "opening_time": "1100", "closing_time": "1530" }, "friday": { "opening_time": "1100", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Broilerinuggetit", "Kasviscannelonit", "Lihakeitto" ] }, "tuesday": { "meal": [ "Lohimurekepihvit", "Chili con carne", "Bataattikeitto" ] }, "wednesday": { "meal": [ "Riistakiusaus", "Pinaattiohukaiset", "Broileri-pastakeitto" ] }, "thursday": { "meal": [ "Tomaattisilakat", "Lihapy\u00f6ryk\u00e4t", "Nuudeli-kasviskeitto" ] }, "friday": { "meal": [ "Kalkkunaleike", "Linssipihvi", "Keitto", "&nbsp;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } } ] }, { "name": "Arabia", "restaurant": [ { "name": "Kipsari", "url": "http:\/\/www.kipsari.com\/menu.php", "info": "", "location": { "address": "H\u00e4meentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "800", "closing_time": "1900" }, "tuesday": { "opening_time": "800", "closing_time": "1900" }, "wednesday": { "opening_time": "800", "closing_time": "1900" }, "thursday": { "opening_time": "800", "closing_time": "1900" }, "friday": { "opening_time": "800", "closing_time": "1900" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "" }, "tuesday": { "meal": "" }, "wednesday": { "meal": "" }, "thursday": { "meal": "" }, "friday": { "meal": "" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Meccala", "url": "http:\/\/www.amica.fi\/meccala#Ruokalista", "info": "", "location": { "address": "H\u00e4meentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1345" }, "tuesday": { "opening_time": "1030", "closing_time": "1345" }, "wednesday": { "opening_time": "1030", "closing_time": "1345" }, "thursday": { "opening_time": "1030", "closing_time": "1345" }, "friday": { "opening_time": "1030", "closing_time": "1345" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Jauhelihakastiketta (*, L, M)Keitettyj&auml; perunoita (*, G, L, M)", "Fetajuusto-oliivit&auml;ytett&auml; uuniperunalle (G)Uuniperuna (*, G, L, M)", "Kermaista purjo-perunasosekeittoa (G, VL)" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml; (L, M)Omena-currykastiketta (VL)", "H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Bataatti-kikhernecurrya (*, G, L, M)Ruis-riisi&auml; (*, L, M)", "Kasvisborssikeittoa (*, G, L, M)" ] }, "wednesday": { "meal": [ "Kalkkunaa rakuunakastikkeessa (*, G, VL)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Juurespihvej&auml; (G, L, M)Jogurtti-basilikapestokastiketta (G, L)", "T&auml;ysjyv&auml;ohraa (*, L, M)", "Pinaattikeittoa ja kananmuna" ] }, "thursday": { "meal": [ "Tomaattista lohipataa (*, G, L, M)Perunasosetta (*, G, VL)", "Kasvisbolognesea (*, G, L, M)T&auml;ysjyv&auml;spagettia (L, M)", "Kermaista porkkanasosekeittoa (G, VL)" ] }, "friday": { "meal": [ "Jauheliha-pastapataa (*, L, M)", "Kasviksia currykastikkeessa (*, G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Tomaattikeittoa (G, L, M)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.antell.fi\/docs\/lunch.php?Arabiakeskus,%20Helsinki", "info": "T\u00e4hdell\u00e4 merkityt opiskelijahintaan", "location": { "address": "H\u00e4meentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "*Tomaatti-vuohenjuustokeittoa (VL)", "*Nakkikastiketta ja perunamuusia (VL)", "Lindstr\u00f6min pihvit sipulikastiketta (VL)", "*Uuniperunaa feta-kasvist\u00e4ytett\u00e4 (VL G)", "Salaattibuffet: Juustovalikoima", "Hedelm\u00e4salaattia (L G M)", "&nbsp;&nbsp;" ] }, "tuesday": { "meal": [ "*Kasvisborchkeittoa ja smetanaa (VL G)", "*Juustoista riistakeittoa (VL G)", "Tulista kookoskanakastiketta (L M)", "*Kasvismoussakaa (VL G)", "Salaattibuffet:Katkarapuja", "Kuningatarpaistosta (VL)", "&nbsp;&nbsp;" ] }, "wednesday": { "meal": [ "*Maa-artisokkakeittoa (VL G)", "*Jauhelihalasagnea (VL)", "Paistettua maksaa ja puolukkaa (VL)", "*Sienik\u00e4\u00e4ryleet (L G M)", "Salaattibuffet: Kanaa", "Raparperirahkaa", "&nbsp;&nbsp;" ] }, "thursday": { "meal": [ "*Juuressosekeittoa (VL G)", "*Hernekeittoa ja luomukasviskeittoa (L G M)", "Limettilohta (VL G)", "*Papu-porkkanakiusausta (VL G)", "Salaattibuffet: Tonnikalaa", "Pannukakkua ja hilloa (VL)", "&nbsp;&nbsp;" ] }, "friday": { "meal": [ "*Sienikeittoa (VL G)", "*Lohilaatikkoa (VL G)", "Jauhelihatortillat (L M)", "*Pinaattilettuja ja puolukkaa (VL)", "Salaattibuffet: Fetaa", "Minimuffinssi ja kahvi", "T\u00e4hdell\u00e4 merkityt opiskelijahintaan.", "Kela tukee korkeakouluopiskelijoiden", "ruokailua \u0080p\u00e4iv\u00e4ateria. Tuen saa", "esitt\u00e4m\u00e4ll\u00e4 voimassa olevan opiskelijakortin", "&nbsp;&nbsp;", "&nbsp;" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } } ] }, { "name": "Kumpula", "restaurant": [ { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php\/Kumpula\/Chemicum\/", "info": "", "location": { "address": "Gustaf H\u00e4llstr\u00f6min katu 2, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Kalaburgerpihvit,, pinaattikastiketta (l)Chili-porsaspataa (g,l,v)Kasvispy\u00f6ryk\u00e4t,, pinaattikastiketta (k,l,p\u00e4)P\u00e4hkin\u00e4ist\u00e4 juustosalaattia (g,k,l,p\u00e4)Vadelmarahkaa (g,k,l) 1,20&euro;" }, "tuesday": { "meal": "H\u00e4rk\u00e4\u00e4 cafe de paris kastikkeessa (vl)Rapea seitipala, chilidippi (l)Bataatti-papuh\u00f6yst\u00f6\u00e4 (g,l,v,ve)Broileri-vehn\u00e4njyv\u00e4salaatti (l,p\u00e4,v)Herkkusienikeittoa (k)" }, "wednesday": { "meal": "Hunajaista broilerinleikett\u00e4, ananaschutneyt\u00e4 (g,l)Lihapy\u00f6ryk\u00f6it\u00e4, ruskeaa kastiketta (l,v)Kasvispilahvia, tomaattikastiketta (k,l,v,ve)Lohi-pastasalaatti (l)Parsakeittoa (k,vl)" }, "thursday": { "meal": "Savustettua lohta, tartar-kastiketta (g,l)Broileri-mango-juustokastiketta (l)Hernekeittoa (g,l), pannukakkua ja hilloaKasvishernekeittoa (g,k,l,ve), pannukakkua ja hilloaLeip\u00e4juustosalaatti (g,k)Kasvishernekeittoa (g,k,l,ve)Pannukakkua ja hilloa (k) 1,00&euro;" }, "friday": { "meal": "Tex Mex- silakat (g,vl)Jauhelihabolognaisea (g,l,p\u00e4,v)Soijabolognaisea (g,k,l,v,ve)" }, "saturday": { "meal": "HAUSKAA VIIKONLOPPUA !" }, "sunday": { "meal": "HAUSKAA VIIKONLOPPUA !" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php\/Kumpula\/Exactum\/", "info": "", "location": { "address": "Gustaf H\u00e4llstr\u00f6min katu 2, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Chili-porsaspataa (g,l,v)Tofu-perunalaatikkoa (k,l,v,ve)Kuhapy\u00f6ryk\u00e4t, pinaattikastikettaRiistasalaattia (g,l)Mandariinirahka 1,20&euro;" }, "tuesday": { "meal": "Jauhelihakastiketta, juustoraastetta (l,v)Bataatti-papuh\u00f6yst\u00f6\u00e4 (g,l,v,ve)Kalaburgerpihvit, tilli-kermaviilikastiketta (l)Leip\u00e4juustosalaatti (g,k)Kerroskiisseli 1,20&euro;" }, "wednesday": { "meal": "Kaalik\u00e4\u00e4ryleit\u00e4, ruskeakastiketta (l)Kalakastiketta thaimaalaisittain (g,l,v)Kasvispilahvia, tomaattikastiketta (k,l,v,ve)Broileri-vehn\u00e4njyv\u00e4salaatti (l,p\u00e4,v)Mustikkapiirakka 1,40&euro;" }, "thursday": { "meal": "Kasvis-kvinoapihvit, kylm\u00e4 hernekastike (g,k,l,v)Smetanasilakat (g,l)Broileria mango-juustokastikkeessaKylm\u00e4savulohisalaatti (g,l)Mokka-suklaamousse 1,20&euro;" }, "friday": { "meal": "Broileripy\u00f6ryk\u00e4t, currykastiketta (vl)Soijabolognaisea (g,k,l,v,ve)P\u00e4hkin\u00e4ist\u00e4 juustosalaattia (g,k,l,p\u00e4)Puolukka-kinuskiunelma 1,20&euro;" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php\/Kumpula\/Valdemar\/", "info": "", "location": { "address": "Teollisuuskatu 23, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1030" }, "tuesday": { "opening_time": "1030", "closing_time": "1030" }, "wednesday": { "opening_time": "1030", "closing_time": "1030" }, "thursday": { "opening_time": "1030", "closing_time": "1030" }, "friday": { "opening_time": "1030", "closing_time": "1030" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Hunajaista lanttupossua (g,l,v)Soija-makaronilaatikkoa (k,l,p\u00e4,ve)Stroganoffia (l)" }, "tuesday": { "meal": "Linssi-kasviskastiketta (g,k,v,vl)Kalkkunarisottoa (g,l,v)" }, "wednesday": { "meal": "Kalakeittoa (g,vl)Kukkakaali-pinaattipannua (g,k,l,p\u00e4,v,ve)" }, "thursday": { "meal": "Broilericurrya (g,l,v)Kasvishernekeittoa soijarouheella (g,k,l,ve)" }, "friday": { "meal": "Lihapy\u00f6ryk\u00f6it\u00e4, ruskeaa kastiketta (l,v)Tofukastiketta (g,k,l,ve)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } } ] }, { "name": "Keskusta", "restaurant": [ { "name": "UniCafe Mets\u00e4talo", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Mets\u00e4talo\/1\/1", "info": "", "location": { "address": "Fabianinkatu 39, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Possu-juurespata (g,vl)Soija-kasvispannua (g,k,l,ve)LounassalaattiKalagratiini (vl)Mustikkaa ja kauraa (l) 1,20&euro;" }, "tuesday": { "meal": "Jauheliha-kaalilaatikkoa (g,l)Siskonmakkarakeittoa (g,l)Kasvispy\u00f6ryk\u00e4t (k,p\u00e4), ruohosipuli-soijajogurttidippi\u00e4Lounassalaatti" }, "wednesday": { "meal": "Quinoakalaa, yrttikastiketta (g,l,v)Tandoorikalkkunaa (g,l,v)Kasvis-munakoisovuokaa (g,k,l,v,ve)Lounassalaatti" }, "thursday": { "meal": "Hernekeittoa (g,l)Mango-vihannesh\u00f6yst\u00f6\u00e4 (g,k,l,se,v,ve)LounassalaattiKasvishernekeittoa (g,k,l,ve)" }, "friday": { "meal": "Riistahauduke (g,l)Lindstr\u00f6minpihvit, tummaa sipulikastiketta (g)Kasvisohrattoa, aprikoosikastiketta (k,l,se,ve)Lounassalaatti" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Olivia\/1\/2", "info": "", "location": { "address": "Siltavuorenpenger 5, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1500" }, "tuesday": { "opening_time": "1030", "closing_time": "1500" }, "wednesday": { "opening_time": "1030", "closing_time": "1500" }, "thursday": { "opening_time": "1030", "closing_time": "1500" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Mausteista kalapataa (g,l,v)Kasvis-papukroketit, soijajogurttizaziki (g,k,v,ve)Kanakastiketta (se,v,vl), mustaherukkahilloaTomaattikeittoa, raejuustoa (k,vl)Marjarahka (g,k,l) 1,20&euro;" }, "tuesday": { "meal": "Paistettua lohta, valkoviinikastiketta (vl)Jauhelihabolognaisea, juustoraastetta (g,l,p\u00e4,v)Tofu-kaurapastavuokaa (k,l,v,ve)" }, "wednesday": { "meal": "Broilericurrya (g,l,v)Kes\u00e4kurpitsa-linssipaistosta (g,k,l,se,v,ve)Kaalik\u00e4\u00e4ryleit\u00e4, ruskeakastiketta (l)Mets\u00e4sienikeittoa (k)" }, "thursday": { "meal": "Valkosipulit\u00e4ytteinen broilerileike, valkosipulidippi\u00e4 (se,v)Pesto-kasvispastaa (k,l,p\u00e4,v)Mantelikuorrutettua seit\u00e4 (g,p\u00e4,vl)Hernekeittoa (g,l)Kasvishernekeittoa (g,l,ve)" }, "friday": { "meal": "Juustoiset broileripihvit ja currykastiketta (v,vl)Chili-jauhelihapataa (g,l)Kikherne-p\u00e4hkin\u00e4pataa (g,k,l,v,ve)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Porthania\/1\/3", "info": "", "location": { "address": "Yliopistonkatu 3, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1630" }, "tuesday": { "opening_time": "1030", "closing_time": "1630" }, "wednesday": { "opening_time": "1030", "closing_time": "1630" }, "thursday": { "opening_time": "1030", "closing_time": "1630" }, "friday": { "opening_time": "1030", "closing_time": "1630" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Tomaattista makkarakastiketta (l,p\u00e4,v)Kalaburgerpihvit, tilli-kermaviilikastiketta (l)Kikhernekastiketta (g,k,l,ve)Kinkkusalaatti (g,l)Jogurtti-p\u00e4hkin\u00e4herkku (g,k,l,p\u00e4) 1,20&euro;Perunasosetta itseotossa (g,k)" }, "tuesday": { "meal": "Hapanimel\u00e4\u00e4 porsaspataa (g,l,v)Pinaattinen p\u00e4hkin\u00e4-kasvislasagne (k,p\u00e4,v,vl)Smetanasilakat (g,l)Lohi-pastasalaatti (l)" }, "wednesday": { "meal": "Paistettua lohta, tilli-kermaviilikastiketta (g,l)Soijabolognaisea (g,k,l,v,ve)Lihapy\u00f6ryk\u00f6it\u00e4 juustokastikkeessa (l,v)Broileri-ceasarsalaatti (l,v)Pastaa itseotossa" }, "thursday": { "meal": "Kalkkuna-herkkusienipataa (g,vl)Sitruunaiset kalaleikkeet, tilli-kermaviilikastiketta (l)Bataatti-papuh\u00f6yst\u00f6\u00e4 (g,l,v,ve)Kreikkalainen salaatti" }, "friday": { "meal": "Farmarin pihvit, pippurikastikettaSoijapy\u00f6ryk\u00e4t chilitomaattikastikkeessa (g,k,l,v,ve)Lohikiusausta (g,vl)Chili-katkarapusalaatti (g,l)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "UniCafe P\u00e4\u00e4rakennus", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/P\u00e4\u00e4rakennus\/1\/4", "info": "", "location": { "address": "Fabianinkatu 33, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1630" }, "tuesday": { "opening_time": "1030", "closing_time": "1630" }, "wednesday": { "opening_time": "1030", "closing_time": "1630" }, "thursday": { "opening_time": "1030", "closing_time": "1630" }, "friday": { "opening_time": "1030", "closing_time": "1630" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Tonnikala-katkarapukastiketta, pasta (vl)Farmarin pihvit, sipulikastikettaVihannesratatouillea (g,k,l,se,v,ve)Riistakeittoa (g,l)Broileri-pekonicouscoussalaatti (l)Ruishiutalepuuroa, mustikkamehukeittoa (k,l,ve)Puolukka-kinuskirahka (g,k,vl) 1,20&euro;" }, "tuesday": { "meal": "Paistettua lohta, tilli-kermaviilikastiketta (g,l)Tofua ja juureksia (g,k,l,ve)Uunimakkara (g,l,v), perunasosettaTomaattista lihakeittoa (g,l)Tonnikala-perunasalaatti (g,l)Marjaista ruispuuroa (k,l,ve)Ananas-banaanismoothie (g,k,vl) 1,20&euro;" }, "wednesday": { "meal": "Kuhapy\u00f6ryk\u00e4t, pinaattikastikettaKasviswrap, soijajugurttia (k,l,v,ve)Broilerinkoipi, currykastiketta (p\u00e4,v,vl)Aurajuustosalaatti (g,k,l,p\u00e4)Punajuurisosekeittoa, raejuustoa (g,k,l)Riisipuuroa, mansikkakeittoa (g,k)Marjapiirakka ja vaniljakastike (k,vl) 1,40&euro;" }, "thursday": { "meal": "H\u00e4rk\u00e4-nuudeliwokkia (l,v)Kalapihvej\u00e4 ja tilli-kermaviilikastiketta (l)Kidneypapu-munakoisopataa (g,k,l,se,ve)Hernekeittoa (g,l)Katkarapu-melonisalaatti (l)Kasvishernekeittoa (g,k,l,ve)Pannukakkua ja hilloa 1,00&euro;" }, "friday": { "meal": "Riistapy\u00f6ryk\u00f6it\u00e4, rosmariinikastikettaGruusialaista kaalilaatikkoa (g,k,l,v)Tofukastiketta (g,k,l,ve)Kalakeittoa (g,vl)Brie-juustosalaatti (g,k,p\u00e4)Mannapuuroa, mansikkakeittoa (k)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Rotunda\/1\/5", "info": "", "location": { "address": "Unioninkatu 36, Helsinki", "lat": "60.170351", "lng": "24.9506854", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Riistakeittoa (g,l)Vuohenjuusto-pinjansiemensalaatti (g,k,p\u00e4)Luomu Ohrahiutalepuuroa, mustikkakeittoa (k,l,ve)Tomaattikeittoa, raejuustoa (k,vl)Ruusunmarjarahkaa (g,k,l) 1,20&euro;" }, "tuesday": { "meal": "Tomaattista lihakeittoa (g,l)Broileri-couscoussalaatti (l)Peruna-palsternakkakeittoa (g,k,vl)Luomu Kaurapuuroa, mustikkakeittoa (l,ve)Mangosuudelma (g,k,l) 1,20&euro;" }, "wednesday": { "meal": "Oliivi-broilerikeittoa (g,se,v,vl)Punajuurisosekeittoa, raejuustoa (g,k,l)Aurajuustosalaatti (g,k,l,p\u00e4)Marjaista Luomuruispuuroa (k,l,ve)Hedelm\u00e4smoothie (g,k,l) 1,20&euro;" }, "thursday": { "meal": "Hernekeittoa (g,l) ja pannukakkuaKatkarapu-melonisalaatti (l)Kasvishernekeittoa (g,k,l,ve)Mannapuuroa, mansikkakeittoa (k)Kahviherkku (g,k,l) &euro;" }, "friday": { "meal": "Kala-pastakeittoa (vl)Brie-juustosalaatti (g,k,p\u00e4)Nelj\u00e4n viljan puuroa, mansikkakeittoa (k,l,ve)Porkkanasosekeittoa (g,k,p\u00e4)Marjarahka (g,k,l) 1,20&euro;" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "UniC<NAME>&Kom", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Soc&Kom\/1\/15", "info": "", "location": { "address": "Yrj\u00f6-Koskisen katu 3, Helsinki", "lat": "60.1730803", "lng": "24.9525119", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Tonnikala-katkarapukastiketta (l)Jauhelihapihvit, sipulikastikettaVihannesratatouillea (g,k,l,se,v,ve)" }, "tuesday": { "meal": "Paistettua lohta, kermaviili-m\u00e4tikastiketta (g,l)Tomaattista lihakeittoa (g,l)Tofua ja juureksia (g,k,l,ve)" }, "wednesday": { "meal": "Kuhapy\u00f6ryk\u00e4t, pinaattikastikettaBroilerinkoipi, currykastiketta (p\u00e4,v,vl)Kasviswrap, ranskankermaa (k,l,v)Kasviswrap, soijajugurttia (k,l,v,ve)" }, "thursday": { "meal": "Kalapihvit ja tilli-valkoviinikastike (g,l,se)Hernekeittoa (g,l)Kidneypapu-munakoisopataa (g,k,l,se,ve)Kasvishernekeittoa (g,k,l,ve)" }, "friday": { "meal": "Kala-pastakeittoa (vl)Riistapy\u00f6ryk\u00f6it\u00e4, rosmariinikastikettaTofukastiketta (g,k,l,ve)Gruusialaista kaalilaatikkoa (g,k,l,v)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Topelias\/1\/6", "info": "", "location": { "address": "Unioninkatu 38, Helsinki", "lat": "60.1718645", "lng": "24.9504841", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Kalagratiini (g,vl)Possu-juurespata (g,l,v)Soija-kasvispannua (g,k,l,ve)" }, "tuesday": { "meal": "Jauheliha-kaalilaatikkoa (g,l)Kasvispy\u00f6ryk\u00e4t, ruohosipuli-soijajogourttikastike (k,p\u00e4)Siskonmakkarakeittoa (g,l)" }, "wednesday": { "meal": "Quinoakala, yrtikastike (l,v)Tandoorikalkkunaa (g,l,v)Kasvis-munakoisovuokaa (g,k,l,v,ve)" }, "thursday": { "meal": "Hernekeittoa (g,l), pannukakkua ja hilloaKasvishernekeittoa (g,k,l,ve), pannukakkua ja hilloaMango-vihannesh\u00f6yst\u00f6\u00e4 (g,k,l,se,v,ve)" }, "friday": { "meal": "Riistahauduke (g,l)Lindstr\u00f6minpihvit, tummaa sipulikastiketta (g)Kasvisohrattoa, aprikoosikastiketta (k,l,se,ve)" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php?ravintola=8#\/Keskusta\/Valtiotiede\/1\/7", "info": "", "location": { "address": "Unioninkatu 37, Helsinki", "lat": "60.173379", "lng": "24.9506235", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Tonnikala-katkarapukastiketta (l)Jauhelihapihvit, sipulikastikettaVihannesratatouillea (g,k,l,se,v,ve)P\u00e4hkin\u00e4ist\u00e4 juustosalaattia (g,k,l,p\u00e4)Marjoja kinuskikastikkeessa (k,vl) 1,20&euro;Pasta itseotossa." }, "tuesday": { "meal": "Paistettua lohta, tilli-kermaviilikastiketta (g,l)Uunimakkara (g,l,v), perunasosettaTofua ja juureksia (g,k,l,ve)Broileri-vehn\u00e4njyv\u00e4salaatti (l,p\u00e4,v)Mansikkarahka (g,k,l) 1,20&euro;" }, "wednesday": { "meal": "Kuhapy\u00f6ryk\u00e4t, pinaattikastikettaBroilerinkoipi, currykastiketta (p\u00e4,v,vl)Kasviswrap, soijajugurttia (k,l,v,ve)Tonnikala-perunasalaatti (g,l)Mokkamousse (k) 1,20&euro;" }, "thursday": { "meal": "H\u00e4rk\u00e4-nuudeliwokkia (l,v)Kalapihvej\u00e4 ja tilli-kermaviilikastiketta (l)Kidneypapu-munakoisopataa (g,k,l,se,ve)Aurajuustosalaatti (g,k,l,p\u00e4)Suklaakiisseli kermavaahdolla (g,k,l) 1,20&euro;" }, "friday": { "meal": "Riistapy\u00f6ryk\u00f6it\u00e4, rosmariinikastikettaKalakeittoa (g,vl)Tofukastiketta (g,k,l,ve)Katkarapu-melonisalaatti (l)Omenapaistos kermavaahdolla (k,l) 1,20&euro;" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php\/Keskusta\/Ylioppilasaukio\/", "info": "", "location": { "address": "Mannerheimintie 3, Helsinki", "lat": "60.1689111", "lng": "24.9406031", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1900" }, "tuesday": { "opening_time": "1100", "closing_time": "1900" }, "wednesday": { "opening_time": "1100", "closing_time": "1900" }, "thursday": { "opening_time": "1100", "closing_time": "1900" }, "friday": { "opening_time": "1100", "closing_time": "1900" }, "saturday": { "opening_time": "1100", "closing_time": "1800" } }, "menu": { "monday": { "meal": "Jauhelihapihvi\u00e4, BBQ-kastiketta (g,l,p\u00e4,v)Smetanasilakat (g,l)Soijalasagnette (k,l,ve)Kana-juureskeittoa (l,v)LounassalaattiBroilericurrya (g,l,v)" }, "tuesday": { "meal": "Broileria appelsiinikastikkeessa (vl)Porsasta ja nuudelia (l)Punajuurikroketteja, ruohosipuli-soijajogurttikastiketta (l,ve)KatkarapukeittoaLounassalaatti" }, "wednesday": { "meal": "MakaronilaatikkoaSeit\u00e4 pestokastikkeessa (g,p\u00e4,v,vl)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)Nakkikeittoa (g,l,v)Lounassalaatti" }, "thursday": { "meal": "Lohileike purjo-juustot\u00e4ytteell\u00e4, ruohosipulidippi\u00e4 (l)Kasviswrap, ranskankermaa (k,l,v)Kookoskanaa (g,l,se,v)Hernekeittoa (g,l)Kasvishernekeittoa soijarouheella (g,k,l,ve)Lounassalaatti" }, "friday": { "meal": "Paistettua lohta, valkoviinikastiketta (vl)Jauhelihabolognaisea, juustoraastetta (g,l,p\u00e4,v)Soija-kasviskastike (g,k,l,v,ve), juustoraastetta (l)Mausteista broileripataa (g,l,v)LounassalaattiRiisipuuroa, mansikkakeittoa (g,k)" }, "saturday": { "meal": "Rosepippuri-porsaskastiketta (g,l)Tomaatti-palsternakkavuokaa (g,k,l,ve)Broilerikebakot, ananaschutney (l,v)Lounassalaatti" }, "sunday": { "meal": "" } } } ] }, { "name": "Viikki", "restaurant": [ { "name": "UniCafe Biokeskus", "url": "http:\/\/www.unicafe.fi\/index.php\/Viikki\/Biokeskus\/", "info": "", "location": { "address": "Viikinkaari 9, Helsinki", "lat": "60.2269484", "lng": "25.0139846", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1500" }, "tuesday": { "opening_time": "1030", "closing_time": "1500" }, "wednesday": { "opening_time": "1030", "closing_time": "1500" }, "thursday": { "opening_time": "1030", "closing_time": "1500" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Broileriwrap (l,v)Nakkikastiketta (l,v)Lohilasagnea (vl)Vihannespihvit, papusalsaa (g,k,l,se,v,ve)Cheddarsalaatti (k,vl)Banaani-mustikkarahkaa (g,k,l) 1,20&euro;" }, "tuesday": { "meal": "Porsaanleike, ros\u00e9pippurikastiketta (l)Katkarapu-nuudelikeittoa (l,v)Chili-jauhelihapataa (g,l)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)Hedelm\u00e4inen kalkkunasalaatti (l)" }, "wednesday": { "meal": "Burgundin h\u00e4rk\u00e4\u00e4 (l,v)Soijaa thaicurrykastikkeessa (g,k,l,v,ve)Maksa-pekonikastiketta (g,l)Kalaburgerpihvit, tilli-kermaviilikastiketta (l)Meksikolainen jauhelihasalaatti (g,l,p\u00e4,v)" }, "thursday": { "meal": "Falafel-py\u00f6ryk\u00e4t, tzatziki (k,l,se,v)Makkarakeittoa (g,l)Seit\u00e4 pestokastikkeessa (g,p\u00e4,v,vl)Tonnikalasalaatti (g,l)Mustajuurikeittoa, auringonkukan siemini\u00e4 (g,k,vl)" }, "friday": { "meal": "Lohta kapriskastikkeessa (vl)Soijabolognaisea (g,k,l,v,ve)Kebabkastiketta, juustoraastetta (g,l,v)Chili-bataattikeittoa, raejuustoa (g,k,l)" }, "saturday": { "meal": "Hyv\u00e4\u00e4 viikonloppua!" }, "sunday": { "meal": "Hyv\u00e4\u00e4 viikonloppua!" } } }, { "name": "<NAME>", "url": "http:\/\/www.unicafe.fi\/index.php\/Viikki\/Viikuna\/", "info": "Pizza 10:30-14:00", "location": { "address": "Agnes Sj\u00f6bergin katu 2, Helsinki", "lat": "60.230094", "lng": "25.020823", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1430" }, "tuesday": { "opening_time": "1030", "closing_time": "1430" }, "wednesday": { "opening_time": "1030", "closing_time": "1430" }, "thursday": { "opening_time": "1030", "closing_time": "1430" }, "friday": { "opening_time": "1030", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "Kinkku-ananas-aurajuustopizzaFeta-oliivi-sipulipizzaPossu-vihannespannu (g,l,v)Kasvis-kvinoapihvit, kylm\u00e4 hernekastike (g,k,l,v)Yrttikalaa (l)Juustosalaatti (g,k,p\u00e4,vl)Ruusunmarjarahkaa (g,k,l) 1,20&euro;" }, "tuesday": { "meal": "Katkaraput\u00e4ytteinen kalaleike, ruohosipulidippiLihapy\u00f6ryk\u00f6it\u00e4, ruskeaa kastiketta (l,v), perunasosetta (k)Soija-kaalilaatikkoa (g,k,l,ve), puolukkasurvosSuomalainen lohikeitto (g,vl)Broileri-vehn\u00e4njyv\u00e4salaatti (l,p\u00e4,v)Jogurttipannacotta 1,20&euro;" }, "wednesday": { "meal": "Kinkku-paprika-sipulipizzaKolmen juuston pizzaChili-porsaspataa (g,l,v)Bataatti-papuh\u00f6yst\u00f6\u00e4 (g,l,v,ve)Smetanasilakat (g,l)Lohi-pastasalaatti (l)Mansikka-raparperikiisseli 1,20&euro;" }, "thursday": { "meal": "Kasvispilahvia, tomaattikastiketta (k,l,v,ve)Riistasalaattia (g,l)Hernekeittoa (g,l), pannukakkua ja hilloaKasvishernekeittoa soijarouheella (g,k,l,ve), pannukakkua ja hilloaJuustoiset broileripihvit ja currykastikettaKasvishernekeittoa soijarouheella (g,k,l,ve)pannukakkua ja hilloa 1,00&euro;" }, "friday": { "meal": "Salami-ananas-aurajuustopizzaMozzarella-tomaatti-pestopizzaJauhelihabolognaisea, juustoraastetta (g,l,p\u00e4,v)Tonnikala-katkarapukastiketta (l)Kikhernepihvit, soijajogurttikastiketta (g,k,l,v,ve)Leip\u00e4juustosalaatti (g,k)Boysenmarjapaistos, vaniljakastike 1,40&euro;" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "UniCafe Korona", "url": "http:\/\/www.unicafe.fi\/index.php\/Viikki\/Korona\/", "info": "", "location": { "address": "Viikinkaari 11, Helsinki", "lat": "60.2271911", "lng": "25.0123344", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": "NakkikastikettaVihannespihvipihvit, papusalsaa" }, "tuesday": { "meal": "Chili-jauhelihapataaKasviscouscousia, yrtti-tomaattikastiketta" }, "wednesday": { "meal": "Kalaburgerpihvit, tilli-kermaviilikastikettaSoijaa thaicurrykastikkeessa" }, "thursday": { "meal": "Broileri-ananaskastikettaFalafel-py\u00f6ryk\u00e4t, tzatziki" }, "friday": { "meal": "Kebabkastiketta, juustoraastettaSoijabolognaisea" }, "saturday": { "meal": "Hyv\u00e4\u00e4 viikonloppua." }, "sunday": { "meal": "Hyv\u00e4\u00e4 viikonloppua." } } }, { "name": "T\u00e4hk\u00e4", "url": "http:\/\/www.amica.fi\/tahka#Ruokalista", "info": "", "location": { "address": "Koetilantie 7, Helsinki", "lat": "60.2230593", "lng": "25.0206768", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Tonnikala-pinaattilasagnettea (VL)", "Jauhelihakastiketta (*, L, M),Keitettyj&auml; perunoita (*, G, L, M)", "Fetajuusto-oliivit&auml;ytett&auml; uuniperunalle (G),Uuniperuna (*, G, L, M)", "Nakkikeittoa (G, L, M)", "Puolukkarahkaa (G, L)" ] }, "tuesday": { "meal": [ "Broilerpy&ouml;ryk&ouml;it&auml; (L, M),Omena-currykastiketta (VL),Ruis-riisi&auml; (*, L, M)", "Mets&auml;st&auml;j&auml;nleike (VL),Lohkoperunoita (G, L, M)", "Bataatti-kikhernecurrya (*, G, L, M),Ruis-riisi&auml; (*, L, M)", "Kasvisborssikeittoa (*, G, L, M)", "Aprikoosikiisseli&auml; (G, L, M),Laktoositonta kermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Kaali-jauhelihalaatikkoa (*, G, L, M),Puolukkahilloa (G, L, M)", "Kalkkunaa rakuunakastikkeessa (*, G, VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Juurespihvej&auml; (*, G, L, M),Jogurtti-basilikapestokastiketta (G, L)", "Pinaattikeittoa ja kananmuna", "Mansikkakiisseli&auml; (G, L, M),Laktoositonta kermavaahtoa (G, L)" ] }, "thursday": { "meal": [ "Uunimakkaraa juustot&auml;ytteell&auml; (G, L),Perunasosetta (*, G, VL)", "Kampelaa katkaraput&auml;ytteell&auml; (VL),Tartarkastiketta (G, L)", "Kasvisbolognesea (*, G, L, M),T&auml;ysjyv&auml;spagettia (L, M)", "Lihakeittoa (*, G, L, M)", "Pannukakkua,Mansikkahilloa" ] }, "friday": { "meal": [ "Jauheliha-pastapataa (*, L, M)", "Silakkapihvej&auml; (L, M),Tilli-kermaviilikastiketta (G, L),Perunasosetta (*, G, VL)", "Kasviksia currykastikkeessa (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Limetorttu (L),Vaniljakermavaahtoa (G, L)" ] }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } }, { "name": "Ladonlukko", "url": "http:\/\/www.sodexo.fi\/ravintolaladonlukko", "info": "", "location": { "address": "Latokartanonkaari 9, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1430" }, "tuesday": { "opening_time": "1030", "closing_time": "1430" }, "wednesday": { "opening_time": "1030", "closing_time": "1430" }, "thursday": { "opening_time": "1030", "closing_time": "1430" }, "friday": { "opening_time": "1030", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "&nbsp;\n Lihakeitto", "Meat soup", "2,43 &euro;4,70 &euro;5,50 &euro;\n \n \n \n \n &nbsp;\n Chili hampurilainen", "Chili burger", "2,43 &euro;4,70 &euro;5,50 &euro;\n \n \n \n \n Vegetarian\n Soija-kasvislasagnette", "Soybean and vegetable lasagnette", "2,43 &euro;4,70 &euro;5,50 &euro;\n \n \n \n \n Salad garden\n Katkarapusalaatti", "Shrimps salad", "1,93 &euro;4,20 &euro;4,90 &euro;\n \n \n \n \n Grill\n K<NAME>, kermaviili-yrttikastiketta", "Chiken kiev, herb and sour cream sauce", "4,68 &euro;7,20 &euro;8,40 &euro;" ] }, "tuesday": { "meal": "" }, "wednesday": { "meal": "" }, "thursday": { "meal": "" }, "friday": { "meal": "" }, "saturday": { "meal": "" }, "sunday": { "meal": "" } } } ] } ] } } }<file_sep>/public/scripts/geo.js (function(FeedMe) { // Position var position; // Position options accuracy var position_high_accuracy = true; // Position options max age of reading in milliseconds var position_max_age = 30000; // Position options maximum timeout in milliseconds var position_timeout = 27000; // Position watch id var position_watch_id = null; var GEOLOCATION_POSITION_ERROR = 'geolocationChangeErrorEvent'; var GEOLOCATION_POSITION_SUCCESS = 'geolocationChangeSuccessEvent'; var calculateDistance = function(lat1,lon1,lat2,lon2) { var R = 6371; // km (change this constant to get miles) var dLat = (lat2-lat1) * Math.PI / 180; var dLon = (lon2-lon1) * Math.PI / 180; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d; }; // Check online var isOnline = function() { return navigator.onLine; }; // Check geolocation support var haveGeoSupport = function() { return navigator.geolocation; }; // Get current position var currentPosition = function() { navigator.geolocation.getCurrentPosition(geoSuccess, geoError, {enableHighAccuracy: position_high_accuracy, maximumAge: position_max_age, timeout: position_timeout}); }; // Start tracking position changes var trackPositionChanges = function() { if (position_watch_id == null) { position_watch_id = navigator.geolocation.watchPosition(geoSuccess, geoError, {enableHighAccuracy: position_high_accuracy, maximumAge: position_max_age, timeout: position_timeout}); } }; // Stop tracking position changes var stopTrackPositionChanges = function() { if (position_watch_id != null) { navigator.geolocation.clearWatch(position_watch_id); position_watch_id = null; } }; // Successful geolocation update var geoSuccess = function(newPosition) { //$(document).trigger(GEOLOCATION_POSITION_SUCCESS, {position: position}); FeedMe.geo.position = newPosition; console.log("Got position:", newPosition); var lat = newPosition.coords.latitude; var lng = newPosition.coords.longitude; // Update distances to model data if( FeedMe.restaurantsData ) { FeedMe.restaurantsData.each(function(item, index){ item.updateDistance(lat,lng); }); } }; // Geolocation error var geoError = function(error) { // error.code can be: // 0: unknown error // 1: permission denied // 2: position unavailable (error response from locaton provider) // 3: timed out $('body').trigger(GEOLOCATION_POSITION_ERROR, {error: error.code}); console.log("Geolocation error occurred. Error code: " + error.code); }; FeedMe.geo = { isOnline : isOnline, haveGeoSupport : haveGeoSupport, calculateDistance : calculateDistance, position : null }; // When document is ready, get position $(document).ready(function() { currentPosition(); }); })(FeedMe);<file_sep>/public/assets/sampledata/sampleRestaurants.js [ { "name": "Teekkariravintolat", "url": "http://www.sodexo.fi/dipoli", "info": "", "location": { "address": "Otakaari 24, Espoo", "lat": "60.1847778", "lng": "24.8309887", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "1130", "closing_time": "1500" } }, "menu": { "monday": { "meal": [ "" ] }, "tuesday": { "meal": [ "&nbsp;\n Lihapyöryköitä italialaisittain, spaghettia", "Meat balls in tomato and basil sauce with spaghetti", "&nbsp;\n Kasvispyöryköitä tomaatti-basilikakastikkeella", "Vegetable balls with tomato and basil sauce", "&nbsp;\n Metsäsienikeittoa", "Wild mushroom soup", "&nbsp;\n Briejuusto-päärynäsalaatti", "Brie cheese and pear salad" ] }, "wednesday": { "meal": [ "&nbsp;\n Meksikolaista jauhelihakastiketta, pepperonechiliä", "Minced meat sauce mexican style", "&nbsp;\n Papuja Dal makhani, kurkkuraitaa", "Beans Indian style with yoghurt sauce", "G\n \n &nbsp;\n Juuustoista savuriistakeittoa", "Smoked game soup with cheese", "&nbsp;\n Pesto-broilersalaattia", "Chicken salad with pesto", "L\n \n &nbsp;\n A la carte: Grillattua lohta tartarkastikkeella", "A la carte: Grilled salmon with tartare sauce" ] }, "thursday": { "meal": [ "&nbsp;\n Broilernuggetteja currymajoneesilla", "Chicken nuggets with curry mayonnaise", "L\n \n &nbsp;\n Punajuuripihvejä currymajoneesilla", "Beetroot patties with curry mayonnaice", "L\n \n &nbsp;\n Hernekeittoa pannukakkua hillolla ja kermavaahdolla", "Pea soup and pancake with jam and cream", "&nbsp;\n Savupaistisalaattia", "Smoked beef salad" ] }, "friday": { "meal": [ "&nbsp;\n Rapea kalapala pikkelsi-kermaviilikastikkeella", "Crispy fish with sour cream sauce", "&nbsp;\n Cashew-pähkinäkasviscouscous", "Vegetable couscous with cashew nuts", "M\n \n &nbsp;\n Cheddarjuustokeittoa ja leipäkrutonkeja", "Cheddar cheese soup with crouton", "&nbsp;\n a la carte: Riistakäristystä, puolukkahilloa ja perunamuusia", "a la carte: Sautêed game with mashed potatoes and lingonberry jam", "&nbsp;\n Katkarapu-nuudelisalaattia", "Shrimp salad with noodles", "L" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "TUAS-talo", "url": "http://www.amica.fi/TUAS#Ruokalista", "info": "", "location": { "address": "Otaniementie 17, Espoo", "lat": "60.1868196", "lng": "24.8187598", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "" ] }, "tuesday": { "meal": [ "Kebab-kasviskastiketta (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Broileripy&ouml;ryk&ouml;it&auml; (L, M),Juusto-mangokastiketta (G, VL),Tummaa riisi&auml; (G, L, M)", "Pinaattiohukaisia (L),Puolukkahilloa (G, L, M),Perunasosetta (*, G, VL)", "Bistro: Tomaattista papukeittoa (G, L, M)", "Bistro: Kevytt&auml; tomaatti-kotijuustosalaattia (VL)", "&Agrave; la carte: Kalkkunapihvi (G, L, M),Sahramikastiketta (G, L),Curryperunoita (G, L, M)", "Vaniljakiisseli&auml; (G),Mansikkahilloa (G, L, M)" ] }, "wednesday": { "meal": [ "Purjosipuliseiti&auml; (*, G, VL),Keitettyj&auml; perunoita (*, G, L, M)", "Pyttipannua ja paistettu kananmuna (G, L, M)", "Kasvislasagnettea (VL)", "Bistro: Herkkusienikeittoa (G, VL)", "Bistro: Kalkkunasalaattia (*, G, L)", "&Agrave; la carte: Seesaminsiemenill&auml; kuorrutettu broilerinfilee (*, L, M),Tummaa hapanimel&auml;kastiketta (G, L, M)", "Mansikkakiisseli&auml; (G, L, M)" ] }, "thursday": { "meal": [ "Jauheliha-pennepataa (L, M)", "Broileria omena-jogurttikastikkeessa (G, L),Tummaa riisi&auml; (G, L, M)", "Meksikolaista maissi-kasvish&ouml;yst&ouml;&auml; (*, G, L, M),Tummaa riisi&auml; (G, L, M)", "Bistro: Savukinkku-perunakeittoa (G, VL)", "Bistro: Tonnikalasalaattia (*, G, L, M)", "&Agrave; la carte: Porsaanleike Amican tapaan (L, M),Sinihomejuustoperunoita (G, VL),BBQ-kastiketta (*, G, L, M)", "Puolukkap&auml;&auml;ryn&auml;&auml; (G, L, M),Kinuskikermavaahtoa (G)" ] }, "friday": { "meal": [ "Porsasstroganoffia (VL),Keitettyj&auml; perunoita (*, G, L, M)", "Kalkkunan jauhelihapihvej&auml; (L, M),Juusto-mangokastiketta (G, VL),Riisi&auml; (G, L, M)", "Linssipihvej&auml; (G, L, M),Currymajoneesia (G, L, M),Riisi&auml; (G, L, M)", "Bistro: Kermaista bataatti-maissisosekeittoa (G, VL)", "Bistro: Broileri-pastasalaattia ja curry-majoneesikastiketta (L, M)", "&Agrave; la carte: Juusto-paprikakuorrutettua lohta (VL),Keitettyj&auml; tilliperunoita (*, G, L, M)", "Hedelm&auml;rahkaa kerroksittain (G, L)", "Hyv&auml;&auml; ruokahalua!" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Alvari", "url": "http://www.amica.fi/alvari#Ruokalista", "info": "", "location": { "address": "Otakaari 2, Espoo", "lat": "60.1862055", "lng": "24.8262297", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1700" }, "tuesday": { "opening_time": "1030", "closing_time": "1700" }, "wednesday": { "opening_time": "1030", "closing_time": "1700" }, "thursday": { "opening_time": "1030", "closing_time": "1700" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Perinteist&auml; karjalanpaistia, keitettyj&auml; perunoita *,G,L,M", "Rapeita kalapaloja, tartarkastiketta, keitettyj&auml; perunoita L", "Kasvismusakaa *", "Mansikkasmoothieta G" ] }, "tuesday": { "meal": [ "Uunimakkaraa pekoni-sipulit&auml;ytteell&auml;, perunasosetta G,VL", "Kanaa sitruunakastikkeessa, tummaa riisi&auml; L,M", "Yrtti-juustopastaa VL", "Appelsiiniohukaisia, kinuskikermavaahtoa" ] }, "wednesday": { "meal": [ "Tomaattista jauhelihakastiketta, keitettyj&auml; perunoita *,L,M", "Tonnikala-pinaattilasagnettea", "Kookos-inkiv&auml;&auml;rimaustettua risottoa G,L,M", "Mustaherukkarahkaa G,L" ] }, "thursday": { "meal": [ "Tortillat, jauhelihat&auml;ytett&auml;, tomaattisalsaa, kermaviili&auml; L", "Lohi-smetanapataa, keitettyj&auml; perunoita *,G,VL", "Kasviksia soijakastikkeessa,tummaa riisi&auml; G,L,M", "A la carte: paneroitua kampelaa Amican tapaan, kes&auml;kurpitsaa, tartarkastiketta, perunasosetta VL", "Raparperi-kaurapaistosta, vaniljakastiketta", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Elissa", "url": "http://www.amica.fi/elissa#Ruokalista", "info": "Puuro 7:30–9:30 Keitto 11:00–15:00", "location": { "address": "Otakaari 2, Espoo", "lat": "60.1862055", "lng": "24.8262297", "distance": "" }, "opening_hours": { "monday": { "opening_time": "730", "closing_time": "1800" }, "tuesday": { "opening_time": "730", "closing_time": "1800" }, "wednesday": { "opening_time": "730", "closing_time": "1800" }, "thursday": { "opening_time": "730", "closing_time": "1800" }, "friday": { "opening_time": "730", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Kaurapuuroa L,M", "Kirjolohi-perunasalaattia, leip&auml;&auml; *,L", "Pinaattikeittoa ja kanamuna", "Op.leip&auml;at.: L&auml;mminsavukirjolohipatonki VL" ] }, "tuesday": { "meal": [ "Mannapuuroa VL", "Broilersalaattia, leip&auml;&auml; L", "Kermaista porkkanasosekeittoa VL", "Op.leip&auml;at.: Fetas&auml;mpyl&auml;" ] }, "wednesday": { "meal": [ "Nelj&auml;nviljanpuuroa L,M", "Tonnikala-nuudelisalaattia, leip&auml;&auml; L,M", "Kasvis-hernekeittoa,sipulia G,L,M", "Op.leip&auml;at.: Kalkkunapatonki" ] }, "thursday": { "meal": [ "Riisipuuroa VL,G", "Hedelm&auml;ist&auml; juustosalaattia, leip&auml;&auml; L", "Kasvisgulassikeittoa *,G,L,M", "Op.leip&auml;at.: Kinkku-juustopatonki VL", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Puu", "url": "http://www.amica.fi/Puu2#Ruokalista", "info": "", "location": { "address": "Tekniikantie 3, Espoo", "lat": "60.1807464", "lng": "24.8246464", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Juustoisia broilerpuikkoja (L)Currykastiketta (VL)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Porsaanleike ananaksella Amican tapaan (L, M)Amerikkalaista chilimajoneesia (G, L, M)Juustoperunoita (G, VL)", "Herkkusienipastaa(VL)", "Suklaakiisseli&auml; (G)Kermavaahtoa (G, L)" ] }, "tuesday": { "meal": [ "Lihamakaronilaatikkoa (*, VL)Tomaattiketsuppia (G, L, M)", "Paistettua haukea(L,M) Tartarkastiketta(G,L)Juustoperunoita(*,G,L,M)", "Falafel-py&ouml;ryk&ouml;it&auml; (L, M)Sitruuna-jogurttikastiketta (G, L)H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "Kaura-omenapaistosta (L, M)Vaniljakermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Porsasta inkiv&auml;&auml;rikastikkeessa (G, L, M)H&ouml;yrytetty&auml; riisi&auml; (G, L, M)", "Kasviksia kookoskastikkeessa (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Hernekeittoa (G, L, M)Hienonnettua sipulia (G, L, M)PannukakkuaMansikkahilloa (G, L, M)", "Mustikkahilloa ja turkkilaista jogurttia (G)" ] }, "thursday": { "meal": [ "Kinkku-ananaspannupizzaa (L)", "Jogurttista linssi-kasvismuhennosta (*, G)Jasminriisi&auml; (G, L, M)", "Vaniljakermavaahtoa (G, L)Mausteisia uunibanaaneita (G, VL)", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Täffä", "url": "http://www.teknologforeningen.fi/index.php/fi/taman-viikon-ruokalista", "info": "", "location": { "address": "Otakaari 22, Espoo", "lat": "60.1859061", "lng": "24.8324844", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Ravintola suljettu" ] }, "tuesday": { "meal": [ "Broilerin rintaleike, juustokastike", "Kasvispyörykät, chilimajoneesi l g", "Nizzansalaatti l g", "Herkkusienikeitto l", "A&#039;la Carte: Oskarinleike" ] }, "wednesday": { "meal": [ "Spaghetti bolognese l", "Gorgonzolakastike l", "Pesto-Broilerisalaatti l g", "Minestronekeittoa l", "A&#039;la Carte: Grillipihvi l g" ] }, "thursday": { "meal": [ "<NAME>", "Kasvispihvit, tartarkastike g l", "Kylmäsavulohi-parsasalaatti l g", "Lihakeitto l g", "A&#039;la Carte: Hawaijinleike l" ] }, "friday": { "meal": [ "Porsaanleike, pippurikastike", "Kasvismunakas l g", "Kreikkalainen maalaissalaatti vl g", "Mausteinen kanakeitto l g", "A&#039;la Carte: Grillattu lohi, kermaviilikastike, lohkoperunat l g" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Kvarkki", "url": "http://www.amica.fi/kvarkki#Ruokalista", "info": "", "location": { "address": "Otakaari 3, Espoo", "lat": "60.1883476", "lng": "24.8294072", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1400" }, "tuesday": { "opening_time": "1030", "closing_time": "1400" }, "wednesday": { "opening_time": "1030", "closing_time": "1400" }, "thursday": { "opening_time": "1030", "closing_time": "1400" }, "friday": { "opening_time": "1030", "closing_time": "1300" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Juustoisia broileripuikkoja (L),Currykastiketta (VL),Tummaa riisi&auml; (G, L, M)", "&Agrave; la carte: Porsaanleike ananaksella Amican tapaan (L, M),Amerikkalaista chilimajoneesia (G, L, M)", "Herkkusienipastaa (VL)", "Kaali-kasviskeittoa ja papu-kikherneseosta (G, L, M)", "Nizzalaista tonnikalasalaattia (G, L, M)", "Suklaakiisseli&auml; (G),Kermavaahtoa (G, L)" ] }, "tuesday": { "meal": [ "Lihamakaronilaatikkoa (*, VL)", "&Agrave; la carte: Paistettua haukea (*, L, M),Tartarkastiketta (G, L),Keitettyj&auml; tilliperunoita (*, G, L, M)", "Falafel-py&ouml;ryk&ouml;it&auml; (L, M),Sitruuna-jogurttikastiketta (G, L),Riisi&auml; (G, L, M)", "Parsakeittoa (G, VL)", "Kevytt&auml; l&auml;mminsavukirjolohisalaattia (G, L)", "Kaura-omenapaistosta (L, M),Vaniljakermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Porsasta inkiv&auml;&auml;rikastikkeessa (G, L, M),Riisi&auml; (G, L, M)", "&Agrave; la carte: Juustokuorrutettu broilerinfilee (L),BBQ-kastiketta (*, G, L, M),Juustoperunoita (G, VL)", "Kasviksia kookoskastikkeessa (G, L, M),Tummaa riisi&auml; (G, L, M)", "Hernekeittoa (G, L, M),Pannukakkua ja mansikkahilloa (G, L, M)", "Kinkku-pastasalaattia (L)", "Mustikkahilloa ja turkkilaista jogurttia (G)" ] }, "thursday": { "meal": [ "Kinkku-ananaspannupizzaa (L)", "&Agrave; la carte: Paistettuja muikkuja (L, M),Tilli-kermaviilikastiketta (G, L),Perunasosetta (*, G, VL)", "Jogurttista linssi-kasvismuhennosta (*, G),Jasminriisi&auml; (G, L, M)", "Kukkakaalisosekeittoa (G, VL)", "Broileri-nuudelisalaattia ja makeaa chilikastiketta (L, M)", "Vaniljakermavaahtoa (G, L),Mausteisia uunibanaaneita (G, VL)", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Silinteri", "url": "http://www.amica.fi/silinteri#Ruokalista", "info": "Henkilökuntaravintola, ei opiskelijahintoja", "location": { "address": "Otakaari 1, Espoo", "lat": "60.1869326", "lng": "24.8272611", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1045", "closing_time": "1330" }, "tuesday": { "opening_time": "1045", "closing_time": "1330" }, "wednesday": { "opening_time": "1045", "closing_time": "1330" }, "thursday": { "opening_time": "1045", "closing_time": "1330" }, "friday": { "opening_time": "1045", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Kirjolohi-perunasalaattia, leip&auml;&auml; *,L", "Pinaattikeittoa ja kananmuna", "Perinteist&auml; karjalanpaistia, keitettyj&auml; perunoita *,G,L,M", "Kasvismusakaa *", "A la carte: broileria pekoni-herkkusienikastikkeessa, paahdettua perunaa, punajuurikuutioita G,L", "Mansikkasmoothieta G" ] }, "tuesday": { "meal": [ "Broilersalaattia, leip&auml;&auml; L", "Kermaista porkkanasosekeittoa G,VL", "Uunimakkaraa pekoni-sipulit&auml;ytteell&auml;, perunasosetta G,VL", "Yrtti-juustopastaa VL", "A la carte: smetanalohta ja kes&auml;kurpitsaa, tilliperunoita G,L", "Appelsiiniohukaisia, kinuskikermavaahtoa" ] }, "wednesday": { "meal": [ "Tonnikala-nuudelisalaattia, leip&auml;&auml; L,M", "Kasvis-hernekeittoa, sipulia *,G,L,M", "Tonnikala-pinaattilasagnea", "Kookos-inkiv&auml;&auml;rimaustettua risottoa G,L,M", "A la carte:Sveitsinleike, perunasosetta, paahdettuja bataattia ja paprikaa VL", "Mustaherukkarahkaa G,L" ] }, "thursday": { "meal": [ "Hedelm&auml;ist&auml; juustosalaattia, leip&auml;&auml; L", "Kasvisgulassikeittoa *,G,L,M", "Tortillat, jauhelihat&auml;ytett&auml;, tomaattisalsaa, kermaviili&auml; L", "Kasviksia soijakastikkeessa, tummaa riisi&auml; G,L,M", "A la carte: paneroitua kampelaa Amican tapaan, kes&auml;kurpitsaa, tartarkastiketta, perunoita VL", "Raparperi-kaurapaistosta, vaniljakastiketta", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Cantina", "url": "http://www.sodexo.fi/cantina", "info": "Opiskelija-alennus 10%, lounas arkisin klo 11-14", "location": { "address": "Otakaari 24, Espoo", "lat": "60.1847778", "lng": "24.8309887", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "2230" }, "tuesday": { "opening_time": "1100", "closing_time": "2230" }, "wednesday": { "opening_time": "1100", "closing_time": "2230" }, "thursday": { "opening_time": "1100", "closing_time": "2230" }, "friday": { "opening_time": "1100", "closing_time": "2230" }, "saturday": { "opening_time": "1100", "closing_time": "2200" } }, "menu": { "monday": { "meal": [ "&nbsp;\n Broilerin rintafileetä BBQ-kastikkeessa ja riisiä.", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelmäinen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "tuesday": { "meal": [ "&nbsp;\n Kebab, minttu-jogurttikastiketta ja riisiä", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelmäinen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "wednesday": { "meal": [ "&nbsp;\n Pangasusfileetä, tsatsikkia ja keitinperunoita", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelmäinen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "thursday": { "meal": [ "&nbsp;\n Lihapullia kermakastikkeessa ja perunamuusia.", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelmäinen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "friday": { "meal": [ "&nbsp;\n Broileria tandoorikastikkeessa ja kasvisiriisiä.", "4,95 &euro;7,60 &euro;\n \n \n \n \n &nbsp;\n Kinkku-paprika-aura pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Salami-ananas pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Bolognese pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tonnikala-herkkusieni pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Kebab-sipuli-jalapeno pizza", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Tomaatti-oliivi-aura", "5,05 &euro;7,80 &euro;\n \n \n L\n \n &nbsp;\n Hedelmäinen kanasalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Chili marinoitu katkarapusalaatti", "5,05 &euro;7,80 &euro;\n \n \n \n \n &nbsp;\n Kreikkalainen salaatti", "5,05 &euro;7,80 &euro;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "<NAME>", "url": "http://www.amica.fi/laureaotaniemi#Ruokalista", "info": "", "location": { "address": "Metsänpojankuja 3, Espoo", "lat": "60.1858124", "lng": "24.8054477", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1315" }, "tuesday": { "opening_time": "1100", "closing_time": "1315" }, "wednesday": { "opening_time": "1100", "closing_time": "1315" }, "thursday": { "opening_time": "1100", "closing_time": "1315" }, "friday": { "opening_time": "1100", "closing_time": "1300" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Naudanliha-juurespataa (L, M),Keitettyj&auml; perunoita (*, G, L, M)", "&Agrave; la carte: Broilerin rintaleike herkkusieni-pekonikastikkeessa (G, L, M),Maalaislohkoperunoita (G, L, M)", "Kasvismusakaa (*)", "Pinaattikeittoa ja kananmuna" ] }, "tuesday": { "meal": [ "Kanaa sitruunakastikkeessa (L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "&Agrave; la carte: Smetanalohta ja kes&auml;kurpitsaa (G, VL),Keitettyj&auml; tilliperunoita (*, G, L, M)", "Yrtti-juustopastaa (VL)", "Porkkanasosekeittoa (G, VL)" ] }, "wednesday": { "meal": [ "Tonnikala-pastavuokaa (VL)", "&Agrave; la carte: Sveitsinleike (L),Perunasosetta (*, G, VL)", "Kookos-inkiv&auml;&auml;rimaustettua paistettua riisi&auml; (G, L, M)", "Riisipuuroa (G),Mansikkakeittoa (G, L, M)" ] }, "thursday": { "meal": [ "Jauhelihalasagnettea", "Kasviksia soijakastikkeessa (G, L, M),Tummaa riisi&auml; (G, L, M)", "Kasvisgulassikeittoa ja papu-kikherneseosta (*, G, L, M)", "Hyv&auml;&auml; ruokahalua!" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Otaniemi" }, { "name": "Rafla", "url": "http://www.amica.fi/rafla#Ruokalista", "info": "", "location": { "address": "Runeberginkatu 14, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1615" }, "tuesday": { "opening_time": "1030", "closing_time": "1615" }, "wednesday": { "opening_time": "1030", "closing_time": "1615" }, "thursday": { "opening_time": "1030", "closing_time": "1615" }, "friday": { "opening_time": "1030", "closing_time": "1615" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Kinkku-tuorejuustokastiketta pastalle (G, VL)T&auml;ysjyv&auml;kierrepastaa (*, L, M)", "Espanjalaista pinaatti-oliivimunakasta (*, G, L)Papumuhennosta (G, L, M)", "Kukkakaalisosekeittoa (G, VL)", "Kalkkunasalaattia (*, G, L)", "Suklaa-banaanimoussea (G)" ] }, "tuesday": { "meal": [ "Juustokuorrutettua jauhelihavuokaa (*)", "Broileria currykastikkeessa (G, VL)Valkosipuliriisi&auml; (G, L, M)", "Kukkakaali-perunacurrya (*, G, L, M)T&auml;ysjyv&auml;ohraa (*, L, M)", "Katkarapusalaattia (*, G, L)", "Mangorahkaa kerroksittain (G, L)" ] }, "wednesday": { "meal": [ "Lohipy&ouml;ryk&ouml;it&auml; (L, M)Tillikastiketta (*, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Broilerikiusausta (G, VL)", "Porsaan grillipihvi (G, L, M)Cafe de Paris -maustevoita (G, VL)Paahdettua perunaa (G, L, M)", "Papu-vihannespastaa (*, L, M)", "Kreikkalainen salaatti (G)", "Sitrussalaattia (G, L, M)Kermavaahtoa (G, L)" ] }, "thursday": { "meal": [ "Jauheliha-sipulipihvej&auml; (G, L, M)Ruskeaa kastiketta (VL)Keitettyj&auml; perunoita (*, G, L, M)", "Intialaista jogurttiseiti&auml; (*, G)Keitettyj&auml; perunoita (*, G, L, M)", "Kasviksia seesamkastikkeessa (*, G, L, M)Nuudeleita (L, M)", "Sipulikeittoa ja siemensekoitusta (G, L, M)", "Kinkku-pastasalaattia (L)", "Rikkaita ritareita" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "Chydenia", "url": "http://www.amica.fi/chydenia#Ruokalista", "info": "", "location": { "address": "Runeberginkatu 22, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "" ] }, "tuesday": { "meal": [ "" ] }, "wednesday": { "meal": [ "" ] }, "thursday": { "meal": [ "" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "Hanken", "url": "http://www.amica.fi/hanken#Ruokalista", "info": "", "location": { "address": "Arkadiankatu 22, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1500" }, "tuesday": { "opening_time": "1100", "closing_time": "1500" }, "wednesday": { "opening_time": "1100", "closing_time": "1500" }, "thursday": { "opening_time": "1100", "closing_time": "1500" }, "friday": { "opening_time": "1100", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Makkara-juustopihvi (G, L)Ruskeaa kastiketta (L, M)Perunasosetta (*, G, VL)", "Broilermureketta Amican tapaan (L, M)Juusto-mangokastiketta (G, VL)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Pinaattiohukaisia (L)Puolukkahilloa (G, L, M)Perunasosetta (*, G, VL)", "Kevytt&auml; tomaatti-kotijuustosalaattia (VL)" ] }, "tuesday": { "meal": [ "Broileri-pekonikastiketta (G, VL)T&auml;ysjyv&auml;pennepastaa (*, L, M)", "Kaalik&auml;&auml;ryleit&auml; (G, L, M)Ruskeaa kastiketta (VL)Puolukkahilloa (G, L, M)Keitettyj&auml; perunoita (*, G, L, M)", "Seesampaneroitu broilerinfilee (*, L, M)Tummaa hapanimel&auml;kastiketta (G, L, M)Jasminriisi&auml; (G, L, M)", "Kasvislasagnettea (VL)", "Kalkkunasalaattia (*, G, L)" ] }, "wednesday": { "meal": [ "Lohimurekepihvej&auml; (L, M)Sitruunakastiketta (*, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Kebab-kasviskastiketta (*, G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Meksikolaista maissi-kasvish&ouml;yst&ouml;&auml; (*, G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kasvis-hernekeittoa (*, G, L, M)Hienonnettua sipulia (G, L, M)OhukaisiaMansikkahilloa (G, L, M)", "Hernekeittoa (G, L, M)Hienonnettua sipulia (G, L, M)OhukaisiaMansikkahilloa (G, L, M)", "Tonnikalasalaattia (*, G, L, M)" ] }, "thursday": { "meal": [ "Kinkkupizzaa (L)", "Meetvurstipizzaa (L)", "Tonnikalapizzaa (L)", "Kasvispizzaa (L)", "Broilericurrya (G, L)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Linssipihvej&auml; (G, L, M)Currymajoneesia (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Broileri-pastasalaattia (L, M)" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "Sibelius-Akatemia / R-Talo", "url": "http://www.amica.fi/r-talo#Ruokalista", "info": "", "location": { "address": "Pohjoinen Rautatienkatu 9, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1530" }, "saturday": { "opening_time": "1100", "closing_time": "1330" } }, "menu": { "monday": { "meal": [ "Yrteill&auml; maustettuja lihapy&ouml;ryk&ouml;it&auml; (L, M),Tummaa kermakastiketta (*, VL),", "Keitettyj&auml; perunoita (*, G, L, M)", "Broileri-juustokastiketta (*, G, VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "P&auml;hkin&auml;ist&auml; kasvis-vehn&auml;risottoa (L, M),Kermaviili&auml; (G, L)", "Minttu-suklaavaahtoa (G)" ] }, "tuesday": { "meal": [ "Naudanliha-juurespataa (L, M),Keitettyj&auml; perunoita (*, G, L, M)", "Porsaanleike ananaksella (L, M),Chilimajoneesia (G, L),Maalaislohkoperunoita (G, L, M)", "Paahdettuja palsternakkalohkoja (G, L, M)", "Kasvismusakaa (*)", "Omena-puolukkakukkoa (L, M),Vaniljakastiketta (G)" ] }, "wednesday": { "meal": [ "Uunimakkara pekoni-sipulit&auml;ytteell&auml; (G, L),Tomaattikastiketta (G, VL),", "Keitettyj&auml; perunoita (*, G, L, M)", "Smetanalohta ja kes&auml;kurpitsaa (G, VL),Keitettyj&auml; tilliperunoita (*, G, L, M)", "Persiljaporkkanoita (G, L, M)", "Yrtti-juustopastaa (VL)", "Appelsiiniohukaisia,Kinuskikermavaahtoa (G)" ] }, "thursday": { "meal": [ "Tomaattista jauhelihakastiketta (*, L, M),Keitettyj&auml; perunoita (*, G, L, M)", "Tonnikala-pastavuokaa (VL)", "Kookos-inkiv&auml;&auml;rimaustettua paistettua riisi&auml; (G, L, M)", "Mustaherukkarahkaa kerroksittain (G, L)", "VL = V&auml;h&auml;laktoosinen", "L = Laktoositon", "G = Gluteeniton", "M = Maidoton", "* = Voi hyvin" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "<NAME>", "url": "http://www.amica.fi/r-talo#Ruokalista", "info": "", "location": { "address": "Töölönkatu 28, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1600" }, "saturday": { "opening_time": "1100", "closing_time": "1330" } }, "menu": { "monday": { "meal": [ "Katkarapuseiti&auml; (*, VL),Perunasosetta (*, G, VL)", "Chili con vege (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Mangorahkaa kerroksittain (G, L)" ] }, "tuesday": { "meal": [ "Riista-herkkusienikastiketta (G, VL),Keitettyj&auml; perunoita (*, G, L, M)", "Currymaustettu broilerin rintaleike (*, G, L, M),Amerikkalaista chilimajoneesia (G, L, M),", "Juustoperunoita (G, VL),H&ouml;yrytetty&auml; parsakaalia (G, L, M)", "Falafel-py&ouml;ryk&ouml;it&auml; (L, M),Amerikkalaista chilimajoneesia (G, L, M),", "Keitettyj&auml; perunoita (*, G, L, M)", "Suklaakiisseli&auml; (G,VL),Kermavaahtoa (G, L)" ] }, "wednesday": { "meal": [ "Juustoisia broilerpuikkoja (L),Currykastiketta (VL),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Paistettua haukea (*, L, M),Tartarkastiketta (G, L),Keitettyj&auml; tilliperunoita (*, G, L, M),", "Sitruunaporkkanoita (G, VL)", "Herkkusienipastaa (VL)", "Kirsikka-omenajuoma (G, L, M)" ] }, "thursday": { "meal": [ "Lihamakaronilaatikkoa (*, VL)", "Kalkkunan lehtipihvi (G, L, M),BBQ-kastiketta (*, G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M),", "Paprika-sipulilis&auml;kett&auml; (G, L, M)", "Kasviksia kookoskastikkeessa (G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Mustikkakiisseli&auml; (G, L, M),Kermavaahtoa (G, L)", "VL = V&auml;h&auml;laktoosinen", "L = Laktoositon", "G = Gluteeniton", "M = Maidoton", "* = Voi hyvin" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "<NAME>", "url": "http://www.hys.net/opiskelijapalvelut/osakuntabaari/ruokalista", "info": "", "location": { "address": "Urho Kekkosen katu 4-6 D, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1530" }, "tuesday": { "opening_time": "1100", "closing_time": "1530" }, "wednesday": { "opening_time": "1100", "closing_time": "1530" }, "thursday": { "opening_time": "1100", "closing_time": "1530" }, "friday": { "opening_time": "1100", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Baari on suljettu!", "Hauskaa", "pääsiäistä!" ] }, "tuesday": { "meal": [ "Kalaleike", "Musta makkara", "Kuskus-kasvispihvi", "Sienikeitto" ] }, "wednesday": { "meal": [ "Tonnikala-pastavuoka", "Kebablihakastike", "Kasviskeitto" ] }, "thursday": { "meal": [ "Uunilohi", "Kasviskiusaus", "Härkä-seljankakeitto" ] }, "friday": { "meal": [ "Sveitsinleike", "Sienikääryleet", "Keitto", "&nbsp;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Töölö" }, { "name": "Kipsari", "url": "http://www.kipsari.com/menu.php", "info": "", "location": { "address": "Hämeentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "800", "closing_time": "1900" }, "tuesday": { "opening_time": "800", "closing_time": "1900" }, "wednesday": { "opening_time": "800", "closing_time": "1900" }, "thursday": { "opening_time": "800", "closing_time": "1900" }, "friday": { "opening_time": "800", "closing_time": "1900" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "" ] }, "tuesday": { "meal": [ "" ] }, "wednesday": { "meal": [ "" ] }, "thursday": { "meal": [ "" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Arabia" }, { "name": "Meccala", "url": "http://www.amica.fi/meccala#Ruokalista", "info": "", "location": { "address": "Hämeentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1345" }, "tuesday": { "opening_time": "1030", "closing_time": "1345" }, "wednesday": { "opening_time": "1030", "closing_time": "1345" }, "thursday": { "opening_time": "1030", "closing_time": "1345" }, "friday": { "opening_time": "1030", "closing_time": "1345" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "P&auml;&auml;si&auml;inen" ] }, "tuesday": { "meal": [ "Smetanaseiti&auml; (G, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Kasvismusakaa (*)", "Pinaattikeittoa ja kananmuna" ] }, "wednesday": { "meal": [ "Kanaa sitruunakastikkeessa (L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)Mustaherukkahilloa (G, L, M)", "Yrtti-juustopastaa (VL)", "Kermaista porkkanasosekeittoa (G, VL)" ] }, "thursday": { "meal": [ "Tomaattista jauhelihakastiketta (*, L, M)T&auml;ysjyv&auml;kierrepastaa (*, L, M)", "Kookos-inkiv&auml;&auml;rimaustettua paistettua riisi&auml; (G, L, M)", "Kasvisborssikeittoa (*, G, L, M)" ] }, "friday": { "meal": [ "Uunimakkara pekoni-sipulit&auml;ytteell&auml; (G, L)Tomaattikastiketta (G, VL)Keitettyj&auml; perunoita (*, G, L, M)", "Kasviksia soijakastikkeessa (G, L, M)H&ouml;yrytetty&auml; tummaa riisi&auml; (G, L, M)", "Kasvisgulassikeittoa ja papu-kikherneseosta (*, G, L, M)", "Hyv&auml;&auml;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Arabia" }, { "name": "<NAME>", "url": "http://www.antell.fi/docs/lunch.php?Arabiakeskus,%20Helsinki", "info": "Tähdellä merkityt opiskelijahintaan", "location": { "address": "Hämeentie 135, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "PÄÄSIÄIS" ] }, "tuesday": { "meal": [ "RAVINTOLA JA", "KAHVILA SULJETTU", "&nbsp;&nbsp;" ] }, "wednesday": { "meal": [ "*Neljän sipulin keittoa (L G M)", "*Savukalakiusausta (VL G)", "Riistakäristystä ja puolukkaa (L G M)", "*Intialaista inkiväärikaalia (L G M)", "Salaattibuffet: Paahtopaistia", "Hedelmäsalaattia (L G M)", "&nbsp;&nbsp;" ] }, "thursday": { "meal": [ "*Punajuuri-perunasosekeittoa (VL G)", "*Jauhelihakaalilaatikkoa (L G M)", "Paistettua kalaa ja remouladekastiketta (VL)", "*Kasvisratatouillea (L G M)", "Salaattibuffet: Katkarapuja", "Appelsiinikiisseliä (L G M)", "&nbsp;&nbsp;" ] }, "friday": { "meal": [ "*Maissikeittoa (VL G)", "*Hernekeittoa ja luomukasviskeittoa (L G M)", "Palapaistia ja perunamuusia (VL G)", "*Raviolit tomaattikastikkeessa (VL)", "Salaattibuffet: Juustovalikoima", "Pannukakkua ja hilloa (VL)", "&nbsp;&nbsp;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Arabia" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php/Kumpula/Chemicum/", "info": "", "location": { "address": "Gustaf Hällströmin katu 2, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1530" }, "tuesday": { "opening_time": "1030", "closing_time": "1530" }, "wednesday": { "opening_time": "1030", "closing_time": "1530" }, "thursday": { "opening_time": "1030", "closing_time": "1530" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "HAUSKAA PÄÄSIÄISTÄ !" ] }, "tuesday": { "meal": [ "Härkä-nuudeliwokkia (l,v)Paprika-broilerkastiketta (vl)Sieni-kasvisrisotto (g,k,l,v,ve)Kinkkusalaatti (g,l)Kasvisborschkeittoa (g,l)" ] }, "wednesday": { "meal": [ "Porsaanleike, pippurikastiketta (l)Lohilasagnea (vl)Soijaa thaicurrykastikkeessa (g,k,l,v,ve)Hedelmäinen kalkkunasalaatti (l)Mustajuurikeittoa, auringonkukan sieminiä (g,k,vl)" ] }, "thursday": { "meal": [ "Burgundin härkää (l,v)Rapeaa chilikalaa, chilimajoneesiaHernekeittoa (g,l), pannukakkua ja hilloaKasvishernekeittoa (g,k,l,ve), pannukakkua ja hilloaCheddarsalaatti (k,vl)Kasvishernekeittoa (g,k,l,ve)Pannukakkua ja hilloa (k) 1,00&euro;" ] }, "friday": { "meal": [ "SmetanalohtaKebabkastiketta (g,l,v)Kasvispyttipannua (g,k,l,ve)" ] }, "saturday": { "meal": [ "HYVÄÄ VIIKONLOPPUA !" ] }, "sunday": { "meal": [ "HYVÄÄ VIIKONLOPPUA !" ] } }, "campus": "Kumpula" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php/Kumpula/Exactum/", "info": "", "location": { "address": "Gustaf Hällströmin katu 2, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Hauskaa pääsiäistä!" ] }, "tuesday": { "meal": [ "Tomaattista lihapullakastiketta (g,v)Sieni-kasvisrisotto (g,k,l,v,ve)Kalapihvejä ja tilli-kermaviilikastiketta (l)Pähkinäistä juustosalaattia (g,k,l,pä)Suklaamoussella täytetyt vohvelit ja suklaakastiketta 1,40&euro;" ] }, "wednesday": { "meal": [ "Juustoiset broileripihvit ja currykastiketta (v,vl)Soijaa thaicurrykastikkeessa (g,k,l,v,ve)Mausteista kalapataa (g,l,v)Meksikolainen jauhelihasalaatti (g,l,pä,v)Ananas-kaurahyve (k,l) 1,20&euro;" ] }, "thursday": { "meal": [ "Burgundin härkää (l,v)Seitä pestokastikkeessa (g,pä,v,vl)Pinaattiohukaisia (k,l), puolukkasurvostaHedelmäinen kalkkunasalaatti (l)Banaanikiisseli ja kinuski-vaniljavaahto 1,20&euro;" ] }, "friday": { "meal": [ "Kebabkastiketta (g,l,v)Vihannespihvipihvit, papusalsaa (g,k,l,se,v,ve)Välimeren kalakeittoa (g,l)Nizzansalaatti (g,l)Marjapiirakkaa ja vaniljakastiketta 1,40&euro;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Kumpula" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php/Kumpula/Valdemar/", "info": "", "location": { "address": "Teollisuuskatu 23, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1030" }, "tuesday": { "opening_time": "1030", "closing_time": "1030" }, "wednesday": { "opening_time": "1030", "closing_time": "1030" }, "thursday": { "opening_time": "1030", "closing_time": "1030" }, "friday": { "opening_time": "1030", "closing_time": "1030" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Lapinkeittoa (g,vl)Kasvis-papukroketit, ruohosipuli-jogurttikastiketta (g,k,l,v)" ] }, "tuesday": { "meal": [ "Broilerilasagnettea (v)Soijaa thaicurrykastikkeessa (g,k,l,v,ve)" ] }, "wednesday": { "meal": [ "Kalapyöryköitä, sitruunakermaviilikastiketta (l)Pinaattikeittoa, ½ kananmuna (k)" ] }, "thursday": { "meal": [ "Jauheliha-juureskastiketta (l)Tofu-perunalaatikkoa (k,l,v,ve)" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Kumpula" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Metsätalo/1/1", "info": "", "location": { "address": "Fabianinkatu 39, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1600" }, "tuesday": { "opening_time": "1030", "closing_time": "1600" }, "wednesday": { "opening_time": "1030", "closing_time": "1600" }, "thursday": { "opening_time": "1030", "closing_time": "1600" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Toinen pääsiäispäivä" ] }, "tuesday": { "meal": [ "Tofu-pähkinäkastiketta (g,k,l,pä,ve)Kalaa tacokastikkeessa (g,pä,v,vl)Broilerinuggetit, currykastiketta (l,v)Lounassalaatti" ] }, "wednesday": { "meal": [ "Quinoa-soijapannua (g,k,l,v,ve)MakaronilaatikkoaMustaherukkaista broilerinkastiketta (g,l)Lounassalaatti" ] }, "thursday": { "meal": [ "Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)Pekonista sieni-kaalipataa (g,l,v)Broilerilasagnettea (v)Lounassalaatti" ] }, "friday": { "meal": [ "Mango-vihanneshöystöä (g,k,l,se,v,ve)Lindströminpihvit, tummaa sipulikastiketta (g)Hunajaista kalapataa (g,vl)Lounassalaatti" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Olivia/1/2", "info": "", "location": { "address": "Siltavuorenpenger 5, Helsinki", "lat": "60.175106", "lng": "24.953385", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1500" }, "tuesday": { "opening_time": "1030", "closing_time": "1500" }, "wednesday": { "opening_time": "1030", "closing_time": "1500" }, "thursday": { "opening_time": "1030", "closing_time": "1500" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Lohta salsakastikkeessa (g,pä,v,vl)Itämaista kikhernekastiketta (g,l,v,ve)Kookos-broilerihöystöä (g,vl)LounassalaattiAurajuustokeittoa (k)" ] }, "tuesday": { "meal": [ "Hapanimelää porsaspataa (g,l,v)Kasvismoussakaa (g,k,v,vl)Broileria aprikoosi-mantelikastikkeessa (g,l,pä,v)Lounassalaatti" ] }, "wednesday": { "meal": [ "Soija-sipulikastiketta (k,l,ve)Hernekeittoa (g,l)Lohikebakoita, ruohosipuli-jogurttikastiketta (vl)LounassalaattiKasvishernekeittoa (g,k,l,ve)" ] }, "thursday": { "meal": [ "Lihacurry (g,l,v)Savukalapastaa (vl)Kasvis-kaalikääryleitä, linssimuhennosta (g,k,l,v,ve)Lounassalaatti" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "UniCafe Porthania", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Porthania/1/3", "info": "", "location": { "address": "Yliopistonkatu 3, Helsinki", "lat": "60.1699536", "lng": "24.9484354", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1630" }, "tuesday": { "opening_time": "1030", "closing_time": "1630" }, "wednesday": { "opening_time": "1030", "closing_time": "1630" }, "thursday": { "opening_time": "1030", "closing_time": "1630" }, "friday": { "opening_time": "1030", "closing_time": "1630" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "2. Pääsiäispäivä" ] }, "tuesday": { "meal": [ "Uunimakkara (g,l,v)Kuhapyörykät, pinaattikastikettaPapupataa (g,k,l,v,ve)Cheddarsalaatti (k,vl)Perunamuusia itseotossa" ] }, "wednesday": { "meal": [ "Jauhelihabolognaisea, juustoraastetta (g,l,pä,v)Itämaista kikhernekastiketta (g,l,v,ve)Juustoista uuniseitä (vl)Paahtopaistisalaattia (g,l)" ] }, "thursday": { "meal": [ "Cheddar-täytteinen kalarulla, ruohosipulikastiketta (v)Punajuurikroketteja, ruohosipuli-soijajogurttikastiketta (l,ve)Broileri-ananaskastiketta (l)Hernekeittoa (g,l), pannukakkua ja hilloaMeksikolainen jauhelihasalaatti (g,l,pä,v)Kasvishernekeittoa (g,k,l,ve)" ] }, "friday": { "meal": [ "SmetanalohtaBroilerinkoipi, currykastiketta (pä,v,vl)Kasviswrap, ranskankermaa (k,l,v)Tofusalaatti (k,l,ve)" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Päärakennus/1/4", "info": "", "location": { "address": "Fabianinkatu 33, Helsinki", "lat": "60.1694418", "lng": "24.9494575", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1630" }, "tuesday": { "opening_time": "1030", "closing_time": "1630" }, "wednesday": { "opening_time": "1030", "closing_time": "1630" }, "thursday": { "opening_time": "1030", "closing_time": "1630" }, "friday": { "opening_time": "1030", "closing_time": "1630" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Jauhelihabolognaisea, juustoraastetta (g,l,pä,v)Seitä pinaattikastikeessaPunajuurikroketteja, ruohosipuli-soijajogurttikastiketta (l,ve)Riistakeittoa (g,l)Parmesan-broilerisalaatti (l)Neljän viljan puuroa, vadelmakeittoa (k,l,ve)Mustikka-banaanirahka (g,k,vl) 1,20&euro;" ] }, "tuesday": { "meal": [ "Valkosipulitäytteinen broilerileike, valkosipulidippiä (se,v)Lindströminpihvit, tummaa sipulikastiketta (g)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)KatkarapukeittoaKylmäsavulohisalaatti (g,l)Riisipuuroa, mansikkakeittoa (g,k)Kaura-omenapaistosta ja vaniljakastike (k,vl), 1,40&euro;" ] }, "wednesday": { "meal": [ "Paistettua lohta, valkoviinikastiketta (vl)MakaronilaatikkoaBroileri-vihannespannua (g,l,pä)Tofu-pähkinäkastiketta (g,k,l,pä,ve)Chili-katkarapusalaatti (g,l)Kaurapuuroa, mustikkakeittoa (l,ve)Vanilja-pannacotta (g,vl) 1,20&euro;" ] }, "thursday": { "meal": [ "Katkaraputäytteinen kalaleike, ruohosipulidippiLihapyöryköitä, ruskeaa kastiketta (l,v)Kookos-juureshöystöä (g,k,l,v,ve)Tattari-mozzarellasalaatti (g,k,l)Purjo-perunasosekeittoa (g,k,vl)Mannapuuroa, mansikkakeittoa (k)Ohukaisia, hilloa ja kermavaahtoa (k,vl) 1,20&euro;" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Rotunda/1/5", "info": "", "location": { "address": "Unioninkatu 36, Helsinki", "lat": "60.170351", "lng": "24.9506851", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Jauhelihabolognaisea, juustoraastetta (g,l,pä,v)Lounassalaatti: Parmesan/ Tonnikala/ TofuTofu-gulassikeittoa (g,k,l,v,ve)Kuningatarrahka (g,k,l) 1,20&euro;" ] }, "tuesday": { "meal": [ "KatkarapukeittoaLounassalaatti: Parmesan/ Tonnikala/ TofuKaali-kasviskeittoa (g,k,l,se,ve)Ruishiutalepuuroa, mustikkamehukeittoa (k,l,ve)Mangorahka (g,k,l) 1,20&euro;" ] }, "wednesday": { "meal": [ "Kanakeittoa (g,l,se,v)Lounassalaatti: Katkarapu (g,l)/ Mozzarella (g,vl) / Tofu (g,ve,l)Maissikeittoa (g,k,vl)LuomuTattarihiutalepuuroa, mustikkakeittoa (g,k,l,ve)Mustikkaherkku (k,l) 1,20&euro;" ] }, "thursday": { "meal": [ "Itämaista kana-kookoskeittoa (g,l,se,v)Lounassalaatti: Katkarapu / Mozzarella / TofuPurjo-perunasosekeittoa (g,k,vl)Ohrahiutalepuuroa, mustikkakeittoa (k,l,ve)Hedelmärahkaa (g,k,l) 1,20&euro;" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Soc&Kom/1/15", "info": "", "location": { "address": "Yrjö-Koskisen katu 3, Helsinki", "lat": "60.1730803", "lng": "24.9525119", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Seitä pinaattikastikkeessa (vl)Jauhelihabolognaisea, juustoraastetta (g,l,pä,v)Tofu-gulassikeittoa (g,k,l,v,ve)" ] }, "tuesday": { "meal": [ "Kievin kanaa ja yrtti-aioli (g,l,se)Lindströminpihvit, tummaa sipulikastiketta (g)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)" ] }, "wednesday": { "meal": [ "Paistettua lohta, valkoviinikastiketta (vl)MakaronilaatikkoaTofu-pähkinäkastiketta (g,k,l,pä,ve)" ] }, "thursday": { "meal": [ "Katkaraputäytteinen kalaleike, ruohosipulidippiLihapyöryköitä, ruskeaa kastiketta (l,v)Purjo-perunasosekeittoa (g,k,vl)" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Topelias/1/6", "info": "", "location": { "address": "Unioninkatu 38, Helsinki", "lat": "60.1718645", "lng": "24.9504841", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1430" }, "tuesday": { "opening_time": "1100", "closing_time": "1430" }, "wednesday": { "opening_time": "1100", "closing_time": "1430" }, "thursday": { "opening_time": "1100", "closing_time": "1430" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Ravintola suljettu" ] }, "tuesday": { "meal": [ "Broilerinuggetit, currykastiketta (l,v)Kalaa tacokastikkeessa (g,pä,v,vl)Tofu-pähkinäkastiketta (g,k,l,pä,ve)" ] }, "wednesday": { "meal": [ "Quinoa-soijapannua (g,k,l,v,ve)MakaronilaatikkoaMustaherukkaista broilerinkastiketta (g,l)" ] }, "thursday": { "meal": [ "Broilerilasagnettea (v)Pekonista sieni-kaalipataa (g,l,v)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)" ] }, "friday": { "meal": [ "Lindströminpihvit, tummaa sipulikastiketta (g)Hunajaista kalapataa (g,vl)Mango-vihanneshöystöä (g,k,l,se,v,ve)" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php?ravintola=8#/Keskusta/Valtiotiede/1/7", "info": "", "location": { "address": "Unioninkatu 37, Helsinki", "lat": "60.173379", "lng": "24.9506235", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Ravintola suljettu 5-9.4.2012 Hyvää pääsiäistä!" ] }, "tuesday": { "meal": [ "Jauhelihakastiketta, juustoraastetta (l,v)Kalaburgerpihvit, tilli-kermaviilikastiketta (l)Parmesan-broilerisalaatti (l)Tofu-gulassikeittoa (g,k,l,v,ve)Banaanirahka (g,k,l) 1,20&euro;" ] }, "wednesday": { "meal": [ "Juustoiset broileripihvit ja currykastiketta (v,vl)Lindströminpihvit, tummaa sipulikastiketta (g)Kasviscouscousia, yrtti-tomaattikastiketta (k,l,v,ve)Lohisalaatti (g,l)Mangorahka 1,20&euro;" ] }, "thursday": { "meal": [ "Paistettua lohta, valkoviinikastiketta (vl)Broileri-vihannespannua (g,l,pä)Tofu-pähkinäkastiketta (g,k,l,pä,ve)Chili-katkarapusalaatti (g,l)Kaura-omenapaistos, kermavaahto (k,l) 1,20&euro;" ] }, "friday": { "meal": [ "Katkaraputäytteinen kalaleike, ruohosipulidippiItämaista kanakeittoa (g,l,se,v)Kookos-juureshöystöä (g,k,l,v,ve)" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php/Keskusta/Ylioppilasaukio/", "info": "", "location": { "address": "Mannerheimintie 3, Helsinki", "lat": "60.1689111", "lng": "24.9406031", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1900" }, "tuesday": { "opening_time": "1100", "closing_time": "1900" }, "wednesday": { "opening_time": "1100", "closing_time": "1900" }, "thursday": { "opening_time": "1100", "closing_time": "1900" }, "friday": { "opening_time": "1100", "closing_time": "1900" }, "saturday": { "opening_time": "1100", "closing_time": "1800" } }, "menu": { "monday": { "meal": [ "Ravintola suljettu" ] }, "tuesday": { "meal": [ "Lohta salsakastikkeessa (g,pä,v,vl)Itämaista kikhernekastiketta (g,l,v,ve)Farmarin pihvit, pippurikastikettaKookos-broilerihöystöä (g,vl)LounassalaattiSipulikeittoa (k,vl)" ] }, "wednesday": { "meal": [ "Hapanimelää porsaspataa (g,l,v)Kreikkalaista kalahöystöä (g,l,v)Parsa-kasvislasagnettea (k,vl)Lapinkeittoa (g,vl)Lounassalaatti" ] }, "thursday": { "meal": [ "Broileriratatouillea (g,l,v)Lohikebakoita, ruohosipuli-jogurttikastiketta (vl)Punajuuri-kaurapastavuokaa (k,l,v,ve)" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Keskusta" }, { "name": "UniCafe Biokeskus", "url": "http://www.unicafe.fi/index.php/Viikki/Biokeskus/", "info": "", "location": { "address": "Viikinkaari 9, Helsinki", "lat": "60.2269484", "lng": "25.0139846", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1500" }, "tuesday": { "opening_time": "1030", "closing_time": "1500" }, "wednesday": { "opening_time": "1030", "closing_time": "1500" }, "thursday": { "opening_time": "1030", "closing_time": "1500" }, "friday": { "opening_time": "1030", "closing_time": "1500" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Hyvää Pääsiäistä!" ] }, "tuesday": { "meal": [ "Paistettua lohta, tilli-kermaviilikastiketta (g,l)Lihapyöryköitä, ruskeaa kastiketta (l,v)Kaali-pastagratiinia (k,vl)Leipäjuustosalaatti (g,k)Linssikeittoa (g,k,l,v,ve)" ] }, "wednesday": { "meal": [ "Lohileike purjo-juustotäytteellä, ruohosipulidippiä (l)Broileria maapähkinäkastikkeessa (g,pä,vl)Kasvispilahvia, tomaattikastiketta (k,l,v,ve)Riistasalaattia (g,l)Nuudeli-kasviskeittoa (k,l,v,ve)" ] }, "thursday": { "meal": [ "Pippurista härkäpataa (l)Smetanasilakat (g,l)Hernekeittoa (g,l), pannukakkua ja hilloaKasvispyörykät, juustokastiketta (k,pä)Lohi-pastasalaatti (l)Kasvishernekeittoa (g,k,l,ve), pannukakkua ja hilloaKasvishernekeittoa (g,k,l,ve)pannukakkua ja hilloa 1,00&euro;" ] }, "friday": { "meal": [ "Jauhelihabolognaisea, juustoraastetta (g,l,pä,v)Tonnikala-katkarapukastiketta (l)Soija-kaalilaatikkoa (g,k,l,ve)Vuohenjuustokeittoa (g,k,l,v)" ] }, "saturday": { "meal": [ "Hyvää viikonloppua!" ] }, "sunday": { "meal": [ "Hyvää viikonloppua!" ] } }, "campus": "Viikki" }, { "name": "UniCafe Viikuna", "url": "http://www.unicafe.fi/index.php/Viikki/Viikuna/", "info": "Pizza 10:30-14:00", "location": { "address": "Agnes Sjöbergin katu 2, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1430" }, "tuesday": { "opening_time": "1030", "closing_time": "1430" }, "wednesday": { "opening_time": "1030", "closing_time": "1430" }, "thursday": { "opening_time": "1030", "closing_time": "1430" }, "friday": { "opening_time": "1030", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "RAVINTOLA SULJETTU 5.4-9.4.2012. AVAAMME JÄLLEEN 10.4.2012 KLO 08.00. HAUSKAA PÄÄSIÄISTÄ!!!" ] }, "tuesday": { "meal": [ "Porsaanleike, rosépippurikastiketta (l)Kalkkuna-vihannespataa (g,l)Kasvispihvit, linssimuhennosta (g,k,l,v,ve)Paahtopaistisalaattia (g,l)Banaani-suklaarahka 1,20&euro;" ] }, "wednesday": { "meal": [ "Jauheliha-tomaatti-sipulipizzaKolmen juuston pizzaKinkkumunakasta (g)Pesto-kasvispastaa (k,l,pä,v)Kalakeittoa (g,vl)Hedelmäinen kalkkunasalaatti (l)Mangokiisseli 1,20&euro;" ] }, "thursday": { "meal": [ "Nakkikastiketta (l,v)Lohikiusausta (g,vl)Falafel-pyörykät, tzatziki (k,l,se,v)Tonnikalasalaatti (g,l)Ananasriisi 1,20&euro;" ] }, "friday": { "meal": [ "Kinkku-ananas-aurajuustopizzaMozzarella-tomaatti-pestopizzaKebabkastiketta, juustoraastetta (g,l,v)Soijabolognaisea (g,k,l,v,ve)Kalaburgerpihvit, tilli-kermaviilikastiketta (l)Juustosalaatti (g,l)Sitruunapiirakka, vaniljakastike 1,40&euro;" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Viikki" }, { "name": "<NAME>", "url": "http://www.unicafe.fi/index.php/Viikki/Korona/", "info": "", "location": { "address": "Viikinkaari 11, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1100", "closing_time": "1400" }, "tuesday": { "opening_time": "1100", "closing_time": "1400" }, "wednesday": { "opening_time": "1100", "closing_time": "1400" }, "thursday": { "opening_time": "1100", "closing_time": "1400" }, "friday": { "opening_time": "1100", "closing_time": "1400" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Korona suljettu. Hauskaa pääsiäistä." ] }, "tuesday": { "meal": [ "Lihapyöryköitä, ruskeaa kastikettaKaali-pastagratiinia" ] }, "wednesday": { "meal": [ "Broileria maapähkinäkastikkeessaKasvispilahvia, tomaattikastiketta" ] }, "thursday": { "meal": [ "SmetanasilakatKasvispyörykät, juustokastiketta" ] }, "friday": { "meal": [ "Jauhelihabolognaisea, juustoraastettaSoija-kaalilaatikkoa" ] }, "saturday": { "meal": [ "Hyvää viikonloppua." ] }, "sunday": { "meal": [ "Hyvää viikonloppua." ] } }, "campus": "Viikki" }, { "name": "Tähkä", "url": "http://www.amica.fi/tahka#Ruokalista", "info": "", "location": { "address": "Koetilantie 7, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1330" }, "tuesday": { "opening_time": "1030", "closing_time": "1330" }, "wednesday": { "opening_time": "1030", "closing_time": "1330" }, "thursday": { "opening_time": "1030", "closing_time": "1330" }, "friday": { "opening_time": "1030", "closing_time": "1330" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "Naudanliha-juurespataa(M,L),Keitettyj&auml; perunoita (*, G, L, M)", "Broilerin rintaleike herkkusieni-pekonikastikkeessa (G, L,", "Kasvismusakaa (*)", "Juustoista riistakeittoa (G, VL)", "Omena-puolukkakukkoa (L, M),Vaniljakastiketta (G)" ] }, "tuesday": { "meal": [ "Uunimakkara pekoni-sipulit&auml;ytteell&auml; (G, L),Tomaattikastiketta (G, VL)", "Kylm&auml;savukirjolohi-juustokastiketta (VL),perunoita (*, G, L, M)", "Yrtti-juustopastaa (VL)", "Kermaista porkkanasosekeittoa (G, VL)", "Appelsiiniohukaisia,Kinuskikermavaahtoa (G)" ] }, "wednesday": { "meal": [ "Smetanalohta ja kes&auml;kurpitsaa (G,VL)", "Sveitsinleike (L),Perunasosetta (*, G, VL)", "Kookos-inkiv&auml;&auml;rimaustettua paistettua riisi&auml; (G, L, M)", "Hernekeittoa (G, L, M),Hienonnettua sipulia (G, L, M)", "Pannukakkua,Mansikkahilloa" ] }, "thursday": { "meal": [ "Jauhelihalasagnettea", "Smetanaseiti&auml; (G, VL),Keitettyj&auml; perunoita (*, G, L, M)", "Kasviksia soijakastikkeessa (G, L, M),H&ouml;yrytetty&auml; tummaa riisi&auml; Suklaakiisseli&auml; (G)" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Viikki" }, { "name": "Ladonlukko", "url": "http://www.sodexo.fi/ravintolaladonlukko", "info": "", "location": { "address": "Latokartanonkaari 9, Helsinki", "lat": "", "lng": "", "distance": "" }, "opening_hours": { "monday": { "opening_time": "1030", "closing_time": "1430" }, "tuesday": { "opening_time": "1030", "closing_time": "1430" }, "wednesday": { "opening_time": "1030", "closing_time": "1430" }, "thursday": { "opening_time": "1030", "closing_time": "1430" }, "friday": { "opening_time": "1030", "closing_time": "1430" }, "saturday": { "opening_time": "", "closing_time": "" } }, "menu": { "monday": { "meal": [ "" ] }, "tuesday": { "meal": [ "" ] }, "wednesday": { "meal": [ "" ] }, "thursday": { "meal": [ "" ] }, "friday": { "meal": [ "" ] }, "saturday": { "meal": [ "" ] }, "sunday": { "meal": [ "" ] } }, "campus": "Viikki" } ]
7861d637ddb562114b252ddf6a9b0c94a4345f4f
[ "JavaScript", "Ruby" ]
6
JavaScript
aaltowebapps/hungrybunch
4427743b0cce71ae845cb3ba13b4435dadbe0044
3c2acb0512781078dfdd005ffc6d924fe6000397
refs/heads/master
<file_sep># Hacker News Dashboard > The Hacker News Dashboard is a full-stack web application which utilizes the Hacker News API to provide a dashboard for data analysis and visualization. ## Team - __Product Owner__: <NAME> - __Scrum Master__: <NAME> - __Development Team Members__: <NAME>, <NAME> ## Table of Contents 1. [Usage](#Usage) 1. [Requirements](#requirements) 1. [Development](#development) 1. [Installing Dependencies](#installing-dependencies) 1. [Tasks](#tasks) 1. [Team](#team) 1. [Contributing](#contributing) ## Usage > Some usage instructions ## Requirements - Node 0.10.32 - Express ~4.9.0 - MySQL ? - Angular ~1.2.18 - etc ## Development ### Installing Dependencies From within the root directory: ```sh sudo npm install -g bower npm install bower install ``` ### Roadmap View the project roadmap [here](https://github.com/Scheming-Lion/Scheming-Lion/issues) ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines. <file_sep>module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), nodemon: { dev: { script: 'server/server.js' } }, karma: { all: { configFile: 'karma.conf.js' } }, shell: { options: { }, target: { command: ['cd testing', 'cd reports', 'open specRunner.html', 'cd coverage', 'open index.html'].join('&&') } }, watch: { scripts: { files: [ 'server/*.js', 'server/**/*.js', //------- need to be removed? ------// 'scraper/*.js', 'scraper/*.html', 'scraper/client/*.js', 'scraper/client/*.html', 'scraper/client/*.html', //---------------------------------// 'client/*.html', ], tasks: ['karma'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-shell'); grunt.registerTask('server-dev', function (target) { // Running nodejs in a different process and displaying output on the main console var nodemon = grunt.util.spawn({ cmd: 'grunt', grunt: true, args: 'nodemon' }); nodemon.stdout.pipe(process.stdout); nodemon.stderr.pipe(process.stderr); grunt.task.run([ 'watch' ]); }); //////////////////////////////////////////////////// // Forcing so karma will run/report even if a test fails /////////////////////////////////////////////////// grunt.registerTask('forceOn', 'turns the --force option ON', function() { if ( !grunt.option( 'force' ) ) { grunt.config.set('forceStatus', true); grunt.option( 'force', true ); } }); grunt.registerTask('forceOff', 'turns the --force option Off', function() { if ( grunt.config.get('forceStatus') ) { grunt.option( 'force', false ); } }); //////////////////////////////////////////////////// // Main grunt tasks //////////////////////////////////////////////////// grunt.registerTask('test', ['forceOn','karma', 'forceOff', "shell"]); grunt.registerTask('build', []); grunt.registerTask('deploy', function(n) { if(grunt.option('prod')) { // add your production server task here } else { // add your dev server task here } }); }; <file_sep>//Firebase has a module that will handle data updating through its event handling system var Firebase = require('firebase'); var url = "https://hacker-news.firebaseio.com/v0/item/"; var postId = 3000; //hard-coded for now. Will need to get this from an input tag var postRef = new Firebase(url + postId); // Attach an asynchronous callback to read the data at our post reference postRef.on('value', function (snapshot) { console.log(snapshot.val()); }, function (errorObject) { console.log('The read failed: ' + errorObject.code); });<file_sep>/* This all needs to be integrated with angular and retrieve the username from an input tag in html, but right now it's hardcoded and seems to work. Bug: doesn't work for users with a HUGE amount of submissions. For example, pg has over 12000, so it freaks out if you try him */ var username = "seanmccann"; var storyIds; var items = []; var topStories; var url = "https://hacker-news.firebaseio.com/v0/"; $.get(url + "/user/" + username + ".json", function(userProfile, status) { storyIds = userProfile.submitted; storyIds.forEach(function(storyId) { $.get(url + "/item/" + storyId + ".json", function(story, status) { items.push(story); if(items.length === storyIds.length) { stories = items.filter(function(story) { return story.score; }); stories.sort(sortByScore); topStories = stories.slice(0,10); // console.log(topStories); // $('.view').append('<h3>' + 'Top Stories By '+ username +'<br>' + '</h3>'); for(var i = 0; i < topStories.length; i++){ var story = "<div class='story'>" + '<strong>Title: </strong>'+ topStories[i].title + '<br>' + "<strong>Score: </strong>" + topStories[i].score + '<br>' + "<strong>Link: </strong>" + topStories[i].url +'<br>'+'<br>' + "</div>"; // $('.view').append(story); } } }); }); }); function sortByScore(a,b) { if (a.score < b.score) return 1; if (a.score > b.score) return -1; return 0; }<file_sep>angular.module('myApp.directives', []) .factory('myName', function(d3Service, $interval) { return { link: function(scope,element, attrs) { d3Service.d3().then(function(d3) { var wordCount = scope.wordCount; var amount = Math.ceil(Math.sqrt(wordCount.length)); var svgContainer = d3.select(".wordVisual").append("svg") .attr("class", "wordVisual") .attr("width", 1000) .attr("height", 1000); var update = function(data) { var column = 0; var counter = 0; var row = 50; var rowCounter = 0; var wordsVisual = svgContainer.selectAll("text") .data(data); wordsVisual.attr("class", "update"); wordsVisual.enter().append("text") .attr("x", function(d,i) { if ( (i-(counter*amount)) > amount) { column+= 40; counter++; } return column; }) .attr("y", function(d,i) { if ( (i-(rowCounter*amount)) > amount ) { row=50; rowCounter++; } else { row += 40; } return row; }) .attr("font-size", function(d) { return d.count*10 +"px"; }) .attr("fill", "#2b3e50") .text(function(d) { return d.word; }) .transition() .duration( 500 ) .attr("fill", "white"); wordsVisual.exit().remove(); }; update(wordCount); }); }, restrict: 'EA', scope: { wordCount: "=" } }; }) .directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { if(attrs.href === '' || attrs.href === '#'){ elem.on('click', function(e){ e.preventDefault(); }); } } }; });<file_sep>//Firebase has a module that will handle data updating through its event handling system var Firebase = require('firebase'); var url = "https://hacker-news.firebaseio.com/v0/user/"; var username = "seanmccann"; //hard-coded for now. Will need to get this from an input tag var postRef = new Firebase(url + username); // Attach an asynchronous callback to read the data at our post reference postRef.on('value', function (snapshot) { console.log(snapshot.val()); }, function (errorObject) { console.log('The read failed: ' + errorObject.code); });
6bfefe8bab54fd80b4190f70ca40493281c214aa
[ "Markdown", "JavaScript" ]
6
Markdown
Oleg24/Scheming-Lion
7e9111b801414d6189367a6b28a62b00908f45d4
b1d527fc94572f3e5487f506b2f76ffead24aa7d
refs/heads/main
<repo_name>IreshOG/bus-booking<file_sep>/MyBusWS/src/routes/routing.js const express = require("express"); const routing = express.Router(); const carBookingService = require("../services/users"); const CarBooking = require("../model/carbooking"); //showmy car database routing.get("/show",async(req,res,next)=>{ try{ let data = await carBookingService.getAllCar(); res.json(data); }catch{ next(err); } }) //Showing all details for the booking of car routing.get("/getAllBookings",async(req,res,next)=>{ //let bid = parseInt(req.params.bookingId); try{ let bookings= await carBookingService.getAllBookings(); res.json(bookings); }catch(err){ next(err); } }) // Inserting car booking routing.post("/bookCar", async (req,res,next)=>{ console.log(req.body); const carBooking = new CarBooking(req.body); try{ let bookingId = await carBookingService.bookCar(carBooking); res.json({ "message": "Car booking is successful with booking Id " + bookingId }); } catch (error) { next(error); } }) //delete booking routing.put("/deleteBooking/:bookingId",async(req,res,next)=>{ let bid = parseInt(req.params.bookingId); try{ let d = await carBookingService.deleteById(bid); res.json("Your booking is deleted"); }catch(err){ next(err); } }) //update route module.exports = routing;<file_sep>/MyBusWS/src/services/users.js const CarBooking = require("../model/carbooking"); const db = require("../model/users"); const validator = require("../utilities/validator"); let carBookingService = {} //getting carDB carBookingService.getAllCar = async()=>{ let data = await db.getAllCar(); if(data){ return data; }else{ let error = new Error("No Cars found in database"); error.status = 404; throw error; } } //Getting All Bookings carBookingService.getAllBookings = async() =>{ let bookings = await db.getAllBookings(); if (bookings == null) { let error = new Error("No bookings found"); error.status = 404; throw error; } else { return bookings; } } //Service for car booking carBookingService.bookCar = async (carBooking) =>{ validator.validateCarId(carBooking.carId); let passenger = await db.checkCustomer(carBooking.customerId); if (passenger) { console.log("received date in service"+carBooking.dateOfBooking); let car = await db.checkAvailability( carBooking.carId,carBooking.dateOfBooking); if (car) { promise = await db.bookCar(carBooking); //let bookingId = await promise; return promise; } else { let error = new Error("Car not available"); error.status = 404; throw error; } } else { let error = new Error("Registration not found. Register to proceed"); error.status = 404; throw error; } } carBookingService.getById = async(bookingId)=>{ let data = db.getBookingById(bookingId); if(data){ return data; }else{ let e = new Error("No bookings by Id:"+bookingId+"found"); e.status=404; throw e; } } carBookingService.deleteById = async(bookingId)=>{ let data = db.deletebooking(bookingId); if(data){ return data; }else{ let err = new Error("No booking found"); err.status = 500; throw err; } } module.exports = carBookingService;<file_sep>/MyCarUI/src/app/shared/booking.ts export class Booking{ userid:Number=0; bookingid:Number=0; dob:Date; carid:Number=0; price:Number = 0; }<file_sep>/MyBusWS/src/model/busbooking.js class BusBooking { constructor ( obj ) { this.passengerId = obj.passengerId; this.bookingId = obj.bookingId; this.numberOfTickets = obj.numberOfTickets; this.bookingCost = obj.bookingCost; this.busId = obj.busId; this.bookingDate = obj.bookingDate; } } module.exports = BusBooking;<file_sep>/MyBusWS/src/model/carbooking.js class CarBooking { constructor ( obj ) { this.customerId = obj.customerId; //this.bookingId = obj.bookingId; this.price = obj.price; this.carId = obj.carId; this.dateOfBooking = obj.dateOfBooking; //this.cartype = obj.cartype; } } module.exports = CarBooking;<file_sep>/MyCarUI/src/app/view-cars/view-cars.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-view-cars', templateUrl: './view-cars.component.html', styleUrls: ['./view-cars.component.css'] }) export class ViewCarsComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>/MyCarUI/src/app/booking-form/booking-form.component.ts import { Component, OnInit } from '@angular/core'; import {FormGroup, FormBuilder, Validators} from '@angular/forms'; import {BookingserviceService} from '../bookingservice.service'; @Component({ selector: 'app-booking-form', templateUrl: './booking-form.component.html', styleUrls: ['./booking-form.component.css'] }) export class BookingFormComponent implements OnInit { bookingform:any; constructor(private fb:FormBuilder,private bs:BookingserviceService) { } //bookingform; data=''; ngOnInit(): void { this.bookingform = this.fb.group({ uid: ['',Validators.required], cid:['',Validators.required], dob:['',Validators.required], //cartype:['',Validators.required], price:['',Validators.required] }); } submit():void{ // console.log(this.data); this.bookingform.reset(); } bookCar():void{ this.bs.bookMyCar(this.bookingform.value).subscribe((res)=>{ console.log(res); //this.submit(); }, (err)=>console.log(err) ); } } <file_sep>/MyBusWS/src/model/users.js const dbModel = require("../utilities/connection"); const CarBooking = require("./carbooking"); const carBookingDb = {}; // Generate Id carBookingDb.generateId = async() =>{ let model = await dbModel.getBookingCollection(); let ids = await model.distinct("bookingId"); let bookId = Math.max(...ids); return bookId + 1; } //get all carDB carBookingDb.getAllCar = async() =>{ let model = await dbModel.getCarCollection(); let data = await model.find({}); if(data.length>0){ return data; }else{ return null; } } //Getting all bookings carBookingDb.getAllBookings = async () =>{ let model = await dbModel.getBookingCollection(); let booking = await model.find({}, { _id:0 }); if(!booking || booking.length == 0) return null; else return booking; } //Check Customer carBookingDb.checkCustomer = async (customerId) =>{ let model = await dbModel.getCustomerCollection(); let customer = await model.findOne({ customerId: customerId}); if (customer) { return customer; } else { return null; } } //Check Availability carBookingDb.checkAvailability = async (carId,dateOfBooking) => { console.log("Received date "+dateOfBooking) let model = await dbModel.getBookingCollection(); let carAvailability = await model.find({ carId:carId }); let f=0; let y = new Date(dateOfBooking).getFullYear(); let m = new Date(dateOfBooking).getMonth(); let d1 = new Date(dateOfBooking).getDate(); //console.log("Given date : "+typeof(d)); for(d of carAvailability){ // console.log(d.dateOfBooking); let year = new Date(d.dateOfBooking).getFullYear(); let month = new Date(d.dateOfBooking).getMonth(); let date = new Date(d.dateOfBooking).getDate(); //console.log(" Date : "+d); if(y==year && m==month && d1==date){ console.log("H"); f=1; break; } } console.log("f = "+f ); if (f==0) { return carAvailability; } else { return null; } } //To book the car carBookingDb.bookCar = async (carBooking) => { let model = await dbModel.getBookingCollection(); let bookId = await carBookingDb.generateId(); carBooking.bookingId = bookId; let c = model.countDocuments(); console.log(c); let data = await model.insertMany({bookingId: carBooking.bookingId, customerId:carBooking.customerId, carId:carBooking.carId,dateOfBooking:carBooking.dateOfBooking ,cartype:carBooking.cartype,price:carBooking.price}); console.log(data); if (data){ return carBooking.bookingId; } else{ return null; } } //get booking by id carBookingDb.getBookingById = async(bookingid)=>{ let book = await dbModel.getBookingCollection(); let data = await book.findOne({bookingId:bookingid}); if(data.length>0){ return data; }else{ return null; } } carBookingDb.deletebooking = async(bookingid)=>{ let book = await dbModel.getBookingCollection(); let data = await book.findOne({bookingId:bookingid}); if(data){ let del = data.deleteOne({bookingId:bookingid}); if(del.deletedCount){ return true; }else{ return false; } } } module.exports = carBookingDb<file_sep>/MyBusWS/src/utilities/validator.js let Validator = {}; //To validate bus Id Validator.validateCarId = function (carId) { let pattern = new RegExp("^[MSL][0-9]{3}$"); if (carId.length != 5 && !(pattern.test(carId))) { let error = new Error("Error in car Id"); error.status = 406; throw error; } } //To validate booking Id Validator.validateBookingId = function (bookingId) { if (new String(bookingId).length != 4) { let error = new Error("Error in booking Id"); error.status = 406; throw error; } } module.exports=Validator;<file_sep>/MyCarUI/src/app/bookingservice.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class BookingserviceService { constructor(private http:HttpClient) { } //function to bookcar bookMyCar(data:Object):Observable<Object>{ return this.http.post<Object>("http://localhost:3000/bookCar/",data); } }
c4391e3b6dc48212438accc0d42e040716afe2de
[ "JavaScript", "TypeScript" ]
10
JavaScript
IreshOG/bus-booking
ec0646556ab0a8cc8be87ce4a2e29f1e0df09184
29db60d7d87769ba59ff90206dba73e1e0b4561c
refs/heads/master
<repo_name>ibayrak/project1<file_sep>/project1/csv_parser.py import csv import sys f = open('C:\some.csv', 'rt') count=1 try: reader = csv.reader(f) next(f) for row in reader: print("Person %d" % count) print("First Name:"+row[0]) print("Last Name:"+row[1]) if row[2] != '': print("Email:"+row[2]) if row[3] != '': print("Phone:"+row[3]) print("") count +=1 finally: f.close() <file_sep>/project1/uploadcsv/views.py # -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.shortcuts import render from django.core.urlresolvers import reverse from django.core.management import call_command import csv from project1.uploadcsv.models import Document from project1.uploadcsv.forms import DocumentForm from project1.uploadcsv.models import Member def home(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return render_to_response('uploadcsv/showmember.html', {'members': get_members(newdoc)}, context_instance=RequestContext(request) ) else: form = DocumentForm() # A empty, unbound form # Render list page with the documents and the form return render_to_response( 'uploadcsv/home.html', {'form': form}, context_instance=RequestContext(request) ) def get_members(newdoc): members=[] with open('project1/media/csv_uploads/sportslab_members.csv') as f: reader = csv.reader(f, delimiter=',') count=0 for row in reader: if count!=0 : member= Member() member.name=row[0] member.surname=row[1] member.email=row[2] member.phone=row[3] members.append(member) count=+1 return members <file_sep>/project1/uploadcsv/models.py # -*- coding: utf-8 -*- from django.db import models class Document(models.Model): docfile = models.FileField(upload_to='csv_uploads') class Member(models.Model): name =models.CharField(max_length=200) surname=models.CharField(max_length=200) email =models.CharField(max_length=100) phone=models.CharField(max_length=20)
662178c188c54a3acd525c34cf7339baa6454f38
[ "Python" ]
3
Python
ibayrak/project1
7f47c3804db7fe6daae7f7f6d7da2093257ae64e
2e196fc4e0a5b76d3140383438f11cc2932c663e
refs/heads/master
<repo_name>ccamiletti/family-cost<file_sep>/app/family-cost-backend/src/main/java/com/ccs/familycost/repository/impl/UserRepositoryImpl.java package com.ccs.familycost.repository.impl; import com.ccs.familycost.repository.UserRepositoryCustomer; public class UserRepositoryImpl implements UserRepositoryCustomer { /* * @PersistenceContext private EntityManager entityManager; */ } <file_sep>/app/family-cost-backend/src/main/java/com/ccs/familycost/controller/LoginController.java package com.ccs.familycost.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.ccs.familycost.model.UserEntity; import com.ccs.familycost.services.UserService; @Controller @RequestMapping("/login") public class LoginController { @Autowired private UserService userService; @RequestMapping("") public void login(@RequestBody UserEntity user) { System.out.println(user); //userService.findById(user); } } <file_sep>/app/family-cost-backend/src/main/java/com/ccs/familycost/repository/UserRepository.java package com.ccs.familycost.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.ccs.familycost.model.UserEntity; public interface UserRepository extends JpaRepository<UserEntity, Long>, UserRepositoryCustomer { @Query("SELECT u FROM UserEntity u LEFT JOIN FETCH u.roles WHERE u.userName=?1") Optional<UserEntity> findByUserName(String userName); Optional<UserEntity> findByEmail(String email); }
0020f6d372a7f56395598c5d417e0b69cafc0cb4
[ "Java" ]
3
Java
ccamiletti/family-cost
c39d8af449f816cfc1c01260df3eccc7b6443994
1b744116fef18230b9f2d14902c955141a8304d9
refs/heads/master
<repo_name>baixiaosh/react-typescript-tools<file_sep>/README.md ## 说明 ts tool<file_sep>/src/redux/index.ts import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import reducers from './reducer/combineReducer'; let createAppStore = applyMiddleware(thunk)(createStore); export const Store = createAppStore(reducers);<file_sep>/src/redux/action/beta/index.ts import types from '../../types/beta'; export default { betaChange: (): any => { return { type: types.BETA_TYPE }; } };;<file_sep>/src/redux/reducer/combineReducer.ts import { combineReducers } from 'redux'; import beta from './beta'; export default combineReducers({ beta });
b9d17afc046c535c003ebcb2bfe1480736af8be7
[ "Markdown", "TypeScript" ]
4
Markdown
baixiaosh/react-typescript-tools
6e8f7884f88b859a5567ae0eb73b8d917137d822
62bd856f95d0f0c4854f1078b7839ee2cbd245ab
refs/heads/master
<file_sep>function userTracker(_rupu,username){ var me = this; this._rupu = _rupu; this.bind(); this._db = new ajaxQueue({url:'usertracker.php',dataType:'json',type:'POST'}); this._userData = { 'user_id':username, 'start_time':Date.now(), 'window':[window.innerWidth,window.innerHeight], 'screen':[window.screen.width,window.screen.height], 'media':window.styleMedia.type, 'type':navigator.userAgent, 'vendor':navigator.vendor, 'latitude':0, 'longitude':0 } if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(e){ me._userData.latitude = e.coords.latitude; me._userData.longitude = e.coords.longitude; me._setUser(); }); } else { this._setUser(); } } userTracker.prototype = { _setUser:function(){ if (!this._userData.user_id){ if (!localStorage.getItem('rupu_id')){ localStorage.setItem('rupu_id',getId()); } this._userData.user_id = localStorage.getItem('rupu_id'); } localStorage.setItem('rupu_id',this._userData.user_id); this._db.add({ login:this._userData.user_id, userdata:this._userData }); }, bind:function(rupu){ var me = this; if (rupu) this._rupu = rupu; this._rupu.on('tracker',function(e){ e.time = Date.now(); e.user_id = me._userData.user_id; e.session_id = me._userData.session_id; e.latitude = me._userData.latitude; e.longitude = me._userData.longitude; me._db.add({data:e}); }); } } function ajaxQueue(args,oncomplete){ this._args = args; this._reqs = []; this._result = []; this._busy = false; this._callback = oncomplete || function(){}; } ajaxQueue.prototype = { add:function(data){ this._reqs.push(data); this._ready(); }, _error:function(e){ if (typeof(this.onError)=='function'){ this.onError(e); } else if (e.responseText){ console.log(e.responseText); } else console.log(e); }, _ready:function(e){ if (this._reqs.length > 0 && !this._busy){ this._send(this._reqs.shift()); } else if (this._reqs.length == 0){ this._callback.call(this, this._result); this._result = []; } }, _send:function(data){ var me = this; this._busy = true; $.ajax({ url:this._args.url, dataType:this._args.dataType, type:this._args.type, data:data, success:function(e){ me._busy = false; if (e.ok == true || e.ok == 'true'){ me._result.push(e); me._ready(); } else { me._error(e); } }, error:function(e){ me._busy = false; me._error(e); me._ready(); } }); } } <file_sep>var //smallImageURL = 'http://ereading.metropolia.fi/puru/img/small/', smallImageURL = 'http://ereading.metropolia.fi/puru/img/', imageURL = 'http://ereading.metropolia.fi/puru/img/', parserURL = 'parser.php'; var rupu = function(){ // iscroll common options this.iscrollOpts = { momentum:true, vScrollbar:false, hScrollbar:false, SnapThreshold:500, lockDirection:true } // elements for rupu to use this.panes = { brand: $('<div id="brand-display"></div>'), top: $('<div id="top-bar"></div>'), left : $('<div id="left-pane" class="pane"></div>'), right : $('<div id="right-pane" class="pane"></div>'), menu_container : $('<div id="menu-container"></div>'), menu_container_scroller : $('<div id="menu-container-scroller"></div>'), main : $('<div id="main-pane" class="pane"></div>'), main_scroller : $('<div id="main-pane-scroller"></div>'), main_content : $('<div id="main-pane-content"></div>'), container : $('<div id="main"></div>') } this._mainScroll = false; // iscroll for main element, the horizontal scroller this._pageScroll=false; // page, item display scroller this._menuScroll=false; this._mainPaneScroll=false; // main pane, the tile display scroll this._listeners =[]; // event listeners registered for rupu this._border = 0; this._gutter = 16; this._lang = 'fi'; this._maintitle = ''; this._subtitle = ''; } rupu.prototype = { showCategories:function(){ if (this._loaded){ var list = this._getCategoryNames(), me = this, e = this.panes.menu_container, brand = $([ '<div id="brand-display">', '<h2 class="title">',this._source.title,'</h2>', '<h2 class="datetime">',dateParser.getDate(this._source.timestamp*1000),'</h2>', //'<img src="',this._source.image.url,'" alt="" />', ,'</div>' ].join('')); e.append(brand); for (var i in list){ if (list[i]){ var items =this.getCategory(list[i]); this._sortSet(items); var img = ''; for (var v in items){ if (items[v].hasImage()){ img = '<img src="'+smallImageURL+items[v].getImageName()+'"/>'; break; } } var c = $('<div id="'+list[i]+'" class="category tile">'+img+'<h4 style="background-color:'+colors.getColor(list[i],0.7)+'">'+list[i]+'</h4></div>') c.hammer().on('tap',function(){ me.showCategory($(this).attr('id')); me._fire('tracker',{'action':'open_category','event_type':'menubutton_tap','data':$(this).attr('id')}); }); c.css({ 'background-color':colors.getColor(list[i]), }) e.append(c); } } this._container.css('background-color',colors.getColor('categories',1)); this._menuScroll = new iScroll(this.panes.right.attr('id'),this.iscrollOpts); this._tile(); } }, // start rupu // container is the element for rupu run in start:function(container){ var me = this; this._dummy = $('<div id="dummy" />'); this._items = []; this.panes.container .append(this.panes.left.append(this.panes.left_newscontainer)) .append(this.panes.main.append(this.panes.main_scroller.append(this.panes.main_content))) .append(this.panes.right.append(this.panes.menu_container_scroller.append(this.panes.menu_container))); $(container).append(this.panes.container); this._container = $(container); this.panes.container.css({ position:'absolute', left:'0px', top:'0px' }); this.panes.container._translate(0,0); this.panes.left.hammer().on('tap',function(){ me._showPane('main-pane'); me._fire('tracker',{'action':'close_article','event_type':'tap','data':me.getVisibleItem()}); me._fire('hideItem',me.getVisibleItem()); }); this._lastEvent = false; this.panes.container.on('mousedown',function(e){ me._lastEvent = false; }); this.panes.container.hammer().on('touchstart',function(e){ me._lastEvent = false; }); this.panes.container.hammer().on('dragleft dragright',function(e){ var dist = 0; if (me._lastEvent){ dist = e.gesture.deltaX- me._lastEvent.gesture.deltaX; } me._drag(dist); me._lastEvent = e; }); this.panes.container.hammer().on('touchend',function(e){ me._checkPosition(); }); this.panes.container.on('mouseup',function(e){ me._checkPosition(); }); this.overlay(true); this.on('load',function(){ me._loaded = true; me.scale(); me.showCategories(); me._showPane('right-pane'); me.overlay(); me._scrollRefresh(); }); $(window).resize(function(){ me.overlay(true); clearTimeout(me._onscale); me._onscale = setTimeout(function(){ me.scale(); me.overlay(false); me._fire('tracker',{'action':'window_resize','event_type':'','data':[window.innerWidth,window.innerHeight].join(',')}); me._fire('resize',[window.innerWidth,window.innerHeight]); },200); }); $(function(){ document.title = this._maintitle || ''; }); this._fire('start'); this._getData(); me._fire('tracker',{'action':'restart','event_type':'page reload','data':''}); }, loading:function(show){ var me = this; if (!this._loading){ this._loading= $([ '<div id="loading-overlay">', '</div>' ].join('')).css({ position:'fixed', top:'0px', left:'0px', width:'100%', height:'100%', opacity:'0' }); } if (show){ if (!this._hasLoadingOverlay){ this._container.append(this._loading); this._hasLoadingOverlay = true; this._loading.animate({ opacity:1, },100); } } else { if (this._hasLoadingOverlay){ this._loading.animate({ opacity:0, },100,function(){ me._hasLoadingOverlay = false; me._loading.remove(); }) } } }, overlay:function(show){ var me = this; if (!this._overlay){ this._overlay= $([ '<div id="overlay">', '<h1 class="main-title">',this._maintitle,'</h1>', '<h3 class="sub-title">',this._subtitle,'</h3>', '<img src="css/load-icon.png" alt="" class="clock-icon" />', '</div>' ].join('')).css({ position:'fixed', top:'0px', left:'0px', width:'100%', height:'100%', opacity:'0' }); } if (show){ if (!this._hasOverlay){ this._container.append(this._overlay); this._hasOverlay = true; this._overlay.animate({ opacity:1, },100); } } else { if (this._overlay){ this._overlay.animate({ opacity:0, },500,function(){ me._hasOverlay = false; me._overlay.remove(); }) } } }, error:function(e){ if (e.stack) console.log(e.stack); this._fire('tracker',{'action':'error','event_type':'error','data':e.message}); this.overlay(true); this._overlay.append('<h3 class="error">something is not quite right just now. try again later :(</h3>') }, getVisibleItem:function(){ return this.panes.left.find('#page').attr('data-item'); }, useBigImage:function(){ if (window.innerWidth > 900){ return true; } else { return false; } }, // scale the elements according to screen size changes scale:function() { var me = this; this.panes.container._translate(0,0); var topOffset = 0;///this.panes.top.height(); this._container.css({ top:0, height:window.innerHeight }) this.panes.left.css({ top:0, left:0, width:window.innerWidth > 900 ? (window.innerWidth*0.5 < 900 ? 900 : window.innerWidth*0.5) : (window.innerWidth > 1000 ? 1000 : window.innerWidth) }); this.panes.main.css({ width:window.innerWidth, left:this.panes.left.width(), height:window.innerHeight - topOffset, top:0 }); this.panes.right.css({ width:window.innerWidth, left:this.panes.left.width() + this.panes.main.width(), top:0 }); this.panes.container.css({ top: topOffset, width: this.panes.left.width() + this.panes.main.width() + this.panes.right.width() }); this._leftPos = 0; this._mainPos = -this.panes.left.outerWidth(true); this._rightPos = -(this.panes.left.outerWidth(true) + this.panes.right.outerWidth(true)); var w = this.panes.main_content.innerWidth(); var s1 = (w), s2 = (w- ((1*this._gutter) - (4*this._border)) )/2, s3 = (w- ((2*this._gutter) - (6*this._border)) )/3, s4 = (w- ((3*this._gutter) - (8*this._border)) )/4; this._itemWidth = s1 < 900 ? s1 : s2 < 500 ? s2 : s3 > 450 ? s4 : s3; this._itemWidth--; var mw = this.panes.menu_container.innerWidth(); var ms2 = (mw - 1*this._gutter) / 2, ms3 = (mw - 2*this._gutter) / 3, ms4 = (mw - 3*this._gutter) / 4, ms5 = (mw - 4*this._gutter) / 5; this._tileWidth = ms2 < 300 ? ms2 : ms3 < 300 ? ms3 : ms4 < 300 ? ms4 : ms5; this._tileWidth--; try{ this._scrollRefresh(); this._tile(); } catch (e){ this.error(e); } this._fire('scale'); this._showPane(this._currentPane); }, _animate:function(distance,callback){ var lastStep = 0, me = this; this._dummy.stop(); this._dummy.css('width','100px'); this._dummy.animate({ width:0 },{ step:function(step){ var cdist = (step-100) * (distance/100); me._drag( -(cdist-lastStep) ); lastStep = cdist; }, duration:200, complete:callback }); }, _drag:function(distance){ var pos = this.panes.container._getPosition().left; this.panes.container._translate(pos+distance,0); }, _checkPosition:function(){ var me = this; var position = this.panes.container._getPosition().left, diffToMain = this._mainPos-position, diffToRight = this._rightPos-position, diffToLeft = this._leftPos-position; var panToright = Math.abs( diffToRight )< (this.panes.right.outerWidth(true)/2) ? true : position < this._rightPos; var panToLeft = Math.abs( diffToLeft ) < (this.panes.left.outerWidth(true)/2) ? true : position > this._leftPos; if (panToright){ if (this._currentPane != 'right-pane'){ me._fire('tracker',{'action':'show_menu','event_type':'drag','data':'right-pane'}); } this._showPane('right-pane'); } else if (panToLeft){ if (this._currentPane != 'left-pane'){ me._fire('tracker',{'action':'open_article','event_type':'drag','data':this.getVisibleItem()}); //me._fire('tracker',{'action':'show_pane','event_type':'drag','data':'left-pane'}); } this._showPane('left-pane'); } else { if (this._currentPane == 'left-pane'){ me._fire('tracker',{'action':'close_article','event_type':'drag','data':this.getVisibleItem()}); } if (this._currentPane != 'main-pane'){ me._fire('tracker',{'action':'open_category','event_type':'drag','data':this._currentCategory}); } this._showPane('main-pane'); } if (this._lastEvent){ if (this._lastEvent.gesture.velocityX > 2.0 || Math.abs(this._lastEvent.gesture.deltaX > 150)){ if (this._lastEvent.gesture.direction == 'left'){ if (this._currentPane == 'left-pane'){//Math.abs(diffToLeft)<Math.abs(diffToMain)){ //me._fire('swipeTo','main-pane'); if (this._currentPane == 'left-pane'){ me._fire('tracker',{'action':'close_article','event_type':'swipe','data':this.getVisibleItem()}); } if (this._currentPane != 'main-pane'){ me._fire('tracker',{'action':'open_category','event_type':'swipe','data':this._currentCategory}); } this._showPane('main-pane'); } else { if (this._currentPane != 'right-pane'){ me._fire('tracker',{'action':'close_category','event_type':'swipe','data':this._currentCategory}); me._fire('tracker',{'action':'show_menu','event_type':'swipe','data':'right-pane'}); } this._showPane('right-pane'); } } else if (this._lastEvent.gesture.direction == 'right'){ if (this._currentPane == 'right-pane'){//Math.abs(diffToRight)<Math.abs(diffToMain)){ //me._fire('swipeTo','main-pane'); if (this._currentPane != 'main-pane'){ me._fire('tracker',{'action':'open_category','event_type':'swipe','data':this._currentCategory}); } this._showPane('main-pane'); } else { //me._fire('swipeTo','left-pane'); if (this._currentPane != 'left-pane'){ me._fire('tracker',{'action':'open_article','event_type':'swipe','data':this.getVisibleItem()}); me._fire('tracker',{'action':'show_pane','event_type':'swipe','data':'left-pane'}); } this._showPane('left-pane'); } } } } }, // scroll to certain pane with _mainScroll-horizontal scroll _showPane:function(id,callback){ var position = 0; if (id == 'main-pane'){ if (this._currentCategory){ position = -this.panes.left.outerWidth(true); } else { this._showPane('right-pane'); return; } } else if (id == 'left-pane'){ if (this.panes.left.children().length > 0){ if (this._currentPane == 'right-pane'){ this._showPane('main-pane'); return; } position = 0; } else { this._showPane('main-pane'); return; } } else if (id == 'right-pane'){ if (this._currentPane == 'left-pane'){ this._showPane(main-pane); return; } position = -(this.panes.left.outerWidth(true) + this.panes.right.outerWidth(true)); } var diff = -this.panes.container._getPosition().left + position; this._currentPane = id; this._animate(diff,callback); this._fire('showPane',id); }, _sortSet:function(items){ items.sort(function(a,b){ return a.priority - b.priority; }); items.sort(function(a,b){ if (a.hasImage() && !b.hasImage()){ return -1; } else if (!a.hasImage() && b.hasImage){ return 1; } else { return 0; } }) }, // show category of items by category name showItems:function(items,sort){ var me = this, found = false, e = []; if (!sort){ this._sortSet(items); } each(items,function(item){ e.push(item.getTile()); }); //e.unshift( $('<div class="category-title"><h2>'+this._currentCategory+'</h2></div>') ); this._showAtPane(e); this._fire('showItems',items); }, showCategory:function(cat){ cat = cat.toLowerCase(); this._currentCategory = cat; var items = this.getCategory(cat); this.showItems(items); this._container.css('background-color',colors.getColor(cat,1)); this._fire('showCategory',cat); }, // show news item in left pane display showItem:function(id,scrollTo){ var me = this; var container = this.panes.left; if (container.find('[data-item="'+id+'"]').length > 0){ if (scrollTo!=false){ me._showPane('left-pane'); } } else { var e = this._getItem(id).getFull(); container.imagesLoaded(function(){ container.transit({ opacity:0, },200,function(){ container.html(e); /* container.find('h1, h2, h3, h4').each(function(){ $(this).addClass('hyphenate text').attr('lang',me._lang); }); */ //Hyphenator.run(); if (scrollTo!=false){ me._showPane('left-pane'); } if (me._pageScroll){ me._pageScroll.destroy(); } container.find('img').each(function(){ if ($(this).outerHeight() > $(this).outerWidth()){ container.find('.news-page').addClass('tall-image'); } }); container.transit({opacity:1}); me._pageScroll = new iScroll('page',me.iscrollOpts); me._fire('showItem',id); }); }); } }, _scrollRefresh:function(){ if (this._mainPaneScroll && this._mainPaneScroll!=undefined){ this._mainPaneScroll.destroy(); } if (this._menuScroll){ this._menuScroll.refresh(); } if (this._pageScroll){ this._pageScroll.refresh(); } this._mainPaneScroll = new iScroll('main-pane',this.iscrollOpts); }, _tile:function(callback){ var container = this.panes.main_content; var menu = this.panes.right.find('#menu-container'); var me = this; var gutter = me._gutter, border = me._border; if (menu[0]){ menu.imagesLoaded(function(){ menu.find('.tile').each(function(){ $(this).css({ 'width':me._tileWidth, 'height':me._tileWidth, }); }); var mp = new Packery(menu[0],{ gutter:gutter }); me._scrollRefresh(); }); } container.imagesLoaded(function(){ container.find('.tile, .category-title').each(function(){ $(this).css({ 'width':me._itemWidth, }); if ($(this).hasClass('category-title')){ $(this).css('width',container.innerWidth()); } if ($(this).width() >= 0.8*container.innerWidth()){ $(this).addClass('one-row'); } else { $(this).removeClass('one-row'); } if ($(this).find('.newsitem-imagecontainer').height() > $(this).find('.newsitem-imagecontainer').width()){ $(this).addClass('tall-image'); if ($(this).hasClass('one-row')){ $(this).find('.image-item-header-container').css('background-color',colors.getColor($(this).attr('category'),1)); } } if (parseInt( $(this).attr('priority') ) < 6 && $(this).hasClass('has-image')){ $(this).addClass('double-size'); $(this).find('.image-item-header-container').css('background-color',colors.getColor($(this).attr('category'),1)); if (window.innerWidth >= me._itemWidth*2){ $(this).css('width',(me._itemWidth*2)+gutter+border); } } else if (parseInt( $(this).attr('priority') )> 6 && (me._itemWidth/2)>190 && $(this).hasClass('no-image') && container.find('.tile').length > 4){ var w = (me._itemWidth - gutter)/2 > 300 ? (me._itemWidth - 2*gutter)/3 : (me._itemWidth - gutter)/2; $(this).css('width',Math.floor( (w) - (border*2)-1 )) .addClass('small-item'); } }); var p = new Packery(container[0],{ gutter:gutter }); me._scrollRefresh(); container.transit({ opacity:1 },500,function(){ //Hyphenator.run(); me.loading(false); }); }); }, _showAtPane:function(content){ var container = this.panes.main_content; var me = this; this._fire('pageChangeStart'); me._showPane('main-pane',function(){ container.transit({ opacity:0 },200,function(){ container.empty(); each(content,function(item){ /* item.find('p, h1, h2, h3, h4').each(function(){ $(this).addClass('hyphenate text').attr('lang',me._lang); }); */ item.hammer().on('tap',function(){ if ($(this).hasClass('newsitem')){ me.showItem($(this).attr('id')); me._fire('tracker',{'action':'open_article','event_type':'tap','data':$(this).attr('id')}); } else if ($(this).hasClass('category')){ me.showCategory($(this).attr('id')); } }); container.append(item); }); me._tile(); }); }); }, _getCategories:function(){ var categories = {}; for (var i in this._items){ if (categories[this._items[i].category]){ categories[this._items[i].category]++; } else { categories[this._items[i].category] = 1; } } this._categories = categories; return categories; }, _getCategoryNames:function(){ this._getCategories(); var result = []; for (var i in this._categories){ //if (i.toLowerCase()!='etusivu'){ result.push(i); //} } return result; }, getCategory:function(name){ var result = []; name = name.toLowerCase(); for (var i in this._items){ if (this._items[i].category.toLowerCase() == name){ result.push(this._items[i]); } } return result; }, _makeFrontPage:function(){ var frontPage = []; this._items.sort(function(a,b){ return a.priority - b.priority; }) for (var i = 0; i<20; i++){ if (this._items[i] && this._items[i] instanceof newsitem){ if (this._items[i].category.toLowerCase() != 'etusivu'){ frontPage.push(this._items[i]); } } } frontPage.sort(function(a,b){ if (a.hasImage()){ return -1; } else if (b.hasImage()){ return 1; } else { return 0; } }); return frontPage; }, _getData:function(){ var me = this; var d = Date.now(); $.ajax({ url:parserURL, dataType:'JSON', success:function(e){ var rs = JSON.parse(e); if (rs.status == 'ok'){ for (var i in rs.data){ me._items.push( new newsitem(rs.data[i])); } me._source = rs.source; me._lang = rs.source.language; me._getCategories(); var d2 = Date.now(), time = d2 - d; me._fire('load',me._items); me._fire('tracker',{'action':'xml-load','event_type':'data load','data':time}); } else { me._error(rs); } }, error:function(e){ me.error(e); } }); }, _getItem:function(id){ var found = false; for (var i in this._items){ if (this._items[i]._id == id){ found = this._items[i]; break; } } return found; }, on:function(name,fn){ if (this._listeners[name] == undefined){ this._listeners[name] = Array(); } this._listeners[name].push(fn); }, _fire : function(evt,data,e){ for (var i in this._listeners['all']){ if (this._listeners['all'][i]!=undefined && typeof(this._listeners['all'][i])== 'function'){ this._listeners['all'][i](evt,data,e); } } if (this._listeners[evt]!=undefined){ for (var i in this._listeners[evt]){ if (typeof(this._listeners[evt][i])=='function'){ this._listeners[evt][i](data,e); } } } }, off:function(evt){ delete this._listeners[evt]; } } <file_sep><?php ini_set("session.cookie_lifetime","600"); session_start(); //session_destroy(); if (isset($_POST)){ if (isset($_POST['login']) && $_POST['userdata']){ if ($_SESSION['user'] != $_POST['login']){ $_SESSION['login']= true; $_SESSION['user'] = $_POST['login']; $d = $_POST['userdata']; $_SESSION['userdata'] = $d; $str = 'INSERT INTO user (user_id,session_id,start_time,window_x,window_y,screen_x,screen_y,media,type,vendor,ip) VALUES( ' .'\''.$_SESSION['user'].'\', ' .'\''.session_id().'\', ' .$d['start_time'].', ' .$d['window'][0].', ' .$d['window'][1].', ' .$d['screen'][0].', ' .$d['screen'][1].', ' .'\''.$d['media'].'\', ' .'\''.$d['type'].'\', ' .'\''.$d['vendor'].'\', ' .'\''.$_SERVER['REMOTE_ADDR'].'\'' .')'; echo save($str); } else { echo json_encode(array('ok'=>true)); } } else if (isset($_POST['data']) && $_SESSION['login']==true){ $d = $_POST['data']; $str = 'INSERT INTO user_action (user_id,session_id,client_time,action,event_type,data,latitude,longitude) VALUES( ' .'\''.$_SESSION['user'].'\', ' .'\''.session_id().'\', ' .$d['time'].', ' .'\''.$d['action'].'\', ' .'\''.$d['event_type'].'\', ' .'\''.$d['data'].'\', ' .$d['latitude'].', ' .$d['longitude'] .' )'; echo save($str); } } function query($str){ try{ $p = new PDO("mysql:host=localhost;dbname=rupu_usertracker","mato","sukkamato"); } catch (PDOException $e){ die( '{ok:false,message:"pdo init error"}' ); } $p->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, PDO::FETCH_ASSOC); $q = $p->prepare($str); $q->execute(); $rep = array(); while ($result = $q->fetch(PDO::FETCH_ASSOC)){ $rep[] = $result; } return $rep; } function save($data){ try{ $p = new PDO("mysql:host=localhost;dbname=rupu_usertracker","mato","sukkamato"); } catch (PDOException $e){ die( '{ok:false,message:"pdo init error"}' ); } $p->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try{ $result = $p->prepare($data); $result->execute(); return json_encode(array('ok'=>true)); } catch (PDOException $e){ return json_encode(array('ok'=>false,'message'=>$e->getMessage())); } } ?><file_sep> function newsitem(data){ for (var i in data){ this[i] = data[i]; } } newsitem.prototype = { hasImage:function(){ var has = false; if (this.image){ if (this.image[0]){ has = true; } } return has; }, getImage:function(){ if (this.hasImage()){ return this.image[0].url; } else { return false; } }, getImageName:function(){ if (this.hasImage()){ return this.image[0].name; } else { return false; } }, getTile:function(){ var txt = this.getShortText(); var textcontainer = ''; if (txt){ textcontainer = ['<div class="textcontainer">', this.getShortText(), '</div>'].join(''); } if (this.hasImage()){ return $([ '<div class="newsitem tile container has-image" category="',this.category,'" priority="',this.priority,'" id="'+this._id+'">', '<div class="newsitem-imagecontainer">', '<img class="newsitem-image" src="',imageURL,this.image[0].name,'" alt="" />', '<div class="image-item-header-container" style="'+colors.getBackground(this.category,0.7)+'">', '<h2>'+this.title+'</h2>', '<div class="text-arrow" style="'+colors.getBackground(this.category,1)+'"></div>', '</div>', '</div>', textcontainer, '<div class="bottom-bar">', '<span class="date">'+getItemDate(this.pubdate)+'</span>', '<span class="source">'+this.author+'</span>', '</div>', '</div>' ].join('')); } else { return $([ '<div class="newsitem tile container no-image" priority="',this.priority,'" id="'+this._id+'">', '<div class="header-container" style="'+colors.getBackground(this.category,1)+'">', '<h2>'+this.title+'</h2>', '</div>', textcontainer, '<div class="bottom-bar">', '<span class="date">'+getItemDate(this.pubdate)+'</span>', '<span class="source">'+this.author+'</span>', '</div>', '</div>' ].join('')); } }, getFull:function(){ var image = '', hasImage = 'no-image'; if (this.hasImage()){ image = [ '<div class="image-container" style="'+colors.getBackground(this.category,1)+'">', //'<img src="../puru/img/',this.image[0].name,'" alt="" />', '<img src="',imageURL,this.image[0].name,'" alt="" />', '<div class="image-item-header-container" style="'+colors.getBackground(this.category,0.7)+'">', //'<div class="image-text">',this.image[0].text,'</div>', '<h1>'+this.title+'</h1>', '<div class="text-arrow" style="'+colors.getBackground(this.category,1)+'"></div>', '</div>', '</div>', ].join(''); hasImage = 'has-image'; } else { image = '<div class="page-header-container" style="'+colors.getBackground(this.category,1)+'" ><h1 class="news-header">'+this.title+'</h1></div>'; } return $([ '<div id="page" data-item="'+this._id+'" class="',hasImage,' pagecontainer">', '<div id="page-scroll" class="page-scroll">', '<div class="news-page">', image, '<div class="textcontainer">', '<div class="textcontainer-content">', this.text, '</div>', '</div>', '<div class="bottom-bar">', '<span class="category">'+this.category+'</span>', '<span class="date">'+getItemDate(this.pubdate)+'</span>', '<span class="author">',this.author,'</span>', '</div>', '</div>', '</div>', '</div>' ].join('')); }, getShortText:function(len){ var t = $(this.text); var text = ''; if (len == undefined){ len = 150; } if ( $(t[1]).text().length < 70){ // tekijän nimi yleensä var txt = $(t[2]).text();//.substr(0,len) + '...'; $(t[2]).text(txt); text = $(t[2]).text(); } else { var txt = $(t[1]).text();//.substr(0,len) + '...'; $(t[1]).text(txt); text = $(t[1]).text(); } if (text.length > len){ text = text.substr(0,len) + '...'; } return text; } }<file_sep><?php date_default_timezone_set('Europe/Helsinki'); function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $start_time = microtime_float(); $url = 'http://tablet.kp24.fi/feed/rss.ashx'; $items = array(); try{ $fileContents= file_get_contents($url); $fileContents = str_replace(array("\n", "\r", "\t"), ' ', $fileContents); $fileContents = str_replace('media:', 'media_', $fileContents); $fileContents = str_replace('dc:creator', 'author', $fileContents); $fileContents = trim(str_replace('"', "'", $fileContents)); $simpleXml = simplexml_load_string($fileContents); } catch (Exception $e){ error($e); } if ($simpleXml){ $paper = array( 'title'=>(string)$simpleXml->channel->title, 'timestamp'=>microtime_float(), 'description'=>(string)$simpleXml->channel->description, 'language'=>(string)$simpleXml->channel->language, 'image'=>array( 'url'=>(string)$simpleXml->channel->image->url, 'link'=>(string)$simpleXml->channel->image->link, 'title'=>(string)$simpleXml->channel->image->title ) ); foreach ($simpleXml->channel->item as $item){ $images = array(); foreach ($item->media_content as $content){ if ($content->attributes() != 'false' && $content->attributes()){ try{ $image = array( //'url'=>(string)$content->attributes(), 'title'=>(string)$content->media_title, 'text'=>(string)$content->media_description, 'author'=>(string)$content->media_credit, 'url'=>(string)$content->attributes(), 'name'=>basename((string)$content->attributes()) ); $images[] = $image; } catch (Exception $e){ error($e); } } } $newsItem = array( '_id'=>(string)$item->guid, 'title'=>(string)$item->title, 'text'=>(string)$item->description, 'category'=>(string)$item->category, 'priority'=>(string)$item->comments, 'pubdate'=>strtotime( (string)$item->pubDate ), 'readtime'=>microtime_float(), 'author'=>(string)$item->author, 'guid'=>(string)$item->guid, 'source'=>$paper['title'], 'image'=>$images ); $items[] = $newsItem; } $end_time = microtime_float(); $data = json_encode(array( 'status'=>'ok', 'source'=>$paper, 'start'=>$start_time, 'end'=>$end_time, 'took'=>$end_time-$start_time, 'data'=> $items )); echo json_encode($data); } else { echo json_encode(array('status'=>'error','message'=>'invalid data')); } function error($e){ echo json_encode(array('status'=>'error','message'=>$e->getMessage())); } function parseText($text){ $result = preg_replace("/<(.|\n)*?>/",' ', $text); return $result; } ?>
2d5759fcf996e57f88a5f602ee9e43ffd3f123c9
[ "JavaScript", "PHP" ]
5
JavaScript
heikkipesonen/testirupu
7f810acc8af6e3a51b8e44212bc6ca4b347eccb9
77b3ae2baaef2f885baeb7d63e15ae8026445fea
refs/heads/master
<file_sep>namespace Mps.Enums { /// <summary> /// Перечисление индексов колонок /// </summary> public enum ColumnIndex { /// <summary> /// Индекс колонки Лямда /// </summary> LamdaColumnIndex, /// <summary> /// Индекс колонки Мю /// </summary> MuColumnIndex, /// <summary> /// Индекс колонки Омега /// </summary> OmegaColumnIndex, /// <summary> /// Индекс колонки K /// </summary> KColumnIndex, /// <summary> /// Индекс колонки P /// </summary> PColumnIndex, /// <summary> /// Индекс колонки C /// </summary> CColumnIndex, /// <summary> /// Индекс колонки A /// </summary> AColumnIndex } }<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Mps.Services { /// <summary> /// Генератор приоритетов /// </summary> public static class Generator { /// <summary> /// Генератор псевдослуайный чисел /// </summary> private static readonly Random Random = new Random(); /// <summary> /// Список приоритетов для генерации /// </summary> private static List<int> _ks = new List<int>(); /// <summary> /// Заполнить приоритеты /// </summary> /// <param name="count"></param> public static void Fill(int count) { for (var i = 0; i < count; i++) { _ks.Add(i + 1); } } /// <summary> /// Очистить приоритеты /// </summary> public static void Clear() { _ks.Clear(); } /// <summary> /// Десортировать приоритеты /// </summary> public static void DeSort() { _ks = _ks.OrderBy(kCurrent => Random.Next()).ToList(); } /// <summary> /// Вернуть элемент по индексу /// </summary> /// <param name="index">Индекс</param> /// <returns>Элемент</returns> public static int GetByIndex(int index) { return _ks[index]; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Mps.Models; namespace Mps.Services { /// <summary> /// Калькулятор /// </summary> public static class Calculator { /// <summary> /// Рассчитать значение загрузки процессора /// </summary> /// <param name="lamdaCurrent">Интенсивность потока задач</param> /// <param name="muCurrent">Интенсивность обслуживания</param> /// <returns>Значение загрузки процессора</returns> public static double CalculateOmega(double lamdaCurrent, double muCurrent) { // Делить без округления return lamdaCurrent / muCurrent; } /// <summary> /// Рассчитать /// </summary> /// <param name="rows">Строки</param> /// <param name="n">Количество процессоров</param> /// <param name="overGammaFunction">Использовать гамма-функцию</param> public static void Calculate(List<Row> rows, int n, bool overGammaFunction = false) { // Для всех строк for (var counter = 0; counter < rows.Count; counter++) { // Текущая строка var row = rows[counter]; // Омега var omega = CalculateOmega(row.Lamda, row.Mu); // Значение C предыдущих строк double prevC = 0; for (var i = 0; i < counter ; i++) { prevC += rows[i].C; } // N - C var nMisusPrevC = n - prevC; // Числитель var numerator = Math.Pow(omega, nMisusPrevC); // Левая часть знаменателя var denominatorLeftPart = GetFactorial(nMisusPrevC, overGammaFunction); // Правая часть знаменателя var denominatorRightPart = GetDenominatorRightPart(nMisusPrevC, omega); // Знаменатель var denominator = denominatorLeftPart * denominatorRightPart; // Значение P row.P = numerator / denominator; // Установка значений с учетом превышения 1 на текущем шаге if (rows.Sum(r => r.P) >= 1) { row.P = 0; row.C = 0; row.A = 0; } else { // Значение С row.C = omega * (1 - row.P); // Значение A row.A = (1 - row.P) * row.Lamda; } } } /// <summary> /// Получить правую часть знаменателя /// </summary> /// <param name="nMisusPrevC">N - C предыдущей строки</param> /// <param name="omega">Омега</param> /// <param name="overGammaFunction">Использовать гамма-функцию для рассчёта факториала</param> /// <returns>Правая часть знаменателя</returns> private static double GetDenominatorRightPart(double nMisusPrevC, double omega, bool overGammaFunction = false) { var result = 0.0; // Если не число или число в обстях бесконечных чисел, вернуть 0.0 if (double.IsNaN(nMisusPrevC) || double.IsNegativeInfinity(nMisusPrevC) || double.IsPositiveInfinity(nMisusPrevC)) { return result; } // Для N - C предыдущей строки сложить for (var i = 0; i <= Math.Ceiling(nMisusPrevC); i++) { // Числитель var stepResultNumerator = Math.Pow(omega, i); // Знаменатель var stepResultDenominator = GetFactorial(i, overGammaFunction); //Результат var stepResult = stepResultNumerator / stepResultDenominator; // Добавить в накапливающую переменную result += stepResult; } return result; } /// <summary> /// Вычислить факториал /// </summary> /// <param name="number">Число, для которого необходимо вычислить факториал</param> /// <param name="overGammaFunction">Использовать гамма-функцию для рассчёта факториала</param> /// <returns>Факториал числа</returns> private static double GetFactorial(double number, bool overGammaFunction) { // Если не число или число в обстях бесконечных чисел, вернуть 1.0 if (double.IsNaN(number) || double.IsNegativeInfinity(number) || double.IsPositiveInfinity(number) || Math.Abs(number - 1) < double.Epsilon || Math.Abs(number) < double.Epsilon) { return 1; } // Если без использования гамма-функции if (!overGammaFunction) { // Целоисленное значение var numberInt = (int)Math.Round(number); // Математики так решили if (numberInt == 0 || numberInt == 1 || numberInt < 0) { return 1; } // Вычислить циклиески var sum = 1; for (var i = numberInt; i != 0; i--) { sum *= i; } return sum; } // Иначе вычислить с использованием гамма-функции return Gamma(number + 1); } /// <summary> /// Гамма-функция /// </summary> /// <param name="x">Число, для которого необходио вычислить факториал</param> /// <returns>Факториал числа</returns> public static double Gamma(double x) { if (x <= 0.0) { return 0; } // К<NAME> для гаммы const double gamma = 0.577215664901532860606512090; // Euler's gamma constant // Если стремится к нулю if (Math.Abs(x) < double.Epsilon) { return 1.0 / (x * (1.0 + gamma * x)); } // Расчет к точкам приближения между (1, 2) double z; if (x < 12.0) { var y = x; var n = 0; var argWasLessThanOne = y < 1.0; // Аргумент меньше 1 if (argWasLessThanOne) { y += 1.0; } // Иначе else { n = (int)Math.Floor(y) - 1; y -= n; } // Коэффициенты числителя аппроксимации для(1, 2) double[] p = { -1.71618513886549492533811E+0, 2.47656508055759199108314E+1, -3.79804256470945635097577E+2, 6.29331155312818442661052E+2, 8.66966202790413211295064E+2, -3.14512729688483675254357E+4, -3.61444134186911729807069E+4, 6.64561438202405440627855E+4 }; // Коэффициенты знаменателя аппроксимации для(1, 2) double[] q = { -3.08402300119738975254353E+1, 3.15350626979604161529144E+2, -1.01515636749021914166146E+3, -3.10777167157231109440444E+3, 2.25381184209801510330112E+4, 4.75584627752788110767815E+3, -1.34659959864969306392456E+5, -1.15132259675553483497211E+5 }; var num = 0.0; var den = 1.0; int i; z = y - 1; for (i = 0; i < 8; i++) { num = (num + p[i]) * z; den = den * z + q[i]; } var result = num / den + 1.0; // Применить коррекцию, если аргумент не был первоначально в (1, 2) if (argWasLessThanOne) { result /= (y - 1.0); } else { for (i = 0; i < n; i++) { result *= y++; } } return result; } // Ниже вычисления логарифма от гамма-фунции if (x > 171.624) { return double.PositiveInfinity; } if (x <= 0.0) { return 0; } if (x < 12.0) { return Math.Log(Math.Abs(Gamma(x))); } double[] c = { 1.0/12.0, -1.0/360.0, 1.0/1260.0, -1.0/1680.0, 1.0/1188.0, -691.0/360360.0, 1.0/156.0, -3617.0/122400.0 }; z = 1.0 / (x * x); var sum = c[7]; for (var i = 6; i >= 0; i--) { sum *= z; sum += c[i]; } var series = sum / x; const double halfLogTwoPi = 0.91893853320467274178032973640562; var logGamma = (x - 0.5) * Math.Log(x) - x + halfLogTwoPi + series; return Math.Exp(logGamma); } } }<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using Mps.Enums; using Mps.Models; using Mps.Properties; using Mps.Services; namespace Mps.Forms { /// <summary> /// Основная форма /// </summary> public partial class MpsForm : Form { /// <summary> /// Предыдущее значение ячейки перед редактированием /// </summary> private object _cellOldValue; /// <summary> /// Название файла /// </summary> private string _fileName; /// <summary> /// Генератор псевдослуайный чисел /// </summary> private readonly Random _random = new Random(); /// <summary> /// Конструктор /// </summary> public MpsForm() { try { // Инициализация компонентов InitializeComponent(); // Установить нумерацию строк SetRowNumbers(); // Установить возможно ли добавление кортежей SetAllowToAddRows(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие закрытия формы /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void MpsFormFormClosing(object sender, FormClosingEventArgs e) { try { // Показать сообщение с вопросом var result = MessageBox.Show(Resources.ExitQuestionMessage, Resources.ExitCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question); // Если нажато "Да", то выйти if (result == DialogResult.Yes) { return; } // Иначе отменить выход e.Cancel = true; } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие активации формы /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void MpsFormActivated(object sender, EventArgs e) { // Отрисовать Draw(); } /// <summary> /// Событие нажатия на кнопку "Рассчитать" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void ButtonCalculateClick(object sender, EventArgs e) { try { // Рассчитать Calculate(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие нажатия на кнопку "Очистить" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void ButtonClearClick(object sender, EventArgs e) { try { // Очистить таблицу tupplesTable.Rows.Clear(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Файл" - "Открыть" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) { try { if (openFileDialog.ShowDialog() == DialogResult.OK) { // Задать имя файла _fileName = openFileDialog.FileName; // Открыть OpenFile(); } } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Файл" - "Сохранить" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void SaveFileToolStripMenuItemClick(object sender, EventArgs e) { try { // Если нет имени файла if (string.IsNullOrEmpty(_fileName)) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Задать имя файла _fileName = saveFileDialog.FileName; // Сохранить SaveFile(); } } // Иначе else { // Сохранить SaveFile(); } } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Файл" - "Сохранить как..." /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void SaveFileAsToolStripMenuItemClick(object sender, EventArgs e) { try { if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Задать имя файла _fileName = saveFileDialog.FileName; // Сохранить SaveFile(); } } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Файл" - "Выход" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void ExitToolStripMenuItemClick(object sender, EventArgs e) { try { // Выход Close(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Команда" - "Рассчитать" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void CalculateToolStripMenuItemClick(object sender, EventArgs e) { try { // Рассчитать Calculate(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие выбора пункта меню "Команда" - "Очистить" /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void ClearTableToolStripMenuItemClick(object sender, EventArgs e) { try { // Очистить таблицу tupplesTable.Rows.Clear(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие начала редактирования ячейки /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void TupplesTableCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { try { // Запомнить старое значение ячейки var cell = tupplesTable.Rows[e.RowIndex].Cells[e.ColumnIndex]; _cellOldValue = cell.Value; } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие завершения редактирования содержимого ячейки /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void TupplesTableCellEndEdit(object sender, DataGridViewCellEventArgs e) { try { // Текущая ячейка var cell = tupplesTable.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cell?.Value == null) { return; } // Значение текущей ячейки var stringValue = cell.Value.ToString(); // Для колонки switch ((ColumnIndex)e.ColumnIndex) { // Если колонка интенсивностей case ColumnIndex.LamdaColumnIndex: case ColumnIndex.MuColumnIndex: // Попытаться получить значение double outDoubleValue; if (double.TryParse(stringValue, out outDoubleValue)) { // Установить значение cell.Value = outDoubleValue; // Отменить ввод отрицательного значения if (outDoubleValue <= 0) { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.NegativeOrZeroValueEnteredErrorMessage); } var lamdaCell = tupplesTable.Rows[e.RowIndex].Cells[(int) ColumnIndex.LamdaColumnIndex]; var muCell = tupplesTable.Rows[e.RowIndex].Cells[(int) ColumnIndex.MuColumnIndex]; if (lamdaCell?.Value == null || muCell?.Value == null) { return; } // Попытаться получить измененные значения // Если удалось получить double outLamdaDoubleValue; double outMuDoubleValue; if (double.TryParse(lamdaCell.Value.ToString(), out outLamdaDoubleValue) && double.TryParse(muCell.Value.ToString(), out outMuDoubleValue)) { // Установить значение var omegaCell = tupplesTable.Rows[e.RowIndex].Cells[(int)ColumnIndex.OmegaColumnIndex]; omegaCell.Value = Calculator.CalculateOmega(outLamdaDoubleValue, outMuDoubleValue); } // Иначе else { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.NotCorrectIntensivityValuesToCalculateErrorMessage); } } else { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.NotCorrectCellValueErrorMessage); } break; // Если колонка приоритетов case ColumnIndex.KColumnIndex: // Попытаться получить значение int outIntValue; if (int.TryParse(stringValue, out outIntValue)) { var ks = new List<int>(); // Получить список приоритетов foreach (DataGridViewRow row in tupplesTable.Rows) { // Пропустить пустые ячейки приоритетов var kCell = row.Cells[(int) ColumnIndex.KColumnIndex]; int outTempIntValue; if (kCell?.Value == null || !int.TryParse(kCell.Value.ToString(), out outTempIntValue)) { continue; } // Пропустить текущую строку if (e.RowIndex == row.Index) { continue; } // Добавить в список ks.Add(outTempIntValue); } // Если не было изменений if (_cellOldValue != null && outIntValue == int.Parse(_cellOldValue.ToString())) { return; } // Если уже имеется указанный приоритет if (ks.Contains(outIntValue)) { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.ExistPriorityValueErrorMessage); } else { // Установить значение cell.Value = outIntValue.ToString("D"); // Отменить ввод отрицательного значения if (outIntValue <= 0) { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.NegativeOrZeroValueEnteredErrorMessage); } } } else { // Показать сообщение об ошибке и установить предыдущее значение ячейки ShowErrorAndSetOldCellValue(cell, Resources.NotCorrectCellValueErrorMessage); } break; } SetRowNumbers(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие удаления строки /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void TupplesTableUserDeletedRow(object sender, DataGridViewRowEventArgs e) { try { // Установить нумерацию строк SetRowNumbers(); // Установить возможно ли добавление кортежей SetAllowToAddRows(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Событие добавления строки /// </summary> /// <param name="sender">Отправитель события</param> /// <param name="e">Аргументы</param> private void TupplesTableUserAddedRow(object sender, DataGridViewRowEventArgs e) { try { // Установить нумерацию строк SetRowNumbers(); // Установить возможно ли добавление кортежей SetAllowToAddRows(); } catch (Exception) { ShowError(Resources.OcceredUnclownExceptionErrorMessage); } } /// <summary> /// Установить картежи /// </summary> public void SetTupples() { // Очистить таблицу tupplesTable.Rows.Clear(); // Очистить приоритеты Generator.Clear(); // Установить нумерацию строк SetRowNumbers(); // Установить возможно ли добавление кортежей SetAllowToAddRows(); } /// <summary> /// Установить нумерацию строк /// </summary> private void SetRowNumbers() { // Для каждой строки установить индекс + 1 foreach (DataGridViewRow row in tupplesTable.Rows) { row.HeaderCell.Value = $"{row.Index + 1}"; } } /// <summary> /// Установить возможно ли добавление кортежей /// </summary> private void SetAllowToAddRows() { // Установить возможно ли редактирование на основе количества строк в таблице tupplesTable.AllowUserToAddRows = tupplesTable.RowCount < 1024; } /// <summary> /// Показать сообщение об ошибке и установить предыдущее значение ячейки /// </summary> /// <param name="cell">Ячейка</param> /// <param name="errorMessage">ТекстОшибки</param> private void ShowErrorAndSetOldCellValue(DataGridViewCell cell, string errorMessage) { // Показать сообщение об ошибке ShowError(errorMessage); // Восстановить значение cell.Value = _cellOldValue; } /// <summary> /// Показать сообщение об ошибке /// </summary> /// <param name="errorMessage">ТекстОшибки</param> private static void ShowError(string errorMessage) { // Показать сообщение об ошибке MessageBox.Show(errorMessage, Resources.ErrorCaption, MessageBoxButtons.OK); } /// <summary> /// Получить значения ячеек таблицы /// </summary> /// <returns>Список строк</returns> private List<Row> GetRows() { return tupplesTable.Rows.Cast<DataGridViewRow>() .Select(dataGridViewRow => dataGridViewRow.Cells) .Select(cells => new Row { Lamda = ParseDoubleFromCell(cells[(int)ColumnIndex.LamdaColumnIndex]), Mu = ParseDoubleFromCell(cells[(int)ColumnIndex.MuColumnIndex]), Omega = ParseDoubleFromCell(cells[(int)ColumnIndex.OmegaColumnIndex]), K = ParseIntFromCell(cells[(int)ColumnIndex.KColumnIndex]), P = ParseDoubleFromCell(cells[(int)ColumnIndex.PColumnIndex]), C = ParseDoubleFromCell(cells[(int)ColumnIndex.CColumnIndex]), A = ParseIntFromCell(cells[(int)ColumnIndex.AColumnIndex]) }) .Where(r => r.Lamda > 0 && r.Mu > 0 && r.K > 0) .ToList(); } /// <summary> /// Установить список строк в таблицу /// </summary> /// <param name="rows">Строки</param> private void SetRows(IEnumerable<Row> rows) { foreach (var row in rows) { tupplesTable.Rows.Add(row.Lamda, row.Mu, row.Omega, row.K, row.P, row.C, row.A); } } /// <summary> /// Рассчитать /// </summary> private void Calculate() { // Получить список строк var rows = GetRows(); // Использовать ли гамма-функцию для расчёта факториала var overGammaFunction = checkBoxOverGammaFunction.Checked; // Вычислить Calculator.Calculate(rows, (int)numericUpDownN.Value, overGammaFunction); // Очистить таблицу tupplesTable.Rows.Clear(); // Установить список строк в таблицу SetRows(rows); // Установить нумерацию строк SetRowNumbers(); // Суммы значений sumLabel.Text = "Суммы: " + $"P = {rows.Sum(r => r.P).ToString("N6")}, " + $"C = {rows.Sum(r => r.C).ToString("N6")}, " + $"A = {rows.Sum(r => r.A).ToString("N6")}"; // Отрисовать Draw(); } /// <summary> /// Получить вещественное значение из ячейки /// </summary> /// <param name="cell">Ячейка</param> /// <returns>Вещественное значение ячейки</returns> private static double ParseDoubleFromCell(DataGridViewCell cell) { double outValue; double.TryParse(cell?.Value?.ToString(), out outValue); return outValue; } /// <summary> /// Получить целочисленное значение из ячейки /// </summary> /// <param name="cell">Ячейка</param> /// <returns>Целочисленное значение ячейки</returns> private static int ParseIntFromCell(DataGridViewCell cell) { int outValue; int.TryParse(cell?.Value?.ToString(), out outValue); return outValue; } /// <summary> /// Сохранить в файл /// </summary> private void SaveFile() { // Если есть имя файла if (!string.IsNullOrEmpty(_fileName)) { // Модель файла var fileModel = new FileModel { N = (int)numericUpDownN.Value, UseGammaFunction = checkBoxOverGammaFunction.Checked, Rows = GetRows() }; // Сохранить XmlFileManager.Save(fileModel, _fileName); MessageBox.Show(Resources.FileSavedSuccessfullyInformationMessage, Resources.SaveFileCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Открыть файл /// </summary> private void OpenFile() { // Если есть имя файла if (!string.IsNullOrEmpty(_fileName)) { // Модель файла var fileModel = XmlFileManager.Open(_fileName); // Установить значения настроек numericUpDownN.Value = fileModel.N; checkBoxOverGammaFunction.Checked = fileModel.UseGammaFunction; checkBoxOverGammaFunction.Checked = fileModel.UseGammaFunction; // Очистить таблицу tupplesTable.Rows.Clear(); // Установить список строк в таблицу SetRows(fileModel.Rows); // Установить нумерацию строк SetRowNumbers(); } } /// <summary> /// Нарисовать /// </summary> public void Draw() { using (var graphics = pictureBox.CreateGraphics()) { graphics.SmoothingMode = SmoothingMode.HighQuality; // Очистить graphics.Clear(pictureBox.BackColor); // Нарисовать сетку DrawGrid(graphics); // Нарисовать оси ординат и абцисс DrawArrows(graphics); // Нарисовать график DrawGraphic(graphics); } } /// <summary> /// Нарисовать график /// </summary> /// <param name="graphics">Объект Graphics</param> private void DrawGraphic(Graphics graphics) { // Получить шаги сетки var gridSteps = GetSteps(); // Начало и конец сетки var a0K0Point = new PointF(gridSteps.Width, pictureBox.Bottom - pictureBox.Top - gridSteps.Height); var aMaxKMaxPoint = new PointF(gridSteps.Width * 20, gridSteps.Height); // Точки построения графика var graphicPoints = GetPoinsForGraphic(); if (!graphicPoints.Any()) { return; } // Самое правое значение по горизонтали var maxKValue = graphicPoints.Max(point => point.K); if (maxKValue == 0) { return; } // Самое верхнее значение по вертикали var maxAValue = graphicPoints.Max(point => point.A); if (maxAValue == 0) { return; } // Шаги графика var graphicSteps = new SizeF((float) ((aMaxKMaxPoint.X - a0K0Point.X - gridSteps.Width) / maxKValue), (float) ((a0K0Point.Y - aMaxKMaxPoint.Y) / maxAValue)); // Точки рисования var points = new List<PointF>(); foreach (var graphicPoint in graphicPoints) { points.Add(new PointF( (float) (a0K0Point.X + graphicPoint.K * graphicSteps.Width), (float) (a0K0Point.Y - graphicPoint.A * graphicSteps.Height))); } using (var pen = new Pen(Color.Red, 1)) { // Округленные начальная и конечная точка pen.StartCap = LineCap.Round; pen.EndCap = LineCap.Round; // Нарисовать линии graphics.DrawLines(pen, points .Where(point => !float.IsInfinity(point.X) && !float.IsNaN(point.X) && !float.IsInfinity(point.Y) && !float.IsNaN(point.Y)) .ToArray()); } } /// <summary> /// Нарисовать оси ординат и абцисс /// </summary> /// <param name="graphics">Объект Graphics</param> private void DrawArrows(Graphics graphics) { // Получить шаги сетки var steps = GetSteps(); // Координаты линий и обозначений var arrowStart = new PointF(steps.Width, pictureBox.Bottom - pictureBox.Top - steps.Height); var verticalArrowEnd = new PointF(arrowStart.X, steps.Height); var horisontalArrowEnd = new PointF(pictureBox.Right - pictureBox.Left - steps.Width, arrowStart.Y); var a0K0Point = new PointF(arrowStart.X - 15, arrowStart.Y); var aLabelPoint = new PointF(verticalArrowEnd.X - 20, verticalArrowEnd.Y); var kLabelPoint = new PointF(horisontalArrowEnd.X - 20, horisontalArrowEnd.Y + 5); // Шрифт var font = new Font("Arial", 12); // Сплошная кисть var brush = new SolidBrush(Color.DimGray); // Кисть using (var grayArrowPen = new Pen(Brushes.DimGray, 2)) { // Стрелка в конце grayArrowPen.CustomEndCap = new AdjustableArrowCap(5, 5); // Нарисовать graphics.DrawLines(grayArrowPen, new[] {arrowStart, verticalArrowEnd}); graphics.DrawLines(grayArrowPen, new[] {arrowStart, horisontalArrowEnd}); graphics.DrawString("0", font, brush, a0K0Point); graphics.DrawString("A", font, brush, aLabelPoint); graphics.DrawString("K", font, brush, kLabelPoint); } } /// <summary> /// Нарисовать сетку /// </summary> /// <param name="graphics">Объект Graphics</param> private void DrawGrid(Graphics graphics) { // Получить шаги сетки var steps = GetSteps(); // Список наборов координат var tuples = new List<Tuple<PointF, PointF>>(); // Нарисовать горизонтальные линии сетки for (float i = 0; i < pictureBox.Bottom; i += steps.Height) { // Вертикальные координаты var lineStartPoint = new PointF(0, i); var lineEndPoint = new PointF(pictureBox.Right, i); // Добавить tuples.Add(new Tuple<PointF, PointF>(lineStartPoint, lineEndPoint)); } // Нарисовать вертикальные линии сетки for (float i = 0; i < pictureBox.Right; i += steps.Width) { // Горизонтальные координаты var lineStartPoint = new PointF(i, 0); var lineEndPoint = new PointF(i, pictureBox.Bottom); // Добавить tuples.Add(new Tuple<PointF, PointF>(lineStartPoint, lineEndPoint)); } // Кисть using (var lightGrayPen = new Pen(Brushes.LightGray, 1)) { foreach (var tuple in tuples) { // Нарисовать graphics.DrawLines(lightGrayPen, new[] {tuple.Item1, tuple.Item2}); } } } /// <summary> /// Получить шаги сетки /// </summary> /// <returns>Размеры шагов сетки</returns> private SizeF GetSteps() { return new SizeF( (pictureBox.Right - pictureBox.Left) / (float) 20, (pictureBox.Bottom - pictureBox.Top) / (float) 20 ); } /// <summary> /// Получить точки для построения графика /// </summary> /// <returns>Список точек для построения графика</returns> private List<GraphicPoint> GetPoinsForGraphic() { return tupplesTable.Rows.Cast<DataGridViewRow>() .Select(dataGridViewRow => dataGridViewRow.Cells) .Select(cells => new GraphicPoint { K = ParseDoubleFromCell(cells[(int)ColumnIndex.KColumnIndex]), A = ParseDoubleFromCell(cells[(int)ColumnIndex.AColumnIndex]) }) .Where(point => point.K > 0) .OrderBy(point => point.K) .ToList(); } } }<file_sep>using System; using System.Collections.Generic; namespace Mps.Models { /// <summary> /// Класс для работы с файлом /// </summary> [Serializable] public class FileModel { /// <summary> /// Количество процессоров /// </summary> public int N { get; set; } /// <summary> /// Установлена ли галочка генерации псевдослучайных наборов /// </summary> public bool IsRandomTupples { get; set; } /// <summary> /// Установлена ли галочка генерации псевдослучайных приоритетов /// </summary> public bool IsRandomPriority { get; set; } /// <summary> /// Установлена ли галочка использования гамма-функции при расчёте факториала /// </summary> public bool UseGammaFunction { get; set; } /// <summary> /// Строки /// </summary> public List<Row> Rows { get; set; } } }<file_sep>namespace Mps.Models { /// <summary> /// Точка на графике /// </summary> public class GraphicPoint { /// <summary> /// Приоритет /// </summary> public double K { get; set; } /// <summary> /// Пропускная способность /// </summary> public double A { get; set; } } }<file_sep>using System.IO; using System.Xml.Serialization; using Mps.Models; namespace Mps.Services { /// <summary> /// Класс-помощник для сериализации и десериализации в файл /// </summary> public static class XmlFileManager { /// <summary> /// Сохранить в файл /// </summary> /// <param name="fileModel">Модель файла</param> /// <param name="fileName">Имя файла</param> public static void Save(FileModel fileModel, string fileName) { // Сериализатор var serializer = new XmlSerializer(typeof(FileModel)); // Записать в файловый поток сериализованный объект using (var fileStream = new FileStream(fileName, FileMode.Create)) { serializer.Serialize(fileStream, fileModel); } } /// <summary> /// Открыть файл /// </summary> /// <param name="fileName">Имя файла</param> /// <returns>Модель файла</returns> public static FileModel Open(string fileName) { // Сериализатор var serializer = new XmlSerializer(typeof(FileModel)); // Полуить из файлового потока и десериализовать объект using (var fileStream = new FileStream(fileName, FileMode.Open)) { return (FileModel)serializer.Deserialize(fileStream); } } } }<file_sep>using System; namespace Mps.Models { /// <summary> /// Строка таблицы /// </summary> [Serializable] public class Row { /// <summary> /// Лямда /// </summary> public double Lamda { get; set; } /// <summary> /// Мю /// </summary> public double Mu { get; set; } /// <summary> /// Омега /// </summary> public double Omega { get; set; } /// <summary> /// K /// </summary> public int K { get; set; } /// <summary> /// P /// </summary> public double P { get; set; } /// <summary> /// C /// </summary> public double C { get; set; } /// <summary> /// A /// </summary> public double A { get; set; } } }<file_sep>using System; using System.Windows.Forms; using Mps.Forms; namespace Mps { /// <summary> /// Основной класс приложения /// </summary> public static class Program { /// <summary> /// Главная точка входа для приложения /// </summary> [STAThread] public static void Main() { // Включить визуальные стили Application.EnableVisualStyles(); // Установить совместимое отображение текста Application.SetCompatibleTextRenderingDefault(false); // Запустить форму Application.Run(new MpsForm()); } } }
b562589bfe8acd6fa4798798478a2ce0bb16918b
[ "C#" ]
9
C#
ajupov/mps
5f82e80f75892df6fffc36f3d9af20b0f85d74bf
e2d79a1bf7fc9d3758bb7d8473e5613aff127e48