text
stringlengths
1
1.05M
import React from "react" import {Link} from "react-router-dom" import './NavB.css' import logo from '../../images/hacknitplogo.svg' const NavB = () => { function handleMenu(e) { e.preventDefault(); document.querySelector('.popup').classList.toggle("popup-open"); } return ( <div className='nav-bar'> <div className="popup"> <div className="cut-btn-flex" onClick={handleMenu}> <i class="fas fa-times popup-cut-btn"></i> </div> <nav class="stroke"> <ul className='nav-mob'> <li onClick={handleMenu}><a href="/">Home</a></li> <li onClick={handleMenu}><a href="#about">About</a></li> <li onClick={handleMenu}><a href="#tracks">Tracks</a></li> <li onClick={handleMenu}><a href="#contact">Contact</a></li> <li onClick={handleMenu}><a href="#faq">FAQ</a></li> </ul> <div className="disc-btn"> <button className='btn btn-primary'> <Link to={{ pathname: "https://bit.ly/hacknitp-4-discord" }} target='_blank' className='discordbtnf'> Join Our Discord </Link> </button> </div> </nav> </div> <div class="navbar2"> <div className="nav-jack"> <img src={logo} alt="" class="njack-logo" /> </div> <div className="right"> <nav class="stroke"> <ul> <li><a href="/">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#tracks">Tracks</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#faq">FAQ</a></li> </ul> <div className="disc-btn"> <button className='btn btn-primary'> <Link to={{ pathname: "https://bit.ly/hacknitp-4-discord" }} target='_blank' className='discordbtnf'> Join Our Discord </Link> </button> </div> </nav> </div> <div className="right-alt"> <i class="fas fa-bars" onClick={handleMenu}></i> </div> </div> </div> ) } export default NavB
def most_common(arr): counts = {} for n in arr: if n in counts: counts[n] += 1 else: counts[n] = 1 max_count = 0 max_element = None for k, v in counts.items(): if v > max_count: max_count = v max_element = k return max_element
# Import the necessary libraries from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing import pandas as pd # Read in the iris dataset df = pd.read_csv("iris.csv") # Translate the labels into numbers le = preprocessing.LabelEncoder() df['Species'] = le.fit_transform(df['Species']) # Create input and output datasets X = df.drop(['Species'], axis=1) Y = df['Species'] # Build model rf = RandomForestClassifier(n_estimators = 10, random_state = 42 ) rf.fit(X, Y) # Predict on the given dataset prediction = rf.predict([[5.1, 3.5, 1.4, 0.2], [7.0, 3.2, 4.7, 1.4], [6.3, 3.3, 6.0, 2.5], [7.3, 3.9, 6.4, 2.5], [7.2, 3.2, 6.0, 1.8], [7.9, 3.8, 6.4, 2.0], [7.6, 2.6, 6.6, 2.1], [7.7, 3.0, 6.1, 2.3], [7.2, 3.0, 6.1, 1.8], [7.7, 2.8, 6.7, 2.0], [7.4, 2.8, 6.1, 1.9], [7.8, 2.8, 6.4, 2.0]] ) print(prediction)
<reponame>JonathanCuestaSanchez/ARWS_PARCIAL2<filename>src/main/java/services/WeathersaApp.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package services; /** * * @author 2118270 */ public interface WeathersaApp { String getCityWeather(String city) throws WeatherException; }
<gh_stars>0 var NAVTREEINDEX0 = { "_b_r_d_f_map_dialog_8cpp.html":[2,0,0], "_b_r_d_f_map_dialog_8h.html":[2,0,1], "_b_r_d_f_map_dialog_8h_source.html":[2,0,1], "_b_r_d_f_map_dialog_8hpp.html":[2,0,2], "_b_r_d_f_map_dialog_8hpp_source.html":[2,0,2], "_b_r_d_f_map_display_8cpp.html":[2,0,3], "_b_r_d_f_map_display_8cpp.html#ad124ee46ffc0ecdf92798aa5db07940a":[2,0,3,0], "_b_r_d_f_map_display_8h.html":[2,0,4], "_b_r_d_f_map_display_8h_source.html":[2,0,4], "_b_r_d_f_map_display_8hpp.html":[2,0,5], "_b_r_d_f_map_display_8hpp.html#a01860c8718172e190ac7bbf2ffe0cc6e":[2,0,5,1], "_b_r_d_f_map_display_8hpp.html#a18b60be1ff147624de87f45b9212e8e2":[2,0,5,2], "_b_r_d_f_map_display_8hpp.html#a9326a8a9b822ad95b67bef24b1cd5e70":[2,0,5,3], "_b_r_d_f_map_display_8hpp.html#af49672fde4cd80f7722c9a80abf2c2a4":[2,0,5,0], "_b_r_d_f_map_display_8hpp_source.html":[2,0,5], "_b_r_d_f_map_point_8cpp.html":[2,0,6], "_b_r_d_f_map_point_8h.html":[2,0,7], "_b_r_d_f_map_point_8h_source.html":[2,0,7], "_b_r_d_f_reconstructed_8cpp.html":[2,0,8], "_b_r_d_f_reconstructed_8h.html":[2,0,9], "_b_r_d_f_reconstructed_8h_source.html":[2,0,9], "_b_r_d_f_reconstructed_8hpp.html":[2,0,10], "_b_r_d_f_reconstructed_8hpp_source.html":[2,0,10], "_b_r_d_f_reconstruction_model_8cpp.html":[2,0,11], "_b_r_d_f_reconstruction_model_8h.html":[2,0,12], "_b_r_d_f_reconstruction_model_8h_source.html":[2,0,12], "_b_r_d_f_reconstruction_model_8hpp.html":[2,0,13], "_b_r_d_f_reconstruction_model_8hpp_source.html":[2,0,13], "_b_r_d_f_reconstruction_model_small_storage_8cpp.html":[2,0,14], "_b_r_d_f_reconstruction_model_small_storage_8h.html":[2,0,15], "_b_r_d_f_reconstruction_model_small_storage_8h_source.html":[2,0,15], "_b_r_d_f_reconstruction_model_small_storage_8hpp.html":[2,0,16], "_b_r_d_f_reconstruction_model_small_storage_8hpp_source.html":[2,0,16], "_b_r_d_f_reconstruction_model_with_z_8cpp.html":[2,0,17], "_b_r_d_f_reconstruction_model_with_z_8h.html":[2,0,18], "_b_r_d_f_reconstruction_model_with_z_8h_source.html":[2,0,18], "_b_r_d_f_reconstruction_model_with_z_8hpp.html":[2,0,19], "_b_r_d_f_reconstruction_model_with_z_8hpp_source.html":[2,0,19], "_parameter_window_8h.html":[2,0,20], "_parameter_window_8h.html#ae52308b3630bba23d07d4fd32347bbce":[2,0,20,1], "_parameter_window_8h_source.html":[2,0,20], "_parametrisation_8h.html":[2,0,21], "_parametrisation_8h.html#a5369c38dfbf19b5b4a77d10cfdc36f7c":[2,0,21,1], "_parametrisation_8h.html#a6c4d013fb62a0ebda77f459876959b69":[2,0,21,5], "_parametrisation_8h.html#a9579ab224f4fc15d1ab2f409d9d8a4c6":[2,0,21,3], "_parametrisation_8h.html#ad7004d690712afdecdfe4f48eddcf451":[2,0,21,2], "_parametrisation_8h.html#afae213bbb2131bfed0cbb814a319913c":[2,0,21,4], "_parametrisation_8h_source.html":[2,0,21], "_reconstruction_thread_8h.html":[2,0,22], "_reconstruction_thread_8h_source.html":[2,0,22], "_waiting_display_8cpp.html":[2,0,24], "_waiting_display_8h.html":[2,0,25], "_waiting_display_8h_source.html":[2,0,25], "annotated.html":[1,0], "class_chef_devr_1_1_b_r_d_f_map_dialog.html":[1,0,0,0], "class_chef_devr_1_1_b_r_d_f_map_dialog.html#a497e6eafadd1a765e9626c6a8d07c807":[1,0,0,0,1], "class_chef_devr_1_1_b_r_d_f_map_dialog.html#a72e11c6dbabc1acbb28b5bd69e2fce25":[1,0,0,0,4], "class_chef_devr_1_1_b_r_d_f_map_dialog.html#ab5f642011589f74343495a65a2de1585":[1,0,0,0,3], "class_chef_devr_1_1_b_r_d_f_map_dialog.html#ac99fa190e0ac1ab1c9b8e7771e47fe8f":[1,0,0,0,2], "class_chef_devr_1_1_b_r_d_f_map_dialog_1_1_b_r_d_f_map_dialog_exception.html":[1,0,0,0,0], "class_chef_devr_1_1_b_r_d_f_map_dialog_1_1_b_r_d_f_map_dialog_exception.html#a14d5aa113e07696c89908092c864bb21":[1,0,0,0,0,0], "class_chef_devr_1_1_b_r_d_f_map_point.html":[1,0,0,1], "class_chef_devr_1_1_b_r_d_f_map_point.html#a276173825a05d52630bf1abe725751c9":[1,0,0,1,8], "class_chef_devr_1_1_b_r_d_f_map_point.html#a28e3b8f272e18820846f2bbdf136f87b":[1,0,0,1,0], "class_chef_devr_1_1_b_r_d_f_map_point.html#a48bf4e95a283b4100a0cdaa01626c2cd":[1,0,0,1,9], "class_chef_devr_1_1_b_r_d_f_map_point.html#a54c8e450a34479ae6357e3dbb92f758a":[1,0,0,1,10], "class_chef_devr_1_1_b_r_d_f_map_point.html#a8721525f6aef212c5ebff78a5c54b489":[1,0,0,1,1], "class_chef_devr_1_1_b_r_d_f_map_point.html#aa028955f5254b88ef04afc1febaed275":[1,0,0,1,11], "class_chef_devr_1_1_b_r_d_f_map_point.html#abfae4cfdd5152df62f1249f2ab8be4c1":[1,0,0,1,6], "class_chef_devr_1_1_b_r_d_f_map_point.html#ac3bed3cd53a4355f1812fce25caff7f7":[1,0,0,1,7], "class_chef_devr_1_1_b_r_d_f_map_point.html#adedba359be82a13b31884e470f05b73e":[1,0,0,1,4], "class_chef_devr_1_1_b_r_d_f_map_point.html#ae571024d34bc4ff888c09e3e52cea6e5":[1,0,0,1,2], "class_chef_devr_1_1_b_r_d_f_map_point.html#ae6bc030db610351d55bb092bd0c3d800":[1,0,0,1,5], "class_chef_devr_1_1_b_r_d_f_map_point.html#af62c069b7aa4fc07540f784f6c039a71":[1,0,0,1,3], "class_chef_devr_1_1_b_r_d_f_map_scene.html":[1,0,0,2], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a04205d114c381f1bb20ff4ed0322d1c5":[1,0,0,2,7], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a133b2ec883a34a5bf02b08abc22ea401":[1,0,0,2,3], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a1da051acdae0ae51a4c8337ad2450827":[1,0,0,2,6], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a220a81cc3661dd6f04b0cce50f6c15e5":[1,0,0,2,2], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a4659bfdae5af0db6f1386757f3cf630f":[1,0,0,2,0], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a4885ef713630b204ca296ef9a38db7c3":[1,0,0,2,8], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a54e1ff2fa9a37e4ac6ef54c519bfa198":[1,0,0,2,11], "class_chef_devr_1_1_b_r_d_f_map_scene.html#a79597ebe1f717b6f96aa62fefa4f72c4":[1,0,0,2,12], "class_chef_devr_1_1_b_r_d_f_map_scene.html#ab527b132ee295754992839646f7cd93b":[1,0,0,2,10], "class_chef_devr_1_1_b_r_d_f_map_scene.html#ac94eaceaf77a1fcd9bf5e6105b67cd7e":[1,0,0,2,5], "class_chef_devr_1_1_b_r_d_f_map_scene.html#adfd40726e65f3d0cde74dbbe4d1f17ae":[1,0,0,2,9], "class_chef_devr_1_1_b_r_d_f_map_scene.html#ae757660c0c92f9a0776f9a01340c5334":[1,0,0,2,4], "class_chef_devr_1_1_b_r_d_f_map_scene.html#aec99842ab9594cc3b40fddb9678c5d5b":[1,0,0,2,1], "class_chef_devr_1_1_b_r_d_f_map_view.html":[1,0,0,3], "class_chef_devr_1_1_b_r_d_f_map_view.html#a09ab0977942116bf62ef0a9b5a07c31a":[1,0,0,3,0], "class_chef_devr_1_1_b_r_d_f_map_view.html#a3f6e649638b1c7eaa9603a307ea1b043":[1,0,0,3,4], "class_chef_devr_1_1_b_r_d_f_map_view.html#a545dcc85721c35cb7fb12bfbe737923b":[1,0,0,3,5], "class_chef_devr_1_1_b_r_d_f_map_view.html#a960cdca173ca049aa2ca2fce4df5e389":[1,0,0,3,1], "class_chef_devr_1_1_b_r_d_f_map_view.html#aa11dae2e2ca7b48547caffeeea4eaa1f":[1,0,0,3,2], "class_chef_devr_1_1_b_r_d_f_map_view.html#aa79fec849caf06341af9a21e96b82d7a":[1,0,0,3,3], "class_chef_devr_1_1_b_r_d_f_map_view.html#ae70272df81270f8b939c83caa0d73ef5":[1,0,0,3,6], "class_chef_devr_1_1_b_r_d_f_map_view.html#af07de699e56ec013931afd6c705d79fb":[1,0,0,3,7], "class_chef_devr_1_1_b_r_d_f_model_init_thread.html":[1,0,0,4], "class_chef_devr_1_1_b_r_d_f_model_init_thread.html#a59cea89afddee2d53d959034b601a8d0":[1,0,0,4,1], "class_chef_devr_1_1_b_r_d_f_model_init_thread.html#a642bd365fa1a608c3ca3bc9dd35dc23e":[1,0,0,4,0], "class_chef_devr_1_1_b_r_d_f_model_init_thread.html#a7a6eb6e662bf681d166ea23be09ffe56":[1,0,0,4,2], "class_chef_devr_1_1_b_r_d_f_reconstructed.html":[1,0,0,5], "class_chef_devr_1_1_b_r_d_f_reconstructed.html#a8c40756e398771c4564bb818b0375f9b":[1,0,0,5,0], "class_chef_devr_1_1_b_r_d_f_reconstructed.html#a993df1520e6ad5f7738f97cc31632388":[1,0,0,5,1], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html":[1,0,0,6], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a38e68d22af436cad75fcae4bad752a8b":[1,0,0,6,4], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a5737181bfd180d830e217cb35800e5b6":[1,0,0,6,1], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a5b0d9e4af2c075f5eb95516bd851aa5b":[1,0,0,6,6], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a5d80b89c920e30cdcc41e0d4018f7b68":[1,0,0,6,9], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a5fadb91fdf43bcf2c245003c729b0544":[1,0,0,6,3], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a6f6e55751d2ae40ee9061fb7b6d896a2":[1,0,0,6,13], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a7253ae610cdb56f3cc8a303da22882a3":[1,0,0,6,2], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a76d0921c08ed3c8959fd882d48600bf5":[1,0,0,6,12], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a84e03cd92421979ddc32ccc1ec024636":[1,0,0,6,14], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#a8cdafc4b7f2e20f72c72361f6abfe48f":[1,0,0,6,7], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#abcf7236c8c0419b47ce1535ab8b94f6f":[1,0,0,6,8], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#ac53eec07e3f2efb76f2dec5e62cb064f":[1,0,0,6,5], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#add276c9c0ec81d90eea0209e54d884ea":[1,0,0,6,10], "class_chef_devr_1_1_b_r_d_f_reconstruction_model.html#ae866ee98b7c033854828609c96675820":[1,0,0,6,11], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_1_1_b_r_d_f_reconstruction_model_error.html":[1,0,0,6,0], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_1_1_b_r_d_f_reconstruction_model_error.html#ad0bc66e1b040503de19256fa6bab732e":[1,0,0,6,0,0], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_small_storage.html":[1,0,0,7], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_small_storage.html#a88240ef0f35410ef84ee8f233ad1c354":[1,0,0,7,0], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_small_storage.html#a8fa70d1fb548d78885fa624f623fb37b":[1,0,0,7,2], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_small_storage.html#acd47de94d36f37e43bfe70af6dc8116b":[1,0,0,7,1], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_with_z.html":[1,0,0,8], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_with_z.html#a7d5eb51186567ba4ec2641286601ceba":[1,0,0,8,0], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_with_z.html#aa79fd305fc6cea580d4bdf355712e85e":[1,0,0,8,1], "class_chef_devr_1_1_b_r_d_f_reconstruction_model_with_z.html#aa91ed5c001ebeb106e3eaa8d9ed7023a":[1,0,0,8,2], "class_chef_devr_1_1_b_r_d_f_reconstructor.html":[1,0,0,9], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a1d8c5a67ec486806ba2e49f09831577c":[1,0,0,9,6], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a2e705b55ccdb9994f080c5f4e0e22ac1":[1,0,0,9,10], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a343a7aa9fe94c2ec051c68cdff2ac3f0":[1,0,0,9,0], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a3c62e143ab28b32e7f6c7fed83980f07":[1,0,0,9,9], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a4cef6e174ab0c7728128de983d02b430":[1,0,0,9,1], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a632da6bbc914791177944cf00f6ea5ea":[1,0,0,9,2], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a743ae5821bf5d1f7ec6fa64a60220f15":[1,0,0,9,5], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#a84c7138f8a5bf6aaae2b0e8ed32bb7b4":[1,0,0,9,7], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#aa06fb7b33e413342fba43cc9dc8f3b48":[1,0,0,9,4], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#aa6bcfa043dd70a8c58411af3d3ba1920":[1,0,0,9,8], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#ab9bfd8c7c205aa065bca5019a62f0e7c":[1,0,0,9,11], "class_chef_devr_1_1_b_r_d_f_reconstructor.html#ada12787c3d79feb4bc8a36e74d093480":[1,0,0,9,3], "class_chef_devr_1_1_progress_interface.html":[1,0,0,10], "class_chef_devr_1_1_progress_interface.html#a48c847b32c9b5194bd26584876386d70":[1,0,0,10,1], "class_chef_devr_1_1_progress_interface.html#aa7d1989ec7ba0b7a9a9372021c1822c0":[1,0,0,10,0], "class_chef_devr_1_1_waiting_display.html":[1,0,0,11], "class_chef_devr_1_1_waiting_display.html#aaf2fee02910d6d1f5a9e6f5a166e5ab1":[1,0,0,11,0], "class_parameter_window.html":[1,0,1], "class_parameter_window.html#a03665f53d06b1ebb0c0470ddc3332cdc":[1,0,1,18], "class_parameter_window.html#a07040bf3d38dbc6d4c2141b486e571ed":[1,0,1,16], "class_parameter_window.html#a0935acf33bf6a8d1f2f640eae14b026b":[1,0,1,13], "class_parameter_window.html#a0acdb58f442b181647f79ca6ed750021":[1,0,1,11], "class_parameter_window.html#a0d5e07e3c9faf784ecc4e0e052974d48":[1,0,1,27], "class_parameter_window.html#a21e0f13c5ccf296129d40779bce1faf4":[1,0,1,31], "class_parameter_window.html#a21fcbeb9c757978a3bc477d10337cbfe":[1,0,1,6], "class_parameter_window.html#a268ccabeab21ec1506607863e57ede64":[1,0,1,12], "class_parameter_window.html#a311569165ea5b97256cbb9934b868e29":[1,0,1,1], "class_parameter_window.html#a344b04e741cc28f246edf46cd4d702dd":[1,0,1,30], "class_parameter_window.html#a35695865727e2848319166c361677981":[1,0,1,3], "class_parameter_window.html#a3e8df7b7b6c67e3af022a13e1cb2cfb1":[1,0,1,9], "class_parameter_window.html#a4105df7ff5a98528e28f747946af6952":[1,0,1,20], "class_parameter_window.html#a4332fb650b6699ceeb527115c0760d41":[1,0,1,35], "class_parameter_window.html#a44a057feb7b57d6b28e3ed57e0af2fca":[1,0,1,17], "class_parameter_window.html#a44c93e82554d52a276b03d9b7a79c4e0":[1,0,1,22], "class_parameter_window.html#a45b8269b456d4f9c0c57913235814eaa":[1,0,1,38], "class_parameter_window.html#a4628c75733493a39c59bb80460bfe804":[1,0,1,29], "class_parameter_window.html#a49c468b81046530a7b412ca7d8dc2a3d":[1,0,1,2], "class_parameter_window.html#a4dd5535d3098abed057ffb2164cc1713":[1,0,1,36], "class_parameter_window.html#a5a52cd1186aacf1177ff2834b87bc539":[1,0,1,10], "class_parameter_window.html#a5c05a4418a024c0eaf22941ef65d225a":[1,0,1,34], "class_parameter_window.html#a6210b8881ee762042779f50c70236bef":[1,0,1,7], "class_parameter_window.html#a69362468782f0eb3379dd2579ed2f7f6":[1,0,1,15], "class_parameter_window.html#a6c6f60f49bd097ddc45872e8b58cc741":[1,0,1,19], "class_parameter_window.html#a6cd732e02f1321ced10fb319fc720047":[1,0,1,23], "class_parameter_window.html#a6d2e50a54b30b33991556ac45b670358":[1,0,1,21], "class_parameter_window.html#a73d2c1887b21a43f775278b7f547b347":[1,0,1,37], "class_parameter_window.html#a8cea960d6b806f62cd8b0afc17f0d008":[1,0,1,26], "class_parameter_window.html#a8fbdc6adc6bf6797c526f206309b6282":[1,0,1,25], "class_parameter_window.html#a94cd5fb5725d7d12a5c7c541053a01f5":[1,0,1,4], "class_parameter_window.html#a95da188be6f3af06732764ea6f074e57":[1,0,1,0], "class_parameter_window.html#aa48b0e6f90454720e8d8932c9a5e5f1c":[1,0,1,28], "class_parameter_window.html#ab8373d1c64795c7e252234bf68c65432":[1,0,1,32], "class_parameter_window.html#acb9cec75966cc62c1e6f22f592bd733d":[1,0,1,24], "class_parameter_window.html#ad8577ea3b5aa0a1e7e67f3264571b1a5":[1,0,1,5], "class_parameter_window.html#ae27de4780e303ea24b11c0a89160c429":[1,0,1,8], "class_parameter_window.html#ae59f4d58842a54a269a92cddfcb36c28":[1,0,1,14], "class_parameter_window.html#ae9ec7132117cabcaeb6baf5478abaf76":[1,0,1,33], "class_parameter_window.html#aee5177ea06f491bcfd5c5816050493c1":[1,0,1,39], "class_r_thread.html":[1,0,2], "class_r_thread.html#a0e34fbc336aae9100f5cbee1aec8c5b6":[1,0,2,3], "class_r_thread.html#a3f56835cb6875d61ee734ede0c6a24c5":[1,0,2,2], "class_r_thread.html#a66eaab5fd584e5a08649e9d671d60cf5":[1,0,2,4], "class_r_thread.html#a8768af1087ff8c01fd2ca89b5b132c6d":[1,0,2,1], "class_r_thread.html#a98aa163fc3c6d908292e5ee096c2f61c":[1,0,2,0], "class_waiting_spinner_widget.html":[1,0,3], "class_waiting_spinner_widget.html#a0034d3b61e3f1f41ea147039913906d4":[1,0,3,39], "class_waiting_spinner_widget.html#a08163883e94d431a7c2aabf30a03c850":[1,0,3,14], "class_waiting_spinner_widget.html#a144cdce01e10daeefb91846b7d7328a5":[1,0,3,8], "class_waiting_spinner_widget.html#a25b9639b865d15610a499aaced705afe":[1,0,3,26], "class_waiting_spinner_widget.html#a288840f2b5f8eca150fde75b0244c0ab":[1,0,3,1], "class_waiting_spinner_widget.html#a29945c03eaf051081ea21f22dca6e97a":[1,0,3,23], "class_waiting_spinner_widget.html#a2ceb91dfdafcd41b99f04aa2b4b81786":[1,0,3,17], "class_waiting_spinner_widget.html#a2eb71c4c6472ce81da6e875cf790809b":[1,0,3,32], "class_waiting_spinner_widget.html#a33bbf199e55d0a5d58f71ba65a686d48":[1,0,3,40], "class_waiting_spinner_widget.html#a35164a7ac60db4b199caf7624ab3acf2":[1,0,3,3], "class_waiting_spinner_widget.html#a3be1ccd1e770ac866aed2469470c239f":[1,0,3,43], "class_waiting_spinner_widget.html#a4162157a6d402ffa3a87f8e6fd7abf0d":[1,0,3,47], "class_waiting_spinner_widget.html#a4a72ed38feadc151679c1b3ee7df8f99":[1,0,3,33], "class_waiting_spinner_widget.html#a4adc650895478217a5f28c72a9df1e53":[1,0,3,19], "class_waiting_spinner_widget.html#a51b04fcda4b13695fcbb8481c73699da":[1,0,3,38], "class_waiting_spinner_widget.html#a5207a447314b9b3505177fec483f5608":[1,0,3,0], "class_waiting_spinner_widget.html#a54f72cfcb508e8d4bea313891d87b766":[1,0,3,15], "class_waiting_spinner_widget.html#a59f0c98b8cf02a3d7f50085e856ff908":[1,0,3,46], "class_waiting_spinner_widget.html#a5bc33ab179119f510d556c214fe7ac9b":[1,0,3,18], "class_waiting_spinner_widget.html#a5fece0a70d836cc01bcfdebaf7b43cc4":[1,0,3,29], "class_waiting_spinner_widget.html#a6c42700d650379cffd704199c63c4f28":[1,0,3,10], "class_waiting_spinner_widget.html#a797995d006da2e96b72daa959ddd274e":[1,0,3,20], "class_waiting_spinner_widget.html#a7ac6a1feaec54bd2f54c7110a179f46f":[1,0,3,31], "class_waiting_spinner_widget.html#a7d5224bb675c63b974acf3ab9da2a0ae":[1,0,3,41], "class_waiting_spinner_widget.html#a853bddeb85306ca792f3696064d911b8":[1,0,3,45], "class_waiting_spinner_widget.html#a885516e19838042bd79042f854452a3d":[1,0,3,5], "class_waiting_spinner_widget.html#a894f40b4623f9e7754c48e4478c23307":[1,0,3,25], "class_waiting_spinner_widget.html#a8a9ed21ff17ead12fcbf26b163940dbe":[1,0,3,11], "class_waiting_spinner_widget.html#a8d220962262d8fc1e8674321535e1e15":[1,0,3,13], "class_waiting_spinner_widget.html#a9398c0e6ec48a6e2f91f7c0ae9b5d924":[1,0,3,44], "class_waiting_spinner_widget.html#a987a9c7234f83ca2665dd05f8d039e64":[1,0,3,21], "class_waiting_spinner_widget.html#a9db984232c785de31390485c30d7a596":[1,0,3,6], "class_waiting_spinner_widget.html#aa0a76a4ea0666f843b8a4cf2cb5a7491":[1,0,3,30], "class_waiting_spinner_widget.html#aa716528e1094789337adc5d291c69747":[1,0,3,9], "class_waiting_spinner_widget.html#aacb453453fd98625eb38e021de72070f":[1,0,3,16], "class_waiting_spinner_widget.html#aaea8d9dd1dfd0fec4d63a73a3b940e79":[1,0,3,35], "class_waiting_spinner_widget.html#ab02d5a79b1794c55b58b3cd417075a5a":[1,0,3,7], "class_waiting_spinner_widget.html#ab8adb44bc0a3eb32bfe9d7b5b1a83e4c":[1,0,3,4], "class_waiting_spinner_widget.html#ac3cbb1d3a1386bca905d7c6a91fbd0ae":[1,0,3,36], "class_waiting_spinner_widget.html#ac61cef28a4710c6d2a0ea3e8d0bca49b":[1,0,3,2], "class_waiting_spinner_widget.html#ad0a0f83cf6adcf03e7c86626bfdaad6d":[1,0,3,28], "class_waiting_spinner_widget.html#ad4ad8fab83b1a60cf1dff78d6ad716d7":[1,0,3,22], "class_waiting_spinner_widget.html#addb2884587497961d78e24c50a2f1aba":[1,0,3,24], "class_waiting_spinner_widget.html#ae80928504ba4586bed5d80db45455b4a":[1,0,3,42], "class_waiting_spinner_widget.html#ae9df7d573477f907da5da0b0518d300a":[1,0,3,34], "class_waiting_spinner_widget.html#af2e707cbf375a3b5626980854e7423f2":[1,0,3,37], "class_waiting_spinner_widget.html#af6a17bce3bc7081c1e0297e6249576e0":[1,0,3,12], "class_waiting_spinner_widget.html#af9ec791036d62a78b0f557346d1c0262":[1,0,3,27], "classes.html":[1,1], "files.html":[2,0], "functions.html":[1,3,0], "functions_func.html":[1,3,1], "functions_vars.html":[1,3,2], "globals.html":[2,1,0], "globals_defs.html":[2,1,2] };
#include "Main.h" #define HASHSIZE INT_MAX/100000 /*HASHTABLE*/ char** HASH=NULL; /*FUNCTIONS*/ int hashfunction(char*); void printHashTable(); void freeHashTable();
using System; using System.Collections.Generic; // Define an interface for pipeline contributors public interface IPipelineContributor { void Execute(); } // Define a class to represent the pipeline public class Pipeline { private readonly List<IPipelineContributor> contributors = new List<IPipelineContributor>(); // Method to register a contributor's operation public void RegisterContributor(IPipelineContributor contributor) { contributors.Add(contributor); } // Method to execute the operations in the pipeline in the specified order public void ExecutePipeline() { foreach (var contributor in contributors) { contributor.Execute(); } } } // Define a class to represent the ContributorExecutingAfter<T> public class ContributorExecutingAfter<T> : IPipelineContributor where T : IPipelineContributor { public void Execute() { // Implement the logic to execute the operation after the specified contributor Console.WriteLine($"Executing operation after {typeof(T).Name}"); } } // Example usage public class ExampleContributor : IPipelineContributor { public void Execute() { Console.WriteLine("Executing example operation"); } } public class Program { public static void Main() { // Create a pipeline var pipeline = new Pipeline(); // Register contributors with the pipeline pipeline.RegisterContributor(new ContributorExecutingAfter<ExampleContributor>()); pipeline.RegisterContributor(new ExampleContributor()); // Execute the pipeline pipeline.ExecutePipeline(); } }
/** * @license Copyright (c) 2003-2016, CKSource - <NAME>. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'sl', { title: 'Navodila za dostopnost', contents: 'Vsebina pomoči. Če želite zapreti pogovorno okno, pritisnite ESC.', legend: [ { name: 'Splošno', items: [ { name: 'Orodna vrstica urejevalnika', legend: 'Pritisnite ${toolbarFocus} za pomik v orodno vrstico. Z TAB in SHIFT+TAB se pomikate na naslednjo in prejšnjo skupino orodne vrstice. Z DESNO PUŠČICO ali LEVO PUŠČICO se pomikate na naslednji in prejšnji gumb orodne vrstice. Pritisnite SPACE ali ENTER, da aktivirate gumb orodne vrstice.' }, { name: 'Urejevalno Pogovorno Okno', legend: 'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING }, { name: 'Kontekstni meni urejevalnika', legend: 'Pritisnite ${contextMenu} ali APPLICATION KEY, da odprete kontekstni meni. Nato se premaknite na naslednjo možnost menija s tipko TAB ali PUŠČICA DOL. Premakniti se na prejšnjo možnost z SHIFT + TAB ali PUŠČICA GOR. Pritisnite SPACE ali ENTER za izbiro možnosti menija. Odprite podmeni trenutne možnosti menija s tipko SPACE ali ENTER ali DESNA PUŠČICA. Vrnite se na matični element menija s tipko ESC ali LEVA PUŠČICA. Zaprite kontekstni meni z ESC.' }, { name: 'Urejevalno Seznamsko Polje', legend: 'Znotraj seznama, se premaknete na naslednji element seznama s tipko TAB ali PUŠČICO DOL. Z SHIFT+TAB ali PUŠČICO GOR se premaknete na prejšnji element seznama. Pritisnite tipko SPACE ali ENTER za izbiro elementa. Pritisnite tipko ESC, da zaprete seznam.' }, { name: 'Urejevalna vrstica poti elementa', legend: 'Pritisnite ${elementsPathFocus} za pomikanje po vrstici elementnih poti. S TAB ali DESNA PUŠČICA se premaknete na naslednji gumb elementa. Z SHIFT+TAB ali LEVO PUŠČICO se premaknete na prejšnji gumb elementa. Pritisnite SPACE ali ENTER za izbiro elementa v urejevalniku.' } ] }, { name: 'Ukazi', items: [ { name: 'Razveljavi ukaz', legend: 'Pritisnite ${undo}' }, { name: 'Ponovi ukaz', legend: 'Pritisnite ${redo}' }, { name: 'Krepki ukaz', legend: 'Pritisnite ${bold}' }, { name: 'Ležeči ukaz', legend: 'Pritisnite ${italic}' }, { name: '<NAME>', legend: 'Pritisnite ${underline}' }, { name: '<NAME>', legend: 'Pritisnite ${link}' }, { name: '<NAME>', legend: 'Pritisnite ${toolbarCollapse}' }, { name: 'Dostop do prejšnjega ukaza ostrenja', legend: 'Pritisnite ${accessPreviousSpace} za dostop do najbližjega nedosegljivega osredotočenega prostora pred strešico, npr.: dva sosednja HR elementa. Ponovite kombinacijo tipk, da dosežete oddaljene osredotočene prostore.' }, { name: 'Dostop do naslednjega ukaza ostrenja', legend: 'Pritisnite ${accessNextSpace} za dostop do najbližjega nedosegljivega osredotočenega prostora po strešici, npr.: dva sosednja HR elementa. Ponovite kombinacijo tipk, da dosežete oddaljene osredotočene prostore.' }, { name: 'Pomoč dostopnosti', legend: 'Pritisnite ${a11yHelp}' } ] } ], tab: 'Tab', pause: 'Pause', capslock: 'Caps Lock', escape: 'Escape', pageUp: 'Page Up', pageDown: 'Page Down', leftArrow: 'Puščica levo', upArrow: 'Puščica gor', rightArrow: 'Puščica desno', downArrow: 'Puščica dol', insert: 'Insert', leftWindowKey: 'Leva tipka Windows', rightWindowKey: 'Desna tipka Windows', selectKey: 'Select tipka', numpad0: 'Numpad 0', numpad1: 'Numpad 1', numpad2: 'Numpad 2', numpad3: 'Numpad 3', numpad4: 'Numpad 4', numpad5: 'Numpad 5', numpad6: 'Numpad 6', numpad7: 'Numpad 7', numpad8: 'Numpad 8', numpad9: 'Numpad 9', multiply: 'Zmnoži', add: 'Dodaj', subtract: 'Odštej', decimalPoint: 'Decimalna vejica', divide: 'Deli', f1: 'F1', f2: 'F2', f3: 'F3', f4: 'F4', f5: 'F5', f6: 'F6', f7: 'F7', f8: 'F8', f9: 'F9', f10: 'F10', f11: 'F11', f12: 'F12', numLock: 'Num Lock', scrollLock: 'Scroll Lock', semiColon: 'Podpičje', equalSign: 'Enačaj', comma: 'Vejica', dash: 'Vezaj', period: 'Pika', forwardSlash: 'Desna poševnica', graveAccent: 'Krativec', openBracket: 'Oklepaj', backSlash: 'Leva poševnica', closeBracket: 'Zaklepaj', singleQuote: 'Opuščaj' } );
import moment from "moment" import { GT } from "@graphql/index" import PricePoint from "@graphql/types/object/price-point" import PriceGraphRange, { priceRangeValues, } from "@graphql/types/scalar/price-graph-range" import { PriceInterval, PriceRange } from "@domain/price" import * as Prices from "@app/prices" import { SATS_PER_BTC } from "@config/app" const parseRange: (string: typeof priceRangeValues[number]) => PriceRange = (range) => { switch (range) { case "ONE_DAY": return PriceRange.OneDay case "ONE_WEEK": return PriceRange.OneWeek case "ONE_MONTH": return PriceRange.OneMonth case "ONE_YEAR": return PriceRange.OneYear case "FIVE_YEARS": return PriceRange.FiveYears } } const parseInterval: (string: typeof priceRangeValues[number]) => PriceInterval = ( range, ) => { switch (range) { case "ONE_DAY": return PriceInterval.OneHour case "ONE_WEEK": return PriceInterval.FourHours case "ONE_MONTH": return PriceInterval.OneDay case "ONE_YEAR": return PriceInterval.OneWeek case "FIVE_YEARS": return PriceInterval.OneMonth } } const BtcPriceListQuery = GT.Field({ type: GT.List(PricePoint), args: { range: { type: GT.NonNull(PriceGraphRange), }, }, resolve: async (_, args) => { const range = parseRange(args.range) const interval = parseInterval(args.range) if (!range) throw new Error("Invalid range") const hourlyPrices = await Prices.getPriceHistory({ range, interval }) if (hourlyPrices instanceof Error) throw hourlyPrices const prices: PricePointType[] = hourlyPrices.map(({ date, price }) => { const btcPriceInCents = price * 100 * SATS_PER_BTC return { timestamp: Math.floor(date.getTime() / 1000), price: { formattedAmount: btcPriceInCents.toString(), base: Math.round(btcPriceInCents * 10 ** 4), offset: 4, currencyUnit: "USDCENT", }, } }) // Add the current price as the last item in the array // This is used by the mobile app to convert prices const currentPrice = await Prices.getCurrentPrice() if (!(currentPrice instanceof Error)) { const currentBtcPriceInCents = currentPrice * 100 * SATS_PER_BTC prices.push({ timestamp: moment().unix(), price: { formattedAmount: currentBtcPriceInCents.toString(), base: Math.round(currentBtcPriceInCents * 10 ** 4), offset: 4, currencyUnit: "USDCENT", }, }) } return prices }, }) export default BtcPriceListQuery
#!/bin/bash FN="TMExplorer_1.4.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.14/data/experiment/src/contrib/TMExplorer_1.4.0.tar.gz" "https://bioarchive.galaxyproject.org/TMExplorer_1.4.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-tmexplorer/bioconductor-tmexplorer_1.4.0_src_all.tar.gz" ) MD5="aa237f4ec204fc9e1dd3b508bfef2ea2" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
<gh_stars>0 class GameTurn { constructor() { this.current = -1; this.values = ["toPlayer", "player", "toBrain", "brain"]; this.displayText = "Default"; this.alphaMax = undefined; this.next(); } next() { this.current++; if (this.current == this.values.length) this.current = 0; this.value = this.values[this.current]; } set value(value) { this.gameTurnValue = value; switch(this.gameTurnValue) { case "toPlayer": this.displayText = "Your's turn!"; this.textFade(this.next.bind(this)); break; case "player": this.displayText = ""; // check if player has lost let canMove = false; for (let playerPawn of grid.pawns.player) { let nextY = parseInt(playerPawn.row) - 1; let nextXs = [0,1,2]; if (playerPawn.col == 0) nextXs.splice(2,1); if (playerPawn.col == 2) nextXs.splice(0,1); let pawnCanMove = true; for (let nextX of nextXs) { let canMoveForwards = true; let canMoveDiagonally = false; for(let brainPawn of grid.pawns.brain) { if (nextX != playerPawn.col && brainPawn.row == nextY && brainPawn.col == nextX) { canMoveDiagonally = true; } if (nextX == playerPawn.col && brainPawn.row == nextY && brainPawn.col == nextX) { canMoveForwards = false; } } if (!(canMoveForwards || canMoveDiagonally)) { pawnCanMove = false; } } if (pawnCanMove) { canMove = true; } } if (!canMove) { this.value = "brainWon"; } break; case "toBrain": this.displayText = "Enemy's turn!"; this.textFade(this.next.bind(this)); break; case "brain": this.displayText = ""; brain.play(); break; case "playerWon": this.displayText = "You have won!"; brain.loss(); setTimeout(()=>{ this.value = "gameReset"; }, 1000); break; case "brainWon": this.displayText = "Enemy have won!"; brain.win(); setTimeout(()=>{ this.value = "gameReset"; }, 1000); break; case "gameReset": brain.restart(); grid.restart(); this.current = -1; this.next(); break; case "brainLoad": this.displayText = "Loading brain memory"; this.textFade(function() { this.value = "gameReset"; }.bind(this)); break; } } get value() { return this.gameTurnValue; } render() { noStroke(); let alpha = (this.alpha === undefined) ? 255 : this.alpha; if (this.alphaMax) { alpha = lerp(this.alphaFrom,this.alphaTo,this.alphaAmt/this.alphaMax); this.alphaAmt++; if (this.alphaAmt == this.alphaMax) { this.alphaMaxAction(); } } fill(0,0,0,alpha); textSize(28); textAlign(CENTER,CENTER); text(this.displayText, width/2,height*3/8); } textFade(endWith) { this.alpha = 0; setTimeout(()=>{ this.alphaFrom = 0; this.alphaTo = 255; this.alphaAmt = 0; this.alphaMax = 15; this.alphaMaxAction = () => { setTimeout(()=>{ this.alphaFrom = 255; this.alphaTo = 0; this.alphaAmt = 0; this.alphaMax = 15; this.alphaMaxAction = () => { this.alpha = undefined; this.alphaMax = undefined; endWith(); } }, 500); } }, 200); } }
package elasta.criteria.json.mapping; import elasta.criteria.Func; /** * Created by Jango on 2017-01-07. */ public interface Operation2Builder { Func build(Func func1, Func func2); }
import logging import os from datetime import datetime from airflow import DAG from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator from airflow_utils import ( DBT_IMAGE, dbt_install_deps_nosha_cmd, gitlab_defaults, gitlab_pod_env_vars, slack_failed_task, xs_warehouse, ) from kube_secrets import ( SALT, SALT_EMAIL, SALT_IP, SALT_NAME, SNOWFLAKE_ACCOUNT, SNOWFLAKE_PASSWORD, SNOWFLAKE_TRANSFORM_ROLE, SNOWFLAKE_TRANSFORM_SCHEMA, SNOWFLAKE_TRANSFORM_WAREHOUSE, SNOWFLAKE_USER, ) # Load the env vars into a dict env = os.environ.copy() GIT_BRANCH = env["GIT_BRANCH"] # ds - Airflow macro template for the execution date as YYYY-MM-DD pod_env_vars = {"DBT_VARS": "{ 'valid_at': '{{ ds }} 06:59:00' }"} pod_env_vars = {**gitlab_pod_env_vars, **pod_env_vars} logging.info(pod_env_vars) # Default arguments for the DAG default_args = { "catchup": False, "depends_on_past": False, "on_failure_callback": slack_failed_task, "params": {"slack_channel_override": "#dbt-runs"}, "owner": "airflow", "start_date": datetime(2020, 3, 31, 0, 0, 0), } # Create the DAG dag = DAG( dag_id="dbt_arr_data_mart_incr", default_args=default_args, schedule_interval="0 7 * * *", description="\nThis DAG runs arr_data_mart_incr model using DAG's execution date" " as input parameter for dbt model. The time used as input parameter " "for the dbt model is set to 06:59 am UTC, which is EOD PST.\n" " This way a dagrun generated any time given execution date will " "capture a snapshot of MRR data state as per dagrun's execution " "date at 06:59 am UTC. ", ) dbt_cmd = f""" {dbt_install_deps_nosha_cmd} && dbt run --profiles-dir profile --target prod --models +arr_data_mart_incr --vars "$DBT_VARS"; ret=$?; python ../../orchestration/upload_dbt_file_to_snowflake.py results; exit $ret """ logging.info(dbt_cmd) dbt_poc = KubernetesPodOperator( **gitlab_defaults, image=DBT_IMAGE, task_id="dbt-arr-data-mart-incr", name="dbt-arr-data-mart-incr", secrets=[ SALT, SALT_EMAIL, SALT_IP, SALT_NAME, SNOWFLAKE_ACCOUNT, SNOWFLAKE_USER, SNOWFLAKE_PASSWORD, SNOWFLAKE_TRANSFORM_ROLE, SNOWFLAKE_TRANSFORM_WAREHOUSE, SNOWFLAKE_TRANSFORM_SCHEMA, ], env_vars=pod_env_vars, arguments=[dbt_cmd], dag=dag, )
import React from "react"; import { Button } from "../../globalStyles"; import { FaFacebook, FaInstagram, FaYoutube, FaTwitter, } from "react-icons/fa"; import { FooterContainer, FooterSubscription, FooterSubHeading, Form, FooterLinksContainer, FooterLinksWrapper, FooterLinkItems, FooterLinkTitle, FooterLink, SocialMedia, SocialMediaWrap, SocialLogo, SocialIcon, WebsiteRights, SocialIcons, SocialIconLink, } from "./Footer.elements"; function Footer() { return ( <FooterContainer> <FooterSubscription> <FooterSubHeading> Bienvenido a donde trabaja el futuro </FooterSubHeading> <Form> <Button fontBig>Hablar de ventas</Button> </Form> </FooterSubscription> <FooterLinksContainer> <FooterLinksWrapper> <FooterLinkItems> <FooterLinkTitle>¿R32?</FooterLinkTitle> <FooterLink to="/">Compromiso</FooterLink> <FooterLink to="/">Canales</FooterLink> <FooterLink to="/">Escala</FooterLink> <FooterLink to="/">Demostración</FooterLink> </FooterLinkItems> <FooterLinkItems> <FooterLinkTitle>Producto</FooterLinkTitle> <FooterLink to="/">Características</FooterLink> <FooterLink to="/">Integraciones</FooterLink> <FooterLink to="/">Soluciones</FooterLink> <FooterLink to="/">Planes</FooterLink> </FooterLinkItems> </FooterLinksWrapper> <FooterLinksWrapper> <FooterLinkItems> <FooterLinkTitle>Terminos</FooterLinkTitle> <FooterLink to="/">Estado</FooterLink> <FooterLink to="/">Condiciones</FooterLink> <FooterLink to="/">cookies</FooterLink> <FooterLink to="/">Ayuda</FooterLink> </FooterLinkItems> <FooterLinkItems> <FooterLinkTitle>Empresa</FooterLinkTitle> <FooterLink to="/">Sobre nosotros</FooterLink> <FooterLink to="/">Liderazgo</FooterLink> <FooterLink to="/">Desarrolladores</FooterLink> <FooterLink to="/">Aplicaciones</FooterLink> </FooterLinkItems> </FooterLinksWrapper> </FooterLinksContainer> <SocialMedia> <SocialMediaWrap> <SocialLogo to="/"> <SocialIcon /> 32 System </SocialLogo> <WebsiteRights> ©{new Date().getFullYear()} Add bross</WebsiteRights> <SocialIcons> <SocialIconLink href="https://twitter.com/CesarCamil0" target="_blank" aria-label="Facebook"> <FaFacebook /> </SocialIconLink> <SocialIconLink href="https://twitter.com/CesarCamil0" target="_blank" aria-label="Instagram"> <FaInstagram /> </SocialIconLink> <SocialIconLink href={ "https://twitter.com/CesarCamil0" } rel="noopener noreferrer" target="_blank" aria-label="Youtube" > <FaYoutube /> </SocialIconLink> <SocialIconLink href="https://twitter.com/CesarCamil0" target="_blank" aria-label="Twitter"> <FaTwitter /> </SocialIconLink> </SocialIcons> </SocialMediaWrap> </SocialMedia> </FooterContainer> ); } export default Footer;
package com.mooo.amjansen.journal; /** * Created with IntelliJ IDEA. * User: matthias * Date: 26.09.18 * Time: 12:30 * * To change this template use File | Settings | File Templates. * */ public interface CancelableJournalAction extends JournalAction { /** * Mit dieser Methode wird diese JournalAction aufgehoben. */ public void cancel(); /** * Diese Methode liefert die Id der JournalAction * die von dieser JournalAction aufgehoben werden * soll.Wenn diese JournalAction keine Andere * aufheben will, muss sie -1 liefern. * * @return */ public int getCancelId(); /** * Mit dieser Methode wird die Id der JournalAction, * die von dieser JournalAction aufgehoben werden * soll. Der Wert sollte als nicht transienter Wert * in der JournalAction gespeichert werden. * * @param id */ public void setCancelId(int id, CancelableJournalAction canceledAction); }
package main import "fmt" func reverseString(s string) string { runes := []rune(s) for first, last := 0, len(runes)-1; first < last; first, last = first+1, last-1 { runes[first], runes[last] = runes[last], runes[first] } return string(runes) } func main() { fmt.Println(reverseString("Hello")) }
import { render, screen, waitFor } from '@testing-library/react'; import { Backdrop } from '.'; describe('Backdrop general behavior', () => { test('renders without crashing', () => { render(<Backdrop />); }); test('renders when "visible" is "true"', async () => { const { rerender } = render( <Backdrop data-testid="test-element" visible /> ); const backdrop = screen.getByTestId('test-element'); expect(backdrop).toBeInTheDocument(); rerender(<Backdrop data-testid="test-element" />); await waitFor(() => expect(backdrop).not.toBeInTheDocument()); }); });
#!/bin/bash cd $(dirname "$0") REPO=getsentry/sentry-cli VERSION=1.71.0 PLATFORMS="Darwin-universal Linux-x86_64 Windows-x86_64" TARGETDIR="../package-dev/Editor/sentry-cli/" rm -f ${TARGETDIR}* for plat in $PLATFORMS; do suffix='' if [[ $plat == *"Windows"* ]]; then suffix='.exe' fi echo "${plat}" download_url=https://github.com/$REPO/releases/download/$VERSION/sentry-cli-${plat}${suffix} fn="${TARGETDIR}/${plat}${suffix}" curl -SL --progress-bar "$download_url" -o "$fn" chmod +x "$fn" done
"""Ex022 Crie um programa que leia o nome completo de uma pessoa, e mostre: O nome com todas as letras maiúsculas: O nome com todas as letras minúsculas: Quantas letras sem considerar espaço Quantas letras tem o primeiro nome:""" nome = str(input('Digite seu nome completo: ')).strip() print('Seu nome com todas as letras maiúsculas: {}'.format(nome.upper())) print('Seu nome com todas as letras minúsculas: {}'.format(nome.lower())) espaco = nome.count(' ') tot = len(nome) - espaco print('Seu nome tem {} letras'.format(tot)) pnome = nome.split() print('Seu primeiro nome tem {} letras'.format(len(pnome[0])))
#!/bin/bash source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh" trap os::test::junit::reconcile_output EXIT os::test::junit::declare_suite_start "cmd/set-env" # This test validates the value of --image for oc run os::cmd::expect_success 'oc new-app node' os::cmd::expect_failure_and_text 'oc set env dc/node' 'error: at least one environment variable must be provided' os::cmd::expect_success_and_text 'oc set env dc/node key=value' 'deploymentconfig.apps.openshift.io/node updated' os::cmd::expect_success_and_text 'oc set env dc/node --list' 'deploymentconfigs/node, container node' os::cmd::expect_success_and_text 'oc set env dc --all --containers="node" key-' 'deploymentconfig.apps.openshift.io/node updated' os::cmd::expect_failure_and_text 'oc set env dc --all --containers="node"' 'error: at least one environment variable must be provided' os::cmd::expect_failure_and_not_text 'oc set env --from=secret/mysecret dc/node' 'error: at least one environment variable must be provided' os::cmd::expect_failure_and_text 'oc set env dc/node test#abc=1234' 'environment variable test#abc=1234 is invalid, a valid environment variable name must consist of alphabetic characters' # ensure deleting a var through --env does not result in an error message os::cmd::expect_success_and_text 'oc set env dc/node key=value' 'deploymentconfig.apps.openshift.io/node updated' os::cmd::expect_success_and_text 'oc set env dc/node dots.in.a.key=dots.in.a.value' 'deploymentconfig.apps.openshift.io/node updated' os::cmd::expect_success_and_text 'oc set env dc --all --containers="node" --env=key-' 'deploymentconfig.apps.openshift.io/node updated' # ensure deleting a var through --env actually deletes the env var os::cmd::expect_success_and_not_text "oc get dc/node -o jsonpath='{ .spec.template.spec.containers[?(@.name==\"node\")].env }'" 'name\:key' os::cmd::expect_success_and_text "oc get dc/node -o jsonpath='{ .spec.template.spec.containers[?(@.name==\"node\")].env }'" 'name\:dots.in.a.key' os::cmd::expect_success_and_text 'oc set env dc --all --containers="node" --env=dots.in.a.key-' 'deploymentconfig.apps.openshift.io/node updated' os::cmd::expect_success_and_not_text "oc get dc/node -o jsonpath='{ .spec.template.spec.containers[?(@.name==\"node\")].env }'" 'name\:dots.in.a.key' # check that env vars are not split at commas os::cmd::expect_success_and_text 'oc set env -o yaml dc/node PASS=x,y=z' 'value: x,y=z' os::cmd::expect_success_and_text 'oc set env -o yaml dc/node --env PASS=x,y=z' 'value: x,y=z' # warning is printed when --env has comma in it os::cmd::expect_success_and_text 'oc set env dc/node --env PASS=x,y=z' 'no longer accepts comma-separated list' # warning is not printed for variables passed as positional arguments os::cmd::expect_success_and_not_text 'oc set env dc/node PASS=x,y=z' 'no longer accepts comma-separated list' # create a build-config object with the JenkinsPipeline strategy os::cmd::expect_success 'oc process -p NAMESPACE=openshift -f examples/jenkins/jenkins-ephemeral-template.json | oc create -f -' os::cmd::expect_success "echo 'apiVersion: v1 kind: BuildConfig metadata: name: fake-pipeline spec: source: git: uri: git://github.com/openshift/ruby-hello-world.git strategy: jenkinsPipelineStrategy: {} ' | oc create -f -" # ensure build-config has been created and that its type is "JenkinsPipeline" os::cmd::expect_success_and_text "oc get bc fake-pipeline -o jsonpath='{ .spec.strategy.type }'" 'JenkinsPipeline' # attempt to set an environment variable os::cmd::expect_success_and_text 'oc set env bc/fake-pipeline FOO=BAR' 'buildconfig.build.openshift.io/fake\-pipeline updated' # ensure environment variable was set os::cmd::expect_success_and_text "oc get bc fake-pipeline -o jsonpath='{ .spec.strategy.jenkinsPipelineStrategy.env }'" 'name\:FOO' os::cmd::expect_success 'oc delete bc fake-pipeline' echo "oc set env: ok" os::test::junit::declare_suite_end
$(function(){ var $t, t, v, animate, cleanupCode = function(code){ return code.replace(/[<>\"\'\t\n]/g, function(m) { return { '<' : '&lt;', '>' : '&gt;', "'" : '&#39;', '"' : '&quot;', '\t': ' ', '\n': '<br/>' // needed for IE }[m]}); }; $("a.external").each(function(){this.target = '_new';}); // get javascript source if ($("#js").length) { $("#javascript pre").addClass('mod').html( cleanupCode( $("#js").html() ) ); } if ($("#css").length) { $("pre.lang-css").addClass('mod').html( cleanupCode( $("#css").html() ) ); } if ($("#demo").length) { $("#html pre").addClass('mod').html( cleanupCode( $("#demo").html() ) ); } // apply to already pre-formatted blocks to add <br> for IE $('pre:not(.mod)').each(function(){ $t = $(this); $t.html( cleanupCode( $t.html() ) ); }); if (typeof prettyPrint !== 'undefined') { prettyPrint(); } // hide child rows $('#root .tablesorter-childRow').hide(); // toggle child row content, not hiding the row since we are using rowspan $('#root .toggle').click(function(){ $(this).closest('tr').nextUntil('tr:not(.tablesorter-childRow)').toggle(); return false; }); animating = false; $('.collapsible').hide(); $('.toggle2') .click(function(e){ if (!animating) { animating = true; $(this).closest('tr').find('.collapsible').slideToggle(); setTimeout(function(){ animating = false; }, 200); } return false; }); $('.toggle2, span.permalink') .dblclick(function(){ window.location.hash = '#' + $(this).closest('tr')[0].id; return false; }); $('.toggleAll, .showAll, .hideAll').click(function(){ t = $.trim($(this).text()); $(this).parent().next('table').find('.collapsible')[t](); return false; }); // update version number $t = $('.current-version'); if ($t.length) { $t.html($.tablesorter.version); } // add high visibility tags for newest versions (just grab the major revision number 2.10.0 -> 10 t = $.tablesorter.version.replace(/(v|version|\+)/g, '').split('.'); v = [ parseInt(t[0], 10) || 1, parseInt(t[1], 10) || 0 ]; $('.version').each(function(){ var i; $t = $(this); i = $t.text().replace(/(v|version|\+)/g, '').split('.'); t = [ parseInt(i[0], 10) || 1, parseInt(i[1], 10) || 0 ]; if (t[0] === v[0] && t[1] >= v[1] - 1 ) { $t.prepend('<span class="tip' + ( t[0] === v[0] && t[1] < v[1] ? ' old' : '' ) + '"><em>'+ ($t.hasClass('updated') ? 'Updated' : 'New') + '</em></span> '); } }); }); function showProperty(){ var prop, h = window.location.hash; if (h) { prop = $(h); if (prop.length && prop[0].tagName !== "TABLE") { prop.find('.collapsible').show(); if (h === '#csschildrow') { $('#root .tablesorter-childRow').show(); } // move below sticky header; added delay as there could be some lag setTimeout(function(){ if (/options/.test(prop.closest('table').attr('id') || '')) { $(window).scrollTop( prop.position().top - 28 ); } }, 200); } } } $(window).load(function(){ if ($('#root').length) { $(window).bind('hashchange', function(){ showProperty(); }); showProperty(); } }); // append hidden parsed value to cell // used by feet-inch-fraction & metric parser demos var addParsedValues = function($t, cols, format){ var i, j, r, $r = $t.find('tbody tr'), c = $t[0].config.cache[0].normalized, l = c.length - 1; $r.each(function(i){ r = this; $.each(cols, function(v,j){ r.cells[j].innerHTML += ' <span class="val hidden removeme">(<span class="results">' + (format ? format(c[i][j]) : c[i][j]) + '</span>)</span>'; }); }); $('.toggleparsedvalue').on('click', function(){ $('.val').toggleClass('hidden'); return false; }); };
<gh_stars>10-100 /* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include "conversion.h" static const char hex_to_ascii_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; static const signed char ascii_to_hex_table[0x100] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const signed char ascii_to_dec_table[0x100] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; void hexa_to_ascii ( uint8_t * from, char *to, size_t length) { int i; for (i = 0; i < length; i++) { uint8_t upper = (from[i] & 0xf0) >> 4; uint8_t lower = from[i] & 0x0f; to[2 * i] = hex_to_ascii_table[upper]; to[2 * i + 1] = hex_to_ascii_table[lower]; } } int ascii_to_hex ( uint8_t * dst, const char *h) { const unsigned char *hex = (const unsigned char *)h; unsigned i = 0; for (;;) { int high, low; while (*hex && isspace (*hex)) { hex++; } if (!*hex) { return 1; } high = ascii_to_hex_table[*hex++]; if (high < 0) { return 0; } while (*hex && isspace (*hex)) { hex++; } if (!*hex) { return 0; } low = ascii_to_hex_table[*hex++]; if (low < 0) { return 0; } dst[i++] = (high << 4) | low; } } int bcd_to_hex ( uint8_t * dst, const char *h, int h_length) { const unsigned char *hex = (const unsigned char *)h; unsigned i = 0; for (i = 0; i < h_length; i++) { int value = ascii_to_dec_table[*hex++]; if (value < 0) return -1; dst[i] = value; } return 0; }
#!/bin/bash # --gtest_filter=tests.test-exclude_tests.exclude_test docker run -it --rm --name=interview_tasks_external_merge_sort interview_tasks/external_merge_sort $@
package io.quarkus.micrometer.runtime.binder; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import org.jboss.logging.Logger; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.Timer; import io.vertx.ext.web.RoutingContext; public class HttpRequestMetric { static final Logger log = Logger.getLogger(HttpRequestMetric.class); public static final String HTTP_REQUEST_PATH = "HTTP_REQUEST_PATH"; public static final String HTTP_REQUEST_PATH_MATCHED = "HTTP_REQUEST_MATCHED_PATH"; public static final Pattern VERTX_ROUTE_PARAM = Pattern.compile("^:(.*)$"); /** Cache of vert.x resolved paths: /item/:id --> /item/{id} */ final static ConcurrentHashMap<String, String> templatePath = new ConcurrentHashMap<>(); volatile RoutingContext routingContext; /** Do not measure requests until/unless a uri path is set */ final boolean measure; /** URI path used as a tag value for non-error requests */ final String path; /** True IFF the path was revised by a matcher expression */ final boolean pathMatched; /** Store the sample used to measure the request */ Timer.Sample sample; /** * Store the tags associated with the request (change 1.6.0). * Default is empty, value assigned @ requestBegin */ Tags tags = Tags.empty(); /** * Extract the path out of the uri. Return null if the path should be * ignored. */ public HttpRequestMetric(Map<Pattern, String> matchPattern, List<Pattern> ignorePatterns, String uri) { if (uri == null) { this.measure = false; this.pathMatched = false; this.path = null; return; } boolean matched = false; String workingPath = extractPath(uri); String finalPath = workingPath; if ("/".equals(workingPath) || workingPath.isEmpty()) { finalPath = "/"; } else { // Label value consistency: result should begin with a '/' and should not end with one workingPath = HttpMetricsCommon.MULTIPLE_SLASH_PATTERN.matcher('/' + workingPath).replaceAll("/"); workingPath = HttpMetricsCommon.TRAILING_SLASH_PATTERN.matcher(workingPath).replaceAll(""); if (workingPath.isEmpty()) { finalPath = "/"; } else { finalPath = workingPath; // test path against configured patterns (whole path) for (Map.Entry<Pattern, String> mp : matchPattern.entrySet()) { if (mp.getKey().matcher(workingPath).matches()) { finalPath = mp.getValue(); matched = true; break; } } } } this.path = finalPath; this.pathMatched = matched; // Compare path against "ignore this path" patterns for (Pattern p : ignorePatterns) { if (p.matcher(this.path).matches()) { log.debugf("Path %s ignored; matches pattern %s", uri, p.pattern()); this.measure = false; return; } } this.measure = true; } public Timer.Sample getSample() { return sample; } public void setSample(Timer.Sample sample) { this.sample = sample; } public Tags getTags() { return tags; } public void setTags(Tags tags) { this.tags = tags; } public String getPath() { return path; } public boolean isMeasure() { return measure; } public boolean isPathMatched() { return pathMatched; } private static String extractPath(String uri) { if (uri.isEmpty()) { return uri; } int i; if (uri.charAt(0) == '/') { i = 0; } else { i = uri.indexOf("://"); if (i == -1) { i = 0; } else { i = uri.indexOf('/', i + 3); if (i == -1) { // contains no / return "/"; } } } int queryStart = uri.indexOf('?', i); if (queryStart == -1) { queryStart = uri.length(); } return uri.substring(i, queryStart); } public String getHttpRequestPath() { // Vertx binder configuration, see VertxMetricsTags if (pathMatched) { return path; } if (routingContext != null) { // JAX-RS or Servlet container filter String rcPath = routingContext.get(HTTP_REQUEST_PATH); if (rcPath != null) { return rcPath; } // vertx-web or reactive route String matchedPath = routingContext.currentRoute().getPath(); if (matchedPath != null) { if (matchedPath.contains(":")) { // Convert /item/:id to /item/{id} and save it for next time matchedPath = templatePath.computeIfAbsent(matchedPath, k -> { String segments[] = k.split("/"); for (int i = 0; i < segments.length; i++) { segments[i] = VERTX_ROUTE_PARAM.matcher(segments[i]).replaceAll("{$1}"); } return String.join("/", segments); }); } return matchedPath; } } return path; } public RoutingContext getRoutingContext() { return routingContext; } public void setRoutingContext(RoutingContext routingContext) { this.routingContext = routingContext; } @Override public String toString() { return "HttpRequestMetric{path=" + path + ",pathMatched=" + pathMatched + ",measure=" + measure + ",tags=" + tags + '}'; } }
#!/usr/bin/env bash set -eu set -o pipefail readonly PROGDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly BUILDPACKDIR="$(cd "${PROGDIR}/.." && pwd)" function main() { mkdir -p "${BUILDPACKDIR}/bin" pushd "${BUILDPACKDIR}/bin" > /dev/null || return printf "%s" "Building run..." GOOS=linux \ go build \ -ldflags="-s -w" \ -o "run" \ "${BUILDPACKDIR}" echo "Success!" for name in detect build; do printf "%s" "Linking ${name}..." ln -sf "run" "${name}" echo "Success!" done popd > /dev/null || return } main "${@:-}"
def maxSumSubArray(arr): max_so_far = 0 max_ending_here = 0 for i in range(0, len(arr)): max_ending_here = max_ending_here + arr[i] if (max_ending_here < 0): max_ending_here = 0 if (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far
/* For license: see LICENSE file at top-level */ #ifndef _MPP_SHMEM_H #define _MPP_SHMEM_H 1 #warning "<mpp/shmem.h> is a deprecated location since specification 1.1, use <shmem.h> instead" #include <shmem.h> #endif /* _MPP_SHMEM_H */
<gh_stars>0 package com.tracy.competition.domain.entity import scala.beans.BeanProperty /** * @author Tracy * @date 2021/2/9 1:12 */ class Advice extends Serializable { @BeanProperty var adviceId: String = _ @BeanProperty var user: User = _ @BeanProperty var adviceType: String = _ @BeanProperty var adviceState: Integer = _ @BeanProperty var adviceContent: String = _ @BeanProperty var adviceDate: java.lang.Long = 0L @BeanProperty var disposeTime: java.lang.Long = 0L override def toString: String = { "Advice{" + "adviceId='" + adviceId + '\'' + ", user=" + user + ", adviceType='" + adviceType + '\'' + ", adviceState=" + adviceState + ", adviceContent='" + adviceContent + '\'' + ", adviceDate=" + adviceDate + ", disposeTime=" + disposeTime + '}' } }
# Authors: # https://github.com/tristola # # Docker-compose related zsh aliases # Aliases ################################################################### alias dcup='docker-compose up' alias dcb='docker-compose build' alias dcrm='docker-compose rm' alias dcps='docker-compose ps' alias dcstop='docker-compose stop' alias dcrestart='docker-compose restart'
package net.henbit.raytracing.weekend; public abstract class Hittable { public abstract boolean hit(final Ray ray, double tMin, double tMax, HitRecord hitRecord); }
/** Copyright (c) 2016, <NAME>, <NAME>, <NAME>, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdio> #include <iostream> #include <string> #include <fstream> using namespace std; #include "log.h" #include "configuration.h" CConfiguration::CConfiguration() { setRootNode("Data"); } CConfiguration::CConfiguration(const char* rootNode) { setRootNode(rootNode); } TiXmlDocument &CConfiguration::getDocument() { return doc; } CConfiguration::~CConfiguration() { } void CConfiguration::clear() { doc.Clear(); } void CConfiguration::setRootNode(const char* node) { if (node != NULL) { sprintf(rootNode, "%s", node); } else { sprintf(rootNode, "%s", ""); } } bool CConfiguration::load(const char* cfgFile) { bool okay = doc.LoadFile(cfgFile); return okay; } bool CConfiguration::parse(const char* str) { doc.Parse(str); return true; } unsigned long CConfiguration::getUnsignedLong(const char* str, unsigned long def) { const char* value = getString(str, ""); if (strcmp(value, "") == 0) return def; else return strtoul(value, NULL, 10); } unsigned long CConfiguration::getAttributeUnsignedLong(TiXmlElement* node, const char* str, unsigned long def) { const char* value = getAttributeString(node,str, ""); if (strcmp(value, "") == 0) return def; else return strtoul(value, NULL, 10); } void CConfiguration::save(const char* cfgFile) { doc.SaveFile(cfgFile); } TiXmlElement* CConfiguration::findNode(const char* name) { TiXmlElement* iter = doc.FirstChildElement( rootNode ); return findNode(name, iter); } TiXmlElement* CConfiguration::findNode(const char* name, TiXmlElement* start) { TiXmlElement* iter = start; if (name == NULL || strcasecmp(name, "") == 0) return start; char *pch; char sBuffer[1024]; strcpy(sBuffer, name); pch = strtok(sBuffer, "."); while (iter && (pch != NULL)) { iter = iter->FirstChildElement(pch); pch = strtok(NULL, "."); } if ((pch == NULL) && (iter)) return iter; else return NULL; } void tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters) { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } void CConfiguration::findNodes(const char* name, std::vector<TiXmlElement*> &result) { TiXmlElement* iter = doc.FirstChildElement( rootNode ); findNodes(name, result, iter, 0); } void CConfiguration::findNodes(const char* name, std::vector<TiXmlElement*> &result, TiXmlElement* start, unsigned int level) { std::string str = name; std::vector<std::string> tokens; tokenize(str, tokens, "."); if (level + 1 > tokens.size()) return; if (start == NULL) return; TiXmlElement* iter = start->FirstChildElement(); while (iter != NULL) { if (strcasecmp(iter->Value(), tokens[level].c_str()) == 0) { if (level + 1 == tokens.size()) result.push_back(iter); else findNodes(name, result, iter, level + 1); } iter = iter->NextSiblingElement(); } } void CConfiguration::findNodes(const char* name, std::vector<TiXmlElement*> &result, TiXmlElement* start) { findNodes(name, result, start, 0); return; /* TiXmlElement* iter = start; std::string str = name; std::vector<std::string> tokens; tokenize(str, tokens, "."); int index = 0; while (iter != NULL && index < tokens.size()) { iter = iter->FirstChildElement(tokens[index].c_str()); index++; } if (iter == NULL) return; while (iter != NULL) { result.push_back(iter); iter = iter->NextSiblingElement(tokens[tokens.size()-1].c_str()); } return; */ } float CConfiguration::getAttributeFloat(TiXmlElement* node,const char* str, float def) { const char* value = getAttributeString(node,str, ""); if (strcmp(value, "") == 0) return def; else return atof(value); } double CConfiguration::getAttributeDouble(TiXmlElement* node, const char* str, double def) { const char* value = getAttributeString(node,str, ""); if (strcmp(value, "") == 0) return def; else return atof(value); } const char* CConfiguration::getAttributeString(TiXmlElement* node, const char* str, const char* def) { const char* tmpstr = node->Attribute(str); if (tmpstr == NULL) return def; else return tmpstr; } int CConfiguration::getAttributeInteger(TiXmlElement* node, const char* str, int def) { const char* value = getAttributeString(node,str, ""); if (strcmp(value, "") == 0) return def; else return atoi(value); } bool CConfiguration::getAttributeBoolean(TiXmlElement* node, const char* str, bool def) { const char* value = getAttributeString(node,str,""); if (strcmp(value, "") == 0) return def; else if (strcasecmp(value, "true") == 0) return true; else if (strcasecmp(value, "false") == 0) return false; else return def; } void CConfiguration::setAttributeFloat(TiXmlElement* node, const char* str, float value) { char buffer[255]; sprintf(buffer, "%f", value); node->SetAttribute(str, buffer); } void CConfiguration::setAttributeDouble(TiXmlElement* node, const char* str, double value) { char buffer[255]; sprintf(buffer, "%f", value); node->SetAttribute(str, buffer); } void CConfiguration::setAttributeString(TiXmlElement* node, const char* str, const char* value) { node->SetAttribute(str, value); } void CConfiguration::setAttributeInteger(TiXmlElement* node, const char* str, int value) { char buffer[255]; sprintf(buffer, "%d", value); node->SetAttribute(str, buffer); } void CConfiguration::setAttributeBoolean(TiXmlElement* node, const char* str, bool value) { if (value) node->SetAttribute(str, "true"); else node->SetAttribute(str, "false"); } void CConfiguration::setFloat(const char* str, float value) { char buffer[255]; sprintf(buffer, "%f", value); setString(str, buffer); } void CConfiguration::setDouble(const char* str, double value) { char buffer[255]; sprintf(buffer, "%f", value); setString(str, buffer); } void CConfiguration::setString(const char* str, const char* value) { TiXmlElement* result = findNode(str); if (result != NULL) { TiXmlText* text = result->FirstChild()->ToText(); text->SetValue(value); } } void CConfiguration::setInteger(const char* str, int value) { char buffer[255]; sprintf(buffer, "%d", value); setString(str, buffer); } void CConfiguration::setBoolean(const char* str, bool value) { if (value) setString(str, "true"); else setString(str, "false"); } std::string CConfiguration::getText(TiXmlElement* node) { if (node != NULL) return node->GetText(); return ""; } const char* CConfiguration::getString(const char* str, const char* def) { TiXmlElement* result = findNode(str); if (result != NULL && result->GetText() != NULL) return (const char*)result->GetText(); else return def; } float CConfiguration::getFloat(const char* str, float def) { return (float) getDouble(str, (double)def); } double CConfiguration::getDouble(const char* str, double def) { const char* value = getString(str, ""); if (strcmp(value, "") == 0) return def; else return atof(value); } int CConfiguration::getInteger(const char* str, int def) { const char* value = getString(str, ""); if (strcmp(value, "") == 0) return def; else return atoi(value); } bool CConfiguration::getBoolean(const char* str, bool def) { const char* value = getString(str, ""); if (strcmp(value, "") == 0) return def; else if (strcasecmp(value, "true") == 0) return true; else if (strcasecmp(value, "false") == 0) return false; else return def; } const char* CConfiguration::getString(const char* str, TiXmlElement* start, const char* def) { TiXmlElement* result = findNode(str, start); if (result != NULL && result->GetText() != NULL) return (const char*)result->GetText(); else return def; } float CConfiguration::getFloat(const char* str, TiXmlElement* start, float def) { return (float) getDouble(str, start, (double)def); } double CConfiguration::getDouble(const char* str, TiXmlElement* start, double def) { const char* value = getString(str, start, ""); if (strcmp(value, "") == 0) return def; else return atof(value); } int CConfiguration::getInteger(const char* str, TiXmlElement* start, int def) { const char* value = getString(str, start,""); if (strcmp(value, "") == 0) return def; else return atoi(value); } bool CConfiguration::getBoolean(const char* str, TiXmlElement* start, bool def) { const char* value = getString(str, start,""); if (strcmp(value, "") == 0) return def; else if (strcasecmp(value, "true") == 0) return true; else if (strcasecmp(value, "false") == 0) return false; else return def; } TiXmlElement* CConfiguration::getNode(const char* name) { return new TiXmlElement( name ); } bool CConfiguration::addNode(TiXmlElement* element) { if (element == NULL) return false; doc.LinkEndChild( element ); return true; } bool CConfiguration::addNode(TiXmlElement * element, TiXmlElement* parent) { if (element == NULL) return false; if (parent == NULL) return addNode(element); parent->LinkEndChild( element ); return element; } bool CConfiguration::insertNode(TiXmlElement* node, TiXmlElement* afterThis) { if (node == NULL) return false; if (afterThis == NULL) return false; doc.InsertAfterChild((TiXmlNode*)afterThis, *(TiXmlNode*)node); return true; } bool CConfiguration::insertNode(TiXmlElement* node, TiXmlElement* afterThis, TiXmlElement* parent) { if (node == NULL) return false; if (afterThis == NULL) return false; if (parent == NULL) return insertNode(node, afterThis); parent->InsertAfterChild(afterThis, *node); return true; } bool CConfiguration::removeNode(TiXmlElement* element, TiXmlElement* parent) { if (element == NULL) return false; if (parent == NULL) return removeNode(element); return parent->RemoveChild(element); } bool CConfiguration::removeNode(TiXmlElement* element) { if (element == NULL) return false; return doc.RemoveChild(element); } bool CConfiguration::removeAttribute(TiXmlElement* element, const char* name) { if (element == NULL) return false; element->RemoveAttribute(name); return true; }
<filename>okr/src/Table/Tables.tsx<gh_stars>0 import * as React from 'react'; import { connect } from 'redux-zero/react'; import { actions, selectorUsers, selectorRoles, selectorAbilities, selectorAll, selectorRolesAbilities, selectorUsersAbilities, selectorCalculatedAbilities, } from '../store'; import Chart from '../Chart'; import Table, { ScrollableTable } from './'; import EditableInput from '../EditableInput'; export const Users = connect(selectorUsers, actions)(({ users, addUser }: any) => ( <Table editable addable="User" storeKey="users" data={users} columns={[ { accessor: 'name', title: 'Кандидати' }, ]} /> )); export const Roles = connect(selectorRoles, actions)(({ roles, addRole }: any) => ( <Table editable addable="Role" storeKey="roles" data={roles} columns={[ { accessor: 'name', title: 'Ролі' }, ]} /> )); export const Abilities = connect(selectorAbilities, actions)(({ abilities, addAbility }: any) => ( <Table editable addable="Ability" storeKey="abilities" data={abilities} columns={[ { accessor: 'name', title: 'Навички' }, ]} /> )); export const CustomRoleAbility = connect(selectorRolesAbilities, actions)(({ abilities, roles, updateItem }: any) => <div className="table"> <strong className="table-title">Вимоги до навичок кандидатів</strong> <table> <thead> <tr> <th></th> {roles.map((item: any, index: number) => <td key={index}>{item.name}</td> )} </tr> </thead> <tbody> {abilities.map((item: any, index: number) => { return <tr key={index}> <td>{item.name}</td> {roles.map((role: any, i: number) => // <td key={i}>{role.abilityCoefs[index].toFixed(1)}</td> <td key={i}> <EditableInput storeRoot="roles" elementKey="abilityCoefs" elementIndex={i} index={index} /> </td> )} </tr> })} </tbody> </table> </div> ); export const CustomUserAbility = connect(selectorUsersAbilities, actions)(({ abilities, users, updateItem }: any) => <div className="table"> <strong className="table-title">Навички кандидатів</strong> <table> <thead> <tr> <th></th> {users.map((item: any, index: number) => <td key={index}>{item.name}</td> )} </tr> </thead> <tbody> {abilities.map((item: any, index: number) => { return <tr key={index}> <td>{item.name}</td> {users.map((role: any, i: number) => <td key={i}> <EditableInput storeRoot="users" elementKey="abilityCoefs" elementIndex={i} index={index} /> </td> )} </tr> })} </tbody> </table> </div> ); export const CustomUsersRolesAbilities = connect(selectorCalculatedAbilities, actions)(({ data, roles }: any) => ( <Table title="Результат" storeKey="abilities" data={data} columns={([] as any).concat( [{ accessor: 'item_0', title: ' ' }], roles.map((role: any, index: number) => ({ accessor: `item_${index + 1}`, title: role.name })) )} /> ));
<gh_stars>0 export interface Configuration { version: string; applicationId: string; runtimeApiUrl: string; storageApiUrl: string; docUrl: string; }
// 17135. <NAME> // 2020.02.22 // 시뮬레이션 #include<iostream> #include<algorithm> #include<vector> using namespace std; int map[16][16]; int n, m, d; int ch[3]; int ans; int endLine=-1; // 최초 상태에 적이 있는 가장 높은 곳 vector<pair<int, int>> shotPos; // 궁수가 쏜 좌표를 모아논곳 // 두점의 거리를 구하는 함수 int GetDistance(int x1, int y1, int x2, int y2) { int x = x1 - x2 > 0 ? x1 - x2 : x2 - x1; int y = y1 - y2 > 0 ? y1 - y2 : y2 - y1; return x + y; } void Simulate() { int cnt = 0; int sum = 0; // 맵 복사 int tmpMap[16][16]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { tmpMap[i][j] = map[i][j]; } } // 맨 위의 적이 다 내려올때까지 반복 while (cnt< endLine) { shotPos.clear(); // 궁수가 먼저 공격 for (int i = 0; i < 3; i++) { int shotX = 20; int shotY = 20; int tmpDist = d; for (int j = n - 1; j >= 0; j--) { for (int k = 0; k < m; k++) { // 거리가 작으면 무조건 선택 if (tmpMap[j][k] == 1 && GetDistance(j, k, n, ch[i]) < tmpDist) { tmpDist = GetDistance(j, k, n, ch[i]); shotX = j; shotY = k; } // 거리가 같을땐 가장 왼쪽 else if (tmpMap[j][k] == 1 && GetDistance(j, k, n, ch[i]) == tmpDist) { if (k < shotY) { shotX = j; shotY = k; } } } } // 궁수가 쏜 위치가 갱신되어있는 상태라면 추가 if (shotX != 20 && shotY != 20) { shotPos.push_back({ shotX,shotY }); } } // 궁수가 쏜 포지션들에 대해 반복 for (int i = 0; i < shotPos.size(); i++) { // 중복된 지점을 쐈을땐 1만 증가해야하므로 아래 조건 추가 if (tmpMap[shotPos[i].first][shotPos[i].second] == 1) { tmpMap[shotPos[i].first][shotPos[i].second] = 0; sum++; } } // 적 이동 for (int i = n-1; i >=1; i--) { for (int j = 0; j < m; j++) { tmpMap[i][j] = tmpMap[i - 1][j]; } } for (int i = 0; i < m; i++) { tmpMap[0][i] = 0; } cnt++; } // 최댓값이라면 갱신 ans = max(ans, sum); } // 궁수 3명을 놓을 위치 선택 void go(int cnt,int idx) { if (cnt == 3) { Simulate(); return; } for (int i = idx; i < m; i++) { ch[cnt] = i; go(cnt + 1, i + 1); } } int main() { cin >> n >> m >> d; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; if (map[i][j] == 1 && endLine==-1) { endLine = n-i; } } } go(0,0); cout << ans << endl; return 0; }
#!/bin/bash # This command only works in privileged container tmp_mount='/tmp/_balena' mkdir -p "$tmp_mount" if mount -t devtmpfs none "$tmp_mount" &> /dev/null; then PRIVILEGED=true umount "$tmp_mount" else PRIVILEGED=false fi rm -rf "$tmp_mount" function mount_dev() { tmp_dir='/tmp/tmpmount' mkdir -p "$tmp_dir" mount -t devtmpfs none "$tmp_dir" mkdir -p "$tmp_dir/shm" mount --move /dev/shm "$tmp_dir/shm" mkdir -p "$tmp_dir/mqueue" mount --move /dev/mqueue "$tmp_dir/mqueue" mkdir -p "$tmp_dir/pts" mount --move /dev/pts "$tmp_dir/pts" touch "$tmp_dir/console" mount --move /dev/console "$tmp_dir/console" umount /dev || true mount --move "$tmp_dir" /dev # Since the devpts is mounted with -o newinstance by Docker, we need to make # /dev/ptmx point to its ptmx. # ref: https://www.kernel.org/doc/Documentation/filesystems/devpts.txt ln -sf /dev/pts/ptmx /dev/ptmx mount -t debugfs nodev /sys/kernel/debug } function start_udev() { if [ "$UDEV" == "on" ]; then if $PRIVILEGED; then mount_dev if command -v udevd &>/dev/null; then unshare --net udevd --daemon &> /dev/null else unshare --net /lib/systemd/systemd-udevd --daemon &> /dev/null fi udevadm trigger &> /dev/null else echo "Unable to start udev, container must be run in privileged mode to start udev!" fi fi } function init() { # echo error message, when executable file doesn't exist. if [ -n "$1" ]; then if CMD=$(command -v "$1" 2>/dev/null); then shift exec "$CMD" "$@" else echo "Command not found: $1" exit 1 fi fi } UDEV=$(echo "$UDEV" | awk '{print tolower($0)}') case "$UDEV" in '1' | 'true') UDEV='on' ;; esac start_udev init "$@"
<filename>framework/src/main/java/me/insidezhou/southernquiet/logging/SouthernQuietLoggerFactory.java package me.insidezhou.southernquiet.logging; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public abstract class SouthernQuietLoggerFactory { private static final Map<String, SouthernQuietLogger> southernQuietLoggers = new HashMap<>(); private static SouthernQuietLogFormatter formatter = new SouthernQuietLogFormatter(); public static void setFormatter(SouthernQuietLogFormatter formatter) { SouthernQuietLoggerFactory.formatter = formatter; southernQuietLoggers.values().forEach(logger -> logger.setFormatter(formatter)); } public static synchronized SouthernQuietLogger getLogger(String name) { SouthernQuietLogger logger = southernQuietLoggers .computeIfAbsent(name, nm -> new SouthernQuietLogger(LoggerFactory.getLogger(nm), formatter)); southernQuietLoggers.putIfAbsent(name, logger); return logger; } public static SouthernQuietLogger getLogger(Class<?> cls) { return getLogger(cls.getName()); } }
package owltools.ontologyrelease; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.obolibrary.macro.MacroExpansionGCIVisitor; import org.obolibrary.macro.MacroExpansionVisitor; import org.obolibrary.obo2owl.OWLAPIOwl2Obo; import org.obolibrary.obo2owl.Obo2OWLConstants; import org.obolibrary.obo2owl.Obo2Owl; import org.obolibrary.obo2owl.OboInOwlCardinalityTools; import org.obolibrary.obo2owl.OboInOwlCardinalityTools.AnnotationCardinalityException; import org.obolibrary.obo2owl.Owl2Obo; import org.obolibrary.oboformat.model.OBODoc; import org.obolibrary.oboformat.parser.InvalidXrefMapException; import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag; import org.obolibrary.oboformat.parser.OBOFormatParserException; import org.obolibrary.oboformat.parser.XrefExpander; import org.obolibrary.oboformat.writer.OBOFormatWriter; import org.obolibrary.owl.LabelFunctionalSyntaxStorerFactory; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.AddAxiom; import org.semanticweb.owlapi.model.AddImport; import org.semanticweb.owlapi.model.AxiomType; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLDocumentFormat; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; import org.semanticweb.owlapi.model.OWLImportsDeclaration; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; import org.semanticweb.owlapi.model.RemoveAxiom; import org.semanticweb.owlapi.model.RemoveImport; import org.semanticweb.owlapi.model.SetOntologyID; import org.semanticweb.owlapi.model.parameters.Imports; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import org.semanticweb.owlapi.util.OWLEntityRenamer; import com.google.common.base.Optional; import owltools.InferenceBuilder; import owltools.InferenceBuilder.ConsistencyReport; import owltools.InferenceBuilder.PotentialRedundant; import owltools.JustifyAssertionsTool; import owltools.JustifyAssertionsTool.JustifyResult; import owltools.cli.Opts; import owltools.gaf.GafDocument; import owltools.gaf.owl.GAFOWLBridge; import owltools.gaf.parser.GafObjectsBuilder; import owltools.graph.AxiomAnnotationTools; import owltools.graph.OWLGraphWrapper; import owltools.io.CatalogXmlIRIMapper; import owltools.io.OWLPrettyPrinter; import owltools.io.ParserWrapper; import owltools.mooncat.Mooncat; import owltools.mooncat.PropertyViewOntologyBuilder; import owltools.mooncat.QuerySubsetGenerator; import owltools.ontologyrelease.OortConfiguration.MacroStrategy; import owltools.ontologyrelease.logging.ErrorReportFileHandler; import owltools.ontologyrelease.logging.ExplicitReportFileHandler; import owltools.ontologyrelease.logging.Log4jHandler; import owltools.ontologyrelease.logging.LogHandler; import owltools.ontologyrelease.logging.TraceReportFileHandler; import owltools.ontologyverification.OntologyCheck; import owltools.ontologyverification.OntologyCheckHandler; import owltools.ontologyverification.OntologyCheckHandler.CheckSummary; import owltools.util.OwlHelper; import uk.ac.manchester.cs.owl.owlapi.OWLImportsDeclarationImpl; import uk.ac.manchester.cs.owlapi.modularity.ModuleType; import uk.ac.manchester.cs.owlapi.modularity.SyntacticLocalityModuleExtractor; /** * This class is a command line utility which builds an ontology release. The * command line argument --h or --help provides usage documentation of this * utility. This tool called through bin/ontology-release-runner. * * @author <NAME> * */ public class OboOntologyReleaseRunner extends ReleaseRunnerFileTools { final OntologyCheckHandler ontologyChecks; ParserWrapper parser; Mooncat mooncat; OWLPrettyPrinter owlpp; OortConfiguration oortConfig; public OboOntologyReleaseRunner(OortConfiguration oortConfig, File base, List<LogHandler> handlers) throws IOException { super(base, oortConfig.isUseReleaseFolder(), oortConfig.isIgnoreLockFile(), addDefaultHandlers(handlers, oortConfig)); this.oortConfig = oortConfig; this.ontologyChecks = new OntologyCheckHandler(false, oortConfig.getOntologyChecks(), handlers); } static List<LogHandler> addDefaultHandlers(List<LogHandler> handlers, OortConfiguration config) { // setup default report files Set<String> suffixes = new HashSet<String>(); suffixes.add("-reasoner-report.txt"); handlers.add(ExplicitReportFileHandler.createSuffixFiltered(suffixes, config)); return handlers; } /** * Check whether the file is new. Throw an {@link IOException}, * if the file already exists and {@link OortConfiguration#isAllowFileOverWrite} * is not set to true. * * @param file * @return file return the same file to allow chaining with other operations * @throws IOException */ @Override protected File checkNew(File file) throws IOException { if (!oortConfig.isAllowFileOverWrite() && file.exists() && file.isFile()) { boolean allow = allowFileOverwrite(file); if (!allow) { throw new IOException("Trying to overwrite an existing file: " + file.getAbsolutePath()); } } return file; } /** * Hook method to handle an unexpected file overwrite request. * Returns true, if the overwrite is allowed. * * @param file * @return boolean * @throws IOException */ protected boolean allowFileOverwrite(File file) throws IOException { /* * For the command line version this is always false, as no dialog * with the user is possible. If the user wants to override file * the command-line flag '--allowOverwrite' has to be used. */ return false; } public static void main(String[] args) { // default log handler final Log4jHandler log4jHandler = new Log4jHandler(Logger.getLogger(OboOntologyReleaseRunner.class), true); int exitCode = 0; OboOntologyReleaseRunner oorr = null; try { OortConfiguration oortConfig = new OortConfiguration(); boolean isHelp = parseOortCommandLineOptions(args, oortConfig); if (isHelp) { System.exit(exitCode); } final List<LogHandler> handlers = new ArrayList<LogHandler>(); handlers.add(log4jHandler); final File base = oortConfig.getBase().getCanonicalFile(); log4jHandler.logInfo("Base directory path " + base.getAbsolutePath()); // setup additional log handlers if (oortConfig.getErrorReportFile() != null) { handlers.add(new ErrorReportFileHandler(base, oortConfig.getErrorReportFile())); } if (oortConfig.getTraceReportFile() != null) { handlers.add(new TraceReportFileHandler(base, oortConfig.getTraceReportFile())); } oorr = new OboOntologyReleaseRunner(oortConfig, base, handlers); boolean success = oorr.createRelease(); String message; if (success) { message = "Finished release manager process"; } else { message = "Finished release manager process, but no release was created."; } log4jHandler.logInfo(message); log4jHandler.logInfo("Done!"); } catch (OboOntologyReleaseRunnerCheckException e) { StringBuilder sb = new StringBuilder(); sb.append("Stopped Release process. Hint: "); sb.append(e.getHint()); List<String> reasons = e.getReasons(); if (reasons != null) { sb.append(" Reasons: "); for (String reason : reasons) { sb.append('\n').append(reason); } } log4jHandler.logError(sb.toString(), e); exitCode = -1; } catch (Throwable e) { log4jHandler.logError("Stopped Release process. Reason: "+e.getMessage(), e); exitCode = -1; } finally { if (oorr != null) { log4jHandler.logInfo("deleting lock file"); oorr.deleteLockFile(); } } System.exit(exitCode); } /** * Parse the CLI parameters into the configuration object. * * @param args * @param oortConfig * @return true, if the parameters contain the help flag. * @throws IOException */ static boolean parseOortCommandLineOptions(String[] args, OortConfiguration oortConfig) throws IOException { Opts opts = new Opts(args); while (opts.hasArgs()) { if (opts.nextEq("--h|--help|-h")) { // Do not return after finding the help flag. // Go through all checks first, to print the options on system out. help(); opts.setHelpMode(true); } if (opts.nextEq("--outdir|-outdir")) { oortConfig.setBase(new File(opts.nextOpt())); } else if (opts.nextEq("--reasoner|-reasoner")) { // TODO - deprecate "-reasoner" oortConfig.setReasonerName(opts.nextOpt()); } else if (opts.nextEq("--no-reasoner")) { oortConfig.setReasonerName(null); } else if (opts.nextEq("--skip-format")) { oortConfig.addToSkipFormatSet(opts.nextOpt()); } else if (opts.nextEq("--prefix")) { oortConfig.addSourceOntologyPrefix(opts.nextOpt()); } else if (opts.nextEq("--enforceEL")) { // If this option is active, the ontology is // restricted to EL before reasoning! oortConfig.setEnforceEL(true); } else if (opts.nextEq("--makeEL")) { // If this option is active, an EL restricted ontology // is written after reasoning. oortConfig.setWriteELOntology(true); } else if (opts.nextEq("--no-subsets")) { oortConfig.setWriteSubsets(false); } else if (opts.nextEq("--force")) { oortConfig.setForceRelease(true); } else if (opts.nextEq("--ignoreLock")) { oortConfig.setIgnoreLockFile(true); } else if (opts.nextEq("--asserted")) { oortConfig.setAsserted(true); } else if (opts.nextEq("--simple")) { oortConfig.setSimple(true); } else if (opts.nextEq("--simple-filtered")) { oortConfig.setSimple(true); List<String> properties = new ArrayList<String>(); oortConfig.setFilterSimpleProperties(properties); while (opts.hasOpts() == false) { properties.add(opts.nextOpt()); } } else if (opts.nextEq("--relaxed")) { oortConfig.setRelaxed(true); } else if (opts.nextEq("--expand-xrefs")) { oortConfig.setExpandXrefs(true); } else if (opts.nextEq("--re-mireot")) { oortConfig.setRecreateMireot(true); } else if (opts.nextEq("--repair-cardinality")) { oortConfig.setRepairAnnotationCardinality(true); } else if (opts.nextEq("--justify")) { oortConfig.setJustifyAssertedSubclasses(true); } else if (opts.nextEq("--justify-from")) { oortConfig.setJustifyAssertedSubclasses(true); oortConfig.setJustifyAssertedSubclassesFrom(opts.nextOpt()); } else if (opts.nextEq("--useIsInferred")) { oortConfig.setUseIsInferred(true); } else if (opts.nextEq("--remove-trailing-qualifiers")) { oortConfig.setRemoveTrailingQualifiers(true); } else if (opts.nextEq("--allow-equivalent-pairs")) { oortConfig.setAllowEquivalentNamedClassPairs(true); } else if (opts.nextEq("--expand-macros")) { oortConfig.setExpandMacros(true); oortConfig.setMacroStrategy(MacroStrategy.GCI); } else if (opts.nextEq("--expand-macros-inplace")) { oortConfig.setExpandMacros(true); oortConfig.setMacroStrategy(MacroStrategy.INPLACE); } else if (opts.nextEq("--allow-overwrite")) { oortConfig.setAllowFileOverWrite(true); } else if (opts.nextEq("--remove-dangling-before-reasoning")) { oortConfig.setRemoveDanglingBeforeReasoning(true); } else if (opts.nextEq("--add-support-from-imports")) { oortConfig.setAddSupportFromImports(true); } else if (opts.nextEq("--add-imports-from-supports")) { oortConfig.setAddImportsFromSupports(true); } else if (opts.nextEq("--translate-disjoints-to-equivalents")) { oortConfig.setTranslateDisjointsToEquivalents(true); } else if (opts.nextEq("--skip-ontology-checks")) { oortConfig.setExecuteOntologyChecks(false); } else if (opts.nextEq("--skip-release-folder")) { oortConfig.setUseReleaseFolder(false); } else if (opts.nextEq("--bridge-ontology|-b")) { oortConfig.addBridgeOntology(opts.nextOpt()); } else if (opts.nextEq("--config-file")) { File file = new File(opts.nextOpt()); OortConfiguration.loadConfig(file , oortConfig); } else if (opts.nextEq("--rename-entity")) { oortConfig.addRewriteIRIMap(IRI.create(opts.nextOpt()), IRI.create(opts.nextOpt())); } else if (opts.nextEq("--catalog-xml")) { oortConfig.setCatalogXML(opts.nextOpt()); } else if (opts.nextEq("--check-for-gaf")) { oortConfig.setGafToOwl(true); } else if (opts.nextEq("--query-ontology")) { oortConfig.setUseQueryOntology(true); oortConfig.setQueryOntology(opts.nextOpt()); } else if (opts.nextEq("--query-ontology-iri")) { oortConfig.setQueryOntologyReferenceIsIRI(true); oortConfig.setQueryOntologyReference(opts.nextOpt()); } else if (opts.nextEq("--query-ontology-label")) { oortConfig.setQueryOntologyReferenceIsIRI(false); oortConfig.setQueryOntologyReference(opts.nextOpt()); } else if (opts.nextEq("--query-ontology-remove-query")) { oortConfig.setQueryOntologyReferenceIsIRI(true); } else if (opts.nextEq("--write-label-owl")) { oortConfig.setWriteLabelOWL(true); } else if (opts.nextEq("--threads")) { oortConfig.setThreads(Integer.parseInt(opts.nextOpt())); } else if (opts.nextEq("--run-obo-basic-dag-check")) { oortConfig.setRunOboBasicDagCheck(true); } else if (opts.nextEq("--skip-remove-redundant")) { oortConfig.setRemoveRedunantAxioms(false); } else if (opts.nextEq("--ignore-potential-redundant")) { oortConfig.setCheckPotentialRedundant(false); } else if (opts.nextEq("--version-report-files")) { oortConfig.setVersionReportFiles(true); } else if (opts.nextEq("--skip-error-modules")) { oortConfig.setCreateErrorModules(false); } else if (opts.nextEq("--error-report")) { String errorReportFile = "error-report.txt"; if (opts.hasArgs() && !opts.hasOpts()) { errorReportFile = opts.nextOpt(); } oortConfig.setErrorReportFile(errorReportFile); } else if (opts.nextEq("--trace-report")) { String traceReportFile = "trace-report.txt"; if (opts.hasArgs() && !opts.hasOpts()) { traceReportFile = opts.nextOpt(); } oortConfig.setTraceReportFile(traceReportFile); } else if (opts.nextEq("--ignore-selected-equivalent-pairs")) { Set<String> ignoreSelectedEquivalentPairSet = new HashSet<String>(opts.nextList()); oortConfig.setIgnoreSelectedEquivalentPairSet(ignoreSelectedEquivalentPairSet); } else if (opts.nextEq("--ontology-checks")) { Set<String> addFlags = new HashSet<String>(); Set<String> removeFlags = new HashSet<String>(); boolean clear = false; while (opts.hasOpts()) { if (opts.nextEq("-a")) { // add addFlags.add(opts.nextOpt()); } else if (opts.nextEq("-r")) { // remove removeFlags.add(opts.nextOpt()); } else if (opts.nextEq("-c|--clear")) { clear = true; } else break; } List<OntologyCheck> checks = oortConfig.getOntologyChecks(); if (checks == null) { checks = new ArrayList<OntologyCheck>(); } if (clear) { checks.clear(); } oortConfig.setOntologyChecks(checks); for(String shortName : addFlags) { OntologyCheck check = OortConfiguration.getOntologyCheck(shortName); if (check != null) { checks.add(check); } } for(String shortName : removeFlags) { OntologyCheck check = OortConfiguration.getOntologyCheck(shortName); if (check != null) { checks.remove(check); } } } else if (opts.hasArgs()) { oortConfig.addPath(opts.nextOpt()); } else { if (opts.isHelpMode()) { return true; // has help } } } return false; // no help } /** * Create a release, use the {@link OortConfiguration} instance specified the in constructor. * * @return true if the release was successful * @throws IOException * @throws OWLOntologyCreationException * @throws FileNotFoundException * @throws OWLOntologyStorageException * @throws OboOntologyReleaseRunnerCheckException * @throws AnnotationCardinalityException * @throws OBOFormatParserException */ public boolean createRelease() throws IOException, OWLOntologyCreationException, FileNotFoundException, OWLOntologyStorageException, OboOntologyReleaseRunnerCheckException, AnnotationCardinalityException, OBOFormatParserException { return createRelease(oortConfig.getPaths()); } private boolean createRelease(Vector<String> allPaths) throws IOException, OWLOntologyCreationException, FileNotFoundException, OWLOntologyStorageException, OboOntologyReleaseRunnerCheckException, AnnotationCardinalityException, OBOFormatParserException { if (allPaths.isEmpty()) { logError("No files to load found, please specify at least one ontology file."); return false; } List<String> paths; List<String> gafs = null; if (oortConfig.isGafToOwl()) { gafs = new ArrayList<String>(); paths = new ArrayList<String>(); for(String path : allPaths) { // TODO - be a bit more sophisticated about this if (path.endsWith(".obo") || path.endsWith(".owl") || path.endsWith(".ofn") || path.endsWith(".owx") || path.endsWith(".omn")) { paths.add(path); } else { gafs.add(path); } } if (gafs.isEmpty()) { logError("No gaf files found, please specify at least one gaf file or disable 'check-for-gaf' mode."); return false; } } else { if (oortConfig.isUseQueryOntology()) { paths = new ArrayList<String>(allPaths.size() + 1); paths.add(oortConfig.getQueryOntology()); paths.addAll(allPaths); } else { paths = allPaths; } } logInfo("Using the following ontologies: " + paths); if (gafs != null) { logInfo("Using the following gaf files: " +gafs); } parser = new ParserWrapper(); String catalogXML = oortConfig.getCatalogXML(); if (catalogXML != null) { parser.addIRIMapper(new CatalogXmlIRIMapper(catalogXML)); } OWLGraphWrapper graph = parser.parseToOWLGraph(paths.get(0)); if (oortConfig.isAddSupportFromImports()) { // add imports to support graph.addSupportOntologiesFromImportsClosure(true); OWLOntology sourceOntology = graph.getSourceOntology(); Set<OWLImportsDeclaration> importsDeclarations = sourceOntology.getImportsDeclarations(); OWLOntologyManager manager = sourceOntology.getOWLOntologyManager(); for (OWLImportsDeclaration owlImportsDeclaration : importsDeclarations) { manager.applyChange(new RemoveImport(sourceOntology, owlImportsDeclaration)); } } // rewrite IRIs // used if two ontologies do not use the same IRI for the same concept if (oortConfig.getRewriteIRIMap().size() > 0) { OWLEntityRenamer oer = new OWLEntityRenamer(graph.getManager(), graph.getAllOntologies()); List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange> (); for (IRI fromIRI : oortConfig.getRewriteIRIMap().keySet()) { changes.addAll( oer.changeIRI(fromIRI, oortConfig.getRewriteIRIMap().get(fromIRI)) ); } logInfo("IRI rewrites: "+changes.size()); graph.getManager().applyChanges(changes); } mooncat = new Mooncat(graph); owlpp = new OWLPrettyPrinter(mooncat.getGraph()); // A bridge ontology contains axioms connecting classes from different ontologies, // but no class declarations or class metadata. // Bridge ontologies are commonly used (e.g. GO, phenotype ontologies) to store // logical definitions such that the core ontology includes no dangling references. // Here we merge in the bridge ontologies into the core ontology for (String f : oortConfig.getBridgeOntologies()) { OWLOntology ont = parser.parse(f); logInfo("Merging "+ont+" into main ontology [loaded from "+f+"]"); mooncat.getGraph().mergeOntology(ont); } for (int k = 1; k < paths.size(); k++) { String p = paths.get(k); OWLOntology ont = parser.parse(p); logInfo("Loaded "+ont+" from "+p); if (oortConfig.isAutoDetectBridgingOntology() && isBridgingOntology(ont)) mooncat.mergeIntoReferenceOntology(ont); else mooncat.addReferencedOntology(ont); } if (oortConfig.isAddImportsFromSupports()) { logInfo("Adding imports from supports"); graph.addImportsFromSupportOntologies(); } // load gafs if (oortConfig.isGafToOwl()) { // prepare an empty ontology for the GAFs to be loaded later // use the first gaf file name as ontology id String gafResource = gafs.get(0); IRI gafIRI; if (gafResource.indexOf(':') > 0) { // if it contains a colon, assume its an IRI gafIRI = IRI.create(gafResource); } else { // assume it is a file, use the filename as id gafIRI = IRI.create(new File(gafResource).getName()); } // create ontology with gaf IRI OWLOntology gafOntology = graph.getManager().createOntology(gafIRI); // create the GAF bridge GAFOWLBridge gafBridge = new GAFOWLBridge(graph, gafOntology); // Do not generate individuals, use a prototype instead // This is required for efficient reasoning gafBridge.setGenerateIndividuals(false); // load gaf files for(String gaf : gafs) { try { GafObjectsBuilder builder = new GafObjectsBuilder(); GafDocument gafdoc = builder.buildDocument(gaf); gafBridge.translate(gafdoc); } catch (URISyntaxException e) { throw new IOException(e); } } // update the owl graph wrapper, mooncat, and pretty printer with the new gaf data OWLGraphWrapper gafGraph = new OWLGraphWrapper(gafOntology); for(OWLOntology ontology : graph.getAllOntologies()) { gafGraph.addSupportOntology(ontology); } mooncat = new Mooncat(gafGraph); owlpp = new OWLPrettyPrinter(gafGraph); } if (oortConfig.getSourceOntologyPrefixes() != null) { logInfo("The following prefixes will be used to determine "+ "which classes belong in source:"+oortConfig.getSourceOntologyPrefixes()); mooncat.setSourceOntologyPrefixes(oortConfig.getSourceOntologyPrefixes()); } if (oortConfig.isRepairAnnotationCardinality()) { logInfo("Checking and repair annotation cardinality constrains"); OboInOwlCardinalityTools.checkAnnotationCardinality(mooncat.getOntology()); } if (oortConfig.isExecuteOntologyChecks()) { CheckSummary summary = ontologyChecks.afterLoading(mooncat.getGraph()); if (summary.success == false) { if (!oortConfig.isForceRelease()) { throw new OboOntologyReleaseRunnerCheckException(summary.message); } else { logWarn("Force Release: ignore "+summary.errorCount+" errors from ontology check, error message: "+summary.message); } } } final String ontologyId = handleOntologyId(); final String version = handleVersion(ontologyId); if (oortConfig.isWriteLabelOWL()) { mooncat.getManager().getOntologyStorers().add(new LabelFunctionalSyntaxStorerFactory()); } // ---------------------------------------- // Macro expansion // ---------------------------------------- // sets gciOntology, if there are macros and the strategy is GCI OWLOntology gciOntology = null; if (oortConfig.isExpandMacros()) { logInfo("expanding macros"); if (oortConfig.getMacroStrategy() == MacroStrategy.GCI) { MacroExpansionGCIVisitor gciVisitor = new MacroExpansionGCIVisitor(mooncat.getOntology(), mooncat.getManager(), false); gciOntology = gciVisitor.createGCIOntology(); logInfo("GCI Ontology has "+gciOntology.getAxiomCount()+" axioms"); gciVisitor.dispose(); } else { OWLOntology ont = mooncat.getOntology(); MacroExpansionVisitor mev = new MacroExpansionVisitor(ont); ont = mev.expandAll(); mooncat.setOntology(ont); mev.dispose(); logInfo("Expanded in place; Ontology has "+ont.getAxiomCount()+" axioms"); } } // ---------------------------------------- // Generate bridge ontologies from xref expansion // ---------------------------------------- if (oortConfig.isExpandXrefs()) { logInfo("Creating Bridge Ontologies by expanding Xrefs"); // Note that this introduces a dependency on the oboformat-specific portion // of the oboformat code. Ideally we would like to make everything run // independent of obo XrefExpander xe; try { // TODO - make this configurable. // currently uses the name "MAIN-bridge-to-EXT" for all final OBODoc obodoc = parser.getOBOdoc(); if (obodoc == null) { final String message = "Creating Bridge Ontologies is only applicable for OBO ontologies as source."; if (!oortConfig.isForceRelease()) { throw new OboOntologyReleaseRunnerCheckException(message); } else { logWarn("Force Release: ignore "+message); } } else { xe = new XrefExpander(obodoc, ontologyId+"-bridge-to"); xe.expandXrefs(); // generate imported obo docs from xrefs for (OBODoc tdoc : parser.getOBOdoc().getImportedOBODocs()) { String tOntId = tdoc.getHeaderFrame().getClause(OboFormatTag.TAG_ONTOLOGY).getValue().toString(); logInfo("Generating bridge ontology:"+tOntId); Obo2Owl obo2owl = new Obo2Owl(); OWLOntology tOnt = obo2owl.convert(tdoc); saveOntologyInAllFormats(ontologyId, tOntId, version, tOnt, null, true); } } } catch (InvalidXrefMapException e) { logInfo("Problem during Xref expansion: "+e.getMessage()); } // TODO - option to generate imports } if (oortConfig.isTranslateDisjointsToEquivalents()) { mooncat.translateDisjointsToEquivalents(); } // ---------------------------------------- // Asserted (non-classified) // ---------------------------------------- if (oortConfig.isAsserted()) { logInfo("Creating Asserted Ontology (copy of original)"); saveInAllFormats(ontologyId, "non-classified", version, gciOntology); logInfo("Asserted Ontology Creation Completed"); } // ---------------------------------------- // Create query from named query (non-classified) // ---------------------------------------- if (oortConfig.isUseQueryOntology()) { logInfo("Use named query to build ontology."); String queryReference = oortConfig.getQueryOntologyReference(); if (queryReference == null || queryReference.isEmpty()) { logError("Could not find a named query reference. This is required for the QueryOntology feature."); return false; } OWLClass namedQuery; if (oortConfig.isQueryOntologyReferenceIsIRI()) { IRI iri = IRI.create(queryReference); namedQuery = mooncat.getGraph().getOWLClass(iri); if (namedQuery == null) { logError("Could not find an OWLClass with the IRI: "+iri); return false; } } else { OWLObject owlObject = mooncat.getGraph().getOWLObjectByLabel(queryReference); if (owlObject != null && owlObject instanceof OWLClass) { namedQuery = (OWLClass) owlObject; } else { logError("Could not find an OWLClass with the label: "+queryReference); return false; } } final String reasonerName = oortConfig.getReasonerName(); if (reasonerName == null) { logError("While using a query ontology a reasoner is required."); return false; } final OWLReasonerFactory reasonerFactory = InferenceBuilder.getFactory(reasonerName); QuerySubsetGenerator subsetGenerator = new QuerySubsetGenerator(); Set<OWLOntology> toMerge = mooncat.getGraph().getSupportOntologySet(); subsetGenerator.createSubOntologyFromDLQuery(namedQuery, mooncat.getGraph(), mooncat.getGraph(), reasonerFactory, toMerge); if (oortConfig.isRemoveQueryOntologyReference()) { logInfo("Removing query term from ontology: "+namedQuery); OWLOntology owlOntology = mooncat.getGraph().getSourceOntology(); Set<OWLAxiom> axioms = new HashSet<OWLAxiom>(); axioms.addAll(owlOntology.getAxioms(namedQuery, Imports.EXCLUDED)); axioms.addAll(owlOntology.getDeclarationAxioms(namedQuery)); OWLOntologyManager manager = owlOntology.getOWLOntologyManager(); manager.removeAxioms(owlOntology, axioms); logInfo("Finished removing query term, removed axiom count: "+axioms.size()); } logInfo("Finished building ontology from query."); } // ---------------------------------------- // Merge in subsets of external ontologies // ---------------------------------------- // only do this if --re-mireot is set // // note this is done *prior* to reasoning - part of the rationale // is that by bringing in a smaller subset we make the reasoning // more tractable (though this is less relevant for Elk) // // This is a mandatory step for checking GAFs, otherwise // the reasoner does not use the loaded support ontologies. if ((oortConfig.isRecreateMireot() || oortConfig.isGafToOwl()) && !oortConfig.isUseQueryOntology() && graph.getSupportOntologySet().size() > 0) { logInfo("Number of dangling classes in source: "+mooncat.getDanglingClasses().size()); logInfo("Merging Ontologies (only has effect if multiple ontologies are specified)"); mooncat.mergeOntologies(); if (oortConfig.isRepairAnnotationCardinality()) { logInfo("Checking and repair annotation cardinality constrains"); OboInOwlCardinalityTools.checkAnnotationCardinality(mooncat.getOntology()); } saveInAllFormats(ontologyId, "merged", version, gciOntology); logInfo("Number of dangling classes in source (post-merge): "+mooncat.getDanglingClasses().size()); // TODO: option to save as imports } else if (oortConfig.isRepairAnnotationCardinality()) { logInfo("Checking and repair annotation cardinality constrains"); OboInOwlCardinalityTools.checkAnnotationCardinality(mooncat.getOntology()); } if (oortConfig.isExecuteOntologyChecks()) { CheckSummary summary = ontologyChecks.afterMireot(mooncat.getGraph()); if (summary.success == false) { if (!oortConfig.isForceRelease()) { throw new OboOntologyReleaseRunnerCheckException(summary.message); } else { logWarn("Force Release: ignore "+summary.errorCount+" errors from ontology check, error message: "+summary.message); } } } if (oortConfig.isRemoveDanglingBeforeReasoning()) { mooncat.removeDanglingAxioms(); } // ---------------------------------------- // Main (asserted plus inference of non-redundant links) // ---------------------------------------- // this is the same as ASSERTED, with certain axioms ADDED based on reasoner results // this is always on by default // at some point we may wish to make this optional, // but a user would rarely choose to omit the main ontology if (true) { logInfo("Creating main ontology"); if (oortConfig.getReasonerName() != null) { // cache all lines to go into reasoner report List<String> reasonerReportLines = new ArrayList<String>(); InferenceBuilder infBuilder = null; try { infBuilder = handleInferences(ontologyId, version, reasonerReportLines, gciOntology); // TEST FOR EQUIVALENT NAMED CLASS PAIRS if (true) { final List<OWLEquivalentClassesAxiom> equivalentNamedClassPairs = infBuilder.getEquivalentNamedClassPairs(); if (equivalentNamedClassPairs.size() > 0) { List<OWLEquivalentClassesAxiom> filteredAxioms = equivalentNamedClassPairs; Set<String> ignoreSelectedEquivalentPairSet = oortConfig.getIgnoreSelectedEquivalentPairSet(); if (ignoreSelectedEquivalentPairSet != null && !ignoreSelectedEquivalentPairSet.isEmpty()) { filteredAxioms = filterEquivalentNamedClassPairs(equivalentNamedClassPairs, ignoreSelectedEquivalentPairSet, graph); } if (filteredAxioms.size() > 0) { logWarn("Found equivalencies between named classes"); List<String> reasons = new ArrayList<String>(); for (OWLEquivalentClassesAxiom eca : filteredAxioms) { String axiomString = owlpp.render(eca); reasons.add(axiomString); String message = "EQUIVALENT_CLASS_PAIR\t"+axiomString; reasonerReportLines.add(message); } if (oortConfig.isCreateErrorModules()) { createEquivModule(ontologyId, filteredAxioms); } if (oortConfig.isAllowEquivalentNamedClassPairs() == false) { // TODO: proper exception mechanism - delay until end? if (!oortConfig.isForceRelease()) { saveReasonerReport(ontologyId, reasonerReportLines); throw new OboOntologyReleaseRunnerCheckException("Found equivalencies between named classes.", reasons, "Use ForceRelease option to ignore this warning."); } } } else { cleanupEquivModule(ontologyId); } } else { cleanupEquivModule(ontologyId); } } // REDUNDANT AXIOMS if (oortConfig.isRemoveRedunantAxioms()) { logInfo("Finding redundant axioms"); for (OWLAxiom ax : infBuilder.getRedundantAxioms()) { // TODO - in future do not remove axioms that are annotated logInfo("Removing redundant axiom:"+ax+" // " + owlpp.render(ax)); reasonerReportLines.add("REDUNDANT\t"+owlpp.render(ax)); // note that the actual axiom in the ontology may be different, but with the same // structure; i.e. with annotations for (OWLAxiom axInOnt : mooncat.getOntology().getAxiomsIgnoreAnnotations(ax)) { logInfo(" Actual axiom: "+axInOnt); mooncat.getManager().applyChange(new RemoveAxiom(mooncat.getOntology(), axInOnt)); } } logInfo("Redundant axioms removed"); } else { logInfo("Skipping removal of redundant axioms"); } if (oortConfig.isCheckPotentialRedundant()) { logInfo("Check for potential redundant subClass axioms"); List<PotentialRedundant> potentialRedundants = infBuilder.checkPotentialRedundantSubClassAxioms(); if (potentialRedundants != null && !potentialRedundants.isEmpty()) { logWarn("Found potential redundant subClass axioms"); List<String> reasons = new ArrayList<String>(); if (oortConfig.isCreateErrorModules()) { createPotentialRedundantModule(ontologyId, potentialRedundants); } // before printing group by relationship and sort by class A Collections.sort(potentialRedundants, PotentialRedundant.PRINT_COMPARATOR); for (PotentialRedundant redundant : potentialRedundants) { StringBuilder sb = new StringBuilder(); sb.append(owlpp.render(redundant.getClassA())).append(" "); sb.append(owlpp.render(redundant.getProperty())).append(" "); sb.append(owlpp.render(redundant.getClassB())); sb.append(" is also a simple SubClassOf."); final String reason = sb.toString(); reasons.add(reason); String message = "POTENTIAL_REDUNDANT\t"+reason; reasonerReportLines.add(message); } } else { cleanupPotentialRedundantModule(ontologyId); } } saveReasonerReport(ontologyId, reasonerReportLines); } finally { if (infBuilder != null) { infBuilder.dispose(); } } } if (oortConfig.isExecuteOntologyChecks()) { CheckSummary summary = ontologyChecks.afterReasoning(mooncat.getGraph()); if (summary.success == false) { if (!oortConfig.isForceRelease()) { throw new OboOntologyReleaseRunnerCheckException(summary.message); } else { logWarn("Force Release: ignore "+summary.errorCount+" errors from ontology check, error message: "+summary.message); } } } if (oortConfig.isRemoveTrailingQualifiers()) { // remove all axiom annotations which translate to trailing qualifiers AxiomAnnotationTools.reduceAxiomAnnotationsToOboBasic(mooncat.getOntology()); } saveInAllFormats(ontologyId, null, version, gciOntology); } // --end of building main ontology // TODO for (PropertyView pv : oortConfig.getPropertyViews()) { PropertyViewOntologyBuilder pvob = new PropertyViewOntologyBuilder(mooncat.getGraph().getDataFactory(), mooncat.getManager(), mooncat.getOntology(), mooncat.getOntology(), pv.property); } // ---------------------------------------- // SUBSETS // ---------------------------------------- // including: named subsets, profile subsets (e.g. EL), simple subsets if (oortConfig.isWriteSubsets()) { // named subsets logInfo("writing named subsets"); Set<String> subsets = mooncat.getGraph().getAllUsedSubsets(); for (String subset : subsets) { Set<OWLClass> objs = mooncat.getGraph().getOWLClassesInSubset(subset); logInfo("subset:"+subset+" #classes:"+objs.size()); String fn = "subsets/"+subset; IRI iri = IRI.create(Obo2OWLConstants.DEFAULT_IRI_PREFIX+ontologyId+"/"+fn+".owl"); OWLOntology subOnt = mooncat.makeMinimalSubsetOntology(objs, iri); logInfo("subOnt:"+subOnt+" #axioms:"+subOnt.getAxiomCount()); saveOntologyInAllFormats(ontologyId, fn, version, subOnt, gciOntology, true); } } // write EL version if(oortConfig.isWriteELOntology()) { logInfo("Creating EL ontology"); OWLGraphWrapper elGraph = InferenceBuilder.enforceEL(mooncat.getGraph()); saveInAllFormats(ontologyId, "el", version, elGraph.getSourceOntology(), gciOntology); logInfo("Finished Creating EL ontology"); } // ---------------------------------------- // Relaxed (assert inferred subclasses and remove equivalence axioms) // ---------------------------------------- if (oortConfig.isRelaxed()) { logInfo("Creating relaxed ontology"); Set<OWLEquivalentClassesAxiom> rmAxs = mooncat.getOntology().getAxioms(AxiomType.EQUIVALENT_CLASSES); logInfo("Removing "+rmAxs.size()+" EquivalentClasses axioms from simple"); mooncat.getManager().removeAxioms(mooncat.getOntology(), rmAxs); saveInAllFormats(ontologyId, "relaxed", version, gciOntology); logInfo("Creating relaxed ontology completed"); } // ---------------------------------------- // Simple/Basic (no MIREOTs, no imports) // ---------------------------------------- // this is the same as MAIN, with certain axiom REMOVED if (oortConfig.isSimple()) { handleSimpleOntology(graph, ontologyId, version, gciOntology); } // ---------------------------------------- // End of export file creation // ---------------------------------------- boolean success = commit(version); return success; } // ---------------------------------------- // Methods for creating and deleting module files. // The modules are only create, if the appropriate flag is set and one of the following conditions is meet: // 1) Unsatisfiable class // 2) Equivalences between names classes // 3) potential redundant axioms // // The modules are create using the OWL-API modularization strategy BottomUp (BOT). // ---------------------------------------- private void createEquivModule(String ontologyId, List<OWLEquivalentClassesAxiom> equivalentNamedClassPairs) throws OWLOntologyCreationException, IOException, OWLOntologyStorageException { Set<OWLEntity> signature = new HashSet<OWLEntity>(); for(OWLEquivalentClassesAxiom ax : equivalentNamedClassPairs) { signature.addAll(ax.getClassesInSignature()); } final String moduleName = "equivalent-classes"; createModule(ontologyId, moduleName, signature); } private void createUnsatisfiableModule(String ontologyId, Collection<OWLEntity> unsatisfiable) throws OWLOntologyCreationException, IOException, OWLOntologyStorageException { Set<OWLEntity> signature = new HashSet<OWLEntity>(unsatisfiable); final String moduleName = "unsatisfiable"; createModule(ontologyId, moduleName, signature); } private void createPotentialRedundantModule(String ontologyId, Collection<PotentialRedundant> redundants) throws OWLOntologyCreationException, IOException, OWLOntologyStorageException { Set<OWLEntity> signature = new HashSet<OWLEntity>(); for (PotentialRedundant redundant : redundants) { signature.addAll(redundant.getAxiomOne().getSignature()); signature.addAll(redundant.getAxiomTwo().getSignature()); } final String moduleName = "potential-redundant"; createModule(ontologyId, moduleName, signature); } private void createModule(String ontologyId, String moduleName, Set<OWLEntity> signature) throws OWLOntologyCreationException, IOException, OWLOntologyStorageException { // create a new manager, avoid unnecessary change events final OWLOntologyManager m = OWLManager.createOWLOntologyManager(); // extract module SyntacticLocalityModuleExtractor sme = new SyntacticLocalityModuleExtractor(m, mooncat.getOntology(), ModuleType.BOT); Set<OWLAxiom> moduleAxioms = sme.extract(signature); OWLOntology module = m.createOntology(IRI.generateDocumentIRI()); m.addAxioms(module, moduleAxioms); // save module OutputStream moduleOutputStream = null; try { moduleOutputStream = getOutputSteam(getModuleFileName(ontologyId, moduleName)); m.saveOntology(module, moduleOutputStream); } finally { IOUtils.closeQuietly(moduleOutputStream); } } private String getModuleFileName(String ontologyId, String moduleName) { return ontologyId+"-"+moduleName+"-module.owl"; } private void cleanupEquivModule(String ontologyId) throws IOException { cleanupFile(getModuleFileName(ontologyId, "equivalent-classes")); } private void cleanupUnsatisfiableModule(String ontologyId) throws IOException { cleanupFile(getModuleFileName(ontologyId, "unsatisfiable")); } private void cleanupPotentialRedundantModule(String ontologyId) throws IOException { cleanupFile(getModuleFileName(ontologyId, "potential-redundant")); } // ---------------------------------------- // Other Helper methods // ---------------------------------------- /** * Given a list of equivalent classes axiom, remove all axioms which use a * class from the ignore set. Maps the class to it's identifier via the * given graph. * * @param all * @param ignores * @param graph * @return filtered list */ private List<OWLEquivalentClassesAxiom> filterEquivalentNamedClassPairs( List<OWLEquivalentClassesAxiom> all, Set<String> ignores, OWLGraphWrapper graph) { List<OWLEquivalentClassesAxiom> filtered = new ArrayList<OWLEquivalentClassesAxiom>(all.size()); for (OWLEquivalentClassesAxiom axiom : all) { Set<OWLClass> namedClasses = axiom.getNamedClasses(); boolean add = true; for (OWLClass owlClass : namedClasses) { String id = graph.getIdentifier(owlClass); if (ignores.contains(id)) { add = false; break; } } if (add) { filtered.add(axiom); } } return filtered; } private void handleSimpleOntology(OWLGraphWrapper graph, String ontologyId, String version, OWLOntology gciOntology) throws OboOntologyReleaseRunnerCheckException, OWLOntologyStorageException, IOException, OWLOntologyCreationException { logInfo("Creating simple ontology"); Set<RemoveImport> ris = new HashSet<RemoveImport>(); for (OWLImportsDeclaration oid : mooncat.getOntology().getImportsDeclarations()) { ris.add( new RemoveImport(mooncat.getOntology(), oid) ); } for (RemoveImport ri : ris) { mooncat.getManager().applyChange(ri); } List<String> filterProperties = oortConfig.getFilterSimpleProperties(); if (filterProperties != null) { logInfo("Using a property filter for simple ontology."); Set<OWLObjectProperty> filterProps = new HashSet<OWLObjectProperty>(); for (String s : filterProperties) { OWLObjectProperty property = graph.getOWLObjectProperty(s); if (property == null) { property = graph.getOWLObjectPropertyByIdentifier(s); } if (property == null) { final OWLObject owlObject = graph.getOWLObjectByLabel(s); if (owlObject instanceof OWLObjectProperty) { property = (OWLObjectProperty) owlObject; } } if (property == null) { logError("Could not find OWLObjectProperty for: "+s); } else { filterProps.add(property); } } if (filterProps.isEmpty()) { logInfo("Property filter will remove all relations, except subClassOf/is_a."); } else { logInfo("Property filter will retain subClassOf/is_a and the following relationships: "+filterProps); } Mooncat.retainAxiomsInPropertySubset(mooncat.getOntology(), filterProps); logInfo(""); } Set<OWLClass> coreSubset = new HashSet<OWLClass>(); Set<String> sourcePrefixes = oortConfig.getSourceOntologyPrefixes(); if (sourcePrefixes == null || sourcePrefixes.isEmpty()) { logInfo("Guessing core ontology idspace from ontology id: "+ontologyId.toLowerCase()); sourcePrefixes = Collections.singleton(ontologyId.toLowerCase()); } else { logInfo("Setting core ontology idspace: "+sourcePrefixes); } for (OWLClass c : mooncat.getOntology().getClassesInSignature()) { String idSpace = getIdSpace(c); if (sourcePrefixes.contains(idSpace)) { coreSubset.add(c); } } logInfo("Estimated core ontology number of classes: "+coreSubset.size()); if (coreSubset.size() == 0) { // TODO - make the core subset configurable logError("cannot determine core subset - simple file will include everything"); } else { mooncat.removeSubsetComplementClasses(coreSubset, true); } if (!oortConfig.isRelaxed()) { // if relaxed was created, than the equivalence axioms, have already been removed Set<OWLEquivalentClassesAxiom> rmAxs = mooncat.getOntology().getAxioms(AxiomType.EQUIVALENT_CLASSES); logInfo("Removing "+rmAxs.size()+" EquivalentClasses axioms from simple"); mooncat.getManager().removeAxioms(mooncat.getOntology(), rmAxs); } mooncat.removeDanglingAxioms(); /* * before saving as simple ontology remove certain axiom annotations * to comply with OBO-Basic level. */ logInfo("Removing axiom annotations which are equivalent to trailing qualifiers"); AxiomAnnotationTools.reduceAxiomAnnotationsToOboBasic(mooncat.getOntology()); if (oortConfig.isRunOboBasicDagCheck()) { logInfo("Start - Verifying DAG requirement for OBO Basic."); List<List<OWLObject>> cycles = OboBasicDagCheck.findCycles(mooncat.getGraph()); if (cycles != null && !cycles.isEmpty()) { StringBuilder sb = new StringBuilder(); for (List<OWLObject> cycle : cycles) { sb.append("Cycle["); for (OWLObject owlObject : cycle) { sb.append(' '); sb.append(owlpp.render(owlObject)); } sb.append("]\n"); } if (!oortConfig.isForceRelease()) { sb.insert(0, "OBO Basic is not a DAG, found the following cycles:\n"); throw new OboOntologyReleaseRunnerCheckException(sb.toString()); } else { logWarn("Force Release: ignore "+cycles.size()+" cycle(s) in basic ontology, cycles: "+sb.toString()); } } logInfo("Finished - Verifying DAG requirement for OBO Basic."); } saveInAllFormats(ontologyId, "simple", version, gciOntology); logInfo("Creating simple ontology completed"); } private String getIdSpace(OWLClass c) { // warning this is a hack. It assumes that the class IRIs are converted into OBO style IDs! return OWLAPIOwl2Obo.getIdentifier(c.getIRI()).replaceAll(":.*", "").toLowerCase(); } private String handleOntologyId() { String ontologyId = Owl2Obo.getOntologyId(mooncat.getOntology()); ontologyId = ontologyId.replaceAll(".obo$", ""); // TODO temp workaround return ontologyId; } private String handleVersion(String ontologyId) { // TODO add an option to set/overwrite the version manually via command-line // TODO re-use/create a method in obo2owl for creating an version IRI String version; OWLOntology ontology = mooncat.getOntology(); OWLOntologyID owlOntologyId = ontology.getOntologyID(); Optional<IRI> versionIRI = owlOntologyId.getVersionIRI(); if (versionIRI.isPresent() == false) { // set a new version IRI using the current date version = OntologyVersionTools.format(new Date()); versionIRI = Optional.of(IRI.create(Obo2OWLConstants.DEFAULT_IRI_PREFIX+ontologyId+"/"+oortConfig.getVersionSubdirectory()+"/"+version+"/"+ontologyId+".owl")); OWLOntologyManager m = mooncat.getManager(); m.applyChange(new SetOntologyID(ontology, new OWLOntologyID(owlOntologyId.getOntologyIRI(), versionIRI))); } else { String versionIRIString = versionIRI.get().toString(); version = OntologyVersionTools.parseVersion(versionIRIString); if (version == null) { // use the whole IRI? escape? logError("Could not parse a version from ontolgy version IRI: "+versionIRIString); version = versionIRIString; } } return version; } /** * Handle all the inference and optional justification steps for the main ontology. * Adds all findings to the reasoner report. * * @param ontologyId * @param version * @param reasonerReportLines * @param gciOntology * @return infBuilder * * @throws OWLOntologyStorageException * @throws IOException * @throws OWLOntologyCreationException * @throws OboOntologyReleaseRunnerCheckException */ private InferenceBuilder handleInferences(String ontologyId, String version, List<String> reasonerReportLines, OWLOntology gciOntology) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException, OboOntologyReleaseRunnerCheckException { logInfo("Using reasoner to add/retract links in main ontology"); OWLGraphWrapper g = mooncat.getGraph(); final OWLOntology ont = g.getSourceOntology(); final OWLOntologyManager manager = ont.getOWLOntologyManager(); final OWLDataFactory factory = manager.getOWLDataFactory(); final Set<OWLSubClassOfAxiom> removedSubClassOfAxioms = new HashSet<OWLSubClassOfAxiom>(); final Set<RemoveAxiom> removedSubClassOfAxiomChanges = new HashSet<RemoveAxiom>(); final InferenceBuilder infBuilder = new InferenceBuilder(g, oortConfig.getReasonerName(), oortConfig.isEnforceEL()) { @Override protected void logInfo(String msg) { OboOntologyReleaseRunner.this.logInfo(msg); } @Override protected boolean isDebug() { return false; } }; // CONSISTENCY CHECK // A consistent ontology is a primary for sensible reasoning results. if (oortConfig.isCheckConsistency()) { logInfo("Checking consistency"); ConsistencyReport consistencyReport = infBuilder.performConsistencyChecks(); if (consistencyReport.errors.size() > 0) { for (String inc : consistencyReport.errors) { String message = "PROBLEM\t" + inc; reasonerReportLines.add(message); } if (oortConfig.isCreateErrorModules() && consistencyReport.unsatisfiable != null && consistencyReport.unsatisfiable.isEmpty() == false) { createUnsatisfiableModule(ontologyId, consistencyReport.unsatisfiable); } // TODO: proper exception mechanism - delay until end? if (!oortConfig.isForceRelease()) { saveReasonerReport(ontologyId, reasonerReportLines); throw new OboOntologyReleaseRunnerCheckException("Found problems during intial checks.", consistencyReport.errors, "Use ForceRelease option to ignore this warning."); } } else { cleanupUnsatisfiableModule(ontologyId); } logInfo("Checking consistency completed"); } // optionally remove a subset of the axioms we want to attempt to recapitulate if (oortConfig.isJustifyAssertedSubclasses()) { if (oortConfig.isUseIsInferred()) { removeInferredAxioms(removedSubClassOfAxioms, removedSubClassOfAxiomChanges); } else { removeInferredOld(infBuilder, removedSubClassOfAxioms, removedSubClassOfAxiomChanges); } logInfo("Removing "+removedSubClassOfAxiomChanges.size()+" axioms"); for (RemoveAxiom rmax : removedSubClassOfAxiomChanges) { manager.applyChange(rmax); } saveInAllFormats(ontologyId, "minimal", version, gciOntology); } logInfo("Creating inferences"); List<OWLAxiom> inferredAxioms = infBuilder.buildInferences(); if (oortConfig.isJustifyAssertedSubclasses()) { OWLReasoner reasoner = infBuilder.getReasoner(ont); JustifyResult result = JustifyAssertionsTool.justifySubClasses(ont, reasoner, removedSubClassOfAxioms, inferredAxioms); for (OWLAxiom ax : result.getExistsEntailed()) { // add to ontology and report addAxiom("EXISTS, ENTAILED", ax, ont, manager, factory, reasonerReportLines); } for (OWLAxiom ax : result.getNewInferred()) { // add to ontology and report addAxiom("NEW, INFERRED", ax, ont, manager, factory, reasonerReportLines); } for (OWLAxiom ax : result.getExistsRedundant()) { // report only String rptLine = "EXISTS, REDUNDANT\t"+owlpp.render(ax); reasonerReportLines.add(rptLine); } for (OWLAxiom ax : result.getExistsNotEntailed()) { // add to ontology and report manager.applyChange(new AddAxiom(ont, ax)); String rptLine = "EXISTS, NOT-ENTAILED\t"+owlpp.render(ax); reasonerReportLines.add(rptLine); } } else { // default for non-justify mode for(OWLAxiom ax: inferredAxioms) { if (ax instanceof OWLSubClassOfAxiom && ((OWLSubClassOfAxiom)ax).getSuperClass().isOWLThing()) { // ignore owlThing as superClass continue; } String info = "NEW, INFERRED"; if (ax instanceof OWLSubClassOfAxiom && !(((OWLSubClassOfAxiom)ax).getSuperClass() instanceof OWLClass)) { // because the reasoner API can only generated subclass axioms with named superclasses, // we assume that any that have anonymous expressions as superclasses were generated // by the inference builder in the process of translating equivalence axioms // to weaker subclass axioms info = "NEW, TRANSLATED"; } addAxiom(info, ax, ont, manager, factory, reasonerReportLines); } } logInfo("Inferences creation completed"); return infBuilder; } private void addAxiom(String info, OWLAxiom ax, OWLOntology ont, OWLOntologyManager manager, OWLDataFactory factory, List<String> reasonerReportLines) { if (oortConfig.isUseIsInferred()) { ax = AxiomAnnotationTools.markAsInferredAxiom(ax, factory); } manager.applyChange(new AddAxiom(ont, ax)); String ppax = owlpp.render(ax); String rptLine = info+"\t"+ppax; reasonerReportLines.add(rptLine); } /** * Use a heuristic to guess which links can be inferred from logic * definitions.<br> * This method will be replaced by * {@link #removeInferredAxioms(Set, Set)}, which relies on axiom * annotations to identify axioms marked as inferred. * * @param infBuilder * @param removedSubClassOfAxioms * @param removedSubClassOfAxiomChanges * * @throws OWLOntologyStorageException * @throws IOException * @throws OWLOntologyCreationException * * @deprecated use #removeInferredNew(String, Set, Set) to replace this method */ @Deprecated private void removeInferredOld(InferenceBuilder infBuilder, Set<OWLSubClassOfAxiom> removedSubClassOfAxioms, Set<RemoveAxiom> removedSubClassOfAxiomChanges) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException { final OWLGraphWrapper g = mooncat.getGraph(); final OWLOntology ont = g.getSourceOntology(); String from = oortConfig.getJustifyAssertedSubclassesFrom(); final Set<OWLClass> markedClasses; OWLClass fromClass = from == null ? null: g.getOWLClassByIdentifier(from); if (fromClass == null) { logInfo("Removing asserted subclasses between defined class pairs"); markedClasses = null; } else { OWLReasoner reasoner = infBuilder.getReasoner(ont); NodeSet<OWLClass> nodeSet = reasoner.getSubClasses(fromClass, false); if (nodeSet == null || nodeSet.isEmpty() || nodeSet.isBottomSingleton()) { logWarn("No subclasses found for class: "+owlpp.render(fromClass)); markedClasses = Collections.singleton(fromClass); } else { markedClasses = new HashSet<OWLClass>(nodeSet.getFlattened()); markedClasses.add(fromClass); } infBuilder.setReasoner(null); // reset reasoner } for (OWLSubClassOfAxiom a : ont.getAxioms(AxiomType.SUBCLASS_OF)) { OWLClassExpression subClassExpression = a.getSubClass(); if (subClassExpression.isAnonymous()) { continue; } OWLClassExpression superClassExpression = a.getSuperClass(); if (superClassExpression.isAnonymous()) { continue; } OWLClass subClass = subClassExpression.asOWLClass(); OWLClass superClass = superClassExpression.asOWLClass(); if (OwlHelper.getEquivalentClasses(subClass, ont).isEmpty()) { continue; } if (OwlHelper.getEquivalentClasses(superClass, ont).isEmpty()) { continue; } if (markedClasses != null) { boolean usesMarkedAxiomSubClass = false; boolean usesMarkedAxiomSuperClass = false; Set<OWLEquivalentClassesAxiom> subClassEqAxioms = ont.getEquivalentClassesAxioms(subClass); for (OWLEquivalentClassesAxiom equivalentClassesAxiom : subClassEqAxioms) { Set<OWLClass> classesInSignature = equivalentClassesAxiom.getClassesInSignature(); for (OWLClass owlClass : classesInSignature) { if (markedClasses.contains(owlClass)) { usesMarkedAxiomSubClass = true; break; } } } Set<OWLEquivalentClassesAxiom> superClassEqAxioms = ont.getEquivalentClassesAxioms(superClass); for (OWLEquivalentClassesAxiom equivalentClassesAxiom : superClassEqAxioms) { Set<OWLClass> classesInSignature = equivalentClassesAxiom.getClassesInSignature(); for (OWLClass owlClass : classesInSignature) { if (markedClasses.contains(owlClass)) { usesMarkedAxiomSuperClass = true; break; } } } if (!usesMarkedAxiomSubClass || !usesMarkedAxiomSuperClass) { continue; } } RemoveAxiom rmax = new RemoveAxiom(ont, a); removedSubClassOfAxiomChanges.add(rmax); removedSubClassOfAxioms.add(a); } } /** * Remove inferred axioms, which are marked by the appropriate axiom annotation. * * @param removedSubClassOfAxioms * @param removedSubClassOfAxiomChanges * * @see AxiomAnnotationTools#isMarkedAsInferredAxiom(OWLAxiom) */ private void removeInferredAxioms(Set<OWLSubClassOfAxiom> removedSubClassOfAxioms, Set<RemoveAxiom> removedSubClassOfAxiomChanges) { final OWLOntology ont = mooncat.getGraph().getSourceOntology(); for (OWLSubClassOfAxiom a : ont.getAxioms(AxiomType.SUBCLASS_OF)) { if (AxiomAnnotationTools.isMarkedAsInferredAxiom(a)) { RemoveAxiom rmax = new RemoveAxiom(ont, a); removedSubClassOfAxiomChanges.add(rmax); removedSubClassOfAxioms.add(a); } } } /** * @param ontologyId * @param ext * @param version * @param gciOntology * @throws OWLOntologyStorageException * @throws IOException * @throws OWLOntologyCreationException */ private void saveInAllFormats(String ontologyId, String ext, String version, OWLOntology gciOntology) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException { saveInAllFormats(ontologyId, ext, version, mooncat.getOntology(), gciOntology); } private void saveInAllFormats(String ontologyId, String ext, String version, OWLOntology ontologyToSave, OWLOntology gciOntology) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException { if (ext == null || ext.isEmpty()) { saveOntologyInAllFormats(ontologyId, ontologyId, version, ontologyToSave, gciOntology, false); } else { saveOntologyInAllFormats(ontologyId, ontologyId + "-" + ext, version, ontologyToSave, gciOntology, true); } } private void saveOntologyInAllFormats(String idspace, String fileNameBase, String version, OWLOntology ontologyToSave, OWLOntology gciOntology, boolean changeOntologyId) throws OWLOntologyStorageException, IOException, OWLOntologyCreationException { logInfo("Saving: "+fileNameBase); final OWLOntologyManager manager = mooncat.getManager(); // if we add a new ontology id, remember the change, to restore the original // ontology id after writing into a file. SetOntologyID reset = null; boolean writeOWL = !oortConfig.isSkipFormat("owl"); boolean writeOWX = !oortConfig.isSkipFormat("owx"); boolean writeOFN = oortConfig.isWriteLabelOWL(); if (changeOntologyId && (writeOWL || writeOWX)) { final OWLOntologyID owlOntologyID = ontologyToSave.getOntologyID(); // create temporary id using the file name base to distinguish between the different release types // pattern: OBO_PREFIX / ID-SPACE / NAME .owl final IRI newOntologyIRI = IRI.create(Obo2OWLConstants.DEFAULT_IRI_PREFIX+idspace+"/"+fileNameBase+".owl"); // create temporary version IRI // pattern: OBO_PREFIX / ID-SPACE / VERSION / NAME .owl final IRI newVersionIRI = IRI.create(Obo2OWLConstants.DEFAULT_IRI_PREFIX+idspace+"/"+version+"/"+fileNameBase+".owl"); final OWLOntologyID newOWLOntologyID = new OWLOntologyID(Optional.of(newOntologyIRI), Optional.of(newVersionIRI)); manager.applyChange(new SetOntologyID(ontologyToSave, newOWLOntologyID)); // create change axiom with original id reset = new SetOntologyID(ontologyToSave, owlOntologyID); } if (writeOWL) { OutputStream os = getOutputSteam(fileNameBase +".owl"); write(manager, ontologyToSave, oortConfig.getDefaultFormat(), os); } if (writeOWX) { OutputStream osxml = getOutputSteam(fileNameBase +".owx"); write(manager, ontologyToSave, oortConfig.getOwlXMLFormat(), osxml); } if (writeOFN) { OutputStream os = getOutputSteam(fileNameBase +".ofn"); write(manager, ontologyToSave, oortConfig.getOwlOfnFormat(), os); } if (reset != null) { // reset versionIRI // the reset is required, because each owl file // has its corresponding file name in the version IRI. manager.applyChange(reset); } if (gciOntology != null && (writeOWL || writeOWX || writeOFN)) { OWLOntologyManager gciManager = gciOntology.getOWLOntologyManager(); // create specific import for the generated owl ontology OWLImportsDeclaration importDeclaration = new OWLImportsDeclarationImpl(IRI.create(fileNameBase +".owl")); AddImport addImport = new AddImport(gciOntology, importDeclaration); RemoveImport removeImport = new RemoveImport(gciOntology, importDeclaration); gciManager.applyChange(addImport); try { if (writeOWL) { OutputStream gciOS = getOutputSteam(fileNameBase +"-aux.owl"); write(gciManager, gciOntology, oortConfig.getDefaultFormat(), gciOS); } if (writeOWX) { OutputStream gciOSxml = getOutputSteam(fileNameBase +"-aux.owx"); write(gciManager, gciOntology, oortConfig.getOwlXMLFormat(), gciOSxml); } if (writeOFN) { OutputStream gciOS = getOutputSteam(fileNameBase +"-aux.ofn"); write(gciManager, gciOntology, oortConfig.getOwlOfnFormat(), gciOS); } } finally { gciManager.applyChange(removeImport); } } if (!oortConfig.isSkipFormat("obo")) { Owl2Obo owl2obo = new Owl2Obo(); OBODoc doc = owl2obo.convert(ontologyToSave); OBOFormatWriter writer = new OBOFormatWriter(); BufferedWriter bwriter = getWriter(fileNameBase +".obo"); writer.write(doc, bwriter); bwriter.close(); } if (!oortConfig.isSkipFormat("metadata")) { if (oortConfig.isWriteMetadata()) { saveMetadata(fileNameBase, mooncat.getGraph()); } } } private void write(OWLOntologyManager manager, OWLOntology ont, OWLDocumentFormat format, OutputStream out) throws OWLOntologyStorageException { try { manager.saveOntology(ont, format, out); } finally { try { out.close(); } catch (IOException e) { logWarn("Could not close stream.", e); } } } private void saveReasonerReport(String ontologyId, List<String> reasonerReportLines) { Collections.sort(reasonerReportLines); StringBuilder sb = new StringBuilder(); for (String s : reasonerReportLines) { sb.append(s); sb.append('\n'); } report(ontologyId + "-reasoner-report.txt", sb); } private void saveMetadata(String ontologyId, OWLGraphWrapper graph) { String fn = ontologyId + "-metadata.txt"; OutputStream fos; try { fos = getOutputSteam(fn); PrintWriter pw = new PrintWriter(fos); OntologyMetadata omd = new OntologyMetadata(pw); omd.generate(graph); pw.close(); fos.close(); } catch (IOException e) { logWarn("Could not print reasoner report for ontolog: "+ontologyId, e); } } private boolean isBridgingOntology(OWLOntology ont) { for (OWLClass c : ont.getClassesInSignature(Imports.INCLUDED)) { if (ont.getDeclarationAxioms(c).size() > 0) { if (mooncat.getOntology().getDeclarationAxioms(c).size() >0) { // class already declared in main ontology - a 2ary ontology MUST // declare at least one of its own classes if it is a bone-fide non-bridging ontology } else if (mooncat.isDangling(ont, c)) { // a dangling class has no OWL annotations. // E.g. bp_xp_cl contains CL classes as dangling } else { logInfo(c+" has declaration axioms, is not in main, and is not dangling, therefore "+ont+" is NOT a bridging ontology"); return false; } } } logInfo(ont+" is a bridging ontology"); return true; } private static void help() { System.out.println("This utility builds an ontology release. This tool is supposed to be run " + "from the location where a particular ontology releases are to be maintained."); System.out.println(); System.out.println("bin/ontology-release-runner [OPTIONAL OPTIONS] ONTOLOGIES-FILES"); System.out.println("Multiple obo or owl files are separated by a space character in the place of the ONTOLOGIES-FILES arguments."); System.out.println(); System.out.println("OPTIONS:"); } }
<reponame>alejsanc/nexttypes /* * Copyright 2015-2021 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nexttypes.serialization; import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.LinkedHashMap; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.nexttypes.datatypes.Audio; import com.nexttypes.datatypes.Document; import com.nexttypes.datatypes.File; import com.nexttypes.datatypes.Image; import com.nexttypes.datatypes.NXObject; import com.nexttypes.datatypes.PT; import com.nexttypes.datatypes.Tuple; import com.nexttypes.datatypes.TypeField; import com.nexttypes.datatypes.Video; import com.nexttypes.exceptions.InvalidValueException; import com.nexttypes.exceptions.NXException; import com.nexttypes.interfaces.ObjectsStream; import com.nexttypes.nodes.Node; import com.nexttypes.settings.LanguageSettings; import com.nexttypes.settings.TypeSettings; import com.nexttypes.system.KeyWords; public class ObjectsStreamDeserializer extends StreamDeserializer implements ObjectsStream { protected String version; protected String type; protected Long count; protected NXObject item; protected LinkedHashMap<String, TypeField> typeFields; protected TypeSettings typeSettings; protected Node nextNode; protected String lang; protected boolean sharedParser; public ObjectsStreamDeserializer(InputStream input, String lang, boolean sharedParser, Node nextNode, TypeSettings typeSettings) { super(input); setParameters(lang, sharedParser, nextNode, typeSettings); } public ObjectsStreamDeserializer(JsonParser parser, String lang, boolean sharedParser, Node nextNode, TypeSettings typeSettings, LanguageSettings languageSettings) { super(parser); setParameters(lang, sharedParser, nextNode, typeSettings); } protected void setParameters(String lang, boolean sharedParser, Node nextNode, TypeSettings typeSettings) { this.lang = lang; this.sharedParser = sharedParser; this.nextNode = nextNode; this.typeSettings = typeSettings; } @Override public String getFormat() { return NEXTTYPES_OBJECTS; } @Override public String getVersion() { return version; } @Override public String getType() { return type; } @Override public LinkedHashMap<String, TypeField> getTypeFields() { return typeFields; } @Override public void close() { try { if (!sharedParser) { parser.close(); } } catch (IOException e) { throw new NXException(e); } } @Override public void exec() { try { parser.nextToken(); parser.nextToken(); parser.nextToken(); checkTag(KeyWords.FORMAT); String format = parser.getText(); if (!NEXTTYPES_OBJECTS.equals(format)) { throw new InvalidValueException(KeyWords.INVALID_STREAM_FORMAT, format); } parser.nextToken(); parser.nextToken(); checkTag(KeyWords.VERSION); version = parser.getText(); parser.nextToken(); parser.nextToken(); checkTag(KeyWords.TYPE); type = parser.getText(); typeFields = nextNode.getTypeFields(type); parser.nextToken(); parser.nextToken(); checkTag(KeyWords.COUNT); count = parser.getLongValue(); parser.nextToken(); parser.nextToken(); checkTag(KeyWords.ITEMS); } catch (IOException e) { throw new NXException(e); } } @Override public boolean next() { try { if (parser.nextToken() == JsonToken.START_OBJECT) { String type = null, id = null; ZonedDateTime cdate = null, udate = null; Boolean backup = null; LinkedHashMap<String, Object> fields = null; while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); switch (parser.getCurrentName()) { case KeyWords.TYPE: type = parser.getText(); break; case KeyWords.ID: id = parser.getText(); break; case KeyWords.CDATE: cdate = Tuple.parseUTCDateTime(parser.getText()); break; case KeyWords.UDATE: udate = Tuple.parseUTCDateTime(parser.getText()); break; case KeyWords.BACKUP: backup = Tuple.parseBoolean(parser.getText()); break; case KeyWords.FIELDS: fields = parseFields(type); break; } } item = new NXObject(type, id, null, cdate, udate, backup, fields); return true; } else { parser.nextToken(); return false; } } catch (IOException e) { throw new NXException(e); } } protected LinkedHashMap<String, Object> parseFields(String type) { try { LinkedHashMap<String, Object> fields = new LinkedHashMap<>(); while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); String field = parser.getCurrentName(); TypeField typeField = typeFields.get(field); String fieldType = typeField.getType(); Object value = null; if (parser.getCurrentToken() != JsonToken.VALUE_NULL) { switch (fieldType) { case PT.TIMEZONE: value = Tuple.parseTimeZone(parser.getText()); break; case PT.HTML: value = Tuple.parseHTML(parser.getText(), lang, typeSettings.getFieldString(type, field, KeyWords.HTML_ALLOWED_TAGS)); break; case PT.XML: value = Tuple.parseXML(parser.getText(), lang, typeSettings.getFieldString(type, field, KeyWords.XML_ALLOWED_TAGS)); break; case PT.JSON: value = Tuple.parseJSON(parser.getText()); break; case PT.INT16: value = Tuple.parseInt16(parser.getText()); break; case PT.INT32: value = Tuple.parseInt32(parser.getText()); break; case PT.INT64: value = Tuple.parseInt64(parser.getText()); break; case PT.FLOAT32: value = Tuple.parseFloat32(parser.getText()); break; case PT.FLOAT64: value = Tuple.parseFloat64(parser.getText()); break; case PT.NUMERIC: value = Tuple.parseNumeric(parser.getText()); break; case PT.BOOLEAN: value = Tuple.parseBoolean(parser.getText()); break; case PT.DATE: value = Tuple.parseDate(parser.getText()); break; case PT.TIME: value = Tuple.parseTime(parser.getText()); break; case PT.DATETIME: value = Tuple.parseDateTime(parser.getText()); break; case PT.COLOR: value = Tuple.parseColor(parser.getText()); break; case PT.URL: value = Tuple.parseURL(parser.getText()); break; case PT.EMAIL: value = Tuple.parseEmail(parser.getText()); break; case PT.BINARY: value = parser.getBinaryValue(); break; case PT.FILE: value = parser.readValueAs(new TypeReference<File>() {}); break; case PT.IMAGE: value = parser.readValueAs(new TypeReference<Image>() {}); break; case PT.DOCUMENT: value = parser.readValueAs(new TypeReference<Document>() {}); break; case PT.AUDIO: value = parser.readValueAs(new TypeReference<Audio>() {}); break; case PT.VIDEO: value = parser.readValueAs(new TypeReference<Video>() {}); break; default: value = parser.getText(); } } fields.put(field, value); } return fields; } catch (IOException e) { throw new NXException(e); } } @Override public NXObject getItem() { return item; } @Override public Long getCount() { return count; } }
class VersionsEdit extends TypeForm { constructor() { super(); this.typeName = "Version"; this.readableTypeName = "Version"; this.icon = '<svg class="SideNav-icon icon-layers no-fill" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>'; this._hideAttributes = true; this.versionId = null; } async _getSectionForm(data) { let current = this.boxHelper.boxWrapDefault({ "children": "" }); this.versionId = data.id; // console.log(this.versionId); // this._setForm(); // append input for name this._editName = document.createElement("text-input"); this._editName.setAttribute("name", "Name"); this._editName.setAttribute("type", "string"); this._editName.setValue(this.data.name); this._editName.default = this.data.name; this._editName.addEventListener("change", this._formChanged.bind(this)); this._form.appendChild(this._editName); // description this._editDescription = document.createElement("text-input"); this._editDescription.setAttribute("name", "Description"); this._editDescription.setAttribute("type", "string"); this._editDescription.setValue(this.data.description); this._editDescription.default = this.data.description; this._editDescription.addEventListener("change", this._formChanged.bind(this)); this._form.appendChild(this._editDescription); // Show Empty this._showEmpty = document.createElement("bool-input"); this._showEmpty.setAttribute("name", "Show Empty"); this._showEmpty.setAttribute("on-text", "Yes"); this._showEmpty.setAttribute("off-text", "No"); this._showEmpty.setValue(this.data.show_empty); this._showEmpty.default = this.data.show_empty; this._showEmpty.addEventListener("change", this._formChanged.bind(this)); this._form.appendChild(this._showEmpty); // number this._number = document.createElement("text-input"); this._number.setAttribute("name", "Number"); this._number.setAttribute("type", "int"); if (typeof data.number === "undefined") { this._number.setValue("Created on Save"); this._number.default = ""; } else { this._number.setValue(this.data.number); this._number.default = this.data.number; } this._number._input.disabled = true; this._number._input.classList.add("disabled"); this._number.addEventListener("change", this._formChanged.bind(this)); this._form.appendChild(this._number); // Bases const basesListWithChecked = await this.versionListHandler.getCompiledVersionList(data.bases, data.id); // console.log(basesListWithChecked); this._basesCheckbox = document.createElement("checkbox-set"); this._basesCheckbox.setAttribute("name", "Bases"); this._basesCheckbox.setAttribute("type", "number"); this._basesCheckbox.setValue(basesListWithChecked); this._basesCheckbox.default = basesListWithChecked; this._basesCheckbox.addEventListener("change", this._formChanged.bind(this)); this._form.appendChild(this._basesCheckbox); current.appendChild(this._form); return current; } _getFormData() { const formData = {}; // console.log(`Data ID: ${this.data.id}`); const isNew = this.data.id == "New" ? true : false; if (this._editName.changed() || isNew) { formData.name = this._editName.getValue(); } if (this._editDescription.changed() || isNew) { formData.description = this._editDescription.getValue(); } if (this._showEmpty.changed() || isNew) { formData.show_empty = this._showEmpty.getValue(); } // if (this._number.changed() || isNew) { // formData.number = this._number.getValue(); // } if (this._basesCheckbox.changed() || isNew) { formData.bases = this._basesCheckbox.getValue(); } return formData; } async _deleteTypeConfirm() { this.loading.showSpinner(); let button = document.createElement("button"); let confirmText = document.createTextNode("Confirm") button.appendChild(confirmText); button.setAttribute("class", "btn btn-clear f1 text-semibold btn-red") button.addEventListener("click", this._deleteType.bind(this)); // Check the related state types const [sc, lc] = await Promise.all( [fetch(`/rest/StateCount/${this.projectId}?version=${this.versionId}`, { method: "GET", credentials: "same-origin", headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" } } ), fetch(`/rest/LocalizationCount/${this.projectId}?version=${this.versionId}`, { method: "GET", credentials: "same-origin", headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" } })] ); const stateCountData = sc.json(); const LocalizationCountData = lc.json(); Promise.all([stateCountData, LocalizationCountData]) .then(([stateCount, LocalizationCount]) => { this._modalConfirm({ "titleText": `Delete Confirmation`, "mainText": `Pressing confirm will delete this ${this.typeName} and all related states and localizations from your account.<br/><br/><span class="text-ted">There are ${stateCount} states and ${LocalizationCount} localizations that will also be deleted.</span><br/><br/>Do you want to continue?`, "buttonSave": button, "scroll": false }); }); } async _save({ id = -1, globalAttribute = false } = {}) { this.loading.showSpinner(); // Overriding save to show prompt let button = document.createElement("button"); let confirmText = document.createTextNode("Confirm") button.appendChild(confirmText); button.setAttribute("class", "btn btn-clear f1 text-semibold") button.addEventListener("click", this._saveConfirmed.bind(this)); // Check the related state types const [sc, lc] = await Promise.all( [fetch(`/rest/StateCount/${this.projectId}?version=${this.versionId}`, { method: "GET", credentials: "same-origin", headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" } } ), fetch(`/rest/LocalizationCount/${this.projectId}?version=${this.versionId}`, { method: "GET", credentials: "same-origin", headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" } })] ); const stateCountData = sc.json(); const LocalizationCountData = lc.json(); Promise.all([stateCountData, LocalizationCountData]) .then(([stateCount, LocalizationCount]) => { this.loading.hideSpinner(); this._modalConfirm({ "titleText": `Edit Confirmation`, "mainText": `There are ${stateCount} states and ${LocalizationCount} localizations existing in this version. Any edits will be reflected on those existing states and localizations.<br/><br/>Do you want to continue?`, "buttonSave": button, "scroll": false }); }); } async _saveConfirmed({ id = this.versionId }) { this.loading.showSpinner(); //create form data & post promise array for the attribute forms, and submit this.successMessages = ""; this.failedMessages = ""; this.confirmMessages = ""; this.nameChanged = false; this.newName = null; this.saveModalMessage = ""; this.requiresConfirmation = false; this.hasAttributeChanges = this.attributeSection && this.attributeSection.hasChanges ? true : false; if (this.isChanged() || this.hasAttributeChanges) { try { if (this.isChanged()) { // Main type form await this._typeFormChanged({ id }); } } catch (err) { console.error("Error saving.", err); this.loading.hideSpinner(); return this._modalError("Error saving type form changes.\nError: " + err); } try { if (this.hasAttributeChanges) { // All attribute forms const attrFormsChanged = this.attributeSection.attrForms.filter(form => form._changed); if (attrFormsChanged && attrFormsChanged.length > 0) { for (let form of attrFormsChanged) { await this._attrFormsChanged(form); } } } } catch (err) { console.error("Error saving.", err); this.loading.hideSpinner(); return this._modalError("Error saving attribute changes.\nError: " + err); } try { // Compiled messages from above await this._showSaveCompletModal(); // Clean up.................. // Reset changed flags this.changed = false; if (this.hasAttributeChanges) { const attrFormsChanged = this.attributeSection.attrForms.filter(form => form._changed); if (attrFormsChanged.length > 0) { for (let f of attrFormsChanged) { f.changeReset(); } } } // Update related items with an event if required if (this.nameChanged) { this._updateNavEvent("rename", this.newName) } } catch (err) { console.error("Error saving.", err); this.loading.hideSpinner(); return this._modalError("Error saving.\nError: " + err); } } else { this.loading.hideSpinner(); return this._modalSuccess("Nothing new to save!"); } } } customElements.define("versions-edit", VersionsEdit);
<filename>server/game/cards/characters/04/podrickpayne.js const DrawCard = require('../../../drawcard.js'); class PodrickPayne extends DrawCard { setupCardAbilities(ability) { this.interrupt({ canCancel: true, location: 'hand', when: { onCharactersKilled: () => this.game.claim.isApplying && this.game.claim.type === 'military' }, target: { activePromptTitle: 'Select character to save', cardCondition: (card, context) => context.event.cards.includes(card) && card.controller === this.controller }, cost: [ ability.costs.payGold(2), ability.costs.putSelfIntoPlay() ], handler: context => { context.event.saveCard(context.target); this.game.addMessage('{0} puts {1} into play and pays 2 gold to save {2}', this.controller, this, context.target); if(context.target.name === '<NAME>' && this.controller.gold >= 2 && this.game.currentChallenge && this.game.currentChallenge.attackers.length >= 1) { this.game.promptWithMenu(this.controller, this, { activePrompt: { menuTitle: 'Pay two gold to kill an attacking character?', buttons: [ { text: 'Yes', method: 'killAttacker' }, { text: 'No', method: 'cancel' } ] }, source: this }); } } }); } killAttacker() { this.game.promptForSelect(this.controller, { activePromptTitle: 'Select a character', source: this, cardCondition: card => card.location === 'play area' && card.getType() === 'character' && this.game.currentChallenge.isAttacking(card), gameAction: 'kill', onSelect: (p, card) => { this.game.addGold(this.controller, -2); card.controller.killCharacter(card); this.game.addMessage('{0} then uses {1} and pays 2 gold to kill {2}', this.controller, this, card); return true; } }); return true; } cancel() { return true; } } PodrickPayne.code = '04109'; module.exports = PodrickPayne;
<gh_stars>0 import { PaginatedResponse } from '../models/response/paginated.response'; import { DbService } from '../models/directbilling/service/db.service'; import { PartialDbService } from '../models/directbilling/service/partial.db.service'; import { DbCalculation } from '../models/directbilling/service/db.calculation'; import { PartialDbTransaction } from '../models/directbilling/transaction/partial.db.transaction'; import { DbTransaction } from '../models/directbilling/transaction/db.transaction'; import { DbGenerationResponse } from '../models/directbilling/transaction/db.generation.response'; import { DbTransactionRequest } from '../models/directbilling/transaction/db.transaction.request'; import { DbNotificationRequest } from '../models/directbilling/transaction/db.notifications.request'; export declare class DirectBilling { private readonly key; private readonly password; private readonly client; constructor(key: string, password: string); getServices(): Promise<PartialDbService[]>; getServicesPaginated(page?: number, pageSize?: number): Promise<PaginatedResponse<PartialDbService>>; getService(id: number): Promise<DbService | undefined>; calculateCommission(serviceId: number, amount: number): Promise<DbCalculation | undefined>; getTransactions(serviceId: number): Promise<PartialDbTransaction[]>; getTransactionsPaginated(serviceId: number, page?: number, pageSize?: number): Promise<PaginatedResponse<PartialDbTransaction>>; getTransaction(serviceId: number, transactionId: string): Promise<DbTransaction | undefined>; createTransaction(serviceId: number, key: string, request: DbTransactionRequest): Promise<DbGenerationResponse | undefined>; checkNotification(key: string, body: any): DbTransaction | undefined; generateSignature(key: string, request: DbTransactionRequest): string; generateSignatureNotification(key: string, request: DbNotificationRequest): string; }
fn solve_sudoku(board: &mut Vec<Vec<i32>>) { solve_sudoku_helper(board); } fn solve_sudoku_helper(board: &mut Vec<Vec<i32>>) -> bool { for i in 0..9 { for j in 0..9 { if board[i][j] == 0 { for num in 1..=9 { if is_safe(board, i, j, num) { board[i][j] = num; if solve_sudoku_helper(board) { return true; } board[i][j] = 0; } } return false; } } } true } fn is_safe(board: &Vec<Vec<i32>>, row: usize, col: usize, num: i32) -> bool { for i in 0..9 { if board[row][i] == num || board[i][col] == num { return false; } } let start_row = row - row % 3; let start_col = col - col % 3; for i in 0..3 { for j in 0..3 { if board[i + start_row][j + start_col] == num { return false; } } } true }
public class Average { public static void main( String [] args ) { int A = 10; int B = 5; int C = 15; int Average = (A+B+C)/3; System.out.println("The average of 3 numbers is: "+Average); } }
<gh_stars>1-10 // account export const account_count = '/counts/account' export const account_create = '/accounts' export const account_lookup = '/accounts' export const account_detail = '/accounts/' // content export const content_create = '/posts' export const content_lookup = '/posts' // user content export const user_content_lookup = '/account_posts' // compare export const compare = '/dci/content' export const compare_text = '/dci/text' // ts export const msgts_fetch = '/last_post' // similar export const similar_lookup = '/similar/post'
#!/usr/bin/env bash # Copyright 2021 The Kubernetes Authors. # # 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. set -euo pipefail export E2E_SECURE=${E2E_SECURE:-""} make fedora-image # Ensure image.tar isn't there rm -f image.tar podman save -o image.tar quay.io/jaosorior/selinuxd-fedora:latest RUN=./hack/ci/run.sh echo "Spawning VM" make vagrant-up if [ -z "$E2E_SECURE" ]; then echo "Spawning selinuxd in VM with tracing" $RUN hack/ci/daemon-and-trace.sh else echo "Spawning selinuxd in VM with security features enabled" $RUN hack/ci/daemon-secure.sh fi echo "Running e2e tests" $RUN hack/ci/e2e.sh echo "Getting logs" $RUN hack/ci/logs.sh
#!/bin/bash # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. set -ex # change to grpc repo root cd $(dirname $0)/../../.. rake
<reponame>zzzzzzzs/Java-self-study package com.me.csv; import cn.hutool.core.io.FileUtil; import cn.hutool.core.lang.Console; import cn.hutool.core.text.csv.CsvData; import cn.hutool.core.text.csv.CsvReader; import cn.hutool.core.text.csv.CsvRow; import cn.hutool.core.text.csv.CsvUtil; import java.util.List; /** * @author zs * @date 2021/12/11 */ public class CsvDemo { public static void main(String[] args) { CsvReader reader = CsvUtil.getReader(); //从文件中读取CSV数据 CsvData data = reader.read(FileUtil.file("D:\\workspace\\zs\\code\\NotMe\\amc\\output\\parsed_data\\02_01.csv")); List<CsvRow> rows = data.getRows(); //遍历行 for (CsvRow csvRow : rows) { //getRawList返回一个List列表,列表的每一项为CSV中的一个单元格(既逗号分隔部分) Console.log(csvRow.get(0)); } } }
<gh_stars>0 module.exports = function(customVariableName, opts) { return ({ addComponents, config }) => { const varModules = { colors: 'color', screens: '', fontFamily: 'font', fontSize: 'text', fontWeight: 'font', lineHeight: 'leading', letterSpacing: 'tracking', backgroundSize: 'bg', borderWidth: 'border', borderRadius: 'rounded', width: 'w', height: 'h', minWidth: 'min-w', minHeight: 'min-h', maxWidth: 'max-w', maxHeight: 'max-h', padding: 'p', margin: 'm', boxShadow: 'shadows', zIndex: 'z', opacity: 'opacity', ...customVariableName }; const options = { postcssEachVariables: false, ...opts }; let rootArray = {}; Object.keys(varModules).forEach(key => { if ((key === 'colors' && varModules['colors']) || (key === 'screens' && varModules['screens'] !== false) || varModules[key]) { const keyValue = config(`theme.${key}`, []); const names = Object.keys(keyValue); const modulePrefix = varModules[key]; if (options.postcssEachVariables) { const selectedKey = ['colors', 'screens', 'fontFamily', 'fontSize']; if (selectedKey.includes(key)) { if (key=== 'colors') { const colorsArr = []; names.forEach(colorName=> { const colorObj = keyValue[colorName]; if (isObject(colorObj)) { Object.keys(colorObj).forEach(level=>{ const fullColorName= `${colorName}-${level}`; colorsArr.push(fullColorName); }); } else { colorsArr.push(colorName); } }) const varName = `--${key !== '' ? key : ''}`; rootArray[varName] = colorsArr.toString(); } else { const varName = `--${key !== '' ? key : ''}`; rootArray[varName] = names.toString(); } } } names.forEach(name => { let varName, value; if (key=== 'colors' && isObject(keyValue[name])) { colorObj = keyValue[name]; Object.keys(colorObj).forEach(key=>{ varName = `--${modulePrefix !== '' ? modulePrefix : ''}-${name}-${key}`.replace(/-default$/, ''); value = typeof keyValue[name][key] === 'string' ? keyValue[name][key] : keyValue[name][key].toString(); rootArray[varName] = value; }); } else { varName = `-${key !== 'screens' ? '-': ''}${modulePrefix !== '' ? modulePrefix : ''}${ name !== 'default' ? '-' + name.replace('/','-') : '' }`; value = typeof keyValue[name] === 'string' ? keyValue[name] : keyValue[name].toString(); rootArray[varName] = value; } }); } }); let root = { ':root': rootArray }; addComponents(root); }; }; var isObject = (obj) =>{ return Object.prototype.toString.call(obj) === '[object Object]'; };
<reponame>amaraimusi/python_sample<filename>ffmpeg_sample/test01_ffmpeg_probe.py<gh_stars>0 print('mp4ファイル、またはmp3ファイルの情報をダンプ') import ffmpeg import pprint print('--------------mp4ファイルの情報--------------') video_info = ffmpeg.probe('./test_data/MVI_0887.MP4') pprint.pprint(video_info) print('--------------mp3ファイルの情報--------------') video_info = ffmpeg.probe('./test_data/MVI_0887.MP4') pprint.pprint(video_info)
<gh_stars>100-1000 import { isPlatformBrowser } from '@angular/common'; import { inject, InjectionToken, PLATFORM_ID, Provider } from '@angular/core'; /** * Injection Token to safely inject * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage} to Angular DI */ export const SESSION_STORAGE_TOKEN: InjectionToken<Storage | undefined> = new InjectionToken< Storage | undefined >('SESSION_STORAGE_TOKEN', { providedIn: 'root', factory: () => (isPlatformBrowser(inject(PLATFORM_ID)) ? sessionStorage : undefined), }); /** * Injection Token to safely inject * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage} to Angular DI */ export const LOCAL_STORAGE_TOKEN: InjectionToken<Storage | undefined> = new InjectionToken< Storage | undefined >('LOCAL_STORAGE_TOKEN', { providedIn: 'root', factory: () => (isPlatformBrowser(inject(PLATFORM_ID)) ? localStorage : undefined), }); /** * Injection Token to inject custom storage approach for persistence; must implement * {@link https://developer.mozilla.org/en-US/docs/Web/API/Storage} interface */ export const FORMS_MANAGER_STORAGE = new InjectionToken<Storage | undefined>( 'FORMS_MANAGER_STORAGE', { providedIn: 'root', factory: () => isPlatformBrowser(inject(PLATFORM_ID)) ? inject(LOCAL_STORAGE_TOKEN) : undefined, } ); /** * Value provider that injects usage of * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage} for persistence */ export const FORMS_MANAGER_SESSION_STORAGE_PROVIDER: Provider = { provide: FORMS_MANAGER_STORAGE, useExisting: SESSION_STORAGE_TOKEN, };
class YourFramework: def __init__(self, predict_ds): self._predict_ds = predict_ds def set_dataset_attribute(self, dataset: Dataset, attribute: str, value): # Implementation of setting dataset attribute def _resolve_collate_fn(self, dataset: Dataset, running_stage: RunningStage) -> Optional[Callable]: if dataset is not None and running_stage == RunningStage.PREDICTING: return lambda: None # Replace with actual callable object if needed else: return None
/** * @file * * The main entry point for the TGView demo */ // create an element and append it to the body const element = document.createElement('div'); element.innerHTML = 'Loading TGView...'; element.setAttribute('style', 'cursor: auto; overflow: hidden; '); document.body.append(element); Promise.all([ import('../').then(e => e.default), // Load all of the required CSS import('../css/styles.css'), // <link href="deps/fontawesome/css/font-awesome.min.css" rel="stylesheet" /> import('vis/dist/vis.min.css'), import('jqueryui/jquery-ui.min.css'), import('jstree/dist/themes/default/style.min.css'), ]).then(([TGView]) => { // once the window has loaded window.onload = function() { window.instance = new TGView({ prefix: 'tgview-prefix', mainContainer: element, serverBaseURL: location.pathname === '/' ? 'https://mmt.mathhub.info/' : '/' }); } });
/* * Copyright 2002 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of * any nuclear facility. */ package com.sun.j2ee.blueprints.opc.transitions; import javax.ejb.EJBException; import javax.naming.Context; import javax.naming.NamingException; import javax.jms.*; import com.sun.j2ee.blueprints.servicelocator.ServiceLocatorException; import com.sun.j2ee.blueprints.servicelocator.ejb.ServiceLocator; import com.sun.j2ee.blueprints.processmanager.transitions.*; /** * TransitionDelegate for MailInvoice MDB */ public class MailInvoiceTransitionDelegate implements TransitionDelegate { private QueueHelper mailHelper; private Queue q; private QueueConnectionFactory qFactory; public MailInvoiceTransitionDelegate() { } /** * sets up all the resources that will be needed to do a transition */ public void setup() throws TransitionException { try { ServiceLocator serviceLocator = new ServiceLocator(); qFactory = serviceLocator.getQueueConnectionFactory(JNDINames.QUEUE_CONNECTION_FACTORY ); q = serviceLocator.getQueue(JNDINames.MAIL_SENDER_QUEUE); mailHelper = new QueueHelper(qFactory, q); } catch (ServiceLocatorException se) { throw new TransitionException(se); } } /** * send a Mail message to mailer service, so customer gets an email */ public void doTransition(TransitionInfo info) throws TransitionException { String xmlMail = info.getXMLMessage(); try { if (xmlMail != null) { mailHelper.sendMessage(xmlMail); } } catch (JMSException je) { throw new TransitionException(je); } } }
# Python code input_string = "bcqbad,bcipbp,cfgcdeh" # split the input string into list of characters char_list = input_string.split(",") # function to check for palindrome def isPalindrome(string): return string == string[::-1] # empty list to store all palindromic characters palindromic_list = [] # loop through the given list of characters for char in char_list: # check for palindrome if isPalindrome(char): # if palindrome, add to the palindromic list palindromic_list.append(char) # remove the palindromic character from original list for palindrome in palindromic_list: char_list.remove(palindrome) # concat the palindromic list and original list final_list = palindromic_list + char_list # join the list and convert to string final_string = ','.join(final_list) # print the output string print(final_string)
package tr.com.minicrm.web.productgroup; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.client.MongoClients; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; import org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.MongoDBContainer; import org.testcontainers.utility.DockerImageName; import tr.com.minicrm.web.generated.productgroup.model.FindProductGroupQuery; import tr.com.minicrm.web.generated.productgroup.model.FindProductGroupQueryOperationResponse; import tr.com.minicrm.web.generated.productgroup.model.NewProductGroup; import tr.com.minicrm.web.generated.productgroup.model.ProductGroup; @SpringBootTest(properties = {"spring.main.allow-bean-definition-overriding=true", "platform.datasource.databaseType=mongo", "spring.liquibase.enabled=false"}) @AutoConfigureMockMvc public class ProductGroupControllerMongoIntegrationTest { private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("mongo"); private static final String DEFAULT_TAG = "4.0.10"; private static GenericContainer container; @Autowired private MockMvc mockMvc; @Test public void testWhenNewProductGroupNameProvidedThanProductGroupDataServiceShouldBeCalled() throws Exception { NewProductGroup group = new NewProductGroup().name("demo"); this.mockMvc .perform(post("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(group))) .andDo(print()).andExpect(status().isOk()); } @Test public void testWhenDuplicateProductGroupNameProvidedThanItShouldThrowException() throws Exception { NewProductGroup group = new NewProductGroup().name("demo2"); this.mockMvc .perform(post("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(group))) .andDo(print()).andExpect(status().isOk()); this.mockMvc .perform(post("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(group))) .andDo(print()).andExpect(status().isBadRequest()); } @Test public void testWhenProductGroupNameQueriedThanItShouldReturnResult() throws Exception { NewProductGroup group = new NewProductGroup().name("demo3"); this.mockMvc .perform(post("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(group))) .andDo(print()).andExpect(status().isOk()); FindProductGroupQuery query = new FindProductGroupQuery().name(group.getName()); this.mockMvc .perform(post("/product-group/find-by-name").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(query))) .andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("$.body.name").value(group.getName())); } @Test public void testWhenUnknownProductGroupNameQueriedThanItShouldThrowException() throws Exception { NewProductGroup group = new NewProductGroup().name("demo-1"); FindProductGroupQuery query = new FindProductGroupQuery().name(group.getName()); this.mockMvc .perform(post("/product-group/find-by-name").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(query))) .andDo(print()).andExpect(status().isNotFound()); } @Test public void testWhenProductGroupNameUpdatedThanProductGroupDataServiceShouldBeCalled() throws Exception { NewProductGroup group = new NewProductGroup().name("demo 4"); this.mockMvc .perform(post("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(group))) .andDo(print()).andExpect(status().isOk()); FindProductGroupQuery query = new FindProductGroupQuery().name(group.getName()); String content = this.mockMvc .perform(post("/product-group/find-by-name").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(query))) .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); FindProductGroupQueryOperationResponse response = asObject(content, FindProductGroupQueryOperationResponse.class); Integer version = response.getBody().getVersion(); Long id = response.getBody().getId(); ProductGroup pg = new ProductGroup().id(id).version(version).name("demo 4.1"); this.mockMvc .perform(put("/product-group").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(pg))) .andDo(print()).andExpect(status().isOk()); FindProductGroupQuery queryAgain = new FindProductGroupQuery().name(pg.getName()); this.mockMvc .perform(post("/product-group/find-by-name").accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE).content(asJsonString(queryAgain))) .andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("$.body.name").value(pg.getName())) .andExpect(jsonPath("$.body.version").value(1)); } @TestConfiguration @ConditionalOnProperty(value = "platform.datasource.databaseType", havingValue = "mongo") @EnableAutoConfiguration(exclude = {MongoReactiveAutoConfiguration.class, MongoAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, MongoDataAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) static class ProductGroupInfraDataMongoConfiguration { @Bean MongoTemplate mongoTemplate() { return new MongoTemplate( MongoClients.create("mongodb://" + container.getContainerIpAddress() + ":" + container.getFirstMappedPort()), "product_management"); } } public static String asJsonString(final Object obj) { try { final ObjectMapper mapper = new ObjectMapper(); final String jsonContent = mapper.writeValueAsString(obj); return jsonContent; } catch (Exception e) { throw new RuntimeException(e); } } public static <T> T asObject(String json, final Class<T> obj) { try { final ObjectMapper mapper = new ObjectMapper(); final T jsonContent = mapper.readValue(json, obj); return jsonContent; } catch (Exception e) { throw new RuntimeException(e); } } @BeforeAll static void setUp() throws Exception { prepareDatabaseServer(); } @AfterAll static void tearDown() { container.stop(); } private static void prepareDatabaseServer() { container = new MongoDBContainer(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG)); container.start(); } }
// Define a query. NameIndexQuery defineQuery(Name queryName) throws NameIndexException, NameIndexStoreException, RNTException { NameIndexQuery query = new NameIndexQuery(queryName); query.setNameDataMinimumMatchScore(.30); return query; }
<filename>ID3-Decision-Tree/main.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 1 17:05:39 2020 @author: safir """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('house-votes-84.csv') rawdataset = pd.read_csv('house-votes-84.csv') party = {'republican':0, 'democrat':1} vote = {'y':1, 'n':0, '?':0} for col in dataset.columns: if col != 'party': dataset[col] = dataset[col].map(vote) dataset['party'] = dataset['party'].map(party) X = dataset.iloc[:, 1:17].values y = dataset.iloc[:, 0].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import KFold kf = KFold(n_splits=5) #print(kf.get_n_splits(X)) for train_index, test_index in kf.split(X,y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # Training the Decision Tree Classification model on the Training set ''' from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier(random_state = 0) classifier.fit(X_train, y_train) ''' ''' # Predicting the Test set results y_pred = classifier.predict(X_test) # Testing the Accuracy print("Training accuracy: {} %".format(np.multiply(classifier.score(X_train,y_train), 100))) print("Test Accuracy: {} %".format(np.multiply(classifier.score(X_test,y_test),100))) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm) ''' # Building the Decision Tree Model with Information Gain from ID3 import DecisionTreeClassifier id3 = DecisionTreeClassifier() id3.add_features(dataset, 'party') print(id3.features) ## Making the decision Tree id3.information_gain(X_train, y_train) y_pred = id3.predict(X_test) print(y_pred) y_pred1 = id3.predict(X_train) from sklearn.metrics import accuracy_score a = accuracy_score(y_test, y_pred) print("Test Set Accuracy", a) b = accuracy_score(y_train, y_pred1) print("Training Set Accuracy", b) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm) # Building the Decision Tree Model with Gini Index id3.gini_index(X_train, y_train) y_pred = id3.predict(X_test) y_pred1 = id3.predict(X_train) from sklearn.metrics import accuracy_score a = accuracy_score(y_test, y_pred) print("Test Set Accuracy", a) b = accuracy_score(y_train, y_pred1) print("Training Set Accuracy", b) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm)
<filename>modules/caas/common/src/main/java/com/github/dockerjava/api/model/Link.java package com.github.dockerjava.api.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Represents a network link between two Docker containers. The container with * the name {@link #getName()} is made available in the target container with * the aliased name {@link #getAlias()}. This involves creating an entry in * <code>/etc/hosts</code> and some environment variables in the target * container as well as creating a network bridge between both containers. */ public class Link { private final String name; private final String alias; /** * Creates a {@link Link} for the container with the given name and an * aliased name for use in the target container. * * @param name * the name of the container that you want to link into the * target container * @param alias * the aliased name under which the linked container will be * available in the target container */ public Link(final String name, final String alias) { this.name = name; this.alias = alias; } /** * @return the name of the container that is linked into the target * container */ public String getName() { return name; } /** * @return the aliased name under which the linked container will be * available in the target container */ public String getAlias() { return alias; } /** * Parses a textual link specification (as used by the Docker CLI) to a * {@link Link}. * * @param serialized * the specification, e.g. <code>name:alias</code> or * <code>/name1:/name2/alias</code> * @return a {@link Link} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ public static Link parse(final String serialized) throws IllegalArgumentException { try { final String[] parts = serialized.split(":"); switch (parts.length) { case 2: { String[] nameSplit = parts[0].split("/"); String[] aliasSplit = parts[1].split("/"); return new Link(nameSplit[nameSplit.length - 1], aliasSplit[aliasSplit.length - 1]); } default: { throw new IllegalArgumentException(); } } } catch (final Exception e) { throw new IllegalArgumentException("Error parsing Link '" + serialized + "'"); } } @Override public boolean equals(final Object obj) { if (obj instanceof Link) { final Link other = (Link) obj; return new EqualsBuilder().append(name, other.getName()).append(alias, other.getAlias()).isEquals(); } else return super.equals(obj); } @Override public int hashCode() { return new HashCodeBuilder().append(name).append(alias).toHashCode(); } /** * Returns a string representation of this {@link Link} suitable for * inclusion in a JSON message. The format is <code>name:alias</code>, like * the argument in {@link #parse(String)}. * * @return a string representation of this {@link Link} */ @Override public String toString() { return name + ":" + alias; } }
#!/bin/bash ################################################################################ # Helper functions # ################################################################################ answer_is_yes() { [[ "$REPLY" =~ ^[Yy]$ ]] \ && return 0 \ || return 1 } ask() { print_question "$1" read } ask_for_confirmation() { print_question "$1 [y/n] " read } print_question() { # Print output in yellow printf "\e[0;33m $1 \e[0m" } ################################################################################ # Dotfiles management functions # ################################################################################ # Backup existing dotfiles into the DOTFILES_BACKUP_DIR directory. backup_dotfiles() { echo "Backing up existing dotfiles from ~ to $DOTFILES_BACKUP_DIR" mkdir -p $DOTFILES_BACKUP_DIR for i in ${FILES_TO_SYMLINK[@]}; do mv -f ~/.${i##*/} $DOTFILES_BACKUP_DIR done } # Create symbolic links. create_dotfiles_symlinks() { backup_dotfiles for i in ${FILES_TO_SYMLINK[@]}; do source="$DOTFILES_DIR/$i" target="$HOME/.$(printf "%s" "$i" | sed "s/.*\/\(.*\)/\1/g")" ln -fs $source $target done } ################################################################################ # Atom package management # ################################################################################ list_atom_packages() { apm list --installed --bare } install_atom_packages() { apm install --packages-file $DOTFILES_DIR/.atom/packages.list } ################################################################################ # Main script # ################################################################################ # Set the dotfiles directory in order to run this script from anywhere. pushd `dirname $0` > /dev/null DOTFILES_DIR=`pwd` popd > /dev/null DOTFILES_BACKUP_DIR=~/dotfiles_old declare -a FILES_TO_SYMLINK=( 'atom' 'git/gitconfig' ) main() { ask_for_confirmation "Backup and override existing dotfiles?" if answer_is_yes; then create_dotfiles_symlinks fi ask_for_confirmation "Install brew?" if answer_is_yes; then . install/brew.sh fi ask_for_confirmation "Install brew cask and its applications" if answer_is_yes; then . install/brew-cask.sh fi ask_for_confirmation "Install atom packages?" if answer_is_yes; then install_atom_packages fi } main
<gh_stars>1-10 package com.dodola.jvmti; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; import com.dodola.jvmtilib.JVMTIHelper; public class Main2Activity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } @Override protected void onResume() { super.onResume(); JVMTIHelper.setTag(Main2Activity.this); Toast.makeText(this, "给Main2Activity对象设置tag 成功", Toast.LENGTH_LONG).show(); } }
package com.testproj.sportapp.web; import static com.testproj.sportapp.UserTestData.ADMIN; import static com.testproj.sportapp.UserTestData.USER; import com.testproj.sportapp.UserTestData; import com.testproj.sportapp.model.User; import com.testproj.sportapp.repository.UserRepository; import com.testproj.sportapp.util.exception.NotFoundException; import com.testproj.sportapp.web.user.AdminRestController; import java.util.Arrays; import java.util.Collection; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AdminInMemoryTest { private static ConfigurableApplicationContext appCtx; private static AdminRestController controller; @BeforeClass public static void beforeClass() { appCtx = new ClassPathXmlApplicationContext("spring/spring-app.xml","spring/mock.xml"); System.out.println("\n" + Arrays.toString(appCtx.getBeanDefinitionNames()) + "\n"); controller = appCtx.getBean(AdminRestController.class); } @Before public void setUp() throws Exception { UserRepository repository = appCtx.getBean(UserRepository.class); repository.save(USER); repository.save(ADMIN); } @AfterClass public static void afterClass() { appCtx.close(); } @Test public void testDelete() throws Exception { controller.delete(UserTestData.USER_ID); Collection<User> users = controller.getAll(); Assert.assertEquals(users.size(), 1); Assert.assertEquals(users.iterator().next(), ADMIN); } @Test(expected = NotFoundException.class) public void testDeleteNotFound() throws Exception { controller.delete(10); } }
<reponame>thewizardplusplus/wizard-basic #ifndef MATHS_H #define MATHS_H namespace thewizardplusplus { namespace wizard_basic { namespace framework { namespace maths { extern "C" { float NumberAdd(float number2, float number1); float NumberSub(float number2, float number1); float NumberMul(float number2, float number1); float NumberDiv(float number2, float number1); float NumberLs(float number2, float number1); float NumberGt(float number2, float number1); float NumberEq(float number2, float number1); float NumberAnd(float number2, float number1); float NumberOr(float number2, float number1); float NumberNot(float number); float MathsSin(float number); float MathsCos(float number); float MathsTg(float number); float MathsArcsin(float number); float MathsArccos(float number); float MathsArctg(float number); float MathsExp(float number); float MathsLn(float number); float MathsLg(float number); float MathsModulus(float number); float MathsPower(float exponent, float base); float MathsIntegral(float number); float MathsSquareRoot(float number); float MathsAngle(float y, float x); float MathsRandom(float maximum, float minimum); } } } } } #endif
#!/bin/bash source /home/pi/allsky/config.sh echo "Posting Next Twilight Time" today=`date +%Y-%m-%d` time="$(sunwait list set civil 60.7N 135.02W)" timeNoZone=${time:0:5} echo {\"sunset\": \"$today"T"$timeNoZone":00.000-0800"\"} > data.json echo "Uploading data.json" lftp "$PROTOCOL"://"$USER":"$PASSWORD"@"$HOST":"$IMGDIR" -e "set net:max-retries 1; set net:timeout 20; put data.json; bye"
import moment from 'moment'; import React from 'react'; import { Link } from 'react-router-dom'; import { formatDate } from './Dashboard'; function Table(props) { const { classN, headers, body } = props; const keys = ['id', 'start_date', 'end_date', 'name', 'location', 'is_open'] return ( <table className={`table ${classN.table}`}> <thead className={classN.thead}> <tr> {headers.map(h => (<th>{h}</th>))} </tr> </thead> <tbody> {body.map((hackathon, index) => ( <tr key={index}> {keys.map(property => ( (property.includes('date')) ? ( <td>{formatDate(hackathon[property])}</td> ) : (property.includes('name')) ? (<td><Link to={`/dashboard/view/${hackathon['id']}`}>{hackathon[property]}</Link></td>) : (<td>{hackathon[property]}</td>) ))} </tr> ))} </tbody> </table> ); } export default Table;
'use strict'; const express = require('express'); const router = express.Router(); const options = require('../grove-node-server-utils/options')(); const authProvider = require('../grove-node-server-utils/auth-helper'); const enableLegacyProxy = true; // TODO: expose this as an env option router.use('/api', require('./api')); // This is a legacy proxy to the MarkLogic REST API. // Best practice is to create endpoints in this middle-tier and to // avoid directly calling MarkLogic APIs from the UI. // But sometimes, particularly for demos and PoCs, it is helpful // to punch through the middle-tier. // // A minimum of proxies are setup by default, and we will eventually // replace those with Grove middle-tier endpoints. // // Further down in this file, you will find more examples // of other proxies that can be setup. if (enableLegacyProxy) { router.use( /\/v1|\/LATEST/, require('../grove-legacy-routes').whitelistProxyRoute({ authProvider: authProvider, whitelist: [ { endpoint: '/suggest', methods: ['get', 'post'], authed: true // return 401 if user not authenticated to middle-tier // when `authed: false`, will authenticate proxied request if the // user is authenticated. If not authenticated, it will still allow // a request without authentication. }, // Follow this pattern for other REST extensions { endpoint: '/resources/*', methods: ['get'], authed: true } // TODO: move this to visjs documentation for visjs-graph // Other possibilities: // { // endpoint: '/config/query/*', // methods: ['get'], // authed: true // }, // { // endpoint: '/graphs/sparql', // methods: ['get', 'post'], // authed: true // }, // { // endpoint: '/search', // methods: ['get', 'post'], // authed: true // }, // { // endpoint: '/values/*', // methods: ['get', 'post'], // authed: true // }, // { // endpoint: '/documents', // methods: ['get'], // authed: true // }, // { // endpoint: '/documents', // methods: ['all'], // authed: true, // update: true // }, // { // endpoint: '/resources/*', // NOTE: allows get on all extensions // methods: ['get'], // authed: true // }, // { // endpoint: '/resources/*', // NOTE: this is for put, post, delete // // which fall through after the 'get' above // // CAUTION: exposes all REST extensions, even future ones // methods: ['all'], // authed: true, // update: true // } ] }) ); } // This sets up this middle-tier to serve static assets found in the // directory specified by GROVE_UI_BUILD_PATH (if that is set). // // If you will never use this middle-tier to serve such assets (for // example, if you are following the best practice of using a reverse proxy // like Nginx or HAProxy to serve them instead), you can remove these lines. if (options.staticUIDirectory) { router.use( require('../grove-default-routes').defaultStaticRoute({ staticUIDirectory: options.staticUIDirectory }) ); } // error handling router.use(function(error, req, res, next) { res.status(500).json({ message: error.toString() }); }); module.exports = router;
import * as ts from 'typescript'; import { ClassNode } from './elements/class-node'; import { ConstructorNode } from './elements/constructor-node'; import { ElementNode } from './elements/element-node'; import { EnumNode } from './elements/enum-node'; import { FunctionNode } from './elements/function-node'; import { GetterNode } from './elements/getter-node'; import { ImportNode } from './elements/import-node'; import { IndexNode } from './elements/index-node'; import { IndexSignatureNode } from './elements/index-signature-node'; import { InterfaceNode } from './elements/interface-node'; import { MethodNode } from './elements/method-node'; import { MethodSignatureNode } from './elements/method-signature-node'; import { PropertyNode } from './elements/property-node'; import { PropertySignatureNode } from './elements/property-signature-node'; import { SetterNode } from './elements/setter-node'; import { TypeAliasNode } from './elements/type-alias-node'; export class Transformer { public analyzeSyntaxTree(sourceFile: ts.SourceFile) { let elements: ElementNode[] = []; // analyze ast for (let node of sourceFile.getChildren(sourceFile)) { this.visitSyntaxTree(elements, node, sourceFile); } return elements; } private visitSyntaxTree(elements: ElementNode[], node: ts.Node, sourceFile: ts.SourceFile) { if (ts.isImportDeclaration(node)) { elements.push(new ImportNode(sourceFile, node)); } if (ts.isTypeAliasDeclaration(node)) { elements.push(new TypeAliasNode(sourceFile, node)); } else if (ts.isInterfaceDeclaration(node)) { elements.push(new InterfaceNode(sourceFile, node)); for (let member of node.members) { if (ts.isPropertySignature(member)) { (<InterfaceNode>elements[elements.length - 1]).properties.push(new PropertySignatureNode(sourceFile, member)); } else if (ts.isIndexSignatureDeclaration(member)) { (<InterfaceNode>elements[elements.length - 1]).indexes.push(new IndexSignatureNode(sourceFile, member)); } else if (ts.isMethodSignature(member)) { (<InterfaceNode>elements[elements.length - 1]).methods.push(new MethodSignatureNode(sourceFile, member)); } } } else if (ts.isClassDeclaration(node)) { elements.push(new ClassNode(sourceFile, node)); for (let member of node.members) { if (ts.isConstructorDeclaration(member)) { (<ClassNode>elements[elements.length - 1]).constructors.push(new ConstructorNode(sourceFile, member)); } else if (ts.isPropertyDeclaration(member)) { if (member.initializer?.kind === ts.SyntaxKind.ArrowFunction) { (<ClassNode>elements[elements.length - 1]).methods.push(new PropertyNode(sourceFile, member)); } else { (<ClassNode>elements[elements.length - 1]).properties.push(new PropertyNode(sourceFile, member)); } } else if (ts.isGetAccessorDeclaration(member)) { (<ClassNode>elements[elements.length - 1]).getters.push(new GetterNode(sourceFile, member)); } else if (ts.isSetAccessorDeclaration(member)) { (<ClassNode>elements[elements.length - 1]).setters.push(new SetterNode(sourceFile, member)); } else if (ts.isMethodDeclaration(member)) { (<ClassNode>elements[elements.length - 1]).methods.push(new MethodNode(sourceFile, member)); } else if (ts.isIndexedAccessTypeNode(member)) { (<ClassNode>elements[elements.length - 1]).indexes.push(new IndexNode(sourceFile, member)); } } } else if (ts.isEnumDeclaration(node)) { elements.push(new EnumNode(sourceFile, node)); } else if (ts.isFunctionDeclaration(node)) { elements.push(new FunctionNode(sourceFile, node)); } else { for (let childNode of node.getChildren(sourceFile)) { this.visitSyntaxTree(elements, childNode, sourceFile); } } return elements; } }
package api; import java.util.*; import java.util.Collections; /** * @Description: 一定要知道的api * @Author: 01401951 * @Date: 2021/7/27 **/ public class MustKnowApi { public static void main(String[] args) { SortApi.sort(); MathApi.math(); SubListApi.sub(); } } /** * 排序API */ class SortApi { /** * 减号可以看做大于号 */ public static void sort() { // 数字正序排序 Collections.sort(Data.numbers); System.out.println("数字正序排序:" + Data.numbers); // 数字逆序排序 Collections.sort(Data.numbers, (a, b) -> b - a); System.out.println("数字逆序排序:" + Data.numbers); // 对象正序排序 Collections.sort(Data.nodes, (a, b) -> a.getNumber() - b.getNumber()); System.out.println("对象正序排序:" + Data.nodes); // 对象逆序排序 Collections.sort(Data.nodes, (a, b) -> b.getNumber() - a.getNumber()); System.out.println("对象逆序排序:" + Data.nodes); } } /** * 数学API */ class MathApi { /** * 数学类的api */ public static void math() { // 绝对值 int abs = Math.abs(-1); System.out.println(abs); // power的缩写,power还有乘方的意思。为了兼容小数输出一定为double double pow = Math.pow(2, 2); System.out.println(pow); // 开2次方根 要记得加上d哦 double gen = Math.pow(8, 1d / 3d); System.out.println(gen); } } /** * 截断API */ class SubListApi { public static void sub() { List<Integer> list = Arrays.asList(27, 59, 8, 72, 19, 8758, 1, 29); // 左闭右开 List<Integer> sub = list.subList(0, 2); System.out.println(sub); // sub里的值改变会影响list里的值 sub.set(0, 3); System.out.println(list); } }
pragma solidity ^0.4.23; contract Auction { // defines the auction start timestamp uint startTimestamp; // defines the auction end timestamp uint endTimestamp; // defines the auction winner address address seller; // defines the seller's bid uint sellerBid; // defines the current bid uint currentBid; // define the current highest bidder address currentBidder; // defines the auction item description string description; function Auction(uint startTime, uint endTime, address _seller, string _description) public { startTimestamp = startTime; endTimestamp = endTime; seller = _seller; description = _description; sellerBid = 0; currentBid = 0; } // allows a user to make a bid on the auction item function bid(address _bidder, uint _bid) public { // checks if the auction is still open require(now < endTimestamp); // checks if the bid is higher than the seller's bid require(_bid > sellerBid); // checks if the bid is higher than the current highest bid require(_bid > currentBid); // sets the current highest bidder currentBidder = _bidder; // sets the current highest bid amount currentBid = _bid; } // returns the highest bidder's address function getCurrentHighBidder() public view returns (address) { return currentBidder; } // returns the highest bid amount function getCurrentHighBid() public view returns (uint) { return currentBid; } }
#!/bin/bash cd projects/build && cmake .. && make
<gh_stars>1-10 /** * Copyright 2021 Shulie Technology, Co.Ltd * Email: <EMAIL> * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.shulie.instrument.simulator.core.classloader; import com.shulie.instrument.simulator.api.annotation.Stealth; import com.shulie.instrument.simulator.core.util.ReflectUtils; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Collection; import java.util.Vector; import java.util.jar.JarFile; /** * 服务提供库ClassLoader */ @Stealth public class ProviderClassLoader extends RoutingURLClassLoader { private final Logger logger = LoggerFactory.getLogger(getClass()); private File providerJarFile; public ProviderClassLoader(final File providerJarFile, final ClassLoader simulatorClassLoader) throws IOException { super( new URL[]{new URL("file:" + providerJarFile.getCanonicalPath())}, new Routing( simulatorClassLoader, "com.shulie.instrument.simulator.api.*", "com.shulie.instrument.simulator.spi.*", "org.apache.commons.lang.*", "org.slf4j.*", "ch.qos.logback.*", "org.objectweb.asm.*", "javax.annotation.Resource*" ) ); this.providerJarFile = providerJarFile; } public void closeIfPossible() { try { // 如果是JDK7+的版本, URLClassLoader实现了Closeable接口,直接调用即可 if (this instanceof Closeable) { if (logger.isDebugEnabled()) { logger.debug("SIMULATOR: JDK is 1.7+, use URLClassLoader[file={}].close()", providerJarFile); } try { ((Closeable) this).close(); } catch (Throwable cause) { logger.warn("SIMULATOR: close ProviderClassLoader[file={}] failed. JDK7+", providerJarFile, cause); } if (routingArray != null) { for (Routing routing : routingArray) { routing.clean(); } routingArray = null; } releaseClasses(); return; } // 对于JDK6的版本,URLClassLoader要关闭起来就显得有点麻烦,这里弄了一大段代码来稍微处理下 // 而且还不能保证一定释放干净了,至少释放JAR文件句柄是没有什么问题了 try { if (logger.isDebugEnabled()) { logger.debug("SIMULATOR: JDK is less then 1.7+, use File.release()"); } final Object ucp = ReflectUtils.getDeclaredJavaFieldValueUnCaught(URLClassLoader.class, "ucp", this); final Object loaders = ReflectUtils.getDeclaredJavaFieldValueUnCaught(ucp.getClass(), "loaders", ucp); for (Object loader : ((Collection) loaders).toArray()) { try { final JarFile jarFile = ReflectUtils.getDeclaredJavaFieldValueUnCaught( loader.getClass(), "jar", loader ); jarFile.close(); } catch (Throwable t) { // if we got this far, this is probably not a JAR loader so skip it } } if (routingArray != null) { for (Routing routing : routingArray) { routing.clean(); } routingArray = null; } releaseClasses(); } catch (Throwable cause) { logger.warn("SIMULATOR: close ProviderClassLoader[file={}] failed. probably not a HOTSPOT VM", providerJarFile, cause); } } finally { // 在这里删除掉临时文件 FileUtils.deleteQuietly(providerJarFile); classLoadingLock.release(); } } private void releaseClasses() { try { final Object classes = ReflectUtils.getDeclaredJavaFieldValueUnCaught(ClassLoader.class, "classes", this); if (classes == null) { return; } if (!(classes instanceof Vector)) { return; } ((Vector) classes).clear(); } catch (Throwable e) { } } }
#!/bin/sh EMAIL=$(git config user.email) if [ $EMAIL == *"alibaba-inc"* ] || [ $EMAIL == *"taobao"* ] then echo "email with *.alibaba-inc.com or *.taobao.com are not allowed"; exit 1; else echo ""; fi;
def _encode(char, offset): char_code = ord(char) new_char_code = char_code + offset return chr(new_char_code) def encode_string(string, offset): encoded_string = "" for char in string: encoded_string += _encode(char, offset) return encoded_string
#!/bin/bash # OpenVPN road warrior installer for Debian, Ubuntu and CentOS # This script will work on Debian, Ubuntu, CentOS and probably other distros # of the same families, although no support is offered for them. It isn't # bulletproof but it will probably work if you simply want to setup a VPN on # your Debian/Ubuntu/CentOS box. It has been designed to be as unobtrusive and # universal as possible. # Detect Debian users running the script with "sh" instead of bash if readlink /proc/$$/exe | grep -qs "dash"; then echo "This script needs to be run with bash, not sh" exit 1 fi if [[ "$EUID" -ne 0 ]]; then echo "Sorry, you need to run this as root" exit 2 fi if [[ ! -e /dev/net/tun ]]; then echo "TUN is not available" exit 3 fi if grep -qs "CentOS release 5" "/etc/redhat-release"; then echo "CentOS 5 is too old and not supported" exit 4 fi if [[ -e /etc/debian_version ]]; then OS=debian GROUPNAME=nogroup RCLOCAL='/etc/rc.local' elif [[ -e /etc/centos-release || -e /etc/redhat-release ]]; then OS=centos GROUPNAME=nobody RCLOCAL='/etc/rc.d/rc.local' else echo "Looks like you aren't running this installer on a Debian, Ubuntu or CentOS system" exit 5 fi newclient () { # Generates the custom client.ovpn cp /etc/openvpn/client-common.txt ~/$1.ovpn echo "<ca>" >> ~/$1.ovpn cat /etc/openvpn/easy-rsa/pki/ca.crt >> ~/$1.ovpn echo "</ca>" >> ~/$1.ovpn echo "<cert>" >> ~/$1.ovpn cat /etc/openvpn/easy-rsa/pki/issued/$1.crt >> ~/$1.ovpn echo "</cert>" >> ~/$1.ovpn echo "<key>" >> ~/$1.ovpn cat /etc/openvpn/easy-rsa/pki/private/$1.key >> ~/$1.ovpn echo "</key>" >> ~/$1.ovpn echo "<tls-auth>" >> ~/$1.ovpn cat /etc/openvpn/ta.key >> ~/$1.ovpn echo "</tls-auth>" >> ~/$1.ovpn } # Try to get our IP from the system and fallback to the Internet. # I do this to make the script compatible with NATed servers (lowendspirit.com) # and to avoid getting an IPv6. IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) if [[ "$IP" = "" ]]; then IP=$(wget -4qO- "http://whatismyip.akamai.com/") fi if [[ -e /etc/openvpn/server.conf ]]; then while : do clear echo "Looks like OpenVPN is already installed" echo "" echo "What do you want to do?" echo " 1) Add a new user" echo " 2) Revoke an existing user" echo " 3) Remove OpenVPN" echo " 4) Exit" read -p "Select an option [1-4]: " option case $option in 1) echo "" echo "Tell me a name for the client certificate" echo "Please, use one word only, no special characters" read -p "Client name: " -e -i client CLIENT cd /etc/openvpn/easy-rsa/ ./easyrsa build-client-full $CLIENT nopass # Generates the custom client.ovpn newclient "$CLIENT" echo "" echo "Client $CLIENT added, configuration is available at" ~/"$CLIENT.ovpn" exit ;; 2) # This option could be documented a bit better and maybe even be simplimplified # ...but what can I say, I want some sleep too NUMBEROFCLIENTS=$(tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep -c "^V") if [[ "$NUMBEROFCLIENTS" = '0' ]]; then echo "" echo "You have no existing clients!" exit 6 fi echo "" echo "Select the existing client certificate you want to revoke" tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | nl -s ') ' if [[ "$NUMBEROFCLIENTS" = '1' ]]; then read -p "Select one client [1]: " CLIENTNUMBER else read -p "Select one client [1-$NUMBEROFCLIENTS]: " CLIENTNUMBER fi CLIENT=$(tail -n +2 /etc/openvpn/easy-rsa/pki/index.txt | grep "^V" | cut -d '=' -f 2 | sed -n "$CLIENTNUMBER"p) cd /etc/openvpn/easy-rsa/ ./easyrsa --batch revoke $CLIENT ./easyrsa gen-crl rm -rf pki/reqs/$CLIENT.req rm -rf pki/private/$CLIENT.key rm -rf pki/issued/$CLIENT.crt rm -rf /etc/openvpn/crl.pem cp /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn/crl.pem # CRL is read with each client connection, when OpenVPN is dropped to nobody chown nobody:$GROUPNAME /etc/openvpn/crl.pem echo "" echo "Certificate for client $CLIENT revoked" exit ;; 3) echo "" read -p "Do you really want to remove OpenVPN? [y/n]: " -e -i n REMOVE if [[ "$REMOVE" = 'y' ]]; then PORT=$(grep '^port ' /etc/openvpn/server.conf | cut -d " " -f 2) PROTOCOL=$(grep '^proto ' /etc/openvpn/server.conf | cut -d " " -f 2) IP=$(grep 'iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to ' $RCLOCAL | cut -d " " -f 11) if pgrep firewalld; then # Using both permanent and not permanent rules to avoid a firewalld reload. firewall-cmd --zone=public --remove-port=$PORT/$PROTOCOL firewall-cmd --zone=trusted --remove-source=10.8.0.0/24 firewall-cmd --permanent --zone=public --remove-port=$PORT/$PROTOCOL firewall-cmd --permanent --zone=trusted --remove-source=10.8.0.0/24 fi if iptables -L -n | grep -qE 'REJECT|DROP|ACCEPT'; then iptables -D INPUT -p $PROTOCOL --dport $PORT -j ACCEPT iptables -D FORWARD -s 10.8.0.0/24 -j ACCEPT iptables -D FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT sed -i "/iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT/d" $RCLOCAL sed -i "/iptables -I FORWARD -s 10.8.0.0\/24 -j ACCEPT/d" $RCLOCAL sed -i "/iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT/d" $RCLOCAL fi iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP sed -i '/iptables -t nat -A POSTROUTING -s 10.8.0.0\/24 -j SNAT --to /d' $RCLOCAL if hash sestatus 2>/dev/null; then if sestatus | grep "Current mode" | grep -qs "enforcing"; then if [[ "$PORT" != '1194' || "$PROTOCOL" = 'tcp' ]]; then semanage port -d -t openvpn_port_t -p $PROTOCOL $PORT fi fi fi if [[ "$OS" = 'debian' ]]; then apt-get remove --purge -y openvpn openvpn-blacklist else yum remove openvpn -y fi rm -rf /etc/openvpn rm -rf /usr/share/doc/openvpn* echo "" echo "OpenVPN removed!" else echo "" echo "Removal aborted!" fi exit ;; 4) exit;; esac done else clear echo 'Welcome to this quick OpenVPN "road warrior" installer' echo "" # OpenVPN setup and first user creation echo "I need to ask you a few questions before starting the setup" echo "You can leave the default options and just press enter if you are ok with them" echo "" echo "First I need to know the IPv4 address of the network interface you want OpenVPN" echo "listening to." read -p "IP address: " -e -i $IP IP echo "" echo "Which protocol do you want for OpenVPN connections?" echo " 1) UDP (recommended)" echo " 2) TCP" read -p "Protocol [1-2]: " -e -i 1 PROTOCOL case $PROTOCOL in 1) PROTOCOL=udp ;; 2) PROTOCOL=tcp ;; esac echo "" echo "What port do you want OpenVPN listening to?" read -p "Port: " -e -i 1194 PORT echo "" echo "Which DNS do you want to use with the VPN?" echo " 1) Current system resolvers" echo " 2) Google" echo " 3) OpenDNS" echo " 4) NTT" echo " 5) Hurricane Electric" echo " 6) Verisign" read -p "DNS [1-6]: " -e -i 1 DNS echo "" echo "Finally, tell me your name for the client certificate" echo "Please, use one word only, no special characters" read -p "Client name: " -e -i client CLIENT echo "" echo "Okay, that was all I needed. We are ready to setup your OpenVPN server now" read -n1 -r -p "Press any key to continue..." if [[ "$OS" = 'debian' ]]; then apt-get update apt-get install openvpn iptables openssl ca-certificates -y else # Else, the distro is CentOS yum install epel-release -y yum install openvpn iptables openssl wget ca-certificates -y fi # An old version of easy-rsa was available by default in some openvpn packages if [[ -d /etc/openvpn/easy-rsa/ ]]; then rm -rf /etc/openvpn/easy-rsa/ fi # Get easy-rsa wget -O ~/EasyRSA-3.0.1.tgz "https://github.com/OpenVPN/easy-rsa/releases/download/3.0.1/EasyRSA-3.0.1.tgz" tar xzf ~/EasyRSA-3.0.1.tgz -C ~/ mv ~/EasyRSA-3.0.1/ /etc/openvpn/ mv /etc/openvpn/EasyRSA-3.0.1/ /etc/openvpn/easy-rsa/ chown -R root:root /etc/openvpn/easy-rsa/ rm -rf ~/EasyRSA-3.0.1.tgz cd /etc/openvpn/easy-rsa/ # Create the PKI, set up the CA, the DH params and the server + client certificates ./easyrsa init-pki ./easyrsa --batch build-ca nopass ./easyrsa gen-dh ./easyrsa build-server-full server nopass ./easyrsa build-client-full $CLIENT nopass ./easyrsa gen-crl # Move the stuff we need cp pki/ca.crt pki/private/ca.key pki/dh.pem pki/issued/server.crt pki/private/server.key /etc/openvpn/easy-rsa/pki/crl.pem /etc/openvpn # CRL is read with each client connection, when OpenVPN is dropped to nobody chown nobody:$GROUPNAME /etc/openvpn/crl.pem # Generate key for tls-auth openvpn --genkey --secret /etc/openvpn/ta.key # Generate server.conf echo "port $PORT proto $PROTOCOL dev tun sndbuf 0 rcvbuf 0 ca ca.crt cert server.crt key server.key dh dh.pem tls-auth ta.key 0 topology subnet server 10.8.0.0 255.255.255.0 ifconfig-pool-persist ipp.txt" > /etc/openvpn/server.conf echo 'push "redirect-gateway def1 bypass-dhcp"' >> /etc/openvpn/server.conf # DNS case $DNS in 1) # Obtain the resolvers from resolv.conf and use them for OpenVPN grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do echo "push \"dhcp-option DNS $line\"" >> /etc/openvpn/server.conf done ;; 2) echo 'push "dhcp-option DNS 8.8.8.8"' >> /etc/openvpn/server.conf echo 'push "dhcp-option DNS 8.8.4.4"' >> /etc/openvpn/server.conf ;; 3) echo 'push "dhcp-option DNS 208.67.222.222"' >> /etc/openvpn/server.conf echo 'push "dhcp-option DNS 208.67.220.220"' >> /etc/openvpn/server.conf ;; 4) echo 'push "dhcp-option DNS 129.250.35.250"' >> /etc/openvpn/server.conf echo 'push "dhcp-option DNS 129.250.35.251"' >> /etc/openvpn/server.conf ;; 5) echo 'push "dhcp-option DNS 74.82.42.42"' >> /etc/openvpn/server.conf ;; 6) echo 'push "dhcp-option DNS 64.6.64.6"' >> /etc/openvpn/server.conf echo 'push "dhcp-option DNS 64.6.65.6"' >> /etc/openvpn/server.conf ;; esac echo "keepalive 10 120 cipher AES-256-CBC comp-lzo user nobody group $GROUPNAME persist-key persist-tun status openvpn-status.log verb 3 crl-verify crl.pem" >> /etc/openvpn/server.conf # Enable net.ipv4.ip_forward for the system sed -i '/\<net.ipv4.ip_forward\>/c\net.ipv4.ip_forward=1' /etc/sysctl.conf if ! grep -q "\<net.ipv4.ip_forward\>" /etc/sysctl.conf; then echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf fi # Avoid an unneeded reboot echo 1 > /proc/sys/net/ipv4/ip_forward # Needed to use rc.local with some systemd distros if [[ "$OS" = 'debian' && ! -e $RCLOCAL ]]; then echo '#!/bin/sh -e exit 0' > $RCLOCAL fi chmod +x $RCLOCAL # Set NAT for the VPN subnet iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP sed -i "1 a\iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to $IP" $RCLOCAL if pgrep firewalld; then # We don't use --add-service=openvpn because that would only work with # the default port and protocol. Using both permanent and not permanent # rules to avoid a firewalld reload. firewall-cmd --zone=public --add-port=$PORT/$PROTOCOL firewall-cmd --zone=trusted --add-source=10.8.0.0/24 firewall-cmd --permanent --zone=public --add-port=$PORT/$PROTOCOL firewall-cmd --permanent --zone=trusted --add-source=10.8.0.0/24 fi if iptables -L -n | grep -qE 'REJECT|DROP'; then # If iptables has at least one REJECT rule, we asume this is needed. # Not the best approach but I can't think of other and this shouldn't # cause problems. iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT sed -i "1 a\iptables -I INPUT -p $PROTOCOL --dport $PORT -j ACCEPT" $RCLOCAL sed -i "1 a\iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT" $RCLOCAL sed -i "1 a\iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT" $RCLOCAL fi # If SELinux is enabled and a custom port or TCP was selected, we need this if hash sestatus 2>/dev/null; then if sestatus | grep "Current mode" | grep -qs "enforcing"; then if [[ "$PORT" != '1194' || "$PROTOCOL" = 'tcp' ]]; then # semanage isn't available in CentOS 6 by default if ! hash semanage 2>/dev/null; then yum install policycoreutils-python -y fi semanage port -a -t openvpn_port_t -p $PROTOCOL $PORT fi fi fi # And finally, restart OpenVPN if [[ "$OS" = 'debian' ]]; then # Little hack to check for systemd if pgrep systemd-journal; then systemctl restart openvpn@server.service else /etc/init.d/openvpn restart fi else if pgrep systemd-journal; then systemctl restart openvpn@server.service systemctl enable openvpn@server.service else service openvpn restart chkconfig openvpn on fi fi # Try to detect a NATed connection and ask about it to potential LowEndSpirit users EXTERNALIP=$(wget -4qO- "http://whatismyip.akamai.com/") if [[ "$IP" != "$EXTERNALIP" ]]; then echo "" echo "Looks like your server is behind a NAT!" echo "" echo "If your server is NATed (e.g. LowEndSpirit), I need to know the external IP" echo "If that's not the case, just ignore this and leave the next field blank" read -p "External IP: " -e USEREXTERNALIP if [[ "$USEREXTERNALIP" != "" ]]; then IP=$USEREXTERNALIP fi fi # client-common.txt is created so we have a template to add further users later echo "client dev tun proto $PROTOCOL sndbuf 0 rcvbuf 0 remote $IP $PORT resolv-retry infinite nobind persist-key persist-tun remote-cert-tls server cipher AES-256-CBC comp-lzo setenv opt block-outside-dns key-direction 1 verb 3" > /etc/openvpn/client-common.txt # Generates the custom client.ovpn newclient "$CLIENT" echo "" echo "Finished!" echo "" echo "Your client configuration is available at" ~/"$CLIENT.ovpn" echo "If you want to add more clients, you simply need to run this script again!" fi
// // LSEManufacturerInfo.h // LSWearable // // Created by lshenrong on 17/3/13. // Copyright © 2017年 lifesense. All rights reserved. // 心率预警设置 #import <Foundation/Foundation.h> @interface LSEManufacturerInfo : NSObject /** 厂商id*/ @property (nonatomic ,strong) NSString *manufacturerId; /** 厂商名称*/ @property (nonatomic ,strong) NSString *manufacturerName; /** 厂商电话*/ @property (nonatomic ,strong) NSString *manufacturerPhone; /** 厂商地址*/ @property (nonatomic ,strong) NSString *manufacturerAdress; /** 备注*/ @property (nonatomic ,strong) NSString *manufacturerMemo; /** 创建时间*/ @property (nonatomic ,strong) NSDate *created; /** 修改时间*/ @property (nonatomic ,strong) NSDate *updated; @end
#!/bin/sh # simple-kubernetes-test-environment # # Copyright (c) 2018 VMware, Inc. All Rights Reserved. # # This product is licensed to you under the Apache 2.0 license (the "License"). # You may not use this product except in compliance with the Apache 2.0 License. # # This product may include a number of subcomponents with separate copyright # notices and license terms. Your use of these subcomponents is subject to the # terms and conditions of the subcomponent's license, as noted in the LICENSE # file. # posix compliant # verified by https://www.shellcheck.net # # A commons library for the Vagrant shell scripts. # set -e set -o pipefail usage() { cat <<EOF usage: ${0} FLAGS ${PROGRAM} This program wraps ${PROGRAM} with some flags specific to sk8. After the sk8 flags and their arguments are provided, ${PROGRAM} is exec'd with the remainder of the command line. FLAGS -k K8S The version of Kubernetes to install. Please see the section KUBERNETES VERSION for accepted versions. The default value is "release/stable". -b BOX Valid box types include: "photon", "centos", and "ubuntu". The default value is "ubuntu". -c CPU The number of CPUs to assign to each box. The default value is "1". -m MEM The amount of memory (MiB) to assign to each box. The default value is "1024". -p PROVIDER Valid providers are: "virtualbox" and "vmware". The default value is "virtualbox". -v Enables the vSphere cloud provider and directs it to use the vCenter simulator. -1 Provision a single-node cluster c01 Controller+Worker -2 Provision a two-node cluster c01 Controller w01 Worker -3 Provision a three-node cluster c01 Controller c02 Controller+Worker w01 Worker KUBERNETES VERSION The -k flag specifies the version of Kubernetes to install. If the value "local" is used, the following local paths are checked and replaces "local" as the Kuberentes version if they exist: * ${GOPATH}/src/k8s.io/kubernetes * ${HOME}/go/src/k8s.io/kubernetes If the Kubernetes version is set to a filesystem path then this program mounts the path into the VM(s) as "/var/lib/kubernetes/install/local" and set the Kubernetes version to "file:///var/lib/kubernetes/install/local". The sk8 process executing inside of the VM(s) checks to see if the configured Kubernetes version begins with "file://". If it does, sk8 processes the contents of the directory using the ascribed manner: 1. An attempt is made to locate the following release tarballs: * kubernetes-client-linux-amd64.tar.gz * kubernetes-node-linux-amd64.tar.gz * kubernetes-server-linux-amd64.tar.gz * kubernetes-test-linux-amd64.tar.gz 2. An attempt is made to locate the following binaries: * kubectl * kube-apiserver * kube-controller-manager * kube-scheduler * kubelet * kube-proxy * e2e.test If multiple copies of the same file are discovered the newest copy is used. Files from step two will overwrite their equivalents inside of any tarballs discovered in step one as long as the copy from step two is newer. Plesae note that only the CentOS and Ubuntu box types support deploying a local Kubernetes build. This is because there is no PhotonOS box in the Vagrant registry that includes support for mounting shared folders. If someone would like to provide such a box, then PhotonOS could also support deploying Kubernetes using local development builds. To read more about the valid versions that may be deployed, please see https://github.com/vmware/simple-k8s-test-env/wiki/Kubernetes-version. NUMBER OF NODES The -1, -2, and -3 flags are used to set the number of nodes in the cluster. The flags are mutually exclusive, and only the first of them that appears on the command line will be respected. EOF } export usage [ "${#}" -gt "0" ] || { usage && exit 1; } fatal() { echo "${@}" 1>&2 && exit 1; }; export fatal # Change directories to the directory that's a parent of this script. cd "$(dirname "$(dirname "${0}")")" || fatal "unable to change directories" while getopts ":k:b:c:m:p:vh123" opt; do case "${opt}" in k) flags=true k8s="${OPTARG}" ;; b) flags=true box="${OPTARG}" ;; c) flags=true cpu="${OPTARG}" ;; m) flags=true mem="${OPTARG}" ;; p) flags=true provider="${OPTARG}" ;; v) export VCSIM=1 ;; 1|2|3) flags=true [ ! -z "${nodes}" ] || nodes="${opt}" ;; h) usage exit 1 ;; :) fatal "Option -${OPTARG} requires an argument" ;; \?) # Ignore invalid flags ;; esac done shift $((OPTIND-1)) lcase() { tr '[:upper:]' '[:lower:]'; } igrep() { a="${1}"; shift; echo "${a}" | grep -i "${@}"; } is_int() { echo "${1}" | tr -d ',' | grep '^[[:digit:]]\{1,\}$'; } validate_box() { igrep "${1}" '^\(centos\|photon\|ubuntu\)$' | lcase || \ fatal "invalid box: ${1}" } validate_provider() { igrep "${1}" '^\(fusion\|\(vmware\(_\(desktop\|fusion\)\)\{0,1\}\)\|virtualbox\)$' | lcase || \ fatal "invalid provider: ${1}" } vagrant_home="${HOME}/.sk8/vagrant" instance="${vagrant_home}/instance" config="${instance}/config.yaml" if [ "${flags}" = "true" ] || [ ! -e "${config}" ]; then k8s="${k8s:-release/stable}" if [ "${k8s}" = "local" ]; then if [ -n "${GOPATH}" ]; then k8s="${GOPATH}/src/k8s.io/kubernetes" else k8s="${HOME}/go/src/k8s.io/kubernetes" fi if [ -d "${k8s}" ]; then k8s=local fi fi box="$(validate_box "${box:-ubuntu}")" case "${box}" in centos) #box='centos/7' box='bento/centos-7.5' ;; photon) box='vmware/photon' ;; ubuntu) #box='ubuntu/xenial64' # the stock ubuntu box does not support VMware box='bento/ubuntu-16.04' # this ubuntu box supports VMware ;; esac provider="$(validate_provider "${provider:-virtualbox}")" case "${provider}" in fusion|vmware|vmware_desktop|vmware_fusion) provider="vmware_fusion" ;; esac cpu="$(is_int "${cpu:-1}")" || fatal "invalid cpu value: ${cpu}" mem="$(is_int "${mem:-1024}")" || fatal "invalid mem value: ${mem}" case "${nodes}" in 1) num_nodes=1; num_controllers=1; num_both=1 ;; 2) num_nodes=2; num_controllers=1; num_both=0 ;; 3) num_nodes=3; num_controllers=2; num_both=1 ;; *) num_nodes="${NUM_NODES:-1}" num_controllers="${NUM_CONTROLLERS:-1}" num_both="${NUM_BOTH:-1}" esac config="$(mktemp)" cat <<EOF >"${config}" --- box: ${box} provider: ${provider} k8s: ${k8s} cpu: ${cpu} mem: ${mem} nodes: ${num_nodes} controllers: ${num_controllers} both: ${num_both} EOF fi # If the -i flag was specified then remove the existing instance. sha7() { { shasum -t -a1 2>/dev/null || sha1sum -t; } | awk '{print $1}' | cut -c-7 } # Configure a custom location for the Vagrant's data directory, .vagrant. VAGRANT_DOTFILE_PATH="${vagrant_home}/$(sha7 <"${config}")" export VAGRANT_DOTFILE_PATH && mkdir -p "${VAGRANT_DOTFILE_PATH}" # Make sure Vagrant sees the path to the config file. export CONFIG="${VAGRANT_DOTFILE_PATH}/config.yaml" # If the config file does not already exist, move the file into its # permanent location. mv -f "${config}" "${CONFIG}" 2>/dev/null || true # Create the symlink to the instance. rm -f "${instance}"; ln -s "${VAGRANT_DOTFILE_PATH}" "${instance}" # Determine the preferred provider. provider="$(grep '^provider:' "${CONFIG}" | awk '{print $2}')" export VAGRANT_DEFAULT_PROVIDER="${provider}" export KUBECONFIG="${VAGRANT_DOTFILE_PATH}/kubeconfig" export DNSCONFIG="${VAGRANT_DOTFILE_PATH}/dnsconfig" print_context() { echo "data: ${VAGRANT_DOTFILE_PATH}" cat "${CONFIG}" } export print_context
<filename>src/global-watchers.js<gh_stars>0 export default ({ $store }) => { $store.watch( rootState => rootState.auth.user, () => { $store.dispatch('updateSessionInLocalStorage') } ) }
package io.github.marcelbraghetto.dailydeviations.framework.foundation.dagger; import android.content.Context; import javax.inject.Singleton; import dagger.Component; import io.github.marcelbraghetto.dailydeviations.features.about.ui.AboutFragment; import io.github.marcelbraghetto.dailydeviations.features.application.MainApp; import io.github.marcelbraghetto.dailydeviations.features.collection.logic.providers.contracts.CollectionProvider; import io.github.marcelbraghetto.dailydeviations.features.collection.ui.CollectionFragment; import io.github.marcelbraghetto.dailydeviations.features.detail.ui.DetailActivity; import io.github.marcelbraghetto.dailydeviations.features.home.ui.HomeActivity; import io.github.marcelbraghetto.dailydeviations.features.home.ui.HomeNavHeaderView; import io.github.marcelbraghetto.dailydeviations.features.info.ui.InfoFragment; import io.github.marcelbraghetto.dailydeviations.features.settings.ui.SettingsFragment; import io.github.marcelbraghetto.dailydeviations.features.wallpaper.providers.contracts.WallpaperProvider; import io.github.marcelbraghetto.dailydeviations.framework.artworks.contracts.ArtworksProvider; import io.github.marcelbraghetto.dailydeviations.framework.artworks.service.ArtworksDataService; import io.github.marcelbraghetto.dailydeviations.framework.foundation.device.contracts.DeviceProvider; import io.github.marcelbraghetto.dailydeviations.framework.foundation.eventbus.contracts.EventBusProvider; import io.github.marcelbraghetto.dailydeviations.framework.foundation.strings.contracts.StringsProvider; /** * Created by <NAME> on 24/02/16. * * Application Dagger component for mapping and injection. */ @Singleton @Component(modules = { AppDaggerModule.class }) public interface AppComponent { void inject(MainApp mainApplication); void inject(ArtworksDataService service); void inject(HomeActivity activity); void inject(HomeNavHeaderView view); void inject(CollectionFragment fragment); void inject(DetailActivity activity); void inject(InfoFragment fragment); void inject(AboutFragment fragment); void inject(SettingsFragment fragment); Context getApplicationContext(); StringsProvider getAppStringsProvider(); DeviceProvider getDeviceProvider(); EventBusProvider getEventBusProvider(); CollectionProvider getCollectionProvider(); ArtworksProvider getArtworksProvider(); WallpaperProvider getWallpaperProvider(); }
(defn find-largest [a b c] (let [orig-list [a b c] sorted-list (sort orig-list >)] (first sorted-list))) (find-largest 5 10 7) => 10
<filename>src/schema/platform.menu.set.js<gh_stars>0 const {array, object, string, integer, empty, oneOf} = require('@qtk/schema').schema; const info = { title: "公众号-设置菜单", description: "" }; const subButton = array().desc('二级菜单').item( oneOf( { type: 'click', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'view', name: string().desc('标签名'), url: string().desc('url') }, { type: 'miniprogram', name: string().desc('标签名'), url: string().desc('url'), appid: string().desc('小程序id'), pagepath: string().desc('小程序的页面路径') }, { type: 'scancode_waitmsg', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'scancode_push', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_sysphoto', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_photo_or_album', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_weixin', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'location_select', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'media_id', name: string().desc('标签名'), media_id: string().desc('调用新增永久素材接口返回的合法media_id') }, { type: 'view_limited', name: string().desc('标签名'), media_id: string().desc('调用新增永久素材接口返回的合法media_id') }) ) const request = { button: array().item( oneOf( { type: 'click', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'view', name: string().desc('标签名'), url: string().desc('url') }, { type: 'miniprogram', name: string().desc('标签名'), url: string().desc('url'), appid: string().desc('小程序id'), pagepath: string().desc('小程序的页面路径') }, { type: 'scancode_waitmsg', name: string().desc('标签名'), key: string().desc('标签key'), sub_button: array().length(0) }, { type: 'scancode_push', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_sysphoto', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_photo_or_album', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'pic_weixin', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'location_select', name: string().desc('标签名'), key: string().desc('标签key') }, { type: 'media_id', name: string().desc('标签名'), media_id: string().desc('调用新增永久素材接口返回的合法media_id') }, { type: 'view_limited', name: string().desc('标签名'), media_id: string().desc('调用新增永久素材接口返回的合法media_id') }, { name: string().desc('菜单名'), sub_button: subButton } ) ) } const response = empty() module.exports = {info, request, response};
def prime_numbers(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n+1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False # Print all prime numbers for p in range(n+1): if prime[p]: print(p)
<reponame>nhood-org/nhood-engine package com.h8.nh.nhoodengine.matrix.impl; import com.h8.nh.nhoodengine.core.DataResourceKey; import com.h8.nh.nhoodengine.matrix.DataMatrixRepositoryAbstractThreadSafeTest; import com.h8.nh.nhoodengine.matrix.DataMatrixRepositoryTestContext; class DataMatrixCellBasedRepositoryThreadSafeTest extends DataMatrixRepositoryAbstractThreadSafeTest<DataResourceKey, Object> { @Override protected DataMatrixRepositoryTestContext<DataResourceKey, Object> initializeContext() { return new DataMatrixCellBasedRepositoryTestContext(); } }
#!/bin/bash set -x VERSION=$(bumpVersions -v) OUTPUT="./docs/swift" rm -rf "${OUTPUT}" mkdir -p "${OUTPUT}" cp -r images "${OUTPUT}" # SoundFontsFramework documentation sourcekitten doc \ --module-name SoundFontsFramework \ -- \ -workspace SoundFonts.xcworkspace \ -scheme App \ -destination name='iPhone 11' \ > /tmp/docs_SoundFontsFramework.json # App documentation sourcekitten doc \ -- \ -workspace SoundFonts.xcworkspace \ -scheme App \ -destination name='iPhone 11' \ > /tmp/docs_app.json # Generate HTML from documentation content jazzy --output "${OUTPUT}" \ --min-acl internal \ --sourcekitten-sourcefile /tmp/docs_SoundFontsFramework.json,/tmp/docs_app.json \ -g https://github.com/bradhowes/SoundFonts \ -a "Brad Howes" \ -u https://linkedin.com/in/bradhowes \ --module-version ${VERSION} # Generate SoundFontInfoLib (C++) documentation rm -rf docs/SoundFontInfoLib VERSION=${VERSION} doxygen SoundFontInfoLib/Doxygen.config
<filename>7-assets/past-student-repos/portfolio-main/components/ProjectCard.js<gh_stars>0 import React from 'react'; import { Flex, Link, Heading, Text, Stack, Icon, useColorMode } from '@chakra-ui/core'; const ProjectCard = ({ title, description, href, image }) => { const { colorMode } = useColorMode(); const borderColor = { light: 'gray.200', dark: 'gray.600' }; const iconColor = { light: 'gray.1000', dark: 'white' }; return ( <div className="project-card"> <Link mb={4} href={href} title={title} isExternal _hover={{ boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.05)', textDecoration: 'none' }} > <Flex align="center" border="1px solid" borderColor={borderColor[colorMode]} borderRadius={4} p={4} > <img src={image} alt={image} width="40px" padding="20px" ml={2} mr={4} /> <Stack> <Heading as="h4" size="md" fontWeight="bold" mb={4} letterSpacing="tighter" > {title} </Heading> <Text lineHeight="1.3">{description}</Text> </Stack> </Flex> </Link> </div> ); }; export default ProjectCard;
package heap; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 9339번: 마라토너 * * @see https://www.acmicpc.net/problem/9339/ * */ public class Boj9339 { private static final int LIMIT = 360; private static final int RETIRE = 2_000; private static final String SPACE = " "; private static final String NEW_LINE = "\n"; private static class Marathon implements Comparable<Marathon>{ int num; int time; boolean isStd; public Marathon(int num, int time, boolean isStd) { this.num = num; this.time = time; this.isStd = isStd; } @Override public int compareTo(Marathon m) { return this.time < m.time ? -1: 1; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int T = Integer.parseInt(br.readLine()); while(T-- > 0) { int K = Integer.parseInt(br.readLine()); HashSet<Integer> lec = new HashSet<>(); StringTokenizer st = new StringTokenizer(br.readLine()); while(K-- > 0) { lec.add(Integer.parseInt(st.nextToken())); // 수강생 } PriorityQueue<Marathon> athlete = new PriorityQueue<>(); int N = Integer.parseInt(br.readLine()); while(N-- > 0) { st = new StringTokenizer(br.readLine()); int no = Integer.parseInt(st.nextToken()); int hour = Integer.parseInt(st.nextToken()); int min = Integer.parseInt(st.nextToken()); int timer = 0; if(hour == -1 || min == -1) timer = RETIRE; // 중도 포기자 else timer = hour * 60 + min; // 완주자 기록 if(lec.contains(no)) athlete.offer(new Marathon(no, timer, true)); else athlete.offer(new Marathon(no, timer, false)); } sb.append(getList(athlete)).append(NEW_LINE); } System.out.print(sb.toString()); } private static String getList(PriorityQueue<Marathon> pq) { StringBuilder sb = new StringBuilder(); int idx = -1, count = 0; while(!pq.isEmpty()) { Marathon current = pq.poll(); if(current.time > LIMIT) break; // 시간초과 if(current.isStd) { if(idx == -1) idx = current.num; // 1등 count++; // 인증 } } return sb.append(idx).append(SPACE).append(count).toString(); } }
#!/bin/bash # # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # ###################################### # ClaraGenomicsAnalysis CPU build script for CI # ###################################### set -e START_TIME=$(date +%s) export PATH=/conda/bin:/usr/local/cuda/bin:$PATH PARALLEL_LEVEL=4 # Set home to the job's workspace export HOME=$WORKSPACE cd "${WORKSPACE}" ################################################################################ # Init ################################################################################ source ci/common/logger.sh logger "Calling prep-init-env..." source ci/common/prep-init-env.sh "${WORKSPACE}" "${CONDA_ENV_NAME}" ################################################################################ # SDK build/test ################################################################################ logger "Build SDK..." CMAKE_COMMON_VARIABLES=(-DCMAKE_BUILD_TYPE=Release) source ci/common/build-test-sdk.sh "${WORKSPACE}" "${CMAKE_COMMON_VARIABLES[@]}" "${PARALLEL_LEVEL}" 0 rm -rf "${WORKSPACE}"/build ################################################################################ # Pyclaragenomics tests ################################################################################ logger "Build Pyclaragenomics..." cd "${WORKSPACE}" source ci/common/test-pyclaragenomics.sh "${WORKSPACE}"/pyclaragenomics logger "Done..."
#!/bin/bash #===--- find-overlay-dependencies-loop.sh - driver for find-overlay-dependency.sh---===# # ## This source file is part of the Swift.org open source project ## ## Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors ## Licensed under Apache License v2.0 with Runtime Library Exception ## ## See https://swift.org/LICENSE.txt for license information ## See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # #===------------------------------------------------------------------------===# SCRIPT="$(dirname "$0")/find-overlay-dependencies.sh" # `update` edits the cmake file in-place; `print` just prints to console function usage() { echo 'usage:' $0 'update|print' >&2 exit 1 } case $# in 1) if [[ $1 != 'update' && $1 != 'print' ]]; then usage fi ;; *) usage ;; esac # Don't update XCTest, handle spaces in directories for f in ./stdlib/public/SDK/*/; do name=$(basename "${f}") if [[ "${name}" == "XCTest" ]]; then continue fi $SCRIPT "${name}" "$1" done
package io.hawt.springboot; import com.fasterxml.jackson.annotation.JsonProperty; public class HawtPlugin { private String name; private String context; private String domain; private String scripts[]; public HawtPlugin(String name, String context, String domain, String[] scripts) { super(); this.name = name; this.context = context; this.domain = domain; this.scripts = scripts; } @JsonProperty("Name") public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonProperty("Context") public String getContext() { return context; } public void setContext(String context) { this.context = context; } @JsonProperty("Domain") public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } @JsonProperty("Scripts") public String[] getScripts() { return scripts; } public void setScripts(String[] scripts) { this.scripts = scripts; } }
#!/usr/bin/env bash # # Edit files, performing code style corrections using clang-format # # Usage: # $ ci/clang-format.sh # echo -e "\033[0;34mRunning clang-format...\033[0m" cd "$(dirname "$0")" || exit clang-format -style=file -i "$(find ../src/ ../inc/ ../test/ -type f -regextype posix-egrep -regex '.*\.(cpp|hpp|tpp|c|h)')" \ -verbose "$@"
require "spec_helper" describe "bower_rails" do let(:jekyll_root) { Pathname.new("../bower_rails_fixtures").expand_path(__FILE__) } it "autoload bower_rails assets to sprockets" do jekyll_build expect(Pathname.glob(jekyll_destination.join("assets/app-*.js"))).to_not be_empty end end
#!/usr/bin/env bash set -e # halt script on error echo "Get ready, we're pushing to gh-pages!" cd dist git init git config user.name "Travis-CI" git config user.email "travis@somewhere.com" git add . git commit -m "CI deploy to gh-pages" git push --force --quiet "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" master:gh-pages
#!/bin/sh -e node2nix -i pkg.json -c nixui.nix -e ../../../development/node-packages/node-env.nix
<reponame>duncangrant/incubator-brooklyn<filename>core/src/main/java/brooklyn/management/internal/EntityChangeListener.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.management.internal; import brooklyn.config.ConfigKey; import brooklyn.entity.Effector; import brooklyn.entity.Feed; import brooklyn.event.AttributeSensor; import brooklyn.policy.Enricher; import brooklyn.policy.Policy; public interface EntityChangeListener { // TODO for testing only! public static final EntityChangeListener NOOP = new EntityChangeListener() { @Override public void onChanged() {} @Override public void onAttributeChanged(AttributeSensor<?> attribute) {} @Override public void onConfigChanged(ConfigKey<?> key) {} @Override public void onLocationsChanged() {} @Override public void onMembersChanged() {} @Override public void onTagsChanged() {} @Override public void onChildrenChanged() {} @Override public void onPolicyAdded(Policy policy) {} @Override public void onPolicyRemoved(Policy policy) {} @Override public void onEnricherAdded(Enricher enricher) {} @Override public void onEnricherRemoved(Enricher enricher) {} @Override public void onFeedAdded(Feed feed) {} @Override public void onFeedRemoved(Feed feed) {} @Override public void onEffectorStarting(Effector<?> effector) {} @Override public void onEffectorCompleted(Effector<?> effector) {} }; void onChanged(); void onAttributeChanged(AttributeSensor<?> attribute); void onConfigChanged(ConfigKey<?> key); void onLocationsChanged(); void onTagsChanged(); void onMembersChanged(); void onChildrenChanged(); void onPolicyAdded(Policy policy); void onPolicyRemoved(Policy policy); void onEnricherAdded(Enricher enricher); void onEnricherRemoved(Enricher enricher); void onFeedAdded(Feed feed); void onFeedRemoved(Feed feed); void onEffectorStarting(Effector<?> effector); void onEffectorCompleted(Effector<?> effector); }
export const AWS_REGION = "<your region>"; export const AWS_IOT_ENDPOINT = "<your endpoint>"; export const AWS_COGNITO_IDENTITY_POOL_ID = "Optional: <your identity pool id>"; export const AWS_STATIC_ACCESS_KEY = "<your static access key>"; export const AWS_STATIC_SECRET_ACCESS_KEY = "<your static secret access key>"; export const AWS_STATIC_ACCESS_TOKEN = "Optional: <your static access token>";
#!/bin/sh # # ################################### #环境变量及程序执行参数 #需要根据实际环境以及Java程序名称来修改这些参数 ################################### #JDK所在路径 JAVA_HOME="/usr/local/jdk1.7.0_80" #执行程序启动所使用的系统用户,考虑到安全,不推荐使用root帐号 #RUNNING_USER="yqshi" #Java程序所在的目录(classes的上一级目录) APP_HOME="./target" #需要启动的Java主程序(main方法类) APP_MAINCLASS="com.unionpay.serializer.thrift.ThriftTest" #需要传入main方法的String[] args APP_ARGS="10000" #日志文件路径及名称 APP_LOG_FILE="thrift_benchmark_$APP_ARGS.log" #拼凑完整的classpath参数,包括指定lib目录下所有的jar CLASSPATH="$APP_HOME/classes" for i in "$APP_HOME"/lib/*.jar; do CLASSPATH="$CLASSPATH":"$i" done #java虚拟机启动参数 JAVA_OPTS="-ms512m -mx512m -Xmn256m -Djava.awt.headless=true -XX:MaxPermSize=128m" ################################### #(函数)判断程序是否已启动 # #说明: #使用JDK自带的JPS命令及grep命令组合,准确查找pid #jps 加 l 参数,表示显示java的完整包路径 #使用awk,分割出pid ($1部分),及Java程序名称($2部分) ################################### #初始化psid变量(全局) psid=0 checkpid() { javaps=`$JAVA_HOME/bin/jps -l | grep $APP_MAINCLASS` if [ -n "$javaps" ]; then psid=`echo $javaps | awk '{print $1}'` else psid=0 fi } ################################### #(函数)启动程序 # #说明: #1. 首先调用checkpid函数,刷新$psid全局变量 #2. 如果程序已经启动($psid不等于0),则提示程序已启动 #3. 如果程序没有被启动,则执行启动命令行 #4. 启动命令执行后,再次调用checkpid函数 #5. 如果步骤4的结果能够确认程序的pid,则打印[OK],否则打印[Failed] #注意:echo -n 表示打印字符后,不换行 #注意: "nohup 某命令 >/dev/null 2>&1 &" 的用法 ################################### start() { checkpid if [ $psid -ne 0 ]; then echo "================================" echo "warn: $APP_MAINCLASS already started! (pid=$psid)" echo "================================" else echo -n "Starting $APP_MAINCLASS ..." JAVA_CMD="nohup $JAVA_HOME/bin/java $JAVA_OPTS -classpath $CLASSPATH $APP_MAINCLASS $APP_ARGS > $APP_LOG_FILE &" JAVA_CMD checkpid if [ $psid -ne 0 ]; then echo "(pid=$psid) [OK]" else echo "[Failed]" fi fi } ################################### #(函数)停止程序 # #说明: #1. 首先调用checkpid函数,刷新$psid全局变量 #2. 如果程序已经启动($psid不等于0),则开始执行停止,否则,提示程序未运行 #3. 使用kill -9 pid命令进行强制杀死进程 #4. 执行kill命令行紧接其后,马上查看上一句命令的返回值: $? #5. 如果步骤4的结果$?等于0,则打印[OK],否则打印[Failed] #6. 为了防止java程序被启动多次,这里增加反复检查进程,反复杀死的处理(递归调用stop)。 #注意:echo -n 表示打印字符后,不换行 #注意: 在shell编程中,"$?" 表示上一句命令或者一个函数的返回值 ################################### stop() { checkpid if [ $psid -ne 0 ]; then echo -n "Stopping $APP_MAINCLASS ...(pid=$psid) " su - $RUNNING_USER -c "kill -9 $psid" if [ $? -eq 0 ]; then echo "[OK]" else echo "[Failed]" fi checkpid if [ $psid -ne 0 ]; then stop fi else echo "================================" echo "warn: $APP_MAINCLASS is not running" echo "================================" fi } ################################### #(函数)检查程序运行状态 # #说明: #1. 首先调用checkpid函数,刷新$psid全局变量 #2. 如果程序已经启动($psid不等于0),则提示正在运行并表示出pid #3. 否则,提示程序未运行 ################################### status() { checkpid if [ $psid -ne 0 ]; then echo "$APP_MAINCLASS is running! (pid=$psid)" else echo "$APP_MAINCLASS is not running" fi } ################################### #(函数)打印系统环境参数 ################################### info() { echo "System Information:" echo "****************************" echo `head -n 1 /etc/issue` echo `uname -a` echo echo "JAVA_HOME=$JAVA_HOME" echo `$JAVA_HOME/bin/java -version` echo echo "APP_HOME=$APP_HOME" echo "APP_MAINCLASS=$APP_MAINCLASS" echo "****************************" } ################################### #读取脚本的第一个参数($1),进行判断 #参数取值范围:{start|stop|restart|status|info} #如参数不在指定范围之内,则打印帮助信息 ################################### case "$1" in 'start') start ;; 'stop') stop ;; 'restart') stop start ;; 'status') status ;; 'info') info ;; *) echo "Usage: $0 {start|stop|restart|status|info}" exit 1 esac exit 0
#!/bin/bash perf_client -i gRPC -u localhost:8001 -m retinaface --percentile=95 --concurrency-range 1:8 -v -a -b 8
name = "John Doe" if len(name) > 8: print("Name is too long")
package io.opensphere.core.common.util.zip; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.CRC32; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; /** * The class <b>Zip</b> is a wrapper to classes and methods int the * java.util.zip package. The static methods contained in this class are * intended to make using the java zip classes and methods more convenient. */ public class Zip { /** * This method is used to uncompress a GZIP compressed file. The output file * name will be the same as the input file name, without the .??? extension. * * @param zipFile the file to be unzipped * @param destDir the directory where you would like to place the unzipped * file. * @return output file from the gunzip action * @throws FileNotFoundException * @throws IOException */ public static File gunzip(File zipFile, File destDir) throws FileNotFoundException, IOException { final int BUFFER_SIZE = 2048; int count; FileInputStream fis = new FileInputStream(zipFile); BufferedInputStream bis = new BufferedInputStream(fis); GZIPInputStream zis = new GZIPInputStream(bis); FileOutputStream fos; BufferedOutputStream bos; String outputFileName = zipFile.getName(); outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf(".")); File outputDir = destDir; File outputFile = new File(outputDir, outputFileName); byte[] data; data = new byte[BUFFER_SIZE]; fos = new FileOutputStream(outputFile); bos = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); zis.close(); bis.close(); fis.close(); return outputFile; } /** * <code>untgz</code> is used to retrieve directories and files from a * TarBall, or a TARred and GZIPped group of files. * * @param tgzFile the input GZIPped TAR file, generally with a .tgz * extension. The .tgz extension is not a requirement. * @param destDir the location where you would like the contents of the TAR * file placed. * @return {@link ArrayList}<{@link File}> of files contained in the TAR * file * @throws FileNotFoundException * @throws IOException */ // TODO this method is not available because we do not have the Tar Package // approved yet .... // public static ArrayList<File> untgz(File tgzFile, File destDir) throws // FileNotFoundException, IOException // { // File tempDir = new File(System.getProperty("java.io.tmpdir")); // File tarFile = gunzip(tgzFile, tempDir); // ArrayList<File> files = Tar.untar(tarFile, destDir); // tarFile.delete(); // return files; // } // ************** ZIP METHODS *******************// /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. * * @param zipPathAndFile the output zip files path and name * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param fStrs array of relative file strings. These strings contain the * paths and file names relative to the <code>relDir</code>. * @throws FileNotFoundException * @throws IOException */ public static void zip(String zipPathAndFile, File relDir, String[] fStrs) throws FileNotFoundException, IOException { File zipFile = new File(zipPathAndFile); zipfiles(zipFile, relDir, fStrs); } /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. * * @param zipdir the directory where the output zip file will be placed * @param zipFileName the name of the output zip file * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param fStrs array of relative file strings. These strings contain the * paths and file names relative to the <code>relDir</code>. * @throws FileNotFoundException * @throws IOException */ public static void zip(File zipdir, String zipFileName, File relDir, String[] fStrs) throws FileNotFoundException, IOException { File zipFile = new File(zipdir, zipFileName); zipfiles(zipFile, relDir, fStrs); } /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. * * @param zfile the output zip file * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param fStrs array of relative file strings. These strings contain the * paths and file names relative to the <code>relDir</code>. * @throws FileNotFoundException * @throws IOException */ public static void zip(File zfile, File relDir, String[] fStrs) throws FileNotFoundException, IOException { zipfiles(zfile, relDir, fStrs); } /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. This version of the zip method is intended to start with * a directory and zip its entire contents into the specified file. It will, * however, work just fine if the <code>inputDir</code> is a file, not a * directory. * * @param zipPathAndFile the output zip files path and name * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param inputDir the input directory whose contents you want to zip. * @throws FileNotFoundException * @throws IOException */ public static void zip(String zipPathAndFile, File relDir, File inputDir) throws FileNotFoundException, IOException { String[] fStrs = null; if (inputDir.isDirectory()) { fStrs = DirectoryListRecursion.getAbsoluteFiles(inputDir); } else { fStrs = new String[1]; fStrs[0] = inputDir.getAbsolutePath(); } File zipFile = new File(zipPathAndFile); zipfiles(zipFile, relDir, fStrs); } /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. This version of the zip method is intended to start with * a directory and zip its entire contents into the specified file. It will, * however, work just fine if the <code>inputDir</code> is a file, not a * directory. * * @param zipdir the directory where the output zip file will be placed * @param zipFileName the name of the output zip file * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param inputDir the input directory whose contents you want to zip. * @throws FileNotFoundException * @throws IOException */ public static void zip(File zipdir, String zipFileName, File relDir, File inputDir) throws FileNotFoundException, IOException { String[] fStrs = null; if (inputDir.isDirectory()) { fStrs = DirectoryListRecursion.getAbsoluteFiles(inputDir); } else { fStrs = new String[1]; fStrs[0] = inputDir.getPath(); } File zipFile = new File(zipdir, zipFileName); zipfiles(zipFile, relDir, fStrs); } /** * The <code>zip</code> method is used to zip one or more files into a * single zip file. This version of the zip method is intended to start with * a directory and zip its entire contents into the specified file. It will, * however, work just fine if the <code>inputDir</code> is a file, not a * directory. * * @param zfile the output zip file * @param relDir the directory to which all files are relative. (ex: * data/mydata.csv is the relative path of an absolute path like * c:/myfiles/data/mydata.csv. The parameter <code>relDir</code> * would be &quote;c:/myfiles%quote; in this case. * @param inputDir the input directory whose contents you want to zip. * @throws FileNotFoundException * @throws IOException */ public static void zip(File zfile, File relDir, File inputDir) throws FileNotFoundException, IOException { String[] fStrs = null; if (inputDir.isDirectory()) { fStrs = DirectoryListRecursion.getRelativeFiles(inputDir); } else { fStrs = new String[1]; fStrs[0] = inputDir.getAbsolutePath(); } zipfiles(zfile, relDir, fStrs); } /** * This is the method that actually does the work of zipping the files. * * @param zipFile * @param relDir * @param fileStrs * @throws FileNotFoundException * @throws IOException */ private static void zipfiles(File zipFile, File relDir, String[] fileStrs) throws FileNotFoundException, IOException { ZipOutputStream zipOS = new ZipOutputStream(new FileOutputStream(zipFile)); zipOS.setLevel(9); byte[] buf = null; String inputFileName = null; for (int i = 0; i < fileStrs.length; i++) { inputFileName = "" + relDir.toString() + File.separatorChar + fileStrs[i]; buf = null; buf = new byte[1024]; ZipEntry entry = new ZipEntry(fileStrs[i]); FileInputStream FIS = new FileInputStream(inputFileName); zipOS.putNextEntry(entry); int len; while ((len = FIS.read(buf)) > 0) { zipOS.write(buf, 0, len); } zipOS.closeEntry(); FIS.close(); } zipOS.close(); } /** * Creates a Zip file given a list of inputs for the zip file. The inputs * can be anything that provide a name, location, input stream, and method * * @param zipFile - the output zip file * @param zipInputs - the list of {@link ZipInputAdapter} inputs * @param pm the progress monitor to hook into * @param progressByFiles TODO * @throws FileNotFoundException * @throws IOException */ public static void zipfiles(File zipFile, List<ZipInputAdapter> zipInputs, final ProgressMonitor pm, final boolean progressByFiles) throws FileNotFoundException, IOException { ZipOutputStream zipOS = new ZipOutputStream(new FileOutputStream(zipFile)); zipOS.setLevel(9); byte[] buf = new byte[1024 * 1024 * 10]; long totalWritten = 0; CRC32 crc = new CRC32(); boolean canceled = false; int totalEntries = zipInputs.size(); int entryCount = 0; for (ZipInputAdapter entry : zipInputs) { entryCount++; String inputFileName = ""; if (entry.getLocation() != null) { inputFileName += entry.getLocation() + File.separatorChar; } inputFileName += entry.getName(); if (pm != null) { final String note = inputFileName; final int count = entryCount; final int totEntries = totalEntries; SwingUtilities.invokeLater(() -> pm.setNote("Adding Entry " + count + " of " + totEntries + " : " + note)); } ZipEntry zEntry = new ZipEntry(inputFileName); zEntry.setMethod(entry.getMethod()); if (entry.getMethod() == ZipEntry.STORED) { crc.reset(); InputStream eIS = entry.getInputStream(); int len; while ((len = eIS.read(buf)) > 0) { crc.update(buf, 0, len); } entry.closeInputStream(); zEntry.setSize(entry.getSize()); zEntry.setCompressedSize(entry.getSize()); zEntry.setCrc(crc.getValue()); } if (pm != null && pm.isCanceled()) { canceled = true; break; } InputStream FIS = entry.getInputStream(); zipOS.putNextEntry(zEntry); int len; while ((len = FIS.read(buf)) > 0) { zipOS.write(buf, 0, len); totalWritten += len; if (pm != null) { final int progress = (int)totalWritten; final int fCount = entryCount; SwingUtilities.invokeLater(() -> { if (progressByFiles) { pm.setProgress(fCount); } else { pm.setProgress(progress); } }); } } zipOS.closeEntry(); entry.closeInputStream(); if (pm != null && pm.isCanceled()) { canceled = true; break; } } zipOS.close(); if (canceled) { zipFile.delete(); } } /** * The <code>unzip</code> method is used to unzip files and directories from * the input zip file. * * @param zipFile the input zip file. * @param destDir the location where files and directories are to be * unzipped * @return {@link ArrayList}<{@link File}> of files and directories found in * the zip file * @throws FileNotFoundException * @throws IOException */ public static ArrayList<File> unzip(File zipFile, File destDir) throws FileNotFoundException, IOException { final int BUFFER_SIZE = 2048; int count; ArrayList<File> files = new ArrayList<>(); ZipEntry entry; FileInputStream fis = new FileInputStream(zipFile); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis); FileOutputStream fos; BufferedOutputStream bos; File outputFile; File outputDir; byte[] data; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { outputDir = new File(entry.getName()); outputDir.mkdirs(); } else { outputFile = new File(destDir, entry.getName()); outputDir = outputFile.getParentFile(); if (!outputDir.exists()) { outputDir.mkdirs(); } files.add(outputFile); data = new byte[BUFFER_SIZE]; fos = new FileOutputStream(outputFile); bos = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); } } zis.close(); return files; } /** * Creates a recursive listing of adapters from a directory * * @param location * @param directory * @param appendList * @return list of input adapters */ public static List<ZipInputAdapter> createAdaptersForDirectory(String location, File directory, List<ZipInputAdapter> appendList) { if (appendList == null) { appendList = new ArrayList<>(); } if (directory.isDirectory()) { File[] children = directory.listFiles(); if (children != null && children.length > 0) { String newLocation = location + File.separator + directory.getName(); for (File child : children) { if (child.isDirectory()) { createAdaptersForDirectory(newLocation, child, appendList); } else { appendList.add(new ZipFileInputAdapter(newLocation, child, ZipEntry.DEFLATED)); } } } } return appendList; } /** A ZipInputAdapter. */ public static abstract class ZipInputAdapter { /** Zip method. Defaults to DEFLATED. */ int myMethod = ZipEntry.DEFLATED; /** * Constructor. * * @param method {@link ZipEntry} method */ public ZipInputAdapter(int method) { myMethod = method; } /** * Gets the method. * * @return the method */ public int getMethod() { return myMethod; } /** * Gets the location. * * @return the location */ public abstract String getLocation(); /** * Gets the name. * * @return the name */ public abstract String getName(); /** * Gets the size. * * @return the size */ public long getSize() { return 0; } /** * Gets the input stream. * * @return the stream * @throws IOException */ public abstract InputStream getInputStream() throws IOException; /** * Closes the input stream. * * @throws IOException */ public void closeInputStream() throws IOException { }; } /** Instance of ZipInputAdapter that reads a file. */ public static class ZipFileInputAdapter extends ZipInputAdapter { /** The file. */ File myFile; /** The location of the file. */ String myLocation; /** The FileInputStream. */ FileInputStream myFIS; /** * Constructor. * * @param location the location * @param aFile the file object * @param method the Zip method */ public ZipFileInputAdapter(String location, File aFile, int method) { super(method); myFile = aFile; myLocation = location; } @Override public InputStream getInputStream() throws IOException { if (myFIS == null) { myFIS = new FileInputStream(myFile); } return myFIS; } @Override public String getLocation() { return myLocation; } @Override public long getSize() { return myFile.length(); } @Override public String getName() { return myFile.getName(); } @Override public void closeInputStream() throws IOException { if (myFIS != null) { myFIS.close(); myFIS = null; } } } /** Instance of ZipInputAdapter that reads a byte array. */ public static class ZipByteArrayInputAdapter extends ZipInputAdapter { /** The location. */ String myLocation; /** The name. */ String myName; /** The ByteArrayInputStream. */ ByteArrayInputStream myBAIS; /** The byte array. */ byte[] myByteArray; /** * Constructor. * * @param name the name * @param location the location * @param byteArray the byte array * @param method the zip method */ public ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method) { super(method); myName = name; myLocation = location; myByteArray = byteArray; } @Override public InputStream getInputStream() throws IOException { if (myBAIS == null) { myBAIS = new ByteArrayInputStream(myByteArray); } return myBAIS; } @Override public String getLocation() { return myLocation; } @Override public String getName() { return myName; } @Override public void closeInputStream() throws IOException { if (myBAIS != null) { myBAIS.close(); myBAIS = null; } } } /** * Zips files in a directory into a buffered byte array. * * @param dir the directory to read * @param fileStrs the filenames to zip * @return an output stream for the byte array * @throws FileNotFoundException * @throws IOException */ public static ByteArrayOutputStream zipToBufferedOutput(File dir, String[] fileStrs) throws FileNotFoundException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipOS = new ZipOutputStream(baos); zipOS.setLevel(9); byte[] buf = null; String inputFileName = null; for (int i = 0; i < fileStrs.length; i++) { inputFileName = "" + dir.toString() + File.separatorChar + fileStrs[i]; buf = null; buf = new byte[1024]; ZipEntry entry = new ZipEntry(fileStrs[i]); FileInputStream FIS = new FileInputStream(inputFileName); zipOS.putNextEntry(entry); int len; while ((len = FIS.read(buf)) > 0) { zipOS.write(buf, 0, len); } zipOS.closeEntry(); FIS.close(); } zipOS.close(); baos.close(); return baos; } }
package day15; import java.util.LinkedList; import java.util.Queue; public class EenyMeeny { public static String EenyMeenyMineyMoe (Queue<String> EMMMList, int n){ int moeCount = n; while (EMMMList.size() > 1) { for (int count = 0; count < moeCount; count++) { String person = EMMMList.remove(); EMMMList.add(person); } String removed = EMMMList.remove(); } return EMMMList.remove(); } }
<filename>config/routes.rb # frozen_string_literal: true Rails.application.routes.draw do root "external#landing" scope module: :admin do get "admin" => "admin#admin" namespace :admin do get :consented get :consented_clinic, path: "consented/:clinic" end end namespace :admin do resources :users do member do post :assign_subject, path: "assign-subject" post :unrevoke end end end scope module: :external do get :about get :pledge get :print_consent, path: "consent.pdf" get :consent get :consent_revisions, path: "consent/revisions" get :enrollment_start, path: "enrollment/start", to: redirect("consent") post :enrollment_start, path: "enrollment/start" get :enrollment_exit, path: "enrollment/exit" get :enrollment_consent, path: "enrollment/consent", to: redirect("consent") post :enrollment_consent, path: "enrollment/consent" get :contact get :clinic, path: "clinic(/:clinic)" get :landing get :privacy_policy, path: "privacy-policy" get :settings_password_reset, path: "settings/password/reset" get :sitemap_xml, path: "sitemap.xml.gz" get :version end scope module: :internal do post :consent, action: :submit_consent delete :consent, action: :revoke_consent get :awards get :dashboard get :test_my_brain, path: "test-my-brain" get :parking, path: "parking-voucher" get :whats_next, path: "whats-next" post :test_my_brain_start, path: "test-my-brain/start" post :biobank_start, path: "biobank/start" post :biobank_complete, path: "biobank/complete" get :surveys get :leave_study, path: "leave-study" post :submit_leave_study, path: "leave-study" get :returning_from, path: "returning-from/:external/:subject_code" end scope module: :profile do get :profile, to: redirect("settings") end namespace :profile do get :address patch :change_address, path: "address" get :dob patch :change_dob, path: "dob" get :complete patch :complete_submit, path: "complete" get :signature patch :signature_submit, path: "signature" end scope module: :settings do get :settings end namespace :settings do # root to: "settings#index" get :consents get :password patch :change_password, path: "password" get :email patch :change_email, path: "email" end namespace :slice, path: "" do # OR: scope module: :slice get :print_overview_report, path: "research/sleep-innovate/overview-report.pdf" end namespace :survey do get :start, path: ":event/:design/start" get :resume, path: ":event/:design/resume" get :review, path: ":event/:design/review" post :complete, path: ":event/:design/review" get :page, path: ":event/:design/:page" patch :submit_page, path: ":event/:design/:page" end devise_for :users, controllers: { confirmations: "confirmations", passwords: "<PASSWORD>", registrations: "registrations", sessions: "sessions", unlocks: "unlocks" }, path_names: { sign_up: "join", sign_in: "login" }, path: "" end
wget http://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.out.gz gzip -d hg19.fa.out.gz awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$10,".",strand}}' hg19.fa.out > hg19.rpmasker.bed bedtools sort -i hg19.rpmasker.bed > hg19.rpmasker.sorted.bed wget http://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.out.gz gzip -d hg38.fa.out.gz awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$10,".",strand}}' hg38.fa.out > hg38.rpmasker.bed bedtools sort -i hg38.rpmasker.bed > hg38.rpmasker.sorted.bed